repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
grhsxy21/Insect_Identification
[ "3b9ffe3ba91c2271bd663c327e384a6679c67bc8" ]
[ "P_rect.py" ]
[ "# coding=utf-8\n# 先读图,然后二值化,\n# 矩形度\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# 此处读入图片,作为接口\norigin = cv2.imread('D:/GitHub/ZRB/Insect_Identification/picture/butterfly.png') #TODO改为绝对路径\ngrayimage = cv2.imread('D:/GitHub/ZRB/Insect_Identification/picture/butterfly.png', 0)\n\n#  高斯滤波\n#*img = cv2.GaussianBlur(src, (blur1, blur2), 0),其中src是要进行滤波的原图像,blur1,blur2)是高斯核的大小,blur1和blur2的选取一般是奇数,blur1和blur2的值可以不同。参数0表示标准差取0。\nblur = cv2.GaussianBlur(grayimage, (5, 5), 0)\n\n#  二值化:用大津法,此处选项若是THRESH_BINARY_INV,则同意选用白色背景的图片样本\nret, otsu = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n\n# 找轮廓\ncontours = cv2.findContours(otsu, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n# 轮廓集数目\n\nlargest_area = 0\nlargest_contour_index = 0\nnum = len(contours[0]) #!cv2.findContour()返回两个值:contours,hierachy,要的是contours,所以后面应该是0而不是1。\nfor i in range(num):\n area = cv2.contourArea(contours[0][i], False)\n if area > largest_area:\n largest_area = area\n largest_contour_index = i\n\nmaxContour = contours[0][largest_contour_index]\n# 画轮廓\ncv2.drawContours(origin, maxContour, -1, (0, 0, 255), 4)\nprint (\"最大面积\" + str(largest_area))\n\n# 查找最小外接矩形\nminAreaRect = cv2.minAreaRect(maxContour)\nbox = cv2.boxPoints(minAreaRect)\nbox = np.int0(box)\n# 画轮廓\ncv2.drawContours(origin, [box], 0, (0, 255, 0), 4)\n\n# 计算最小外接矩形面积\nminAreaRect_Area = int(cv2.contourArea(box, False))\nprint (\"最小外接矩形面积\" + str(minAreaRect_Area))\n\n# 特征一:矩形度的计算\nP_Rect = largest_area * 1.0 / minAreaRect_Area\n# 统一结果为3位小数\nP_Rect = round(P_Rect, 3)\nprint (\"矩形度\" + str(P_Rect))\n\ncv2.putText(origin, 'S_maxContour : ' + str(largest_area), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (50, 50, 50), 2, cv2.LINE_AA)\ncv2.putText(origin, 'S_minAreaRect: ' + str(minAreaRect_Area), (50, 85), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (50, 50, 50), 2, cv2.LINE_AA)\ncv2.putText(origin, 'P_Rect: ' + str(P_Rect), (50, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (50, 50, 50), 2, cv2.LINE_AA)\n\n\n# 显示\ncv2.namedWindow('Butterfly', cv2.WINDOW_AUTOSIZE)\ncv2.imshow('Butterfly', origin)\ncv2.imwrite('picture/p-rect.png',origin)\n\nk = cv2.waitKey(0)\n\n# 'ESC'\nif k == 27:\n cv2.destroyAllWindows()\n" ]
[ [ "numpy.int0" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
steffen-schroeder-by/kartothek
[ "1821ea5df60d4079d3911b3c2f17be11d8780e22" ]
[ "kartothek/io/eager.py" ]
[ "import warnings\nfrom functools import partial\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union, cast\n\nimport deprecation\nimport pandas as pd\nfrom simplekv import KeyValueStore\n\nfrom kartothek.core.common_metadata import (\n empty_dataframe_from_schema,\n make_meta,\n store_schema_metadata,\n)\nfrom kartothek.core.dataset import DatasetMetadata, DatasetMetadataBuilder\nfrom kartothek.core.docs import default_docs\nfrom kartothek.core.factory import DatasetFactory, _ensure_factory\nfrom kartothek.core.naming import (\n DEFAULT_METADATA_STORAGE_FORMAT,\n DEFAULT_METADATA_VERSION,\n METADATA_BASE_SUFFIX,\n METADATA_FORMAT_JSON,\n PARQUET_FILE_SUFFIX,\n get_partition_file_prefix,\n)\nfrom kartothek.core.typing import StoreInput\nfrom kartothek.core.utils import lazy_store\nfrom kartothek.io.iter import store_dataframes_as_dataset__iter\nfrom kartothek.io_components.delete import (\n delete_common_metadata,\n delete_indices,\n delete_top_level_metadata,\n)\nfrom kartothek.io_components.gc import delete_files, dispatch_files_to_gc\nfrom kartothek.io_components.index import update_indices_from_partitions\nfrom kartothek.io_components.metapartition import (\n SINGLE_TABLE,\n MetaPartition,\n parse_input_to_metapartition,\n)\nfrom kartothek.io_components.read import dispatch_metapartitions_from_factory\nfrom kartothek.io_components.update import update_dataset_from_partitions\nfrom kartothek.io_components.utils import (\n _ensure_compatible_indices,\n align_categories,\n normalize_args,\n sort_values_categorical,\n validate_partition_keys,\n)\nfrom kartothek.io_components.write import raise_if_dataset_exists\nfrom kartothek.serialization import DataFrameSerializer\nfrom kartothek.serialization._parquet import ParquetSerializer\nfrom kartothek.utils.ktk_adapters import get_dataset_keys\nfrom kartothek.utils.migration_helpers import (\n DEPRECATION_WARNING_REMOVE_PARAMETER,\n deprecate_parameters,\n deprecate_parameters_if_set,\n get_deprecation_warning_remove_dict_multi_table,\n get_deprecation_warning_remove_parameter_multi_table,\n get_generic_function_deprecation_waring,\n get_parameter_default_value_deprecation_warning,\n get_parameter_generic_replacement_deprecation_warning,\n get_parameter_type_change_deprecation_warning,\n)\nfrom kartothek.utils.store import copy_rename_keys\n\n__all__ = (\n \"delete_dataset\",\n \"read_dataset_as_dataframes\",\n \"read_table\",\n \"commit_dataset\",\n \"store_dataframes_as_dataset\",\n \"create_empty_dataset_header\",\n \"write_single_partition\",\n \"update_dataset_from_dataframes\",\n \"build_dataset_indices\",\n \"garbage_collect_dataset\",\n \"copy_dataset\",\n)\n\n\n@default_docs\n@normalize_args\ndef delete_dataset(dataset_uuid=None, store=None, factory=None):\n \"\"\"\n Delete the entire dataset from the store.\n\n Parameters\n ----------\n \"\"\"\n\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n load_schema=False,\n store=store,\n factory=factory,\n load_dataset_metadata=False,\n )\n\n # Remove possibly unreferenced files\n garbage_collect_dataset(factory=ds_factory)\n\n # Delete indices first since they do not affect dataset integrity\n delete_indices(dataset_factory=ds_factory)\n\n for metapartition in dispatch_metapartitions_from_factory(ds_factory):\n metapartition = cast(MetaPartition, metapartition)\n metapartition.delete_from_store(dataset_uuid=dataset_uuid, store=store)\n\n # delete common metadata after partitions\n delete_common_metadata(dataset_factory=ds_factory)\n\n # Delete the top level metadata file\n delete_top_level_metadata(dataset_factory=ds_factory)\n\n\n@default_docs\n@deprecate_parameters(\n get_parameter_default_value_deprecation_warning(\n from_value=\"False\", to_value=\"True\", deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"dates_as_object\",\n)\n@deprecate_parameters_if_set(\n get_deprecation_warning_remove_dict_multi_table(\n deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"categoricals\",\n)\n@deprecate_parameters_if_set(\n get_deprecation_warning_remove_parameter_multi_table(\n deprecated_in=\"5.3\", removed_in=\"6.0\"\n ),\n \"tables\",\n \"label_filter\",\n \"concat_partitions_on_primary_index\",\n)\ndef read_dataset_as_dataframes(\n dataset_uuid: Optional[str] = None,\n store=None,\n tables: Optional[List[str]] = None,\n columns: Dict[str, List[str]] = None,\n concat_partitions_on_primary_index: bool = False,\n predicate_pushdown_to_io: bool = True,\n categoricals: Dict[str, List[str]] = None,\n label_filter: Callable = None,\n dates_as_object: bool = False,\n predicates: Optional[List[List[Tuple[str, str, Any]]]] = None,\n factory: Optional[DatasetFactory] = None,\n dispatch_by: Optional[List[str]] = None,\n) -> List[pd.DataFrame]:\n \"\"\"\n Read a dataset as a list of dataframes.\n\n Every element of the list corresponds to a physical partition.\n\n Parameters\n ----------\n\n Returns\n -------\n List[pandas.DataFrame]\n Returns a list of pandas.DataFrame. One element per partition\n\n Examples\n --------\n Dataset in store contains two partitions with two files each\n\n .. code ::\n\n >>> import storefact\n >>> from kartothek.io.eager import read_dataset_as_dataframes\n\n >>> store = storefact.get_store_from_url('s3://bucket_with_dataset')\n\n >>> dfs = read_dataset_as_dataframes('dataset_uuid', store, 'core')\n\n \"\"\"\n\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n store=store,\n factory=factory,\n load_dataset_metadata=True,\n )\n\n mps = read_dataset_as_metapartitions(\n tables=tables,\n columns=columns,\n concat_partitions_on_primary_index=concat_partitions_on_primary_index,\n predicate_pushdown_to_io=predicate_pushdown_to_io,\n categoricals=categoricals,\n label_filter=label_filter,\n dates_as_object=dates_as_object,\n predicates=predicates,\n factory=ds_factory,\n dispatch_by=dispatch_by,\n dispatch_metadata=False,\n )\n return [mp.data for mp in mps]\n\n\n@default_docs\n@deprecate_parameters(\n get_parameter_default_value_deprecation_warning(\n from_value=\"False\", to_value=\"True\", deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"dates_as_object\",\n)\n@deprecate_parameters_if_set(\n get_deprecation_warning_remove_parameter_multi_table(\n deprecated_in=\"5.3\", removed_in=\"6.0\"\n ),\n \"tables\",\n \"concat_partitions_on_primary_index\",\n \"label_filter\",\n \"dispatch_metadata\",\n)\ndef read_dataset_as_metapartitions(\n dataset_uuid=None,\n store=None,\n tables=None,\n columns=None,\n concat_partitions_on_primary_index=False,\n predicate_pushdown_to_io=True,\n categoricals=None,\n label_filter=None,\n dates_as_object=False,\n predicates=None,\n factory=None,\n dispatch_by=None,\n dispatch_metadata=True,\n):\n \"\"\"\n Read a dataset as a list of :class:`kartothek.io_components.metapartition.MetaPartition`.\n\n Every element of the list corresponds to a physical partition.\n\n Parameters\n ----------\n\n Returns\n -------\n List[kartothek.io_components.metapartition.MetaPartition]\n Returns a tuple of the loaded dataframe and the dataset metadata\n\n Examples\n --------\n Dataset in store contains two partitions with two files each\n\n .. code ::\n\n >>> import storefact\n >>> from kartothek.io.eager import read_dataset_as_dataframe\n\n >>> store = storefact.get_store_from_url('s3://bucket_with_dataset')\n\n >>> list_mps = read_dataset_as_metapartitions('dataset_uuid', store, 'core')\n\n \"\"\"\n\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n store=store,\n factory=factory,\n load_dataset_metadata=False,\n )\n\n if len(ds_factory.tables) > 1:\n warnings.warn(\n \"Trying to read a dataset with multiple internal tables. This functionality will be removed in the next \"\n \"major release. If you require a multi tabled data format, we recommend to switch to the kartothek Cube \"\n \"functionality. \"\n \"https://kartothek.readthedocs.io/en/stable/guide/cube/kartothek_cubes.html\",\n DeprecationWarning,\n )\n\n from .iter import read_dataset_as_metapartitions__iterator\n\n ds_iter = read_dataset_as_metapartitions__iterator(\n tables=tables,\n columns=columns,\n concat_partitions_on_primary_index=concat_partitions_on_primary_index,\n predicate_pushdown_to_io=predicate_pushdown_to_io,\n categoricals=categoricals,\n label_filter=label_filter,\n dates_as_object=dates_as_object,\n predicates=predicates,\n factory=ds_factory,\n dispatch_by=dispatch_by,\n dispatch_metadata=dispatch_metadata,\n )\n return list(ds_iter)\n\n\[email protected](\n deprecated_in=\"5.3\",\n removed_in=\"6.0\",\n details=get_generic_function_deprecation_waring(\n function_name=\"_check_compatible_list\"\n ),\n)\ndef _check_compatible_list(table, obj, argument_name=\"\"):\n if obj is None:\n return obj\n elif isinstance(obj, dict):\n if table not in obj:\n raise ValueError(\n \"Provided table {} is not compatible with input from argument {}.\".format(\n table, argument_name\n )\n )\n return obj\n elif isinstance(obj, list):\n return {table: obj}\n else:\n raise TypeError(\n \"Unknown type encountered for argument {}. Expected `list`, got `{}` instead\".format(\n argument_name, type(obj)\n )\n )\n\n\n@default_docs\n@deprecate_parameters(\n get_parameter_default_value_deprecation_warning(\n from_value=\"False\", to_value=\"True\", deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"dates_as_object\",\n)\n@deprecate_parameters_if_set(\n get_deprecation_warning_remove_dict_multi_table(\n deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"categoricals\",\n)\n@deprecate_parameters_if_set(\n get_deprecation_warning_remove_parameter_multi_table(\n deprecated_in=\"5.3\", removed_in=\"6.0\"\n ),\n \"table\",\n \"concat_partitions_on_primary_index\",\n \"label_filter\",\n)\ndef read_table(\n dataset_uuid: Optional[str] = None,\n store=None,\n table: Optional[str] = SINGLE_TABLE,\n columns: Dict[str, List[str]] = None,\n concat_partitions_on_primary_index: bool = False,\n predicate_pushdown_to_io: bool = True,\n categoricals: Dict[str, List[str]] = None,\n label_filter: Callable = None,\n dates_as_object: bool = False,\n predicates: Optional[List[List[Tuple[str, str, Any]]]] = None,\n factory: Optional[DatasetFactory] = None,\n) -> pd.DataFrame:\n \"\"\"\n A utility function to load a single table with multiple partitions as a single dataframe in one go.\n Mostly useful for smaller tables or datasets where all partitions fit into memory.\n\n The order of partitions is not guaranteed to be stable in the resulting dataframe.\n\n Parameters\n ----------\n\n Returns\n -------\n pandas.DataFrame\n Returns a pandas.DataFrame holding the data of the requested columns\n\n Examples\n --------\n Dataset in store contains two partitions with two files each\n\n .. code ::\n\n >>> import storefact\n >>> from kartothek.io.eager import read_table\n\n >>> store = storefact.get_store_from_url('s3://bucket_with_dataset')\n\n >>> df = read_table(store, 'dataset_uuid', 'core')\n\n \"\"\"\n if not isinstance(table, str):\n raise TypeError(\"Argument `table` needs to be a string\")\n\n columns = _check_compatible_list(table, columns, \"columns\")\n categoricals = _check_compatible_list(table, categoricals, \"categoricals\")\n\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n store=store,\n factory=factory,\n load_dataset_metadata=False,\n )\n partitions = read_dataset_as_dataframes(\n tables=[table],\n columns=columns,\n concat_partitions_on_primary_index=concat_partitions_on_primary_index,\n predicate_pushdown_to_io=predicate_pushdown_to_io,\n categoricals=categoricals,\n label_filter=label_filter,\n dates_as_object=dates_as_object,\n predicates=predicates,\n factory=ds_factory,\n )\n\n empty_df = empty_dataframe_from_schema(\n schema=ds_factory.table_meta[table],\n columns=columns[table] if columns is not None else None,\n )\n if categoricals:\n empty_df = empty_df.astype({col: \"category\" for col in categoricals[table]})\n dfs = [partition_data[table] for partition_data in partitions] + [empty_df]\n # require meta 4 otherwise, can't construct types/columns\n if categoricals:\n dfs = align_categories(dfs, categoricals[table])\n df = pd.concat(dfs, ignore_index=True, sort=False)\n\n # ensure column order\n if len(empty_df.columns) > 0 and list(empty_df.columns) != list(df.columns):\n df = df.reindex(empty_df.columns, copy=False, axis=1)\n\n return df\n\n\n@default_docs\n@normalize_args\n@deprecate_parameters_if_set(\n DEPRECATION_WARNING_REMOVE_PARAMETER, \"output_dataset_uuid\", \"df_serializer\",\n)\ndef commit_dataset(\n store: Optional[StoreInput] = None,\n dataset_uuid: Optional[str] = None,\n new_partitions: Optional[Iterable[MetaPartition]] = None,\n output_dataset_uuid: Optional[str] = None,\n delete_scope: Optional[Iterable[Dict[str, Any]]] = None,\n metadata: Dict = None,\n df_serializer: DataFrameSerializer = None,\n metadata_merger: Callable[[List[Dict]], Dict] = None,\n default_metadata_version: int = DEFAULT_METADATA_VERSION,\n partition_on: Optional[Iterable[str]] = None,\n factory: Optional[DatasetFactory] = None,\n secondary_indices: Optional[Iterable[str]] = None,\n):\n \"\"\"\n Commit new state to an existing dataset. This can be used for three distinct operations\n\n 1. Add previously written partitions to this dataset\n\n If for some reasons, the existing pipelines are not sufficient but you need more control, you can write the files outside of a kartothek pipeline and commit them whenever you choose to.\n\n This should be used in combination with\n :func:`~kartothek.io.eager.write_single_partition` and :func:`~kartothek.io.eager.create_empty_dataset_header`.\n\n .. code::\n\n import pandas as pd\n from kartothek.io.eager import write_single_partition, commit_dataset\n\n store = \"hfs://my_store\"\n\n # The partition writing can be done concurrently and distributed if wanted.\n # Only the information about what partitions have been written is required for the commit.\n new_partitions = [\n write_single_partition(\n store=store,\n dataset_uuid='dataset_uuid',\n data=pd.DataFrame({'column': [1, 2]}),\n )\n ]\n\n new_dataset = commit_dataset(\n store=store,\n dataset_uuid='dataset_uuid',\n new_partitions=new_partitions,\n )\n\n 2. Simple delete of partitions\n\n If you want to remove some partitions this is one of the simples ways of doing so. By simply providing a delete_scope, this removes the references to these files in an atomic commit.\n\n .. code::\n\n commit_dataset(\n store=store,\n dataset_uuid='dataset_uuid',\n delete_scope=[\n {\n \"partition_column\": \"part_value_to_be_removed\"\n }\n ],\n )\n\n 3. Add additional metadata\n\n To add new metadata to an existing dataset\n\n .. code::\n\n commit_dataset(\n store=store,\n dataset_uuid='dataset_uuid',\n metadata={\"new\": \"user_metadata\"},\n )\n\n Note::\n\n If you do not want the new metadata to be merged with the existing one, povide a custom ``metadata_merger``\n\n Parameters\n ----------\n new_partitions:\n Input partition to be committed.\n\n \"\"\"\n if not new_partitions and not metadata and not delete_scope:\n raise ValueError(\n \"Need to provide either new data, new metadata or a delete scope. None of it was provided.\"\n )\n store = lazy_store(store)\n ds_factory, metadata_version, partition_on = validate_partition_keys(\n dataset_uuid=dataset_uuid,\n store=store,\n ds_factory=factory,\n default_metadata_version=default_metadata_version,\n partition_on=partition_on,\n )\n\n mps = parse_input_to_metapartition(\n new_partitions, metadata_version=metadata_version\n )\n\n if secondary_indices:\n mps = mps.build_indices(columns=secondary_indices)\n\n mps_list = [_maybe_infer_files_attribute(mp, dataset_uuid) for mp in mps]\n\n dmd = update_dataset_from_partitions(\n mps_list,\n store_factory=store,\n dataset_uuid=dataset_uuid,\n ds_factory=ds_factory,\n delete_scope=delete_scope,\n metadata=metadata,\n metadata_merger=metadata_merger,\n )\n return dmd\n\n\ndef _maybe_infer_files_attribute(metapartition, dataset_uuid):\n new_mp = metapartition.as_sentinel()\n for mp in metapartition:\n if len(mp.files) == 0:\n if mp.data is None or len(mp.data) == 0:\n raise ValueError(\n \"Trying to commit partitions without `data` or `files` information.\"\n \"Either one is necessary to infer the dataset tables\"\n )\n new_files = {}\n for table in mp.data:\n new_files[table] = (\n get_partition_file_prefix(\n dataset_uuid=dataset_uuid,\n partition_label=mp.label,\n table=table,\n metadata_version=mp.metadata_version,\n )\n + PARQUET_FILE_SUFFIX # noqa: W503 line break before binary operator\n )\n mp = mp.copy(files=new_files)\n\n new_mp = new_mp.add_metapartition(mp)\n return new_mp\n\n\n@default_docs\n@normalize_args\n@deprecate_parameters_if_set(\n get_parameter_type_change_deprecation_warning(\n from_type=\"Optional[ParquetSerializer]\",\n to_type=\"Optional[DataFrameSerializer]\",\n deprecated_in=\"5.3\",\n changed_in=\"6.0\",\n ),\n \"df_serializer\",\n)\ndef store_dataframes_as_dataset(\n store: KeyValueStore,\n dataset_uuid: str,\n dfs: List[Union[pd.DataFrame, Dict[str, pd.DataFrame]]],\n metadata: Optional[Dict[str, Dict[str, Any]]] = None,\n partition_on: Optional[List[str]] = None,\n df_serializer: Optional[ParquetSerializer] = None,\n overwrite: bool = False,\n secondary_indices=None,\n metadata_storage_format: str = DEFAULT_METADATA_STORAGE_FORMAT,\n metadata_version: int = DEFAULT_METADATA_VERSION,\n):\n \"\"\"\n Utility function to store a list of dataframes as a partitioned dataset with multiple tables (files).\n\n Useful for very small datasets where all data fits into memory.\n\n Parameters\n ----------\n dfs:\n The dataframe(s) to be stored.\n\n \"\"\"\n if isinstance(dfs, (pd.DataFrame, dict)):\n dfs = [dfs]\n warnings.warn(\n \"Passing a single dataframe instead of an iterable is deprecated and may \"\n \"be removed in the next major release.\",\n DeprecationWarning,\n )\n\n return store_dataframes_as_dataset__iter(\n dfs,\n store=store,\n dataset_uuid=dataset_uuid,\n metadata=metadata,\n partition_on=partition_on,\n df_serializer=df_serializer,\n overwrite=overwrite,\n secondary_indices=secondary_indices,\n metadata_storage_format=metadata_storage_format,\n metadata_version=metadata_version,\n )\n\n\n@default_docs\n@normalize_args\n@deprecate_parameters_if_set(\n get_parameter_generic_replacement_deprecation_warning(\n replacing_parameter=\"schema\", deprecated_in=\"5.3\", changed_in=\"6.0\"\n ),\n \"table_meta\",\n)\ndef create_empty_dataset_header(\n store,\n dataset_uuid,\n table_meta,\n partition_on=None,\n metadata=None,\n overwrite=False,\n metadata_storage_format=DEFAULT_METADATA_STORAGE_FORMAT,\n metadata_version=DEFAULT_METADATA_VERSION,\n):\n \"\"\"\n Create an dataset header without any partitions. This may be used in combination\n with :func:`~kartothek.io.eager.write_single_partition` to create implicitly partitioned datasets.\n\n .. note::\n\n The created dataset will **always** have explicit_partition==False\n\n .. warning::\n\n This function should only be used in very rare occasions. Usually you're better off using\n full end-to-end pipelines.\n\n Parameters\n ----------\n \"\"\"\n store = lazy_store(store)()\n if not overwrite:\n raise_if_dataset_exists(dataset_uuid=dataset_uuid, store=store)\n\n for table, schema in table_meta.items():\n table_meta[table] = make_meta(schema, origin=table, partition_keys=partition_on)\n store_schema_metadata(\n schema=table_meta[table],\n dataset_uuid=dataset_uuid,\n store=store,\n table=table,\n )\n dataset_builder = DatasetMetadataBuilder(\n uuid=dataset_uuid,\n metadata_version=metadata_version,\n partition_keys=partition_on,\n explicit_partitions=False,\n table_meta=table_meta,\n )\n if metadata:\n for key, value in metadata.items():\n dataset_builder.add_metadata(key, value)\n if metadata_storage_format.lower() == \"json\":\n store.put(*dataset_builder.to_json())\n elif metadata_storage_format.lower() == \"msgpack\":\n store.put(*dataset_builder.to_msgpack())\n else:\n raise ValueError(\n \"Unknown metadata storage format encountered: {}\".format(\n metadata_storage_format\n )\n )\n return dataset_builder.to_dataset()\n\n\n@default_docs\n@normalize_args\n@deprecate_parameters_if_set(\n get_parameter_type_change_deprecation_warning(\n from_type=\"Optional[ParquetSerializer]\",\n to_type=\"Optional[DataFrameSerializer]\",\n deprecated_in=\"5.3\",\n changed_in=\"6.0\",\n ),\n \"df_serializer\",\n)\n@deprecate_parameters_if_set(\n DEPRECATION_WARNING_REMOVE_PARAMETER, \"metadata\", \"overwrite\", \"metadata_merger\",\n)\ndef write_single_partition(\n store: Optional[KeyValueStore] = None,\n dataset_uuid: Optional[str] = None,\n data=None,\n metadata: Optional[Dict[str, Dict[str, Any]]] = None,\n df_serializer: Optional[ParquetSerializer] = None,\n overwrite: bool = False,\n metadata_merger=None,\n metadata_version: int = DEFAULT_METADATA_VERSION,\n partition_on: Optional[List[str]] = None,\n factory=None,\n secondary_indices=None,\n):\n \"\"\"\n Write the parquet file(s) for a single partition. This will **not** update the dataset header and can therefore\n be used for highly concurrent dataset writes.\n\n For datasets with explicit partitions, the dataset header can be updated by calling\n :func:`kartothek.io.eager.commit_dataset` with the output of this function.\n\n .. note::\n\n It is highly recommended to use the full pipelines whenever possible. This functionality should be\n used with caution and should only be necessary in cases where traditional pipeline scheduling is not an\n option.\n\n .. note::\n\n This function requires an existing dataset metadata file and the schemas for the tables to be present.\n Either you have ensured that the dataset always exists though some other means or use\n :func:`create_empty_dataset_header` at the start of your computation to ensure the basic dataset\n metadata is there.\n\n Parameters\n ----------\n data: Dict\n The input is defined according to :func:`~kartothek.io_components.metapartition.parse_input_to_metapartition`\n\n Returns\n -------\n An empty :class:`~kartothek.io_components.metapartition.MetaPartition` referencing the new files\n \"\"\"\n if data is None:\n raise TypeError(\"The parameter `data` is not optional\")\n _, ds_metadata_version, partition_on = validate_partition_keys(\n dataset_uuid=dataset_uuid,\n store=lazy_store(store),\n ds_factory=factory,\n default_metadata_version=metadata_version,\n partition_on=partition_on,\n )\n\n mp = parse_input_to_metapartition(obj=data, metadata_version=ds_metadata_version)\n if partition_on:\n mp = mp.partition_on(partition_on)\n\n if secondary_indices:\n mp = mp.build_indices(columns=secondary_indices)\n\n mp = mp.validate_schema_compatible(dataset_uuid=dataset_uuid, store=store)\n\n mp = mp.store_dataframes(\n store=store, dataset_uuid=dataset_uuid, df_serializer=df_serializer\n )\n return mp\n\n\n@default_docs\n@normalize_args\n@deprecate_parameters_if_set(\n get_parameter_type_change_deprecation_warning(\n from_type=\"Optional[ParquetSerializer]\",\n to_type=\"Optional[DataFrameSerializer]\",\n deprecated_in=\"5.3\",\n changed_in=\"6.0\",\n ),\n \"df_serializer\",\n)\n@deprecate_parameters_if_set(\n DEPRECATION_WARNING_REMOVE_PARAMETER,\n \"central_partition_metadata\",\n \"load_dynamic_metadata\",\n)\ndef update_dataset_from_dataframes(\n df_list: List[Union[pd.DataFrame, Dict[str, pd.DataFrame]]],\n store: Optional[KeyValueStore] = None,\n dataset_uuid: Optional[str] = None,\n delete_scope=None,\n metadata=None,\n df_serializer: Optional[ParquetSerializer] = None,\n metadata_merger: Callable = None,\n central_partition_metadata: bool = True,\n default_metadata_version: int = DEFAULT_METADATA_VERSION,\n partition_on: Optional[List[str]] = None,\n load_dynamic_metadata: bool = True,\n sort_partitions_by: Optional[str] = None,\n secondary_indices: Optional[List[str]] = None,\n factory: Optional[DatasetFactory] = None,\n) -> DatasetMetadata:\n \"\"\"\n Update a kartothek dataset in store at once, using a list of dataframes.\n\n Useful for datasets which do not fit into memory.\n\n Parameters\n ----------\n df_list:\n The dataframe(s) to be stored.\n\n Returns\n -------\n The dataset metadata object (:class:`~kartothek.core.dataset.DatasetMetadata`).\n\n See Also\n --------\n :ref:`mutating_datasets`\n \"\"\"\n ds_factory, metadata_version, partition_on = validate_partition_keys(\n dataset_uuid=dataset_uuid,\n store=store,\n ds_factory=factory,\n default_metadata_version=default_metadata_version,\n partition_on=partition_on,\n )\n\n inferred_indices = _ensure_compatible_indices(ds_factory, secondary_indices)\n del secondary_indices\n\n mp = parse_input_to_metapartition(\n df_list,\n metadata_version=metadata_version,\n expected_secondary_indices=inferred_indices,\n )\n\n if sort_partitions_by:\n mp = mp.apply(partial(sort_values_categorical, columns=sort_partitions_by))\n\n if partition_on:\n mp = mp.partition_on(partition_on)\n\n if inferred_indices:\n mp = mp.build_indices(inferred_indices)\n\n mp = mp.store_dataframes(\n store=store, dataset_uuid=dataset_uuid, df_serializer=df_serializer\n )\n\n return update_dataset_from_partitions(\n mp,\n store_factory=store,\n dataset_uuid=dataset_uuid,\n ds_factory=ds_factory,\n delete_scope=delete_scope,\n metadata=metadata,\n metadata_merger=metadata_merger,\n )\n\n\n@default_docs\n@normalize_args\ndef build_dataset_indices(store, dataset_uuid, columns, factory=None):\n \"\"\"\n Function which builds a :class:`~kartothek.core.index.ExplicitSecondaryIndex`.\n\n This function loads the dataset, computes the requested indices and writes\n the indices to the dataset. The dataset partitions itself are not mutated.\n\n Parameters\n ----------\n \"\"\"\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n store=store,\n factory=factory,\n load_dataset_metadata=False,\n )\n\n cols_to_load = {\n table: set(columns) & set(meta.names)\n for table, meta in ds_factory.table_meta.items()\n }\n cols_to_load = {table: cols for table, cols in cols_to_load.items() if cols}\n\n new_partitions = []\n for mp in dispatch_metapartitions_from_factory(ds_factory):\n mp = mp.load_dataframes(\n store=ds_factory.store,\n tables=list(cols_to_load.keys()),\n columns=cols_to_load,\n )\n mp = mp.build_indices(columns=columns)\n mp = mp.remove_dataframes() # Remove dataframe from memory\n new_partitions.append(mp)\n\n return update_indices_from_partitions(\n new_partitions, dataset_metadata_factory=ds_factory\n )\n\n\n@default_docs\n@normalize_args\ndef garbage_collect_dataset(dataset_uuid=None, store=None, factory=None):\n \"\"\"\n Remove auxiliary files that are no longer tracked by the dataset.\n\n These files include indices that are no longer referenced by the metadata\n as well as files in the directories of the tables that are no longer\n referenced. The latter is only applied to static datasets.\n\n Parameters\n ----------\n \"\"\"\n\n ds_factory = _ensure_factory(\n dataset_uuid=dataset_uuid,\n store=store,\n factory=factory,\n load_dataset_metadata=False,\n )\n\n nested_files = dispatch_files_to_gc(\n dataset_uuid=None, store_factory=None, chunk_size=None, factory=ds_factory\n )\n\n # Given that `nested_files` is a generator with a single element, just\n # return the output of `delete_files` on that element.\n return delete_files(next(nested_files), store_factory=ds_factory.store_factory)\n\n\ndef copy_dataset(\n source_dataset_uuid: str,\n store: KeyValueStore,\n target_dataset_uuid: Optional[str] = None,\n target_store: Optional[KeyValueStore] = None,\n) -> Dict[str, DatasetMetadata]:\n \"\"\"\n Copies and optionally renames a dataset, either from one store to another or\n within one store.\n\n Parameters\n ----------\n source_dataset_uuid: str\n UUID of source dataset\n store: simplekv.KeyValueStore\n Source store\n target_dataset_uuid: Optional[str]\n UUID of target dataset. May be the same as src_dataset_uuid, if store\n and tgt_store are different. If empty, src_dataset_uuid is used\n target_store: Optional[simplekv.KeyValueStore]\n Target Store. May be the same as store, if src_dataset_uuid and\n target_dataset_uuid are different. If empty, value from parameter store is\n used\n \"\"\"\n if target_dataset_uuid is None:\n target_dataset_uuid = source_dataset_uuid\n if target_store is None:\n target_store = store\n\n if (source_dataset_uuid == target_dataset_uuid) & (store == target_store):\n raise ValueError(\n \"Cannot copy to a dataset with the same UUID within the same store!\"\n )\n\n ds_factory_source = _ensure_factory(\n dataset_uuid=source_dataset_uuid,\n store=store,\n factory=None,\n load_dataset_metadata=True,\n )\n\n # Create a dict of {source key: target key} entries\n keys = get_dataset_keys(ds_factory_source.dataset_metadata)\n mapped_keys = {\n source_key: source_key.replace(source_dataset_uuid, target_dataset_uuid)\n for source_key in keys\n }\n\n # Create a dict of metadata which has to be changed. This is only the\n # <uuid>.by-dataset-metadata.json file\n\n md_transformed = {\n f\"{target_dataset_uuid}{METADATA_BASE_SUFFIX}{METADATA_FORMAT_JSON}\": DatasetMetadataBuilder.from_dataset(\n ds_factory_source.dataset_metadata\n )\n .modify_uuid(target_dataset_uuid)\n .to_dataset()\n }\n # Copy the keys from one store to another\n copy_rename_keys(mapped_keys, store, target_store, md_transformed)\n\n return md_transformed\n" ]
[ [ "pandas.concat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
ChristianSchorr/InertialFlowCutter
[ "baac26aa394e6bb58ed43d122b820dd963cfb303", "baac26aa394e6bb58ed43d122b820dd963cfb303" ]
[ "evaluation/parameterstudy.py", "evaluation/order_experiments.py" ]
[ "import configurable_inertialflowcutter_order as ifc\nimport pandas as pd\nimport numpy as np\nimport re\nimport subprocess\nimport os\n\nexperiments_folder = \"\"\ngraph = \"col\" #TODO replace again with europe\ngraph_path = experiments_folder + graph + \"/\"\nmetric_path = graph_path + \"travel_time\"\nquery_sources = experiments_folder + graph + \".q.s\"\nquery_targets = experiments_folder + graph + \".q.t\"\n\nbinary_path = \"./../build/\"\norder_console = binary_path + \"console\"\ncustomization_binary = binary_path + \"customize\"\nquery_binary = binary_path + \"query\"\n\n\ndef config_contained(config, results):\n cpd = pd.DataFrame([config._asdict()])\n return len(cpd.merge(results)) > 0\n\ndef config_to_string(config):\n return '.'.join(map(str,config))\n\ndef order_path(config):\n return experiments_folder + \"parameterstudy/\" + graph + \".\" + config_to_string(config) + \".order\"\n\ndef log_path(config):\n return order_path(config) + \".log\"\n\ndef parse_order_log(config):\n log = open(log_path(config))\n row_dict = dict()\n for l in log:\n m = re.match(r\"^\\s*([a-zA-Z_ ]+) : ([0-9.]+)[^0-9]*$\", l)\n assert(m)\n name = m.group(1).replace(\" \", \"_\")\n value = m.group(2)\n if '.' in value:\n value = float(value)\n else:\n value = int(value)\n if \"running_time\" in name:\n name = \"order_running_time\"\n value /= 1000000 #in seconds\n row_dict[name] = value\n return row_dict\n\ndef run_customizations(config):\n args = [customization_binary, graph_path + \"first_out\", graph_path + \"head\", order_path(config), metric_path, str(1)]\n runtimes = []\n for i in range(9):\n t = subprocess.check_output(args, universal_newlines=True)\n runtimes.append(float(t) / 1000) #in ms\n return np.median(np.array(runtimes))\n\ndef run_queries(config):\n args = [query_binary, graph_path + \"first_out\", graph_path + \"head\", order_path(config), metric_path, query_sources, query_targets]\n t = subprocess.check_output(args, universal_newlines=True)\n return float(t)\n\ndef main():\n configs = pd.read_csv(experiments_folder + \"parameterstudy_configs.csv\")\n if not os.path.isfile(experiments_folder + \"parameterstudy.csv\"):\n x = pd.DataFrame(columns=[\"geo_distance_cutters\",\"hop_distance_cutters\",\"initial_assimilated_fraction\",\"bulk_step_fraction\",\"bulk_assimilation_order_threshold\",\"bulk_assimilation_threshold\"])\n x.to_csv(experiments_folder + \"parameterstudy.csv\", index=False)\n results = pd.read_csv(experiments_folder + \"parameterstudy.csv\")\n\n for config in configs.itertuples(index=False):\n if not config_contained(config, results):\n print(\"computing order with config\", config)\n ifc.save_inertialflowcutter_cch_order(config, order_console, graph_path, order_path(config), log_path(config))\n row_dict = config._asdict()\n row_dict.update(parse_order_log(config))\n print(\"running customization\")\n row_dict[\"median_customization_time\"] = run_customizations(config)\n print(\"running queries\")\n row_dict[\"avg_query_time\"] = run_queries(config)\n print(row_dict)\n results = results.append(pd.DataFrame([row_dict]), ignore_index=True)\n\n results.sort_values([x for x in configs.columns], ascending=[True for i in configs.columns], inplace=True)\n results.to_csv(experiments_folder + \"parameterstudy.csv\", index=False) #careful\nif __name__ == '__main__':\n main()\n", "import pandas as pd\nimport numpy as np\nimport re\nimport subprocess\nimport os\n\nexperiments_folder = \"\"\n\ngraphs = [\"col\", \"cal\", \"europe\", \"usa\"]\npartitioners = [\"metis\", \"kahip_v0_71\", \"kahip_v1_00_cut\", \"kahip_v2_11\", \"inertial_flow\", \"flowcutter3\", \"flowcutter20\", \"flowcutter100\",\"inertialflowcutter4\", \"inertialflowcutter8\", \"inertialflowcutter12\", \"inertialflowcutter16\"]\n\nbinary_path = \"./../build/\"\nconsole = binary_path + \"console\"\ncustomization_binary = binary_path + \"customize\"\nquery_binary = binary_path + \"query\"\n\ndef config_contained(G, P, results):\n cpd = pd.DataFrame.from_dict({\n 'graph' : [G],\n 'partitioner' : [P],\n })\n return len(cpd.merge(results)) > 0\n\ndef partitioner_id(P):\n return next(i for i,v in enumerate(partitioners) if v == P)\n\ndef graph_id(G):\n return next(i for i,v in enumerate(graphs) if v == G)\n\ndef order_path(G,P):\n return experiments_folder + G + \".\" + P + \".order\"\n\ndef graph_path(G):\n return experiments_folder + G + \"/\"\n\ndef metric_file(G):\n return graph_path(G) + \"travel_time\"\n\ndef query_file(G):\n return experiments_folder + G + \".q.\"\n\ndef parse_order_log(G,P):\n args = [console]\n args.append(\"load_routingkit_unweighted_graph\")\n \n args.append(graph_path(G) + \"first_out\")\n args.append(graph_path(G) + \"head\")\n args.append(\"add_back_arcs\")\n args.append(\"remove_multi_arcs\")\n args.append(\"remove_loops\")\n \n args.append(\"permutate_nodes_routingkit\")\n args.append(order_path(G,P))\n\n args.append(\"examine_chordal_supergraph\")\n log = subprocess.check_output(args, universal_newlines=True)\n print(log)\n row_dict = dict()\n for l in log.splitlines():\n if l == \"\":\n continue\n m = re.match(r\"^\\s*([a-zA-Z_ ]+) : ([0-9.]+)[^0-9]*$\", l)\n assert(m)\n name = m.group(1).replace(\" \", \"_\")\n value = m.group(2)\n if '.' in value:\n value = float(value)\n else:\n value = int(value)\n row_dict[name] = value\n return row_dict\n\ndef run_customizations(G,P):\n q = query_file(G)\n g = graph_path(G)\n args = [customization_binary, g + \"first_out\", g + \"head\", order_path(G,P), metric_file(G), str(1)]\n for x in args:\n print(x, end=' ')\n print()\n runtimes = []\n for i in range(9):\n t = subprocess.check_output(args, universal_newlines=True)\n runtimes.append(float(t) / 1000) #in ms\n print(t.strip())\n return np.median(np.array(runtimes))\n\ndef run_queries(G,P):\n q = query_file(G)\n g = graph_path(G)\n args = [query_binary, g + \"first_out\", g + \"head\", order_path(G,P), metric_file(G), q + \"s\", q + \"t\"]\n for x in args:\n print(x, end=' ')\n print()\n t = subprocess.check_output(args, universal_newlines=True)\n print(t.strip())\n return float(t)\n\ndef main():\n \n order_times = pd.read_csv(experiments_folder + \"order_running_time.csv\")\n\n if not os.path.isfile(experiments_folder + \"order_experiments.csv\"): #Create nonsensical file\n f = open(experiments_folder + \"order_experiments.csv\", 'w')\n f.write(\"graph,partitioner\\n\") #Could be anything in csv\n f.close()\n results = pd.read_csv(experiments_folder + \"order_experiments.csv\")\n\n for G in graphs:\n for P in partitioners:\n if not os.path.isfile(order_path(G,P)):\n print(\"Warning: order for partitioner\", P, \"on graph\", G, \"missing. Skip.\")\n continue\n if config_contained(G, P, results):\n print(\"Skipping\", P, G, \"because this config was already run\")\n continue\n print(\"Running\", P, G)\n row_dict = dict()\n row_dict[\"graph\"] = G\n row_dict[\"partitioner\"] = P\n print(\"parsing order log\")\n row_dict.update(parse_order_log(G,P))\n row_dict[\"order_running_time\"] = float(order_times[(order_times.partitioner==P) & (order_times.graph==G)].order_running_time_sec) #If this fails, the order exists, but the running time is not in order_running_time.csv\n print(\"running customization\")\n row_dict[\"median_customization_time\"] = run_customizations(G,P)\n print(\"running queries\")\n row_dict[\"avg_query_time\"] = run_queries(G,P)\n print(row_dict)\n results = results.append(pd.DataFrame([row_dict]), ignore_index=True)\n\n print(\"Order experiments done.\")\n new_cols = list(results.columns)\n new_cols.remove(\"graph\")\n new_cols.remove(\"partitioner\")\n new_cols = [\"graph\", \"partitioner\"] + new_cols\n results = results[new_cols]\n results[\"graph_id\"] = results[\"graph\"].map(graph_id)\n results[\"partitioner_id\"] = results[\"partitioner\"].map(partitioner_id)\n results.sort_values([\"graph_id\", \"partitioner_id\"], ascending=[True,True], inplace=True)\n results.drop(columns=[\"graph_id\", \"partitioner_id\"])\n results.to_csv(experiments_folder + \"order_experiments.csv\", index=False)\n \n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array", "pandas.read_csv", "pandas.DataFrame" ], [ "numpy.array", "pandas.read_csv", "pandas.DataFrame", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
JedersonLuz/Codenation_AceleraDev_DataScience
[ "a23137ba7f1349bdc544647ef680ea6f822f797b" ]
[ "module_3/df_test.py" ]
[ "import pandas as pd\r\nimport altair as alt\r\nimport streamlit as st\r\n\r\[email protected]\r\ndef get_UN_data():\r\n AWS_BUCKET_URL = \"https://streamlit-demo-data.s3-us-west-2.amazonaws.com\"\r\n df = pd.read_csv(AWS_BUCKET_URL + \"/agri.csv.gz\")\r\n return df.set_index(\"Region\")\r\n\r\ntry:\r\n df = get_UN_data()\r\nexcept urllib.error.URLError as e:\r\n st.error(\r\n \"\"\"\r\n **This demo requires internet access.**\r\n\r\n Connection error: %s\r\n \"\"\"\r\n % e.reason\r\n )\r\n #return\r\n\r\ncountries = st.multiselect(\r\n \"Choose countries\", list(df.index), [\"China\", \"United States of America\"]\r\n)\r\nif not countries:\r\n st.error(\"Please select at least one country.\")\r\n #return\r\n\r\ndata = df.loc[countries]\r\ndata /= 1000000.0\r\nst.write(\"### Gross Agricultural Production ($B)\", data.sort_index())\r\n\r\ndata = data.T.reset_index()\r\ndata = pd.melt(data, id_vars=[\"index\"]).rename(\r\n columns={\"index\": \"year\", \"value\": \"Gross Agricultural Product ($B)\"}\r\n)\r\nchart = (\r\n alt.Chart(data)\r\n .mark_area(opacity=0.3)\r\n .encode(\r\n x=\"year:T\",\r\n y=alt.Y(\"Gross Agricultural Product ($B):Q\", stack=None),\r\n color=\"Region:N\",\r\n )\r\n)\r\nst.altair_chart(chart, use_container_width=True)" ]
[ [ "pandas.read_csv", "pandas.melt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
kishiyamat/npbdaa
[ "c13a97b32635e00b192b7075fdc09875710c5029", "c13a97b32635e00b192b7075fdc09875710c5029" ]
[ "sample/simple_pyhlm_sample.py", "sample/summary_and_plot_light.py" ]
[ "import time\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport pyhsmm\nfrom tqdm import trange\nfrom util.config_parser import ConfigParser_with_eval\n\nfrom pyhlm.model import WeakLimitHDPHLM\nfrom pyhlm.word_model import LetterHSMM\n\nwarnings.filterwarnings('ignore')\n\n\n# import pyximport;\n# pyximport.install() # https://stackoverflow.com/questions/36880336/setup-of-pycharm-for-cython\n\n\ndef load_config(filename):\n cp = ConfigParser_with_eval()\n cp.read(filename)\n return cp\n\n\ndef load_datas():\n data = []\n names = np.loadtxt(\"files.txt\", dtype=str)\n files = names\n for name in names:\n data.append(np.loadtxt(\"DATA/\" + name + \".txt\"))\n return data\n\n\ndef unpack_durations(dur):\n unpacked = np.zeros(dur.sum())\n d = np.cumsum(dur)\n unpacked[d - 1] = 1.0\n return unpacked\n\n\ndef save_stateseq(model):\n # Save sampled states sequences.\n names = np.loadtxt(\"files.txt\", dtype=str)\n for i, s in enumerate(model.states_list):\n with open(\"results/\" + names[i] + \"_s.txt\", \"a\") as f:\n np.savetxt(f, s.stateseq, fmt=\"%d\")\n with open(\"results/\" + names[i] + \"_l.txt\", \"a\") as f:\n np.savetxt(f, s.letter_stateseq, fmt=\"%d\")\n with open(\"results/\" + names[i] + \"_d.txt\", \"a\") as f:\n np.savetxt(f, unpack_durations(s.durations_censored), fmt=\"%d\")\n\n\ndef save_params_as_text(itr_idx, model):\n with open(\"parameters/ITR_{0:04d}.txt\".format(itr_idx), \"w\") as f:\n f.write(str(model.params))\n\n\ndef save_params_as_file(iter_idx, model):\n params = model.params\n root_dir = Path(\"parameters/ITR_{0:04d}\".format(iter_idx))\n root_dir.mkdir(exist_ok=True)\n save_json(root_dir, params)\n\n\ndef save_json(root_dir, json_obj):\n for keyname, subjson in json_obj.items():\n type_of_subjson = type(subjson)\n if type_of_subjson == dict:\n dir = root_dir / keyname\n dir.mkdir(exist_ok=True)\n save_json(dir, json_obj[keyname])\n else:\n savefile = root_dir / f\"{keyname}.txt\"\n if type_of_subjson == np.ndarray:\n if subjson.dtype in [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64]:\n np.savetxt(savefile, subjson, fmt=\"%d\")\n else:\n np.savetxt(savefile, subjson)\n else:\n savefile.write_text(str(subjson))\n\n\ndef save_params_as_npz(iter_idx, model):\n params = model.params\n flatten_params = flatten_json(params)\n # flatten_params = copy_flatten_json(flatten_params)\n np.savez(f\"parameters/ITR_{iter_idx:04d}.npz\", **flatten_params)\n\n\ndef flatten_json(json_obj, keyname_prefix=None, dict_obj=None):\n if dict_obj is None:\n dict_obj = {}\n if keyname_prefix is None:\n keyname_prefix = \"\"\n for keyname, subjson in json_obj.items():\n if type(subjson) == dict:\n prefix = f\"{keyname_prefix}{keyname}/\"\n flatten_json(subjson, keyname_prefix=prefix, dict_obj=dict_obj)\n else:\n dict_obj[f\"{keyname_prefix}{keyname}\"] = subjson\n return dict_obj\n\n\ndef unflatten_json(flatten_json_obj):\n dict_obj = {}\n for keyname, value in flatten_json_obj.items():\n current_dict = dict_obj\n splitted_keyname = keyname.split(\"/\")\n for key in splitted_keyname[:-1]:\n if key not in current_dict:\n current_dict[key] = {}\n current_dict = current_dict[key]\n current_dict[splitted_keyname[-1]] = value\n return dict_obj\n\n\ndef copy_flatten_json(json_obj):\n new_json = {}\n for keyname, subjson in json_obj.items():\n type_of_subjson = type(subjson)\n if type_of_subjson in [int, float, complex, bool]:\n new_json[keyname] = subjson\n elif type_of_subjson in [list, tuple]:\n new_json[keyname] = subjson[:]\n elif type_of_subjson == np.ndarray:\n new_json[keyname] = subjson.copy()\n else:\n raise NotImplementedError(f\"type :{type_of_subjson} can not copy. Plz implement here!\")\n return new_json\n\n\ndef save_loglikelihood(model):\n with open(\"summary_files/log_likelihood.txt\", \"a\") as f:\n f.write(str(model.log_likelihood()) + \"\\n\")\n\n\ndef save_resample_times(resample_time):\n with open(\"summary_files/resample_times.txt\", \"a\") as f:\n f.write(str(resample_time) + \"\\n\")\n\n\ndef main():\n # Ensure that you have the directories\n Path(\"results\").mkdir(exist_ok=True)\n Path(\"parameters\").mkdir(exist_ok=True)\n Path(\"summary_files\").mkdir(exist_ok=True)\n\n # Declare the config path\n # NOTE: use `unroll_default_config.py` to get the following configs.\n hypparams_model = \"hypparams/model.config\"\n hypparams_letter_duration = \"hypparams/letter_duration.config\"\n hypparams_letter_hsmm = \"hypparams/letter_hsmm.config\"\n hypparams_letter_observation = \"hypparams/letter_observation.config\"\n hypparams_pyhlm = \"hypparams/pyhlm.config\"\n hypparams_word_length = \"hypparams/word_length.config\"\n hypparams_superstate = \"hypparams/superstate.config\"\n\n # Parse configs such as hyper parameters\n config_parser = load_config(hypparams_model)\n section = config_parser[\"model\"] # it has some sections\n thread_num: int = section[\"thread_num\"]\n pretrain_iter: int = section[\"pretrain_iter\"]\n train_iter: int = section[\"train_iter\"]\n word_num: int = section[\"word_num\"]\n letter_num: int = section[\"letter_num\"]\n observation_dim = section[\"observation_dim\"]\n\n # コンフィグ(Sectionというクラス. dictのように使える)だけを返す.\n hlm_hypparams = load_config(hypparams_pyhlm)[\"pyhlm\"]\n\n config_parser = load_config(hypparams_letter_observation)\n obs_hypparams = [config_parser[f\"{i + 1}_th\"] for i in range(letter_num)]\n\n config_parser = load_config(hypparams_letter_duration)\n dur_hypparams = [config_parser[f\"{i + 1}_th\"] for i in range(letter_num)]\n\n len_hypparams = load_config(hypparams_word_length)[\"word_length\"]\n\n letter_hsmm_hypparams = load_config(hypparams_letter_hsmm)[\"letter_hsmm\"]\n\n superstate_config = load_config(hypparams_superstate)\n\n # Make instance of distributions and models\n letter_obs_distns = [pyhsmm.distributions.Gaussian(**hypparam) for hypparam in obs_hypparams]\n letter_dur_distns = [pyhsmm.distributions.PoissonDuration(**hypparam) for hypparam in dur_hypparams] # Argが変?\n dur_distns = [pyhsmm.distributions.PoissonDuration(lmbda=20) for _ in range(word_num)] # Argが変?\n length_distn = pyhsmm.distributions.PoissonDuration(**len_hypparams) # Argが変?\n\n letter_hsmm = LetterHSMM(**letter_hsmm_hypparams, obs_distns=letter_obs_distns, dur_distns=letter_dur_distns)\n model = WeakLimitHDPHLM(**hlm_hypparams, letter_hsmm=letter_hsmm, dur_distns=dur_distns, length_distn=length_distn)\n\n # TODO: 要は何をすれば良いのか、の記述\n # 1. セットアップ\n # a. プロジェクトのクローン\n # b. 各種ライブラリの導入\n # c. optional: PyCharmなどを使う場合は Cython のコンパイル\n # 2. データの配置 (sample/DATA/.)\n # a. データは一つの観測 (e.g. aioi_aioi) で得た (m, n_feature) の行列\n # ただし、その行列は txt として export される。\n # FYI: file name にはセグメントとワードを書いてある (e.g. aioi_aioi.txt)\n # c. 学習する txt のリストを `files.txt` として配置 (sample/.)\n # 3. ハイパーパラメータを設定\n # a. 必要に応じて `default.config` の以下を更新:\n # model, pyhlm, letter_observation, letter_duration, letter_hsmm, superstate, word_length\n # b. `unroll_default_config.py` を使って展開 (各ファイル名はよしなにつけてくれる)\n # 4. `pyhlm_sample.py` (あるいは simple_pyhlm_sample.py) を実行\n # a. よしなに学習をすすめてくれる模様\n # 5. `summary_and_plot.py` を実行\n # a. load model config -> plot results -> ARI の計算などなど\n # a. DAAのletterとsegmentのアノテーションの図がそれぞれ `<label>_l.png` と `<label>_s.png` に書き出される\n # FYI: Path モジュールの `import` が無いように見える (c.f. https://github.com/RyoOzaki/npbdaa/pull/2/files)\n # FYI: `Log_likelihood.png` の生成は ValueError を起こす\n # TODO: 質問\n # 1. 分析/報告の手順\n # a. Aと同様、A\n # b. Bと同様、B\n # c. その他\n # 1. 分析にベースラインとの比較が含まれる場合(b/c)、妥当なベースライン\n # 1. 上の3のハイパーパラメータを設定するステップに関するドキュメントは存在するか\n # %%\n files = np.loadtxt(\"files.txt\", dtype=str)\n datas = load_datas()\n\n # %% Pre training.\n for data in datas:\n letter_hsmm.add_data(data, **superstate_config[\"DEFAULT\"])\n for t in trange(pretrain_iter): # t: 0\n letter_hsmm.resample_model(num_procs=thread_num)\n letter_hsmm.states_list = []\n\n # %%\n print(\"Add datas...\")\n for name, data in zip(files, datas):\n model.add_data(data, **superstate_config[name], generate=False)\n model.resample_states(num_procs=thread_num)\n # # or\n # for name, data in zip(files, datas):\n # model.add_data(data, **superstate_config[name], initialize_from_prior=False)\n print(\"Done!\")\n\n # %% Save init params\n # save_params_as_text(0, model)\n # save_params_as_file(0, model)\n save_params_as_npz(0, model)\n save_loglikelihood(model)\n\n # %%\n for t in trange(train_iter):\n st = time.time()\n model.resample_model(num_procs=thread_num)\n resample_model_time = time.time() - st\n save_stateseq(model)\n save_loglikelihood(model)\n # save_params_as_text(t+1, model)\n # save_params_as_file(t+1, model)\n save_params_as_npz(t + 1, model)\n save_resample_times(resample_model_time)\n print(model.word_list)\n print(model.word_counts())\n print(f\"log_likelihood:{model.log_likelihood()}\")\n print(f\"resample_model:{resample_model_time}\")\n\n\nif __name__ == \"__main__\":\n main()\n", "#%%\nfrom pathlib import Path\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.cm as cm\nfrom tqdm import trange, tqdm\nfrom sklearn.metrics import adjusted_rand_score, f1_score\nfrom argparse import ArgumentParser\nfrom util.config_parser import ConfigParser_with_eval\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#%% parse arguments\ndef arg_check(value, default):\n return value if value else default\n\ndefault_hypparams_model = \"hypparams/model.config\"\n\nparser = ArgumentParser()\nparser.add_argument(\"--model\", help=f\"hyper parameters of model, default is [{default_hypparams_model}]\")\nargs = parser.parse_args()\n\nhypparams_model = arg_check(args.model, default_hypparams_model)\n\n#%%\ndef load_config(filename):\n cp = ConfigParser_with_eval()\n cp.read(filename)\n return cp\n\n#%%\ndef get_names():\n return np.loadtxt(\"files.txt\", dtype=str)\n\ndef get_letter_labels(names):\n return _get_labels(names, \"lab\")\n\ndef get_word_labels(names):\n return _get_labels(names, \"lab2\")\n\ndef _get_labels(names, ext):\n return [np.loadtxt(\"LABEL/\" + name + \".\" + ext) for name in names]\n\n\ndef get_datas_and_length(names):\n datas = [np.loadtxt(\"DATA/\" + name + \".txt\") for name in names]\n length = [len(d) for d in datas]\n return datas, length\n\ndef get_results_of_word(names, length):\n return _joblib_get_results(names, length, \"s\")\n\ndef get_results_of_letter(names, length):\n return _joblib_get_results(names, length, \"l\")\n\ndef get_results_of_duration(names, length):\n return _joblib_get_results(names, length, \"d\")\n\ndef _get_results(names, lengths, c):\n return [np.loadtxt(\"results/\" + name + \"_\" + c + \".txt\").reshape((-1, l)) for name, l in zip(names, lengths)]\n\ndef _joblib_get_results(names, lengths, c):\n from joblib import Parallel, delayed\n def _component(name, length, c):\n return np.loadtxt(\"results/\" + name + \"_\" + c + \".txt\").reshape((-1, length))\n return Parallel(n_jobs=-1)([delayed(_component)(n, l, c) for n, l in zip(names, lengths)])\n\ndef _convert_label(truth, predict, N):\n converted_label = np.full_like(truth, N)\n for true_lab in range(N):\n counted = [np.sum(predict[truth == true_lab] == pred) for pred in range(N)]\n pred_lab = np.argmax(counted)\n converted_label[predict == pred_lab] = true_lab\n return converted_label\n\ndef calc_f1_score(truth, predict, N, **kwargs):\n converted_predict = _convert_label(truth, predict, N)\n return f1_score(truth, converted_predict, labels=np.unique(converted_predict), **kwargs )\n\n#%%\nPath(\"figures\").mkdir(exist_ok=True)\nPath(\"summary_files\").mkdir(exist_ok=True)\n\n#%% config parse\nprint(\"Loading model config...\")\nconfig_parser = load_config(hypparams_model)\nsection = config_parser[\"model\"]\ntrain_iter = section[\"train_iter\"]\nword_num = section[\"word_num\"]\nletter_num = section[\"letter_num\"]\nprint(\"Done!\")\n\n#%%\nprint(\"Loading results....\")\nnames = get_names()\ndatas, length = get_datas_and_length(names)\nl_labels = get_letter_labels(names)\nw_labels = get_word_labels(names)\nconcat_l_l = np.concatenate(l_labels, axis=0)\nconcat_w_l = np.concatenate(w_labels, axis=0)\n\nl_results = get_results_of_letter(names, length)\nw_results = get_results_of_word(names, length)\nd_results = get_results_of_duration(names, length)\n\nconcat_l_r = np.concatenate(l_results, axis=1)\nconcat_w_r = np.concatenate(w_results, axis=1)\n\nlog_likelihood = np.loadtxt(\"summary_files/log_likelihood.txt\")\nresample_times = np.loadtxt(\"summary_files/resample_times.txt\")\nprint(\"Done!\")\n\n#%%\nletter_ARI = np.zeros(train_iter)\nletter_macro_f1_score = np.zeros(train_iter)\nletter_micro_f1_score = np.zeros(train_iter)\nword_ARI = np.zeros(train_iter)\nword_macro_f1_score = np.zeros(train_iter)\nword_micro_f1_score = np.zeros(train_iter)\n\n#%% calculate ARI\nprint(\"Calculating ARI...\")\nfor t in trange(train_iter):\n letter_ARI[t] = adjusted_rand_score(concat_l_l, concat_l_r[t])\n letter_macro_f1_score[t] = calc_f1_score(concat_l_l, concat_l_r[t], letter_num, average=\"macro\")\n letter_micro_f1_score[t] = calc_f1_score(concat_l_l, concat_l_r[t], letter_num, average=\"micro\")\n word_ARI[t] = adjusted_rand_score(concat_w_l, concat_w_r[t])\n word_macro_f1_score[t] = calc_f1_score(concat_w_l, concat_w_r[t], word_num, average=\"macro\")\n word_micro_f1_score[t] = calc_f1_score(concat_w_l, concat_w_r[t], word_num, average=\"micro\")\nprint(\"Done!\")\n\n#%% plot ARIs.\nplt.clf()\nplt.title(\"Letter ARI\")\nplt.plot(range(train_iter), letter_ARI, \".-\")\nplt.savefig(\"figures/Letter_ARI.png\")\n\n#%%\nplt.clf()\nplt.title(\"Word ARI\")\nplt.plot(range(train_iter), word_ARI, \".-\")\nplt.savefig(\"figures/Word_ARI.png\")\n\n#%%\nplt.clf()\nplt.title(\"Log likelihood\")\nplt.plot(range(train_iter+1), log_likelihood, \".-\")\nplt.savefig(\"figures/Log_likelihood.png\")\n\n#%%\nplt.clf()\nplt.title(\"Resample times\")\nplt.plot(range(train_iter), resample_times, \".-\")\nplt.savefig(\"figures/Resample_times.png\")\n\n#%%\nnp.savetxt(\"summary_files/Letter_ARI.txt\", letter_ARI)\nnp.savetxt(\"summary_files/Letter_macro_F1_score.txt\", letter_macro_f1_score)\nnp.savetxt(\"summary_files/Letter_micro_F1_score.txt\", letter_micro_f1_score)\nnp.savetxt(\"summary_files/Word_ARI.txt\", word_ARI)\nnp.savetxt(\"summary_files/Word_macro_F1_score.txt\", word_macro_f1_score)\nnp.savetxt(\"summary_files/Word_micro_F1_score.txt\", word_micro_f1_score)\nnp.savetxt(\"summary_files/Sum_of_resample_times.txt\", resample_times.sum())\n" ]
[ [ "numpy.savetxt", "numpy.savez", "numpy.cumsum", "numpy.loadtxt" ], [ "matplotlib.pyplot.title", "numpy.unique", "matplotlib.pyplot.savefig", "numpy.concatenate", "numpy.full_like", "matplotlib.pyplot.clf", "numpy.argmax", "numpy.savetxt", "sklearn.metrics.adjusted_rand_score", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fearaschiarrai/gxpy
[ "4c5e7594b24e530a8cd94df1eef562c5c6ce3e92", "4c5e7594b24e530a8cd94df1eef562c5c6ce3e92", "4c5e7594b24e530a8cd94df1eef562c5c6ce3e92" ]
[ "geosoft/gxpy/tests/test_group.py", "geosoft/gxapi/GXVA.py", "geosoft/gxpy/grid.py" ]
[ "import unittest\nimport os\nimport numpy as np\n\nimport geosoft\nimport geosoft.gxapi as gxapi\nimport geosoft.gxpy.system as gsys\nimport geosoft.gxpy.map as gxmap\nimport geosoft.gxpy.geometry as gxgm\nimport geosoft.gxpy.grid as gxgrd\nimport geosoft.gxpy.agg as gxagg\nimport geosoft.gxpy.system as gxsys\nimport geosoft.gxpy.view as gxv\nimport geosoft.gxpy.group as gxg\nimport geosoft.gxpy.vv as gxvv\nimport geosoft.gxpy.viewer as gxviewer\n\nfrom base import GXPYTest\n\n\ndef rect_line(g, size=100):\n g.rectangle(gxgm.Point2((0, 0, size, size), coordinate_system=\"cm\"), pen=g.new_pen(line_thick=1))\n p1 = gxgm.Point((0.1, 0.1)) * size\n p2 = gxgm.Point((0.9, 0.9)) * size\n poff = gxgm.Point((0.15, 0.05)) * size\n g.rectangle((p1, p2), pen=g.new_pen(fill_color=gxg.C_LT_GREEN))\n p12 = gxgm.Point2((p1 + poff, p2 - poff))\n g.line((p12.p0.x, p12.p0.y, p12.p1.x, p12.p1.y), pen=g.new_pen(line_style=2, line_pitch=2.0))\n\n\ndef pline():\n return gxgm.PPoint([[10, 5],\n [20, 20],\n [30, 15],\n [50, 50],\n [60, 70],\n [75, 35],\n [90, 65],\n [20, 50],\n [35, 18.5]])\n\n\ndef draw_stuff(g, size=1.0):\n plinelist = [[110, 5],\n [120, 20],\n [130, 15],\n [150, 50],\n [160, 70],\n [175, 35],\n [190, 65],\n [220, 50],\n [235, 18.5]]\n\n pp = gxgm.PPoint.from_list(plinelist) * size\n g.pen = g.new_pen(line_style=2, line_pitch=2.0)\n g.polyline(pp)\n g.pen = g.new_pen(line_style=4, line_pitch=2.0, line_smooth=gxg.SMOOTH_AKIMA)\n g.polyline(pp)\n\n ppp = np.array(plinelist)\n pp = gxgm.PPoint(ppp[3:, :]) * size\n g.pen = g.new_pen(line_style=5, line_pitch=5.0,\n line_smooth=gxg.SMOOTH_CUBIC,\n line_color=gxg.C_RED,\n line_thick=0.25,\n fill_color=gxg.C_LT_BLUE)\n g.polygon(pp)\n\n g.pen = g.new_pen(fill_color=gxg.C_LT_GREEN)\n p1 = gxgm.Point((100, 0, 0)) * size\n p2 = gxgm.Point((100, 0, 0)) * size\n pp = (pp - p1) / 2 + p2\n g.polygon(pp)\n pp += gxgm.Point((0, 25, 0)) * size\n g.pen = g.new_pen(fill_color=gxg.C_LT_RED)\n g.polygon(pp)\n\nclass Test(GXPYTest):\n def test_version(self):\n self.start()\n self.assertEqual(gxmap.__version__, geosoft.__version__)\n\n def test_create(self):\n self.start()\n\n def test_lock(self):\n self.start()\n\n with gxmap.Map.new(data_area=(0, 0, 50, 40), coordinate_system='cm') as map:\n with gxv.View.open(map, 'data') as v:\n self.assertFalse(bool(v.lock))\n with gxg.Draw(v, 'rectangle') as g:\n self.assertEqual(str(g), 'rectangle/data')\n self.assertTrue(g.drawing_plane is None)\n self.assertEqual(g.unit_of_measure, '')\n self.assertTrue(bool(v.lock))\n self.assertEqual(v.lock, 'rectangle')\n self.assertRaises(gxg.GroupException, gxg.Group, v)\n self.assertFalse(bool(v.lock))\n\n def test_metadata(self):\n self.start()\n\n with gxmap.Map.new(data_area=(0, 0, 50, 40), coordinate_system='cm') as map:\n with gxv.View.open(map, 'data') as v:\n with gxg.Draw(v, 'rectangle') as g:\n\n self.assertTrue(g.guid)\n meta = g.gx_metadata\n meta.node_token('maki/data/more')\n meta.set_attribute('/maki/data/more/scale', 45)\n meta.set_attribute('/maki/data/more/unit_of_measure', 'cm')\n g.gx_metadata = meta\n g.unit_of_measure = 'billy-bob'\n\n with gxg.Draw(v, 'rectangle') as g:\n meta = g.gx_metadata\n self.assertTrue(meta.has_node('/maki/data'))\n self.assertTrue(meta.has_node('/maki/data/more'))\n self.assertEqual(meta.get_attribute('/maki/data/more/scale'), 45)\n self.assertEqual(meta.get_attribute('/maki/data/more/unit_of_measure'), 'cm')\n self.assertEqual(g.unit_of_measure, 'billy-bob')\n\n\n def test_cs(self):\n self.start()\n\n with gxmap.Map.new(data_area=(0, 0, 50, 40), coordinate_system='cm') as map:\n with gxv.View.open(map, 'data') as v:\n with gxg.Draw(v, 'rectangle') as g:\n self.assertEqual(g.drawing_coordinate_system.unit_of_measure, 'cm')\n g.drawing_coordinate_system = \"NAD83 / UTM zone 15N\"\n self.assertEqual(str(g.drawing_coordinate_system), \"NAD83 / UTM zone 15N\")\n g.drawing_coordinate_system = None\n self.assertEqual(g.drawing_coordinate_system.unit_of_measure, 'cm')\n\n\n def test_extent(self):\n self.start()\n\n map_file = None\n try:\n with gxmap.Map.new(data_area=(3, 2, 50, 40), coordinate_system='cm', overwrite=True) as map:\n map_file = map.file_name\n with gxv.View.open(map, 'data') as v:\n self.assertEqual(v.extent_map_cm(), (2.0, 6.0, 41.6, 38.4))\n with gxg.Draw(v, 'rectangle') as g:\n g.rectangle((3, 2, 28, 20),\n pen=g.new_pen(line_thick=0.25, line_color='R', line_style=gxg.LINE_STYLE_LONG,\n line_pitch=5))\n self.assertEqual(g.extent, (3., 2., 28., 20.))\n self.assertEqual(g.extent_map_cm(), (3.0, 7.0, 23.0, 21.4))\n finally:\n gxmap.delete_files(map_file)\n\n @unittest.skip('skipping to let fixture pass')\n def test_force_assert(self):\n self.start()\n\n with gxmap.Map.figure((0, 0, 1000, 1000)) as gmap:\n with gxv.View.open(gmap, \"data\") as v:\n gxapi.GXMVU.arrow(v.gxview, 500, 500, 450, 450, 0.5, 30, 1) # asserts\n with gxg.Draw(v, \"arrow\") as g:\n gxapi.GXMVU.arrow(g.view.gxview, 500, 500, 450, 450, 0.5, 30, 1)\n\n def test_point(self):\n self.start()\n\n p1 = gxgm.Point((10, 20))\n p2 = gxgm.Point((20, 20))\n p3 = gxgm.Point((30, 20))\n rect = gxgm.Point2((p1 - (15, 15), p3 + (15, 15)))\n\n with gxmap.Map.new(data_area=rect.extent_xy) as gmap:\n map_file = gmap.file_name\n with gxv.View.new(gmap, \"data\") as v:\n with gxg.Draw(v, 'test_point') as g:\n g.pen = gxg.Pen(line_thick=1)\n g.rectangle(rect)\n\n g.pen = gxg.Pen(line_thick=2, line_color='R')\n g.line((p1, p1)) # invisible - zero-length, but we should see it\n\n g.pen = gxg.Pen(line_thick=2, line_color='G')\n g.line((p2, p2 + (0.04, 0))) # invisible - bug\n\n g.pen = gxg.Pen(line_thick=2, line_color='B')\n g.line((p3, p3 + (0.05, 0))) # visible - correct!\n\n self.crc_map(map_file, pix_width=800)\n\n def test_points(self):\n self.start()\n\n plinelist = [[110, 5],\n [120, 20],\n [130, 15],\n [150, 50],\n [160, 70],\n [175, 35],\n [190, 65],\n [220, 50],\n [235, 18.5]]\n\n pp = gxgm.PPoint.from_list(plinelist)\n\n with gxmap.Map.new() as gmap:\n map_file = gmap.file_name\n with gxv.View.new(gmap, \"points\", area=(100, 0, 260, 100)) as v:\n with gxg.Draw(v, 'test_group') as g:\n\n g.rectangle(pp.extent, pen=gxg.Pen(line_thick=1))\n g.pen = gxg.Pen(line_thick=2, line_color='B')\n for p in pp:\n g.point(p)\n\n pp += (15, 15)\n g.pen = gxg.Pen(line_thick=1.5, line_color='G')\n g.polypoint(pp)\n\n pp -= (0, 5)\n g.pen = gxg.Pen(line_thick=1, line_color='R')\n g.polypoint((gxvv.GXvv(pp.x), gxvv.GXvv(pp.y)))\n\n self.crc_map(map_file, pix_width=800)\n\n def test_rectangle(self):\n self.start()\n\n with gxmap.Map.new(data_area=(0, 0, 50, 40), coordinate_system='cm', overwrite=True) as map:\n map_file = map.file_name\n with gxv.View.open(map, 'data') as v:\n with gxg.Draw(v, 'rectangle') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=0.5, line_color='B'))\n g.rectangle((2, 2, 48, 38),\n pen=g.new_pen(line_thick=0.25, line_color='R', line_style=gxg.LINE_STYLE_LONG,\n line_pitch=5))\n\n self.crc_map(map_file)\n\n def test_smooth_line(self):\n self.start()\n\n pp = pline()\n p1, p2 = pp.extent\n area = (p1.x, p1.y, p2.x, p2.y)\n with gxmap.Map.new() as map:\n map_file = map.file_name\n with gxv.View.new(map, 'smooth') as v:\n v.locate(coordinate_system='mm', area=area, map_location=(1,1), scale=0.4)\n with gxg.Draw(v) as g:\n g.rectangle(v.extent_clip)\n g.polyline(pp, pen=g.new_pen(line_smooth=gxg.SMOOTH_AKIMA, line_color='r', line_thick=1))\n g.polyline(pp, pen=g.new_pen(line_smooth=gxg.SMOOTH_CUBIC, line_color='b', line_thick=2))\n g.polyline(pp)\n map.delete_view('data')\n map.delete_view('base')\n self.crc_map(map_file)\n\n def test_view_groups_1(self):\n self.start()\n\n testmap = os.path.join(self.gx.temp_folder(), \"test\")\n with gxmap.Map.new(testmap, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.new(gmap, \"rectangle_test\", area=(0, 0, 250, 125)) as v:\n with gxg.Draw(v, 'test_group') as g:\n rect_line(g)\n g.graticule(25, 20, style=gxg.GRATICULE_LINE)\n g.pen = g.new_pen(line_thick=0.1)\n g.rectangle(((0, 0), (250, 125)), pen=g.new_pen(line_thick=0.1, line_color='R'))\n with gxv.View.new(gmap, \"poly\") as v:\n with gxg.Draw(v) as g:\n draw_stuff(g)\n\n try:\n self.crc_map(map_file)\n finally:\n gxmap.delete_files(map_file)\n\n def test_view_groups_2(self):\n self.start()\n\n testmap = os.path.join(self.gx.temp_folder(), \"test\")\n with gxmap.Map.new(testmap, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.new(gmap, \"rectangle_test\", area=(0, 0, 250, 125)) as v:\n with gxg.Draw(v, 'line') as g:\n rect_line(g)\n with gxg.Draw(v, 'graticule') as g:\n g.graticule(25, 20, style=gxg.GRATICULE_LINE)\n g.pen = g.new_pen(line_thick=0.1)\n with gxg.Draw(v, 'test_rectangles') as g:\n g.rectangle(((0, 0), (250, 125)), pen=g.new_pen(line_thick=0.1, line_color='R'))\n g.rectangle(((10, 5), (240, 120)), pen=g.new_pen(line_thick=2, line_color='B'))\n v.delete_group('graticule')\n with gxv.View.new(gmap, \"poly\") as v:\n with gxg.Draw(v, 'test_group') as g:\n draw_stuff(g)\n\n try:\n self.crc_map(map_file)\n finally:\n gxmap.delete_files(map_file)\n\n def test_reopen_map_view(self):\n self.start()\n\n testmap = os.path.join(self.gx.temp_folder(), \"test\")\n with gxmap.Map.new(testmap, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.new(gmap, \"test_view\") as v:\n with gxg.Draw(v) as g:\n rect_line(g)\n with gxv.View.open(gmap, \"test_view\") as v:\n pass\n gxmap.delete_files(map_file)\n\n def test_3D(self):\n self.start()\n\n testmap = os.path.join(self.gx.temp_folder(), \"test.map\")\n with gxmap.Map.new(testmap, overwrite=True) as gmap:\n with gxv.View.open(gmap, \"base\") as view_base:\n with gxg.Draw(view_base, 'Surround') as g:\n g.rectangle(((0, 0), (280, 260)))\n\n test3dv = os.path.join(self.gx.temp_folder(), \"test.geosoft_3dv\")\n with gxv.View_3d.new(test3dv, overwrite=True) as view_3d:\n self.assertTrue(view_3d.extent == None)\n\n with gxg.Draw(view_3d, '2d_group') as g:\n rect_line(g)\n draw_stuff(g)\n\n with gxg.Draw_3d(view_3d, '3d_group_cylinders') as g:\n self.assertEqual(g.render_backfaces, False)\n g.cylinder_3d(((100, 10, 10), (120, 10, 10)), 8, pen='r', close=gxg.CYLINDER_CLOSE_ALL)\n self.assertEqual(view_3d.extent_xyz, (92.0, 2.0, 2.0, 128.0, 18.0, 18.0))\n g.cylinder_3d(((100, 10, 70), (120, 10, 70)), 8, pen='c', close=gxg.CYLINDER_OPEN)\n self.assertEqual(view_3d.extent_xyz, (92.0, 2.0, 2.0, 128.0, 18.0, 78.0))\n g.cylinder_3d(((100, 10, 50), (120, 10, 50)), 8, pen='b', close=gxg.CYLINDER_CLOSE_END)\n g.cylinder_3d(((100, 10, 30), (120, 10, 30)), 8, pen='g', close=gxg.CYLINDER_CLOSE_START)\n self.assertEqual(view_3d.extent_xyz, (92.0, 2.0, 2.0, 128.0, 18.0, 78.0))\n self.assertEqual(g.render_backfaces, True)\n\n with gxg.Draw_3d(view_3d, '3d_group') as g:\n g.cylinder_3d(((20, 10, 60), (80, 50, 80)), 5, pen='b')\n g.cone_3d(((20, 10, 80), (80, 50, 60)), 8, pen='g')\n g.cone_3d(((20, 50, 65), (20, 50, 40)), 30, pen='r')\n g.sphere((20, 50, 80), 10, pen='c')\n self.assertEqual(g.render_backfaces, False)\n g.cylinder_3d(((80, 10, 0), (80, 10, 80)), 5, pen='y', close=gxg.CYLINDER_OPEN)\n self.assertEqual(g.render_backfaces, True)\n g.box_3d(((20, 10, 30), (80, 50, 50)), pen=g.new_pen(line_color='R255G100B50'))\n g.box_3d(((80, 50, 50), (90,60, 65)), wireframe=True,\n pen=g.new_pen(line_color='R25G255B50', line_thick=2))\n\n with gxmap.Map.open(testmap) as gmap:\n gmap.create_linked_3d_view(view_3d, area_on_map=(10, 10, 270, 250))\n\n # test re-open a 3D view, with explicit close\n view_3d = gxv.View_3d.open(test3dv)\n group_list = view_3d.group_list\n self.assertEqual(len(group_list), 3)\n view_3d.close()\n\n self.crc_map(test3dv, alt_crc_name=gxsys.func_name() + '_3dv')\n self.crc_map(testmap, alt_crc_name=gxsys.func_name() + '_map')\n\n def test_basic_grid_1(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n with gxmap.Map.new(map_file,\n data_area=area, media=\"A4\", margins=(0, 10, 0, 0),\n coordinate_system=cs, overwrite=True) as gmap:\n map_file = gmap.file_name\n\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='R'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n with gxg.Aggregate_group.new(v, agg) as gagg:\n self.assertEqual(gagg.name, str(agg))\n\n self.assertEqual(len(v.group_list_agg), 1)\n\n self.crc_map(map_file)\n\n def test_basic_grid_3D(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n with gxv.View_3d.new() as v:\n v3d_file = v.file_name\n with gxg.Draw(v, 'line') as g:\n self.assertEqual(g.drawing_plane, 'Plane')\n self.assertEqual(str(g), 'line/Plane/uuid_test_basic_grid_3D_1')\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='R'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n with gxg.Aggregate_group.new(v, agg) as gagg:\n self.assertEqual(str(gagg), agg.name + '/Plane/uuid_test_basic_grid_3D_1')\n\n self.assertEqual(len(v.group_list_agg), 1)\n\n self.crc_map(v3d_file)\n\n\n def test_basic_grid_2(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n with gxmap.Map.new(map_file,\n data_area=area, media=\"A3\", margins=(0, 0, 0, 0),\n scale=(area[2] - area[0]) / 0.2,\n coordinate_system=cs, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=2, line_color='K'))\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='G'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n gxg.Aggregate_group.new(v, agg)\n\n self.crc_map(map_file)\n\n def test_zone_grid(self):\n self.start()\n\n def test_zone(zone, suffix, shade=False):\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_\" + suffix)\n with gxmap.Map.new(map_file, overwrite=True,\n data_area=(ex[0], ex[1], ex[2], ex[3]),\n scale=(ex[2] - ex[0]) / 0.2) as gmap:\n map_file = gmap.file_name\n with gxv.View.open(gmap, \"data\") as v:\n with gxagg.Aggregate_image.new(grid_file, zone=zone, shade=shade) as agg:\n gxg.Aggregate_group.new(v, agg)\n gmap.delete_view('base')\n\n self.crc_map(map_file, alt_crc_name='{}_{}'.format(gxsys.func_name(1), suffix))\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n\n with gxgrd.Grid(os.path.join(folder, 'test_agg_utm.grd')) as grd:\n ex = grd.extent_2d()\n grid_file = 'test_zone'\n gxgrd.delete_files(grid_file)\n with gxgrd.Grid.copy(grd, grid_file) as test:\n grid_file = test.file_name\n\n try:\n test_zone(gxagg.ZONE_LINEAR, \"linear_shade\", shade=True)\n test_zone(gxagg.ZONE_EQUALAREA, \"eq_area\")\n test_zone(gxagg.ZONE_DEFAULT, \"default\")\n test_zone(gxagg.ZONE_LAST, \"last\")\n test_zone(gxagg.ZONE_LINEAR, \"linear\")\n test_zone(gxagg.ZONE_NORMAL, \"normal\")\n test_zone(gxagg.ZONE_SHADE, \"shade\")\n test_zone(gxagg.ZONE_LOGLINEAR, \"log_linear\")\n\n finally:\n gxgrd.delete_files(grid_file)\n\n def test_text_definition(self):\n self.start()\n\n t = gxg.Text_def()\n self.assertEqual(t.slant, 0)\n self.assertEqual(t.height, 0.25)\n self.assertEqual(t.weight, gxg.FONT_WEIGHT_MEDIUM)\n self.assertEqual(t.font, 'DEFAULT')\n t.font = \"Arial\"\n self.assertEqual(t.font, 'Arial')\n self.assertEqual(t.mapplot_string, '0.25,,,0,\"Arial(TT)\"')\n t.font = 'sr.gfn'\n self.assertEqual(t.mapplot_string, '0.25,,,0,\"sr\"')\n t.font = ''\n self.assertEqual(t.mapplot_string, '0.25,,,0,\"DEFAULT\"')\n t.italics = True\n self.assertTrue(t.italics)\n self.assertEqual(t.slant, 15)\n t.italics = 0\n self.assertFalse(t.italics)\n self.assertEqual(t.slant, 0)\n\n t.weight = gxg.FONT_WEIGHT_ULTRALIGHT\n self.assertAlmostEqual(t.line_thick, 0.005208333333333333)\n t.weight = gxg.FONT_WEIGHT_BOLD\n self.assertAlmostEqual(t.line_thick, 0.020833333333333331)\n thick = t.line_thick\n t.weight = gxg.FONT_WEIGHT_XXBOLD\n self.assertAlmostEqual(t.line_thick, 0.0625)\n t.line_thick = thick\n self.assertEqual(t.weight, gxg.FONT_WEIGHT_BOLD)\n t.height = 10.\n self.assertEqual(t.weight, gxg.FONT_WEIGHT_BOLD)\n self.assertAlmostEqual(t.line_thick, 0.8333333333333333)\n t.line_thick = t.line_thick\n self.assertEqual(t.weight, gxg.FONT_WEIGHT_BOLD)\n\n def test_colours(self):\n self.start()\n\n c = gxg.Color((150, 200, 500))\n self.assertEqual(c.rgb, (150, 200, 255))\n c = gxg.Color((150, 200, 500), model=gxg.CMODEL_CMY)\n self.assertEqual(c.cmy, (150, 200, 255))\n\n c = gxg.Color('r255g128b56')\n self.assertEqual(c.rgb, (255, 128, 56))\n self.assertEqual(c.cmy, (0, 127, 199))\n c.rgb = (64, 32, 16)\n self.assertEqual(c.rgb, (64, 32, 16))\n c.cmy = (100, 200, 300)\n self.assertEqual(c.cmy, (100, 200, 255))\n\n c = gxg.Color((0, 127, 64), gxg.CMODEL_HSV)\n self.assertEqual(c.rgb, (191, 96, 96))\n\n c = gxg.Color((0, 127, 64), gxg.CMODEL_RGB)\n self.assertEqual(c.rgb, (0, 127, 64))\n\n\n c = gxg.Color(gxg.C_GREEN)\n self.assertEqual(c.rgb, (0, 255, 0))\n\n c2 = gxg.Color(c)\n self.assertEqual(c2.rgb, (0, 255, 0))\n\n c = gxg.Color(gxg.C_TRANSPARENT)\n self.assertEqual(c.rgb, None)\n self.assertEqual(c.cmy, None)\n self.assertTrue(c == gxg.Color(gxg.C_TRANSPARENT))\n\n def test_pen(self):\n self.start()\n\n p = gxg.Pen()\n self.assertEqual(p.line_color.int_value, gxg.C_BLACK)\n self.assertEqual(p.fill_color.int_value, gxg.C_TRANSPARENT)\n self.assertEqual(p.line_style, gxg.LINE_STYLE_SOLID)\n\n p.line_color = (255, 127, 64)\n self.assertEqual(p.mapplot_string, 'r255g127b64t10')\n\n p2 = gxg.Pen(line_color = (255, 127, 64))\n self.assertTrue(p == p2)\n p2.line_color = 'K'\n self.assertFalse(p == p2)\n\n p = gxg.Pen.from_mapplot_string('r20b100k16R64K16')\n ms = p.mapplot_string\n self.assertEqual(ms, 'r4g0b84R48G0B0t1')\n p = gxg.Pen.from_mapplot_string(ms)\n self.assertEqual(p.mapplot_string, ms)\n\n p = gxg.Pen.from_mapplot_string('c64K64')\n self.assertEqual(p.line_color.rgb, (191, 255, 255))\n self.assertEqual(p.fill_color.rgb, (191, 191, 191))\n\n p = gxg.Pen(line_color='K')\n self.assertEqual(p.line_color.int_value, gxg.C_BLACK)\n self.assertTrue(p.line_color == gxg.Color(gxg.C_BLACK))\n\n p = gxg.Pen(line_color=gxg.C_WHITE)\n self.assertEqual(p.line_color.int_value, gxg.C_WHITE)\n self.assertTrue(p.line_color == gxg.Color(gxg.C_WHITE))\n\n p = gxg.Pen.from_mapplot_string('r20b100k16R64K16')\n p = gxg.Pen(default=p, line_thick=0.5, fill_color='K')\n ms = p.mapplot_string\n self.assertEqual(ms, 'r4g0b84R0G0B0t500')\n p = gxg.Pen.from_mapplot_string(ms)\n self.assertEqual(p.mapplot_string, ms)\n\n self.assertRaises(gxg.GroupException, gxg.Pen, bad=1)\n\n def test_scaled(self):\n self.start()\n\n p = gxg.Pen(factor=10)\n self.assertEqual(p.line_thick, 0.1)\n self.assertEqual(p.line_pitch, 5.0)\n self.assertEqual(p.pat_thick, 0.1)\n self.assertEqual(p.pat_size, 10.0)\n\n p = gxg.Pen(default=p, factor=5)\n self.assertEqual(p.line_thick, 0.5)\n self.assertEqual(p.line_pitch, 25.0)\n self.assertEqual(p.pat_thick, 0.5)\n self.assertEqual(p.pat_size, 50.0)\n\n t = gxg.Text_def(factor=0.2)\n self.assertEqual(t.height, 0.05)\n\n def test_text(self):\n self.start()\n\n with gxmap.Map.new(data_area=(400000, 5000000, 500000, 5150000),\n coordinate_system='WGS 84 / UTM zone 15N [geoid]') as map:\n map_file = map.file_name\n with gxv.View.open(map, 'base') as v:\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n g.text('Text on base view')\n g.text('Bigger, blue, higher',\n (v.units_per_map_cm, v.units_per_map_cm),\n text_def=gxg.Text_def(height=20, color='B', font='Times New Roman'))\n g.text('Bigger, blue, angled, italics',\n (10, 25),\n angle=60,\n text_def=gxg.Text_def(height=20, color='B', font='Calibri', italics=True))\n g.text_def = gxg.Text_def(height=20, color='B', font='Calibri', italics=True)\n tex = g.text_extent('Bigger, blue, angled, italics')\n self.assertAlmostEqual(209.9629, tex.dimension_xy[0], 3)\n self.assertAlmostEqual(334.6408, tex.dimension_xy[1], 3)\n tex = g.text_extent('Bigger, blue, angled, italics',\n gxg.Text_def(height=10, font='Calibri', italics=True))\n self.assertAlmostEqual(104.98147, tex.dimension_xy[0], 3)\n self.assertAlmostEqual(167.32042, tex.dimension_xy[1], 3)\n\n self.crc_map(map_file)\n\n def test_text_1(self):\n self.start()\n\n with gxmap.Map.new(data_area=(400000, 5000000, 500000, 5050000),\n coordinate_system='WGS 84 / UTM zone 15N [geoid]') as map:\n map_file = map.file_name\n with gxv.View.open(map, '*data') as v:\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n ex = g.extent\n width = ex[2] - ex[0]\n height = ex[3] - ex[1]\n cxy = (ex[0] + width / 2, ex[1] + height / 2)\n td = gxg.Text_def(height=width / 20, color='K128', font='sr.gfn', weight=gxg.FONT_WEIGHT_XBOLD)\n self.assertTrue(td == gxg.Text_def(height=width / 20, color='K128', font='sr.gfn', weight=gxg.FONT_WEIGHT_XBOLD))\n self.assertEqual(td.mapplot_string, '5227.3,,,0,\"sr\"')\n g.rectangle(ex)\n g.line((ex[0], cxy[1], ex[2], cxy[1]))\n g.line((cxy[0], ex[1], cxy[0], ex[3]))\n g.text('Centered',\n cxy,\n text_def=td,\n reference=gxg.REF_CENTER)\n g.text('Bottom',\n (cxy[0], ex[1]),\n text_def=td,\n reference=gxg.REF_BOTTOM_CENTER)\n g.text('Top',\n (cxy[0], ex[3]),\n text_def=td,\n reference=gxg.REF_TOP_CENTER)\n g.text('Left',\n (ex[0], cxy[1]),\n text_def=td,\n angle=90,\n reference=gxg.REF_TOP_CENTER)\n g.text('Right',\n (ex[2], cxy[1]),\n text_def=td,\n angle=-90,\n reference=gxg.REF_TOP_CENTER)\n\n self.crc_map(map_file)\n\n def test_text_multiline(self):\n self.start()\n\n with gxmap.Map.new(data_area=(400000, 5000000, 500000, 5050000),\n coordinate_system='WGS 84 / UTM zone 15N [geoid]') as map:\n map_file = map.file_name\n with gxv.View.open(map, '*data') as v:\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n ex = v.extent_clip\n width = ex[2] - ex[0]\n height = ex[3] - ex[1]\n cxy = (ex[0] + width / 2, ex[1] + height / 2)\n td = gxg.Text_def(height=width / 20, color='K128', font='sr.gfn', weight=gxg.FONT_WEIGHT_XBOLD)\n g.rectangle(ex)\n g.line((ex[0], cxy[1], ex[2], cxy[1]))\n g.line((cxy[0], ex[1], cxy[0], ex[3]))\n g.text('Centered\\nline2\\nand another',\n cxy,\n text_def=td,\n reference=gxg.REF_CENTER)\n\n self.crc_map(map_file)\n\n def test_locate_group(self):\n self.start()\n\n with gxmap.Map.new(data_area=(400000, 5000000, 500000, 5050000),\n coordinate_system='WGS 84 / UTM zone 15N [geoid]') as map:\n map_file = map.file_name\n with gxv.View.open(map, '*data') as v:\n with gxg.Draw(v) as g:\n g.rectangle(v.extent_clip)\n rect = gxgm.Point2((v.extent_clip[0], v.extent_clip[1],\n (v.extent_clip[2] + v.extent_clip[0]) * 0.5,\n (v.extent_clip[3] + v.extent_clip[1]) * 0.5))\n with gxg.Draw(v, 'a') as g:\n g.rectangle(rect)\n with gxg.Draw(v, 'b') as g:\n self.assertEqual(g.number, 2)\n g.rectangle(rect, pen=\"b\")\n g.locate((450000, 5025000),\n reference=gxg.REF_TOP_CENTER)\n\n self.crc_map(map_file)\n\n def test_color_bar(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid.open(grid_file, mode=gxgrd.FILE_READWRITE) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n grd.unit_of_measure = 'maki'\n\n with gxmap.Map.new(map_file, fixed_size=False,\n data_area=area, media=\"A4\", margins=(7, 7, 2.5, 2.5),\n coordinate_system=cs, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=0.1, line_color='G'))\n g.rectangle(v.extent_all, pen=g.new_pen(line_thick=0.1, line_color='B'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n self.assertEqual(agg.layer_unit_of_measure(0), 'maki')\n self.assertEqual(agg.layer_unit_of_measure(agg.layer_file_names[0]), 'maki')\n self.assertEqual(agg.layer_color_map(0).unit_of_measure, 'maki')\n\n gxg.legend_color_bar(v, 'color_legend', agg.layer_color_map())\n gxg.legend_color_bar(v, 'color_legend', agg.layer_color_map(),\n bar_location=gxg.COLOR_BAR_LEFT)\n\n gxg.legend_color_bar(v, 'bottom', agg.layer_color_map(),\n bar_location=gxg.COLOR_BAR_BOTTOM,\n box_size=0.5,\n location=(1, -0.1),\n annotation_offset=0.1)\n\n gxg.legend_color_bar(v, 'top', agg.layer_color_map(),\n bar_location=gxg.COLOR_BAR_TOP,\n box_size=0.5,\n bar_width=0.1,\n location=0.5,\n interval_1 = 50,\n annotation_offset=0.1)\n\n self.crc_map(map_file)\n\n def test_color_bar_existing_agg(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n with gxmap.Map.new(map_file, fixed_size=False,\n data_area=area, media=\"A4\", margins=(2, 10, 2, 1),\n coordinate_system=cs, overwrite=True) as gmap:\n map_file = gmap.file_name\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=0.1, line_color='G'))\n g.rectangle(v.extent_all, pen=g.new_pen(line_thick=0.1, line_color='B'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n with gxg.Aggregate_group.new(v, agg) as g:\n agg_group_name = g.name\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Aggregate_group.open(v, agg_group_name) as g:\n gxg.legend_color_bar(v, 'color_legend', g.agg.layer_color_map())\n\n\n self.crc_map(map_file)\n\n def test_properties(self):\n self.start()\n\n with gxmap.Map.new() as map:\n with gxv.View.open(map, \"base\") as v:\n with gxg.Draw(v, 'edge') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n with gxv.View.open(map, \"data\") as v:\n with gxg.Draw(v, 'edge') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='B'))\n self.assertTrue(g.visible)\n g.visible = False\n self.assertFalse(g.visible)\n\n def test_graticule(self):\n self.start()\n\n test_map = os.path.join(self.gx.temp_folder(), \"test\")\n with gxmap.Map.new(test_map, overwrite=True) as map:\n map_file = map.file_name\n map.delete_view('data')\n\n with gxv.View.new(map, \"my_data_1\", map_location=(2, 3), area=(0, 0, 1000, 1500), scale=10000) as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip,\n pen=g.new_pen(line_thick=5, line_color='G'))\n\n g.graticule(style=gxg.GRATICULE_LINE, pen=g.new_pen(line_thick=5))\n ex1 = v.extent_group('line', unit=gxv.UNIT_MAP)\n\n with gxv.View.new(map, \"my_data_2\", map_location=(15, 3), area=(0, 0, 1000, 1500), scale=10000) as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip,\n pen=g.new_pen(line_thick=5, line_color='G'))\n\n g.graticule(style=gxg.GRATICULE_DOT, pen=g.new_pen(line_thick=5))\n ex2 = v.extent_group('line', unit=gxv.UNIT_MAP)\n\n with gxv.View.new(map, \"my_data_3\", map_location=(28, 3), area=(0, 0, 1000, 1500), scale=10000) as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip,\n pen=g.new_pen(line_thick=5, line_color='G'))\n\n g.graticule(style=gxg.GRATICULE_CROSS, pen=g.new_pen(line_thick=5))\n ex3 = v.extent_group('line', unit=gxv.UNIT_MAP)\n\n area = (min(ex1[0], ex2[0], ex3[0])/10.0 - 2, max(ex1[1], ex2[1], ex3[1])/10.0 - 2,\n max(ex1[2], ex2[2], ex3[2])/10.0 + 2, max(ex1[3], ex2[3], ex3[3])/10.0 + 2)\n with gxv.View.new(map, \"my_base_view\", area=area, scale=100.0) as v:\n with gxg.Draw(v, 'base_edge') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=0.1, line_color='R'))\n map.delete_view('base')\n\n self.crc_map(map_file)\n\n def test_ppoint_3d(self):\n self.start()\n \n plist = [[110, 5, 0],\n [120, 20, 10],\n [130, 15, 50],\n [150, 50, 20],\n [160, 70, 0],\n [175, 35, 30],\n [190, 65, 80],\n [220, 50, 90],\n [235, 18.5, 100]]\n pp = gxgm.PPoint(plist)\n with gxv.View_3d.new(gxsys.func_name(), overwrite=True) as v:\n file_name = v.file_name\n with gxg.Draw_3d(v) as g:\n g.pen = gxg.Pen(line_color='R')\n g.polypoint_3d(pp)\n pp += (0, 0, 20)\n g.polypoint_3d(pp, style=gxg.POINT_STYLE_SPHERE, pen=gxg.Pen(line_color='G', line_thick=5))\n\n try:\n self.crc_map(file_name)\n finally:\n gxmap.delete_files(file_name)\n\n def test_pp_3d(self):\n self.start()\n\n plist = [[110, 5, 0],\n [120, 20, 10],\n [130, 15, 50],\n [150, 50, 20],\n [160, 70, 0],\n [175, 35, 30],\n [190, 65, 80],\n [220, 50, 90],\n [235, 18.5, 100]]\n with gxv.View_3d.new(gxsys.func_name(), overwrite=True) as v:\n file_name = v.file_name\n with gxg.Draw_3d(v) as g:\n pp = gxgm.PPoint(plist)\n\n g.pen = gxg.Pen(line_color='R')\n g.polypoint_3d(pp)\n\n pp += (0, 0, 10)\n g.polypoint_3d(pp, style=gxg.POINT_STYLE_SPHERE, pen=gxg.Pen(line_color='G', line_thick=4))\n\n pp += (0, 0, 10)\n g.pen = gxg.Pen(line_color='R')\n g.polyline_3d(pp)\n\n pp += (0, 0, 10)\n g.pen = gxg.Pen(line_color='C', line_thick=3)\n g.polyline_3d(pp, style=gxg.LINE3D_STYLE_TUBE)\n\n pp += (0, 0, 10)\n g.polyline_3d(pp, style=gxg.LINE3D_STYLE_TUBE_JOINED, pen=gxg.Pen(line_color='K64', line_thick=4))\n\n try:\n self.crc_map(file_name)\n finally:\n gxmap.delete_files(file_name)\n\n def test_color_map(self):\n self.start()\n\n cm = gxg.Color_map()\n self.assertEqual(cm.length, 39)\n self.assertFalse(cm.initialized)\n\n cm = gxg.Color_map(16)\n self.assertEqual(cm.length, 16)\n self.assertEqual(cm[0][1], gxg.Color(gxg.C_BLACK))\n self.assertEqual(cm[cm.length-1], (None, gxg.Color(gxg.C_BLACK)))\n cm[4] = (cm[4][0], gxg.Color(gxg.C_GREEN))\n self.assertEqual(cm[4][1].rgb, (0, 255, 0))\n self.assertFalse(cm.initialized)\n\n self.assertTrue(isinstance(cm.gxitr, gxapi.GXITR))\n\n cm = gxg.Color_map('grey')\n self.assertFalse(cm.initialized)\n cm.set_sequential()\n self.assertTrue(cm.initialized)\n self.assertEqual(cm.length, 32)\n self.assertEqual(cm[0][1].rgb, (31, 31, 31))\n self.assertEqual(cm[cm.length-1][1].rgb, (255, 255, 255))\n self.assertEqual(cm.color_of_value(0), cm[0][1])\n self.assertEqual(cm.color_of_value(7.0), cm[7][1])\n self.assertEqual(cm.color_of_value(7.000001), cm[8][1])\n\n self.assertEqual(cm.brightness, 0.)\n cm.brightness = 0.5\n self.assertEqual(cm.brightness, 0.5)\n self.assertEqual(cm[0][1].rgb, (143, 143, 143))\n self.assertEqual(cm[cm.length - 1][1].rgb, (255, 255, 255))\n cm.brightness = -0.25\n self.assertEqual(cm.brightness, -0.25)\n self.assertEqual(cm[0][1].rgb, (24, 24, 24))\n self.assertEqual(cm[cm.length - 1][1].rgb, (192, 192, 192))\n cm.brightness = 0\n self.assertEqual(cm[0][1].rgb, (31, 31, 31))\n self.assertEqual(cm[cm.length - 1][1].rgb, (255, 255, 255))\n\n cm.set_linear(4, 45)\n self.assertEqual(cm.length, 32)\n self.assertEqual(cm[0][0], 4)\n self.assertEqual(cm[30][0], 45)\n\n cm.set_linear(4, 45, inner_limits=False)\n self.assertEqual(cm.length, 32)\n self.assertEqual(cm[0][0], 5.28125)\n self.assertEqual(cm[30][0], 43.71875)\n\n cm.set_linear(5, 50, contour_interval=5)\n self.assertEqual(cm.length, 11)\n\n cm = gxg.Color_map('grey')\n cm.set_logarithmic(0.0001,1000)\n self.assertEqual(cm.length, 32)\n cm.set_logarithmic(0.0001,1000, contour_interval=10)\n self.assertEqual(cm.length, 7)\n cm = gxg.Color_map('grey')\n cm.set_logarithmic(0.000023,18000, contour_interval=100)\n self.assertEqual(cm.length, 5)\n\n cm = gxg.Color_map()\n cm.set_normal(25, 55000)\n self.assertAlmostEqual(cm[cm.length//2][0], 55000.811582690316)\n\n itr = cm.save_file()\n cm2 = gxg.Color_map(itr)\n self.assertTrue(cm == cm2)\n tbl = gxg.Color_map().save_file()\n self.assertEqual(os.path.splitext(tbl)[1], '.tbl')\n cm = gxg.Color_map(tbl)\n self.assertFalse(cm.initialized)\n\n def test_color_symbols(self):\n self.start()\n\n data = [((0, 0), 1),\n ((10, 0), 2),\n ((0, 10), 3),\n ((10, 10), 4)]\n data2 = [((0, 0, 45), 1, 4),\n ((10, 0, 8), None, None),\n ((0, 10, 16), 3, 75),\n ((None, 10, -22), 4, 7)]\n\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n\n with gxmap.Map.new(data_area=(-1, -1, 11, 11), scale=100) as map:\n map_file = map.file_name\n with gxv.View.open(map, '*data') as v:\n\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n\n gxg.Color_symbols_group.new(v, 'outer_symbols', data, cmap, unit_of_measure='maki').close()\n with gxg.Color_symbols_group.open(v, 'outer_symbols') as cs:\n cm = cs.color_map()\n self.assertEqual(cm.unit_of_measure, 'maki')\n self.assertEqual(cm.unit_of_measure, cs.unit_of_measure)\n\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n with gxg.Color_symbols_group.new(v, 'mark', data2, cmap,\n symbol=gxg.SYMBOL_BOX,\n symbol_def=gxg.Text_def(font='symbols.gfn',\n height=0.15,\n color=gxg.C_WHITE,\n weight=gxg.FONT_WEIGHT_ULTRALIGHT)) as cs:\n nv = cs.name\n\n with gxg.Color_symbols_group.open(v, nv) as cs:\n gxg.legend_color_bar(v, 'symbol_legend', cs.color_map())\n\n self.crc_map(map_file)\n\n def test_color_symbols_from_array(self):\n self.start()\n\n data = [(0, 0, 1),\n (10, 0, 2),\n (0, 10, 3),\n (10, 10, 4)]\n\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n\n with gxmap.Map.new(data_area=(-1, -1, 11, 11), scale=100) as map:\n map_file = map.file_name\n with gxv.View.open(map, '*data') as v:\n\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n\n gxg.Color_symbols_group.new(v, 'outer_symbols',\n np.array(data), cmap,\n unit_of_measure='maki').close()\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n\n self.crc_map(map_file)\n\n\n def test_color_symbols_3d(self):\n self.start()\n\n data = [((0, 0), 1),\n ((10, 0), 2),\n ((0, 10), 3),\n ((10, 10), 4)]\n data2 = [((0, 0, 45), 1, 4),\n ((10, 0, 8), None, None),\n ((0, 10, 16), 3, 75),\n ((None, 10, -22), 4, 7)]\n\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n\n with gxv.View_3d.new() as v:\n v3d_file = v.file_name\n with gxg.Draw(v) as g:\n g.rectangle(g.extent)\n\n gxg.Color_symbols_group.new(v, 'outer_symbols', data, cmap, unit_of_measure='maki').close()\n cmap = gxg.Color_map('hotcycle')\n cmap.set_linear(0, 5, contour_interval=1)\n with gxg.Color_symbols_group.new(v, 'mark', data2, cmap,\n symbol=gxg.SYMBOL_BOX,\n symbol_def=gxg.Text_def(font='symbols.gfn',\n height=0.15,\n color=gxg.C_WHITE,\n weight=gxg.FONT_WEIGHT_ULTRALIGHT)) as cs:\n nv = cs.name\n\n with gxg.Color_symbols_group.open(v, nv) as cs:\n self.assertEqual(cs.number, 2)\n\n self.crc_map(v3d_file)\n\n def test_polydata_3d(self):\n self.start()\n\n def render_spheres(item, cmap_radius):\n xyz, value = item\n if None in xyz or value is None:\n return None\n cmap, radius = cmap_radius\n cint = cmap.color_of_value(value)\n return gxg.SYMBOL_3D_SPHERE, xyz, cint.int_value, radius\n\n def render_cubes(point, size_color):\n size, cint = size_color\n half = size * 0.5\n p2 = gxgm.Point2((point - (half, half, half), point + (half, half, half)))\n return gxg.SYMBOL_3D_CUBE, p2, cint, None\n\n def render_cylinders(point, size_color):\n size, cint = size_color\n half = size * 0.2\n p2 = gxgm.Point2((point - (half, half, half), point + (half, half, half)))\n return gxg.SYMBOL_3D_CYLINDER, p2, cint, size * 0.4\n\n def render_cones(point, size_color):\n size, cint = size_color\n half = size * 0.5\n p2 = gxgm.Point2((point - (half, half, half), point + (half, half, half)))\n return gxg.SYMBOL_3D_CONE, p2, cint, size * 0.2\n\n data = [((0, 0, 0), 1),\n ((10, 0, 5), 2),\n ((0, 10, -5), 3),\n ((0, None, -5), 99),\n ((0, 10, -5), None),\n ((10, 10, 10), 4)]\n\n cmap = gxg.Color_map()\n cmap.set_linear(0, 5, contour_interval=1)\n for c in cmap:\n if c[0]:\n self.assertTrue(isinstance(c[0], float))\n self.assertTrue(isinstance(c[1], gxg.Color))\n\n with gxv.View_3d.new(area_2d=(-1, -1, 11, 11)) as v:\n v3d_file = v.file_name\n\n with gxg.Draw(v, 'rect') as g:\n g.rectangle((0,0,10,10),\n pen=gxg.Pen(line_color=gxg.C_BLACK,\n line_thick=0.2,\n fill_color=gxg.C_GREEN))\n\n with gxg.Draw_3d(v, 'pipes') as g:\n g.polyline_3d(((0,0,0), (10,0,0), (10,10,0), (0,10,0), (0,0,0)),\n style=gxg.LINE3D_STYLE_TUBE_JOINED,\n pen=gxg.Pen(line_color=gxg.C_GREY,\n line_thick=0.2))\n\n with gxg.Draw_3d(v, 'outer') as g:\n g.polydata_3d(data, render_spheres, (cmap, 0.25))\n \n pp = gxgm.PPoint(((5, 5, 5), (7, 5, 5), (7, 7, 7)))\n g.polydata_3d(pp, render_cubes, (1, gxg.Color('y').int_value))\n\n pp += (0, 0, 2)\n g.polydata_3d(pp, render_cylinders, (1, gxg.Color('m').int_value))\n\n pp += (0, 0, 2)\n n = 0\n g.polydata_3d(pp, render_cones, (1, gxg.Color('r255g128b128').int_value))\n\n self.crc_map(v3d_file)\n\n def test_polydata_3d_grd(self):\n self.start()\n\n def render_spheres(item, cmap_radius):\n cmap, radius = cmap_radius\n if not np.isnan(item[2]):\n cint = cmap.color_of_value(item[2]).int_value\n return gxg.SYMBOL_3D_SPHERE, item, cint, radius\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'dem_small.grd')\n\n with gxgrd.Grid.open(grid_file) as grd:\n\n # get the data and replace z with DEM valie\n data = grd.xyzv().reshape(-1, 4)\n data[:, 2] = data[:, 3] * 3\n data = data[:, 0:3]\n\n cmap = gxg.Color_map()\n try:\n std = np.nanstd(data[:, 2])\n mean = np.nanmean(data[:, 2])\n cmap.set_normal(std, mean)\n except:\n cmap.set_linear(0, 1)\n\n with gxv.View_3d.new(coordinate_system=grd.coordinate_system) as v:\n v3d_file = v.file_name\n with gxg.Draw_3d(v, 'dem_points') as g:\n g.polydata_3d(data.reshape((-1, 3)), render_spheres, (cmap, 10 * v.units_per_map_cm))\n p_min = gxgm.Point((np.nanmin(data[:, 0]), np.nanmin(data[:, 1]), np.nanmin(data[:, 2])))\n p_max = gxgm.Point((np.nanmax(data[:, 0]), np.nanmax(data[:, 1]), np.nanmax(data[:, 2])))\n extent = gxgm.Point2((p_min, p_max))\n g.box_3d(extent,\n wireframe=True,\n pen=gxg.Pen(line_color='c', line_thick= 20 * v.units_per_map_cm))\n\n self.crc_map(v3d_file)\n\n def test_plane_relief_surface(self):\n self.start()\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'dem_small.grd')\n\n v3d_name = ''\n try:\n # create a 3D view\n with gxv.View_3d.new(\"data\",\n area_2d=gxgrd.Grid(grid_file).extent_2d(),\n coordinate_system=gxgrd.Grid(grid_file).coordinate_system,\n scale=5000,\n overwrite=True) as v:\n v3d_name = v.file_name\n\n v.set_plane_relief_surface(grid_file, base=200, scale=2, max=250, min=150, refine=2)\n\n # add the grid image to the view, with shading, 20 nT contour interval to match default contour lines\n gxg.Aggregate_group.new(v, gxagg.Aggregate_image.new(grid_file, shade=True, contour=20))\n\n # contour the grid\n gxg.contour(v, 'TMI_contour', grid_file)\n\n self.crc_map(v3d_name)\n\n finally:\n gxv.delete_files(v3d_name)\n\n def test_plane_contour(self):\n self.start()\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'dem_small.grd')\n\n # create a 2D view\n with gxmap.Map.new(data_area=gxgrd.Grid(grid_file).extent_2d(),\n scale=20000,\n inside_margin=0.1,\n coordinate_system=gxgrd.Grid(grid_file).coordinate_system,\n overwrite=True) as map:\n map_name = map.file_name\n\n with gxv.View.open(map, \"data\") as v:\n gxg.contour(v, 'TMI_contour', grid_file)\n with gxg.Draw(v, 'edge') as g:\n g.rectangle((v.extent_clip), pen=gxg.Pen(line_thick=v.units_per_map_cm * 0.1))\n\n self.crc_map(map_name)\n\n def test_plane_contour_3d(self):\n self.start()\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'dem_small.grd')\n\n v3d_name = ''\n try:\n\n # create a 3D view\n with gxv.View_3d.new(\"data\",\n area_2d=gxgrd.Grid(grid_file).extent_2d(),\n coordinate_system=gxgrd.Grid(grid_file).coordinate_system,\n scale=20000,\n overwrite=True) as v:\n v3d_name = v.file_name\n gxg.contour(v, 'TMI_contour', grid_file)\n with gxg.Draw(v, 'edge') as g:\n g.rectangle((v.extent_clip), pen=gxg.Pen(line_thick=v.units_per_map_cm * 0.1))\n\n self.crc_map(v3d_name)\n\n finally:\n gxv.delete_files(v3d_name)\n\n\n def test_polydata_3d_grd_cone(self):\n self.start()\n\n def render_spheres(item, cmap_radius):\n cmap, radius = cmap_radius\n if not np.isnan(item[2]):\n cint = cmap.color_of_value(item[2]).int_value\n item = gxgm.Point(item)\n item2 = item + (0, radius, radius * 2)\n return gxg.SYMBOL_3D_CONE, gxgm.Point2((item, item2)), cint, radius\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n\n grid_file = os.path.join(folder, 'dem_small.grd')\n with gxgrd.Grid.open(grid_file) as grd:\n\n # get the data and replace z with DEM valie\n data = grd.xyzv().reshape(-1, 4)\n data[:, 2] = data[:, 3] * 3\n data = data[:, 0:3]\n\n cmap = gxg.Color_map()\n try:\n std = np.nanstd(data[:, 2])\n mean = np.nanmean(data[:, 2])\n cmap.set_normal(std, mean)\n except:\n cmap.set_linear(0, 1)\n\n with gxv.View_3d.new(coordinate_system=grd.coordinate_system) as v:\n v3d_file = v.file_name\n with gxg.Draw_3d(v, 'dem_points') as g:\n g.polydata_3d(data.reshape((-1, 3)), render_spheres, (cmap, 10 * v.units_per_map_cm))\n p_min = gxgm.Point((np.nanmin(data[:, 0]), np.nanmin(data[:, 1]), np.nanmin(data[:, 2])))\n p_max = gxgm.Point((np.nanmax(data[:, 0]), np.nanmax(data[:, 1]), np.nanmax(data[:, 2])))\n extent = gxgm.Point2((p_min, p_max))\n g.box_3d(extent,\n wireframe=True,\n pen=gxg.Pen(line_color='c', line_thick= 20 * v.units_per_map_cm))\n\n self.crc_map(v3d_file)\n\n def test_polydata_3d_grd_cylinder(self):\n self.start()\n\n def render_spheres(item, cmap_radius):\n cmap, radius = cmap_radius\n if not np.isnan(item[2]):\n cint = cmap.color_of_value(item[2]).int_value\n item = gxgm.Point(item)\n item2 = item + (0, radius, radius * 2)\n return gxg.SYMBOL_3D_CYLINDER, gxgm.Point2((item, item2)), cint, radius\n\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'dem_small.zip'),\n folder=self.gx.temp_folder())\n\n grid_file = os.path.join(folder, 'dem_small.grd')\n with gxgrd.Grid.open(grid_file) as grd:\n\n # get the data and replace z with DEM valie\n data = grd.xyzv().reshape(-1, 4)\n data[:, 2] = data[:, 3] * 3\n data = data[:, 0:3]\n\n cmap = gxg.Color_map()\n try:\n std = np.nanstd(data[:, 2])\n mean = np.nanmean(data[:, 2])\n cmap.set_normal(std, mean)\n except:\n cmap.set_linear(0, 1)\n\n with gxv.View_3d.new(coordinate_system=grd.coordinate_system) as v:\n v3d_file = v.file_name\n with gxg.Draw_3d(v, 'dem_points') as g:\n g.polydata_3d(data.reshape((-1, 3)), render_spheres, (cmap, 10 * v.units_per_map_cm))\n p_min = gxgm.Point((np.nanmin(data[:, 0]), np.nanmin(data[:, 1]), np.nanmin(data[:, 2])))\n p_max = gxgm.Point((np.nanmax(data[:, 0]), np.nanmax(data[:, 1]), np.nanmax(data[:, 2])))\n extent = gxgm.Point2((p_min, p_max))\n g.box_3d(extent,\n wireframe=True,\n pen=gxg.Pen(line_color='c', line_thick= 20 * v.units_per_map_cm))\n\n self.crc_map(v3d_file)\n\n def test_contour(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n with gxmap.Map.new(map_file,\n data_area=area, media=\"A4\", margins=(0, 10, 0, 0),\n coordinate_system=cs, overwrite=True) as gmap:\n map_file = gmap.file_name\n\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='R'))\n\n with gxagg.Aggregate_image.new(grid_file) as agg:\n with gxg.Aggregate_group.new(v, agg) as gagg:\n self.assertEqual(gagg.name, str(agg))\n\n self.assertEqual(len(v.group_list_agg), 1)\n\n gxg.contour(v, 'contour', grid_file)\n\n self.crc_map(map_file)\n\n def test_contour2(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n\n with gxmap.Map.new(map_file,\n data_area=area, margins=(2, 10, 2, 2),\n coordinate_system=cs, overwrite=True, scale=20000) as gmap:\n map_file = gmap.file_name\n\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='R'))\n\n with gxagg.Aggregate_image.new(grid_file, contour=10) as agg:\n cmap = agg.layer_color_map()\n cname = agg.name\n with gxg.Aggregate_group.new(v, agg) as gagg:\n self.assertEqual(gagg.name, str(agg))\n\n gxg.legend_color_bar(v, cname, cmap)\n\n self.assertEqual(len(v.group_list_agg), 1)\n\n gxg.contour(v, 'contour', grid_file)\n\n self.crc_map(map_file)\n\n def test_contour_parameters(self):\n self.start()\n\n # test grid file\n folder, files = gsys.unzip(os.path.join(os.path.dirname(self._test_case_py), 'testgrids.zip'),\n folder=self.gx.temp_folder())\n grid_file = os.path.join(folder, 'test_agg_utm.grd')\n map_file = os.path.join(self.gx.temp_folder(), \"test_agg_utm\")\n\n with gxgrd.Grid(grid_file) as grd:\n cs = grd.coordinate_system\n area = grd.extent_2d()\n\n with gxmap.Map.new(map_file,\n data_area=area, margins=(2, 10, 2, 2),\n coordinate_system=cs, overwrite=True, scale=20000) as gmap:\n map_file = gmap.file_name\n\n with gxv.View.open(gmap, \"base\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(v.extent_clip, pen=g.new_pen(line_thick=1, line_color='K'))\n\n with gxv.View.open(gmap, \"data\") as v:\n with gxg.Draw(v, 'line') as g:\n g.rectangle(area, pen=g.new_pen(line_thick=0.1, line_color='R'))\n\n #gxg.contour(v, '_250', grid_file, parameters=('', '', '', '', '', '', '50/'))\n gxg.contour(v, '_250', grid_file, parameters=('', '', '', '', '', '', '10', '50', '250'))\n gxg.contour(v, '_260_270', grid_file,\n parameters={'levels': {'levopt': 1},\n 'contours': [{'cint': 260, 'label': 0, 'catt': 'a=rt50'},\n {'cint': 270, 'label': 1, 'catt': 'b=gt1000'},\n {'cint': 280, 'label': 1, 'catt': 'c=br100g100t500'}]})\n\n self.crc_map(map_file)\n\n def test_color_str(self):\n self.start()\n\n self.assertEqual(gxg.color_from_string(\"R\"), 33554687)\n self.assertEqual(gxg.color_from_string(\"H255S127V32\"), 18907135)\n\n def test_group_properties(self):\n self.start()\n\n rect = gxgm.Point2((0,0,10,5))\n with gxmap.Map.new(data_area=rect.extent_xy) as gmap:\n with gxv.View.new(gmap, \"data\") as v:\n gxg.Draw(v, 'rect').rectangle(rect)\n self.assertTrue(len(v.group_list), 1)\n gxg.Draw(v, 'rect').rectangle(rect)\n self.assertTrue(len(v.group_list), 1)\n gxg.Draw(v, 'rect', mode=gxg.NEW).rectangle(rect)\n self.assertTrue(len(v.group_list), 2)\n self.assertTrue('rect_1' in v.group_list)\n gxg.Draw(v, 'rect_1', mode=gxg.REPLACE).rectangle(rect)\n self.assertTrue(len(v.group_list), 2)\n self.assertTrue('rect_1' in v.group_list)\n\n with gxg.Draw(v, 'property_test') as g:\n self.assertEqual(g.group_opacity, 1.0)\n g.group_opacity = 0.25\n self.assertEqual(g.group_opacity, 0.25)\n g.group_opacity = -50\n self.assertEqual(g.group_opacity, 0.)\n g.group_opacity = 5\n self.assertEqual(g.group_opacity, 1.)\n self.assertFalse(g.group_3d)\n self.assertEqual(g.name, 'property_test')\n self.assertEqual(g.view.name, 'data')\n\n @unittest.skip('WIP see issue #73')\n def test_surface(self):\n self.start()\n\n verts = np.array([[0, 0, 0],\n [5, 0, 0],\n [5, 5, 0],\n [0, 3, 5],\n [2.5, 2, 10],\n [-3, 6, 8],\n [-4, 0, 12]], dtype=np.float64)\n faces = np.array([[0, 1, 2],\n [0, 2, 3],\n [3, 2, 4],\n [1, 2, 4],\n [3, 4, 5],\n [6, 4, 5]], dtype=np.int32)\n\n with gxv.View_3d.new() as v3d:\n v3d_file = v3d.file_name\n with gxg.Draw_3d(v3d, 'Surface') as g:\n g._surface(faces, verts)\n image_file = gxmap.Map.open(v3d_file).image_file(pix_width=800)\n gxviewer.view_document(v3d_file, wait_for_close=True)\n pass # self.crc_map(v3d_file)\n\nif __name__ == '__main__':\n unittest.main()", "### extends 'class_empty.py'\n### block ClassImports\n# NOTICE: Do not edit anything here, it is generated code\nfrom . import gxapi_cy\nfrom geosoft.gxapi import GXContext, float_ref, int_ref, str_ref\nfrom .GXVV import GXVV\n\n\n### endblock ClassImports\n\n### block Header\n# NOTICE: The code generator will not replace the code in this block\nimport numpy as np\nfrom . import gxapi_cy_extend\n### endblock Header\n\n### block ClassImplementation\n# NOTICE: Do not edit anything here, it is generated code\nclass GXVA(gxapi_cy.WrapVA):\n \"\"\"\n GXVA class.\n\n The `GXVA <geosoft.gxapi.GXVA>` class is the 2-Dimensional analogue to the `GXVV <geosoft.gxapi.GXVV>` class.\n When displayed in a database, `GXVA <geosoft.gxapi.GXVA>` objects are displayed graphically\n as profiles, one to a cell, and can also be displayed one column of\n data at a time by specifying an index; e.g. CH[0]. A `GXVA <geosoft.gxapi.GXVA>` object is\n declared with a fixed number of columns, which cannot be altered.\n The number of rows, however can be changed, in the same way that\n the length of a `GXVV <geosoft.gxapi.GXVV>` can be changed. Data can be added or extracted\n using VVs, either by row or column.\n\n A `GXVA <geosoft.gxapi.GXVA>` is used to store an array of data in which each element may have\n multiple elements. For example, 256-channel radiometric data can\n be stored in a `GXVA <geosoft.gxapi.GXVA>` that is 256 elements wide.\n \"\"\"\n\n def __init__(self, handle=0):\n super(GXVA, self).__init__(GXContext._get_tls_geo(), handle)\n\n @classmethod\n def null(cls):\n \"\"\"\n A null (undefined) instance of `GXVA <geosoft.gxapi.GXVA>`\n \n :returns: A null `GXVA <geosoft.gxapi.GXVA>`\n :rtype: GXVA\n \"\"\"\n return GXVA()\n\n def is_null(self):\n \"\"\"\n Check if this is a null (undefined) instance\n \n :returns: True if this is a null (undefined) instance, False otherwise.\n :rtype: bool\n \"\"\"\n return self._internal_handle() == 0\n\n\n\n# Miscellaneous\n\n\n\n def get_array(self, start_row, start_col, rows, cols, data, gs_type):\n \"\"\"\n Get an array of data from a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param start_row: Starting Row\n :param start_col: Starting Column\n :param rows: # rows\n :param cols: # cols\n :param data: Data buffer to copy `GXVA <geosoft.gxapi.GXVA>` data into\n :param gs_type: :ref:`GS_TYPES`\n :type start_row: int\n :type start_col: int\n :type rows: int\n :type cols: int\n :type data: bytearray\n :type gs_type: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._get_array(start_row, start_col, rows, cols, data, gs_type)\n \n\n\n\n\n def set_array(self, start_row, start_col, rows, cols, data, gs_type):\n \"\"\"\n Set a range of data in an array\n \n :param start_row: Starting Row\n :param start_col: Starting Column\n :param rows: # rows\n :param cols: # cols\n :param data: Data buffer to copy into `GXVA <geosoft.gxapi.GXVA>`\n :param gs_type: :ref:`GS_TYPES`\n :type start_row: int\n :type start_col: int\n :type rows: int\n :type cols: int\n :type data: bytearray\n :type gs_type: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._set_array(start_row, start_col, rows, cols, data, gs_type)\n \n\n\n\n\n def add_elevations_vv_to_depths(self, vv, negative_depths):\n \"\"\"\n Add one `GXVV <geosoft.gxapi.GXVV>` value to each row of the `GXVA <geosoft.gxapi.GXVA>`, output true elevation.\n \n :param vv: Elevations to add\n :param negative_depths: Use negative `GXVA <geosoft.gxapi.GXVA>` depths (0:No, 1:Yes)?\n :type vv: GXVV\n :type negative_depths: int\n\n .. versionadded:: 7.2\n\n **License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_\n\n **Note:** Adds each value in an input elevation `GXVV <geosoft.gxapi.GXVV>` to all the values at\n the same fid in a depths `GXVA <geosoft.gxapi.GXVA>`. Includes an option for negative depths down\n (e.g. a relative level).\n \"\"\"\n self._add_elevations_vv_to_depths(vv, negative_depths)\n \n\n\n\n\n def append(self, v_aa):\n \"\"\"\n Appends VAs\n \n :param v_aa: `GXVA <geosoft.gxapi.GXVA>` to append\n :type v_aa: GXVA\n\n .. versionadded:: 5.1.3\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** If the VAs have different numbers of columns, the smaller number\n is used in the copy operation.\n \"\"\"\n self._append(v_aa)\n \n\n\n\n\n def average(self, vv, rc):\n \"\"\"\n Average elements in a `GXVA <geosoft.gxapi.GXVA>` by row or column\n \n :param vv: `GXVV <geosoft.gxapi.GXVV>` in which to place average results\n :param rc: :ref:`VA_AVERAGE`\n :type vv: GXVV\n :type rc: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** The output `GXVV <geosoft.gxapi.GXVV>` will be dimensioned by the number of\n rows or columns in the input `GXVV <geosoft.gxapi.GXVV>` depending on the\n :ref:`VA_AVERAGE` setting.\n\n Dummies are not included in the average.\n \"\"\"\n self._average(vv, rc)\n \n\n\n\n\n def copy(self, v_as):\n \"\"\"\n Copy one `GXVA <geosoft.gxapi.GXVA>` to another.\n \n :param v_as: source\n :type v_as: GXVA\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._copy(v_as)\n \n\n\n\n\n def copy2(self, d_row, d_col, v_as, s_row, s_col, rows, cols):\n \"\"\"\n Copy part of a vector into part of another vector.\n \n :param d_row: Destination start row\n :param d_col: Destination start column\n :param v_as: Source `GXVA <geosoft.gxapi.GXVA>` (can be the same as Destination)\n :param s_row: Source start row\n :param s_col: Source start column\n :param rows: Number of rows\n :param cols: Number of columns\n :type d_row: int\n :type d_col: int\n :type v_as: GXVA\n :type s_row: int\n :type s_col: int\n :type rows: int\n :type cols: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** 1. Unlike `copy <geosoft.gxapi.GXVA.copy>` destination `GXVA <geosoft.gxapi.GXVA>` is not reallocated, nor are\n the dimensions changed. The caller must make any desired changes.\n\n 2. All `GXVA <geosoft.gxapi.GXVA>` types are supported and will be converted using\n Convert_GS if necessary.\n \"\"\"\n self._copy2(d_row, d_col, v_as, s_row, s_col, rows, cols)\n \n\n\n\n @classmethod\n def create(cls, type, rows, cols):\n \"\"\"\n Create a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param type: :ref:`GEO_VAR`\n :param rows: Maximum number of rows in the `GXVA <geosoft.gxapi.GXVA>`, >= 0\n :param cols: Number of columns in the `GXVA <geosoft.gxapi.GXVA>`, > 0\n :type type: int\n :type rows: int\n :type cols: int\n\n :returns: `GXVA <geosoft.gxapi.GXVA>` Object\n :rtype: GXVA\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n ret_val = gxapi_cy.WrapVA._create(GXContext._get_tls_geo(), type, rows, cols)\n return GXVA(ret_val)\n\n\n\n @classmethod\n def create_ext(cls, type, rows, cols):\n \"\"\"\n Create a `GXVA <geosoft.gxapi.GXVA>`, using one of the :ref:`GS_TYPES` special data types.\n \n :param type: :ref:`GS_TYPES`\n :param rows: Maximum number of rows in the `GXVA <geosoft.gxapi.GXVA>`, >= 0\n :param cols: Number of columns in the `GXVA <geosoft.gxapi.GXVA>`, > 0\n :type type: int\n :type rows: int\n :type cols: int\n\n :returns: `GXVA <geosoft.gxapi.GXVA>`, aborts if creation fails\n :rtype: GXVA\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** See `GXVV.create <geosoft.gxapi.GXVV.create>`\n \"\"\"\n ret_val = gxapi_cy.WrapVA._create_ext(GXContext._get_tls_geo(), type, rows, cols)\n return GXVA(ret_val)\n\n\n\n @classmethod\n def create_vv(cls, vv, rows, columns):\n \"\"\"\n Create a `GXVA <geosoft.gxapi.GXVA>` using the data in a `GXVV <geosoft.gxapi.GXVV>`.\n \n :param vv: `GXVV <geosoft.gxapi.GXVV>` with the data\n :param rows: # of rows\n :param columns: # of columns\n :type vv: GXVV\n :type rows: int\n :type columns: int\n\n :returns: `GXVA <geosoft.gxapi.GXVA>`, aborts if creation fails\n :rtype: GXVA\n\n .. versionadded:: 7.2.1\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** See `GXVV.create <geosoft.gxapi.GXVV.create>`\n \"\"\"\n ret_val = gxapi_cy.WrapVA._create_vv(GXContext._get_tls_geo(), vv, rows, columns)\n return GXVA(ret_val)\n\n\n\n\n\n\n def get_full_vv(self):\n \"\"\"\n Get the full `GXVV <geosoft.gxapi.GXVV>` from the `GXVA <geosoft.gxapi.GXVA>`.\n \n\n :returns: `GXVV <geosoft.gxapi.GXVV>` Object\n :rtype: GXVV\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** No data is copied, this is the handle to the data `GXVV <geosoft.gxapi.GXVV>` in the `GXVA <geosoft.gxapi.GXVA>`.\n The fid start/increment of the `GXVA <geosoft.gxapi.GXVA>` is passed to the `GXVV <geosoft.gxapi.GXVV>` at the time\n of the call. If a new `GXVA <geosoft.gxapi.GXVA>` is read, you must call GetFull_VV_VA\n to get the new fid in the `GXVV <geosoft.gxapi.GXVV>`.\n \"\"\"\n ret_val = self._get_full_vv()\n return GXVV(ret_val)\n\n\n\n\n def get_vv(self, no, row_col, vv):\n \"\"\"\n Get a row or column of data as a `GXVV <geosoft.gxapi.GXVV>` from an array.\n \n :param no: Row or Column # (0 is first)\n :param row_col: :ref:`VA_OBJECT`\n :param vv: `GXVV <geosoft.gxapi.GXVV>` in which to place data\n :type no: int\n :type row_col: int\n :type vv: GXVV\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._get_vv(no, row_col, vv)\n \n\n\n\n\n def col(self):\n \"\"\"\n Return number of columns in `GXVA <geosoft.gxapi.GXVA>`\n \n\n :returns: Columns in `GXVA <geosoft.gxapi.GXVA>`\n :rtype: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** `len <geosoft.gxapi.GXVA.len>` returns the number of rows.\n \"\"\"\n ret_val = self._col()\n return ret_val\n\n\n\n\n def get_int(self, row, col):\n \"\"\"\n Get an integer element from a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :type row: int\n :type col: int\n\n :returns: Element wanted, `rDUMMY <geosoft.gxapi.rDUMMY>`, `iDUMMY <geosoft.gxapi.iDUMMY>` or blank string\n if the value is dummy or outside of the range of data.\n :rtype: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Type conversions are performed if necessary. Dummy values\n are converted to \"*\" string.\n \"\"\"\n ret_val = self._get_int(row, col)\n return ret_val\n\n\n\n\n def get_string(self, row, col, str_val):\n \"\"\"\n Get a string element from a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :param str_val: String in which to place element\n :type row: int\n :type col: int\n :type str_val: str_ref\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Returns element wanted, `rDUMMY <geosoft.gxapi.rDUMMY>`, `iDUMMY <geosoft.gxapi.iDUMMY>` or blank string\n if the value is dummy or outside of the range of data.\n\n Type conversions are performed if necessary. Dummy values\n are converted to \"*\" string.\n \"\"\"\n str_val.value = self._get_string(row, col, str_val.value.encode())\n \n\n\n\n\n def len(self):\n \"\"\"\n Return length (number of rows) in a `GXVA <geosoft.gxapi.GXVA>`.\n \n\n :returns: Length of `GXVA <geosoft.gxapi.GXVA>`\n :rtype: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** `col <geosoft.gxapi.GXVA.col>` returns the number of columns.\n \"\"\"\n ret_val = self._len()\n return ret_val\n\n\n\n @classmethod\n def index_order(cls, vv, va):\n \"\"\"\n Reorder a `GXVA <geosoft.gxapi.GXVA>` based on an index `GXVV <geosoft.gxapi.GXVV>`\n \n :param vv: Index `GXVV <geosoft.gxapi.GXVV>` of type INT\n :param va: `GXVA <geosoft.gxapi.GXVA>` to order\n :type vv: GXVV\n :type va: GXVA\n\n .. versionadded:: 5.1\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Given a row index `GXVV <geosoft.gxapi.GXVV>` (of type INT), this method reorders a\n `GXVA <geosoft.gxapi.GXVA>`. Please make sure that the index holds valid information.\n \"\"\"\n gxapi_cy.WrapVA._index_order(GXContext._get_tls_geo(), vv, va)\n \n\n\n\n\n def lookup_index(self, vvi, var):\n \"\"\"\n Lookup a `GXVA <geosoft.gxapi.GXVA>` from another `GXVA <geosoft.gxapi.GXVA>` using an index `GXVV <geosoft.gxapi.GXVV>`.\n \n :param vvi: Index `GXVV <geosoft.gxapi.GXVV>` of REAL\n :param var: `GXVA <geosoft.gxapi.GXVA>` to output results (same type as Data `GXVA <geosoft.gxapi.GXVA>`)\n :type vvi: GXVV\n :type var: GXVA\n\n .. versionadded:: 6.4.2\n\n **License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_\n\n **Note:** Fractional values in the `GXVV <geosoft.gxapi.GXVV>` will interpolate between the value\n at the whole integer value and the next whole integer, dummy\n if outside the `GXVA <geosoft.gxapi.GXVA>`.\n \"\"\"\n self._lookup_index(vvi, var)\n \n\n\n\n\n def range(self, startRow, startCol, rows, columns, min, max):\n \"\"\"\n Computes the minimum and maximum range of the data, in doubles,\n in a vector while ignoring dummies, for a range of columns and rows.\n \n :param startRow: Starting row (0 to nRows-1)\n :param startCol: Starting column (0 to nColumns-1\n :param rows: Number of rows (-1 for all from start)\n :param columns: Number of columns (-1 for all from start)\n :param min: Minimum value - returned\n :param max: Maximum value - returned\n :type startRow: int\n :type startCol: int\n :type rows: int\n :type columns: int\n :type min: float_ref\n :type max: float_ref\n\n .. versionadded:: 9.6\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n min.value, max.value = self._range(startRow, startCol, rows, columns, min.value, max.value)\n \n\n\n\n\n def range_double(self, min, max):\n \"\"\"\n Computes the minimum and maximum range of the data, in doubles,\n in a vector while ignoring dummies.\n \n :param min: Minimum value - returned\n :param max: Maximum value - returned\n :type min: float_ref\n :type max: float_ref\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n min.value, max.value = self._range_double(min.value, max.value)\n \n\n\n\n\n def range_columns(self, startRow, startCol, rows, columns, minimums, maximums):\n \"\"\"\n Computes the minimum and maximum range of the data for individual columns, in doubles,\n for a range of columns and rows.\n \n :param startRow: Starting row (0 to nRows-1)\n :param startCol: Starting column (0 to nColumns-1\n :param rows: Number of rows (-1 for all from start)\n :param columns: Number of columns (-1 for all from start)\n :param minimums: Minimum values returned:`VV` object - GS_REAL\n :param maximums: Maximum values returned:`VV` object - GS_REAL\n :type startRow: int\n :type startCol: int\n :type rows: int\n :type columns: int\n :type minimums: GXVV\n :type maximums: GXVV\n\n .. versionadded:: 9.6\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._range_columns(startRow, startCol, rows, columns, minimums, maximums)\n \n\n\n\n\n def re_fid(self, start, incr, length):\n \"\"\"\n Re-sample a `GXVA <geosoft.gxapi.GXVA>` to a new fid start/icrement\n \n :param start: New fid start\n :param incr: New fid increment\n :param length: New length\n :type start: float\n :type incr: float\n :type length: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._re_fid(start, incr, length)\n \n\n\n\n\n def reverse(self):\n \"\"\"\n Reverses the order of the rows in a `GXVA <geosoft.gxapi.GXVA>`.\n \n\n .. versionadded:: 5.1.5\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._reverse()\n \n\n\n\n\n def get_fid_incr(self):\n \"\"\"\n Gets the Fiducial increment from a `GXVA <geosoft.gxapi.GXVA>`\n \n\n :returns: Fiducial increment of the `GXVA <geosoft.gxapi.GXVA>`.\n :rtype: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n ret_val = self._get_fid_incr()\n return ret_val\n\n\n\n\n def get_fid_start(self):\n \"\"\"\n Gets the Fiducial start from a `GXVA <geosoft.gxapi.GXVA>`\n \n\n :returns: Fiducial start of the `GXVA <geosoft.gxapi.GXVA>`.\n :rtype: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n ret_val = self._get_fid_start()\n return ret_val\n\n\n\n\n def get_double(self, row, col):\n \"\"\"\n Get a real element from a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :type row: int\n :type col: int\n\n :returns: Element wanted, `rDUMMY <geosoft.gxapi.rDUMMY>`, `iDUMMY <geosoft.gxapi.iDUMMY>` or blank string\n if the value is dummy or outside of the range of data.\n :rtype: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Type conversions are performed if necessary. Dummy values\n are converted to \"*\" string.\n \"\"\"\n ret_val = self._get_double(row, col)\n return ret_val\n\n\n\n\n def set_fid_incr(self, incr):\n \"\"\"\n Sets the Fiducial increment of a `GXVA <geosoft.gxapi.GXVA>`\n \n :param incr: New increment\n :type incr: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._set_fid_incr(incr)\n \n\n\n\n\n def set_fid_start(self, start):\n \"\"\"\n Sets the Fiducial start of a `GXVA <geosoft.gxapi.GXVA>`\n \n :param start: New start\n :type start: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._set_fid_start(start)\n \n\n\n\n\n def set_int(self, row, col, value):\n \"\"\"\n Set an integer element in a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :param value: Value to set\n :type row: int\n :type col: int\n :type value: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Element being set cannot be < 0.\n If the element is > current `GXVA <geosoft.gxapi.GXVA>` length, the `GXVA <geosoft.gxapi.GXVA>` length is\n increased.\n \"\"\"\n self._set_int(row, col, value)\n \n\n\n\n\n def set_ln(self, rows):\n \"\"\"\n Set the length (number of rows) of the `GXVA <geosoft.gxapi.GXVA>`\n \n :param rows: Length\n :type rows: int\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** The number of columns in a `GXVA <geosoft.gxapi.GXVA>` is fixed, and cannot be\n altered once the `GXVA <geosoft.gxapi.GXVA>` is created.\n \"\"\"\n self._set_ln(rows)\n \n\n\n\n\n def set_double(self, row, col, value):\n \"\"\"\n Set a real element in a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :param value: Value to set\n :type row: int\n :type col: int\n :type value: float\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Element being set cannot be < 0.\n If the element is > current `GXVA <geosoft.gxapi.GXVA>` length, the `GXVA <geosoft.gxapi.GXVA>` length is\n increased.\n \"\"\"\n self._set_double(row, col, value)\n \n\n\n\n\n def set_string(self, row, col, value):\n \"\"\"\n Set a string element in a `GXVA <geosoft.gxapi.GXVA>`.\n \n :param row: Row\n :param col: Column\n :param value: String to set\n :type row: int\n :type col: int\n :type value: str\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** Element being set cannot be < 0.\n If the element is > current `GXVA <geosoft.gxapi.GXVA>` length, the `GXVA <geosoft.gxapi.GXVA>` length is\n increased.\n \"\"\"\n self._set_string(row, col, value.encode())\n \n\n\n\n\n def set_vv(self, no, row_col, vv):\n \"\"\"\n Set a row or column of data in an array from a `GXVV <geosoft.gxapi.GXVV>`.\n \n :param no: Row or Column # (0 is first)\n :param row_col: :ref:`VA_OBJECT`\n :param vv: `GXVV <geosoft.gxapi.GXVV>` from which to get data\n :type no: int\n :type row_col: int\n :type vv: GXVV\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n \"\"\"\n self._set_vv(no, row_col, vv)\n \n\n\n\n\n def trans(self, base, mult):\n \"\"\"\n Translate (`GXVA <geosoft.gxapi.GXVA>` + base ) * mult\n \n :param base: Base value\n :param mult: Mult value\n :type base: float\n :type mult: float\n\n .. versionadded:: 7.2\n\n **License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_\n\n **Note:** Supports all `GXVA <geosoft.gxapi.GXVA>` types using an internal double `GXVV <geosoft.gxapi.GXVV>`.\n \"\"\"\n self._trans(base, mult)\n \n\n\n\n\n def window(self, start, count, vv):\n \"\"\"\n Window a `GXVA <geosoft.gxapi.GXVA>` to a `GXVV <geosoft.gxapi.GXVV>` based in intergral frame\n \n :param start: First element in the window\n :param count: Number of elements in the window\n :param vv: `GXVV <geosoft.gxapi.GXVV>` in which to place results\n :type start: int\n :type count: int\n :type vv: GXVV\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** The defined window must be within the `GXVA <geosoft.gxapi.GXVA>` element dimensions.\n The windowed result will be the simple sum of all\n values in the window.\n If any values are dummy, the result will be dummy.\n \"\"\"\n self._window(start, count, vv)\n \n\n\n\n\n def window2(self, start, end, vv):\n \"\"\"\n Window a `GXVA <geosoft.gxapi.GXVA>` to a `GXVV <geosoft.gxapi.GXVV>` based on fractional frame\n \n :param start: Start point (from 0.0)\n :param end: End point (< `GXVA <geosoft.gxapi.GXVA>` elements - 1.0)\n :param vv: `GXVV <geosoft.gxapi.GXVV>` in which to place results\n :type start: float\n :type end: float\n :type vv: GXVV\n\n .. versionadded:: 5.0\n\n **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_\n\n **Note:** The defined window must be within the `GXVA <geosoft.gxapi.GXVA>` element dimensions.\n The windowed result will be the simple sum of all\n values in the window.\n If any values are dummy, the result will be dummy.\n \"\"\"\n self._window2(start, end, vv)\n \n\n\n\n\n def check_for_repeating(self, vv_t, subtract_vv, vv_sub, tol):\n \"\"\"\n Window a `GXVA <geosoft.gxapi.GXVA>` to a `GXVV <geosoft.gxapi.GXVV>` based on fractional frame\n \n :param vv_t: Items to test for repeats (length equal to the number of columns in the `GXVA <geosoft.gxapi.GXVA>`)\n :param subtract_vv: If set to 1, subtract single values in the following `GXVV <geosoft.gxapi.GXVV>` from every array row item before testing (e.g. an elevation value)\n :param vv_sub: Values to subtract from each row before doing the comparison test (length equal to the length of the `GXVA <geosoft.gxapi.GXVA>`). Can be VV_NULL (-1) if above subtraction parameter is zero\n :param tol: Comparison tolerance - set to zero or dummy for exact match\n :type vv_t: GXVV\n :type subtract_vv: int\n :type vv_sub: GXVV\n :type tol: float\n\n :returns: 1 if rows repeat, 0 if not.\n :rtype: int\n\n .. versionadded:: 8.2\n\n **License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_\n\n **Note:** Returns 1 if all rows contain values which match the input values.\n Optionally, row values can be offset by amounts specified with a secondary `GXVV <geosoft.gxapi.GXVV>`.\n This function was designed to detect \"depth\" array channels, including those which might\n have been offset with topography on each row.\n An absolute tolerance can be specified to ignore numerical noise.\n \"\"\"\n ret_val = self._check_for_repeating(vv_t, subtract_vv, vv_sub, tol)\n return ret_val\n\n\n\n\n def check_for_repeating2(self, vv_t, subtract_vv, vv_sub, tol, bad_row, bad_col):\n \"\"\"\n Window a `GXVA <geosoft.gxapi.GXVA>` to a `GXVV <geosoft.gxapi.GXVV>` based on fractional frame\n \n :param vv_t: Items to test for repeats (length equal to the number of columns in the `GXVA <geosoft.gxapi.GXVA>`)\n :param subtract_vv: If set to 1, subtract single values in the following `GXVV <geosoft.gxapi.GXVV>` from every array row item before testing (e.g. an elevation value)\n :param vv_sub: Values to subtract from each row before doing the comparison test (length equal to the length of the `GXVA <geosoft.gxapi.GXVA>`). Can be VV_NULL (-1) if above subtraction parameter is zero\n :param tol: Comparison tolerance - set to zero or dummy for exact match\n :param bad_row: Row index of first mismatch\n :param bad_col: Column index of first mismatch\n :type vv_t: GXVV\n :type subtract_vv: int\n :type vv_sub: GXVV\n :type tol: float\n :type bad_row: int_ref\n :type bad_col: int_ref\n\n :returns: 1 if rows repeat, 0 if not.\n :rtype: int\n\n .. versionadded:: 8.2\n\n **License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_\n\n **Note:** Returns 1 if all rows contain values which match the input values.\n Optionally, row values can be offset by amounts specified with a secondary `GXVV <geosoft.gxapi.GXVV>`.\n This function was designed to detect \"depth\" array channels, including those which might\n have been offset with topography on each row.\n An absolute tolerance can be specified to ignore numerical noise.\n This version returns the row and column index of first mismatch.\n \"\"\"\n ret_val, bad_row.value, bad_col.value = self._check_for_repeating2(vv_t, subtract_vv, vv_sub, tol, bad_row.value, bad_col.value)\n return ret_val\n\n\n\n\n\n### endblock ClassImplementation\n### block ClassExtend\n# NOTICE: The code generator will not replace the code in this block\n def get_array_np(self, start_row: int, start_col: int, rows: int, cols: int, np_dtype: type(np.dtype)):\n from .GXNumpy import gs_from_np\n gs_type = gs_from_np(np_dtype)\n return np.asarray(self.get_data_array(start_row, start_col, rows, cols, gs_type))\n\n def set_array_np(self, start_row: int, start_col: int, np_array: type(np.ndarray)):\n from .GXNumpy import gs_from_np\n gs_type = gs_from_np(np_array.dtype)\n if np_array.ndim != 2:\n raise GXAPIError(\"Only 2D Numpy arrays supported for this method\");\n rows = np_array.shape[0];\n columns = np_array.shape[1];\n if not np_array.flags['C_CONTIGUOUS']:\n np_array = np.ascontiguousarray(np_array)\n self.set_array(start_row, start_col, rows, columns, np_array.data.tobytes(), gs_type)\n \n def get_data_array(self, start_row: int, start_col: int, rows: int, cols: int, gs_type: int):\n return gxapi_cy_extend.GXMemMethods.get_array_data_va(GXContext._internal_p(), self._internal_handle(), start_row, start_col, rows, cols, gs_type)\n### endblock ClassExtend\n\n\n### block Footer\n# NOTICE: The code generator will not replace the code in this block\n### endblock Footer", "\"\"\"\nGeosoft grid and image handling, including all\n`supported file formats <https://geosoftgxdev.atlassian.net/wiki/display/GXDEV92/Grid+File+Name+Decorations>`_ .\n\n:Classes:\n :`Grid`: grid dataset\n\n:Constants:\n :FILE_READ: 0 open for read, files are not changed\n :FILE_READWRITE: 1 open for read and write, files can be changed\n :FILE_NEW: 2 new grid file, accompanied by `overwrite=` parameter\n\n.. seealso:: :mod:`geosoft.gxpy.grid_utility`, :mod:`geosoft.gxpy.grid_fft`,\n :class:`geosoft.gxapi.GXIMG`, :class:`geosoft.gxapi.GXIMU`\n\n.. note::\n\n Regression tests provide usage examples: \n `Tests <https://github.com/GeosoftInc/gxpy/blob/master/geosoft/gxpy/tests/test_grid.py>`_\n\n\"\"\"\nimport os\nimport numpy as np\nimport math\n\nimport geosoft\nimport geosoft.gxapi as gxapi\nfrom . import gx as gx\nfrom . import coordinate_system as gxcs\nfrom . import vv as gxvv\nfrom . import utility as gxu\nfrom . import agg as gxagg\nfrom . import geometry as gxgm\nfrom . import map as gxmap\nfrom . import grid_utility as gxgrdu\nfrom . import view as gxview\nfrom . import gdb as gxgdb\n\n__version__ = geosoft.__version__\n\n\nFILE_READ = 0\nFILE_READWRITE = 1\nFILE_NEW = 2\n\n\ndef _t(s):\n return geosoft.gxpy.system.translate(s)\n\n\nclass GridException(geosoft.GXRuntimeError):\n \"\"\"\n Exceptions from :mod:`geosoft.gxpy.grid`.\n\n .. versionadded:: 9.1\n \"\"\"\n pass\n\n\ndef reopen(g, dtype=None, mode=FILE_READWRITE):\n \"\"\"\n Reopen a grid to access the grid as an existing grid.\n \n Some gxapi.GXIMU methods will not work with grids open as new grids. This method closes\n the grid and reopens in the specific mode\n \n :param g: `Grid` instance\n :param dtype: data type, None to match the data type of the grid being reopened\n :param mode: `FILE_READWRITE` (default) or `FILE_READ`\n :return: new `Grid` instance\n \n .. versionadded:: 9.4\n \"\"\"\n\n if dtype is None:\n dtype = g.dtype\n dfn = g.file_name_decorated\n delete_set = g.remove_on_close\n g.delete_files(False)\n g.close()\n g = Grid.open(dfn, dtype=dtype, mode=mode)\n if delete_set:\n g.delete_files()\n return g\n\n\ndef name_parts(name):\n \"\"\"\n Return folder, undecorated file name + ext, file root, ext, decorations.\n\n If extension is not specified, \".grd\" assumed\n\n For example:\n\n .. code::\n\n >>> import geosoft.gxpy.grid as gxgrd\n >>> namep = gxgrd.name_parts(\"f:/someFolder/name.grd(GRD;TYPE=SHORT)\")\n >>> print(namep)\n ('f:/someFolder/','name.grd','name','.grd','(GRD;TYPE=SHORT)')\n\n .. versionadded:: 9.1\n \"\"\"\n\n path = os.path.abspath(name)\n fn = os.path.dirname(path)\n root, ext = os.path.splitext(os.path.basename(path))\n\n if '(' in ext:\n ext, dec = ext.split('(')\n if ')' in dec:\n dec = dec.split(')')[0]\n else:\n dec = ''\n\n if not ext:\n if (not dec) or (dec[:3].upper() == 'GRD'):\n ext = '.grd'\n name = root + ext\n\n return fn, name, root, ext, dec\n\n\ndef decorate_name(name, decorations=''):\n \"\"\"\n Properly decorate a grid name.\n\n :param name: file name\n :param decorations: file decorations, semicolon delimited\n :returns: decorated file name\n\n .. versionadded:: 9.1\n \"\"\"\n\n if name is None:\n return None\n\n root, ext = os.path.splitext(name)\n dec = decorations.strip()\n if dec:\n d = decorations.lstrip('(')\n end = d.rfind(')')\n if end != -1:\n d = d[:end]\n ext = ext.split('(')[0]\n return '{}{}({})'.format(root, ext, d)\n\n else:\n if ext.lower() == '.grd':\n return '{}{}(GRD)'.format(root, ext)\n else:\n return name\n\n\ndef delete_files(file_name):\n \"\"\"\n Delete all files associates with this grid name.\n\n :param file_name: name of the grid file\n\n .. versionadded:: 9.2\n \"\"\"\n\n if file_name is not None:\n\n fn = name_parts(file_name)\n file_name = os.path.join(fn[0], fn[1])\n ext = fn[3]\n gxu.delete_file(file_name)\n gxu.delete_file(file_name + '.gi')\n gxu.delete_file(file_name + '.xml')\n\n # remove shaded files associated with this grid\n file_s = os.path.join(fn[0], fn[1].replace('.', '_')) + '_s.grd'\n gxu.delete_file(file_s)\n gxu.delete_file(file_s + '.gi')\n gxu.delete_file(file_s + '.xml')\n\n # hgd files\n if ext == '.hgd':\n for i in range(16):\n gxu.delete_file(file_name + str(i))\n\n\ndef _transform_color_int_to_rgba(np_values):\n np_values[np_values == gxapi.iDUMMY] = 0\n a = (np.right_shift(np_values, 24) & 0xFF).astype(np.uint8)\n b = (np.right_shift(np_values, 16) & 0xFF).astype(np.uint8)\n g = (np.right_shift(np_values, 8) & 0xFF).astype(np.uint8)\n r = (np_values & 0xFF).astype(np.uint8)\n # the values for color grids actually do not contain alphas but just\n # 0 or 1 to indicate if the color is valid or not\n a[a > 0] = 255\n return np.array([r, g, b, a]).transpose()\n\n\nclass Grid(gxgm.Geometry):\n \"\"\"\n Grid and image class.\n\n :Constructors:\n\n ========================= ==============================================================\n :meth:`open` open an existing grid/image\n :meth:`new` create a new grid/image\n :meth:`copy` create a copy\n :meth:`index_window` create a windowed grid based on grid indexes\n :meth:`from_data_array` create a new grid from a 2d data array\n :meth:`minimum_curvature` create by fitting a minimum-curvature surface to located data.\n ========================= ==============================================================\n\n A grid instance supports iteration that yields (x, y, z, grid_value) by points along rows.\n For example, the following prints the x, y, z, grid_value of every non-dummy point in a grid:\n\n .. code::\n\n import geosoft.gxpy.grid as gxgrd\n\n with gxgrd.Grid.open('some.grd') ad g:\n for x, y, z, v in g:\n if v is not None:\n print(x, y, z, v)\n\n Specific grid cell values can be indexed (null grid values are None):\n\n .. code::\n\n import geosoft.gxpy.grid as gxgrd\n\n with gxgrd.Grid.open('some.grd') as g:\n for ix in range(g.nx):\n for iy in range(g.ny):\n x, y, z, v = g[ix, iy]\n if v is not None:\n print(x, y, z, v)\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.2.1 added iterator support\n \"\"\"\n\n _delete_files = False\n _file_name = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, _type, _value, _traceback):\n self.__del__()\n\n def __del__(self):\n if hasattr(self, '_close'):\n self._close()\n\n def _close(self, pop=True):\n\n def flush_hgd(hgd_temp):\n\n # convert tempory grid to an HGD file\n img = gxapi.GXIMG.create_file(gxapi.GS_TYPE_DEFAULT,\n decorate_name(hgd_temp, 'GRD'),\n gxapi.IMG_FILE_READONLY)\n gxapi.GXHGD.h_create_img(img, decorate_name(self._hgd_name, 'HGD'))\n img = None\n\n if hasattr(self, '_open'):\n if self._open:\n\n self._img = None\n\n grid_file_name = self._file_name\n file_name_decorated = decorate_name(self._file_name, self._decoration) if self._decoration else None\n\n if self._hgd:\n\n flush_hgd(self._file_name)\n if self._metadata_changed:\n with open(self._file_name + '.xml', 'w+') as f:\n f.write(gxu.xml_from_dict(self._metadata))\n if file_name_decorated:\n gxapi.GXIMG.sync(file_name_decorated)\n delete_files(grid_file_name)\n\n else:\n\n if self._delete_files:\n delete_files(self._file_name)\n elif self._mode != FILE_READ:\n if file_name_decorated:\n try:\n gxapi.GXIMG.sync(file_name_decorated)\n except (geosoft.GXRuntimeError, geosoft.gxapi.GXAPIError):\n # Locked files, extremely large files (e.g. GXF) etc. could cause errors with the\n # command above. TODO: Do we even need it? The code below overwrites it anyway?\n pass\n\n if grid_file_name:\n if self._metadata and self._metadata_changed:\n with open(grid_file_name + '.xml', 'w+') as f:\n f.write(gxu.xml_from_dict(self._metadata))\n\n if pop:\n gx.pop_resource(self._open)\n self._open = None\n self._buffer_np = None\n self._buffer_x = None\n self._buffer_y = None\n self._cs = None\n self._gxpg = None\n\n def __repr__(self):\n return \"{}({})\".format(self.__class__, self.__dict__)\n\n def __str__(self):\n if self._file_name is None:\n return '<class Grid>: memory ({}, {})'.format(self.nx, self.ny)\n else:\n return '<class Grid>: {} ({}, {})'.format(self.file_name_decorated, self.nx, self.ny)\n\n def __init__(self, file_name=None, in_memory=False, dtype=None, mode=None, kx=1, dim=None, overwrite=False, **kwargs):\n\n self._delete_files = False\n self._readonly = False\n self._decoration = ''\n\n if 'name' not in kwargs:\n if file_name:\n kwargs['name'] = os.path.splitext(file_name)[0]\n else:\n kwargs['name'] = '_grid_'\n super().__init__(**kwargs)\n\n self._hgd = False\n self._hgd_name = None\n self._metadata = None\n self._metadata_changed = False\n self._metadata_root = ''\n self._img = None\n self._buffered_row = None\n self._buffer_np = None\n self._buffered_xy = None\n self._buffer_x = None\n self._buffer_y = None\n self._cs = None\n self._gxpg = None\n\n # build a file name\n if in_memory:\n self._file_name = None\n else:\n if (file_name is None) or (len(file_name.strip()) == 0):\n file_name = gx.gx().temp_file('.grd(GRD)')\n path, file_name, root, ext, self._decoration = name_parts(file_name)\n self._file_name = os.path.join(path, file_name)\n\n # for an HGD file work with a temporary grid, save to HGD on closing\n if mode == FILE_NEW and ext.lower() == '.hgd':\n self._hgd = True\n self._hgd_name = self._file_name\n file_name = gx.gx().temp_file('.grd(GRD)')\n path, file_name, root, ext, self._decoration = name_parts(file_name)\n self._file_name = os.path.join(path, file_name)\n\n if mode == FILE_NEW:\n if dtype is None:\n dtype = np.float64\n gxtype = gxu.gx_dtype(dtype)\n if in_memory:\n self._img = gxapi.GXIMG.create(gxtype, kx, dim[0], dim[1])\n # Need to set the kx otherwise it will be 0 and some routines (e.g. IMU stats calc) could cause aborts\n self._img.opt_kx(kx)\n else: \n if not overwrite:\n if os.path.isfile(self._file_name):\n raise GridException(_t('Cannot overwrite existing grid {}'.format(self.file_name)))\n self._img = gxapi.GXIMG.create_new_file(gxtype,\n kx, dim[0], dim[1],\n decorate_name(self._file_name, self._decoration))\n else: # open an existing grid\n\n if mode == FILE_READ:\n open_mode = gxapi.IMG_FILE_READONLY\n self._readonly = True\n else:\n mode = FILE_READWRITE\n open_mode = gxapi.IMG_FILE_READORWRITE\n self._readonly = False\n\n # always open in default type unless float or double specifically requested\n gxtype = gxapi.GS_TYPE_DEFAULT\n if dtype is not None:\n gxtype_from_dtype = gxu.gx_dtype(dtype)\n if gxtype_from_dtype in (gxapi.GS_FLOAT, gxapi.GS_DOUBLE):\n gxtype = gxtype_from_dtype\n\n self._img = gxapi.GXIMG.create_file(gxtype,\n self.file_name_decorated,\n open_mode)\n if dtype is None:\n dtype = gxu.dtype_gx(self._img.e_type())\n\n self._mode = mode\n self._next = 0\n self._next_row = 0\n self._next_col = 0\n self._gxtype = self._img.e_type()\n self._dtype = dtype\n self._dummy = gxu.gx_dummy(self._dtype)\n self._is_int = gxu.is_int(gxu.gx_dtype(self.dtype))\n self._cos_rot = self._sin_rot = None\n self.rot = self.rot # this sets _cos_rot and _sin_rot\n\n self._open = gx.track_resource(self.__class__.__name__, self._file_name)\n\n @classmethod\n def open(cls, file_name, dtype=None, mode=FILE_READ,\n coordinate_system=None, cell_size=None, expand=None):\n \"\"\"\n Open an existing grid file.\n\n :param file_name: name of the grid file, with decorations. See `supported file formats\n <https://geosoftgxdev.atlassian.net/wiki/display/GXDEV92/Grid+File+Name+Decorations>`_)\n :param dtype: numpy data type, which will be the grid data type.\n :param mode: open mode:\n\n ================= ================================================\n FILE_READ only read the file, properties cannot be changed\n FILE_READWRITE grid stays the same, but properties may change\n ================= ================================================\n\n :param coordinate_system: desired coordinate system. The grid will be reprojected if necessary.\n :param cell_size: desired cell size, defaults to the current cell size.\n :param expand: if reprojecting or resampling the are can be expanded by this percentage\n to allow for curved edges in the new coordinate system space. The default\n expands by 1%. Set to 0 to prevent expansion.\n\n If reprojecting or setting the cell size different from the original grid, the mode must be FILE_READ.\n\n If reprojecting without setting the cell size a default cell size will be calculated in the new\n coordinate system that is nominally equivalent to the current cell size.\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.4 added reprojection support\n \"\"\"\n\n grd = cls(file_name, dtype=dtype, mode=mode)\n\n # determine if we need to reproject or resample\n repro = False\n if coordinate_system:\n if not isinstance(coordinate_system, gxcs.Coordinate_system):\n coordinate_system = gxcs.Coordinate_system(coordinate_system)\n repro = coordinate_system != grd.coordinate_system\n\n if (not repro and cell_size is not None) and ((cell_size != grd.dx) or (cell_size != grd.dy)):\n repro = True\n\n if repro:\n if mode != FILE_READ:\n raise GridException(_t('Mode must be FILE_READ to reproject or resample a grid.'))\n if cell_size is None:\n cell_size = gxapi.rDUMMY\n if expand is None:\n expand = gxapi.rDUMMY\n if not coordinate_system:\n coordinate_system = grd.coordinate_system\n grd.gximg.create_projected3(coordinate_system.gxipj, cell_size, expand)\n grd._cs = None\n grd._cos_rot = 1.0\n grd._sin_rot = 0.0\n\n return grd\n\n @classmethod\n def new(cls, file_name=None, properties=None, overwrite=False, in_memory=False):\n \"\"\"\n Create a new grid file.\n\n :param file_name: name of the grid file, None for a temporary grid. See `supported file formats\n <https://geosoftgxdev.atlassian.net/wiki/display/GXDEV92/Grid+File+Name+Decorations>`_)\n :param in_memory: Creates an in-memory grid (file_name will be ignored)\n :param properties: dictionary of grid properties, see :meth:`properties`\n :param overwrite: True to overwrite existing file\n\n .. versionadded:: 9.1\n \"\"\"\n\n if properties is None:\n raise GridException(_t(\"Missing properties dictionary.\"))\n\n # set basic grid properties\n dtype = properties.get('dtype', None)\n nx = properties.get('nx', 0)\n ny = properties.get('ny', 0)\n if (nx <= 0) or (ny <= 0):\n raise GridException(_t('Grid dimension ({},{}) must be > 0').format(nx, ny))\n\n grd = cls(file_name, in_memory=in_memory, dtype=dtype, mode=FILE_NEW, dim=(nx, ny), overwrite=overwrite)\n grd.set_properties(properties)\n\n return grd\n\n @classmethod\n def minimum_curvature(cls, data,\n unit_of_measure=None,\n file_name=None, overwrite=False,\n max_segments=1000,\n coordinate_system=None,\n cs='',\n area=('', '', '', ''),\n bclip='',\n logopt='',\n logmin='',\n idsf='',\n bkd='',\n srd='',\n iwt='',\n edgclp='',\n tol='',\n pastol='100',\n itrmax='',\n ti='',\n icgr=''):\n \"\"\"\n Create a minimum-curvature surface grid from (x, y, value) located data.\n\n Reference: Smith and Wessel, 1990, Gridding with continuous curvature splines in tension.\n\n :param data: list of [(x, y, value), ...] or a callback that returns lists, or a tuple\n (gdb, value_channel, x_channel, y_channel) where x_channel and y_channel, if not\n specified, default to the current database (x, y) channels. See below.\n :param unit_of_measure: string unit of measurement descriptor.\n :param file_name: name of the grid file, None for a temporary grid. See `supported file formats\n <https://geosoftgxdev.atlassian.net/wiki/display/GXDEV92/Grid+File+Name+Decorations>`_)\n :param overwrite: True to overwrite existing file\n :param max_segments: Maximum number of line segments if using a callback, defaults to 1000.\n :param coordinate_system: coordinate system\n\n Gridding parameters follow the nomenclature of the rangrid.con file:\n https://github.com/GeosoftInc/gxc/blob/master/reference/con_files/rangrid.con\n\n :param cs: The grid cell size in reference system units.\n :param area: (xmin, ymin, xmax, ymax) - grid area, default is the data limits\n :param bclip: 0 to use all data (default), 1 to only use data in the dat area.\n :param logopt: 1 for log(value) minimum cliped to log(logmin); 2 for `logmin + log(value/logmin)` for\n postive `value`, `-logmin - log(-value/logmin` for negative `value`\n :param logmin: see `logopt`, default is 1.\n :param idsf: low-pass desampling factor in cells, default is 1. Effectively a low-pass filter that\n can smooth noisy data that has clustered locations.\n :param bkd: Blanking distance. All grid cells farther than the blanking\n distance from a valid point will be blanked in the output grid.\n The default is the nominal sample interval, i.e. sqrt(area/#data).\n This parameter should normally be set to just greater than the maximum\n sampling interval through which interpolation is desired.\n If there are too many holes in the resulting grid,\n increase appropriately.\n :param srd: The maximum search radius to use for establishing the starting\n values for the coarse grid. The default is four times the coarse\n grid size defined by `icgr`. If no data is found within the maximum\n search radius, the mean of the data is used as the starting value.\n If the search radius is too small, the starting grid can be a poor\n approximation of the desired grid, resulting in excessive processing\n time. If too large, too much time will be consumed establishing\n the original coarse grid.\n :param iwt: The weighting power to use to establish the coarse starting grid.\n The default is 2, for inverse distance squared. There is little\n reason to change this from the default.\n :param edgclp: Edge clipping parameter, the number of grid cells to extend beyond\n the outside limits of the data. The default (-1) is not to apply\n edge clipping to the blanking distanced grid.\n Use this parameter to ensure the grid does not extend too far\n beyond the actual data limits, which can occur when using a large\n blanking distance with widely spaced data.\n :param tol: The tolerance required for each grid cell. The default is 0.1\n percent of the range of the data. Decrease for a more accurate grid.\n :param pastol: The percentage of points that must meet the tolerance. The\n iteration process will stop when the percentage of points change\n by higher than this required percentage in iteration. The default\n is 100.0 percent. Decrease for rough data to reduce minimum curvature\n overshoot, and increase for a to make the grid surface more accurately\n match the data. Overshoot can also be controlled by increasing tension (ti).\n :param itrmax: Maximum number of iterations to use in solving the minimum curvature\n function. The default is 200 iterations. Increase for a more\n accurate grid. A value of 1000 is typically sufficient for maximum accuracy.\n :param ti: The degree of internal tension ( between 0 and 1 ).\n The default is no tension (0.0) which produces a true minimum\n curvature surface. Increasing tension can prevent overshooting of\n valid data in sparse areas at the expense of increased local curvature\n near data points.\n :param icgr: The course grid size relative to the final grid size. Allowable\n factors are 16,8,4,2 or 1. The default is 8. The optimum is a\n factor close to half the nominal data spacing, although in most\n situations the default is fine. This parameter effects the\n length of time it takes to find a solution.\n\n **The** `data` **parameter:**\n\n The data can be provided to the gridding algorithm either as a list array, a callback function that\n returns list array segments, or a `geosoft.gxpy.gdb.Geosoft_database` instance. In the case of a list or\n a callback, a temporary database is constructed internally.\n\n A callback is passed a sequence number, 0, 1, 2, ... and is expected to return a list array with each call\n or None when there is no more data. See the example below. When a callback is used, the `max_segments`\n parameter sets the maximum number of lines for the temporary database as each return from the\n callback will create a new line in the internal temporary database.\n\n If a database instance is passed it must be the first item in a tuple of 2 or 4 items:\n (gdb_instance, value_channel) or (gdb_instance, value_channel, x_channel, y_channel).\n In the first case the default spatial (x, y) channels in the database are assumed.\n\n Examples:\n\n .. code::\n\n import numpy as np\n import geosoft.gxpy.grid as gxgrd\n\n # simple data array\n xyv = [(45., 10., 100), (60., 25., 77.), (50., 8., 80.)]\n grid = gxgrd.Grid.minimum_curvature(xyv)\n\n # or a numpy array\n grid = gxgrd.Grid.minimum_curvature(np.array(xyv))\n\n # a database, grid to a cell size of 100\n import geosoft.gxpy.gdb as gxgdb\n gdb = gxgdb.Geosoft_database.open('some_mag_data.gdb')\n grid = gxgrd.Grid.minimum_curvature((gdb, 'tmi'), cs=100)\n\n # a callback, used for very large data, or to feed data efficiently from some other source.\n nxyv = np.array([[(45., 10., 100), (60., 25., 77.), (50., 8., 81.), (55., 11., 66.)],\n [(20., 15., 108), (25., 5., 77.), (33., 9., np.nan), (28., 2., 22.)],\n [(35., 18., 110), (40., 31., 77.), (13., 4., 83.), (44., 4., 7.)]])\n def feed_data(n):\n if n >= len(nxyv):\n return None\n return nxyv[n]\n grid = gxgrd.Grid.minimum_curvature(feed_data, cs=1.)\n\n .. versionadded:: 9.4\n \"\"\"\n\n def gdb_from_callback(callback):\n _gdb = gxgdb.Geosoft_gdb.new(max_lines=max_segments)\n channels = ('x', 'y', 'v')\n il = 0\n xyz_list = callback(il)\n while xyz_list is not None:\n _gdb.write_line('L{}'.format(il), xyz_list, channels=channels)\n il += 1\n xyz_list = callback(il)\n _gdb.xyz_channels = channels[:2]\n return _gdb\n\n def gdb_from_data(_d):\n def _data(i):\n if i == 0:\n return _d\n else:\n return None\n return gdb_from_callback(_data)\n\n # create a database from the data\n xc, yc = ('x', 'y')\n discard = False\n if callable(data):\n gdb = gdb_from_callback(data)\n vc = 'v'\n discard = True\n\n elif isinstance(data, tuple):\n gdb = data[0]\n vc = data[1]\n if len(data) == 4:\n xc = data[2]\n yc = data[3]\n else:\n xc, yc, _ = gdb.xyz_channels\n discard = True\n\n else:\n gdb = gdb_from_data(data)\n vc = 'v'\n\n if tol and float(tol) <= 0.:\n tol = 1.0e-25\n\n # parameter control file\n con_file = gx.gx().temp_file('con')\n with open(con_file, 'x') as f:\n f.write('{} / cs\\n'.format(cs))\n f.write('{},{},{},{},{} / xmin, ymin, xmax, ymax, bclip\\n'.\n format(area[0], area[1], area[2], area[3], bclip))\n f.write(',,,{},{} / ,,, logopt, logmin\\n'.format(logopt, logmin))\n f.write('{},{},{},{},{} / idsf, bkd, srd, iwt, edgeclp\\n'.format(idsf, bkd, srd, iwt, edgclp))\n f.write('{},{},{},{},{} / tol, pastol, itrmax, ti, icgr\\n'.format(tol, pastol, itrmax, ti, icgr))\n\n if file_name is None:\n file_name = gx.gx().temp_file('grd(GRD)')\n elif os.path.exists(file_name):\n if overwrite:\n gxu.delete_files_by_root(file_name)\n else:\n raise GridException(_t('Cannot overwrite existing file: {}').format(file_name))\n\n gxapi.GXRGRD.run2(gdb.gxdb, xc, yc, vc, con_file, file_name)\n\n grd = cls.open(file_name, mode=FILE_READWRITE)\n if coordinate_system is None:\n coordinate_system = gdb.coordinate_system\n grd.coordinate_system = coordinate_system\n if unit_of_measure is None:\n unit_of_measure = gxgdb.Channel(gdb, vc).unit_of_measure\n grd.unit_of_measure = unit_of_measure\n\n log_file = 'rangrid.log'\n if os.path.exists(log_file):\n gxu.delete_file(log_file)\n\n if discard:\n gdb.close(discard=True)\n\n return grd\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self._next >= self.nx * self.ny:\n self._next = 0\n raise StopIteration\n else:\n v = self.__getitem__(self._next)\n self._next += 1\n return v\n\n def __getitem__(self, item):\n\n if isinstance(item, int):\n ix = item % self.nx\n iy = item // self.nx\n else:\n ix, iy = item\n\n x, y, z = self.xyz((ix, iy))\n\n if self._buffered_row != iy:\n self._buffered_row = iy\n self._buffer_np = self.read_row(self._buffered_row).np\n\n v = self._buffer_np[ix]\n if self._is_int:\n v = int(v)\n if v == gxapi.iDUMMY:\n v = None\n elif np.isnan(v):\n v = None\n else:\n v = float(v)\n return x, y, z, v\n\n def gxpg(self, copy=False):\n \"\"\"\n Get a copy of the `geosoft.gxapi.GXPG` instance for the grid.\n\n :param copy: `True` to return a copy of the grids pager. The default is `False`, which\n returns the shared grid pager, such that changes to the pager change the grid\n and the pager is invalid when thr grid is closed or loses context.\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.4 added `copy` parameter\n \"\"\"\n\n if self._gxpg is None:\n self._gxpg = self._img.geth_pg()\n\n if copy:\n pg = gxapi.GXPG.create(self._gxpg.n_rows(), self._gxpg.n_cols(), self._gxpg.e_type())\n pg.copy(self._gxpg)\n return pg\n return self._gxpg\n\n def get_value(self, x, y):\n \"\"\"\n Return a grid value at a point as a float. For scalar data the point value will\n be interpolated between neighbors. For color data the nearest value is returned\n as a color int.\n \n :param x: X location on the grid plane \n :param y: Y location on the grid plane\n :returns: grid value, or None if outside of grid area\n \n \"\"\"\n return gxu.dummy_none(self.gximg.get_z(x, y))\n\n @classmethod\n def copy(cls, grd, file_name=None, dtype=None, overwrite=False, in_memory=False, mode=FILE_READWRITE):\n \"\"\"\n Create a new Grid instance as a copy of an existing grid.\n\n :param grd: :class:`Grid` instance to save as a new grid, or a grid file name\n :param file_name: name of the new grid (file with optional decorations). If not specified a temporary file\n is created.\n :param dtype: numpy data type, None to use type of the parent grid\n :param overwrite: True to overwrite if the file exists, False to not overwrite.\n :param in_memory: True to create a grin in memory.\n :param mode: `open` mode for working with the copy.\n\n .. versionadded:: 9.2\n \"\"\"\n\n if not isinstance(grd, Grid):\n grd = cls.open(grd, mode=FILE_READ)\n close_grid = True\n else:\n close_grid = False\n\n p = grd.properties()\n if dtype is not None:\n p['dtype'] = dtype\n\n if not in_memory and file_name is not None:\n path0, base_file0, root0, ext0, dec0 = name_parts(grd.file_name_decorated)\n path1, base_file1, root1, ext1, dec1 = name_parts(file_name)\n if not ext1:\n ext1 = ext0\n if (ext1 == ext0) and not dec1:\n dec1 = dec0\n file_name = decorate_name(os.path.join(path1, root1) + ext1, dec1)\n\n copy = cls.new(file_name, p, overwrite=overwrite, in_memory=in_memory)\n if file_name is None:\n file_name = copy.file_name_decorated\n grd.gximg.copy(copy.gximg)\n\n if close_grid:\n grd.close()\n\n if in_memory:\n return copy\n\n copy.close()\n return cls.open(file_name, dtype=dtype, mode=mode)\n\n @classmethod\n def index_window(cls, grd, name=None, x0=0, y0=0, nx=None, ny=None, overwrite=False):\n \"\"\"\n Create a windowed instance of a grid.\n \n :param grd: :class:`Grid` instance\n :param name: name for the windowed_grid, default is constructed from input grid\n :param x0: integer index of the first X point\n :param y0: integer index of the first Y point\n :param nx: number of points in x\n :param ny: number of points in y\n :param overwrite: True to overwrite existing file, default is False\n\n .. versionadded:: 9.2\n \"\"\"\n\n if not isinstance(grd, Grid):\n grd = Grid.open(grd)\n\n gnx = grd.nx\n gny = grd.ny\n if nx is None:\n nx = gnx - x0\n if ny is None:\n ny = gny - y0\n mx = x0 + nx\n my = y0 + ny\n if ((x0 >= gnx) or (y0 >= gny) or\n (x0 < 0) or (y0 < 0) or\n (nx <= 0) or (ny <= 0) or\n (mx > gnx) or (my > gny)):\n raise GridException(_t('Window x0,y0,mx,my({},{},{},{}) out of bounds ({},{})').\n format(x0, y0, mx, my, gnx, gny))\n\n if name is None:\n path, file_name, root, ext, dec = name_parts(grd.file_name_decorated)\n name = '{}_({},{})({},{}){}'.format(root, x0, y0, nx, ny, ext)\n name = decorate_name(name, dec)\n overwrite = True\n\n # create new grid\n p = grd.properties()\n p['nx'] = nx\n p['ny'] = ny\n if grd.rot == 0.0:\n p['x0'] = grd.x0 + grd.dx * x0\n p['y0'] = grd.y0 + grd.dy * y0\n else:\n dx = grd.dx * x0\n dy = grd.dy * y0\n cos, sin = grd.rotation_cos_sine\n p['x0'] = grd.x0 - dx * cos - dy * sin\n p['y0'] = grd.y0 - dy * cos + dx * sin\n\n window_grid = cls.new(name, p, overwrite=overwrite)\n source_pager = grd.gxpg(copy=False)\n window_pager = window_grid.gxpg(copy=False)\n window_pager.copy_subset(source_pager, 0, 0, y0, x0, ny, nx)\n\n return window_grid\n\n @classmethod\n def from_data_array(cls, data, file_name=None, properties=None, overwrite=False):\n \"\"\"\n Create grid from a 2D data array or `geosoft.gxapi.GXPG`.\n\n :param data: 2D numpy data array, a 2d list, ir a `geosoft.gxapi.GXPG`.\n :param file_name: name of the file, default creates a temporary file name\n :param properties: grid properties as a dictionary\n :param overwrite: `True` to overwrite existing grid.\n :returns: :class:`Grid` instance\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.4 - support for default temporary file name and creation from a GXPG.\n \"\"\"\n\n if isinstance(data, gxapi.GXPG):\n if data.n_slices() != 1:\n raise GridException(_t('Pager must be 2D'))\n nx = data.n_cols()\n ny = data.n_rows()\n dtype = gxu.dtype_gx(data.e_type())\n\n else:\n if not isinstance(data, np.ndarray):\n data = np.array(data)\n ny, nx = data.shape\n dtype = data.dtype\n\n if properties is None:\n properties = {}\n properties['nx'] = nx\n properties['ny'] = ny\n properties['dtype'] = dtype\n\n if (file_name is None) or (len(file_name.strip()) == 0):\n file_name = gx.gx().temp_file('.grd(GRD)')\n\n grd = cls.new(file_name, properties=properties, overwrite=overwrite)\n grd.write_rows(data)\n\n return reopen(grd)\n\n @property\n def is_crooked_path(self):\n \"\"\"True if this grid follows a crooked path section.\"\"\"\n return self.coordinate_system.gxipj.get_orientation() == gxapi.IPJ_ORIENT_SECTION_CROOKED\n\n def crooked_path(self):\n \"\"\"\n Return the `CrookedPath` instance for a crooked-path grid.\n\n .. versionadded::9.4\n \"\"\"\n if not self.is_crooked_path:\n raise GridException(_t(\"This is not a crooked-path section grid.\"))\n return gxview.CrookedPath(self.coordinate_system)\n\n @property\n def rotation_cos_sine(self):\n \"\"\"\n Returns grid rotation (cosine, sine).\n\n .. versionadded:: 9.3.1\n \"\"\"\n return self._cos_rot, self._sin_rot\n\n def delete_files(self, delete=True):\n \"\"\"\n Delete the files associated with this grid when deleting the grid object.\n Note that files are not deleted until all references to this object are\n deleted and garbage collection is performed.\n\n :param delete: set to False to reverse a previous delete request\n\n .. versionadded:: 9.1\n \"\"\"\n self._delete_files = delete\n\n @property\n def remove_on_close(self):\n \"\"\"Remove files on close setting, can be set.\"\"\"\n return self._delete_files\n \n @remove_on_close.setter\n def remove_on_close(self, tf):\n self._delete_files = bool(tf)\n\n def close(self, discard=False):\n \"\"\"\n Close the grid and release all instance resources.\n\n :param discard: `True` to discard associated files on close\n\n .. versionchanged:: 9.4 added `discard` parameter\n \"\"\"\n if discard:\n self.delete_files()\n self._close()\n\n @property\n def dummy_value(self):\n \"\"\" Return the grid data dummy value.\"\"\"\n return self._dummy\n\n @property\n def gximg(self):\n \"\"\" The `geosoft.gxapi.GXIMG` instance handle.\"\"\"\n return self._img\n\n def _init_metadata(self):\n if not self._metadata:\n self._metadata = gxu.geosoft_metadata(self._file_name)\n self._metadata_root = tuple(self._metadata.items())[0][0]\n\n @property\n def metadata(self):\n \"\"\"\n Return the grid metadata as a dictionary. Can be set, in which case\n the dictionary items passed will be added to, or replace existing metadata.\n \n .. seealso::\n `Geosoft metadata schema <https://geosoftgxdev.atlassian.net/wiki/display/GXDEV92/Geosoft+Metadata+Schema>`_ \n\n .. versionadded:: 9.2\n \"\"\"\n self._init_metadata()\n return self._metadata[self._metadata_root]\n\n @metadata.setter\n def metadata(self, meta):\n self._init_metadata()\n self._metadata[self._metadata_root] = gxu.merge_dict(self._metadata[self._metadata_root], meta)\n self._metadata_changed = True\n\n @property\n def unit_of_measure(self):\n \"\"\"\n Units of measurement (a string) for the grid data, can be set.\n \n .. versionadded:: 9.2\n \"\"\"\n try:\n uom = self.metadata['geosoft']['dataset']['geo:unitofmeasurement']['#text']\n except (KeyError, TypeError):\n uom = ''\n return uom\n\n @unit_of_measure.setter\n def unit_of_measure(self, uom):\n self.metadata = {'geosoft':\n {'@xmlns': 'http://www.geosoft.com/schema/geo',\n 'dataset':\n {'geo:unitofmeasurement':\n {'@xmlns:geo': 'http://www.geosoft.com/schema/geo',\n '#text': str(uom)}}}}\n\n @property\n def dtype(self):\n \"\"\"\n numpy data type for the grid\n\n .. versionadded:: 9.2\n \"\"\"\n return self._dtype\n\n @property\n def gxtype(self):\n \"\"\"\n Geosoft data type for the grid\n\n .. versionadded:: 9.2\n \"\"\"\n return self._gxtype\n\n @property\n def is_int(self):\n \"\"\" returns True if base grid type is integer, which includes color integers\"\"\"\n return self._is_int\n\n @property\n def nx(self):\n \"\"\"\n grid x dimension (number of columns)\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.nx()\n\n @property\n def ny(self):\n \"\"\"\n grid y dimension (number of rows)\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.ny()\n\n @property\n def x0(self):\n \"\"\"\n grid origin x location in the plane coordinate system\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.query_double(gxapi.IMG_QUERY_rXO)\n\n @property\n def y0(self):\n \"\"\"\n grid origin y location in the plane coordinate system\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.query_double(gxapi.IMG_QUERY_rYO)\n\n @property\n def dx(self):\n \"\"\"\n separation between grid points in the grid x direction\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.query_double(gxapi.IMG_QUERY_rDX)\n\n @property\n def dy(self):\n \"\"\"\n separation between grid points in the grid y direction\n\n .. versionadded:: 9.2\n \"\"\"\n return self._img.query_double(gxapi.IMG_QUERY_rDY)\n\n @property\n def rot(self):\n \"\"\"\n grid rotation angle, degrees azimuth\n \n Note that grid rotations in the gxapi GXIMG are degrees clockwise, which is the opposite of\n degree azimuth, used here. All horizontal plane angles in the Python gxpy module are degrees\n azimuth for consistency.\n\n .. versionadded:: 9.2\n \"\"\"\n return -self._img.query_double(gxapi.IMG_QUERY_rROT)\n\n @property\n def is_color(self):\n \"\"\" returns True if grid contains colors. is_int will also be True\"\"\"\n return bool(self._img.is_colour())\n\n @property\n def file_name(self):\n \"\"\"\n grid file name without decorations\n\n .. versionadded:: 9.2\n \"\"\"\n if self._hgd:\n return self._hgd_name\n return self._file_name\n\n @property\n def file_name_decorated(self):\n \"\"\"\n grid file name with decorations\n\n .. versionadded:: 9.2\n \"\"\"\n if self._hgd:\n decor = 'HGD'\n else:\n decor = self._decoration\n return decorate_name(self.file_name, decor)\n\n @property\n def name(self):\n \"\"\"\n Grid name, usually the file name without path or extension.\n \n .. versionadded:: 9.2\n \"\"\"\n if self._file_name is None:\n return 'None'\n basename = os.path.basename(self.file_name)\n return os.path.splitext(basename)[0]\n\n @property\n def gridtype(self):\n \"\"\"\n grid type (e.g. 'GRD', 'HGD' etc. 'MEMORY' for in-memory grid)\n\n .. versionadded:: 9.2\n \"\"\"\n if self._file_name is None:\n return 'MEMORY'\n _, _, _, ext, dec = name_parts(self._file_name)\n if len(dec) > 0:\n return dec.split(';')[0]\n else:\n return ext[1:].upper()\n\n @property\n def decoration(self):\n \"\"\"\n grid descriptive decoration\n\n .. versionadded:: 9.2\n \"\"\"\n return self._decoration\n\n @property\n def coordinate_system(self):\n \"\"\"\n grid coordinate system as a :class:`geosoft.gxpy.coordinate_system.Coordinate_system` instance.\n\n Can be set from any :class:`geosoft.gxpy.coordinate_system.Coordinate_system` constructor.\n\n .. versionadded:: 9.2\n\n .. versionchanged:: 9.3\n added ability to set directly\n \"\"\"\n if self._cs is None:\n ipj = gxapi.GXIPJ.create()\n self._img.get_ipj(ipj)\n self._cs = gxcs.Coordinate_system(ipj)\n\n return self._cs\n\n @coordinate_system.setter\n def coordinate_system(self, cs):\n self._cs = gxcs.Coordinate_system(cs)\n self._img.set_ipj(self._cs.gxipj)\n\n def properties(self):\n \"\"\"\n Get the grid properties dictionary\n\n :returns: dictionary of all grid properties\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.4 added 'unit_of_measure'\n \"\"\"\n\n properties = {'nx': self.nx,\n 'ny': self.ny,\n 'x0': self.x0,\n 'y0': self.y0,\n 'dx': self.dx,\n 'dy': self.dy,\n 'rot': self.rot,\n 'is_color': self.is_color,\n 'dtype': self.dtype,\n 'gridtype': self.gridtype,\n 'decoration': self._decoration,\n 'unit_of_measure': self.unit_of_measure,\n 'coordinate_system': self.coordinate_system}\n\n return properties\n\n def statistics(self, gxst=None):\n \"\"\"\n Calculate and return current grid data statistics as a dictionary.\n\n :param gxst: gxapi.GXST instance, to which stats will be accumulated, or None.\n\n :returns: dictionary of grid data statistics:\n\n =============== ============================\n min minimum\n max maximum\n mean mean\n geometric_mean geometric mean\n variance variance\n sd standard deviation\n skew skew\n kurtosis kurtosis\n sum sum of all data\n sum_power_2 sum of data**2\n sum_power_3 sum of data**3\n sum_power_4 sum of data**4\n num_data number of valid data values\n num_dummy number of dummy values\n =============== ============================\n\n .. versionadded:: 9.4\n \"\"\"\n\n def get_st(what):\n v = gxst.get_info(what)\n if v == gxapi.rDUMMY:\n return None\n return v\n\n if gxst is None:\n gxst = gxapi.GXST.create()\n vv = gxvv.GXvv()\n for iv in range(self.gximg.nv()):\n self.gximg.read_v(iv, 0, 0, vv.gxvv)\n gxst.data_vv(vv.gxvv)\n\n st = {'min': get_st(gxapi.ST_MIN),\n 'max': get_st(gxapi.ST_MAX),\n 'mean': get_st(gxapi.ST_MEAN),\n 'geometric_mean': get_st(gxapi.ST_GEOMEAN),\n 'variance': get_st(gxapi.ST_VARIANCE),\n 'sd': get_st(gxapi.ST_STDDEV),\n 'skew': get_st(gxapi.ST_SKEW),\n 'kurtosis': get_st(gxapi.ST_KURTOSIS),\n 'sum': get_st(gxapi.ST_SUM),\n 'sum_power_2': get_st(gxapi.ST_SUM2),\n 'sum_power_3': get_st(gxapi.ST_SUM3),\n 'sum_power_4': get_st(gxapi.ST_SUM4),\n 'num_data': get_st(gxapi.ST_ITEMS),\n 'num_dummy': get_st(gxapi.ST_DUMMIES)\n }\n\n return st\n\n @x0.setter\n def x0(self, v):\n self._img.set_info(self.dx, self.dy, v, self.y0, -self.rot)\n\n @y0.setter\n def y0(self, v):\n self._img.set_info(self.dx, self.dy, self.x0, v, -self.rot)\n\n @dx.setter\n def dx(self, v):\n self._img.set_info(v, self.dy, self.x0, self.y0, -self.rot)\n\n @dy.setter\n def dy(self, v):\n self._img.set_info(self.dx, v, self.x0, self.y0, -self.rot)\n\n @rot.setter\n def rot(self, v):\n self._img.set_info(self.dx, self.dy, self.x0, self.y0, -v)\n self._cos_rot = math.cos(math.radians(v))\n self._sin_rot = math.sin(math.radians(v))\n\n def set_properties(self, properties):\n \"\"\"\n Set grid properties from a properties dict. Settable property keys are:\n\n ==================== ============================================\n 'x0' grid X origin location (default 0.0)\n 'y0' grid Y origin location (0.0)\n 'dx' grid X point separation (1.0)\n 'dy' grid Y point separation (1.0)\n 'rot' grid rotation angle in degrees azimuth (0.0)\n 'unit_of_measure' unit of measure for the grid data\n 'coordinate_system' coordinate system (unchanged)\n ==================== ============================================\n\n Not all keys need be passed, though typically one will get the properties from\n the grid and modify those that need to change and pass the properties back.\n\n :param properties: properties dictionary\n\n .. versionadded:: 9.1\n \"\"\"\n\n if self._readonly:\n raise GridException(_t('{} opened as read-only, cannot set properties.').format(self.file_name_decorated))\n\n dx = properties.get('dx', 1.0)\n dy = properties.get('dy', dx)\n self._img.set_info(dx, dy,\n properties.get('x0', 0.0),\n properties.get('y0', 0.0),\n -properties.get('rot', 0.0))\n self.rot = self.rot # calculates cos and sin\n\n uom = properties.get('unit_of_measure', None)\n if uom is not None:\n self.unit_of_measure = uom\n\n cs = properties.get('coordinate_system', None)\n if cs is not None:\n if not isinstance(cs, gxcs.Coordinate_system):\n cs = gxcs.Coordinate_system(cs)\n self._img.set_ipj(cs.gxipj)\n\n def write_rows(self, data, ix0=0, iy0=0, order=1):\n \"\"\"\n Write data to a grid by rows.\n\n :param data: array of data to write, numpy, list or `geosoft.gxapi.GXPG`\n :param ix0: grid X index of first point\n :param iy0: grid Y index of first point, top index if writing rows top to bottom\n :param order: 1: bottom to top; -1: top to bottom\n\n .. versionadded:: 9.1\n\n .. versionchanged:: 9.4 accepts list or GXPG\n \"\"\"\n\n if isinstance(data, gxapi.GXPG):\n nx = data.n_cols()\n ny = data.n_rows()\n\n else:\n if not isinstance(data, np.ndarray):\n data = np.array(data)\n ny, nx = data.shape\n\n if ((nx - ix0) > self.nx) or ((ny - iy0) > self.ny):\n raise GridException(_t('Data size exceeds grid size.'))\n\n dvv = gxvv.GXvv(dtype=self.dtype)\n dvv.length = nx\n iy = iy0\n\n for i in range(ny):\n if isinstance(data, gxapi.GXPG):\n data.read_row(i, 0, 0, dvv.gxvv)\n else:\n dvv.set_data(data[i, :])\n self._img.write_y(iy, ix0, 0, dvv.gxvv)\n iy += order\n\n def read_row(self, row=None, start=0, length=None):\n \"\"\"\n\n :param row: row to read, if not specified the next row is read starting from row 0\n :param start: the first point in the row, default is 0\n :param length: number of points to read, the default is to the end of the row.\n :return: :class:`geosoft.gxvv.GXvv` instance\n\n .. versionadded:: 9.1\n \"\"\"\n\n if row is None:\n row = self._next_row\n self._next_row = row + 1\n if self._next_row == self.ny:\n self._next_row = 0\n\n if row >= self.ny:\n raise GridException(_t('Attempt to read row {} past the last row {}'.format(row, self.ny)))\n vv = gxvv.GXvv(dtype=self.dtype)\n if length is None:\n length = 0\n self._img.read_y(row, start, length, vv.gxvv)\n\n return vv\n\n def read_column(self, column=None, start=0, length=0):\n \"\"\"\n\n :param column: column to read, if not specified the next column is read starting from column 0\n :param start: the first point in the column, default is 0\n :param length: number of points to read, the default is to the end of the col.\n :return: :class:`geosoft.gxvv.GXvv` instance\n\n .. versionadded:: 9.1\n \"\"\"\n\n if column is None:\n column = self._next_col\n if column >= self.nx:\n raise GridException(_t('Attempt to read column {} past the last column {}'.format(column, self.ny)))\n self._next_col = column + 1\n if self._next_col == self.nx:\n self._next_col = 0\n\n vv = gxvv.GXvv(dtype=self.dtype)\n self._img.read_x(column, start, length, vv.gxvv)\n\n return vv\n\n def write_row(self, data, row=None, start=0, length=None):\n \"\"\"\n\n :param data: data to write, `geosoft.gxpy.vv.GXvv` instance or an array\n :param row: row to write, if not specified the next row is written starting from row 0\n :param start: the first point in the row, default is 0\n :param length: number of points to read, the default is to the end of the row.\n\n .. versionadded:: 9.4\n \"\"\"\n\n if not isinstance(data, gxvv.GXvv):\n data = gxvv.GXvv(data, dtype=self.dtype)\n\n if row is None:\n row = self._next_row\n self._next_row = row + 1\n if self._next_row == self.ny:\n self._next_row = 0\n\n if row >= self.ny:\n raise GridException(_t('Attempt to read row {} past the last row {}'.format(row, self.ny)))\n if length is None:\n length = 0\n self._img.write_y(row, start, length, data.gxvv)\n\n def write_column(self, data, column=None, start=0, length=None):\n \"\"\"\n\n :param data: data to write, `geosoft.gxpy.vv.GXvv` instance or an array\n :param column: column to write, if not specified the next column is written starting from column 0\n :param start: the first point in the column, default is 0\n :param length: number of points to write, the default is to the end of the row.\n\n .. versionadded:: 9.4\n \"\"\"\n\n if not isinstance(data, gxvv.GXvv):\n data = gxvv.GXvv(data, dtype=self.dtype)\n\n if column is None:\n column = self._next_col\n self._next_col = column + 1\n if self._next_col == self.nx:\n self._next_col = 0\n\n if column >= self.nx:\n raise GridException(_t('Attempt to read column {} past the last column {}'.format(column, self.nx)))\n if length is None:\n length = 0\n self._img.write_x(column, start, length, data.gxvv)\n\n def reset_read_write(self):\n \"\"\" Reset the default read/write to the grid row 0, column 0. \"\"\"\n self._next = self._next_col = self._next_row = 0\n\n @staticmethod\n def name_parts(name):\n \"\"\"\n .. deprecated:: 9.2 use gxpy.grid.name_parts()\n \"\"\"\n return name_parts(name)\n\n @staticmethod\n def decorate_name(name, decorations=''):\n \"\"\"\n .. deprecated:: 9.2 use gxpy.grid.name_parts()\n \"\"\"\n return decorate_name(name, decorations)\n\n def indexWindow(self, name, x0=0, y0=0, nx=None, ny=None):\n \"\"\"\n .. deprecated:: 9.2 gxpy.Grid.index_window()\n \"\"\"\n return self.index_window(self, name, x0, y0, nx, ny, overwrite=True)\n\n def xy_from_index(self, ix, iy):\n \"\"\"\n Return the rotated location of grid index ix, iy\n\n :param ix: grid index x\n :param iy: grid index y\n\n .. versionadded:: 9.4\n \"\"\"\n\n def rotate(x, y):\n x -= self.x0\n y -= self.y0\n _x = x * self._cos_rot + y * self._sin_rot\n _y = -x * self._sin_rot + y * self._cos_rot\n return _x + self.x0, _y + self.y0\n\n x = self.x0 + (ix * self.dx)\n y = self.y0 + (iy * self.dy)\n if self.rot != 0.:\n return rotate(x, y)\n return x, y\n\n def extent_2d(self):\n \"\"\"\n Return the 2D extent of the grid on the grid plane.\n\n Extent is to the outer edge of grid \"cells\", which extend half a cell beyond the edge points.\n\n :returns:(min_x, min_y, max_x, max_y)\n\n .. versionadded:: 9.2\n\n .. versionchanged:: 9.4 - extent to the cell edges.\n \"\"\"\n\n x0, y0 = self.xy_from_index(-0.5, -0.5)\n x1, y1 = self.xy_from_index(self.nx - 0.5, self.ny - 0.5)\n\n if self.rot != 0.:\n xx0, yy0 = self.xy_from_index(self.nx - 0.5, -0.5)\n xx1, yy1 = self.xy_from_index(-0.5, self.ny - 0.5)\n min_x = min(x0, xx0, x1, xx1)\n min_y = min(y0, yy0, y1, yy1)\n max_x = max(x0, xx0, x1, xx1)\n max_y = max(y0, yy0, y1, yy1)\n return min_x, min_y, max_x, max_y\n\n return x0, y0, x1, y1\n\n def extent_point_2d(self):\n \"\"\"\n Return the 2D extent of the grid point (cell centers) on the grid plane.\n\n :returns:(min_x, min_y, max_x, max_y)\n\n .. versionadded:: 9.4\n \"\"\"\n\n x0, y0 = self.x0, self.y0\n x1, y1 = self.xy_from_index(self.nx - 1, self.ny - 1)\n\n if self.rot != 0.:\n xx0, yy0 = self.xy_from_index(self.nx - 1, 0)\n xx1, yy1 = self.xy_from_index(0, self.ny - 1)\n min_x = min(x0, xx0, x1, xx1)\n min_y = min(y0, yy0, y1, yy1)\n max_x = max(x0, xx0, x1, xx1)\n max_y = max(y0, yy0, y1, yy1)\n return min_x, min_y, max_x, max_y\n\n return x0, y0, x1, y1\n\n def extent_cell_2d(self):\n \"\"\"\n .. deprecated:: 9.4 - same as `extent_2d()`\n \"\"\"\n return self.extent_2d()\n\n def extent_3d(self):\n \"\"\"\n Return the 3D extent of the grid in the base coordinate system.\n\n :returns: (min_x, min_y, min_z, max_x, max_y, max_z)\n\n .. versionadded:: 9.2\n \"\"\"\n\n cs = self.coordinate_system\n ex2d = self.extent_2d()\n if self.is_crooked_path:\n min_x, min_y, max_x, max_y = self.crooked_path().extent_xy\n min_z = cs.xyz_from_oriented((ex2d[0], ex2d[1], 0.0))[2]\n max_z = cs.xyz_from_oriented((ex2d[0], ex2d[3], 0.0))[2]\n\n else:\n xyz0 = cs.xyz_from_oriented((ex2d[0], ex2d[1], 0.0))\n xyz1 = cs.xyz_from_oriented((ex2d[2], ex2d[1], 0.0))\n xyz2 = cs.xyz_from_oriented((ex2d[2], ex2d[3], 0.0))\n xyz3 = cs.xyz_from_oriented((ex2d[0], ex2d[3], 0.0))\n\n min_x = min(xyz0[0], xyz1[0], xyz2[0], xyz3[0])\n min_y = min(xyz0[1], xyz1[1], xyz2[1], xyz3[1])\n min_z = min(xyz0[2], xyz1[2], xyz2[2], xyz3[2])\n max_x = max(xyz0[0], xyz1[0], xyz2[0], xyz3[0])\n max_y = max(xyz0[1], xyz1[1], xyz2[1], xyz3[1])\n max_z = max(xyz0[2], xyz1[2], xyz2[2], xyz3[2])\n\n return min_x, min_y, min_z, max_x, max_y, max_z\n\n def extent_cell_3d(self):\n \"\"\"\n .. deprecated:: 9.4 - same as `extent_3d()`\n \"\"\"\n return self.extent_3d()\n\n @property\n def extent(self):\n \"\"\"\n Grid cell extent as `geosoft.gxpy.geometry.Point2`.\n\n .. versionadded:: 9.3.1\n \"\"\"\n return gxgm.Point2((self.extent_3d()), coordinate_system=self.coordinate_system)\n\n def np(self, dtype=None):\n \"\"\"\n Return a numpy array of grid values in the working dtype.\n\n :param dtype: desired data type, default is the work_dtype, ignored for color grids\n\n :returns: numpy array shape (nx, ny) or (nx, ny, 4) containing RGBA bytes in case of color grids\n\n .. versionadded:: 9.3.1\n \"\"\"\n\n nx = self.nx\n ny = self.ny\n if self.is_color:\n data = np.zeros((ny, nx, 4), np.dtype(np.uint8))\n else:\n if dtype is None:\n dtype = self.dtype\n data = np.zeros((ny, nx), dtype=dtype)\n if self.gximg.query_kx() == -1:\n for i in range(self.nx):\n column = self.read_column(i).np\n if self.is_color:\n column = _transform_color_int_to_rgba(column)\n data[:, i] = column\n else:\n for i in range(self.ny):\n row = self.read_row(i).np\n if self.is_color:\n row = _transform_color_int_to_rgba(row)\n data[i, :] = row\n\n return data\n\n def xyzv(self):\n \"\"\"\n Return a numpy float array of (x, y, z, v) grid points.\n\n x, y, z) is the location of each grid point in 3D space and v is the grid value at that location.\n Dummies will be numpy.nan.\n\n :returns: numpy array shape (nx, ny, 4)\n\n .. versionadded:: 9.2\n \"\"\"\n\n nx = self.nx\n ny = self.ny\n dx = self.dx\n dy = self.dy\n cs = self.coordinate_system\n xyzv = np.zeros((ny, nx, 4))\n xyzv[:, :, 0:2] = np.mgrid[0: (nx - 0.5) * dx: dx, 0: (ny - 0.5) * dy: dy].swapaxes(0, 2)\n\n if self.rot != 0.:\n x = xyzv[:, :, 0]\n cosx = x * self._cos_rot\n sinx = x * self._sin_rot\n y = xyzv[:, :, 1]\n cosy = y * self._cos_rot\n siny = y * self._sin_rot\n xyzv[:, :, 0] = cosx + siny\n xyzv[:, :, 1] = cosy - sinx\n\n xyzv += (self.x0, self.y0, 0, 0)\n\n if cs.is_oriented:\n xyzv[:, :, :3] = cs.xyz_from_oriented(xyzv[:, :, :3].reshape((-1, 3))).reshape((ny, nx, 3))\n\n if self.gximg.query_kx() == -1:\n for i in range(self.nx):\n xyzv[:, i, 3] = self.read_column(i).np\n else:\n for i in range(self.ny):\n xyzv[i, :, 3] = self.read_row(i).np\n\n return xyzv\n\n def xyz(self, item):\n \"\"\"\n Returns the (x, y, z) location of an indexed point in the grid.\n\n :param item: tuple (ix, iy) grid point, or the point number counting by row\n :return: tuple (x, y, z) location\n\n .. versionadded:: 9.2.1\n \"\"\"\n\n if isinstance(item, int):\n ix = item % self.nx\n iy = item // self.nx\n else:\n ix, iy = item\n\n if self._buffered_xy != iy:\n self._buffered_xy = iy\n self._buffer_x = np.arange(self.nx, dtype=np.float64)\n self._buffer_x *= self.dx\n self._buffer_y = np.zeros(self.nx, dtype=np.float64)\n self._buffer_y += iy * self.dy\n\n if self.rot != 0.:\n rx = self._buffer_x * self._cos_rot + self._buffer_y * self._sin_rot\n self._buffer_y *= self._buffer_y * self._cos_rot\n self._buffer_y -= self._buffer_x * self._sin_rot\n self._buffer_x = rx\n\n self._buffer_x += self.x0\n self._buffer_y += self.y0\n\n ggx = self._buffer_x[ix]\n ggy = self._buffer_y[ix]\n ggz = 0.\n\n if self.coordinate_system.is_oriented:\n ggx, ggy, ggz = self.coordinate_system.xyz_from_oriented((ggx, ggy, ggz))\n\n return ggx, ggy, ggz\n\n def image_file(self, image_file_name=None, image_type=gxmap.RASTER_FORMAT_PNG, pix_width=None,\n shade=False, color_map=None, contour=None, display_area=None, pix_32_bit=False):\n \"\"\"\n Save as a georeferenced image file.\n\n :param image_file_name: image file name. The extension should be consistent with the image_type.\n If not specified a temporary PNG file is created.\n :param image_type: image type, one ot the RASTER_FORMAT constants in `geosoft.gxpy.map`.\n :param pix_width: desired image width in pixels, default is the width of the aggregate base layer\n :param shade: `True` to add shading effect\n :param color_map: `geosoft.gxpy.group.Color_map` instance, or a colour ramp file name,\n default is grid's default\n :param contour: colour contour interval if colours need to break at exact levels\n :param display_area: `geosoft.gxpy.geometry.Point2` instance, which defines the desired display\n area. The display area coordinate system can be different from the grid.\n :param pix_32_bit: make 32-bit image (with 8-bit alpha background)\n :return: image file name.\n\n .. seealso:: `geosoft.gxpy.grid.image_file`, which creates an image directly from a grid file.\n\n .. Note:: Unless read-only this method saves the grid as a temporary file from which an aggregate and image are\n created. If the grid already exists as a grid file it is more efficient to call\n `geosoft.gxpy.grid.image_file`.\n\n .. versionadded:: 9.3.1\n \"\"\"\n\n temp_grid = gx.gx().temp_file('grd')\n try:\n if self._mode == FILE_READ and self._file_name is not None:\n grd_decorated = self.file_name_decorated\n else:\n with self.__class__.copy(self, temp_grid) as g:\n grd_decorated = g.file_name_decorated\n\n if color_map is None:\n color_map = self.get_default_color_map()\n\n imagefile = image_file(grd_decorated,\n image_file=image_file_name,\n image_type=image_type,\n pix_width=pix_width,\n shade=shade,\n color_map=color_map,\n contour=contour,\n display_area=display_area,\n pix_32_bit=pix_32_bit)\n finally:\n delete_files(temp_grid)\n\n return imagefile\n\n def generate_color_map(self, method=gxapi.ITR_ZONE_DEFAULT):\n \"\"\"\n Generate color map for grid based on statistics and method\n\n :param method: :ref:`ITR_ZONE`\n :return: A `geosoft.gxpy.group.Color_map` instance.\n\n .. versionadded:: 9.4.0\n \"\"\"\n itr = gxapi.GXITR.create_img(self._img, \"\", method, gxapi.rDUMMY)\n return geosoft.gxpy.group.Color_map(itr)\n\n def get_default_color_map(self):\n \"\"\"\n Get default color map for grid\n\n :return: A `geosoft.gxpy.group.Color_map` instance.\n\n .. versionadded:: 9.4.0\n \"\"\"\n itr = gxapi.GXITR.create()\n if 1 == self._img.get_def_itr(itr):\n return self.generate_color_map()\n\n return geosoft.gxpy.group.Color_map(itr)\n\n\n def mask(self, mask):\n \"\"\"\n Mask against blank areas in `mask` grid. Both grids must be same dimension.\n\n :param mask: reference mask grid, file of `Grid` instance.\n\n .. versionadded:: 9.4\n \"\"\"\n\n if not isinstance(mask, Grid):\n mask = Grid.open(mask)\n\n if (self.nx != mask.nx or self.ny != mask.ny):\n raise GridException(_t('Grids dimensions do not match'))\n\n for row in range(self.ny):\n mr = self.read_row(row)\n mr.gxvv.mask(mask.read_row(row).gxvv)\n self.write_row(mr, row)\n\n\n# grid utilities\ndef array_locations(properties):\n \"\"\"\n Create an array of (x,y,z) points for a grid defined by properties\n :param properties: grid properties\n :returns: array of points, shaped (ny, nx, 3)\n\n .. versionadded:: 9.1\n \"\"\"\n\n with Grid.new(properties=properties) as g:\n return g.xyzv()[:, :, :3]\n\n\ndef gridMosaic(*args, **kwargs):\n \"\"\"\n .. deprecated:: 9.2 use :py:method: grid_mosaic\n \"\"\"\n return grid_mosaic(*args, **kwargs)\n\n\ndef grid_mosaic(*args, **kwargs):\n \"\"\"\n .. deprecated:: 9.4 use `geosoft.gxpy.grid_utility.grid_mosaic`\n \"\"\"\n\n\ndef gridBool(*args, **kwargs):\n \"\"\"\n .. deprecated:: 9.2 use `grid_bool`\n \"\"\"\n return grid_bool(*args, **kwargs)\n\n\ndef grid_bool(*args, **kwargs):\n \"\"\"\n .. deprecated:: 9.4 use `geosoft.gxpy.grid_utility.grid_bool`\n \"\"\"\n return gxgrdu.grid_bool(*args, **kwargs)\n\n\ndef figure_map(grid_file, map_file=None, shade=True, color_map=None, contour=None, **kwargs):\n \"\"\"\n Create a map figure from a grid file.\n\n :param grid_file: grid file name\n :param map_file: name of the map file, if `None` a default map is created.\n :param shade: `True` to add shading effect\n :param color_map: `geosoft.gxpy.group.Color_map` instance, or a colour ramp file name, default is user's default\n :param contour: colour contour interval if colours need to break at exact levels\n :param kwargs: passed to `geosoft.gxpy.agg.Aggregate_image.figure_map` and `geosoft.gxpy.map.Map.new`\n :return: `geosoft.gxpy.map.Map` instance\n\n .. versionadded:: 9.3\n \"\"\"\n\n with gxagg.Aggregate_image.new(grid_file, shade=shade, color_map=color_map, contour=contour) as agg:\n return agg.figure_map(file_name=map_file, **kwargs)\n\n\ndef image_file(grid_file, image_file=None, image_type=gxmap.RASTER_FORMAT_PNG, pix_width=None,\n shade=True, color_map=None, contour=None, display_area=None, pix_32_bit=False):\n \"\"\"\n Save a grid file grid as a georeferenced image file.\n\n :param grid_file: grid file name\n :param image_file: image file name. The extension should be consistent with the image_type.\n If not specified a temporary PNG file is created.\n :param image_type: image type, one ot the RASTER_FORMAT constants in `geosoft.gxpy.map`.\n :param pix_width: desired image width in pixels, default is the width of the aggregate base layer\n :param shade: `True` to add shading effect\n :param color_map: `geosoft.gxpy.group.Color_map` instance, or a colour ramp file name, default is grid's default\n :param contour: colour contour interval if colours need to break at exact levels\n :param display_area: `geosoft.gxpy.geometry.Point2` instance, which defines the desired display\n area. The display area coordinate system can be different from the grid.\n :param pix_32_bit: make 32-bit image (with 8-bit alpha background)\n\n :return: image file name.\n\n .. versionadded:: 9.3.1\n \"\"\"\n\n if color_map is None:\n with Grid.open(grid_file) as g:\n color_map = g.get_default_color_map()\n\n with gxagg.Aggregate_image.new(grid_file, shade=shade, color_map=color_map, contour=contour) as agg:\n return agg.image_file(image_file, image_type=image_type, pix_width=pix_width,\n display_area=display_area, pix_32_bit=pix_32_bit)\n" ]
[ [ "numpy.nanmax", "numpy.isnan", "numpy.nanmin", "numpy.nanmean", "numpy.nanstd", "numpy.array" ], [ "numpy.ascontiguousarray" ], [ "numpy.right_shift", "numpy.isnan", "numpy.arange", "numpy.dtype", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
konstin/jax
[ "f7df3ee9c4221a202959e67816d485c35eb98102", "c3581a221842c09dc1b2f301012c3a01734f6b43" ]
[ "tests/filecheck/math.filecheck.py", "jax/experimental/sparse/bcoo.py" ]
[ "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Tests for lowerings of elementwise ops to MHLO.\n\n# RUN: %PYTHON %s | FileCheck %s\n\nfrom absl import app\nfrom functools import partial\n\nimport jax\nfrom jax import numpy as jnp\nfrom jax import lax\nimport numpy as np\n\nfrom jax.tests.filecheck.jax_filecheck_helpers import print_ir\n\njax.config.update(\"jax_enable_mlir\", True)\njax.config.update(\"jax_enable_x64\", True)\n\n\ndef main(_):\n # CHECK-LABEL: TEST: abs int32[]\n # CHECK: mhlo.abs\n # CHECK-SAME: tensor<i32>\n print_ir(np.int32(0))(lax.abs)\n\n # CHECK-LABEL: TEST: add float32[] float32[]\n # CHECK: mhlo.add\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.add)\n\n # CHECK-LABEL: TEST: acos float32[]\n # CHECK: mhlo.atan2\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1))(lax.acos)\n\n # CHECK-LABEL: TEST: acosh float32[]\n # CHECK: xla_fallback_acosh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.acosh)\n\n # CHECK-LABEL: TEST: asin float32[]\n # CHECK: mhlo.atan2\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1))(lax.asin)\n\n # CHECK-LABEL: TEST: asinh float32[]\n # CHECK: xla_fallback_asinh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.asinh)\n\n # CHECK-LABEL: TEST: atan float32[]\n # CHECK: mhlo.atan2\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1))(lax.atan)\n\n # CHECK-LABEL: TEST: atanh float32[]\n # CHECK: xla_fallback_atanh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.atanh)\n\n # CHECK-LABEL: TEST: atan2 float64[] float64[]\n # CHECK: mhlo.atan2\n # CHECK-SAME: tensor<f64>\n print_ir(np.float64(1), np.float64(2))(lax.atan2)\n\n # CHECK-LABEL: TEST: bessel_i0e float32[]\n # CHECK: xla_fallback_bessel_i0e\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.bessel_i0e)\n\n # CHECK-LABEL: TEST: bessel_i1e float32[]\n # CHECK: xla_fallback_bessel_i1e\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.bessel_i1e)\n\n # CHECK-LABEL: TEST: betainc float32[] float32[] float32[]\n # CHECK: xla_fallback_regularized_incomplete_beta\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0), np.float32(0))(lax.betainc)\n\n # CHECK-LABEL: TEST: bitcast_convert_type uint32[7]\n # CHECK: mhlo.bitcast_convert\n # CHECK-SAME: tensor<7xui32>\n # CHECK-SAME: tensor<7xf32>\n print_ir(np.empty((7,), np.uint32))(\n partial(lax.bitcast_convert_type, new_dtype=np.float32))\n\n # CHECK-LABEL: TEST: bitwise_and int32[] int32[]\n # CHECK: mhlo.and\n # CHECK-SAME: tensor<i32>\n print_ir(np.int32(1), np.int32(2))(lax.bitwise_and)\n\n # CHECK-LABEL: TEST: bitwise_and bool[] bool[]\n # CHECK: mhlo.and\n # CHECK-SAME: tensor<i1>\n print_ir(np.bool_(0), np.bool_(0))(lax.bitwise_and)\n\n # CHECK-LABEL: TEST: bitwise_or int32[] int32[]\n # CHECK: mhlo.or\n # CHECK-SAME: tensor<i32>\n print_ir(np.int32(1), np.int32(2))(lax.bitwise_or)\n\n # CHECK-LABEL: TEST: bitwise_or bool[] bool[]\n # CHECK: mhlo.or\n # CHECK-SAME: tensor<i1>\n print_ir(np.bool_(0), np.bool_(0))(lax.bitwise_or)\n\n # CHECK-LABEL: TEST: bitwise_xor int32[] int32[]\n # CHECK: mhlo.xor\n # CHECK-SAME: tensor<i32>\n print_ir(np.int32(1), np.int32(2))(lax.bitwise_xor)\n\n # CHECK-LABEL: TEST: bitwise_xor bool[] bool[]\n # CHECK: mhlo.xor\n # CHECK-SAME: tensor<i1>\n print_ir(np.bool_(0), np.bool_(0))(lax.bitwise_xor)\n\n # CHECK-LABEL: TEST: cbrt bfloat16[]\n # CHECK: mhlo.cbrt\n # CHECK-SAME: tensor<bf16>\n print_ir(jnp.bfloat16(0))(lax.cbrt)\n\n # CHECK-LABEL: TEST: clamp bfloat16[] bfloat16[] bfloat16[]\n # CHECK: mhlo.clamp\n # CHECK-SAME: tensor<bf16>\n print_ir(jnp.bfloat16(0), jnp.bfloat16(0), jnp.bfloat16(0))(lax.clamp)\n\n # CHECK-LABEL: TEST: ceil float16[7]\n # CHECK: mhlo.ceil\n # CHECK-SAME: tensor<7xf16>\n print_ir(np.empty((7,), np.float16))(lax.ceil)\n\n # CHECK-LABEL: TEST: convert_element_type float16[7]\n # CHECK: mhlo.convert\n # CHECK-SAME: tensor<7xf16>\n # CHECK-SAME: tensor<7xf32>\n print_ir(np.empty((7,), np.float16))(\n partial(lax.convert_element_type, new_dtype=np.float32))\n\n # CHECK-LABEL: TEST: convert_element_type complex64[7]\n # CHECK: mhlo.real\n # CHECK-SAME: tensor<7xcomplex<f32>>\n # CHECK-SAME: tensor<7xf32>\n print_ir(np.empty((7,), np.complex64))(\n partial(lax.convert_element_type, new_dtype=np.float32))\n\n # CHECK-LABEL: TEST: convert_element_type float32[7]\n # CHECK: mhlo.compare\n # CHECK-SAME: tensor<7xf32>\n # CHECK-SAME: tensor<7xi1>\n print_ir(np.empty((7,), np.float32))(\n partial(lax.convert_element_type, new_dtype=np.bool_))\n\n # CHECK-LABEL: TEST: clz uint32[]\n # CHECK: mhlo.count_leading_zeros\n # CHECK-SAME: tensor<ui32>\n print_ir(np.uint32(0))(lax.clz)\n\n # CHECK-LABEL: TEST: conj complex64[]\n # CHECK-DAG: mhlo.real\n # CHECK-DAG: mhlo.imag\n # CHECK-DAG: mhlo.neg\n # CHECK-DAG: mhlo.complex\n # CHECK-SAME: tensor<complex<f32>>\n print_ir(np.complex64(0))(lax.conj)\n\n # CHECK-LABEL: TEST: cos float32[]\n # CHECK: mhlo.cos\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.cos)\n\n # CHECK-LABEL: TEST: cosh float32[]\n # CHECK: xla_fallback_cosh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.cosh)\n\n # CHECK-LABEL: TEST: digamma float32[]\n # CHECK: chlo.digamma\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.digamma)\n\n # CHECK-LABEL: TEST: div float32[] float32[]\n # CHECK: mhlo.div\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.div)\n\n # CHECK-LABEL: TEST: eq float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction EQ\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.eq)\n\n # CHECK-LABEL: TEST: eq complex128[] complex128[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction EQ\">\n # CHECK-SAME: tensor<complex<f64>>\n print_ir(np.complex128(1), np.complex128(2))(lax.eq)\n\n # CHECK-LABEL: TEST: eq int64[] int64[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type SIGNED\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction EQ\">\n # CHECK-SAME: tensor<i64>\n print_ir(np.int64(1), np.int64(2))(lax.eq)\n\n # CHECK-LABEL: TEST: eq uint16[] uint16[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type UNSIGNED\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction EQ\">\n # CHECK-SAME: tensor<ui16>\n print_ir(np.uint16(1), np.uint16(2))(lax.eq)\n\n # CHECK-LABEL: TEST: erf float32[]\n # CHECK: xla_fallback_erf\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.erf)\n\n # CHECK-LABEL: TEST: erfc float32[]\n # CHECK: xla_fallback_erfc\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.erfc)\n\n # CHECK-LABEL: TEST: erf_inv float32[]\n # CHECK: xla_fallback_erf_inv\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.erf_inv)\n\n # CHECK-LABEL: TEST: exp float16[]\n # CHECK: mhlo.exp\n # CHECK-SAME: tensor<f16>\n print_ir(np.float16(0))(lax.exp)\n\n # CHECK-LABEL: TEST: expm1 bfloat16[]\n # CHECK: mhlo.exponential_minus_one\n # CHECK-SAME: tensor<bf16>\n print_ir(jnp.bfloat16(0))(lax.expm1)\n\n # CHECK-LABEL: TEST: floor bfloat16[2,3]\n # CHECK: mhlo.floor\n # CHECK-SAME: tensor<2x3xbf16>\n print_ir(np.empty((2, 3), jnp.bfloat16))(lax.floor)\n\n # CHECK-LABEL: TEST: ge float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction GE\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.ge)\n\n # CHECK-LABEL: TEST: gt float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction GT\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.gt)\n\n # CHECK-LABEL: TEST: igamma float32[] float32[]\n # CHECK: xla_fallback_igamma\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0))(lax.igamma)\n\n # CHECK-LABEL: TEST: igammac float32[] float32[]\n # CHECK: xla_fallback_igammac\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0))(lax.igammac)\n\n # CHECK-LABEL: TEST: igamma_grad_a float32[] float32[]\n # CHECK: xla_fallback_igamma_grad_a\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0))(lax.igamma_grad_a)\n\n # CHECK-LABEL: TEST: imag complex64[]\n # CHECK: mhlo.imag\n # CHECK-SAME: tensor<complex<f32>>\n print_ir(np.complex64(0))(lax.imag)\n\n # CHECK-LABEL: TEST: integer_pow float32[]\n # CHECK-DAG: mhlo.mul\n # CHECK-SAME: tensor<f32>\n @print_ir(np.float32(1))\n def integer_pow(x): return lax.integer_pow(x, 3)\n\n # CHECK-LABEL: TEST: is_finite float64[]\n # CHECK: mhlo.is_finite\n # CHECK-SAME: tensor<f64>\n print_ir(np.float64(0))(lax.is_finite)\n\n # CHECK-LABEL: TEST: le float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction LE\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.le)\n\n # CHECK-LABEL: TEST: lgamma float32[]\n # CHECK: chlo.lgamma\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.lgamma)\n\n # CHECK-LABEL: TEST: log float32[]\n # CHECK: mhlo.log\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.log)\n\n # CHECK-LABEL: TEST: log1p float32[]\n # CHECK: mhlo.log_plus_one\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.log1p)\n\n # CHECK-LABEL: TEST: lt float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction LT\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.lt)\n\n # CHECK-LABEL: TEST: max float32[] float32[]\n # CHECK: mhlo.max\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.max)\n\n # CHECK-LABEL: TEST: min float32[] float32[]\n # CHECK: mhlo.min\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.min)\n\n # CHECK-LABEL: TEST: mul float32[] float32[]\n # CHECK: mhlo.mul\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.mul)\n\n # CHECK-LABEL: TEST: ne float32[] float32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: compare_type = #mhlo<\"comparison_type FLOAT\">\n # CHECK-SAME: comparison_direction = #mhlo<\"comparison_direction NE\">\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.ne)\n\n # CHECK-LABEL: TEST: neg int64[]\n # CHECK: mhlo.negate\n # CHECK-SAME: tensor<i64>\n print_ir(np.int64(0))(lax.neg)\n\n # CHECK-LABEL: TEST: nextafter float32[] float32[]\n # CHECK: chlo.next_after\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0))(lax.nextafter)\n\n # CHECK-LABEL: TEST: bitwise_not int64[]\n # CHECK: mhlo.not\n # CHECK-SAME: tensor<i64>\n print_ir(np.int64(0))(lax.bitwise_not)\n\n # CHECK-LABEL: TEST: bitwise_not bool[]\n # CHECK: mhlo.not\n # CHECK-SAME: tensor<i1>\n print_ir(np.bool_(0))(lax.bitwise_not)\n\n # CHECK-LABEL: TEST: population_count uint32[]\n # CHECK: mhlo.popcnt\n # CHECK-SAME: tensor<ui32>\n print_ir(np.uint32(0))(lax.population_count)\n\n # CHECK-LABEL: TEST: pow float32[] float32[]\n # CHECK: mhlo.power\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.pow)\n\n # CHECK-LABEL: TEST: random_gamma_grad float32[] float32[]\n # CHECK: xla_fallback_random_gamma_grad\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0), np.float32(0))(lax.random_gamma_grad)\n\n # CHECK-LABEL: TEST: real complex128[]\n # CHECK: mhlo.real\n # CHECK-SAME: tensor<complex<f64>>\n print_ir(np.complex128(0))(lax.real)\n\n # CHECK-LABEL: TEST: reduce_precision bfloat16[]\n # CHECK: mhlo.reduce_precision\n # CHECK-SAME: tensor<bf16>\n print_ir(jnp.bfloat16(0))(\n partial(lax.reduce_precision, exponent_bits=2, mantissa_bits=2))\n\n # CHECK-LABEL: TEST: rem float32[] float32[]\n # CHECK: mhlo.rem\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.rem)\n\n # CHECK-LABEL: TEST: round float64[7,1]\n # CHECK: mhlo.round\n # CHECK-SAME: tensor<7x1xf64>\n print_ir(np.empty((7,1), np.float64))(\n partial(lax.round, rounding_method=lax.RoundingMethod.AWAY_FROM_ZERO))\n\n # CHECK-LABEL: TEST: rsqrt complex64[]\n # CHECK: mhlo.rsqrt\n # CHECK-SAME: tensor<complex<f32>>\n print_ir(jnp.complex64(0))(lax.rsqrt)\n\n # CHECK-LABEL: TEST: shift_left uint32[] uint32[]\n # CHECK: mhlo.shift_left\n # CHECK-SAME: tensor<ui32>\n print_ir(np.uint32(0), np.uint32(0))(lax.shift_left)\n\n # CHECK-LABEL: TEST: shift_right_arithmetic uint8[] uint8[]\n # CHECK: mhlo.shift_right_arithmetic\n # CHECK-SAME: tensor<ui8>\n print_ir(np.uint8(0), np.uint8(0))(lax.shift_right_arithmetic)\n\n # CHECK-LABEL: TEST: shift_right_logical uint16[] uint16[]\n # CHECK: mhlo.shift_right_logical\n # CHECK-SAME: tensor<ui16>\n print_ir(np.uint16(0), np.uint16(0))(lax.shift_right_logical)\n\n # CHECK-LABEL: TEST: sign int64[]\n # CHECK: mhlo.sign\n # CHECK-SAME: tensor<i64>\n print_ir(np.int64(0))(lax.sign)\n\n # CHECK-LABEL: TEST: sign uint32[]\n # CHECK: mhlo.compare\n # CHECK-SAME: tensor<ui32>\n print_ir(np.uint32(0))(lax.sign)\n\n # CHECK-LABEL: TEST: sin float32[]\n # CHECK: mhlo.sin\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.sin)\n\n # CHECK-LABEL: TEST: sinh float32[]\n # CHECK: xla_fallback_sinh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.sinh)\n\n # CHECK-LABEL: TEST: sub float32[] float32[]\n # CHECK: mhlo.sub\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(1), np.float32(2))(lax.sub)\n\n # CHECK-LABEL: TEST: sqrt bfloat16[]\n # CHECK: mhlo.sqrt\n # CHECK-SAME: tensor<bf16>\n print_ir(jnp.bfloat16(0))(lax.sqrt)\n\n # CHECK-LABEL: TEST: tan float16[]\n # CHECK: mhlo.sine\n # CHECK-SAME: tensor<f32>\n # CHECK: mhlo.cosine\n # CHECK-SAME: tensor<f32>\n print_ir(np.float16(0))(lax.tan)\n\n # CHECK-LABEL: TEST: tanh float32[]\n # CHECK: mhlo.tanh\n # CHECK-SAME: tensor<f32>\n print_ir(np.float32(0))(lax.tanh)\n\n\nif __name__ == \"__main__\":\n app.run(main)\n", "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"BCOO (Bached coordinate format) matrix object and associated primitives.\"\"\"\nimport functools\nimport operator\nfrom typing import Any, NamedTuple, Sequence, Tuple\nimport warnings\n\nimport numpy as np\n\nfrom jax import core\nfrom jax import lax\nfrom jax import tree_util\nfrom jax import vmap\nfrom jax.config import config\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse.util import _safe_asarray, CuSparseEfficiencyWarning\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\nimport jax.numpy as jnp\nfrom jax.interpreters import ad\nfrom jax.util import safe_zip, unzip2, split_list\nfrom jax._src import api_util\nfrom jax._src.api_util import flatten_axes\nfrom jax._src.lax.lax import (\n ranges_like, remaining, _dot_general_batch_dim_nums, _dot_general_shape_rule,\n DotDimensionNumbers)\nfrom jax._src.lib import cusparse\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.numpy.setops import _unique\n\nxops = xc._xla.ops\n\nDtype = Any\nShape = Tuple[int, ...]\n\n#----------------------------------------------------------------------\n# General utilities...\ndef broadcasting_vmap(fun, in_axes=0, out_axes=0):\n @functools.wraps(fun)\n def batched_fun(*args):\n args_flat, in_tree = tree_util.tree_flatten(args)\n in_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, in_axes, kws=False)\n size = max(arg.shape[i] for arg, i in safe_zip(args_flat, in_axes_flat) if i is not None)\n if size > 1:\n if any(i is not None and arg.shape[i] not in (1, size)\n for arg, i in safe_zip(args_flat, in_axes_flat)):\n raise ValueError(\"broadcasting_vmap: mismatched input shapes\")\n args_flat, in_axes_flat = zip(*(\n (arg, None) if i is None else (lax.squeeze(arg, (i,)), None) if arg.shape[i] == 1 else (arg, i)\n for arg, i in zip(args_flat, in_axes_flat)\n ))\n new_args = tree_util.tree_unflatten(in_tree, args_flat)\n new_in_axes = tree_util.tree_unflatten(in_tree, in_axes_flat)\n return vmap(fun, in_axes=new_in_axes, out_axes=out_axes)(*new_args)\n return batched_fun\n\n#----------------------------------------------------------------------\n# BCOO primitives: batched extension of COO.\n\ndef _bcoo_nse(mat, n_batch=0, n_dense=0):\n mat = jnp.asarray(mat)\n mask = (mat != 0)\n if n_dense > 0:\n mask = mask.any([-(i + 1) for i in range(n_dense)])\n mask = mask.sum(list(range(n_batch, mask.ndim)))\n return mask.max()\n\ndef _bcoo_sum_duplicates(data, indices, shape, nse=None, remove_zeros=True):\n if nse is None and isinstance(jnp.array(0), core.Tracer):\n raise ValueError(\"When used with JIT, vmap, or another transform, sum_duplicates() \"\n \"requires passing a non-None value for the nse argument.\")\n props = _validate_bcoo(data, indices, shape)\n f = functools.partial(_bcoo_sum_duplicates_unbatched, shape=shape[props.n_batch:],\n nse=nse, remove_zeros=remove_zeros)\n for _ in range(props.n_batch):\n f = broadcasting_vmap(f)\n data_unique, indices_unique, nse_out = f(data, indices)\n if nse is None:\n nse = jnp.max(nse_out)\n data_unique = lax.slice_in_dim(data_unique, 0, nse, axis=props.n_batch)\n indices_unique = lax.slice_in_dim(indices_unique, 0, nse, axis=props.n_batch)\n return data_unique, indices_unique\n\ndef _bcoo_sum_duplicates_unbatched(data, indices, *, shape, nse, remove_zeros):\n props = _validate_bcoo(data, indices, shape)\n assert props.n_batch == 0\n if not props.n_sparse:\n nse = 1 if nse is None else nse\n data_unique = jnp.zeros_like(data, shape=(nse, *data.shape[1:])).at[0].set(data.sum(0))\n indices_unique = jnp.zeros_like(indices, shape=(nse, 0))\n return data_unique, indices_unique, nse\n fill_value = jnp.expand_dims(jnp.array(shape[:props.n_sparse], dtype=indices.dtype),\n range(indices.ndim - 1))\n out_of_bounds = (indices >= fill_value).any(-1, keepdims=True)\n if remove_zeros:\n data_all_zero = (data == 0).all(range(props.n_batch + 1, data.ndim))[:, None]\n out_of_bounds = out_of_bounds | data_all_zero\n indices = jnp.where(out_of_bounds, fill_value, indices)\n if nse is None:\n indices_unique, inv_idx, nse = _unique(\n indices, axis=0, return_inverse=True, return_true_size=True,\n size=props.nse, fill_value=fill_value)\n nse = nse - (indices == fill_value).any()\n else:\n indices_unique, inv_idx = jnp.unique(\n indices, axis=0, return_inverse=True,\n size=nse, fill_value=fill_value)\n data_shape = [indices_unique.shape[0], *data.shape[1:]]\n data_unique = jnp.zeros(data_shape, data.dtype).at[inv_idx].add(data)\n oob_mask = jnp.all(indices_unique == fill_value, 1)\n data_unique = jnp.where(oob_mask[(...,) + props.n_dense * (None,)], 0, data_unique)\n return data_unique, indices_unique, nse\n\ndef _bcoo_sort_indices(data, indices, shape):\n props = _validate_bcoo(data, indices, shape)\n if props.n_sparse == 0:\n return data, indices\n def f(data, indices):\n _, N = indices.shape\n idx_cols = (indices[:, i] for i in range(N))\n if data.ndim > 1:\n *indices, i = lax.sort((*idx_cols, lax.iota(indices.dtype, len(data))), num_keys=N)\n data = data[i]\n else:\n *indices, data = lax.sort((*idx_cols, data), num_keys=N)\n return data, jnp.column_stack(indices)\n for _ in range(props.n_batch):\n f = broadcasting_vmap(f)\n return f(data, indices)\n\n_bcoo_sort_indices_rule = xla.lower_fun(\n _bcoo_sort_indices, multiple_results=True, new_style=True)\n\ndef _unbatch_bcoo(data, indices, shape):\n n_batch = _validate_bcoo(data, indices, shape).n_batch\n if n_batch == 0:\n return data, indices\n data = jnp.broadcast_to(data, shape[:n_batch] + data.shape[n_batch:])\n indices = jnp.broadcast_to(indices, shape[:n_batch] + indices.shape[n_batch:])\n batch_indices = jnp.mgrid[tuple(slice(None, d) for d in indices.shape[:n_batch + 1])][:-1]\n batch_indices = batch_indices.reshape(n_batch, -1).T\n data = data.reshape(np.prod(data.shape[:n_batch + 1]), *data.shape[n_batch + 1:])\n indices = indices.reshape(np.prod(indices.shape[:n_batch + 1]), *indices.shape[n_batch + 1:])\n return data, jnp.hstack([batch_indices, indices])\n\n\nclass BCOOProperties(NamedTuple):\n n_batch: int\n n_sparse: int\n n_dense: int\n nse: int\n\nclass BCOOInfo(NamedTuple):\n shape: Shape\n\n\ndef _validate_bcoo(data: jnp.ndarray, indices: jnp.ndarray, shape: Sequence[int]) -> BCOOProperties:\n props = _validate_bcoo_indices(indices, shape)\n n_batch, n_sparse, n_dense, nse = props\n shape = tuple(shape)\n if any(s1 not in (1, s2) for s1, s2 in safe_zip(data.shape[:n_batch], shape[:n_batch])):\n raise ValueError(\"data batch dimensions not compatible for \"\n f\"data.shape={data.shape}, shape={shape}\")\n if data.shape[n_batch:] != (nse,) + shape[n_batch + n_sparse:]:\n raise ValueError(f\"Invalid data.shape={data.shape} for \"\n f\"nse={nse}, n_batch={n_batch}, n_dense={n_dense}\")\n return props\n\n\ndef _validate_bcoo_indices(indices: jnp.ndarray, shape: Sequence[int]) -> BCOOProperties:\n assert jnp.issubdtype(indices.dtype, jnp.integer)\n shape = tuple(shape)\n nse, n_sparse = indices.shape[-2:]\n n_batch = indices.ndim - 2\n n_dense = len(shape) - n_batch - n_sparse\n assert n_dense >= 0\n if any(s1 not in (1, s2) for s1, s2 in safe_zip(indices.shape[:n_batch], shape[:n_batch])):\n raise ValueError(\"indices batch dimensions not compatible for \"\n f\"indices.shape={indices.shape}, shape={shape}\")\n if indices.shape[n_batch:] != (nse, n_sparse):\n raise ValueError(f\"Invalid indices.shape={indices.shape} for \"\n f\"nse={nse}, n_batch={n_batch}, n_dense={n_dense}\")\n return BCOOProperties(n_batch=n_batch, n_sparse=n_sparse, n_dense=n_dense, nse=nse)\n\n\n#----------------------------------------------------------------------\n# bcoo_todense\n\nbcoo_todense_p = core.Primitive('bcoo_todense')\n\ndef bcoo_todense(data, indices, *, spinfo):\n \"\"\"Convert batched sparse matrix to a dense matrix.\n\n Args:\n data : array of shape ``batch_dims + (nse,) + block_dims``.\n indices : array of shape ``batch_dims + (n_sparse, nse)``\n spinfo : BCOOInfo. In particular, this includes the shape\n of the matrix, which is equal to ``batch_dims + sparse_dims + block_dims``\n where ``len(sparse_dims) == n_sparse``\n\n Returns:\n mat : array with specified shape and dtype matching ``data``\n \"\"\"\n return bcoo_todense_p.bind(jnp.asarray(data), jnp.asarray(indices), spinfo=spinfo)\n\n@bcoo_todense_p.def_impl\ndef _bcoo_todense_impl(data, indices, *, spinfo):\n shape = spinfo.shape\n n_batch, n_sparse, _, _ = _validate_bcoo(data, indices, shape)\n\n ind_slices = tuple(np.zeros(s, int) if i_s == 1 else np.arange(s)\n for s, i_s in zip(shape[:n_batch], indices.shape[:n_batch]))\n grid = tuple(np.meshgrid(*ind_slices, indexing='ij', sparse=True))\n sparse_ind = tuple(indices[grid + (slice(None), i)] for i in range(n_sparse))\n\n batch_slices = tuple(np.arange(s) for s in shape[:n_batch])\n grid = np.meshgrid(*batch_slices, np.arange(1), indexing='ij', sparse=True)\n batch_ind = tuple(grid)[:-1]\n\n if not sparse_ind:\n data = data.sum(n_batch, keepdims=bool(batch_ind), dtype=data.dtype)\n return jnp.zeros(shape, data.dtype).at[batch_ind + sparse_ind].add(data)\n\n@bcoo_todense_p.def_abstract_eval\ndef _bcoo_todense_abstract_eval(data, indices, *, spinfo):\n shape = spinfo.shape\n _validate_bcoo(data, indices, shape)\n return core.ShapedArray(shape, data.dtype)\n\ndef _bcoo_todense_jvp(data_dot, data, indices, *, spinfo):\n return bcoo_todense(data_dot, indices, spinfo=spinfo)\n\ndef _bcoo_todense_transpose(ct, data, indices, *, spinfo):\n shape = spinfo.shape\n assert ad.is_undefined_primal(data)\n if ad.is_undefined_primal(indices):\n raise ValueError(\"Cannot transpose with respect to sparse indices\")\n assert ct.shape == shape\n assert ct.dtype == data.aval.dtype\n return bcoo_extract(indices, ct), indices\n\ndef _bcoo_todense_batching_rule(batched_args, batch_dims, *, spinfo):\n data, indices = batched_args\n if any(b not in [0, None] for b in batch_dims):\n raise NotImplementedError(f\"batch_dims={batch_dims}. Only 0 and None are supported.\")\n if batch_dims[0] is None:\n data = data[None, ...]\n if batch_dims[1] is None:\n indices = indices[None, ...]\n new_spinfo = BCOOInfo(\n shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\n return bcoo_todense(data, indices, spinfo=new_spinfo), 0\n\nad.defjvp(bcoo_todense_p, _bcoo_todense_jvp, None)\nad.primitive_transposes[bcoo_todense_p] = _bcoo_todense_transpose\nbatching.primitive_batchers[bcoo_todense_p] = _bcoo_todense_batching_rule\nxla.register_translation(bcoo_todense_p, xla.lower_fun(\n _bcoo_todense_impl, multiple_results=False, new_style=True))\n\n#--------------------------------------------------------------------\n# bcoo_fromdense\n\nbcoo_fromdense_p = core.Primitive('bcoo_fromdense')\nbcoo_fromdense_p.multiple_results = True\n\n_TRACED_NSE_ERROR = \"\"\"\nThe error arose for the nse argument of bcoo_fromdense. In order for BCOO.fromdense()\nto be used in traced/compiled code, you must pass a concrete value to the nse\n(number of specified elements) argument.\n\"\"\"\n\ndef bcoo_fromdense(mat, *, nse=None, n_batch=0, n_dense=0, index_dtype=jnp.int32):\n \"\"\"Create COO-format sparse matrix from a dense matrix.\n\n Args:\n mat : array to be converted to COO, with ``ndim = n_batch + n_sparse + n_dense``.\n nse : number of specified elements in each batch\n n_batch : number of batch dimensions (default: 0)\n n_dense : number of block_dimensions (default: 0)\n index_dtype : dtype of sparse indices (default: int32)\n\n Returns:\n data : array of shape ``mat.shape[:n_batch] + (nse,) + mat.shape[mat.ndim - n_dense:]``\n and dtype ``mat.dtype``\n indices : array of shape ``mat.shape[:n_batch] + (n_sparse, nse)``\n \"\"\"\n mat = jnp.asarray(mat)\n if nse is None:\n nse = _bcoo_nse(mat, n_batch, n_dense)\n nse = core.concrete_or_error(operator.index, nse, _TRACED_NSE_ERROR)\n return bcoo_fromdense_p.bind(mat, nse=nse, n_batch=n_batch, n_dense=n_dense,\n index_dtype=index_dtype)\n\n@bcoo_fromdense_p.def_impl\ndef _bcoo_fromdense_impl(mat, *, nse, n_batch, n_dense, index_dtype):\n mat = jnp.asarray(mat)\n n_sparse = mat.ndim - n_dense - n_batch\n mask = (mat != 0)\n if n_dense > 0:\n mask = mask.any([-(i + 1) for i in range(n_dense)])\n def _nonzero(a):\n if a.ndim:\n return jnp.nonzero(a, size=nse, fill_value=a.shape[:n_sparse])\n return ()\n for _ in range(n_batch):\n _nonzero = vmap(_nonzero, 0)\n indices = _nonzero(mask)\n if not indices:\n indices = jnp.zeros(mask.shape[:n_batch] + (nse, 0), index_dtype)\n else:\n indices = jnp.moveaxis(jnp.array(indices, index_dtype), 0, n_batch + 1)\n data = bcoo_extract(indices, mat)\n\n true_nonzeros = (lax.broadcasted_iota(jnp.int32, (1,) * n_batch + (nse,), n_batch) <\n mask.sum(list(range(n_batch, mask.ndim)))[..., None])\n true_nonzeros = true_nonzeros[(n_batch + 1) * (slice(None),) + n_dense * (None,)]\n data = jnp.where(true_nonzeros, data, 0)\n\n return data, indices\n\n@bcoo_fromdense_p.def_abstract_eval\ndef _bcoo_fromdense_abstract_eval(mat, *, nse, n_batch, n_dense, index_dtype):\n n_sparse = mat.ndim - n_batch - n_dense\n data_shape = mat.shape[:n_batch] + (nse,) + mat.shape[n_batch + n_sparse:]\n index_shape = mat.shape[:n_batch] + (nse, n_sparse)\n return core.ShapedArray(data_shape, mat.dtype), core.ShapedArray(index_shape, index_dtype)\n\ndef _bcoo_fromdense_jvp(primals, tangents, *, nse, n_batch, n_dense, index_dtype):\n M, = primals\n Mdot, = tangents\n\n primals_out = bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense, index_dtype=index_dtype)\n data, indices = primals_out\n\n if type(Mdot) is ad.Zero:\n data_dot = ad.Zero.from_value(data)\n else:\n data_dot = bcoo_extract(indices, Mdot)\n\n tangents_out = (data_dot, ad.Zero.from_value(indices))\n\n return primals_out, tangents_out\n\ndef _bcoo_fromdense_transpose(ct, M, *, nse, n_batch, n_dense, index_dtype):\n data, indices = ct\n n_sparse = M.ndim = n_batch - n_dense\n assert data.shape == M.shape[:n_batch] + (nse,) + M.shape[n_batch + n_sparse:]\n assert indices.shape == M.shape[:n_batch] + (n_sparse, nse)\n assert indices.dtype == index_dtype\n if isinstance(indices, ad.Zero):\n raise ValueError(\"Cannot transpose with respect to sparse indices\")\n assert ad.is_undefined_primal(M)\n return bcoo_todense(data, indices, spinfo=BCOOInfo(M.aval.shape))\n\ndef _bcoo_fromdense_batching_rule(batched_args, batch_dims, *, nse, n_batch, n_dense, index_dtype):\n M, = batched_args\n if batch_dims != (0,):\n raise NotImplementedError(f\"batch_dims={batch_dims}\")\n return bcoo_fromdense(M, nse=nse, n_batch=n_batch + 1, n_dense=n_dense, index_dtype=index_dtype), (0, 0)\n\nad.primitive_jvps[bcoo_fromdense_p] = _bcoo_fromdense_jvp\nad.primitive_transposes[bcoo_fromdense_p] = _bcoo_fromdense_transpose\nbatching.primitive_batchers[bcoo_fromdense_p] = _bcoo_fromdense_batching_rule\nxla.register_translation(bcoo_fromdense_p, xla.lower_fun(\n _bcoo_fromdense_impl, multiple_results=True, new_style=True))\n\n#----------------------------------------------------------------------\n# bcoo_extract\n\nbcoo_extract_p = core.Primitive('bcoo_extract')\n\ndef bcoo_extract(indices, mat):\n \"\"\"Extract BCOO values from dense matrix `mat` at given BCOO indices.\"\"\"\n return bcoo_extract_p.bind(indices, mat)\n\n@bcoo_extract_p.def_impl\ndef _bcoo_extract_impl(indices, mat):\n mat = jnp.asarray(mat)\n n_batch, n_sparse, _, _ = _validate_bcoo_indices(indices, mat.shape)\n\n ind_slices = tuple(np.zeros(s, int) if i_s == 1 else np.arange(s)\n for s, i_s in zip(mat.shape[:n_batch], indices.shape[:n_batch]))\n grid = tuple(np.meshgrid(*ind_slices, indexing='ij', sparse=True))\n sparse_ind = tuple(indices[grid + (slice(None), i)] for i in range(n_sparse))\n\n batch_slices = tuple(np.arange(s) for s in mat.shape[:n_batch])\n grid = np.meshgrid(*batch_slices, np.arange(1), indexing='ij', sparse=True)\n batch_ind = tuple(grid)[:-1]\n\n if not sparse_ind + batch_ind:\n return mat[None]\n return mat.at[batch_ind + sparse_ind].get(mode='fill', fill_value=0)\n\n@bcoo_extract_p.def_abstract_eval\ndef _bcoo_extract_abstract_eval(indices, mat):\n n_batch, _, n_dense, nse = _validate_bcoo_indices(indices, mat.shape)\n out_shape = mat.shape[:n_batch] + (nse,) + mat.shape[mat.ndim - n_dense:]\n return core.ShapedArray(out_shape, mat.dtype)\n\ndef _bcoo_extract_jvp(mat_dot, indices, mat):\n assert mat_dot.shape == mat.shape\n return bcoo_extract(indices, mat_dot)\n\ndef _bcoo_extract_transpose(ct, indices, mat):\n assert ad.is_undefined_primal(mat)\n if ad.is_undefined_primal(indices):\n raise ValueError(\"Cannot transpose with respect to sparse indices\")\n assert ct.dtype == mat.aval.dtype\n return indices, bcoo_todense(ct, indices, spinfo=BCOOInfo(mat.aval.shape))\n\ndef _bcoo_extract_batching_rule(batched_args, batch_dims):\n indices, mat = batched_args\n assert any(b is not None for b in batch_dims)\n if batch_dims[0] is None:\n bdim = batch_dims[1]\n indices = lax.expand_dims(indices, (bdim,))\n elif batch_dims[1] is None:\n # TODO(jakevdp) can we handle this case without explicit broadcasting?\n bdim = batch_dims[0]\n result_shape = list(mat.shape)\n result_shape.insert(bdim, indices.shape[bdim])\n mat = lax.broadcast_in_dim(mat, result_shape, (bdim,))\n else:\n if batch_dims[0] != batch_dims[1]:\n raise NotImplementedError(\"bcoo_extract with unequal batch dimensions.\")\n bdim = batch_dims[0]\n n_batch = indices.ndim - 2\n if bdim >= n_batch:\n raise ValueError(f\"batch_dims={batch_dims} out of range for indices with n_batch={n_batch}\")\n return bcoo_extract(indices, mat), bdim\n\nad.defjvp(bcoo_extract_p, None, _bcoo_extract_jvp)\nad.primitive_transposes[bcoo_extract_p] = _bcoo_extract_transpose\nbatching.primitive_batchers[bcoo_extract_p] = _bcoo_extract_batching_rule\nxla.register_translation(bcoo_extract_p, xla.lower_fun(\n _bcoo_extract_impl, multiple_results=False, new_style=True))\n\n#----------------------------------------------------------------------\n# bcoo_transpose\n# transpose of a BCOO array\n\nbcoo_transpose_p = core.Primitive('bcoo_transpose')\nbcoo_transpose_p.multiple_results = True\n\ndef bcoo_transpose(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n permutation = tuple(permutation)\n if permutation == tuple(range(len(spinfo.shape))):\n return data, indices\n else:\n return bcoo_transpose_p.bind(data, indices, permutation=permutation,\n spinfo=spinfo)\n\ndef _validate_permutation(data, indices, permutation, shape):\n if not isinstance(permutation, (tuple, list, np.ndarray)):\n raise TypeError(f\"transpose permutation must be a tuple/list/ndarray, got {type(permutation)}.\")\n if tuple(sorted(permutation)) != tuple(range(len(shape))):\n raise TypeError(\"transpose permutation isn't a permutation of operand dimensions, \"\n f\"got permutation {permutation} for shape {shape}.\")\n n_batch, n_sparse, n_dense, _ = _validate_bcoo(data, indices, shape)\n batch_perm = permutation[:n_batch]\n sparse_perm = [p - n_batch for p in permutation[n_batch: n_batch + n_sparse]]\n dense_perm = [p - n_sparse - n_batch for p in permutation[n_batch + n_sparse:]]\n if n_batch and tuple(sorted(batch_perm)) != tuple(range(n_batch)):\n raise NotImplementedError(\"transpose permutation cannot permute batch axes with non-batch axes; \"\n f\"got permutation {permutation}, with n_batch={n_batch}.\")\n if n_dense and tuple(sorted(dense_perm)) != tuple(range(n_dense)):\n raise NotImplementedError(\"transpose permutation cannot permute dense axes with non-dense axes; \"\n f\"got permutation {permutation}, with n_dense={n_dense}.\")\n return batch_perm, sparse_perm, dense_perm\n\n@bcoo_transpose_p.def_impl\ndef _bcoo_transpose_impl(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n batch_perm, sparse_perm, dense_perm = _validate_permutation(data, indices, permutation, spinfo.shape)\n n_batch = len(batch_perm)\n indices = indices[..., sparse_perm].transpose(*batch_perm, n_batch, n_batch + 1)\n data = data.transpose(*batch_perm, n_batch, *(d + n_batch + 1 for d in dense_perm))\n return data, indices\n\n@bcoo_transpose_p.def_abstract_eval\ndef _bcoo_transpose_abstract_eval(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n batch_perm, _, dense_perm = _validate_permutation(data, indices, permutation, spinfo.shape)\n n_batch = len(batch_perm)\n indices_shape = np.array(indices.shape)[[*batch_perm, n_batch, n_batch + 1]]\n data_shape = np.array(data.shape)[[*batch_perm, n_batch, *(d + n_batch + 1 for d in dense_perm)]]\n return core.ShapedArray(data_shape, data.dtype), core.ShapedArray(indices_shape, indices.dtype)\n\ndef _bcoo_transpose_jvp(primals, tangents, *, permutation: Sequence[int], spinfo: BCOOInfo):\n data, indices = primals\n data_dot, _ = tangents\n primals_out = bcoo_transpose(data, indices, permutation=permutation, spinfo=spinfo)\n data_dot_out, _ = bcoo_transpose(data_dot, indices, permutation=permutation, spinfo=spinfo)\n return primals_out, (data_dot_out, ad.Zero.from_value(indices))\n\ndef _bcoo_transpose_transpose(ct, data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n data_ct, indices_ct = ct\n assert isinstance(indices_ct, ad.Zero)\n if ad.is_undefined_primal(indices):\n raise ValueError(\"Cannot transpose with respect to sparse indices\")\n assert data_ct.dtype == data.aval.dtype\n ct_spinfo = BCOOInfo(tuple(spinfo.shape[p] for p in permutation))\n rev_permutation = list(np.argsort(permutation))\n # TODO(jakevdp) avoid dummy indices?\n dummy_indices = jnp.zeros([1 for i in range(indices.ndim - 2)] + list(indices.shape[-2:]), dtype=int)\n data_trans, _ = bcoo_transpose(data_ct, dummy_indices, permutation=rev_permutation, spinfo=ct_spinfo)\n return data_trans, indices_ct\n\ndef _bcoo_transpose_batch_rule(batched_args, batch_dims, *, permutation: Sequence[int], spinfo: BCOOInfo):\n data, indices = batched_args\n batch_dims = list(batch_dims)\n batch_size = max(0 if dim is None else arg.shape[dim]\n for arg, dim in zip(batched_args, batch_dims))\n if batch_dims[0] is None:\n data = data[None]\n else:\n assert batch_dims[0] == 0\n if batch_dims[1] is None:\n indices = indices[None]\n else:\n assert batch_dims[1] == 0\n batched_spinfo = BCOOInfo((batch_size, *spinfo.shape))\n batched_permutation = (0, *(p + 1 for p in permutation))\n data, indices = bcoo_transpose(data, indices, permutation=batched_permutation, spinfo=batched_spinfo)\n if batch_dims[0] is None:\n data = data[0]\n if batch_dims[1] is None:\n indices = indices[0]\n return (data, indices), batch_dims\n\nad.primitive_jvps[bcoo_transpose_p] = _bcoo_transpose_jvp\nad.primitive_transposes[bcoo_transpose_p] = _bcoo_transpose_transpose\nbatching.primitive_batchers[bcoo_transpose_p] = _bcoo_transpose_batch_rule\nxla.register_translation(bcoo_transpose_p, xla.lower_fun(\n _bcoo_transpose_impl, multiple_results=True, new_style=True))\n\n#----------------------------------------------------------------------\n# bcoo_dot_general\n# (batched) general dot product of a BCOO sparse ND array and a dense ND array,\n# returning a dense ND array.\n\nbcoo_dot_general_p = core.Primitive('bcoo_dot_general')\n\ndef _dot_general_validated_shape(lhs_shape: Shape, rhs_shape: Shape, dimension_numbers: DotDimensionNumbers) -> Shape:\n \"\"\"Validate the inputs and return the output shape.\"\"\"\n lhs = core.ShapedArray(lhs_shape, np.float32)\n rhs = core.ShapedArray(rhs_shape, np.float32)\n return _dot_general_shape_rule(\n lhs, rhs, dimension_numbers=dimension_numbers,\n precision=None, preferred_element_type=None)\n\ndef bcoo_dot_general(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n cdims = (api_util._ensure_index_tuple(lhs_contract),\n api_util._ensure_index_tuple(rhs_contract))\n bdims = (api_util._ensure_index_tuple(lhs_batch),\n api_util._ensure_index_tuple(rhs_batch))\n return bcoo_dot_general_p.bind(jnp.asarray(lhs_data), jnp.asarray(lhs_indices), jnp.asarray(rhs),\n dimension_numbers=(cdims, bdims),\n lhs_spinfo=lhs_spinfo)\n\ndef bcoo_rdot_general(lhs, rhs_data, rhs_indices, *, dimension_numbers: DotDimensionNumbers, rhs_spinfo: BCOOInfo):\n # TODO(jakevdp): perhaps this should be part of the bcoo_dot_general primitive?\n result = bcoo_dot_general(rhs_data, rhs_indices, lhs, lhs_spinfo=rhs_spinfo,\n dimension_numbers=[d[::-1] for d in dimension_numbers])\n n_contract, n_batch = (len(d[0]) for d in dimension_numbers)\n n_swap = len(rhs_spinfo.shape) - n_contract\n permutation = tuple([*range(n_batch), *range(n_swap, result.ndim), *range(n_batch, n_swap)])\n return lax.transpose(result, permutation)\n\n@bcoo_dot_general_p.def_impl\ndef _bcoo_dot_general_impl(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n lhs_data = jnp.asarray(lhs_data)\n lhs_indices = jnp.asarray(lhs_indices)\n rhs = jnp.asarray(rhs)\n # Validate all inputs via abstract_eval\n out_aval = _bcoo_dot_general_abstract_eval(lhs_data.aval, lhs_indices.aval, rhs.aval,\n dimension_numbers=dimension_numbers,\n lhs_spinfo=lhs_spinfo)\n n_sparse = lhs_indices.shape[-1]\n n_batch = lhs_indices.ndim - 2\n\n (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n lhs_contracting_b, rhs_contracting_b = unzip2([\n (l, r) for l, r in safe_zip(lhs_contracting, rhs_contracting) if l < n_batch])\n lhs_contracting_s, rhs_contracting_s = unzip2([\n (l, r) for l, r in safe_zip(lhs_contracting, rhs_contracting) if l >= n_batch])\n\n # Reorder lhs batch dimensions\n if lhs_batch or lhs_contracting_b:\n batch_perm = [*lhs_batch, *remaining(range(n_batch), lhs_batch, lhs_contracting_b), *lhs_contracting_b]\n lhs_data = lhs_data.transpose([*batch_perm, *range(n_batch, lhs_data.ndim)])\n lhs_indices = lhs_indices.transpose([*batch_perm, *range(n_batch, lhs_indices.ndim)])\n\n # Reorder lhs sparse dimensions\n if lhs_contracting_s:\n lhs_contracting_s = [d - n_batch for d in lhs_contracting_s]\n sparse_perm = jnp.array([*lhs_contracting_s, *remaining(range(n_sparse), lhs_contracting_s)])\n lhs_indices = lhs_indices[..., sparse_perm]\n\n # Reorder rhs dimensions\n rhs_perm = [*rhs_batch, *rhs_contracting_b, *rhs_contracting_s,\n *remaining(range(rhs.ndim), rhs_batch, rhs_contracting)]\n rhs = rhs.transpose(rhs_perm)\n\n def result(out_array, lhs_data, lhs_indices, rhs):\n idx = tuple(lhs_indices[..., i] for i in range(n_sparse))\n idx_right = idx[:len(lhs_contracting_s)]\n idx_out = idx[len(lhs_contracting_s):]\n if idx_right and lhs_indices.ndim > 2:\n idx_batch = jnp.meshgrid(\n *(jnp.arange(n) for n in lhs_indices.shape[:-1]),\n indexing='ij')[:lhs_indices.ndim - 2]\n idx_right = (*idx_batch, *idx_right)\n batch_dims = list(range(len(lhs_contracting_b) + bool(lhs_contracting_s)))\n prod = lax.dot_general(lhs_data, rhs.at[idx_right].get(mode='fill', fill_value=0),\n (([], []), (batch_dims, batch_dims)))\n if idx_out:\n return out_array.at[idx_out].add(prod)\n else:\n return prod.sum(tuple(range(prod.ndim - out_array.ndim)), dtype=out_array.dtype)\n for _ in range(n_batch - len(lhs_contracting_b)):\n result = broadcasting_vmap(result)\n rhs = lax.expand_dims(rhs, range(len(rhs_batch), n_batch - len(lhs_contracting_b)))\n out_array = jnp.zeros(out_aval.shape, out_aval.dtype)\n return result(out_array, lhs_data, lhs_indices, rhs)\n\n@bcoo_dot_general_p.def_abstract_eval\ndef _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n if lhs_data.dtype != rhs.dtype:\n raise ValueError(\"bcoo_dot_general requires arguments to have matching dtypes; \"\n f\"got lhs.dtype={lhs_data.dtype}, rhs.dtype={rhs.dtype}\")\n\n (lhs_contracting, _), (lhs_batch, _) = dimension_numbers\n n_batch, n_sparse, _, _ = _validate_bcoo(lhs_data, lhs_indices, lhs_spinfo.shape)\n out_shape = _dot_general_validated_shape(lhs_spinfo.shape, rhs.shape, dimension_numbers)\n\n if lhs_batch and max(lhs_batch) >= n_batch:\n raise NotImplementedError(\n \"bcoo_dot_general batch dimensions must be among the batch dimensions in the sparse representtaion.\\n\"\n f\"got lhs_batch={lhs_batch}, n_batch={n_batch}\")\n\n # TODO: support contraction of dense dimensions?\n if any(d >= n_batch + n_sparse for d in lhs_contracting):\n raise NotImplementedError(\"bcoo_dot_general: contracting over dense dimensions.\")\n\n return core.ShapedArray(out_shape, lhs_data.dtype)\n\n_bcoo_dot_general_default_translation_rule = xla.lower_fun(\n _bcoo_dot_general_impl, multiple_results=False, new_style=True)\n\ndef _bcoo_dot_general_cuda_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n lhs_spinfo: BCOOInfo):\n\n c = ctx.builder\n\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n props = _validate_bcoo_indices(lhs_indices_aval, lhs_spinfo.shape)\n rhs_ndim = len(c.get_shape(rhs).dimensions())\n\n # Checks the shapes of lhs and rhs.\n assert props.n_dense == 0\n assert props.n_batch == 0\n assert props.n_sparse in [1, 2]\n assert rhs_ndim in [1, 2]\n\n # Checks the operation dimensions.\n assert len(lhs_batch) == 0\n assert len(rhs_batch) == 0\n assert len(lhs_contract) == 1\n\n # Checks the dtype.\n assert lhs_data_aval.dtype in [np.float32, np.float64, np.complex64, np.complex128]\n assert lhs_data_aval.dtype == rhs_aval.dtype\n assert lhs_indices_aval.dtype == np.int32\n\n if rhs_ndim == 1:\n bcoo_dot_general_fn = cusparse.coo_matvec\n elif rhs_ndim == 2:\n bcoo_dot_general_fn = cusparse.coo_matmat\n if rhs_contract[0] == 1:\n rhs = xops.Transpose(rhs, permutation=[1, 0])\n else:\n raise ValueError(f\"rhs has to be 1d or 2d; get {rhs_ndim}d.\")\n\n lhs_transpose = False\n if props.n_sparse == 1:\n # Converts lhs to a row vector.\n col = xops.Collapse(lhs_indices, dimensions=[0, 1])\n row = xops.Broadcast(xops.Constant(c, jnp.array(0, dtype=jnp.int32)),\n c.get_shape(col).dimensions())\n lhs_shape = (1, lhs_spinfo.shape[0])\n dot_product = bcoo_dot_general_fn(\n c, lhs_data, row, col, rhs, shape=lhs_shape, transpose=lhs_transpose)\n\n if rhs_ndim == 1:\n # Transforms a single-element array to a scalar.\n return [xops.Reshape(dot_product, dimensions=[0], new_sizes=[])]\n else:\n return [xops.Collapse(dot_product, dimensions=[0, 1])]\n elif props.n_sparse == 2:\n row = xops.Collapse(\n xops.Slice(lhs_indices,\n start_indices=[0, 0],\n limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 1],\n strides=[1, 1]),\n dimensions=[0, 1])\n col = xops.Collapse(\n xops.Slice(lhs_indices,\n start_indices=[0, 1],\n limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 2],\n strides=[1, 1]),\n dimensions=[0, 1])\n\n if lhs_contract[0] == 0:\n lhs_transpose = True\n\n return [bcoo_dot_general_fn(\n c, lhs_data, row, col, rhs, shape=lhs_spinfo.shape,\n transpose=lhs_transpose)]\n else:\n raise ValueError(f\"lhs has to be 1d or 2d; get {props.n_sparse}d.\")\n\ndef _bcoo_dot_general_gpu_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n lhs_spinfo: BCOOInfo):\n\n if not config.jax_bcoo_cusparse_lowering:\n return _bcoo_dot_general_default_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n n_batch, n_sparse, n_dense, nse = _validate_bcoo(\n lhs_data_aval, lhs_indices_aval, lhs_spinfo.shape)\n\n dtype = lhs_data_aval.dtype\n if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:\n warnings.warn(f'bcoo_dot_general cusparse lowering not available for '\n f'dtype={dtype}. Falling back to default implementation.',\n CuSparseEfficiencyWarning)\n return _bcoo_dot_general_default_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n\n if (n_batch or n_dense or\n n_sparse not in [1, 2] or rhs_aval.ndim not in [1, 2] or\n lhs_batch or rhs_batch or len(lhs_contract) != 1):\n return _bcoo_dot_general_default_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n else:\n # Sorts lhs by row indices.\n lhs_data, lhs_indices = _bcoo_sort_indices_rule(\n ctx, avals_in[:2], avals_in[:2], lhs_data, lhs_indices,\n shape=lhs_spinfo.shape)\n\n return _bcoo_dot_general_cuda_translation_rule(\n ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n\ndef _bcoo_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n return bcoo_dot_general(lhs_data_dot, lhs_indices, rhs, dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n\ndef _bcoo_dot_general_jvp_rhs(rhs_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n return bcoo_dot_general(lhs_data, lhs_indices, rhs_dot, dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n\ndef _bcoo_dot_general_transpose(ct, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n assert not ad.is_undefined_primal(lhs_indices)\n if type(ct) is ad.Zero:\n return ad.Zero\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n lhs_ndim = len(lhs_spinfo.shape)\n rhs_ndim = rhs.aval.ndim if ad.is_undefined_primal(rhs) else rhs.ndim\n lhs_kept = remaining(range(lhs_ndim), lhs_contract, lhs_batch)\n rhs_kept = remaining(range(rhs_ndim), rhs_contract, rhs_batch)\n ans_batch, ans_lhs, ans_rhs = map(list, ranges_like(lhs_batch, lhs_kept, rhs_kept))\n if ad.is_undefined_primal(lhs_data):\n dims = ((ans_rhs, rhs_kept), (ans_batch, rhs_batch))\n lhs_contract_sorted_by_rhs = list(np.take(lhs_contract, np.argsort(rhs_contract)))\n permutation = list(lhs_batch) + lhs_kept + lhs_contract_sorted_by_rhs\n out_axes = list(np.argsort(permutation))\n\n # What follows is essentially this, but computed in terms of dot_general_sampled:\n # out_dense_T = lax.dot_general(ct, rhs, dimension_numbers=dims)\n # out_dense = lax.transpose(out_dense_T, out_axes)\n # result = bcoo_extract(lhs_indices, out_dense)\n\n # Instead we (1) un-transpose indices, (2) compute SDDMM, (3) re-transpose result\n dummy_data = jnp.ones([1 for i in range(lhs_indices.ndim - 2)] + [lhs_indices.shape[-2]])\n dummy_spinfo = BCOOInfo(tuple(lhs_indices.shape[:-2]) + tuple(1 for i in range(lhs_indices.shape[-1])))\n _, lhs_indices_T = bcoo_transpose(dummy_data, lhs_indices, permutation=permutation, spinfo=dummy_spinfo)\n result_T = bcoo_dot_general_sampled(ct, rhs, lhs_indices_T, dimension_numbers=dims)\n result, _ = bcoo_transpose(result_T, lhs_indices_T, permutation=out_axes, spinfo=dummy_spinfo)\n\n return result, lhs_indices, rhs\n else:\n dims = ((lhs_kept, ans_lhs), (lhs_batch, ans_batch))\n rhs_contract_sorted_by_lhs = list(np.take(rhs_contract, np.argsort(lhs_contract)))\n out_axes = list(np.argsort(list(rhs_batch) + rhs_contract_sorted_by_lhs + rhs_kept))\n result = bcoo_dot_general(lhs_data, lhs_indices, ct, lhs_spinfo=lhs_spinfo, dimension_numbers=dims)\n return lhs_data, lhs_indices, lax.transpose(result, out_axes)\n\ndef _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n lhs_data, lhs_indices, rhs = batched_args\n batch_dims = list(batch_dims)\n batch_size = max(0 if dim is None else arg.shape[dim]\n for arg, dim in zip(batched_args, batch_dims))\n if batch_dims[0] is None:\n lhs_data = lhs_data[None]\n batch_dims[0] = 0\n if batch_dims[1] is None:\n lhs_indices = lhs_indices[None]\n batch_dims[1] = 0\n # TODO: handle different batchings between lhs_data and lhs_indices?\n assert batch_dims[0] == batch_dims[1] == 0\n new_dimension_numbers, result_batch_dim = _dot_general_batch_dim_nums(\n (len(lhs_spinfo.shape), rhs.ndim), (batch_dims[0], batch_dims[2]), dimension_numbers)\n new_shape = (batch_size, *lhs_spinfo.shape)\n batched_out = bcoo_dot_general(lhs_data, lhs_indices, rhs, lhs_spinfo=BCOOInfo(new_shape),\n dimension_numbers=new_dimension_numbers)\n return batched_out, result_batch_dim\n\nad.defjvp(bcoo_dot_general_p, _bcoo_dot_general_jvp_lhs, None, _bcoo_dot_general_jvp_rhs)\nad.primitive_transposes[bcoo_dot_general_p] = _bcoo_dot_general_transpose\nbatching.primitive_batchers[bcoo_dot_general_p] = _bcoo_dot_general_batch_rule\n\nxla.register_translation(\n bcoo_dot_general_p, _bcoo_dot_general_default_translation_rule)\nif cusparse and cusparse.is_supported:\n xla.register_translation(bcoo_dot_general_p,\n _bcoo_dot_general_gpu_translation_rule,\n platform='gpu')\n\n#----------------------------------------------------------------------\n# bcoo_dot_general_sampled\n# (batched) general sampled dot product of two dense ND arrays, with\n# output computed only at a given set of sparse indices.\n\nbcoo_dot_general_sampled_p = core.Primitive(\"bcoo_dot_general_sampled\")\n\ndef bcoo_dot_general_sampled(A, B, indices, *, dimension_numbers):\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n cdims = (api_util._ensure_index_tuple(lhs_contract),\n api_util._ensure_index_tuple(rhs_contract))\n bdims = (api_util._ensure_index_tuple(lhs_batch),\n api_util._ensure_index_tuple(rhs_batch))\n return bcoo_dot_general_sampled_p.bind(A, B, indices,\n dimension_numbers=(cdims, bdims))\n\n@bcoo_dot_general_sampled_p.def_impl\ndef _bcoo_dot_general_sampled_impl(A, B, indices, *, dimension_numbers):\n # TODO(jakevdp): use a more efficient implementation that avoids the full dot product.\n dense_result = lax.dot_general(A, B, dimension_numbers=dimension_numbers)\n return bcoo_extract(indices, dense_result)\n\n@bcoo_dot_general_sampled_p.def_abstract_eval\ndef _bcoo_dot_general_sampled_abstract_eval(A, B, indices, *, dimension_numbers):\n dense_result, = pe.abstract_eval_fun(lambda *args: [lax.dot_general(*args, dimension_numbers=dimension_numbers)], A, B)\n sparse_result, = pe.abstract_eval_fun(lambda *args: [bcoo_extract(*args)], indices, dense_result)\n return sparse_result\n\ndef _bcoo_dot_general_sampled_transpose(ct, A, B, indices, *, dimension_numbers):\n A_shape = A.aval.shape if hasattr(A, 'aval') else A.shape\n B_shape = B.aval.shape if hasattr(B, 'aval') else B.shape\n mat_shape = _dot_general_validated_shape(A_shape, B_shape, dimension_numbers)\n mat = ad.UndefinedPrimal(core.ShapedArray(mat_shape, ct.dtype))\n indices, ct = _bcoo_extract_transpose(ct, indices, mat)\n kwds = {'dimension_numbers': dimension_numbers,\n 'precision': None,\n 'preferred_element_type': None}\n A, B = ad.get_primitive_transpose(lax.dot_general_p)(ct, A, B, **kwds)\n return A, B, indices\n\ndef _bcoo_dot_general_sampled_jvp_A(A_dot, A, B, indices, *, dimension_numbers):\n return bcoo_dot_general_sampled(A_dot, B, indices, dimension_numbers=dimension_numbers)\n\ndef _bcoo_dot_general_sampled_jvp_B(B_dot, A, B, indices, *, dimension_numbers):\n return bcoo_dot_general_sampled(A, B_dot, indices, dimension_numbers=dimension_numbers)\n\ndef _bcoo_dot_general_sampled_batch_rule(batched_args, batch_dims, *, dimension_numbers):\n def impl(A, B, indices):\n return _bcoo_dot_general_sampled_impl(A, B, indices, dimension_numbers=dimension_numbers)\n return vmap(impl, in_axes=batch_dims, out_axes=0)(*batched_args), 0\n\nad.defjvp(bcoo_dot_general_sampled_p, _bcoo_dot_general_sampled_jvp_A,\n _bcoo_dot_general_sampled_jvp_B, None)\nad.primitive_transposes[bcoo_dot_general_sampled_p] = _bcoo_dot_general_sampled_transpose\nbatching.primitive_batchers[bcoo_dot_general_sampled_p] = _bcoo_dot_general_sampled_batch_rule\nxla.register_translation(bcoo_dot_general_sampled_p, xla.lower_fun(\n _bcoo_dot_general_sampled_impl, multiple_results=False, new_style=True))\n\n#----------------------------------------------------------------------\n# bcoo_spdot_general\n# (batched) general dot product of two BCOO sparse arrays returning a\n# Dense ND array.\n\nbcoo_spdot_general_p = core.Primitive('bcoo_spdot_general')\nbcoo_spdot_general_p.multiple_results = True\n\ndef bcoo_spdot_general(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers: DotDimensionNumbers):\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n cdims = (api_util._ensure_index_tuple(lhs_contract),\n api_util._ensure_index_tuple(rhs_contract))\n bdims = (api_util._ensure_index_tuple(lhs_batch),\n api_util._ensure_index_tuple(rhs_batch))\n return bcoo_spdot_general_p.bind(lhs_data, lhs_indices, rhs_data, rhs_indices,\n lhs_spinfo=lhs_spinfo, rhs_spinfo=rhs_spinfo,\n dimension_numbers=(cdims, bdims))\n\ndef _bcoo_spdot_general_unbatched(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo, rhs_spinfo, lhs_contracting, rhs_contracting):\n lhs_shape = lhs_spinfo.shape\n rhs_shape = rhs_spinfo.shape\n\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n\n assert lhs.n_batch == rhs.n_batch == 0\n assert lhs.n_dense == rhs.n_dense == 0\n assert [lhs_shape[d] for d in lhs_contracting] == [rhs_shape[d] for d in rhs_contracting]\n assert max(lhs_contracting, default=-1) < lhs.n_sparse\n assert max(rhs_contracting, default=-1) < rhs.n_sparse\n\n out_shape = (\n [s for i, s in enumerate(lhs_shape) if i not in lhs_contracting] +\n [s for i, s in enumerate(rhs_shape) if i not in rhs_contracting])\n\n lhs_i = lhs_indices[:, jnp.array(lhs_contracting, dtype=int)]\n rhs_i = rhs_indices[:, jnp.array(rhs_contracting, dtype=int)]\n lhs_j = lhs_indices[:, jnp.array(remaining(range(lhs.n_sparse), lhs_contracting), dtype=int)]\n rhs_j = rhs_indices[:, jnp.array(remaining(range(rhs.n_sparse), rhs_contracting), dtype=int)]\n\n # TODO(jakevdp): can we do this more efficiently than using an outer product? Note that\n # jnp.isin() currently doesn't help much, because it also does all() over an outer\n # comparison.\n overlap = (lhs_i[:, None] == rhs_i[None, :]).all(-1)\n lhs_fill_value = jnp.expand_dims(\n jnp.array([lhs_shape[d] for d in lhs_contracting]), range(lhs_i.ndim - 1))\n rhs_fill_value = jnp.expand_dims(\n jnp.array([rhs_shape[d] for d in rhs_contracting]), range(rhs_i.ndim - 1))\n lhs_valid = (lhs_i < lhs_fill_value).all(-1)\n rhs_valid = (rhs_i < rhs_fill_value).all(-1)\n out_data = jnp.where(overlap & lhs_valid[:, None] & rhs_valid[None, :],\n lhs_data[:, None] * rhs_data[None, :], 0).ravel()\n\n out_indices = jnp.empty([lhs.nse, rhs.nse, lhs_j.shape[-1] + rhs_j.shape[-1]],\n dtype=jnp.result_type(lhs_indices, rhs_indices))\n out_indices = out_indices.at[:, :, :lhs_j.shape[-1]].set(lhs_j[:, None])\n out_indices = out_indices.at[:, :, lhs_j.shape[-1]:].set(rhs_j[None, :])\n out_indices = out_indices.reshape(len(out_data), out_indices.shape[-1])\n out_nse = (lhs.nse if lhs_j.shape[1] else 1) * (rhs.nse if rhs_j.shape[1] else 1)\n return _bcoo_sum_duplicates(out_data, out_indices, out_shape, nse=out_nse)\n\n@bcoo_spdot_general_p.def_impl\ndef _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n lhs_shape = lhs_spinfo.shape\n rhs_shape = rhs_spinfo.shape\n\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n assert lhs.n_dense == rhs.n_dense == 0\n data_aval, indices_aval = _bcoo_spdot_general_abstract_eval(\n lhs_data.aval, lhs_indices.aval, rhs_data.aval, rhs_indices.aval,\n lhs_spinfo=lhs_spinfo, rhs_spinfo=rhs_spinfo, dimension_numbers=dimension_numbers)\n out_shape = _dot_general_validated_shape(lhs_shape, rhs_shape, dimension_numbers)\n _validate_bcoo(data_aval, indices_aval, out_shape)\n\n (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n\n # Move batch dimensions to front of each array.\n lhs_batch_perm = [*lhs_batch, *remaining(range(lhs.n_batch), lhs_batch)]\n rhs_batch_perm = [*rhs_batch, *remaining(range(rhs.n_batch), rhs_batch)]\n lhs_data = lhs_data.transpose([*lhs_batch_perm, *range(lhs.n_batch, lhs_data.ndim)])\n rhs_data = rhs_data.transpose([*rhs_batch_perm, *range(rhs.n_batch, rhs_data.ndim)])\n lhs_indices = lhs_indices.transpose([*lhs_batch_perm, *range(lhs.n_batch, lhs_indices.ndim)])\n rhs_indices = rhs_indices.transpose([*rhs_batch_perm, *range(rhs.n_batch, rhs_indices.ndim)])\n\n # Implement batched dot product via vmap\n func = functools.partial(_bcoo_spdot_general_unbatched,\n lhs_spinfo=BCOOInfo(lhs_shape[lhs.n_batch:]),\n rhs_spinfo=BCOOInfo(rhs_shape[rhs.n_batch:]),\n lhs_contracting=[d - lhs.n_batch for d in lhs_contracting],\n rhs_contracting=[d - rhs.n_batch for d in rhs_contracting])\n\n for _ in reversed(range(len(rhs_batch), rhs.n_batch)):\n func = broadcasting_vmap(func, in_axes=(None, None, 0, 0))\n for _ in reversed(range(len(lhs_batch), lhs.n_batch)):\n func = broadcasting_vmap(func, in_axes=(0, 0, None, None))\n for _ in range(len(lhs_batch)):\n func = broadcasting_vmap(func, in_axes=0)\n return func(lhs_data, lhs_indices, rhs_data, rhs_indices)\n\n@bcoo_spdot_general_p.def_abstract_eval\ndef _bcoo_spdot_general_abstract_eval(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n lhs_shape = lhs_spinfo.shape\n rhs_shape = rhs_spinfo.shape\n\n if lhs_data.dtype != rhs_data.dtype:\n raise ValueError(\"bcoo_spdot_general requires inputs to have matching dtypes; \"\n f\"got lhs.dtype={lhs_data.dtype}, rhs.dtype={rhs_data.dtype}\")\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n _ = _dot_general_validated_shape(lhs_shape, rhs_shape, dimension_numbers)\n\n if lhs.n_dense or rhs.n_dense:\n # TODO(jakevdp): handle dense dimensions\n raise NotImplementedError(\"bcoo_spdot_general with dense dimensions.\")\n\n if (lhs_batch and max(lhs_batch) >= lhs.n_batch) or (rhs_batch and max(rhs_batch) >= rhs.n_batch):\n raise NotImplementedError(\"bcoo_spdot_general: batch_dims must correspond to batch dimensions of the sparse representation.\")\n\n if lhs_contracting and (min(lhs_contracting) < lhs.n_batch or max(lhs_contracting) >= lhs.n_batch + lhs.n_sparse):\n raise NotImplementedError(\"bcoo_spdot_general only supports contraction of sparse indices.\")\n\n if rhs_contracting and (min(rhs_contracting) < rhs.n_batch or max(rhs_contracting) >= rhs.n_batch + rhs.n_sparse):\n raise NotImplementedError(\"bcoo_spdot_general only supports contraction of sparse indices.\")\n\n if rhs.n_batch > len(rhs_batch) and lhs.n_sparse > len(lhs_contracting):\n raise ValueError(\"bcoo_spdot_general: cannot have unused batch dims on rhs with unused sparse dims on lhs.\")\n\n out_nse = (\n (lhs.nse if lhs.n_sparse > len(lhs_contracting) else 1) *\n (rhs.nse if rhs.n_sparse > len(rhs_contracting) else 1)\n )\n\n data_shape = (\n *(lhs_shape[dim] for dim in lhs_batch),\n *(lhs_data.shape[dim] for dim in range(lhs.n_batch) if dim not in lhs_batch),\n *(rhs_data.shape[dim] for dim in range(rhs.n_batch) if dim not in rhs_batch),\n out_nse)\n indices_shape = (\n *(lhs_shape[dim] for dim in lhs_batch),\n *(lhs_indices.shape[dim] for dim in range(lhs.n_batch) if dim not in lhs_batch),\n *(rhs_indices.shape[dim] for dim in range(rhs.n_batch) if dim not in rhs_batch),\n out_nse, lhs.n_sparse + rhs.n_sparse - 2 * len(lhs_contracting))\n return core.ShapedArray(data_shape, lhs_data.dtype), core.ShapedArray(indices_shape, lhs_indices.dtype)\n\ndef _bcoo_spdot_general_batch_rule(batched_args, batch_dims, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n lhs_shape = lhs_spinfo.shape\n rhs_shape = rhs_spinfo.shape\n\n lhs_data, lhs_indices, rhs_data, rhs_indices = batched_args\n batch_dims = list(batch_dims)\n batch_size = max(0 if dim is None else arg.shape[dim]\n for arg, dim in zip(batched_args, batch_dims))\n if batch_dims[0] is None:\n lhs_data = lhs_data[None]\n batch_dims[0] = 0\n if batch_dims[1] is None:\n lhs_indices = lhs_indices[None]\n batch_dims[1] = 0\n assert batch_dims[0] == batch_dims[1] == 0\n if batch_dims[2] is None:\n rhs_data = rhs_data[None]\n batch_dims[2] = 0\n if batch_dims[3] is None:\n rhs_indices = rhs_indices[None]\n batch_dims[3] = 0\n if any(dim != 0 for dim in batch_dims):\n raise NotImplementedError(\"batching along non-leading dimension.\")\n assert all(dim == 0 for dim in batch_dims)\n new_dimension_numbers, result_batch_dim = _dot_general_batch_dim_nums(\n (len(lhs_shape), len(rhs_shape)), (batch_dims[0], batch_dims[2]), dimension_numbers)\n new_lhs_shape = (batch_size, *lhs_shape)\n new_rhs_shape = (batch_size, *rhs_shape)\n batched_out = bcoo_spdot_general(lhs_data, lhs_indices, rhs_data, rhs_indices,\n dimension_numbers=new_dimension_numbers,\n lhs_spinfo=BCOOInfo(new_lhs_shape),\n rhs_spinfo=BCOOInfo(new_rhs_shape))\n return batched_out, (result_batch_dim, result_batch_dim)\n\n\ndef _bcoo_spdot_general_jvp(primals, tangents, **kwds):\n lhs_data, lhs_indices, rhs_data, rhs_indices = primals\n lhs_data_dot, lhs_indices_dot, rhs_data_dot, rhs_indices_dot = tangents\n primals_out = bcoo_spdot_general(*primals, **kwds)\n assert type(lhs_indices_dot) is ad.Zero\n assert type(rhs_indices_dot) is ad.Zero\n data_dot_out = 0\n if type(lhs_data_dot) is not ad.Zero:\n data_dot_out += bcoo_spdot_general(lhs_data_dot, lhs_indices, rhs_data, rhs_indices, **kwds)[0]\n if type(rhs_data_dot) is not ad.Zero:\n data_dot_out += bcoo_spdot_general(lhs_data, lhs_indices, rhs_data_dot, rhs_indices, **kwds)[0]\n return primals_out, [data_dot_out, ad.Zero.from_value(primals_out[1])]\n\n# TODO(JVP): transpose rule\nbatching.primitive_batchers[bcoo_spdot_general_p] = _bcoo_spdot_general_batch_rule\nad.primitive_jvps[bcoo_spdot_general_p] = _bcoo_spdot_general_jvp\nxla.register_translation(bcoo_spdot_general_p, xla.lower_fun(\n _bcoo_spdot_general_impl, multiple_results=True, new_style=True))\n\n#----------------------------------------------------------------------\n# BCOO functions that maybe should be primitives?\n\ndef bcoo_broadcast_in_dim(data, indices, *, spinfo, shape, broadcast_dimensions):\n \"\"\"BCOO equivalent of lax.broadcast_in_dim\"\"\"\n if len(spinfo.shape) != len(broadcast_dimensions):\n raise ValueError(f\"spinfo.shape={spinfo.shape} and broadcast_dimensions={broadcast_dimensions} must have the same length\")\n props = _validate_bcoo(data, indices, spinfo.shape)\n batch_dims, sparse_dims, dense_dims = split_list(broadcast_dimensions, [props.n_batch, props.n_sparse])\n\n if max(batch_dims, default=0) > min(sparse_dims, default=len(shape)):\n raise ValueError(\"Cannot mix batch and sparse dimensions during broadcast_in_dim\")\n if max(sparse_dims, default=0) > min(dense_dims, default=len(shape)):\n raise ValueError(\"Cannot mix sparse and dense dimensions during broadcast_in_dim\")\n\n new_n_batch = props.n_batch and 1 + max(broadcast_dimensions[:props.n_batch])\n new_n_dense = props.n_dense and len(shape) - min(broadcast_dimensions[-props.n_dense:])\n new_n_sparse = len(shape) - new_n_batch - new_n_dense\n\n if np.prod(spinfo.shape[props.n_batch: props.n_batch + props.n_sparse]) != np.prod(shape[new_n_batch:new_n_batch + new_n_sparse]):\n raise NotImplementedError(\"Adding sparse dimensions with lengths != 1\")\n nse = props.nse\n\n # batch & dense dimensions\n new_data = lax.broadcast_in_dim(data,\n shape=(*shape[:new_n_batch], nse, *shape[new_n_batch + new_n_sparse:]),\n broadcast_dimensions=(*batch_dims, new_n_batch, *(b + 1 - new_n_sparse for b in dense_dims)))\n new_indices = lax.broadcast_in_dim(indices,\n shape=(*shape[:new_n_batch], nse, props.n_sparse),\n broadcast_dimensions=(*batch_dims, new_n_batch, new_n_batch + 1))\n\n # sparse dimensions\n new_indices = (jnp.zeros_like(new_indices, shape=(*shape[:new_n_batch], nse, new_n_sparse))\n .at[..., jnp.array(sparse_dims, int) - new_n_batch].set(new_indices))\n\n return new_data, new_indices\n\ndef _tuple_replace(tup, ind, val):\n return tuple(val if i == ind else t for i, t in enumerate(tup))\n\ndef bcoo_reduce_sum(data, indices, *, spinfo, axes):\n shape = spinfo.shape\n assert all(0 <= a < len(shape) for a in axes)\n n_batch, n_sparse, _, nse = _validate_bcoo(data, indices, shape)\n axes = sorted(set(axes))\n\n # Sum over dense dimensions -> sum over data\n dense_axes = tuple(ax - n_sparse + 1 for ax in axes if ax >= n_batch + n_sparse)\n data = data.sum(dense_axes)\n if n_sparse:\n # zero-out data corresponding to invalid indices.\n fill_value = jnp.expand_dims(\n jnp.array(shape[n_batch: n_batch + n_sparse]), range(indices.ndim - 1))\n mask = jnp.all(indices < fill_value, -1)\n if data.ndim > mask.ndim:\n mask = lax.expand_dims(mask, tuple(range(mask.ndim, data.ndim)))\n data = jnp.where(mask, data, 0)\n\n # Sum over sparse dimensions -> drop index; sum is implicit\n sparse_idx = [i for i in range(n_sparse) if i + n_batch not in axes]\n if not sparse_idx:\n indices = jnp.zeros(_tuple_replace(indices.shape, n_batch + 1, 0), indices.dtype)\n else:\n indices = indices[..., np.array(sparse_idx)]\n\n # Sum over batch dimensions -> reshape into nse\n batch_axes = {ax for ax in axes if ax < n_batch}\n\n # First handle broadcasted batch dimensions\n for ax in batch_axes:\n if data.shape[ax] == 1:\n if indices.shape[ax] == 1:\n data = data * shape[ax]\n else:\n data = lax.broadcast_in_dim(data, _tuple_replace(data.shape, ax, shape[ax]), tuple(range(data.ndim)))\n else:\n if indices.shape[ax] == 1:\n data = data.sum(ax)\n assert data.shape[ax] == indices.shape[ax]\n\n new_batch_dims = tuple(sorted(set(range(n_batch)) - batch_axes))\n new_batch_shape = tuple(data.shape[i] for i in new_batch_dims)\n new_nse = int(nse * np.prod([data.shape[i] for i in batch_axes]))\n\n data = lax.reshape(data,\n (*new_batch_shape, new_nse, *data.shape[n_batch + 1:]),\n (*new_batch_dims, *batch_axes, *range(n_batch, data.ndim)))\n indices = lax.reshape(indices,\n (*new_batch_shape, new_nse, *indices.shape[n_batch + 1:]),\n (*new_batch_dims, *batch_axes, *range(n_batch, indices.ndim)))\n\n out_shape = tuple(shape[i] for i in range(len(shape)) if i not in axes)\n return data, indices, out_shape\n\ndef bcoo_multiply_sparse(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo, rhs_spinfo):\n lhs_shape = lhs_spinfo.shape\n rhs_shape = rhs_spinfo.shape\n\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n if len(lhs_shape) != len(rhs_shape):\n # Similar requirement as lax.mul:\n raise TypeError(\"bcoo_multiply_sparse: arrays must have same number of dimensions, \"\n f\"got {lhs_shape}, {rhs_shape}\")\n if lhs.n_dense != rhs.n_dense:\n raise NotImplementedError(\"bcoo_multiply_sparse: arrays with differing numbers of \"\n f\"dense dimensions: {lhs}, {rhs}\")\n n_batch = min(lhs.n_batch, rhs.n_batch)\n _mul = functools.partial(_bcoo_multiply_sparse_unbatched,\n lhs_shape=lhs_shape[n_batch:],\n rhs_shape=rhs_shape[n_batch:])\n for _ in range(n_batch):\n _mul = broadcasting_vmap(_mul)\n data, indices = _mul(lhs_data, lhs_indices, rhs_data, rhs_indices)\n return data, indices, jnp.broadcast_shapes(lhs_shape, rhs_shape)\n\ndef _bcoo_multiply_sparse_unbatched(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_shape, rhs_shape):\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n assert (lhs.n_batch == 0) or (rhs.n_batch == 0) # Ensured at call site above\n\n # TODO(jakevdp): this can be made more efficient by utilizing batch structure.\n if lhs.n_batch:\n lhs_data, lhs_indices = _unbatch_bcoo(lhs_data, lhs_indices, lhs_shape)\n lhs = _validate_bcoo(lhs_data, lhs_indices, lhs_shape)\n elif rhs.n_batch:\n rhs_data, rhs_indices = _unbatch_bcoo(rhs_data, rhs_indices, rhs_shape)\n rhs = _validate_bcoo(rhs_data, rhs_indices, rhs_shape)\n dims = jnp.array([i for i, (s1, s2) in enumerate(safe_zip(lhs_shape[:lhs.n_sparse], rhs_shape[:rhs.n_sparse]))\n if s1 != 1 and s2 != 1], dtype=int)\n\n # TODO(jakevdp): this nse can be tightened to min(lhs.nse, rhs.nse) if there\n # is no broadcasting and indices are unique.\n nse = lhs.nse * rhs.nse\n\n # TODO(jakevdp): this is pretty inefficient. Can we do this membership check\n # without constructing the full (lhs.nse, rhs.nse) masking matrix?\n mask = jnp.all(lhs_indices[:, None, dims] == rhs_indices[None, :, dims], -1)\n i_lhs, i_rhs = jnp.nonzero(mask, size=nse, fill_value=(lhs.nse, rhs.nse))\n data = (lhs_data.at[i_lhs].get(mode='fill', fill_value=0) *\n rhs_data.at[i_rhs].get(mode='fill', fill_value=0))\n indices = jnp.maximum(\n lhs_indices.at[i_lhs].get(mode='fill', fill_value=max(lhs_shape, default=0)),\n rhs_indices.at[i_rhs].get(mode='fill', fill_value=max(rhs_shape, default=0)))\n return data, indices\n\ndef bcoo_multiply_dense(data, indices, v, *, spinfo):\n \"\"\"Broadcasted elementwise multiplication between a BCOO array and a dense array.\"\"\"\n # TODO(jakevdp): the logic here is similar to bcoo_extract... can we reuse that?\n shape = spinfo.shape\n if v.ndim == 0:\n return lax.mul(data, v)\n if shape == v.shape:\n # Note: due to distributive property, no deduplication necessary!\n return lax.mul(data, bcoo_extract(indices, v))\n\n if lax.broadcast_shapes(v.shape, shape) != shape:\n raise NotImplementedError(\n \"multiplication between sparse and dense is only implemented for cases \"\n \"where the output shape matches the sparse matrix shape. Got \"\n f\"shape={shape}, v.shape={v.shape}\")\n v = lax.expand_dims(v, range(len(shape) - v.ndim))\n\n props = _validate_bcoo(data, indices, shape)\n\n def _mul(data, indices, v):\n assert indices.shape[1] == v.ndim - props.n_dense\n ind = tuple(indices[:, i] for i in range(indices.shape[1]))\n ind = tuple(i if s != 1 else 0 for i, s in zip(ind, v.shape))\n return data * v[ind]\n for _ in range(props.n_batch):\n _mul = broadcasting_vmap(_mul)\n return _mul(data, indices, v)\n\n@tree_util.register_pytree_node_class\nclass BCOO(JAXSparse):\n \"\"\"Experimental batched COO matrix implemented in JAX\n\n Args:\n (data, indices) : data and indices in batched COO format.\n shape : shape of sparse array.\n\n Attributes:\n data : ndarray of shape ``[*batch_dims, nse, *dense_dims]`` containing the\n explicitly stored data within the sparse matrix.\n indices : ndarray of shape ``[*batch_dims, nse, n_sparse]`` containing the\n indices of the explicitly stored data. Duplicate entries will be summed.\n\n Examples:\n Create a sparse array from a dense array:\n\n >>> M = jnp.array([[0., 2., 0.], [1., 0., 4.]])\n >>> M_sp = BCOO.fromdense(M)\n >>> M_sp\n BCOO(float32[2, 3], nse=3)\n\n Examine the internal representation:\n\n >>> M_sp.data\n DeviceArray([2., 1., 4.], dtype=float32)\n >>> M_sp.indices\n DeviceArray([[0, 1],\n [1, 0],\n [1, 2]], dtype=int32)\n\n Create a dense array from a sparse array:\n\n >>> M_sp.todense()\n DeviceArray([[0., 2., 0.],\n [1., 0., 4.]], dtype=float32)\n\n Create a sparse array from COO data & indices:\n\n >>> data = jnp.array([1., 3., 5.])\n >>> indices = jnp.array([[0, 0],\n ... [1, 1],\n ... [2, 2]])\n >>> mat = BCOO((data, indices), shape=(3, 3))\n >>> mat\n BCOO(float32[3, 3], nse=3)\n >>> mat.todense()\n DeviceArray([[1., 0., 0.],\n [0., 3., 0.],\n [0., 0., 5.]], dtype=float32)\n \"\"\"\n # Note: additional BCOO methods are defined in transform.py\n\n data: jnp.ndarray\n indices: jnp.ndarray\n shape: Shape\n nse = property(lambda self: self.indices.shape[-2])\n dtype = property(lambda self: self.data.dtype)\n n_batch = property(lambda self: self.indices.ndim - 2)\n n_sparse = property(lambda self: self.indices.shape[-1])\n n_dense = property(lambda self: self.data.ndim - 1 - self.n_batch)\n _info = property(lambda self: BCOOInfo(self.shape))\n\n def __init__(self, args, *, shape):\n # JAX transforms will sometimes instantiate pytrees with null values, so we\n # must catch that in the initialization of inputs.\n self.data, self.indices = _safe_asarray(args)\n super().__init__(args, shape=shape)\n\n @classmethod\n def fromdense(cls, mat, *, nse=None, index_dtype=np.int32, n_dense=0, n_batch=0):\n \"\"\"Create a BCOO array from a (dense) :class:`DeviceArray`.\"\"\"\n return cls(bcoo_fromdense(mat, nse=nse, index_dtype=index_dtype, n_dense=n_dense, n_batch=n_batch), shape=mat.shape)\n\n @classmethod\n def from_scipy_sparse(cls, mat, *, index_dtype=None, n_dense=0, n_batch=0):\n \"\"\"Create a BCOO array from a :mod:`scipy.sparse` array.\"\"\"\n if n_dense != 0 or n_batch != 0:\n raise NotImplementedError(\"BCOO.fromscipy with nonzero n_dense/n_batch\")\n mat = mat.tocoo()\n data = jnp.asarray(mat.data)\n indices = jnp.column_stack((mat.row, mat.col)).astype(index_dtype or jnp.int32)\n return cls((data, indices), shape=mat.shape)\n\n @classmethod\n def _empty(cls, shape, *, dtype=None, index_dtype='int32', n_dense=0, n_batch=0, nse=0):\n \"\"\"Create an empty BCOO instance. Public method is sparse.empty().\"\"\"\n shape = tuple(shape)\n n_sparse = len(shape) - n_dense - n_batch\n if n_sparse < 0 or n_dense < 0 or n_batch < 0 or nse < 0:\n raise ValueError(f\"Invalid inputs: shape={shape}, n_dense={n_dense}, n_batch={n_batch}, nse={nse}\")\n batch_shape, sparse_shape, dense_shape = split_list(shape, [n_batch, n_sparse])\n data = jnp.zeros((*batch_shape, nse, *dense_shape), dtype)\n indices = jnp.full((*batch_shape, nse, n_sparse), jnp.array(sparse_shape), index_dtype)\n return cls((data, indices), shape=shape)\n\n def _unbatch(self):\n \"\"\"Return an unbatched representation of the BCOO matrix.\"\"\"\n return BCOO(_unbatch_bcoo(self.data, self.indices, self.shape), shape=self.shape)\n\n def _dedupe(self):\n warnings.warn(\"_dedupe() is deprecated. Use sum_duplicates() instead.\", FutureWarning)\n return self.sum_duplicates(nse=self.nse)\n\n def sum_duplicates(self, nse=None, remove_zeros=True):\n \"\"\"Return a copy of the array with duplicate indices summed.\n\n Additionally, this operation will result in explicit zero entries removed, and\n indices being sorted in lexicographic order.\n\n Because the size of the resulting representation depends on the values in the\n arrays, this operation is not compatible with JIT or other transforms. To use\n ``sum_duplicates`` in such cases, you may pass a value to `nse` to specify the\n desired size of the output representation.\n\n Args:\n nse : integer (optional), if specified, gives the number of specified elements in\n the output sparse representation; if it is larger than the number required, data\n will be padded with zeros and indices will be padded with out-of-bounds values.\n If it is smaller than the number required, data will be silently discarded.\n remove_zeros : bool (default=True). If True, remove explicit zeros from the data\n as part of summing duplicates. If False, then explicit zeros at unique indices\n will remain among the specified elements.\n \"\"\"\n data, indices = _bcoo_sum_duplicates(self.data, self.indices, self.shape,\n nse=nse, remove_zeros=remove_zeros)\n return BCOO((data, indices), shape=self.shape)\n\n def sort_indices(self):\n \"\"\"Return a copy of the matrix with indices sorted.\"\"\"\n data, indices = _bcoo_sort_indices(self.data, self.indices, self.shape)\n return BCOO((data, indices), shape=self.shape)\n\n def todense(self):\n \"\"\"Create a dense version of the array.\"\"\"\n return bcoo_todense(self.data, self.indices, spinfo=self._info)\n\n def transpose(self, axes=None):\n \"\"\"Create a new array containing the transpose.\"\"\"\n axes = np.arange(self.ndim)[::-1] if axes is None else axes\n data_T, indices_T = bcoo_transpose(self.data, self.indices, permutation=axes, spinfo=self._info)\n shape_T = tuple(self.shape[i] for i in axes)\n return BCOO((data_T, indices_T), shape=shape_T)\n\n def tree_flatten(self):\n return (self.data, self.indices), self._info._asdict()\n\n\n# vmappable handlers\ndef _bcoo_to_elt(cont, _, val, axis):\n if axis is None:\n return val\n if axis >= val.n_batch:\n raise ValueError(f\"Cannot map in_axis={axis} for BCOO array with n_batch={val.n_batch}. \"\n \"in_axes for batched BCOO operations must correspond to a batch dimension.\")\n return BCOO((cont(val.data, axis), cont(val.indices, axis)),\n shape= val.shape[:axis] + val.shape[axis + 1:])\n\ndef _bcoo_from_elt(cont, axis_size, elt, axis):\n if axis > elt.n_batch:\n raise ValueError(f\"BCOO: cannot add out_axis={axis} for BCOO array with n_batch={elt.n_batch}. \"\n \"BCOO batch axes must be a contiguous block of leading dimensions.\")\n return BCOO((cont(axis_size, elt.data, axis), cont(axis_size, elt.indices, axis)),\n shape=elt.shape[:axis] + (axis_size,) + elt.shape[axis:])\n\nbatching.register_vmappable(BCOO, int, int, _bcoo_to_elt, _bcoo_from_elt, None)\n" ]
[ [ "numpy.complex128", "numpy.uint32", "numpy.uint8", "numpy.float16", "numpy.int32", "numpy.int64", "numpy.uint16", "numpy.float64", "numpy.float32", "numpy.bool_", "numpy.empty", "numpy.complex64" ], [ "numpy.meshgrid", "numpy.arange", "numpy.prod", "numpy.argsort", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shikiponn/optuna
[ "a151fafc4d816d9ba7d6740adf8892a7832f83a9" ]
[ "optuna/storages/base.py" ]
[ "import abc\nimport numpy as np\nimport six\nfrom typing import Any # NOQA\nfrom typing import Dict # NOQA\nfrom typing import List # NOQA\nfrom typing import Optional # NOQA\nfrom typing import Tuple # NOQA\n\nfrom optuna import distributions # NOQA\nfrom optuna import structs # NOQA\n\nDEFAULT_STUDY_NAME_PREFIX = 'no-name-'\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass BaseStorage(object):\n \"\"\"Base class for storages.\n\n This class is not supposed to be directly accessed by library users.\n\n Storage classes abstract a backend database and provide library internal interfaces to\n read/write history of studies and trials.\n \"\"\"\n\n # Basic study manipulation\n\n @abc.abstractmethod\n def create_new_study_id(self, study_name=None):\n # type: (Optional[str]) -> int\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_study_user_attr(self, study_id, key, value):\n # type: (int, str, Any) -> None\n\n raise NotImplementedError\n\n @ abc.abstractmethod\n def set_study_direction(self, study_id, direction):\n # type: (int, structs.StudyDirection) -> None\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_study_system_attr(self, study_id, key, value):\n # type: (int, str, Any) -> None\n\n raise NotImplementedError\n\n # Basic study access\n\n @abc.abstractmethod\n def get_study_id_from_name(self, study_name):\n # type: (str) -> int\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_study_name_from_id(self, study_id):\n # type: (int) -> str\n\n raise NotImplementedError\n\n @ abc.abstractmethod\n def get_study_direction(self, study_id):\n # type: (int) -> structs.StudyDirection\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_study_user_attrs(self, study_id):\n # type: (int) -> Dict[str, Any]\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_study_system_attrs(self, study_id):\n # type: (int) -> Dict[str, Any]\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_all_study_summaries(self):\n # type: () -> List[structs.StudySummary]\n\n raise NotImplementedError\n\n # Basic trial manipulation\n\n @abc.abstractmethod\n def create_new_trial_id(self, study_id):\n # type: (int) -> int\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_state(self, trial_id, state):\n # type: (int, structs.TrialState) -> None\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_param(self, trial_id, param_name, param_value_internal, distribution):\n # type: (int, str, float, distributions.BaseDistribution) -> bool\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_trial_param(self, trial_id, param_name):\n # type: (int, str) -> float\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_value(self, trial_id, value):\n # type: (int, float) -> None\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_intermediate_value(self, trial_id, step, intermediate_value):\n # type: (int, int, float) -> bool\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_user_attr(self, trial_id, key, value):\n # type: (int, str, Any) -> None\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def set_trial_system_attr(self, trial_id, key, value):\n # type: (int, str, Any) -> None\n\n raise NotImplementedError\n\n # Basic trial access\n\n @abc.abstractmethod\n def get_trial(self, trial_id):\n # type: (int) -> structs.FrozenTrial\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_all_trials(self, study_id):\n # type: (int) -> List[structs.FrozenTrial]\n\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_n_trials(self, study_id, state=None):\n # type: (int, Optional[structs.TrialState]) -> int\n\n raise NotImplementedError\n\n def get_best_trial(self, study_id):\n # type: (int) -> structs.FrozenTrial\n\n all_trials = self.get_all_trials(study_id)\n all_trials = [t for t in all_trials if t.state is structs.TrialState.COMPLETE]\n\n if len(all_trials) == 0:\n raise ValueError('No trials are completed yet.')\n\n # TODO(sano): Deal with maximize direction.\n return min(all_trials, key=lambda t: t.value)\n\n def get_trial_params(self, trial_id):\n # type: (int) -> Dict[str, Any]\n\n return self.get_trial(trial_id).params\n\n def get_trial_user_attrs(self, trial_id):\n # type: (int) -> Dict[str, Any]\n\n return self.get_trial(trial_id).user_attrs\n\n def get_trial_system_attrs(self, trial_id):\n # type: (int) -> Dict[str, Any]\n\n return self.get_trial(trial_id).system_attrs\n\n # Methods for the TPE sampler\n\n def get_trial_param_result_pairs(self, study_id, param_name):\n # type: (int, str) -> List[Tuple[float, float]]\n\n # Be careful: this method returns param values in internal representation\n all_trials = self.get_all_trials(study_id)\n\n return [\n (t.params_in_internal_repr[param_name], t.value)\n for t in all_trials\n if (t.value is not None and\n param_name in t.params and\n t.state is structs.TrialState.COMPLETE)\n # TODO(Akiba): We also want to use pruned results\n ]\n\n # Methods for the median pruner\n\n def get_best_intermediate_result_over_steps(self, trial_id):\n # type: (int) -> float\n\n return np.nanmin(np.array(\n list(self.get_trial(trial_id).intermediate_values.values()),\n np.float))\n\n def get_median_intermediate_result_over_trials(self, study_id, step):\n # type: (int, int) -> float\n\n all_trials = [t for t in self.get_all_trials(study_id)\n if t.state == structs.TrialState.COMPLETE]\n\n if len(all_trials) == 0:\n raise ValueError(\"No trials have been completed.\")\n\n return float(np.nanmedian(np.array([\n t.intermediate_values[step] for t in all_trials\n if step in t.intermediate_values\n ], np.float)))\n\n def remove_session(self):\n # type: () -> None\n\n pass\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bklppr/yolo2_onnx
[ "fcb85bd94e22c1c47f20fc13bb6ae3ac1ccd10f4" ]
[ "dataset.py" ]
[ "#!/usr/bin/python\n# encoding: utf-8\n\nimport os\nimport random\nimport torch\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nfrom utils import read_truths_args, read_truths\nfrom image import *\n\nclass listDataset(Dataset):\n\n def __init__(self, root, shape=None, shuffle=True, transform=None, target_transform=None, train=False, seen=0, batch_size=8, num_workers=2):\n with open(root, 'r') as file:\n self.lines = file.readlines()\n\n if shuffle:\n random.shuffle(self.lines)\n\n self.nSamples = len(self.lines)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n self.shape = shape\n self.seen = seen\n self.batch_size = batch_size\n self.num_workers = num_workers\n\n def __len__(self):\n return self.nSamples\n\n def __getitem__(self, index):\n assert index <= len(self), 'index range error'\n imgpath = self.lines[index].rstrip()\n\n if self.train and index % 64== 0:\n if self.seen < 4000*64:\n width = 13*32\n self.shape = (width, width)\n elif self.seen < 8000*64:\n width = (random.randint(0,3) + 13)*32\n self.shape = (width, width)\n elif self.seen < 12000*64:\n width = (random.randint(0,5) + 12)*32\n self.shape = (width, width)\n elif self.seen < 16000*64:\n width = (random.randint(0,7) + 11)*32\n self.shape = (width, width)\n else: # self.seen < 20000*64:\n width = (random.randint(0,9) + 10)*32\n self.shape = (width, width)\n\n if self.train:\n jitter = 0.2\n hue = 0.1\n saturation = 1.5 \n exposure = 1.5\n\n img, label = load_data_detection(imgpath, self.shape, jitter, hue, saturation, exposure)\n label = torch.from_numpy(label)\n else:\n img = Image.open(imgpath).convert('RGB')\n if self.shape:\n img = img.resize(self.shape)\n \n labpath = imgpath.replace('images', 'labels').replace('JPEGImages', 'labels').replace('.jpg', '.txt').replace('.png','.txt')\n label = torch.zeros(50*5)\n #if os.path.getsize(labpath):\n #tmp = torch.from_numpy(np.loadtxt(labpath))\n try:\n tmp = torch.from_numpy(read_truths_args(labpath, 8.0/img.width).astype('float32'))\n except Exception:\n tmp = torch.zeros(1,5)\n #tmp = torch.from_numpy(read_truths(labpath))\n tmp = tmp.view(-1)\n tsz = tmp.numel()\n #print('labpath = %s , tsz = %d' % (labpath, tsz))\n if tsz > 50*5:\n label = tmp[0:50*5]\n elif tsz > 0:\n label[0:tsz] = tmp\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n label = self.target_transform(label)\n\n self.seen = self.seen + self.num_workers\n return (img, label)\n" ]
[ [ "torch.from_numpy", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ZitongLu1996/NeuroRA
[ "4e72f5b37ff308a4a068107b35f7555df6b7df0d" ]
[ "neurora/rsa_plot.py" ]
[ "# -*- coding: utf-8 -*-\n\n' a module for plotting the NeuroRA results '\n\n__author__ = 'Zitong Lu'\n\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy import signal\nfrom scipy.stats import ttest_1samp, ttest_rel\nfrom nilearn import plotting, datasets, surface\nimport nibabel as nib\nfrom neurora.stuff import get_affine, get_bg_ch2, get_bg_ch2bet, correct_by_threshold, \\\n clusterbased_permutation_1d_1samp_1sided, clusterbased_permutation_2d_1samp_1sided, \\\n clusterbased_permutation_1d_1samp_2sided, clusterbased_permutation_2d_2sided, smooth_1d\nfrom decimal import Decimal\n\n\n' a function for plotting the RDM '\n\ndef plot_rdm(rdm, percentile=False, rescale=False, lim=[0, 1], conditions=None, con_fontsize=12, cmap=None):\n\n \"\"\"\n Plot the RDM\n\n Parameters\n ----------\n rdm : array or list [n_cons, n_cons]\n A representational dissimilarity matrix.\n percentile : bool True or False. Default is False.\n Rescale the values in RDM or not by displaying the percentile.\n rescale : bool True or False. Default is False.\n Rescale the values in RDM or not.\n Here, the maximum-minimum method is used to rescale the values except for the\n values on the diagnal.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n conditions : string-array or string-list. Default is None.\n The labels of the conditions for plotting.\n conditions should contain n_cons strings, If conditions=None, the labels of conditions will be invisible.\n con_fontsize : int or float. Default is 12.\n The fontsize of the labels of the conditions for plotting.\n cmap : matplotlib colormap. Default is None.\n The colormap for RDM.\n If cmap=None, the ccolormap will be 'jet'.\n \"\"\"\n\n if len(np.shape(rdm)) != 2 or np.shape(rdm)[0] != np.shape(rdm)[1]:\n\n return \"Invalid input!\"\n\n # get the number of conditions\n cons = rdm.shape[0]\n\n crdm = copy.deepcopy(rdm)\n\n # if cons=2, the RDM cannot be plotted.\n if cons == 2:\n print(\"The shape of RDM cannot be 2*2. Here NeuroRA cannot plot this RDM.\")\n\n return None\n\n # determine if it's a square\n a, b = np.shape(crdm)\n if a != b:\n return None\n\n if percentile == True:\n\n v = np.zeros([cons * cons, 2], dtype=np.float)\n for i in range(cons):\n for j in range(cons):\n v[i * cons + j, 0] = crdm[i, j]\n\n index = np.argsort(v[:, 0])\n m = 0\n for i in range(cons * cons):\n if i > 0:\n if v[index[i], 0] > v[index[i - 1], 0]:\n m = m + 1\n v[index[i], 1] = m\n\n v[:, 0] = v[:, 1] * 100 / m\n\n for i in range(cons):\n for j in range(cons):\n crdm[i, j] = v[i * cons + j, 0]\n\n if cmap == None:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=plt.cm.jet, clim=(0, 100))\n else:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=cmap, clim=(0, 100))\n\n # rescale the RDM\n elif rescale == True:\n\n # flatten the RDM\n vrdm = np.reshape(rdm, [cons * cons])\n # array -> set -> list\n svrdm = set(vrdm)\n lvrdm = list(svrdm)\n lvrdm.sort()\n\n # get max & min\n maxvalue = lvrdm[-1]\n minvalue = lvrdm[1]\n\n # rescale\n if maxvalue != minvalue:\n\n for i in range(cons):\n for j in range(cons):\n\n # not on the diagnal\n if i != j:\n crdm[i, j] = float((crdm[i, j] - minvalue) / (maxvalue - minvalue))\n\n # plot the RDM\n min = lim[0]\n max = lim[1]\n if cmap == None:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=plt.cm.jet, clim=(min, max))\n else:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=cmap, clim=(min, max))\n\n else:\n\n # plot the RDM\n min = lim[0]\n max = lim[1]\n if cmap == None:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=plt.cm.jet, clim=(min, max))\n else:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=cmap, clim=(min, max))\n\n # plt.axis(\"off\")\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=16)\n font = {'size': 18}\n\n if percentile == True:\n cb.set_label(\"Dissimilarity (percentile)\", fontdict=font)\n elif rescale == True:\n cb.set_label(\"Dissimilarity (Rescaling)\", fontdict=font)\n else:\n cb.set_label(\"Dissimilarity\", fontdict=font)\n\n if conditions != None:\n print(\"1\")\n step = float(1 / cons)\n x = np.arange(0.5 * step, 1 + 0.5 * step, step)\n y = np.arange(1 - 0.5 * step, -0.5 * step, -step)\n plt.xticks(x, conditions, fontsize=con_fontsize, rotation=30, ha=\"right\")\n plt.yticks(y, conditions, fontsize=con_fontsize)\n else:\n plt.axis(\"off\")\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the RDM with values '\n\ndef plot_rdm_withvalue(rdm, lim=[0, 1], value_fontsize=10, conditions=None, con_fontsize=12, cmap=None):\n\n \"\"\"\n Plot the RDM with values\n\n Parameters\n ----------\n rdm : array or list [n_cons, n_cons]\n A representational dissimilarity matrix.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n value_fontsize : int or float. Default is 10.\n The fontsize of the values on the RDM.\n conditions : string-array or string-list or None. Default is None.\n The labels of the conditions for plotting.\n conditions should contain n_cons strings, If conditions=None, the labels of conditions will be invisible.\n con_fontsize : int or float. Default is 12.\n The fontsize of the labels of the conditions for plotting.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for RDM.\n If cmap=None, the ccolormap will be 'Greens'.\n \"\"\"\n\n if len(np.shape(rdm)) != 2 or np.shape(rdm)[0] != np.shape(rdm)[1]:\n\n return \"Invalid input!\"\n\n # get the number of conditions\n cons = rdm.shape[0]\n\n # if cons=2, the RDM cannot be plotted.\n if cons == 2:\n print(\"The shape of RDM cannot be 2*2. Here NeuroRA cannot plot this RDM.\")\n\n return None\n\n crdm = copy.deepcopy(rdm)\n\n # determine if it's a square\n a, b = np.shape(crdm)\n if a != b:\n return None\n\n # plot the RDM\n min = lim[0]\n max = lim[1]\n if cmap == None:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=plt.cm.Greens, clim=(min, max))\n else:\n plt.imshow(crdm, extent=(0, 1, 0, 1), cmap=cmap, clim=(min, max))\n\n # plt.axis(\"off\")\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=16)\n font = {'size': 18}\n cb.set_label(\"Dissimilarity\", fontdict=font)\n\n # add values\n step = float(1 / cons)\n for i in range(cons):\n for j in range(cons):\n print(i, j)\n text = plt.text(i * step + 0.5 * step, 1 - j * step - 0.5 * step, float('%.4f' % rdm[i, j]),\n ha=\"center\", va=\"center\", color=\"blue\", fontsize=value_fontsize)\n\n if conditions != None:\n print(\"1\")\n step = float(1 / cons)\n x = np.arange(0.5 * step, 1 + 0.5 * step, step)\n y = np.arange(1 - 0.5 * step, -0.5 * step, -step)\n plt.xticks(x, conditions, fontsize=con_fontsize, rotation=30, ha=\"right\")\n plt.yticks(y, conditions, fontsize=con_fontsize)\n else:\n plt.axis(\"off\")\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the correlation coefficients by time sequence '\n\ndef plot_corrs_by_time(corrs, labels=None, time_unit=[0, 0.1]):\n\n \"\"\"\n plot the correlation coefficients by time sequence\n\n corrs : array\n The correlation coefficients time-by-time.\n The shape of corrs must be [n, ts, 2] or [n, ts]. n represents the number of curves of the correlation\n coefficient by time sequence. ts represents the time-points. If shape of corrs is [n, ts 2], each time-point\n of each correlation coefficient curve contains a r-value and a p-value. If shape is [n, ts], only r-values.\n label : string-array or string-list or None. Default is None.\n The label for each corrs curve.\n If label=None, no legend in the figure.\n time_unit : array or list [start_t, t_step]. Default is [0, 0.1]\n The time information of corrs for plotting\n start_t represents the start time and t_step represents the time between two adjacent time-points. Default\n time_unit=[0, 0.1], which means the start time of corrs is 0 sec and the time step is 0.1 sec.\n \"\"\"\n\n if len(np.shape(corrs)) < 2 or len(np.shape(corrs)) > 3:\n\n return \"Invalid input!\"\n\n # get the number of curves\n n = corrs.shape[0]\n\n # get the number of time-points\n ts = corrs.shape[1]\n\n # get the start time and the time step\n start_t = time_unit[0]\n tstep = time_unit[1]\n\n # calculate the end time\n end_t = start_t + ts * tstep\n\n # initialize the x\n x = np.arange(start_t, end_t, tstep)\n\n # interp1d t\n t = ts * 50\n\n # initialize the interp1d x\n x_soft = np.linspace(x.min(), x.max(), t)\n\n # initialize the interp1d y\n y_soft = np.zeros([n, t])\n\n # interp1d\n for i in range(n):\n if len(corrs.shape) == 3:\n f = interp1d(x, corrs[i, :, 0], kind='cubic')\n y_soft[i] = f(x_soft)\n if len(corrs.shape) == 2:\n f = interp1d(x, corrs[i, :], kind='cubic')\n y_soft[i] = f(x_soft)\n\n # get the max value\n vmax = np.max(y_soft)\n # get the min value\n vmin = np.min(y_soft)\n\n if vmax <= 1/1.1:\n ymax = np.max(y_soft)*1.1\n else:\n ymax = 1\n\n if vmin >= 0:\n ymin = -0.1\n elif vmin < 0 and vmin > -1/1.1:\n ymin = np.min(y_soft)*1.1\n else:\n ymin = -1\n\n fig, ax = plt.subplots()\n\n for i in range(n):\n\n if labels:\n plt.plot(x_soft, y_soft[i], linewidth=3, label=labels[i])\n else:\n plt.plot(x_soft, y_soft[i], linewidth=3)\n\n plt.ylim(ymin, ymax)\n plt.ylabel(\"Similarity\", fontsize=20)\n plt.xlabel(\"Time (s)\", fontsize=20)\n plt.tick_params(labelsize=18)\n\n if labels:\n plt.legend()\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the time-by-time Similarities with statistical results'\n\ndef plot_tbytsim_withstats(similarities, start_time=0, end_time=1, time_interval=0.01, smooth=True, p=0.05, cbpt=True,\n clusterp=0.05, stats_time=[0, 1], color='r', xlim=[0, 1], ylim=[-0.1, 0.8],\n xlabel='Time (s)', ylabel='Representational Similarity', figsize=[6.4, 3.6], x0=0,\n ticksize=12, fontsize=16, markersize=2, avgshow=False):\n\n \"\"\"\n Plot the time-by-time Similarities with statistical results\n\n Parameters\n ----------\n similarities : array\n The Similarities.\n The size of similarities should be [n_subs, n_ts] or [n_subs, n_ts, 2]. n_subs, n_ts represent the number of\n subjects and number of time-points. 2 represents the similarity and a p-value.\n start_time : int or float. Default is 0.\n The start time.\n end_time : int or float. Default is 1.\n The end time.\n time_interval : float. Default is 0.01.\n The time interval between two time samples.\n smooth : bool True or False. Default is True.\n Smooth the results or not.\n chance : float. Default is 0.5.\n The chance level.\n p : float. Default is 0.05.\n The threshold of p-values.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_time : array or list [stats_time1, stats_time2]. Default os [0, 1].\n Time period for statistical analysis.\n color : matplotlib color or None. Default is 'r'.\n The color for the curve.\n xlim : array or list [xmin, xmax]. Default is [0, 1].\n The x-axis (time) view lims.\n ylim : array or list [ymin, ymax]. Default is [0.4, 0.8].\n The y-axis (decoding accuracy) view lims.\n xlabel : string. Default is 'Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Representational Similarity'.\n The label of y-axis.\n figsize : array or list, [size_X, size_Y]. Default is [6.4, 3.6].\n The size of the figure.\n x0 : float. Default is 0.\n The Y-axis is at x=x0.\n ticksize : int or float. Default is 12.\n The size of the ticks.\n fontsize : int or float. Default is 16.\n The fontsize of the labels.\n markersize : int or float. Default is 2.\n The size of significant marker.\n avgshow : boolen True or False. Default is False.\n Show the averaging decoding accuracies or not.\n \"\"\"\n\n if len(np.shape(similarities)) < 2 or len(np.shape(similarities)) > 3:\n\n return \"Invalid input!\"\n\n n = len(np.shape(similarities))\n\n yminlim = ylim[0]\n ymaxlim = ylim[1]\n\n if n == 3:\n similarities = similarities[:, :, 0]\n\n csimilarities = copy.deepcopy(similarities)\n\n nsubs, nts = np.shape(csimilarities)\n tstep = float(Decimal((end_time - start_time) / nts).quantize(Decimal(str(time_interval))))\n\n if tstep != time_interval:\n return \"Invalid input!\"\n\n delta1 = (stats_time[0] - start_time) / tstep - int((stats_time[0] - start_time) / tstep)\n delta2 = (stats_time[1] - start_time) / tstep - int((stats_time[1] - start_time) / tstep)\n if delta1 == 0:\n stats_time1 = int((stats_time[0] - start_time) / tstep)\n else:\n stats_time1 = int((stats_time[0] - start_time) / tstep) + 1\n if delta2 == 0:\n stats_time2 = int((stats_time[1] - start_time) / tstep)\n else:\n stats_time2 = int((stats_time[1] - start_time) / tstep) + 1\n\n if smooth is True:\n for sub in range(nsubs):\n for t in range(nts):\n\n if t<=1:\n csimilarities[sub, t] = np.average(csimilarities[sub, :t+3])\n if t>1 and t<(nts-2):\n csimilarities[sub, t] = np.average(csimilarities[sub, t-2:t+3])\n if t>=(nts-2):\n csimilarities[sub, t] = np.average(csimilarities[sub, t-2:])\n\n avg = np.average(csimilarities, axis=0)\n err = np.zeros([nts], dtype=np.float)\n\n for t in range(nts):\n err[t] = np.std(csimilarities[:, t], ddof=1)/np.sqrt(nsubs)\n\n if cbpt == True:\n ps_stats = clusterbased_permutation_1d_1samp_1sided(csimilarities[:, stats_time1:stats_time2], level=0,\n p_threshold=p, clusterp_threshold=clusterp)\n ps = np.zeros([nts])\n ps[stats_time1:stats_time2] = ps_stats\n else:\n ps = np.zeros([nts])\n for t in range(nts):\n ps[t] = ttest_1samp(csimilarities[:, t], 0, alternative=\"greater\")[1]\n if ps[t] < p:\n ps[t] = 1\n else:\n ps[t] = 0\n\n for t in range(nts):\n if ps[t] == 1:\n plt.plot(t*tstep+start_time+0.5*tstep, (ymaxlim-yminlim)*0.95+yminlim, 's',\n color=color, alpha=0.8, markersize=markersize)\n xi = [t*tstep+start_time, t*tstep+tstep+start_time]\n ymin = [0]\n ymax = [avg[t]-err[t]]\n plt.fill_between(xi, ymax, ymin, facecolor=color, alpha=0.1)\n\n fig = plt.gcf()\n fig.set_size_inches(figsize[0], figsize[1])\n\n ax = plt.gca()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_linewidth(3)\n ax.spines[\"left\"].set_position((\"data\", x0))\n ax.spines[\"bottom\"].set_linewidth(3)\n ax.spines['bottom'].set_position(('data', 0))\n x = np.arange(start_time+0.5*tstep, end_time+0.5*tstep, tstep)\n if avgshow is True:\n plt.plot(x, avg, color=color, alpha=0.9)\n plt.fill_between(x, avg + err, avg - err, facecolor=color, alpha=0.8)\n plt.ylim(yminlim, ymaxlim)\n plt.xlim(xlim[0], xlim[1])\n plt.tick_params(labelsize=ticksize)\n plt.xlabel(xlabel, fontsize=fontsize)\n plt.ylabel(ylabel, fontsize=fontsize)\n plt.show()\n\n return 0\n\n\n' a function for plotting the time-by-time decoding accuracies '\n\ndef plot_tbyt_decoding_acc(acc, start_time=0, end_time=1, time_interval=0.01, chance=0.5, p=0.05, cbpt=True,\n clusterp=0.05, stats_time=[0, 1], color='r', xlim=[0, 1], ylim=[0.4, 0.8],\n xlabel='Time (s)', ylabel='Decoding Accuracy', figsize=[6.4, 3.6], x0=0, ticksize=12,\n fontsize=16, markersize=2, avgshow=False):\n\n \"\"\"\n Plot the time-by-time decoding accuracies\n\n Parameters\n ----------\n acc : array\n The decoding accuracies.\n The size of acc should be [n_subs, n_ts]. n_subs, n_ts represent the number of subjects and number of\n time-points.\n start_time : int or float. Default is 0.\n The start time.\n end_time : int or float. Default is 1.\n The end time.\n time_interval : float. Default is 0.01.\n The time interval between two time samples.\n chance : float. Default is 0.5.\n The chance level.\n p : float. Default is 0.05.\n The threshold of p-values.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_time : array or list [stats_time1, stats_time2]. Default os [0, 1].\n Time period for statistical analysis.\n color : matplotlib color or None. Default is 'r'.\n The color for the curve.\n xlim : array or list [xmin, xmax]. Default is [0, 1].\n The x-axis (time) view lims.\n ylim : array or list [ymin, ymax]. Default is [0.4, 0.8].\n The y-axis (decoding accuracy) view lims.\n xlabel : string. Default is 'Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Decoding Accuracy'.\n The label of y-axis.\n figsize : array or list, [size_X, size_Y]. Default is [6.4, 3.6].\n The size of the figure.\n x0 : float. Default is 0.\n The Y-axis is at x=x0.\n ticksize : int or float. Default is 12.\n The size of the ticks.\n fontsize : int or float. Default is 16.\n The fontsize of the labels.\n markersize : int or float. Default is 2.\n The size of significant marker.\n avgshow : boolen True or False. Default is False.\n Show the averaging decoding accuracies or not.\n \"\"\"\n\n if len(np.shape(acc)) != 2:\n\n return \"Invalid input!\"\n\n nsubs, nts = np.shape(acc)\n tstep = float(Decimal((end_time - start_time) / nts).quantize(Decimal(str(time_interval))))\n\n if tstep != time_interval:\n\n return \"Invalid input!\"\n\n delta1 = (stats_time[0] - start_time) / tstep - int((stats_time[0] - start_time) / tstep)\n delta2 = (stats_time[1] - start_time) / tstep - int((stats_time[1] - start_time) / tstep)\n if delta1 == 0:\n stats_time1 = int((stats_time[0] - start_time) / tstep)\n else:\n stats_time1 = int((stats_time[0] - start_time) / tstep) + 1\n if delta2 == 0:\n stats_time2 = int((stats_time[1] - start_time) / tstep)\n else:\n stats_time2 = int((stats_time[1] - start_time) / tstep) + 1\n\n yminlim = ylim[0]\n ymaxlim = ylim[1]\n\n avg = np.average(acc, axis=0)\n err = np.zeros([nts])\n for t in range(nts):\n err[t] = np.std(acc[:, t], ddof=1) / np.sqrt(nsubs)\n\n if cbpt == True:\n\n ps_stats = clusterbased_permutation_1d_1samp_1sided(acc[:, stats_time1:stats_time2], level=chance,\n p_threshold=p, clusterp_threshold=clusterp, iter=1000)\n ps = np.zeros([nts])\n ps[stats_time1:stats_time2] = ps_stats\n\n else:\n ps = np.zeros([nts])\n for t in range(nts):\n if t >= stats_time1 and t< stats_time2:\n ps[t] = ttest_1samp(acc[:, t], chance, alternative=\"greater\")[1]\n if ps[t] < p:\n ps[t] = 1\n else:\n ps[t] = 0\n\n for t in range(nts):\n if ps[t] == 1:\n plt.plot(t*tstep+start_time+0.5*tstep, (ymaxlim-yminlim)*0.95+yminlim, 's', color=color, alpha=0.8,\n markersize=markersize)\n xi = [t*tstep+start_time, t*tstep+tstep+start_time]\n ymin = [chance]\n ymax = [avg[t] - err[t]]\n plt.fill_between(xi, ymax, ymin, facecolor=color, alpha=0.2)\n\n fig = plt.gcf()\n fig.set_size_inches(figsize[0], figsize[1])\n ax = plt.gca()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_linewidth(3)\n ax.spines[\"left\"].set_position((\"data\", x0))\n ax.spines[\"bottom\"].set_linewidth(3)\n ax.spines[\"bottom\"].set_position((\"data\", chance))\n x = np.arange(start_time+0.5*tstep, end_time+0.5*tstep, tstep)\n if avgshow is True:\n plt.plot(x, avg, color=color, alpha=0.9)\n plt.fill_between(x, avg+err, avg-err, facecolor=color, alpha=0.8)\n plt.ylim(yminlim, ymaxlim)\n plt.xlim(xlim[0], xlim[1])\n plt.tick_params(labelsize=ticksize)\n plt.xlabel(xlabel, fontsize=fontsize)\n plt.ylabel(ylabel, fontsize=fontsize)\n plt.show()\n\n\n' a function for plotting the differences of time-by-time decoding accuracies between two conditions '\n\ndef plot_tbyt_diff_decoding_acc(acc1, acc2, start_time=0, end_time=1, time_interval=0.01, chance=0.5, p=0.05, cbpt=True,\n clusterp=0.05, stats_time=[0, 1], color1='r', color2='b', xlim=[0, 1], ylim=[0.4, 0.8],\n xlabel='Time (s)', ylabel='Decoding Accuracy', figsize=[6.4, 3.6], x0=0, ticksize=12,\n fontsize=16, markersize=2, avgshow=False):\n\n \"\"\"\n Plot the differences of time-by-time decoding accuracies between two conditions\n\n Parameters\n ----------\n acc1 : array\n The decoding accuracies under condition1.\n The size of acc1 should be [n_subs, n_ts]. n_subs, n_ts represent the number of subjects and number of\n time-points.\n acc2 : array\n The decoding accuracies under condition2.\n The size of acc2 should be [n_subs, n_ts]. n_subs, n_ts represent the number of subjects and number of\n time-points.\n start_time : int or float. Default is 0.\n The start time.\n end_time : int or float. Default is 1.\n The end time.\n time_interval : float. Default is 0.01.\n The time interval between two time samples.\n chance : float. Default is 0.5.\n The chance level.\n p : float. Default is 0.05.\n The threshold of p-values.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_time : array or list [stats_time1, stats_time2]. Default os [0, 1].\n Time period for statistical analysis.\n color1 : matplotlib color or None. Default is 'r'.\n The color for the curve under condition1.\n color2 : matplotlib color or None. Default is 'r'.\n The color for the curve under condition2.\n xlim : array or list [xmin, xmax]. Default is [0, 1].\n The x-axis (time) view lims.\n ylim : array or list [ymin, ymax]. Default is [0.4, 0.8].\n The y-axis (decoding accuracy) view lims.\n xlabel : string. Default is 'Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Decoding Accuracy'.\n The label of y-axis.\n figsize : array or list, [size_X, size_Y]. Default is [6.4, 3.6].\n The size of the figure.\n x0 : float. Default is 0.\n The Y-axis is at x=x0.\n ticksize : int or float. Default is 12.\n The size of the ticks.\n fontsize : int or float. Default is 16.\n The fontsize of the labels.\n markersize : int or float. Default is 2.\n The size of significant marker.\n avgshow : boolen True or False. Default is False.\n Show the averaging decoding accuracies or not.\n \"\"\"\n\n if len(np.shape(acc1)) != 2 or len(np.shape(acc2)) != 2:\n\n return \"Invalid input!\"\n\n nsubs, nts = np.shape(acc1)\n tstep = float(Decimal((end_time - start_time) / nts).quantize(Decimal(str(time_interval))))\n\n if tstep != time_interval:\n\n return \"Invalid input!\"\n\n delta1 = (stats_time[0] - start_time) / tstep - int((stats_time[0] - start_time) / tstep)\n delta2 = (stats_time[1] - start_time) / tstep - int((stats_time[1] - start_time) / tstep)\n if delta1 == 0:\n stats_time1 = int((stats_time[0] - start_time) / tstep)\n else:\n stats_time1 = int((stats_time[0] - start_time) / tstep) + 1\n if delta2 == 0:\n stats_time2 = int((stats_time[1] - start_time) / tstep)\n else:\n stats_time2 = int((stats_time[1] - start_time) / tstep) + 1\n\n yminlim = ylim[0]\n ymaxlim = ylim[1]\n\n avg1 = np.average(acc1, axis=0)\n err1 = np.zeros([nts])\n for t in range(nts):\n err1[t] = np.std(acc1[:, t], ddof=1) / np.sqrt(nsubs)\n\n avg2 = np.average(acc2, axis=0)\n err2 = np.zeros([nts])\n for t in range(nts):\n err2[t] = np.std(acc2[:, t], ddof=1) / np.sqrt(nsubs)\n\n if cbpt == True:\n\n ps1_stats = clusterbased_permutation_1d_1samp_1sided(acc1[:, stats_time1:stats_time2], level=chance,\n p_threshold=p, clusterp_threshold=clusterp, iter=1000)\n ps1 = np.zeros([nts])\n ps1[stats_time1:stats_time2] = ps1_stats\n ps2_stats = clusterbased_permutation_1d_1samp_1sided(acc2[:, stats_time1:stats_time2], level=chance,\n p_threshold=p, clusterp_threshold=clusterp, iter=1000)\n ps2 = np.zeros([nts])\n ps2[stats_time1:stats_time2] = ps2_stats\n ps_stats = clusterbased_permutation_1d_1samp_2sided(acc1[:, stats_time1:stats_time2]-\n acc2[:, stats_time1:stats_time2], level=0, p_threshold=p,\n clusterp_threshold=clusterp, iter=1000)\n ps = np.zeros([nts])\n ps[stats_time1:stats_time2] = ps_stats\n\n else:\n ps1 = np.zeros([nts])\n ps2 = np.zeros([nts])\n ps = np.zeros([nts])\n for t in range(nts):\n if t >= stats_time1 and t< stats_time2:\n ps1[t] = ttest_1samp(acc1[:, t], chance, alternative=\"greater\")[1]\n ps2[t] = ttest_1samp(acc2[:, t], chance, alternative=\"greater\")[1]\n if ps1[t] < p:\n ps1[t] = 1\n else:\n ps1[t] = 0\n if ps2[t] < p:\n ps2[t] = 1\n else:\n ps2[t] = 0\n if ttest_rel(acc1[:, t], acc1[:, t], alternative=\"greater\")[1] < p:\n ps[t] = 1\n elif ttest_rel(acc1[:, t], acc1[:, t], alternative=\"less\")[1] < p:\n ps[t] = -1\n else:\n ps[t] = 0\n\n for t in range(nts):\n if ps1[t] == 1:\n plt.plot(t*tstep+start_time+0.5*tstep, (ymaxlim-yminlim)*0.95+yminlim, 's', color=color1, alpha=0.8,\n markersize=markersize)\n if ps2[t] == 1:\n plt.plot(t*tstep+start_time+0.5*tstep, (ymaxlim-yminlim)*0.91+yminlim, 's', color=color2, alpha=0.8,\n markersize=markersize)\n if ps[t] == 1:\n xi = [t*tstep+start_time, t*tstep+tstep+start_time]\n ymin = [avg2[t] + err2[t]]\n ymax = [avg1[t] - err1[t]]\n plt.fill_between(xi, ymax, ymin, facecolor=\"grey\", alpha=0.2)\n if ps[t] == -1:\n xi = [t*tstep+start_time, t*tstep+tstep+start_time]\n ymin = [avg1[t] + err1[t]]\n ymax = [avg2[t] - err2[t]]\n plt.fill_between(xi, ymax, ymin, facecolor=\"grey\", alpha=0.2)\n\n fig = plt.gcf()\n fig.set_size_inches(figsize[0], figsize[1])\n ax = plt.gca()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_linewidth(3)\n ax.spines[\"left\"].set_position((\"data\", x0))\n ax.spines[\"bottom\"].set_linewidth(3)\n ax.spines[\"bottom\"].set_position((\"data\", chance))\n x = np.arange(start_time+0.5*tstep, end_time+0.5*tstep, tstep)\n if avgshow is True:\n plt.plot(x, avg1, color=color1, alpha=0.9)\n plt.plot(x, avg2, color=color2, alpha=0.9)\n plt.fill_between(x, avg1+err1, avg1-err1, facecolor=color1, alpha=0.8)\n plt.fill_between(x, avg2+err2, avg2-err2, facecolor=color2, alpha=0.8)\n plt.ylim(yminlim, ymaxlim)\n plt.xlim(xlim[0], xlim[1])\n plt.tick_params(labelsize=ticksize)\n plt.xlabel(xlabel, fontsize=fontsize)\n plt.ylabel(ylabel, fontsize=fontsize)\n plt.show()\n\n\n' a function for plotting cross-temporal decoding accuracies '\n\ndef plot_ct_decoding_acc(acc, start_timex=0, end_timex=1, start_timey=0, end_timey=1, time_intervalx=0.01,\n time_intervaly=0.01, chance=0.5, p=0.05, cbpt=True, clusterp=0.05, stats_timex=[0, 1],\n stats_timey=[0, 1], xlim=[0, 1], ylim=[0, 1], clim=[0.4, 0.8], xlabel='Training Time (s)',\n ylabel='Test Time (s)', clabel='Decoding Accuracy', figsize=[6.4, 4.8], cmap=\"viridis\",\n ticksize=12, fontsize=16):\n\n \"\"\"\n Plot the cross-temporal decoding accuracies\n\n Parameters\n ----------\n acc : array\n The decoding accuracies.\n The size of acc should be [n_subs, n_tsx, n_tsy]. n_subs, n_tsx and n_tsy represent the number of subjects,\n the number of training time-points and the number of test time-points.\n start_timex : int or float. Default is 0.\n The training start time.\n end_timex : int or float. Default is 1.\n The training end time.\n start_timey : int or float. Default is 0.\n The test start time.\n end_timey : int or float. Default is 1.\n The test end time.\n time_intervalx : float. Default is 0.01.\n The training time interval between two time samples.\n time_intervaly : float. Default is 0.01.\n The test time interval between two time samples.\n chance : float. Default is 0.5.\n The chance level.\n p : float. Default is 0.05.\n The threshold of p-values.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_timex : array or list [stats_timex1, stats_timex2]. Default os [0, 1].\n Trainning time period for statistical analysis.\n stats_timey : array or list [stats_timey1, stats_timey2]. Default os [0, 1].\n Test time period for statistical analysis.\n xlim : array or list [xmin, xmax]. Default is [0, 1].\n The x-axis (training time) view lims.\n ylim : array or list [ymin, ymax]. Default is [0, 1].\n The y-axis (test time) view lims.\n clim : array or list [cmin, cmax]. Default is [0.4, 0.8].\n The color-bar (decoding accuracy) view lims.\n xlabel : string. Default is 'Training Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Test Time (s)'.\n The label of y-axis.\n clabel : string. Default is 'Decoding Accuracy'.\n The label of color-bar.\n figsize : array or list, [size_X, size_Y]. Default is [6.4, 3.6].\n The size of the figure.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n ticksize : int or float. Default is 12.\n The size of the ticks.\n fontsize : int or float. Default is 16.\n The fontsize of the labels.\n \"\"\"\n\n nsubs, nx, ny = np.shape(acc)\n cminlim = clim[0]\n cmaxlim = clim[1]\n\n tstepx = float(Decimal((end_timex - start_timex) / nx).quantize(Decimal(str(time_intervalx))))\n tstepy = float(Decimal((end_timey - start_timey) / ny).quantize(Decimal(str(time_intervaly))))\n\n if tstepx != time_intervalx or tstepy != time_intervaly:\n return \"Invalid input!\"\n\n deltax1 = (stats_timex[0] - start_timex) / tstepx - int((stats_timex[0] - start_timex) / tstepx)\n deltax2 = (stats_timex[1] - start_timex) / tstepx - int((stats_timex[1] - start_timex) / tstepx)\n if deltax1 == 0:\n stats_timex1 = int((stats_timex[0] - start_timex) / tstepx)\n else:\n stats_timex1 = int((stats_timex[0] - start_timex) / tstepx) + 1\n if deltax2 == 0:\n stats_timex2 = int((stats_timex[1] - start_timex) / tstepx)\n else:\n stats_timex2 = int((stats_timex[1] - start_timex) / tstepx) + 1\n\n deltay1 = (stats_timey[0] - start_timey) / tstepy - int((stats_timey[0] - start_timey) / tstepy)\n deltay2 = (stats_timey[1] - start_timey) / tstepy - int((stats_timey[1] - start_timey) / tstepy)\n if deltay1 == 0:\n stats_timey1 = int((stats_timey[0] - start_timey) / tstepy)\n else:\n stats_timey1 = int((stats_timey[0] - start_timey) / tstepy) + 1\n if deltay2 == 0:\n stats_timey2 = int((stats_timey[1] - start_timey) / tstepy)\n else:\n stats_timey2 = int((stats_timey[1] - start_timey) / tstepy) + 1\n\n if cbpt is True:\n\n ps_stats = clusterbased_permutation_2d_1samp_1sided(\n acc[:, stats_timex1:stats_timex2, stats_timey1:stats_timey2], level=chance, p_threshold=p,\n clusterp_threshold=clusterp, iter=1000)\n ps = np.zeros([nx, ny])\n ps[stats_timex1:stats_timex2, stats_timey1:stats_timey2] = ps_stats\n\n else:\n ps = np.zeros([nx, ny])\n for t1 in range(nx):\n for t2 in range(ny):\n if t1 >= stats_timex1 and t1 < stats_timex2 and t2 >= stats_timey1 and t2 < stats_timey2:\n ps[t1, t2] = ttest_1samp(acc[:, t1, t2], chance, alternative=\"greater\")[1]\n if ps[t1, t2] < p:\n ps[t1, t2] = 1\n else:\n ps[t1, t2] = 0\n\n newps = np.zeros([nx + 2, ny + 2])\n newps[1:nx + 1, 1:ny + 1] = ps\n x = np.linspace(start_timex - 0.5 * tstepx, end_timex + 0.5 * tstepx, nx + 2)\n y = np.linspace(start_timey - 0.5 * tstepy, end_timey + 0.5 * tstepy, ny + 2)\n X, Y = np.meshgrid(x, y)\n plt.contour(X, Y, np.transpose(newps, (1, 0)), [0, 1], colors=\"silver\", alpha=0.9, linewidths=3,\n linestyles=\"dashed\")\n\n fig = plt.gcf()\n fig.set_size_inches(figsize[0], figsize[1])\n ax = plt.gca()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_linewidth(2)\n ax.spines[\"bottom\"].set_linewidth(2)\n avg = np.average(acc, axis=0)\n avg = np.transpose(avg, (1, 0))\n plt.imshow(avg, extent=(start_timex, end_timex, start_timey, end_timey), cmap=cmap, origin=\"lower\",\n clim=(cminlim, cmaxlim))\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=ticksize)\n font = {'size': ticksize+2}\n cb.set_label(clabel, fontdict=font)\n plt.xlim(xlim[0], xlim[1])\n plt.ylim(ylim[0], ylim[1])\n plt.tick_params(labelsize=ticksize)\n plt.xlabel(xlabel, fontsize=fontsize)\n plt.ylabel(ylabel, fontsize=fontsize)\n plt.show()\n\n\n' a function for plotting the differences of cross-temporal decoding accuracies between two conditions '\n\ndef plot_ct_diff_decoding_acc(acc1, acc2, start_timex=0, end_timex=1, start_timey=0, end_timey=1, time_intervalx=0.01,\n time_intervaly=0.01, p=0.05, cbpt=True, clusterp=0.05, stats_timex=[0, 1],\n stats_timey=[0, 1], xlim=[0, 1], ylim=[0, 1], clim=[0.4, 0.8], xlabel='Training Time (s)',\n ylabel='Test Time (s)', clabel='Differences of Decoding Accuracies', figsize=[6.4, 4.8],\n cmap=\"viridis\", ticksize=12, fontsize=16):\n\n \"\"\"\n Plot the differences of cross-temporal decoding accuracies between two conditions\n\n Parameters\n ----------\n acc1 : array\n The decoding accuracies under condition1.\n The size of acc should be [n_subs, n_tsx, n_tsy]. n_subs, n_tsx and n_tsy represent the number of subjects,\n the number of training time-points and the number of test time-points.\n acc2 : array\n The decoding accuracies under condition2.\n The size of acc should be [n_subs, n_tsx, n_tsy]. n_subs, n_tsx and n_tsy represent the number of subjects,\n the number of training time-points and the number of test time-points.\n start_timex : int or float. Default is 0.\n The training start time.\n end_timex : int or float. Default is 1.\n The training end time.\n start_timey : int or float. Default is 0.\n The test start time.\n end_timey : int or float. Default is 1.\n The test end time.\n time_intervalx : float. Default is 0.01.\n The training time interval between two time samples.\n time_intervaly : float. Default is 0.01.\n The test time interval between two time samples.\n chance : float. Default is 0.5.\n The chance level.\n p : float. Default is 0.05.\n The threshold of p-values.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_timex : array or list [stats_timex1, stats_timex2]. Default os [0, 1].\n Trainning time period for statistical analysis.\n stats_timey : array or list [stats_timey1, stats_timey2]. Default os [0, 1].\n Test time period for statistical analysis.\n xlim : array or list [xmin, xmax]. Default is [0, 1].\n The x-axis (training time) view lims.\n ylim : array or list [ymin, ymax]. Default is [0, 1].\n The y-axis (test time) view lims.\n clim : array or list [cmin, cmax]. Default is [0.4, 0.8].\n The color-bar (decoding accuracy) view lims.\n xlabel : string. Default is 'Training Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Test Time (s)'.\n The label of y-axis.\n clabel : string. Default is 'Differences of Decoding Accuracies'.\n The label of color-bar.\n figsize : array or list, [size_X, size_Y]. Default is [6.4, 3.6].\n The size of the figure.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n ticksize : int or float. Default is 12.\n The size of the ticks.\n fontsize : int or float. Default is 16.\n The fontsize of the labels.\n \"\"\"\n\n acc = acc1 - acc2\n nsubs, nx, ny = np.shape(acc)\n cminlim = clim[0]\n cmaxlim = clim[1]\n\n tstepx = float(Decimal((end_timex - start_timex) / nx).quantize(Decimal(str(time_intervalx))))\n tstepy = float(Decimal((end_timey - start_timey) / ny).quantize(Decimal(str(time_intervaly))))\n\n if tstepx != time_intervalx or tstepy != time_intervaly:\n return \"Invalid input!\"\n\n deltax1 = (stats_timex[0] - start_timex) / tstepx - int((stats_timex[0] - start_timex) / tstepx)\n deltax2 = (stats_timex[1] - start_timex) / tstepx - int((stats_timex[1] - start_timex) / tstepx)\n if deltax1 == 0:\n stats_timex1 = int((stats_timex[0] - start_timex) / tstepx)\n else:\n stats_timex1 = int((stats_timex[0] - start_timex) / tstepx) + 1\n if deltax2 == 0:\n stats_timex2 = int((stats_timex[1] - start_timex) / tstepx)\n else:\n stats_timex2 = int((stats_timex[1] - start_timex) / tstepx) + 1\n\n deltay1 = (stats_timey[0] - start_timey) / tstepy - int((stats_timey[0] - start_timey) / tstepy)\n deltay2 = (stats_timey[1] - start_timey) / tstepy - int((stats_timey[1] - start_timey) / tstepy)\n if deltay1 == 0:\n stats_timey1 = int((stats_timey[0] - start_timey) / tstepy)\n else:\n stats_timey1 = int((stats_timey[0] - start_timey) / tstepy) + 1\n if deltay2 == 0:\n stats_timey2 = int((stats_timey[1] - start_timey) / tstepy)\n else:\n stats_timey2 = int((stats_timey[1] - start_timey) / tstepy) + 1\n\n if cbpt is True:\n\n ps_stats = clusterbased_permutation_2d_2sided(acc1[:, stats_timex1:stats_timex2, stats_timey1:stats_timey2],\n acc2[:, stats_timex1:stats_timex2, stats_timey1:stats_timey2],\n p_threshold=p, clusterp_threshold=clusterp, iter=1000)\n ps = np.zeros([nx, ny])\n ps[stats_timex1:stats_timex2, stats_timey1:stats_timey2] = ps_stats\n\n else:\n ps = np.zeros([nx, ny])\n for t1 in range(nx):\n for t2 in range(ny):\n if t1 >= stats_timex1 and t1 < stats_timex2 and t2 >= stats_timey1 and t2 < stats_timey2:\n if ttest_1samp(acc[:, t1, t2], 0, alternative=\"greater\")[1] < p:\n ps[t1, t2] = 1\n elif ttest_1samp(acc[:, t1, t2], 0, alternative=\"less\")[1] < p:\n ps[t1, t2] = -1\n else:\n ps[t1, t2] = 0\n\n newps = np.zeros([nx + 2, ny + 2])\n newps[1:nx + 1, 1:ny + 1] = ps\n x = np.linspace(start_timex - 0.5 * tstepx, end_timex + 0.5 * tstepx, nx + 2)\n y = np.linspace(start_timey - 0.5 * tstepy, end_timey + 0.5 * tstepy, ny + 2)\n X, Y = np.meshgrid(x, y)\n plt.contour(X, Y, np.transpose(newps, (1, 0)), (-0.5, 0.5), colors=\"silver\", alpha=0.9, linewidths=3,\n linestyles=\"dashed\")\n\n fig = plt.gcf()\n fig.set_size_inches(figsize[0], figsize[1])\n ax = plt.gca()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_linewidth(2)\n ax.spines[\"bottom\"].set_linewidth(2)\n avg = np.average(acc, axis=0)\n avg = np.transpose(avg, (1, 0))\n plt.imshow(avg, extent=(start_timex, end_timex, start_timey, end_timey), cmap=cmap, origin=\"lower\",\n clim=(cminlim, cmaxlim))\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=ticksize)\n font = {'size': ticksize+2}\n cb.set_label(clabel, fontdict=font)\n plt.xlim(xlim[0], xlim[1])\n plt.ylim(ylim[0], ylim[1])\n plt.tick_params(labelsize=ticksize)\n plt.xlabel(xlabel, fontsize=fontsize)\n plt.ylabel(ylabel, fontsize=fontsize)\n plt.show()\n\n\n' a function for plotting the hotmap of correlations coefficients for channels/regions by time sequence '\n\ndef plot_corrs_hotmap(corrs, chllabels=None, time_unit=[0, 0.1], lim=[0, 1], smooth=False, figsize=None, cmap=None):\n\n \"\"\"\n plot the hotmap of correlation coefficients for channels/regions by time sequence\n\n corrs : array\n The correlation coefficients time-by-time.\n The shape of corrs must be [n_chls, ts, 2] or [n_chls, ts]. n_chls represents the number of channels or\n regions. ts represents the number of time-points. If shape of corrs is [n_chls, ts 2], each time-point\n of each channel/region contains a r-value and a p-value. If shape is [n_chls, ts], only r-values.\n chllabel : string-array or string-list or None. Default is None.\n The label for channels/regions.\n If label=None, the labels will be '1st', '2nd', '3th', '4th', ... automatically.\n time_unit : array or list [start_t, t_step]. Default is [0, 0.1]\n The time information of corrs for plotting\n start_t represents the start time and t_step represents the time between two adjacent time-points. Default\n time_unit=[0, 0.1], which means the start time of corrs is 0 sec and the time step is 0.1 sec.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n smooth : bool True or False. Default is False.\n Smooth the results or not.\n figsize : array or list, [size_X, size_Y]\n The size of the figure.\n If figsize=None, the size of the figure will be ajusted automatically.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n If cmap=None, the ccolormap will be 'inferno'.\n \"\"\"\n\n if len(np.shape(corrs)) < 2 or len(np.shape(corrs)) > 3:\n\n return \"Invalid input!\"\n\n # get the number of channels\n nchls = corrs.shape[0]\n\n # get the number of time-points\n ts = corrs.shape[1]\n\n # get the start time and the time step\n start_t = time_unit[0]\n tstep = time_unit[1]\n\n # calculate the end time\n end_t = start_t + ts * tstep\n\n # initialize the x\n x = np.arange(start_t, end_t, tstep)\n\n # set labels of the channels\n if chllabels == None:\n\n chllabels = []\n for i in range(nchls):\n\n if i % 10 == 0 and i != 10:\n newlabel = str(i+1) + \"st\"\n elif i % 10 == 1 and i != 11:\n newlabel = str(i+1) + \"nd\"\n elif i % 10 == 2 and i != 12:\n newlabel = str(i+1) + \"rd\"\n else:\n newlabel = str(i+1) + \"th\"\n\n chllabels.append(newlabel)\n\n # smooth the results\n if smooth == True:\n\n t = ts * 50\n\n x_soft = np.linspace(x.min(), x.max(), t)\n y_soft = np.zeros([nchls, t])\n\n samplerate = int(1 / tstep) * 50\n b, a = signal.butter(4, 2*30/samplerate, 'lowpass')\n\n for i in range(nchls):\n\n if len(corrs.shape) == 3:\n f = interp1d(x, corrs[i, :, 0], kind='cubic')\n y_soft[i] = f(x_soft)\n elif len(corrs.shape) == 2:\n f = interp1d(x, corrs[i, :], kind='cubic')\n y_soft[i] = f(x_soft)\n y_soft[i] = signal.filtfilt(b, a, y_soft[i])\n\n rlts = y_soft\n\n if smooth == False:\n\n if len(corrs.shape) == 3:\n rlts = corrs[:, :, 0]\n elif len(corrs.shape) == 2:\n rlts = corrs\n\n fig = plt.gcf()\n size = fig.get_size_inches()\n\n if figsize == None:\n size_x = ts * tstep * (size[0] - 2) + 2\n size_y = nchls * 0.2 * (size[1] - 1.5) + 1.5\n else:\n size_x = figsize[0]\n size_y = figsize[1]\n\n fig.set_size_inches(size_x, size_y)\n\n delta = (size_y * 3) / (size_x * 4)\n\n # get min of lims & max of lims\n limmin = lim[0]\n limmax = lim[1]\n\n if cmap == None:\n plt.imshow(rlts, extent=(start_t, end_t, 0, nchls*0.16*delta), clim=(limmin, limmax), origin='lower', cmap='inferno')\n else:\n plt.imshow(rlts, extent=(start_t, end_t, 0, nchls * 0.16*delta), clim=(limmin, limmax), origin='lower', cmap=cmap)\n\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=16)\n font = {'size': 18}\n cb.set_label(\"Similarity\", fontdict=font)\n\n xi = []\n\n for i in range(nchls):\n xi.append(0.16*delta*i + 0.08*delta)\n\n yi = chllabels\n\n plt.tick_params(labelsize=18)\n plt.yticks(xi, yi, fontsize=18)\n plt.ylabel(\"Channel\", fontsize=20)\n plt.xlabel(\"Time (s)\", fontsize=20)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the hotmap of correlations coefficients for channels/regions by time sequence with the significant outline '\n\ndef plot_corrs_hotmap_withstats(corrs, chllabels=None, time_unit=[0, 0.1], lim=[0, 1], p=0.05, cbpt=False,\n clusterp=0.05, stats_time=[0, 1], smooth=False, xlabel='Time (s)', ylabel='Channel',\n clabel='Similarity', ticksize=18, figsize=None, cmap=None):\n\n \"\"\"\n plot the hotmap of correlation coefficients for channels/regions by time sequence with the significant outline\n\n corrs : array\n The correlation coefficients time-by-time.\n The shape of corrs must be [n_subs, n_chls, ts, 2] or [n_subs, n_chls, ts]. n_subs represents the number of\n subjects. n_chls represents the number of channels or regions. ts represents the number of time-points. If shape\n of corrs is [n_chls, ts 2], each time-point of each channel/region contains a r-value and a p-value. If shape is\n [n_chls, ts], only r-values.\n chllabels : string-array or string-list or None. Default is None.\n The label for channels/regions.\n If label=None, the labels will be '1st', '2nd', '3th', '4th', ... automatically.\n time_unit : array or list [start_t, t_step]. Default is [0, 0.1]\n The time information of corrs for plotting\n start_t represents the start time and t_step represents the time between two adjacent time-points. Default\n time_unit=[0, 0.1], which means the start time of corrs is 0 sec and the time step is 0.1 sec.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n p: float. Default is 0.05.\n The p threshold for outline.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_time : array or list [stats_time1, stats_time2]. Default os [0, 1].\n The time period for statistical analysis.\n smooth : bool True or False. Default is False.\n Smooth the results or not.\n xlabel : string. Default is 'Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Channel'.\n The label of y-axis.\n clabel : string. Default is 'Similarity'.\n The label of color-bar.\n ticksize : int or float. Default is 18.\n The size of the ticks.\n figsize : array or list, [size_X, size_Y]\n The size of the figure.\n If figsize=None, the size of the figure will be ajusted automatically.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n If cmap=None, the colormap will be 'inferno'.\n \"\"\"\n\n if len(np.shape(corrs)) < 3 or len(np.shape(corrs)) > 4:\n\n return \"Invalid input!\"\n\n # get the number of channels\n nchls = corrs.shape[1]\n\n # get the number of time-points\n nts = corrs.shape[2]\n\n # get the start time and the time step\n start_time = time_unit[0]\n tstep = time_unit[1]\n\n # calculate the end time\n end_time = start_time + nts * tstep\n\n delta1 = (stats_time[0] - start_time) / tstep - int((stats_time[0] - start_time) / tstep)\n delta2 = (stats_time[1] - start_time) / tstep - int((stats_time[1] - start_time) / tstep)\n if delta1 == 0:\n stats_time1 = int((stats_time[0] - start_time) / tstep)\n else:\n stats_time1 = int((stats_time[0] - start_time) / tstep) + 1\n if delta2 == 0:\n stats_time2 = int((stats_time[1] - start_time) / tstep)\n else:\n stats_time2 = int((stats_time[1] - start_time) / tstep) + 1\n\n # set labels of the channels\n if chllabels == None:\n\n chllabels = []\n for i in range(nchls):\n\n if i % 10 == 0 and i != 10:\n newlabel = str(i+1) + \"st\"\n elif i % 10 == 1 and i != 11:\n newlabel = str(i+1) + \"nd\"\n elif i % 10 == 2 and i != 12:\n newlabel = str(i+1) + \"rd\"\n else:\n newlabel = str(i+1) + \"th\"\n\n chllabels.append(newlabel)\n\n if len(corrs.shape) == 4:\n rlts = corrs[:, :, :, 0]\n elif len(corrs.shape) == 3:\n rlts = corrs\n\n # smooth the results\n if smooth == True:\n\n for chl in range(nchls):\n rlts[:, chl] = smooth_1d(rlts[:, chl])\n\n fig = plt.gcf()\n size = fig.get_size_inches()\n\n if figsize == None:\n size_x = nts * tstep * (size[0] - 2) + 2\n size_y = nchls * 0.2 * (size[1] - 1.5) + 1.5\n else:\n size_x = figsize[0]\n size_y = figsize[1]\n\n fig.set_size_inches(size_x, size_y)\n\n delta = (size_y * 3) / (size_x * 4)\n\n avg = np.average(rlts, axis=0)\n\n ps = np.zeros([nchls, nts])\n\n if cbpt == True:\n\n for chl in range(nchls):\n ps_stats = clusterbased_permutation_1d_1samp_2sided(rlts[:, chl, stats_time1:stats_time2], 0, p_threshold=p,\n clusterp_threshold=clusterp, iter=1000)\n ps[chl, stats_time1:stats_time2] = ps_stats\n\n else:\n for chl in range(nchls):\n for t in range(nts):\n if t >= stats_time1 and t < stats_time2:\n ps[chl, t] = ttest_1samp(rlts[:, chl, t], 0)[1]\n if ps[chl, t] < p and avg[chl, t] > 0:\n ps[chl, t] = 1\n elif ps[chl, t] < p and avg[chl, t] < 0:\n ps[chl, t] = -1\n else:\n ps[chl, t] = 0\n\n newps = np.zeros([nchls + 2, nts + 2], dtype=np.float)\n newps[1:nchls + 1, 1:nts + 1] = ps\n\n x = np.linspace(start_time - 0.5 * tstep, end_time + 0.5 * tstep, nts + 2)\n y = np.linspace(-0.08*delta, 0.16*delta * nchls + 0.08*delta, nchls + 2)\n X, Y = np.meshgrid(x, y)\n plt.contour(X, Y, newps, [0.5], linewidths=2, linestyles=\"dashed\")\n plt.contour(X, Y, newps, [-0.5], linewidths=2, linestyles=\"dashed\")\n\n # get min of lims & max of lims\n limmin = lim[0]\n limmax = lim[1]\n\n if cmap == None:\n plt.imshow(avg, extent=(start_time, end_time, 0, nchls*delta*0.16), clim=(limmin, limmax), origin='lower', cmap='inferno')\n else:\n plt.imshow(avg, extent=(start_time, end_time, 0, nchls*delta * 0.16), clim=(limmin, limmax), origin='lower', cmap=cmap)\n\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=ticksize-2)\n font = {'size': ticksize}\n cb.set_label(clabel, fontdict=font)\n\n xi = []\n\n for i in range(nchls):\n xi.append(0.16*delta*i + 0.08*delta)\n\n yi = chllabels\n\n plt.tick_params(labelsize=ticksize)\n plt.yticks(xi, yi, fontsize=ticksize)\n plt.ylabel(ylabel, fontsize=20)\n plt.xlabel(xlabel, fontsize=20)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the hotmap of neural pattern similarities for channels/regions by time sequence '\n\ndef plot_nps_hotmap(similarities, chllabels=None, time_unit=[0, 0.1], lim=[0, 1], abs=False, smooth=False, figsize=None,\n cmap=None):\n\n \"\"\"\n plot the hotmap of neural pattern similarities for channels/regions by time sequence\n\n similarities : array\n The neural pattern similarities time-by-time.\n The shape of similarities must be [n_chls, ts]. n_chls represents the number of channels or regions.\n ts represents the number of time-points.\n chllabel : string-array or string-list or None. Default is None.\n The label for channels/regions.\n If label=None, the labels will be '1st', '2nd', '3th', '4th', ... automatically.\n time_unit : array or list [start_t, t_step]. Default is [0, 0.1]\n The time information of corrs for plotting\n start_t represents the start time and t_step represents the time between two adjacent time-points. Default\n time_unit=[0, 0.1], which means the start time of corrs is 0 sec and the time step is 0.1 sec.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n abs : boolean True or False. Default is False.\n Change the similarities into absolute values or not.\n smooth : boolean True or False. Default is False.\n Smooth the results or not.\n figsize : array or list, [size_X, size_Y]\n The size of the figure.\n If figsize=None, the size of the figure will be ajusted automatically.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n If cmap=None, the ccolormap will be 'viridis'.\n \"\"\"\n\n if len(np.shape(similarities)) != 2:\n\n return \"Invalid input!\"\n\n # absolute value\n if abs == True:\n similarities = np.abs(similarities)\n\n # get the number of channels\n nchls = similarities.shape[0]\n\n # get the number of time-points\n ts = similarities.shape[1]\n\n # get the start time and the time step\n start_t = time_unit[0]\n tstep = time_unit[1]\n\n # calculate the end time\n end_t = start_t + ts * tstep\n\n # initialize the x\n x = np.arange(start_t, end_t, tstep)\n\n # set labels of the channels\n if chllabels == None:\n\n chllabels = []\n for i in range(nchls):\n\n if i % 10 == 0 and i != 10:\n newlabel = str(i + 1) + \"st\"\n elif i % 10 == 1 and i != 11:\n newlabel = str(i + 1) + \"nd\"\n elif i % 10 == 2 and i != 12:\n newlabel = str(i + 1) + \"rd\"\n else:\n newlabel = str(i + 1) + \"th\"\n chllabels.append(newlabel)\n\n if smooth == True:\n\n t = ts * 50\n\n x_soft = np.linspace(x.min(), x.max(), t)\n y_soft = np.zeros([nchls, t])\n\n samplerate = int(1 / tstep) * 50\n b, a = signal.butter(4, 2*30/samplerate, 'lowpass')\n\n for i in range(nchls):\n f = interp1d(x, similarities[i, :], kind='cubic')\n y_soft[i] = f(x_soft)\n y_soft[i] = signal.filtfilt(b, a, y_soft[i])\n\n rlts = y_soft\n\n if smooth == False:\n rlts = similarities\n\n fig = plt.gcf()\n size = fig.get_size_inches()\n\n if figsize == None:\n size_x = ts * tstep * (size[0] - 2) + 2\n size_y = nchls * 0.2 * (size[1] - 1.5) + 1.5\n else:\n size_x = figsize[0]\n size_y = figsize[1]\n\n fig.set_size_inches(size_x, size_y)\n\n delta = (size_y * 3) / (size_x * 4)\n\n # get min of lims & max of lims\n limmin = lim[0]\n limmax = lim[1]\n\n if cmap == None:\n plt.imshow(rlts, extent=(start_t, end_t, 0, nchls*delta*0.16), clim=(limmin, limmax), origin='lower')\n else:\n plt.imshow(rlts, extent=(start_t, end_t, 0, nchls*delta*0.16), clim=(limmin, limmax), origin='lower', cmap=cmap)\n\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=16)\n font = {'size': 18}\n cb.set_label(\"Similarity\", fontdict=font)\n\n xi = []\n\n for i in range(nchls):\n xi.append(0.16*delta*i + 0.08*delta)\n\n yi = chllabels\n\n plt.tick_params(labelsize=18)\n plt.yticks(xi, yi, fontsize=18)\n plt.ylabel(\"Channel\", fontsize=20)\n plt.xlabel(\"Time (s)\", fontsize=20)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the hotmap of statistical results for channels/regions by time sequence '\n\ndef plot_t_hotmap_withstats(results, chllabels=None, time_unit=[0, 0.1], lim=[-7, 7], p=0.05, cbpt=False,\n clusterp=0.05, stats_time=[0, 1], smooth=False, xlabel='Time (s)', ylabel='Channel',\n clabel='t', ticksize=18, figsize=None, cmap=None):\n\n \"\"\"\n plot the hotmap of statistical results for channels/regions by time sequence\n\n results : array\n The results.\n The shape of results must be [n_subs, n_chls, ts, 2] or [n_subs, n_chls, ts]. n_subs represents the number of\n subjects. n_chls represents the number of channels or regions. ts represents the number of time-points. If shape\n of corrs is [n_chls, ts 2], each time-point of each channel/region contains a r-value and a p-value. If shape is\n [n_chls, ts], only r-values.\n chllabels : string-array or string-list or None. Default is None.\n The label for channels/regions.\n If label=None, the labels will be '1st', '2nd', '3th', '4th', ... automatically.\n time_unit : array or list [start_t, t_step]. Default is [0, 0.1]\n The time information of corrs for plotting\n start_t represents the start time and t_step represents the time between two adjacent time-points. Default\n time_unit=[0, 0.1], which means the start time of corrs is 0 sec and the time step is 0.1 sec.\n lim : array or list [min, max]. Default is [0, 1].\n The corrs view lims.\n p: float. Default is 0.05.\n The p threshold for outline.\n cbpt : bool True or False. Default is True.\n Conduct cluster-based permutation test or not.\n clusterp : float. Default is 0.05.\n The threshold of cluster-defining p-values.\n stats_time : array or list [stats_time1, stats_time2]. Default os [0, 1].\n The time period for statistical analysis.\n smooth : bool True or False. Default is False.\n Smooth the results or not.\n xlabel : string. Default is 'Time (s)'.\n The label of x-axis.\n ylabel : string. Default is 'Channel'.\n The label of y-axis.\n clabel : string. Default is 'Similarity'.\n The label of color-bar.\n ticksize : int or float. Default is 18.\n The size of the ticks.\n figsize : array or list, [size_X, size_Y]\n The size of the figure.\n If figsize=None, the size of the figure will be ajusted automatically.\n cmap : matplotlib colormap or None. Default is None.\n The colormap for the figure.\n If cmap=None, the ccolormap will be 'bwr'.\n \"\"\"\n\n if len(np.shape(results)) < 3 or len(np.shape(results)) > 4:\n return \"Invalid input!\"\n\n # get the number of channels\n nchls = results.shape[1]\n\n # get the number of time-points\n nts = results.shape[2]\n\n # get the start time and the time step\n start_time = time_unit[0]\n tstep = time_unit[1]\n\n # calculate the end time\n end_time = start_time + nts * tstep\n\n delta1 = (stats_time[0] - start_time) / tstep - int((stats_time[0] - start_time) / tstep)\n delta2 = (stats_time[1] - start_time) / tstep - int((stats_time[1] - start_time) / tstep)\n if delta1 == 0:\n stats_time1 = int((stats_time[0] - start_time) / tstep)\n else:\n stats_time1 = int((stats_time[0] - start_time) / tstep) + 1\n if delta2 == 0:\n stats_time2 = int((stats_time[1] - start_time) / tstep)\n else:\n stats_time2 = int((stats_time[1] - start_time) / tstep) + 1\n\n # set labels of the channels\n if chllabels == None:\n\n chllabels = []\n for i in range(nchls):\n\n if i % 10 == 0 and i != 10:\n newlabel = str(i + 1) + \"st\"\n elif i % 10 == 1 and i != 11:\n newlabel = str(i + 1) + \"nd\"\n elif i % 10 == 2 and i != 12:\n newlabel = str(i + 1) + \"rd\"\n else:\n newlabel = str(i + 1) + \"th\"\n\n chllabels.append(newlabel)\n\n if len(results.shape) == 4:\n rlts = results[:, :, :, 0]\n elif len(results.shape) == 3:\n rlts = results\n\n # smooth the results\n if smooth == True:\n\n for chl in range(nchls):\n rlts[:, chl] = smooth_1d(rlts[:, chl])\n\n fig = plt.gcf()\n size = fig.get_size_inches()\n\n if figsize == None:\n size_x = nts * tstep * (size[0] - 2) + 2\n size_y = nchls * 0.2 * (size[1] - 1.5) + 1.5\n else:\n size_x = figsize[0]\n size_y = figsize[1]\n\n fig.set_size_inches(size_x, size_y)\n\n delta = (size_y * 3) / (size_x * 4)\n\n ts = ttest_1samp(rlts, 0, axis=0)[:, :, 0]\n\n ps = np.zeros([nchls, nts])\n if cbpt == True:\n\n for chl in range(nchls):\n ps_stats = clusterbased_permutation_1d_1samp_2sided(rlts[:, chl, stats_time1:stats_time2], 0, p_threshold=p,\n clusterp_threshold=clusterp, iter=1000)\n ps[chl, stats_time1:stats_time2] = ps_stats\n\n else:\n for chl in range(nchls):\n for t in range(nts):\n if t >= stats_time1 and t < stats_time2:\n ps[chl, t] = ttest_1samp(rlts[:, chl, t], 0)[1]\n if ps[chl, t] < p and ts[chl, t] > 0:\n ps[chl, t] = 1\n elif ps[chl, t] < p and ts[chl, t] < 0:\n ps[chl, t] = -1\n else:\n ps[chl, t] = 0\n\n newps = np.zeros([nchls + 2, nts + 2], dtype=np.float)\n newps[1:nchls + 1, 1:nts + 1] = ps\n\n x = np.linspace(start_time - 0.5 * tstep, end_time + 0.5 * tstep, nts + 2)\n y = np.linspace(-0.08*delta, 0.16*delta * nchls + 0.08*delta, nchls + 2)\n X, Y = np.meshgrid(x, y)\n plt.contour(X, Y, newps, [0.5], linewidths=2, linestyles=\"dashed\")\n plt.contour(X, Y, newps, [-0.5], linewidths=2, linestyles=\"dashed\")\n\n # get min of lims & max of lims\n limmin = lim[0]\n limmax = lim[1]\n\n if cmap == None:\n plt.imshow(ts, extent=(start_time, end_time, 0, nchls * 0.16*delta), clim=(limmin, limmax), origin='lower',\n cmap='bwr')\n else:\n plt.imshow(ts, extent=(start_time, end_time, 0, nchls * 0.16*delta), clim=(limmin, limmax), origin='lower',\n cmap=cmap)\n\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=ticksize-2)\n font = {'size': ticksize}\n cb.set_label(clabel, fontdict=font)\n\n xi = []\n\n for i in range(nchls):\n xi.append(0.16*delta * i + 0.08*delta)\n\n yi = chllabels\n\n plt.tick_params(labelsize=ticksize)\n plt.yticks(xi, yi, fontsize=ticksize)\n plt.ylabel(ylabel, fontsize=20)\n plt.xlabel(xlabel, fontsize=20)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the RSA-result regions by 3 cuts (frontal, axial & lateral) '\n\ndef plot_brainrsa_regions(img, threshold=None, background=get_bg_ch2(), type='r'):\n\n \"\"\"\n Plot the RSA-result regions by 3 cuts (frontal, axial & lateral)\n\n Parameters\n ----------\n img : string\n The file path of the .nii file of the RSA results.\n threshold : None or int. Default is None.\n The threshold of the number of voxels used in correction.\n If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is\n None, the threshold-correction will not work.\n background : Niimg-like object or string. Default is stuff.get_bg_ch2()\n The background image that the RSA results will be plotted on top of.\n type : string 'r' or 't'\n The type of result (r-values or t-values).\n \"\"\"\n\n imgarray = nib.load(img).get_fdata()\n\n if (imgarray == np.nan).all() == True:\n print(\"No Valid Results\")\n\n else:\n if threshold != None:\n\n imgarray = nib.load(img).get_fdata()\n affine = get_affine(img)\n\n imgarray = correct_by_threshold(imgarray, threshold)\n\n img = nib.Nifti1Image(imgarray, affine)\n\n if type == 'r':\n plotting.plot_roi(roi_img=img, bg_img=background, threshold=0, vmin=0.1, vmax=1,\n title=\"Similarity\", resampling_interpolation=\"continuous\")\n if type == 't':\n plotting.plot_roi(roi_img=img, bg_img=background, threshold=0, vmin=-7, vmax=7,\n title=\"Similarity\", resampling_interpolation=\"continuous\")\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the RSA-result by different cuts '\n\ndef plot_brainrsa_montage(img, threshold=None, slice=[6, 6, 6], background=get_bg_ch2bet(), type='r'):\n\n \"\"\"\n Plot the RSA-result by different cuts\n\n Parameters\n ----------\n img : string\n The file path of the .nii file of the RSA results.\n threshold : None or int. Default is None.\n The threshold of the number of voxels used in correction.\n If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is\n None, the threshold-correction will not work.\n slice : array\n The point where the cut is performed.\n If slice=[slice_x, slice_y, slice_z], slice_x, slice_y, slice_z represent the coordinates of each cut in the x,\n y, z direction. If slice=[[slice_x1, slice_x2], [slice_y1, slice_y2], [slice_z1, slice_z2]], slice_x1 & slice_x2\n represent the coordinates of each cut in the x direction, slice_y1 & slice_y2 represent the coordinates of each\n cut in the y direction, slice_z1 & slice_z2 represent the coordinates of each cut in the z direction.\n background : Niimg-like object or string. Default is stuff.get_bg_ch2bet()\n The background image that the RSA results will be plotted on top of.\n type : string 'r' or 't'\n The type of result (r-values or t-values).\n \"\"\"\n\n imgarray = nib.load(img).get_fdata()\n\n if (imgarray == np.nan).all() == True:\n\n print(\"No Valid Results\")\n\n else:\n\n if threshold != None:\n imgarray = nib.load(img).get_fdata()\n affine = get_affine(img)\n imgarray = correct_by_threshold(imgarray, threshold)\n img = nib.Nifti1Image(imgarray, affine)\n\n slice_x = slice[0]\n slice_y = slice[1]\n slice_z = slice[2]\n\n if type == 'r':\n vmax = 1\n if type == 't':\n vmax = 7\n\n if slice_x != 0:\n plotting.plot_stat_map(stat_map_img=img, bg_img=background, display_mode='x', cut_coords=slice_x,\n title=\"Similarity -sagittal\", draw_cross=True, vmax=vmax)\n\n if slice_y != 0:\n plotting.plot_stat_map(stat_map_img=img, bg_img=background, display_mode='y', cut_coords=slice_y,\n title=\"Similarity -coronal\", draw_cross=True, vmax=vmax)\n\n if slice_z != 0:\n plotting.plot_stat_map(stat_map_img=img, bg_img=background, display_mode='z', cut_coords=slice_z,\n title=\"Similarity -axial\", draw_cross=True, vmax=vmax)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the 2-D projection of the RSA-result '\n\ndef plot_brainrsa_glass(img, threshold=None, type='r'):\n\n \"\"\"\n Plot the 2-D projection of the RSA-result\n\n Parameters\n ----------\n img : string\n The file path of the .nii file of the RSA results.\n threshold : None or int. Default is None.\n The threshold of the number of voxels used in correction.\n If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is\n None, the threshold-correction will not work.\n type : string 'r' or 't'\n The type of result (r-values or t-values).\n \"\"\"\n\n imgarray = nib.load(img).get_fdata()\n\n if (imgarray == np.nan).all() == True:\n\n print(\"No Valid Results\")\n\n else:\n if threshold != None:\n\n imgarray = nib.load(img).get_fdata()\n affine = get_affine(img)\n imgarray = correct_by_threshold(imgarray, threshold)\n img = nib.Nifti1Image(imgarray, affine)\n\n if type == 'r':\n plotting.plot_glass_brain(img, colorbar=True, title=\"Similarity\", black_bg=True, draw_cross=True, vmax=1)\n if type == 't':\n plotting.plot_glass_brain(img, colorbar=True, title=\"Similarity\", black_bg=True, draw_cross=True, vmax=7)\n\n plt.show()\n\n return 0\n\n\n' a function for plotting the RSA-result into a brain surface '\n\ndef plot_brainrsa_surface(img, threshold=None, type='r'):\n\n \"\"\"\n Plot the RSA-result into a brain surface\n\n Parameters\n ----------\n img : string\n The file path of the .nii file of the RSA results.\n threshold : None or int. Default is None.\n The threshold of the number of voxels used in correction.\n If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is\n None, the threshold-correction will not work.\n type : string 'r' or 't'\n The type of result (r-values or t-values).\n \"\"\"\n\n imgarray = nib.load(img).get_fdata()\n\n if (imgarray == np.nan).all() == True:\n\n print(\"No Valid Results\")\n\n else:\n\n if threshold != None:\n\n imgarray = nib.load(img).get_fdata()\n affine = get_affine(img)\n imgarray = correct_by_threshold(imgarray, threshold)\n img = nib.Nifti1Image(imgarray, affine)\n\n fsaverage = datasets.fetch_surf_fsaverage(mesh='fsaverage')\n texture_left = surface.vol_to_surf(img, fsaverage.pial_left)\n texture_right = surface.vol_to_surf(img, fsaverage.pial_right)\n\n # type='r'\n if type == 'r':\n plotting.plot_surf_stat_map(fsaverage.pial_left, texture_left, hemi='left', threshold=0.1,\n bg_map=fsaverage.sulc_right, colorbar=False, vmax=0.8, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_right, texture_right, hemi='right', threshold=0.1,\n bg_map=fsaverage.sulc_right, colorbar=True, vmax=0.8, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_right, texture_left, hemi='left', threshold=0.1,\n bg_map=fsaverage.sulc_right, colorbar=False, vmax=0.8, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_left, texture_right, hemi='right', threshold=0.1,\n bg_map=fsaverage.sulc_right, colorbar=True, vmax=0.8, darkness=0.7)\n\n plt.show()\n\n # type='t'\n if type == 't':\n plotting.plot_surf_stat_map(fsaverage.pial_left, texture_left, hemi='left', threshold=0.8,\n bg_map=fsaverage.sulc_right, colorbar=False, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_right, texture_right, hemi='right', threshold=0.8,\n bg_map=fsaverage.sulc_right, colorbar=True, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_right, texture_left, hemi='left', threshold=0.8,\n bg_map=fsaverage.sulc_right, colorbar=False, darkness=0.7)\n\n plotting.plot_surf_stat_map(fsaverage.pial_left, texture_right, hemi='right', threshold=0.8,\n bg_map=fsaverage.sulc_right, colorbar=True, darkness=0.7)\n\n plt.show()\n\n return 0\n\n\n\n' a function for plotting the RSA-result by a set of images '\n\ndef plot_brainrsa_rlts(img, threshold=None, slice=[6, 6, 6], background=None, type='r'):\n\n \"\"\"\n Plot the RSA-result by a set of images\n\n Parameters\n ----------\n img : string\n The file path of the .nii file of the RSA results.\n threshold : None or int. Default is None.\n The threshold of the number of voxels used in correction.\n If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is\n None, the threshold-correction will not work.\n background : Niimg-like object or string. Default is None.\n The background image that the RSA results will be plotted on top of.\n type : string 'r' or 't'\n The type of result (r-values or t-values).\n \"\"\"\n\n imgarray = nib.load(img).get_fdata()\n\n if (imgarray == np.nan).all() == True:\n print(\"No Valid Results\")\n else:\n\n if threshold != None:\n\n imgarray = nib.load(img).get_fdata()\n affine = get_affine(img)\n imgarray = correct_by_threshold(imgarray, threshold)\n img = nib.Nifti1Image(imgarray, affine)\n\n if background == None:\n\n plot_brainrsa_regions(img, threshold=threshold, type=type)\n\n plot_brainrsa_montage(img, threshold=threshold, slice=slice, type=type)\n\n plot_brainrsa_glass(img, threshold=threshold, type=type)\n\n plot_brainrsa_surface(img, threshold=threshold, type=type)\n\n else:\n\n plot_brainrsa_regions(img, threshold=threshold, background=background, type=type)\n\n plot_brainrsa_montage(img, threshold=threshold, slice=slice, background=background, type=type)\n\n plot_brainrsa_surface(img, threshold=threshold, type=type)\n\n return 0" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.sqrt", "numpy.linspace", "matplotlib.pyplot.plot", "numpy.max", "scipy.stats.ttest_rel", "matplotlib.pyplot.gca", "numpy.reshape", "numpy.arange", "matplotlib.pyplot.gcf", "scipy.signal.butter", "scipy.interpolate.interp1d", "numpy.std", "matplotlib.pyplot.axis", "numpy.zeros", "numpy.min", "matplotlib.pyplot.ylim", "matplotlib.pyplot.fill_between", "numpy.transpose", "numpy.argsort", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "scipy.stats.ttest_1samp", "scipy.signal.filtfilt", "numpy.abs", "matplotlib.pyplot.subplots", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.xlim", "numpy.shape", "matplotlib.pyplot.contour", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks", "numpy.average", "matplotlib.pyplot.tick_params" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
isabella232/corpora-data-portal
[ "09ed3cad3165f8b0db854b76404e0d5d0ea0b7d9" ]
[ "backend/scripts/curation/leng2020_AD/curate.py" ]
[ "\"\"\"Create the 'original' and 'remix' datasets for the snRNAseq of human neurons AD (Leng,\net. al. 2020) biorxiv preprint submission\"\"\"\n\n\nimport anndata\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\nfrom scipy.sparse import csr_matrix\n\nimport utils.hgnc\nimport utils.ontology\n\n\ndef basic_curation(adata):\n \"\"\"Changes to create the matrix for presentation in cellxgene.\"\"\"\n\n # Check if there are duplicate cell or gene IDs\n if not adata.obs.index.is_unique:\n raise Exception(\"Cell IDs not unique.\")\n if not adata.var.index.is_unique:\n raise Exception(\"Gene symbols not unique.\")\n\n # These are deleted at the request of the submitter\n del adata.obsm[\"X_CCA\"]\n del adata.obsm[\"X_CCA.ALIGNED\"]\n\n adata.uns[\"contributors\"] = [\n {\"name\": \"Kun Leng\"},\n {\"name\": \"Emmy Li\"},\n {\"name\": \"Rana Eser\"},\n {\"name\": \"Antonia Piergies\"},\n {\"name\": \"Rene Sit\"},\n {\"name\": \"Michelle Tan\"},\n {\"name\": \"Norma Neff\"},\n {\"name\": \"Song Hua Li\"},\n {\"name\": \"Roberta Diehl Rodriguez\"},\n {\"name\": \"Claudia Kimie Suemoto\"},\n {\"name\": \"Renata Elaine Paraizo Leite\"},\n {\"name\": \"Carlos A. Pasqualucci\"},\n {\"name\": \"William W. Seeley\"},\n {\"name\": \"Salvatore Spina\"},\n {\"name\": \"Helmut Heinsen\"},\n {\"name\": \"Lea T. Grinberg\", \"email\": \"[email protected]\"},\n {\"name\": \"Martin Kampmann\", \"email\": \"[email protected]\"},\n ]\n\n adata.uns[\"preprint_doi\"] = \"https://doi.org/10.1101/2020.04.04.025825\"\n adata.uns[\"default_embedding\"] = \"X_tSNE\"\n\n\ndef remix(adata, title: str):\n \"\"\"Create the full Corpora remix\"\"\"\n\n # First fill in missing metadata fields\n adata.obs[\"assay_ontology\"] = \"EFO:0009899\"\n adata.obs[\"assay\"] = utils.ontology.get_ontology_label(\"EFO:0009899\")\n\n adata.obs[\"sex\"] = \"male\"\n\n adata.obs[\"disease_ontology\"] = \"MONDO:0004975\"\n adata.obs[\"disease\"] = utils.ontology.get_ontology_label(\"MONDO:0004975\")\n\n adata.obs[\"tissue_ontology\"] = \"UBERON:0002728\"\n adata.obs[\"tissue\"] = utils.ontology.get_ontology_label(\"UBERON:0002728\")\n\n adata.uns[\"organism_ontology\"] = \"NCBITaxon:9606\"\n adata.uns[\"organism\"] = utils.ontology.get_ontology_label(\"NCBITaxon:9606\")\n\n adata.uns[\"title\"] = title\n\n adata.uns[\"project_name\"] = \"Molecular characterization of selectively vulnerable neurons in \" \"Alzheimer’s Disease\"\n adata.uns[\"project_description\"] = (\n \"Single-nuclei RNA sequencing of caudal entorhinal cortex and \"\n \"superior frontal gyrus from individuals spanning the \"\n \"neuropathological progression of AD\"\n )\n adata.uns[\"project_raw_data_links\"] = [\"https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE147528\"]\n adata.uns[\"project_other_links\"] = [\"https://www.synapse.org/#!Synapse:syn21788402/wiki/601825\"]\n\n # Set the cell ontology values\n cell_type_map = {\n \"Exc\": \"excitatory neuron\",\n \"OPC\": \"oligodendrocyte precursor cell\",\n \"Inh\": \"inhibitory neuron\",\n \"Micro\": \"mature microglial cell\",\n \"Astro\": \"mature astrocyte\",\n \"Oligo\": \"oligodendrocyte\",\n \"Endo\": \"endothelial cell\",\n }\n\n adata.obs[\"cell_type\"] = adata.obs[\"clusterAssignment\"].str.split(\":|\\\\.\", expand=True)[1].map(cell_type_map)\n del adata.obs[\"clusterAssignment\"]\n\n # make dictionary mapping cell_type to CL term\n cell_type_ontology_map = {\n cell_type: utils.ontology.lookup_candidate_term(cell_type)[0][0]\n for cell_type in adata.obs[\"cell_type\"].unique()\n }\n # result: {'excitatory neuron': 'CL:0008030', 'oligodendrocyte precursor cell': 'CL:0002453',\n # 'inhibitory neuron': 'CL:0008029', 'mature microglial cell': 'CL:0002629',\n # 'mature astrocyte': 'CL:0002627', 'oligodendrocyte': 'CL:0000128', 'endothelial cell':\n # 'CL:0000115'}\n\n adata.obs[\"cell_type_ontology\"] = adata.obs[\"cell_type\"].map(cell_type_ontology_map)\n\n # optional\n adata.uns[\"tags\"] = [\"AD\", \"Alzheimer's Disease\", \"neurons\"]\n\n # Now translate the gene symbols and sum new duplicates\n # Note that we're pulling from raw here. That's where the raw counts that we can sum are\n upgraded_var_index = utils.hgnc.get_upgraded_var_index(adata.var)\n merged_raw_counts = pd.DataFrame.sparse.from_spmatrix(\n adata.raw.X,\n index=adata.obs.index,\n columns=upgraded_var_index,\n ).sum(axis=1, level=0, skipna=False)\n\n # Create the new anndata object with the summed values\n remix_adata = anndata.AnnData(\n X=merged_raw_counts,\n obs=adata.obs,\n var=merged_raw_counts.columns.to_frame(name=\"hgnc_gene_symbol\"),\n uns=adata.uns,\n obsm=adata.obsm,\n )\n remix_adata.raw = remix_adata.copy()\n\n # Perform the same tranformations on the new values as they did in the paper\n # Divide counts of each cell by sizeFactors from logNormCounts used by author\n r, c = remix_adata.X.nonzero()\n rX_sp = csr_matrix(((1.0 / remix_adata.obs.sizeFactors)[r], (r, c)), shape=(remix_adata.X.shape))\n remix_adata.X = remix_adata.X.multiply(rX_sp)\n\n sc.pp.log1p(remix_adata, base=2)\n\n # Finally describe the layers and we're done\n remix_adata.uns[\"layer_descriptions\"] = {\n \"raw.X\": \"raw\",\n \"X\": \"logNormCounts\",\n }\n\n return remix_adata\n\n\ndef print_summary(adata):\n \"\"\"Print out a little summary of the metadata.\"\"\"\n print(adata.obs.dtypes)\n for column in adata.obs.nunique().items():\n field, n_unique = column\n if n_unique > 1000 and not np.issubdtype(adata.obs[field].dtype, np.number):\n print(\"TOO MANY:\", field)\n elif n_unique == 1:\n print(\"ONLY ONE:\", field)\n\n # Print missing cell fields required by Corpora schema\n remix_cellfields = np.array(\n [\n \"tissue\",\n \"assay\",\n \"disease\",\n \"cell_type\",\n \"sex\",\n \"ethnicity\",\n \"tissue_ontology\",\n \"assay_ontology\",\n \"disease_ontology\",\n \"cell_type_ontology\",\n \"ethnicity_ontology\",\n ]\n )\n missing_remix_cellfields = np.array(set(remix_cellfields) - set(adata.obs.columns.values))\n print(\"MISSING CORPORA FIELDS:\", missing_remix_cellfields)\n\n\n# Process EC_all\nad = sc.read_h5ad(\"EC_allCells/kampmann_lab_human_AD_snRNAseq_EC.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\"EC_allCells/kampmann_lab_human_AD_snRNAseq_EC-curated.h5ad\", compression=\"gzip\")\nrad = remix(\n ad,\n title=\"Molecular characterization of selectively vulnerable neurons in \"\n \"Alzheimer’s Disease: caudal entorhinal cortex\",\n)\nprint_summary(rad)\nrad.write(\"EC_allCells/kampmann_lab_human_AD_snRNAseq_EC-remixed.h5ad\", compression=\"gzip\")\n\n# Process SFG_all\nad = sc.read_h5ad(\"SFG_allCells/kampmann_lab_human_AD_snRNAseq_SFG.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\"SFG_allCells/kampmann_lab_human_AD_snRNAseq_SFG-curated.h5ad\", compression=\"gzip\")\nrad = remix(\n ad,\n title=\"Molecular characterization of selectively vulnerable neurons in \"\n \"Alzheimer’s Disease: superior frontal gyrus\",\n)\nprint_summary(rad)\nrad.write(\"SFG_allCells/kampmann_lab_human_AD_snRNAseq_SFG-remixed.h5ad\", compression=\"gzip\")\n\n# Process EC_astrocytes\nad = sc.read_h5ad(\"EC_subclusters/EC_astrocytes/kampmann_lab_human_AD_snRNAseq_EC_astrocytes.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\"EC_subclusters/EC_astrocytes/kampmann_lab_human_AD_snRNAseq_EC_astrocytes-curated.h5ad\", compression=\"gzip\")\nrad = remix(\n ad, title=\"Molecular characterization of selectively vulnerable neurons in \" \"Alzheimer’s Disease: EC astrocytes\"\n)\nprint_summary(rad)\nrad.write(\"EC_subclusters/EC_astrocytes/kampmann_lab_human_AD_snRNAseq_EC_astrocytes-remixed.h5ad\", compression=\"gzip\")\n\n# Process EC_excitatoryNeurons\nad = sc.read_h5ad(\"EC_subclusters/EC_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_excitatoryNeurons.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\n \"EC_subclusters/EC_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_excitatoryNeurons-curated.h5ad\",\n compression=\"gzip\",\n)\nrad = remix(\n ad,\n title=\"Molecular characterization of selectively vulnerable neurons in \"\n \"Alzheimer’s Disease: EC excitatoryNeurons\",\n)\nprint_summary(rad)\nrad.write(\n \"EC_subclusters/EC_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_excitatoryNeurons-remixed.h5ad\",\n compression=\"gzip\",\n)\n\n# Process EC_inhibitoryNeurons\nad = sc.read_h5ad(\"EC_subclusters/EC_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_inhibitoryNeurons.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\n \"EC_subclusters/EC_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_inhibitoryNeurons-curated.h5ad\",\n compression=\"gzip\",\n)\nrad = remix(\n ad,\n title=\"Molecular characterization of selectively vulnerable neurons in \"\n \"Alzheimer’s Disease: EC inhibitoryNeurons\",\n)\nprint_summary(rad)\nrad.write(\n \"EC_subclusters/EC_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_EC_inhibitoryNeurons-remixed.h5ad\",\n compression=\"gzip\",\n)\n\n# Process EC_microglia\nad = sc.read_h5ad(\"EC_subclusters/EC_microglia/kampmann_lab_human_AD_snRNAseq_EC_microglia.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\"EC_subclusters/EC_microglia/kampmann_lab_human_AD_snRNAseq_EC_microglia-curated.h5ad\", compression=\"gzip\")\nrad = remix(\n ad, title=\"Molecular characterization of selectively vulnerable neurons in \" \"Alzheimer’s Disease: EC microglia\"\n)\nprint_summary(rad)\nrad.write(\"EC_subclusters/EC_microglia/kampmann_lab_human_AD_snRNAseq_EC_microglia-remixed.h5ad\", compression=\"gzip\")\n\n# Process SFG_astrocytes\nad = sc.read_h5ad(\"SFG_subclusters/SFG_astrocytes/kampmann_lab_human_AD_snRNAseq_SFG_astrocytes.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\n \"SFG_subclusters/SFG_astrocytes/kampmann_lab_human_AD_snRNAseq_SFG_astrocytes-curated.h5ad\", compression=\"gzip\"\n)\nrad = remix(\n ad, title=\"MolSFGular characterization of selSFGtively vulnerable neurons in \" \"Alzheimer’s Disease: SFG astrocytes\"\n)\nprint_summary(rad)\nrad.write(\n \"SFG_subclusters/SFG_astrocytes/kampmann_lab_human_AD_snRNAseq_SFG_astrocytes-remixed.h5ad\", compression=\"gzip\"\n)\n\n# Process SFG_excitatoryNeurons\nad = sc.read_h5ad(\"SFG_subclusters/SFG_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_excitatoryNeurons.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\n \"SFG_subclusters/SFG_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_excitatoryNeurons-curated.h5ad\",\n compression=\"gzip\",\n)\nrad = remix(\n ad,\n title=\"MolSFGular characterization of selSFGtively vulnerable neurons in \"\n \"Alzheimer’s Disease: SFG excitatoryNeurons\",\n)\nprint_summary(rad)\nrad.write(\n \"SFG_subclusters/SFG_excitatoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_excitatoryNeurons-remixed.h5ad\",\n compression=\"gzip\",\n)\n\n# Process SFG_inhibitoryNeurons\nad = sc.read_h5ad(\"SFG_subclusters/SFG_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_inhibitoryNeurons.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\n \"SFG_subclusters/SFG_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_inhibitoryNeurons-curated.h5ad\",\n compression=\"gzip\",\n)\nrad = remix(\n ad,\n title=\"MolSFGular characterization of selSFGtively vulnerable neurons in \"\n \"Alzheimer’s Disease: SFG inhibitoryNeurons\",\n)\nprint_summary(rad)\nrad.write(\n \"SFG_subclusters/SFG_inhibitoryNeurons/kampmann_lab_human_AD_snRNAseq_SFG_inhibitoryNeurons-remixed.h5ad\",\n compression=\"gzip\",\n)\n\n# Process SFG_microglia\nad = sc.read_h5ad(\"SFG_subclusters/SFG_microglia/kampmann_lab_human_AD_snRNAseq_SFG_microglia.h5ad\")\nbasic_curation(ad)\nprint_summary(ad)\nad.write(\"SFG_subclusters/SFG_microglia/kampmann_lab_human_AD_snRNAseq_SFG_microglia-curated.h5ad\", compression=\"gzip\")\nrad = remix(\n ad, title=\"MolSFGular characterization of selSFGtively vulnerable neurons in \" \"Alzheimer’s Disease: SFG microglia\"\n)\nprint_summary(rad)\nrad.write(\"SFG_subclusters/SFG_microglia/kampmann_lab_human_AD_snRNAseq_SFG_microglia-remixed.h5ad\", compression=\"gzip\")\n" ]
[ [ "numpy.issubdtype", "numpy.array", "pandas.DataFrame.sparse.from_spmatrix", "scipy.sparse.csr_matrix" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
PPjaisri/Senior-project
[ "cf29a51bdff33e1cc9ae505b454a002457bc3245" ]
[ "News_fetcher/Sure/sure_info.py" ]
[ "import os\nimport csv\nimport time\nimport logging\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nclass sure_info(object):\n path = os.getcwd()\n path = os.path.dirname(path)\n # If directly run this file --> uncomment line 16 and 17.\n path = os.path.dirname(path)\n\n input_path = os.path.join(path, 'result\\\\Sure\\\\sure_thread.csv')\n save_path = os.path.join(path, 'result\\\\Sure\\\\sure_info.csv')\n\n logging.basicConfig(level=logging.DEBUG)\n\n def __init__(self):\n self.fetch_data = []\n self.current_page = 1\n self.finish = False\n self.last_link = ''\n self.count = 0\n\n def read_latest_save(self):\n try:\n data = pd.read_csv(self.save_path, encoding='utf-8')\n last_link = data.iloc[-1]['link']\n return last_link\n except:\n return ''\n\n def finished_crawl(self):\n logging.info(f'Crawled {self.count} pages')\n with open(self.save_path, 'a', encoding='utf-8', newline='') as file:\n fieldnames = ['category', 'header', 'content', 'link', 'image', 'time']\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n if self.last_link != '':\n writer.writerows(self.fetch_data)\n else:\n writer.writeheader()\n writer.writerows(self.fetch_data)\n\n def fetch_page(self):\n urls = []\n self.last_link = self.read_latest_save()\n\n with open(self.input_path, 'r', encoding='utf-8') as file:\n data = file.readlines()\n\n for obj in data:\n if obj != '\\n':\n obj = obj.split(',')\n urls.append(obj[1])\n\n new_urls = []\n for url in range(len(urls) - 1, 0, -1):\n new_urls.append(urls[url])\n\n for url in new_urls:\n if url == self.last_link:\n break\n else:\n self.count += 1\n time.sleep(0.5)\n self.crawl_page(url)\n\n self.finished_crawl()\n\n def crawl_page(self, url):\n response = requests.get(url)\n # logging.debug(f'Crawling at {url}')\n soup = BeautifulSoup(response.text, 'lxml')\n\n header = soup.h1.text.strip()\n time = (soup.find('div', class_='entry-meta')).text\n time = ' '.join(time.split())\n entry_content = soup.find('div', class_='entry-content')\n \n try:\n category = entry_content.find_all('strong')[1].text\n except:\n category = None\n \n content_blog = entry_content.select('p')\n content = [(i.text).strip() for i in content_blog]\n\n try:\n image = (soup.find('div', class_='thumb').find('img'))['data-src']\n except:\n image = None\n\n data = {\n 'category': category,\n 'header': header,\n 'content': content,\n 'link': url,\n 'image': image,\n 'time': time\n }\n\n self.fetch_data.insert(0, data)\n\nif __name__ == '__main__':\n sure = sure_info()\n sure.fetch_page()" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
OleguerCanal/kaggle_digit-recognizer
[ "89268df3e13744faacec5bf18bdc5071abf094d4" ]
[ "scripts/model.py" ]
[ "import datetime\nimport os\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nimport sys\nimport time\nimport yaml\n\n# Keras\nfrom keras.models import model_from_json\nfrom keras.optimizers import RMSprop, Adam\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Own imports TODO(oleguer): Fix this path problem\nsys.path.append(str(Path(__file__).parent))\nfrom architectures.simple_cnn import simple_cnn_classification\nfrom architectures.model2 import model2\nfrom data_processing.preprocessing import preprocess_data\nfrom helpers.callbacks import TensorBoard, ReduceLROnPlateau, ModelCheckpoint, TelegramSummary\n\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nset_session(tf.Session(config=config))\n\nclass Model():\n def __init__(self, param_yaml):\n self.__load_params(param_yaml)\n \n def __load_params(self, param_yaml):\n stream = open(param_yaml, 'r')\n self.params = yaml.load(stream, Loader = yaml.FullLoader)\n\n def recover_logged_model(self, weights_path):\n weights_name = weights_path.split(\"/\")[-1]\n full_model_path = weights_path.replace(\"/\" + weights_name, \"\")\n json_file = open(full_model_path + \"/architecture.json\", \"r\")\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n\n # load weights into new model\n loaded_model.load_weights(weights_path)\n print(\"Loaded model from disk\")\n return loaded_model\n\n def __log_model(self, path):\n # Make sure dir exists\n if not os.path.exists(path):\n os.makedirs(path)\n\n # Serialize model to JSON\n model_json = self.model.to_json()\n with open(path + \"/architecture.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n # Save model params\n with open(path + \"/params.yaml\", 'w') as outfile:\n yaml.dump(self.params, outfile, default_flow_style=False)\n\n def get_submission(self, mod, test, csv_path = \"../input/solution.csv\"):\n results = mod.predict(test)\n results = np.argmax(results, axis = 1)\n results = pd.Series(results, name=\"Label\")\n submission = pd.concat([pd.Series(range(1, 28001), name = \"ImageId\"), results], axis = 1)\n submission.to_csv(csv_path, index = False)\n\n def train(self):\n # 1. Load data\n raw_train = pd.read_csv(self.params[\"data_path\"])\n raw_train = raw_train.sample(frac = self.params[\"sample_data\"])\n\n # 2. Process data\n x_train, y_train, x_val, y_val = preprocess_data(raw_train)\n del raw_train\n\n # 3. Define Model\n optimizer = RMSprop(\n lr = float(self.params[\"learning_rate\"]),\n rho = float(self.params[\"rho\"]),\n epsilon = float(self.params[\"epsilon\"]),\n decay = float(self.params[\"decay\"]))\n if str(self.params[\"optimizer\"]) == \"Adam\": \n opimizer = Adam(float(self.params[\"learning_rate\"]))\n\n # self.model = simple_cnn_classification(input_shape = x_train[0].shape) # Default: Start with random weights\n self.model = model2(input_shape = x_train[0].shape) # Default: Start with random weights\n if self.params[\"train_from_saved_weights\"]:\n self.model = self.recover_logged_model(self.params[\"saved_weights_path\"])\n \n self.model.compile(\n optimizer = optimizer,\n loss = self.params[\"loss\"],\n metrics = self.params[\"metrics\"])\n\n # 4. Log model\n time_stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M:%S')\n save_path = str(self.params[\"model_logging_path\"]) + \"/\" + str(time_stamp)\n self.__log_model(path = save_path)\n\n # Datagen\n datagen_args = dict(rotation_range = 20,\n width_shift_range = 0.1,\n height_shift_range = 0.1,\n shear_range = 0.1,\n zoom_range = 0.1)\n datagen = ImageDataGenerator(**datagen_args)\n datagen.fit(x_train)\n\n # Callbacks:\n weights_filepath = save_path + \"/weights-{epoch:0f}-{val_acc:.4f}.hdf5\"\n checkpoint = ModelCheckpoint( # Save model weights after each epoch\n filepath=weights_filepath,\n monitor='val_acc',\n verbose=1,\n save_best_only=True,\n mode='max')\n telegram_summary = TelegramSummary()\n log_dir = str(self.params[\"tensorboard_logging_path\"]) + \"/{}\".format(time.time())\n tensorboard = TensorBoard(log_dir = log_dir)\n learning_rate_reduction = ReduceLROnPlateau(\n monitor = 'val_acc', \n patience = 5,\n verbose = 1,\n factor = 0.85, # Each patience epoch reduce lr by half\n min_lr = 1e-10)\n callbacks = [checkpoint, learning_rate_reduction, tensorboard, telegram_summary]\n\n # 4. Fit Model\n self.model.summary()\n history = self.model.fit_generator(\n generator = datagen.flow(x_train, y_train, batch_size = self.params[\"batch_size\"]),\n epochs = self.params[\"epochs\"],\n validation_data = (x_val, y_val),\n verbose = 1,\n callbacks = callbacks,\n steps_per_epoch = x_train.shape[0] // self.params[\"batch_size\"]) # // is floor division\n # TODO(oleguer): Log history?\n return\n \n def test(self, data):\n #TODO(oleguer): self.model.predict\n pass\n\n def analyze(self):\n pass\n" ]
[ [ "pandas.read_csv", "pandas.Series", "tensorflow.ConfigProto", "numpy.argmax", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
Chutlhu/DechorateDB
[ "378eda37ed296f2823e3306238101343c5f4084a" ]
[ "dechorate/cadzow.py" ]
[ "import numpy as np\n\nfrom dechorate.utils.dsp_utils import make_toepliz_as_in_mulan, reshape_toeplitz, enforce_toeplitz, build_frobenius_weights\n\ndef cadzow_denoise(A, n_spikes, thr_Cadzow=2e-5):\n '''\n Cadzow denoising method\n from Condat implementation\n '''\n N, P = A.shape\n K = n_spikes\n # run Cadzow denoising\n for _ in range(100):\n # low-rank projection\n u, s, vh = np.linalg.svd(A, full_matrices=False)\n A = np.dot(u[:, :K] * s[:K], vh[:K, :])\n print(s[:K], s[K])\n\n # enforce Toeplitz structure\n A = enforce_toeplitz(A)\n\n if s[K] < thr_Cadzow:\n break\n\n A = reshape_toeplitz(A, K+1)\n assert A.shape[1] == K+1\n return A\n\n\ndef condat_denoise(A, n_spikes, thr_Cadzow=2e-5):\n '''\n Method from Condat\n the matrices have size D-L-1 x L. K <= L <= M required.\n '''\n N, L = A.shape # matrix have size D-L+1 x L\n D = N + L - 1\n K = n_spikes\n\n # parameters\n niter = 20 # number of iterations.\n μ = 0.1 # parameter. Must be in ]0,2[\n γ = 0.51*μ # parameter. Must be in ]μ/2,1[\n\n # initialization of the weighted matrix, w\n W = build_frobenius_weights(A)\n\n Tnoisy = A.copy()\n Tdensd = A.copy() # the noisy matrix is the initialization\n Tauxil = A.copy() # auxtiliary matrix\n\n for _ in range(niter):\n U, s, Vh = np.linalg.svd(\n Tauxil + γ*(Tdensd-Tauxil) + μ*(Tnoisy-Tdensd)/W,\n full_matrices=False)\n # SVD truncation -> Tdenoised has rank K\n Tdensd = np.dot(U[:, :K] * s[:K], Vh[:K, :])\n print(s[:K], s[K])\n Tauxil = Tauxil-Tdensd+enforce_toeplitz(2*Tdensd-Tauxil)\n\n # at this point, Tdensd has rank K but is not exactly Toeplitz\n Tdensd = enforce_toeplitz(Tdensd)\n # we reshape the Toeplitz matrix Tdensd into a Toeplitz matrix with K+1 columns\n Tdensd = reshape_toeplitz(Tdensd, K+1)\n assert Tdensd.shape[1] == K+1\n return Tdensd\n\n\ndef amplitudes_from_locations(obs, taus, nfft, Fs):\n # according to Condat's paper (Condat2015cadzow)\n # observation are in the FFT domain\n # [-M, M] Fourier coefficient of the signal\n assert len(obs) > nfft\n v = np.fft.fft(obs, nfft)\n assert len(v) == 2*nfft+1\n M = nfft\n\n U = np.exp(-1j*2*np.pi/tau*MM@tk)\n akest = np.real(np.linalg.lstsq(U, vobs)[0].T)\n return akest\n" ]
[ [ "numpy.dot", "numpy.linalg.svd", "numpy.fft.fft", "numpy.linalg.lstsq", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lilianschuster/PyGEM
[ "c805d09960f937fe6e35cdd1587f9089d4bec6b8" ]
[ "class_mbdata.py" ]
[ "\"\"\"class of mass balance data and functions associated with manipulating the dataset to be in the proper format\"\"\"\n\n# External libraries\nimport pandas as pd\nimport numpy as np\nimport calendar\nimport collections\nimport datetime\n# Local libraries\nimport pygem_input as input\nimport pygemfxns_modelsetup as modelsetup\n\n\nclass MBData():\n \"\"\"\n Mass balance data properties and functions used to automatically retrieve data for calibration.\n \n Attributes\n ----------\n name : str\n name of mass balance dataset.\n ds_fp : str\n file path \n \"\"\"\n def __init__(self, \n name='wgms_d',\n ):\n \"\"\"\n Add variable name and specific properties associated with each variable.\n \"\"\"\n \n # Source of climate data\n self.name = name\n # Set parameters for ERA-Interim and CMIP5 netcdf files\n if self.name == 'shean': \n self.ds_fp = input.shean_fp\n self.ds_fn = input.shean_fn\n self.rgi_glacno_cn = input.shean_rgi_glacno_cn\n self.mb_mwea_cn = input.shean_mb_cn\n self.mb_mwea_err_cn = input.shean_mb_err_cn\n self.t1_cn = input.shean_time1_cn\n self.t2_cn = input.shean_time2_cn\n self.area_cn = input.shean_area_cn\n \n elif self.name == 'berthier': \n self.ds_fp = input.berthier_fp\n self.ds_fn = input.berthier_fn\n self.rgi_glacno_cn = input.berthier_rgi_glacno_cn\n self.mb_mwea_cn = input.berthier_mb_cn\n self.mb_mwea_err_cn = input.berthier_mb_err_cn\n self.t1_cn = input.berthier_time1_cn\n self.t2_cn = input.berthier_time2_cn\n self.area_cn = input.berthier_area_cn\n \n elif self.name == 'braun': \n self.ds_fp = input.braun_fp\n self.ds_fn = input.braun_fn\n self.rgi_glacno_cn = input.braun_rgi_glacno_cn\n self.mb_mwea_cn = input.braun_mb_cn\n self.mb_mwea_err_cn = input.braun_mb_err_cn\n self.t1_cn = input.braun_time1_cn\n self.t2_cn = input.braun_time2_cn\n self.area_cn = input.braun_area_cn\n \n elif self.name == 'mcnabb':\n self.ds_fp = input.mcnabb_fp\n self.ds_fn = input.mcnabb_fn\n self.rgi_glacno_cn = input.mcnabb_rgiid_cn\n self.mb_mwea_cn = input.mcnabb_mb_cn\n self.mb_mwea_err_cn = input.mcnabb_mb_err_cn\n self.t1_cn = input.mcnabb_time1_cn\n self.t2_cn = input.mcnabb_time2_cn\n self.area_cn = input.mcnabb_area_cn\n \n elif self.name == 'larsen':\n self.ds_fp = input.larsen_fp\n self.ds_fn = input.larsen_fn\n self.rgi_glacno_cn = input.larsen_rgiid_cn\n self.mb_mwea_cn = input.larsen_mb_cn\n self.mb_mwea_err_cn = input.larsen_mb_err_cn\n self.t1_cn = input.larsen_time1_cn\n self.t2_cn = input.larsen_time2_cn\n self.area_cn = input.larsen_area_cn\n \n elif self.name == 'brun':\n self.data_fp = input.brun_fp\n \n elif self.name == 'mauer':\n self.ds_fp = input.mauer_fp\n self.ds_fn = input.mauer_fn\n self.rgi_glacno_cn = input.mauer_rgi_glacno_cn\n self.mb_mwea_cn = input.mauer_mb_cn\n self.mb_mwea_err_cn = input.mauer_mb_err_cn\n self.t1_cn = input.mauer_time1_cn\n self.t2_cn = input.mauer_time2_cn\n \n elif self.name == 'wgms_d':\n self.ds_fp = input.wgms_fp\n self.ds_fn = input.wgms_d_fn_preprocessed\n self.rgi_glacno_cn = input.wgms_rgi_glacno_cn\n self.thickness_chg_cn = input.wgms_d_thickness_chg_cn\n self.thickness_chg_err_cn = input.wgms_d_thickness_chg_err_cn\n self.volume_chg_cn = input.wgms_d_volume_chg_cn\n self.volume_chg_err_cn = input.wgms_d_volume_chg_err_cn\n self.z1_cn = input.wgms_d_z1_cn\n self.z2_cn = input.wgms_d_z2_cn\n self.obs_type_cn = input.wgms_obs_type_cn\n \n elif self.name == 'wgms_ee':\n self.ds_fp = input.wgms_fp\n self.ds_fn = input.wgms_ee_fn_preprocessed\n self.rgi_glacno_cn = input.wgms_rgi_glacno_cn\n self.mb_mwe_cn = input.wgms_ee_mb_cn\n self.mb_mwe_err_cn = input.wgms_ee_mb_err_cn\n self.t1_cn = input.wgms_ee_t1_cn\n self.period_cn = input.wgms_ee_period_cn\n self.z1_cn = input.wgms_ee_z1_cn\n self.z2_cn = input.wgms_ee_z2_cn\n self.obs_type_cn = input.wgms_obs_type_cn\n \n elif self.name == 'cogley':\n self.ds_fp = input.cogley_fp\n self.ds_fn = input.cogley_fn_preprocessed\n self.rgi_glacno_cn = input.cogley_rgi_glacno_cn\n self.mass_chg_cn = input.cogley_mass_chg_cn\n self.mass_chg_err_cn = input.cogley_mass_chg_err_cn\n self.z1_cn = input.cogley_z1_cn\n self.z2_cn = input.cogley_z2_cn\n self.obs_type_cn = input.cogley_obs_type_cn\n \n elif self.name == 'group':\n self.ds_fp = input.mb_group_fp\n self.ds_fn = input.mb_group_data_fn\n self.ds_dict_fn = input.mb_group_dict_fn\n self.rgi_regionO1_cn = 'rgi_regionO1'\n self.t1_cn = input.mb_group_t1_cn\n self.t2_cn = input.mb_group_t2_cn\n \n \n def retrieve_mb(self, main_glac_rgi, main_glac_hyps, dates_table):\n \"\"\"\n Retrieve the mass balance for various datasets to be used in the calibration.\n \n \n Parameters\n ----------\n main_glac_rgi : pandas dataframe\n dataframe containing relevant rgi glacier information\n main_glac_hyps : pandas dataframe\n dataframe containing glacier hypsometry\n dates_table : pandas dataframe\n dataframe containing dates of model run\n \n Returns\n -------\n ds_output : pandas dataframe\n dataframe of mass balance observations and other relevant information for calibration \n \"\"\" \n # Dictionary linking glacier number (glacno) to index for selecting elevation indices\n glacnodict = dict(zip(main_glac_rgi['rgino_str'], main_glac_rgi.index.values))\n # Column names of output\n ds_output_cols = ['RGIId', 'glacno', 'group_name', 'obs_type', 'mb_mwe', 'mb_mwe_err', 'sla_m', 'z1_idx', \n 'z2_idx', 'z1', 'z2', 't1_idx', 't2_idx', 't1', 't2', 'area_km2', 'WGMS_ID']\n # Avoid group data as processing is slightly different\n if self.name is not 'group':\n # Load all data\n ds_all = pd.read_csv(self.ds_fp + self.ds_fn) \n if str(ds_all.loc[0,self.rgi_glacno_cn]).startswith('RGI'):\n ds_all['glacno'] = [str(x).split('-')[1] for x in ds_all[self.rgi_glacno_cn].values]\n else:\n ds_all['glacno'] = [str(int(x)).zfill(2) + '.' + str(int(np.round(x%1*10**5))).zfill(5) \n for x in ds_all[self.rgi_glacno_cn]]\n ds = ds_all.iloc[np.where(ds_all['glacno'].isin(list(main_glac_rgi.rgino_str.values)))[0],:].copy()\n ds.reset_index(drop=True, inplace=True)\n # Elevation indices\n elev_bins = main_glac_hyps.columns.values.astype(int)\n elev_bin_interval = elev_bins[1] - elev_bins[0]\n \n # DATASET SPECIFIC CALCULATIONS\n # ===== SHEAN GEODETIC DATA =====\n if self.name in ['shean', 'berthier', 'braun']:\n ds['z1_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values != 0).argmax(axis=1).astype(int))\n ds['z2_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values.cumsum(1)).argmax(axis=1).astype(int))\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n ds['area_km2'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n # Time indices\n ds['t1'] = ds[self.t1_cn].astype(np.float64)\n ds['t2'] = ds[self.t2_cn].astype(np.float64)\n ds['t1_year'] = ds['t1'].astype(int)\n ds['t1_month'] = round(ds['t1'] % ds['t1_year'] * 12 + 1)\n ds.loc[ds['t1_month'] == 13, 't1_year'] = ds.loc[ds['t1_month'] == 13, 't1_year'] + 1\n ds.loc[ds['t1_month'] == 13, 't1_month'] = 1\n # add 1 to account for the fact that January starts with value of 1\n ds['t2_year'] = ds['t2'].astype(int)\n ds['t2_month'] = round(ds['t2'] % ds['t2_year'] * 12)\n ds.loc[ds['t2_month'] == 0, 't2_month'] = 1\n # do not need to add one for t2 because we want the last full time step\n # Remove data with dates outside of calibration period\n year_decimal_min = dates_table.loc[0,'year'] + dates_table.loc[0,'month'] / 12\n year_decimal_max = (dates_table.loc[dates_table.shape[0]-1,'year'] + \n (dates_table.loc[dates_table.shape[0]-1,'month'] + 1) / 12)\n ds = ds[ds['t1_year'] + ds['t1_month'] / 12 >= year_decimal_min]\n ds = ds[ds['t2_year'] + ds['t2_month'] / 12 < year_decimal_max]\n ds.reset_index(drop=True, inplace=True) \n \n # Determine time indices (exclude spinup years, since massbal fxn discards spinup years)\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n# if x == 10539:\n# print(x, ds.loc[x,'RGIId'], ds.loc[x,'t1'], ds.loc[x,'t1_month'], ds.loc[x,'t2_month'])\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n ds['t1_idx'] = ds['t1_idx'].astype(int)\n # Specific mass balance [mwea]\n ds['mb_mwe'] = ds[self.mb_mwea_cn] * (ds['t2'] - ds['t1'])\n ds['mb_mwe_err'] = ds[self.mb_mwea_err_cn] * (ds['t2'] - ds['t1']) \n# # Total mass change [Gt]\n# ds['mb_gt'] = ds[self.mb_vol_cn] * (ds['t2'] - ds['t1']) * (1/1000)**3 * input.density_water / 1000\n# ds['mb_gt_err'] = ds[self.mb_vol_err_cn] * (ds['t2'] - ds['t1']) * (1/1000)**3 * input.density_water / 1000\n if 'obs_type' not in list(ds.columns.values):\n # Observation type\n ds['obs_type'] = 'mb_geo'\n # Add columns with nan for things not in list\n ds_addcols = [x for x in ds_output_cols if x not in ds.columns.values]\n for colname in ds_addcols:\n ds[colname] = np.nan\n \n# # ===== BERTHIER =====\n# if self.name == 'berthier':\n# ds['z1_idx'] = (\n# (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values != 0).argmax(axis=1).astype(int))\n# ds['z2_idx'] = (\n# (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values.cumsum(1)).argmax(axis=1).astype(int))\n# # Lower and upper bin elevations [masl]\n# ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n# ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n# # Area [km2]\n# ds['area_km2'] = np.nan\n# for x in range(ds.shape[0]):\n# ds.loc[x,'area_km2'] = (\n# main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n# ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n# # Time indices\n# ds['t1'] = ds[self.t1_cn]\n# ds['t2'] = ds[self.t2_cn]\n# print(ds)\n# ds['t1_year'] = ds['t1'].astype(int)\n# ds['t1_month'] = round(ds['t1'] % ds['t1_year'] * 12 + 1)\n# # add 1 to account for the fact that January starts with value of 1\n# ds['t2_year'] = ds['t2'].astype(int)\n# ds['t2_month'] = round(ds['t2'] % ds['t2_year'] * 12)\n# # do not need to add one for t2 because we want the last full time step\n# # Remove data with dates outside of calibration period\n# year_decimal_min = dates_table.loc[0,'year'] + dates_table.loc[0,'month'] / 12\n# year_decimal_max = (dates_table.loc[dates_table.shape[0]-1,'year'] + \n# (dates_table.loc[dates_table.shape[0]-1,'month'] + 1) / 12)\n# ds = ds[ds['t1_year'] + ds['t1_month'] / 12 >= year_decimal_min]\n# ds = ds[ds['t2_year'] + ds['t2_month'] / 12 <= year_decimal_max]\n# ds.reset_index(drop=True, inplace=True) \n# # Determine time indices (exclude spinup years, since massbal fxn discards spinup years)\n# ds['t1_idx'] = np.nan\n# ds['t2_idx'] = np.nan\n# for x in range(ds.shape[0]):\n# ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n# (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n# ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n# (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n# ds['t1_idx'] = ds['t1_idx'].astype(int)\n# # Specific mass balance [mwea]\n# print(ds[self.mb_mwea_cn])\n# ds['mb_mwe'] = ds[self.mb_mwea_cn] * (ds['t2'] - ds['t1'])\n# ds['mb_mwe_err'] = ds[self.mb_mwea_err_cn] * (ds['t2'] - ds['t1']) \n# # Observation type\n# ds['obs_type'] = 'mb_geo'\n# # Add columns with nan for things not in list\n# ds_addcols = [x for x in ds_output_cols if x not in ds.columns.values]\n# for colname in ds_addcols:\n# ds[colname] = np.nan\n \n # ===== BRUN GEODETIC DATA =====\n elif self.name == 'brun':\n print('code brun')\n \n # ===== MAUER GEODETIC DATA =====\n elif self.name == 'mauer':\n ds['z1_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values != 0).argmax(axis=1).astype(int))\n ds['z2_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values.cumsum(1)).argmax(axis=1).astype(int))\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n ds['area_km2'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n # Time indices\n ds['t1'] = ds[self.t1_cn]\n ds['t2'] = ds[self.t2_cn]\n ds['t1_year'] = ds['t1'].astype(int)\n ds['t1_month'] = round(ds['t1'] % ds['t1_year'] * 12 + 1)\n # add 1 to account for the fact that January starts with value of 1\n ds.loc[ds['t1_month'] > 12, 't1_month'] = 12\n ds['t2_year'] = ds['t2'].astype(int)\n ds['t2_month'] = 2\n # Remove data with dates outside of calibration period\n year_decimal_min = dates_table.loc[0,'year'] + dates_table.loc[0,'month'] / 12\n year_decimal_max = (dates_table.loc[dates_table.shape[0]-1,'year'] + \n (dates_table.loc[dates_table.shape[0]-1,'month'] + 1) / 12)\n ds = ds[ds['t1_year'] + ds['t1_month'] / 12 >= year_decimal_min]\n ds = ds[ds['t2_year'] + ds['t2_month'] / 12 <= year_decimal_max]\n ds.reset_index(drop=True, inplace=True) \n # Determine time indices (exclude spinup years, since massbal fxn discards spinup years)\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n ds['t1_idx'] = ds['t1_idx'].astype(int)\n # Specific mass balance [mwea]\n ds['mb_mwe'] = ds[self.mb_mwea_cn] * (ds['t2'] - ds['t1'])\n ds['mb_mwe_err'] = ds[self.mb_mwea_err_cn] * (ds['t2'] - ds['t1']) \n # Observation type\n ds['obs_type'] = 'mb_geo'\n \n # ===== WGMS GEODETIC DATA =====\n elif self.name == 'wgms_d':\n ds['z1_idx'] = np.nan\n ds['z2_idx'] = np.nan\n ds.loc[ds[self.z1_cn] == 9999, 'z1_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z1_cn] == 9999, 'glacno'].map(glacnodict)].values != 0)\n .argmax(axis=1))\n ds.loc[ds[self.z2_cn] == 9999, 'z2_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z2_cn] == 9999, 'glacno'].map(glacnodict)].values.cumsum(1))\n .argmax(axis=1))\n ds.loc[ds[self.z1_cn] != 9999, 'z1_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z1_cn] != 9999, self.z1_cn].shape[0],1)) - \n ds.loc[ds[self.z1_cn] != 9999, self.z1_cn][:,np.newaxis]) > 0).argmax(axis=1))\n ds.loc[ds[self.z2_cn] != 9999, 'z2_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z2_cn] != 9999, self.z2_cn].shape[0],1)) - \n ds.loc[ds[self.z2_cn] != 9999, self.z2_cn][:,np.newaxis]) > 0).argmax(axis=1) - 1)\n ds['z1_idx'] = ds['z1_idx'].values.astype(int)\n ds['z2_idx'] = ds['z2_idx'].values.astype(int)\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n # use WGMS area when provided; otherwise use area from RGI\n ds['area_km2_rgi'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2_rgi'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum()) \n ds['area_km2'] = np.nan\n ds.loc[ds.AREA_SURVEY_YEAR.isnull(), 'area_km2'] = ds.loc[ds.AREA_SURVEY_YEAR.isnull(), 'area_km2_rgi']\n ds.loc[ds.AREA_SURVEY_YEAR.notnull(), 'area_km2'] = ds.loc[ds.AREA_SURVEY_YEAR.notnull(), \n 'AREA_SURVEY_YEAR']\n # Time indices\n # remove data that does not have reference date or survey data\n ds = ds[np.isnan(ds['REFERENCE_DATE']) == False]\n ds = ds[np.isnan(ds['SURVEY_DATE']) == False]\n ds.reset_index(drop=True, inplace=True)\n # Extract date information\n ds['t1_year'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t1_month'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t1_day'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[6:].astype(int)\n ds['t2_year'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t2_month'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t2_day'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[6:].astype(int)\n # if month/day unknown for start or end period, then replace with water year\n # Add latitude \n latdict = dict(zip(main_glac_rgi['RGIId'], main_glac_rgi['CenLat']))\n ds['CenLat'] = ds['RGIId'].map(latdict)\n ds['lat_category'] = np.nan\n ds.loc[ds['CenLat'] >= input.lat_threshold, 'lat_category'] = 'northernmost'\n ds.loc[(ds['CenLat'] < input.lat_threshold) & (ds['CenLat'] > 0), 'lat_category'] = 'north'\n ds.loc[(ds['CenLat'] <= 0) & (ds['CenLat'] > -1*input.lat_threshold), 'lat_category'] = 'south'\n ds.loc[ds['CenLat'] <= -1*input.lat_threshold, 'lat_category'] = 'southernmost'\n ds['months_wintersummer'] = ds['lat_category'].map(input.monthdict)\n ds['winter_begin'] = ds['months_wintersummer'].apply(lambda x: x[0])\n ds['winter_end'] = ds['months_wintersummer'].apply(lambda x: x[1])\n ds['summer_begin'] = ds['months_wintersummer'].apply(lambda x: x[2])\n ds['summer_end'] = ds['months_wintersummer'].apply(lambda x: x[3])\n ds.loc[ds['t1_month'] == 99, 't1_month'] = ds.loc[ds['t1_month'] == 99, 'winter_begin']\n ds.loc[ds['t1_day'] == 99, 't1_day'] = 1\n ds.loc[ds['t2_month'] == 99, 't2_month'] = ds.loc[ds['t2_month'] == 99, 'winter_begin'] - 1\n for x in range(ds.shape[0]):\n if ds.loc[x, 't2_day'] == 99:\n try:\n ds.loc[x, 't2_day'] = (\n dates_table.loc[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month']), 'daysinmonth']\n .values[0])\n except:\n ds.loc[x, 't2_day'] = 28 \n # Replace poor values of months\n ds['t1_month'] = ds['t1_month'].map(lambda x: x if x <=12 else x%12)\n ds['t2_month'] = ds['t2_month'].map(lambda x: x if x <=12 else x%12)\n # Replace poor values of days\n ds['t1_daysinmonth'] = (\n [calendar.monthrange(ds.loc[x,'t1_year'], ds.loc[x,'t1_month'])[1] for x in range(ds.shape[0])])\n ds['t2_daysinmonth'] = (\n [calendar.monthrange(ds.loc[x,'t2_year'], ds.loc[x,'t2_month'])[1] for x in range(ds.shape[0])])\n ds['t1_day'] = (ds.apply(lambda x: x['t1_day'] if x['t1_day'] <= x['t1_daysinmonth'] \n else x['t1_daysinmonth'], axis=1))\n ds['t2_day'] = (ds.apply(lambda x: x['t2_day'] if x['t2_day'] <= x['t2_daysinmonth'] \n else x['t2_daysinmonth'], axis=1))\n # Calculate decimal year and drop measurements outside of calibration period\n ds['t1_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t1_year.values, 'month':ds.t1_month.values, 'day':ds.t1_day.values}))\n ds['t2_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t2_year.values, 'month':ds.t2_month.values, 'day':ds.t2_day.values}))\n ds['t1_doy'] = ds.t1_datetime.dt.strftime(\"%j\").astype(float)\n ds['t2_doy'] = ds.t2_datetime.dt.strftime(\"%j\").astype(float)\n ds['t1_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t2_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t1'] = ds.t1_year + ds.t1_doy / ds.t1_daysinyear\n ds['t2'] = ds.t2_year + ds.t2_doy / ds.t2_daysinyear\n end_datestable = dates_table.loc[dates_table.shape[0]-1, 'date']\n end_datetime = datetime.datetime(end_datestable.year, end_datestable.month + 1, end_datestable.day)\n ds = ds[ds['t1_datetime'] >= dates_table.loc[0, 'date']]\n ds = ds[ds['t2_datetime'] < end_datetime]\n ds.reset_index(drop=True, inplace=True)\n # Time indices\n # exclude spinup years, since massbal fxn discards spinup years\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n # Specific mass balance [mwe]\n # if thickness change is available, then compute the specific mass balance with the thickness change\n # otherwise, use the volume change and area to estimate the specific mass balance\n # using thickness change\n ds['mb_mwe'] = ds[self.thickness_chg_cn] / 1000 * input.density_ice / input.density_water\n ds['mb_mwe_err'] = ds[self.thickness_chg_err_cn] / 1000 * input.density_ice / input.density_water\n # using volume change (note: units volume change [1000 m3] and area [km2])\n ds.loc[ds.mb_mwe.isnull(), 'mb_mwe'] = (\n ds.loc[ds.mb_mwe.isnull(), self.volume_chg_cn] * 1000 / ds.loc[ds.mb_mwe.isnull(), 'area_km2'] * \n (1/1000)**2 * input.density_ice / input.density_water)\n ds.loc[ds.mb_mwe.isnull(), 'mb_mwe'] = (\n ds.loc[ds.mb_mwe.isnull(), self.volume_chg_err_cn] * 1000 / ds.loc[ds.mb_mwe.isnull(), 'area_km2'] * \n (1/1000)**2 * input.density_ice / input.density_water)\n # Observation type\n ds['obs_type'] = 'mb_geo'\n \n # ===== WGMS GLACIOLOGICAL DATA =====\n elif self.name == 'wgms_ee':\n ds['z1_idx'] = np.nan\n ds['z2_idx'] = np.nan\n ds.loc[ds[self.z1_cn] == 9999, 'z1_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z1_cn] == 9999, 'glacno'].map(glacnodict)].values != 0)\n .argmax(axis=1))\n ds.loc[ds[self.z2_cn] == 9999, 'z2_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z2_cn] == 9999, 'glacno'].map(glacnodict)].values.cumsum(1))\n .argmax(axis=1))\n ds.loc[ds[self.z1_cn] != 9999, 'z1_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z1_cn] != 9999, self.z1_cn].shape[0],1)) - \n ds.loc[ds[self.z1_cn] != 9999, self.z1_cn][:,np.newaxis]) > 0).argmax(axis=1))\n ds.loc[ds[self.z2_cn] != 9999, 'z2_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z2_cn] != 9999, self.z2_cn].shape[0],1)) - \n ds.loc[ds[self.z2_cn] != 9999, self.z2_cn][:,np.newaxis]) > 0).argmax(axis=1) - 1)\n ds['z1_idx'] = ds['z1_idx'].values.astype(int)\n ds['z2_idx'] = ds['z2_idx'].values.astype(int)\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n ds['area_km2'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n ds = ds[ds['area_km2'] > 0]\n ds.reset_index(drop=True, inplace=True)\n # Time indices\n # winter and summer balances typically have the same data for 'BEGIN_PERIOD' and 'END_PERIOD' as the annual\n # measurements, so need to set these dates manually\n # Remove glaciers without begin or end period\n ds = ds.drop(np.where(np.isnan(ds['BEGIN_PERIOD'].values))[0].tolist(), axis=0)\n ds = ds.drop(np.where(np.isnan(ds['END_PERIOD'].values))[0].tolist(), axis=0)\n ds.reset_index(drop=True, inplace=True)\n ds['t1_year'] = ds['BEGIN_PERIOD'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t1_month'] = ds['BEGIN_PERIOD'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t1_day'] = ds['BEGIN_PERIOD'].astype(str).str.split('.').str[0].str[6:].astype(int)\n ds['t2_year'] = ds['END_PERIOD'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t2_month'] = ds['END_PERIOD'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t2_day'] = ds['END_PERIOD'].astype(str).str.split('.').str[0].str[6:].astype(int) \n # if annual measurement and month/day unknown for start or end period, then replace with water year\n # Add latitude \n latdict = dict(zip(main_glac_rgi['RGIId'], main_glac_rgi['CenLat']))\n ds['CenLat'] = ds['RGIId'].map(latdict)\n ds['lat_category'] = np.nan\n ds.loc[ds['CenLat'] >= input.lat_threshold, 'lat_category'] = 'northernmost'\n ds.loc[(ds['CenLat'] < input.lat_threshold) & (ds['CenLat'] > 0), 'lat_category'] = 'north'\n ds.loc[(ds['CenLat'] <= 0) & (ds['CenLat'] > -1*input.lat_threshold), 'lat_category'] = 'south'\n ds.loc[ds['CenLat'] <= -1*input.lat_threshold, 'lat_category'] = 'southernmost'\n ds['months_wintersummer'] = ds['lat_category'].map(input.monthdict)\n ds['winter_begin'] = ds['months_wintersummer'].apply(lambda x: x[0])\n ds['winter_end'] = ds['months_wintersummer'].apply(lambda x: x[1])\n ds['summer_begin'] = ds['months_wintersummer'].apply(lambda x: x[2])\n ds['summer_end'] = ds['months_wintersummer'].apply(lambda x: x[3])\n # annual start\n ds.loc[ds['t1_month'] == 99, 't1_month'] = ds.loc[ds['t1_month'] == 99, 'winter_begin']\n ds.loc[ds['t1_day'] == 99, 't1_day'] = 1\n ds.loc[ds['t2_month'] == 99, 't2_month'] = ds.loc[ds['t2_month'] == 99, 'winter_begin'] - 1\n for x in range(ds.shape[0]):\n if ds.loc[x, 't2_day'] == 99:\n try:\n ds.loc[x, 't2_day'] = (\n dates_table.loc[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month']), 'daysinmonth']\n .values[0])\n except:\n ds.loc[x, 't2_day'] = 28\n # If period is summer/winter, adjust dates accordingly\n for x in range(ds.shape[0]):\n if (((ds.loc[x, 'lat_category'] == 'north') or (ds.loc[x, 'lat_category'] == 'northern')) and \n (ds.loc[x, 'period'] == 'summer')):\n ds.loc[x, 't1_year'] = ds.loc[x, 't1_year'] + 1\n ds.loc[x, 't1_month'] = ds.loc[x, 'summer_begin']\n ds.loc[x, 't2_month'] = ds.loc[x, 'summer_end']\n elif (((ds.loc[x, 'lat_category'] == 'south') or (ds.loc[x, 'lat_category'] == 'southernmost')) and \n (ds.loc[x, 'period'] == 'summer')):\n ds.loc[x, 't1_month'] = ds.loc[x, 'summer_begin']\n ds.loc[x, 't2_month'] = ds.loc[x, 'summer_end']\n elif (((ds.loc[x, 'lat_category'] == 'north') or (ds.loc[x, 'lat_category'] == 'northern')) and \n (ds.loc[x, 'period'] == 'winter')):\n ds.loc[x, 't1_month'] = ds.loc[x, 'winter_begin']\n ds.loc[x, 't2_month'] = ds.loc[x, 'winter_end']\n elif (((ds.loc[x, 'lat_category'] == 'south') or (ds.loc[x, 'lat_category'] == 'southernmost')) and \n (ds.loc[x, 'period'] == 'summer')):\n ds.loc[x, 't1_year'] = ds.loc[x, 't1_year'] + 1\n ds.loc[x, 't1_month'] = ds.loc[x, 'winter_begin']\n ds.loc[x, 't2_month'] = ds.loc[x, 'winter_end']\n ds.loc[x, 't1_day'] = 1\n ds.loc[x, 't2_day'] = calendar.monthrange(ds.loc[x, 't2_year'], ds.loc[x, 't2_month'])[1]\n # Replace poor values of months\n ds['t1_month'] = ds['t1_month'].map(lambda x: x if x <=12 else x%12)\n ds['t2_month'] = ds['t2_month'].map(lambda x: x if x <=12 else x%12)\n # Calculate decimal year and drop measurements outside of calibration period\n ds['t1_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t1_year.values, 'month':ds.t1_month.values, 'day':ds.t1_day.values}))\n ds['t2_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t2_year.values, 'month':ds.t2_month.values, 'day':ds.t2_day.values}))\n ds['t1_doy'] = ds.t1_datetime.dt.strftime(\"%j\").astype(float)\n ds['t2_doy'] = ds.t2_datetime.dt.strftime(\"%j\").astype(float)\n ds['t1_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t2_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t1'] = ds.t1_year + ds.t1_doy / ds.t1_daysinyear\n ds['t2'] = ds.t2_year + ds.t2_doy / ds.t2_daysinyear\n end_datestable = dates_table.loc[dates_table.shape[0]-1, 'date']\n end_datetime = datetime.datetime(end_datestable.year, end_datestable.month + 1, end_datestable.day)\n ds = ds[ds['t1_datetime'] >= dates_table.loc[0, 'date']]\n ds = ds[ds['t2_datetime'] < end_datetime]\n ds.reset_index(drop=True, inplace=True)\n # Annual, summer, and winter time indices\n # exclude spinup years, since massbal fxn discards spinup years\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n # Specific mass balance [mwe]\n ds['mb_mwe'] = ds[self.mb_mwe_cn] / 1000\n ds['mb_mwe_err'] = ds[self.mb_mwe_err_cn] / 1000\n# # Total mass change [Gt]\n# ds['mb_gt'] = ds[self.mb_mwe_cn] / 1000 * ds['area_km2'] * 1000**2 * input.density_water / 1000 / 10**9\n# ds['mb_gt_err'] = (ds[self.mb_mwe_err_cn] / 1000 * ds['area_km2'] * 1000**2 * input.density_water / 1000 \n# / 10**9)\n # Observation type\n ds['obs_type'] = 'mb_glac'\n \n # ===== WGMS GLACIOLOGICAL DATA =====\n elif self.name == 'cogley':\n ds['z1_idx'] = np.nan\n ds['z2_idx'] = np.nan\n ds.loc[ds[self.z1_cn] == 9999, 'z1_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z1_cn] == 9999, 'glacno'].map(glacnodict)].values != 0)\n .argmax(axis=1))\n ds.loc[ds[self.z2_cn] == 9999, 'z2_idx'] = (\n (main_glac_hyps.iloc[ds.loc[ds[self.z2_cn] == 9999, 'glacno'].map(glacnodict)].values.cumsum(1))\n .argmax(axis=1))\n ds.loc[ds[self.z1_cn] != 9999, 'z1_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z1_cn] != 9999, self.z1_cn].shape[0],1)) - \n ds.loc[ds[self.z1_cn] != 9999, self.z1_cn][:,np.newaxis]) > 0).argmax(axis=1))\n ds.loc[ds[self.z2_cn] != 9999, 'z2_idx'] = (\n ((np.tile(elev_bins, (ds.loc[ds[self.z2_cn] != 9999, self.z2_cn].shape[0],1)) - \n ds.loc[ds[self.z2_cn] != 9999, self.z2_cn][:,np.newaxis]) > 0).argmax(axis=1) - 1)\n ds['z1_idx'] = ds['z1_idx'].values.astype(int)\n ds['z2_idx'] = ds['z2_idx'].values.astype(int)\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n # use WGMS area when provided; otherwise use area from RGI\n ds['area_km2_rgi'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2_rgi'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n # Time indices\n ds['t1_year'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t1_month'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t1_day'] = ds['REFERENCE_DATE'].astype(str).str.split('.').str[0].str[6:].astype(int)\n ds['t2_year'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t2_month'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t2_day'] = ds['SURVEY_DATE'].astype(str).str.split('.').str[0].str[6:].astype(int)\n # if month/day unknown for start or end period, then replace with water year\n # Add latitude \n latdict = dict(zip(main_glac_rgi['RGIId'], main_glac_rgi['CenLat']))\n ds['CenLat'] = ds['RGIId'].map(latdict)\n ds['lat_category'] = np.nan\n ds.loc[ds['CenLat'] >= input.lat_threshold, 'lat_category'] = 'northernmost'\n ds.loc[(ds['CenLat'] < input.lat_threshold) & (ds['CenLat'] > 0), 'lat_category'] = 'north'\n ds.loc[(ds['CenLat'] <= 0) & (ds['CenLat'] > -1*input.lat_threshold), 'lat_category'] = 'south'\n ds.loc[ds['CenLat'] <= -1*input.lat_threshold, 'lat_category'] = 'southernmost'\n ds['months_wintersummer'] = ds['lat_category'].map(input.monthdict)\n ds['winter_begin'] = ds['months_wintersummer'].apply(lambda x: x[0])\n ds['winter_end'] = ds['months_wintersummer'].apply(lambda x: x[1])\n ds['summer_begin'] = ds['months_wintersummer'].apply(lambda x: x[2])\n ds['summer_end'] = ds['months_wintersummer'].apply(lambda x: x[3])\n ds.loc[ds['t1_month'] == 99, 't1_month'] = ds.loc[ds['t1_month'] == 99, 'winter_begin']\n ds.loc[ds['t1_day'] == 99, 't1_day'] = 1\n ds.loc[ds['t2_month'] == 99, 't2_month'] = ds.loc[ds['t2_month'] == 99, 'winter_begin'] - 1\n for x in range(ds.shape[0]):\n if ds.loc[x, 't2_day'] == 99:\n try:\n ds.loc[x, 't2_day'] = (\n dates_table.loc[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month']), 'daysinmonth']\n .values[0])\n except:\n ds.loc[x, 't2_day'] = 28 \n # Calculate decimal year and drop measurements outside of calibration period\n ds['t1_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t1_year.values, 'month':ds.t1_month.values, 'day':ds.t1_day.values}))\n ds['t2_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t2_year.values, 'month':ds.t2_month.values, 'day':ds.t2_day.values}))\n ds['t1_doy'] = ds.t1_datetime.dt.strftime(\"%j\").astype(float)\n ds['t2_doy'] = ds.t2_datetime.dt.strftime(\"%j\").astype(float)\n ds['t1_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t2_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t1'] = ds.t1_year + ds.t1_doy / ds.t1_daysinyear\n ds['t2'] = ds.t2_year + ds.t2_doy / ds.t2_daysinyear\n end_datestable = dates_table.loc[dates_table.shape[0]-1, 'date']\n end_datetime = datetime.datetime(end_datestable.year, end_datestable.month + 1, end_datestable.day)\n ds = ds[ds['t1_datetime'] >= dates_table.loc[0, 'date']]\n ds = ds[ds['t2_datetime'] < end_datetime]\n ds.reset_index(drop=True, inplace=True)\n # Time indices\n # exclude spinup years, since massbal fxn discards spinup years\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n # Specific mass balance [mwe]\n ds['mb_mwe'] = ds[self.mass_chg_cn] / input.density_water * (ds['t2'] - ds['t1'])\n ds['mb_mwe_err'] = ds[self.mass_chg_err_cn] / input.density_water * (ds['t2'] - ds['t1'])\n # Observation type\n ds['obs_type'] = 'mb_geo'\n \n # ===== LARSEN OR MCNABB GEODETIC MASS BALANCE =====\n elif self.name == 'mcnabb' or self.name == 'larsen': \n ds['z1_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values != 0).argmax(axis=1).astype(int))\n ds['z2_idx'] = (\n (main_glac_hyps.iloc[ds['glacno'].map(glacnodict)].values.cumsum(1)).argmax(axis=1).astype(int))\n # Lower and upper bin elevations [masl]\n ds['z1'] = elev_bins[ds['z1_idx'].values] - elev_bin_interval/2\n ds['z2'] = elev_bins[ds['z2_idx'].values] + elev_bin_interval/2\n # Area [km2]\n ds['area_km2'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'area_km2'] = (\n main_glac_hyps.iloc[glacnodict[ds.loc[x,'glacno']], \n ds.loc[x,'z1_idx']:ds.loc[x,'z2_idx']+1].sum())\n # Time\n ds['t1_year'] = [int(str(x)[0:4]) for x in ds[self.t1_cn].values]\n ds['t1_month'] = [int(str(x)[4:6]) for x in ds[self.t1_cn].values]\n ds['t1_day'] = [int(str(x)[6:]) for x in ds[self.t1_cn].values]\n ds['t2_year'] = [int(str(x)[0:4]) for x in ds[self.t2_cn].values]\n ds['t2_month'] = [int(str(x)[4:6]) for x in ds[self.t2_cn].values]\n ds['t2_day'] = [int(str(x)[6:]) for x in ds[self.t2_cn].values] \n ds['t1_daysinmonth'] = ds.apply(lambda row: modelsetup.daysinmonth(row['t1_year'], row['t1_month']), axis=1)\n ds['t2_daysinmonth'] = ds.apply(lambda row: modelsetup.daysinmonth(row['t2_year'], row['t2_month']), axis=1)\n ds['t1_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t1_year.values, 'month':ds.t1_month.values, 'day':ds.t1_day.values}))\n ds['t2_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t2_year.values, 'month':ds.t2_month.values, 'day':ds.t2_day.values}))\n ds['t1'] = ds['t1_year'] + (ds['t1_month'] + ds['t1_day'] / ds['t1_daysinmonth']) / 12\n ds['t2'] = ds['t2_year'] + (ds['t2_month'] + ds['t2_day'] / ds['t2_daysinmonth']) / 12\n # Remove data with dates outside of calibration period\n year_decimal_min = dates_table.loc[0,'year'] + dates_table.loc[0,'month'] / 12\n year_decimal_max = (dates_table.loc[dates_table.shape[0]-1,'year'] + \n (dates_table.loc[dates_table.shape[0]-1,'month'] + 1) / 12)\n ds = ds[ds['t1_year'] + ds['t1_month'] / 12 >= year_decimal_min]\n ds = ds[ds['t2_year'] + ds['t2_month'] / 12 < year_decimal_max]\n ds.reset_index(drop=True, inplace=True) \n # Determine time indices (exclude spinup years, since massbal fxn discards spinup years)\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n ds['t1_idx'] = ds['t1_idx'].astype(int)\n # Specific mass balance [mwea]\n ds['mb_mwe'] = ds[self.mb_mwea_cn] * (ds['t2'] - ds['t1'])\n ds['mb_mwe_err'] = ds[self.mb_mwea_err_cn] * (ds['t2'] - ds['t1']) \n # Total mass change [Gt]\n# ds['mb_gt'] = ds[self.mb_vol_cn] * (ds['t2'] - ds['t1']) * (1/1000)**3 * input.density_water / 1000\n# ds['mb_gt_err'] = ds[self.mb_vol_err_cn] * (ds['t2'] - ds['t1']) * (1/1000)**3 * input.density_water / 1000\n # Observation type\n ds['obs_type'] = 'mb_geo'\n \n # ====== GROUP DATA ======\n elif self.name == 'group':\n # Load all data\n ds_all = pd.read_csv(self.ds_fp + self.ds_fn, encoding='latin1')\n # Dictionary linking group_names with the RGIIds\n ds_dict_raw = pd.read_csv(self.ds_fp + self.ds_dict_fn)\n ds_dict = dict(zip(ds_dict_raw['RGIId'], ds_dict_raw['group_name']))\n # For each unique group name identify all glaciers associated with the group and test if all those glaciers\n # are included in the model run via main_glac_rgi\n group_names_unique = list(set(ds_dict.values()))\n ds_dict_keyslist = [[] for x in group_names_unique]\n for n, group in enumerate(group_names_unique):\n ds_dict_keyslist[n] = [group, [k for k, v in ds_dict.items() if v == group]]\n ds_all['glaciers_present'] = set(ds_dict_keyslist[n][1]).issubset(main_glac_rgi.RGIId.values.tolist())\n ds_all.loc[n, 'first_RGIId'] = ds_dict_keyslist[n][1][0]\n # Remove groups where all glaciers are not included\n ds = ds_all[ds_all.glaciers_present == True].copy()\n ds.reset_index(drop=True, inplace=True)\n # Time indices\n ds['t1_year'] = ds[self.t1_cn].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t1_month'] = ds[self.t1_cn].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t1_day'] = ds[self.t1_cn].astype(str).str.split('.').str[0].str[6:].astype(int)\n ds['t2_year'] = ds[self.t2_cn].astype(str).str.split('.').str[0].str[:4].astype(int)\n ds['t2_month'] = ds[self.t2_cn].astype(str).str.split('.').str[0].str[4:6].astype(int)\n ds['t2_day'] = ds[self.t2_cn].astype(str).str.split('.').str[0].str[6:].astype(int)\n # if month/day unknown for start or end period, then replace with water year\n # Add latitude \n latdict = dict(zip(main_glac_rgi['RGIId'], main_glac_rgi['CenLat']))\n ds['CenLat'] = ds['first_RGIId'].map(latdict)\n ds['lat_category'] = np.nan\n ds.loc[ds['CenLat'] >= input.lat_threshold, 'lat_category'] = 'northernmost'\n ds.loc[(ds['CenLat'] < input.lat_threshold) & (ds['CenLat'] > 0), 'lat_category'] = 'north'\n ds.loc[(ds['CenLat'] <= 0) & (ds['CenLat'] > -1*input.lat_threshold), 'lat_category'] = 'south'\n ds.loc[ds['CenLat'] <= -1*input.lat_threshold, 'lat_category'] = 'southernmost'\n ds['months_wintersummer'] = ds['lat_category'].map(input.monthdict)\n ds['winter_begin'] = ds['months_wintersummer'].apply(lambda x: x[0])\n ds['winter_end'] = ds['months_wintersummer'].apply(lambda x: x[1])\n ds['summer_begin'] = ds['months_wintersummer'].apply(lambda x: x[2])\n ds['summer_end'] = ds['months_wintersummer'].apply(lambda x: x[3])\n ds.loc[ds['t1_month'] == 99, 't1_month'] = ds.loc[ds['t1_month'] == 99, 'winter_begin']\n ds.loc[ds['t1_day'] == 99, 't1_day'] = 1\n ds.loc[ds['t2_month'] == 99, 't2_month'] = ds.loc[ds['t2_month'] == 99, 'winter_begin'] - 1\n for x in range(ds.shape[0]):\n if ds.loc[x, 't2_day'] == 99:\n try:\n ds.loc[x, 't2_day'] = (\n dates_table.loc[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month']), 'daysinmonth']\n .values[0])\n except:\n ds.loc[x, 't2_day'] = 28 \n # Calculate decimal year and drop measurements outside of calibration period\n ds['t1_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t1_year.values, 'month':ds.t1_month.values, 'day':ds.t1_day.values}))\n ds['t2_datetime'] = pd.to_datetime(\n pd.DataFrame({'year':ds.t2_year.values, 'month':ds.t2_month.values, 'day':ds.t2_day.values}))\n ds['t1_doy'] = ds.t1_datetime.dt.strftime(\"%j\").astype(float)\n ds['t2_doy'] = ds.t2_datetime.dt.strftime(\"%j\").astype(float)\n ds['t1_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t1_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t2_daysinyear'] = (\n (pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':12, 'day':31})) - \n pd.to_datetime(pd.DataFrame({'year':ds.t2_year.values, 'month':1, 'day':1}))).dt.days + 1)\n ds['t1'] = ds.t1_year + ds.t1_doy / ds.t1_daysinyear\n ds['t2'] = ds.t2_year + ds.t2_doy / ds.t2_daysinyear\n end_datestable = dates_table.loc[dates_table.shape[0]-1, 'date']\n end_datetime = datetime.datetime(end_datestable.year, end_datestable.month + 1, end_datestable.day)\n ds = ds[ds['t1_datetime'] >= dates_table.loc[0, 'date']]\n ds = ds[ds['t2_datetime'] < end_datetime]\n ds.reset_index(drop=True, inplace=True)\n # Time indices\n # exclude spinup years, since massbal fxn discards spinup years\n ds['t1_idx'] = np.nan\n ds['t2_idx'] = np.nan\n for x in range(ds.shape[0]):\n ds.loc[x,'t1_idx'] = (dates_table[(ds.loc[x, 't1_year'] == dates_table['year']) & \n (ds.loc[x, 't1_month'] == dates_table['month'])].index.values[0])\n ds.loc[x,'t2_idx'] = (dates_table[(ds.loc[x, 't2_year'] == dates_table['year']) & \n (ds.loc[x, 't2_month'] == dates_table['month'])].index.values[0])\n # Mass balance [mwe]\n ds['mb_mwe'] = np.nan\n ds['mb_mwe_err'] = np.nan\n ds.loc[ds['dhdt_ma'].notnull(), 'mb_mwe'] = (\n ds.loc[ds['dhdt_ma'].notnull(), 'dhdt_ma'] * input.density_ice / input.density_water * \n (ds['t2'] - ds['t1']))\n ds.loc[ds['dhdt_ma'].notnull(), 'mb_mwe_err'] = (\n ds.loc[ds['dhdt_ma'].notnull(), 'dhdt_unc_ma'] * input.density_ice / input.density_water * \n (ds['t2'] - ds['t1']))\n \n \n # Add columns with nan for things not in list\n ds_addcols = [x for x in ds_output_cols if x not in ds.columns.values]\n for colname in ds_addcols:\n ds[colname] = np.nan\n # Select output\n ds_output = ds[ds_output_cols].sort_values(['glacno', 't1_idx'])\n ds_output.reset_index(drop=True, inplace=True)\n\n return ds_output\n \n\ndef select_best_mb(cal_data):\n \"\"\"\n Retrieve 'best' mass balance (observed > extrapolated) and longest time period\n \n Returns\n -------\n cal_data_best : pandas dataframe\n dataframe of 'best' mass balance observations and other relevant information for calibration \n \"\"\" \n cal_data['dt'] = cal_data['t2'] - cal_data['t1']\n rgiids = list(cal_data.RGIId.values)\n rgiids_count = collections.Counter(rgiids)\n rgiids_multiple = []\n rgiids_single_idx = []\n cal_data_rgiids_all = list(cal_data.RGIId.values)\n for x in rgiids_count:\n if rgiids_count[x] > 1:\n rgiids_multiple.append(x)\n else:\n rgiids_single_idx.append(cal_data_rgiids_all.index(x))\n rgiids_multiple = sorted(rgiids_multiple)\n rgiids_single_idx = sorted(rgiids_single_idx) \n \n # Select all data with single value \n cal_data_best = cal_data.loc[rgiids_single_idx,:]\n \n # Append 'best' value for those with multiple observations\n for rgiid in rgiids_multiple:\n cal_data_multiple = cal_data[cal_data['RGIId'] == rgiid]\n # Select observations over extrapolated values\n if 'mb_geo' in list(cal_data_multiple.obs_type.values):\n cal_data_multiple = cal_data_multiple[cal_data_multiple.obs_type == 'mb_geo']\n # Select longest time series\n cal_data_append = cal_data_multiple[cal_data_multiple.dt == cal_data_multiple.dt.max()] \n \n cal_data_best = pd.concat([cal_data_best, cal_data_append], axis=0)\n \n cal_data_best = cal_data_best.sort_values(by=['RGIId'])\n cal_data_best.reset_index(inplace=True, drop=True)\n \n return cal_data_best\n \n\n#%% Testing\nif __name__ == '__main__':\n # Glacier selection\n rgi_regionsO1 = [1]\n rgi_glac_number = 'all'\n glac_no = input.glac_no\n startyear = 1950\n endyear = 2018\n \n# # Select glaciers\n# for rgi_regionsO1 in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]:\n# main_glac_rgi = modelsetup.selectglaciersrgitable(rgi_regionsO1=[rgi_regionsO1], rgi_regionsO2 = 'all', \n# rgi_glac_number='all')\n# marine = main_glac_rgi[main_glac_rgi['TermType'] == 1]\n# lake = main_glac_rgi[main_glac_rgi['TermType'] == 2]\n# print('Region ' + str(rgi_regionsO1) + ':')\n# print(' marine:', np.round(marine.Area.sum() / main_glac_rgi.Area.sum() * 100,0))\n# print(' lake:', np.round(lake.Area.sum() / main_glac_rgi.Area.sum() * 100,0))\n main_glac_rgi = modelsetup.selectglaciersrgitable(rgi_regionsO1=rgi_regionsO1, rgi_regionsO2 = 'all', \n rgi_glac_number=rgi_glac_number, glac_no=input.glac_no)\n # Glacier hypsometry [km**2], total area\n main_glac_hyps = modelsetup.import_Husstable(main_glac_rgi, input.hyps_filepath, input.hyps_filedict, \n input.hyps_colsdrop)\n # Determine dates_table_idx that coincides with data\n dates_table = modelsetup.datesmodelrun(startyear, endyear, spinupyears=0, option_wateryear=3)\n \n elev_bins = main_glac_hyps.columns.values.astype(int)\n elev_bin_interval = elev_bins[1] - elev_bins[0]\n \n \n #%%\n# cal_datasets = ['shean'] \n# cal_datasets = ['braun', 'mcnabb', 'larsen', 'berthier']\n# cal_datasets = ['braun', 'larsen', 'mcnabb']\n cal_datasets = ['braun']\n# cal_datasets = ['shean', 'mauer', 'wgms_d', 'wgms_ee', 'cogley', 'mcnabb', 'larsen']\n# cal_datasets = ['group']\n \n cal_data = pd.DataFrame()\n for dataset in cal_datasets:\n cal_subset = MBData(name=dataset)\n cal_subset_data = cal_subset.retrieve_mb(main_glac_rgi, main_glac_hyps, dates_table)\n cal_data = cal_data.append(cal_subset_data, ignore_index=True)\n \n # Count unique glaciers and fraction of total area\n glacno_unique = list(cal_subset_data.glacno.unique())\n main_glac_rgi_cal = modelsetup.selectglaciersrgitable(glac_no = glacno_unique)\n print(dataset, '- glacier area covered: ', \n np.round(main_glac_rgi_cal.Area.sum() / main_glac_rgi.Area.sum() * 100,1),'%')\n \n cal_data = cal_data.sort_values(['glacno', 't1_idx'])\n cal_data.reset_index(drop=True, inplace=True)\n \n # Count unique glaciers and fraction of total area\n if len(cal_datasets) > 1:\n glacno_unique = list(cal_data.glacno.unique())\n main_glac_rgi_cal = modelsetup.selectglaciersrgitable(glac_no = glacno_unique)\n print('All datasets glacier area covered: ', \n np.round(main_glac_rgi_cal.Area.sum() / main_glac_rgi.Area.sum() * 100,1),'%')\n \n# # Export 'best' dataset\n# cal_data_best = select_best_mb(cal_data)\n# cal_data_best = cal_data_best.drop(['group_name', 'sla_m', 'WGMS_ID'], axis=1)\n# cal_data_best['mb_mwea'] = cal_data_best.mb_mwe / cal_data_best.dt\n# cal_data_best['mb_mwea_sigma'] = cal_data_best.mb_mwe_err / cal_data_best.dt\n# cal_data_best.to_csv(input.braun_fp + 'braun_AK_all_20190924_wlarsen_mcnabb_best.csv', index=False)\n \n\n#%% PRE-PROCESS MCNABB DATA\n# # Remove glaciers that:\n# # (1) poor percent coverage\n# # (2) uncertainty is too hig\n# \n# density_ice_brun = 850\n# \n# mcnabb_fn = 'McNabb_data_all_raw.csv'\n# output_fn = 'McNabb_data_all_preprocessed.csv'\n# \n# # Load data\n# ds_raw = pd.read_csv(input.mcnabb_fp + mcnabb_fn)\n# ds_raw['glacno_str'] = [x.split('-')[1] for x in ds_raw.RGIId.values]\n# ds_raw['mb_mwea'] = ds_raw['smb'] * density_ice_brun / input.density_water\n# ds_raw['mb_mwea_sigma'] = ds_raw['e_dh'] * density_ice_brun / input.density_water\n# nraw = ds_raw.shape[0]\n# \n# # remove data with poor coverage\n# ds = ds_raw[ds_raw['pct_data'] > 0.75].copy()\n# ds.reset_index(drop=True, inplace=True)\n# nraw_goodcoverage = ds.shape[0]\n# print('Glaciers removed (poor coverage):', nraw - nraw_goodcoverage, 'points')\n# \n# # remove glaciers with too high uncertainty (> 1.96 stdev)\n# uncertainty_median = ds.e_dh.median()\n# ds['e_mad'] = np.absolute(ds['e_dh'] - uncertainty_median)\n# uncertainty_mad = np.median(ds['e_mad'])\n# print('uncertainty median and mad [m/yr]:', np.round(uncertainty_median,2), np.round(uncertainty_mad,2))\n# ds = ds[ds['e_dh'] < uncertainty_median + 3*uncertainty_mad].copy()\n# ds = ds.sort_values('RGIId')\n# ds.reset_index(drop=True, inplace=True)\n# print('Glaciers removed (too high uncertainty):', nraw_goodcoverage - ds.shape[0], 'points')\n# \n# # Select glaciers\n# glac_no = sorted(set(ds['glacno_str'].values))\n# main_glac_rgi = modelsetup.selectglaciersrgitable(glac_no=glac_no)\n# \n# # Count unique glaciers and fraction of total area\n# print('Glacier area covered: ', np.round(main_glac_rgi['Area'].sum(),1),'km2')\n# \n## # All values\n## rgiid_values = list(ds.RGIId.values)\n## rgiid_idx = []\n## for rgiid in rgiid_values:\n## rgiid_idx.append(np.where(main_glac_rgi.RGIId.values == rgiid)[0][0])\n## ds['CenLat'] = main_glac_rgi.loc[rgiid_idx, 'CenLat'].values\n## ds['CenLon'] = main_glac_rgi.loc[rgiid_idx, 'CenLon'].values\n#\n#\n# # Only longest value\n# ds_output = pd.DataFrame(np.zeros((len(glac_no), ds.shape[1])), columns=ds.columns)\n# for nglac, glacno in enumerate(glac_no):\n# ds_subset = ds.loc[np.where(ds.glacno_str.values == glacno)[0],:]\n# ds_subset.reset_index(inplace=True)\n# ds_output.loc[nglac,:] = (\n# ds_subset.loc[np.where(ds_subset['pct_data'].values == ds_subset['pct_data'].max())[0][0],:])\n# \n# # Minimum and maximum mass balances\n# print('Max MB:', np.round(ds_output.loc[np.where(ds_output.smb.values == ds_output.smb.max())[0][0],'smb'],2), \n# '+/-', np.round(ds_output.loc[np.where(ds_output.smb.values == ds_output.smb.max())[0][0],'e_dh'],2))\n# print('Min MB:', np.round(ds_output.loc[np.where(ds_output.smb.values == ds_output.smb.min())[0][0],'smb'],2), \n# '+/-', np.round(ds_output.loc[np.where(ds_output.smb.values == ds_output.smb.min())[0][0],'e_dh'],2))\n#\n# # Adjust date to YYYYMMDD format\n# print('\\nCHECK ALL YEARS AFTER IN 2000s\\n')\n# ds_output['y0'] = ['20' + str(x.split('/')[2]).zfill(2) for x in ds_output['date0'].values]\n# ds_output['m0'] = [str(x.split('/')[0]).zfill(2) for x in ds_output['date0'].values]\n# ds_output['d0'] = [str(x.split('/')[1]).zfill(2) for x in ds_output['date0'].values]\n# ds_output['y1'] = ['20' + str(x.split('/')[2]).zfill(2) for x in ds_output['date1'].values]\n# ds_output['m1'] = [str(x.split('/')[0]).zfill(2) for x in ds_output['date1'].values]\n# ds_output['d1'] = [str(x.split('/')[1]).zfill(2) for x in ds_output['date1'].values]\n# ds_output['date0'] = ds_output['y0'] + ds_output['m0'] + ds_output['d0']\n# ds_output['date1'] = ds_output['y1'] + ds_output['m1'] + ds_output['d1']\n# ds_output.drop(['y0', 'm0', 'd0', 'y1', 'm1', 'd1'], axis=1, inplace=True)\n# \n# ds_output.to_csv(input.mcnabb_fp + output_fn)\n \n\n#%%\n# # PRE-PROCESS MAUER DATA\n# mauer_fn = 'Mauer_geoMB_HMA_1970s_2000.csv'\n# min_pctCov = 80\n# \n# ds = pd.read_csv(input.mauer_fp + mauer_fn)\n# ds.dropna(axis=0, how='any', inplace=True)\n# ds.sort_values('RGIId')\n# ds.reset_index(drop=True, inplace=True)\n# demyears = ds.demYears.tolist()\n# demyears = [x.split(';') for x in demyears]\n# t1_raw = []\n# t2 = []\n# for x in demyears:\n# if '2000' in x:\n# x.remove('2000')\n# t2.append(2000)\n# t1_raw.append([np.float(y) for y in x])\n# t1 = np.array([np.array(x).mean() for x in t1_raw])\n# ds['t1'] = t1\n# ds['t2'] = t2 \n# # Minimum percent coverage\n# ds2 = ds[ds.pctCov > min_pctCov].copy()\n# ds2['RegO1'] = ds2.RGIId.astype(int)\n# # Glacier number and index for comparison\n# ds2['glacno'] = ((ds2['RGIId'] % 1) * 10**5).round(0).astype(int)\n# ds_list = ds2[['RegO1', 'glacno']]\n# ds2['RGIId'] = ds2['RegO1'] + ds2['glacno'] / 10**5\n# ds2.reset_index(drop=True, inplace=True)\n# ds2.drop(['RegO1', 'glacno'], axis=1, inplace=True)\n# ds2.to_csv(input.mauer_fp + input.mauer_fn.split('.csv')[0] + '_min' + str(min_pctCov) + 'pctCov.csv', index=False)\n# \n# # Pickle lists of glacier numbers for each region\n# import pickle\n# for reg in [13, 14, 15]:\n# ds_subset = ds_list[ds_list['RegO1'] == reg]\n# rgi_glacno_list = [str(x).rjust(5,'0') for x in ds_subset['glacno'].tolist()]\n# pickle_fn = 'R' + str(reg) + '_mauer_1970s_2000_rgi_glac_number.pkl'\n# print('Region ' + str(reg) + ' list:', rgi_glacno_list)\n# print(pickle_fn)\n## \n## with open(pickle_fn, 'wb') as f:\n## pickle.dump(rgi_glacno_list, f) \n \n #%%\n# import pickle\n# region = 15\n# \n# mauer_pickle_fn = 'R' + str(region) + '_mauer_1970s_2000_rgi_glac_number.pkl'\n# \n# with open(mauer_pickle_fn, 'rb') as f:\n# rgi_glac_number = pickle.load(f)\n# \n# # Select glaciers\n# main_glac_rgi = modelsetup.selectglaciersrgitable(rgi_regionsO1=[region], rgi_regionsO2 = 'all', \n# rgi_glac_number=rgi_glac_number)\n# # Glacier hypsometry [km**2], total area\n# main_glac_hyps = modelsetup.import_Husstable(main_glac_rgi, input.hyps_filepath, \n# input.hyps_filedict, input.hyps_colsdrop)\n# # Determine dates_table_idx that coincides with data\n# dates_table = modelsetup.datesmodelrun(1970, 2017, spinupyears=0)\n# \n# \n# # Select mass balance data\n# mb1 = MBData(name='mauer')\n# ds_mb = mb1.retrieve_mb(main_glac_rgi, main_glac_hyps, dates_table)" ]
[ [ "pandas.concat", "pandas.read_csv", "numpy.isnan", "numpy.tile", "pandas.DataFrame", "numpy.round" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
nhm-usgs/bmi-test-projects
[ "9ed065f291f0b33be9a9faeb0a02b3a253f36e9e" ]
[ "src/prms6bmi/prms6bmi/reader.py" ]
[ "\"\"\"\nCreated on Thu Dec 12 08:00:48 2019\n\n@author:rmcd build on pangeo package by Steve Markstrom - USGS\n\"\"\"\n\nimport xarray as xr\nimport glob\nimport os\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\ndef get_DataSet_prms6(summary, myparam):\n # merge spatial locations of hru and segments into summary file\n ds = xr.open_dataset(summary)\n param = xr.open_dataset(myparam)\n hru_lat = param.get(\"hru_lat\")\n ds['hru_lat'] = hru_lat\n hru_lon = param.get(\"hru_lon\")\n ds['hru_lon'] = hru_lon\n seg_lat = param.get(\"seg_lat\")\n ds['seg_lat'] = seg_lat\n seg_lon = param.get(\"seg_lon\")\n ds['seg_lon'] = seg_lon\n return ds\n\n\ndef bmi_prms6_value_splot(gdf, mbmi, value, tvmin, tvmax, index, timesel, pax = None):\n tax = pax or plt.gca()\n gdf[value] = mbmi.get_value(value)\n divider = make_axes_locatable(tax)\n tcax = divider.append_axes(position='right', size='5%', pad=0.1)\n gdf.plot(column=value, vmin=tvmin, vmax=tvmax, ax=tax, legend=True, cax=tcax)\n tax.set_title(value)\n\n\ndef plot_climate(c_xarray, hru_index, val, start, end, tax=None):\n tax = tax or plt.gca()\n hru_ids = c_xarray.hru.values\n simclimate = c_xarray.sel(time=slice(start, end))\n\n line, = simclimate.sel(hru=hru_ids[hru_index])[val].plot(ax=tax)\n tax.set_title(val)\n\ndef bmi_prms6_value_plot(data, n_index, val, label, start, end, tax = None):\n tax = tax or plt.gca()\n #test if val exists in both and get nhru or nsegment\n dim_type = None\n try:\n dim_type = data[val].dims[1]\n\n if dim_type == 'nhru':\n data_val = data[val].sel(nhru=n_index, time=slice(start, end)).to_pandas()\n # dprms_val = dprms[val].sel(nhru=n_index, time=slice(start, end))\n data_val.plot.line(ax=tax, label=label)\n tax.legend()\n # line1, = dprms_val.plot.line(x='time', ax=tax, add_legend=True)\n\n elif dim_type == 'nsegment':\n data_val = data[val].sel(nsegment=n_index, time=slice(start, end)).to_pandas()\n # dprms_val = dprms[val].sel(nsegment=n_index, time=slice(start, end)).to_pandas()\n\n data_val.plot(ax=tax, label=label)\n tax.legend()\n # line1, = dprms_val.plot(label='PRMS6')\n\n tax.set_title(f'{val} {n_index}')\n\n except Exception as err:\n print('Error', {err})\n\ndef bmi_prms6_residual_plot(dbmi, dprms, n_index, val, label, start, end, tax = None):\n tax = tax or plt.gca()\n dim_type = dbmi[val].dims[1]\n try:\n if dim_type == 'nhru':\n data_val = dbmi[val] - dprms[val]\n data = data_val.sel(nhru=n_index, time=slice(start, end)).to_pandas()\n # bmi = dbmi[val]\n # prms = dprms.sel(nhru=n_index, time=slice(start, end))[val]\n elif dim_type == 'nsegment':\n data_val = dbmi[val] - dprms[val]\n data = data_val.sel(nsegment=n_index, time=slice(start, end)).to_pandas()\n # bmi = dbmi.sel[val]\n # prms = dprms.sel(nsegment=n_index, time=slice(start, end))[val]\n # res = prms-bmi\n data.plot(ax=tax, label=label)\n plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)\n tax.legend()\n tax.set_title('Residual (prms-bmi)')\n except Exception as err:\n print('Error', {err})\n\ndef get_feat_coord(feat, data_set, feat_id):\n lat_da = data_set[feat + '_lat']\n lat = lat_da[feat_id-1].values\n lon_da = data_set[feat + '_lon']\n lon = lon_da[feat_id-1].values\n return lat,lon\n\n\ndef get_hrus_for_box(ds, lat_min, lat_max, lon_min, lon_max):\n sel = ds.hru_lat.sel(hruid=((ds.hru_lat.values >= lat_min)\n & (ds.hru_lat.values <= lat_max)))\n ids_1 = sel.hruid.values\n sel_1 = ds.hru_lon.sel(hruid=ids_1)\n sel_2 = sel_1.sel(hruid=((sel_1.values >= lon_min) & (sel_1.values <= lon_max)))\n ids_2 = sel_2.hruid.values\n return ids_2\n\n\ndef get_segs_for_box(ds, lat_min, lat_max, lon_min, lon_max):\n sel = ds.seg_lat.sel(segid=((ds.seg_lat.values >= lat_min)\n & (ds.seg_lat.values <= lat_max)))\n ids_1 = sel.segid.values\n sel_1 = ds.seg_lon.sel(segid=ids_1)\n sel_2 = sel_1.sel(segid=((sel_1.values >= lon_min) & (sel_1.values <= lon_max)))\n ids_2 = sel_2.segid.values\n return ids_2\n\n\ndef get_values_for_DOY(ds, timestamp, hru_ids, var_name):\n if (timestamp < pd.Timestamp('1979-10-01') or timestamp > pd.Timestamp('1980-09-30')):\n print(\"The date you provided is outside of range 1979-10-01 to 1980-09-30\")\n return None\n \n time_range = pd.date_range(timestamp, freq='1Y', periods=40)\n dif = timestamp - time_range[0]\n time_range = time_range + dif\n # print(time_range)\n\n date_list = []\n val_list = []\n for ts in time_range:\n try:\n date_str = str(ts.year).zfill(4) + '-' + str(ts.month).zfill(2) + '-' + str(ts.day).zfill(2)\n ds_sel = ds[var_name].sel(hruid=hru_ids, time=date_str)\n val = ds_sel.values[0][0]\n date_list.append(date_str + 'T05:00:00')\n val_list.append(val)\n except:\n pass\n \n val_np = np.asarray(val_list, dtype=np.float64)\n val_np = val_np.reshape((1, val_np.shape[0]))\n hru_ids_np = np.asarray(hru_ids, dtype=np.int32)\n date_np = np.asarray(date_list, dtype='datetime64[ns]')\n \n attrs = ds[var_name].attrs\n da_new = xr.DataArray(data=val_np, dims=['hruid','time'],\n coords={'hruid':hru_ids_np,'time':date_np},\n attrs=attrs)\n\n return da_new\n \n" ]
[ [ "numpy.asarray", "matplotlib.pyplot.gca", "pandas.Timestamp", "pandas.date_range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
kircher-sw/expenses-tracker
[ "afd9550616a79f54dd119d91cec209c7748e9689" ]
[ "expenses_report/visualizations/transaction_bubbles_visualization.py" ]
[ "import pandas as pd\nfrom plotly import graph_objects as go\n\nfrom expenses_report.chart_builder import ChartBuilder\nfrom expenses_report.config import config\nfrom expenses_report.preprocessing.data_provider import DataProvider\nfrom expenses_report.visualizations.i_visualization import IVisualization\n\n\nclass TransactionBubblesVisualization(IVisualization):\n _category_values = dict()\n\n def prepare_data(self, data: DataProvider):\n \"\"\"\n Preprocesses each transaction and calculates the relative amount within its category\n \"\"\"\n RATIO = 'ratio'\n df_all = data.get_all_transactions()\n for category_name in config.categories.keys():\n df_category = df_all[df_all[config.CATEGORY_MAIN_COL] == category_name]\n category_total = df_category[config.ABSAMOUNT_COL].sum()\n df_category.loc[:, RATIO] = df_category[config.ABSAMOUNT_COL] / category_total\n x_axis = list(map(lambda datetime: pd.Timestamp(datetime), pd.DatetimeIndex(df_category.index).values))\n if x_axis:\n self._category_values[category_name] = (x_axis,\n df_category[config.ABSAMOUNT_COL].values,\n df_category[RATIO].values,\n df_category[config.LABEL].values)\n\n\n def build_visualization(self) -> go.Figure:\n return ChartBuilder.create_bubble_chart(self._category_values)\n" ]
[ [ "pandas.Timestamp", "pandas.DatetimeIndex" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
aDecisionTree/HRNet_for_PolSAR_seg
[ "5243437ffa99ac4bce074d8f19bbdc1ec054f4b0" ]
[ "gaofenbisai_9436.py" ]
[ "# -*- coding: utf-8 -*-\nfrom PIL import Image,ImagePalette\nimport numpy as np\nimport yaml\n\nfrom skimage import io\nfrom torchvision import transforms\nimport os\nimport logging\n# import functools\n\nimport torch\nimport torch.nn as nn\n# import torch._utils\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport xml.dom.minidom as xml\nimport glob\nimport threading\n\n\"\"\"# label test\n[ 0, 15, 40, 45, 190, 220]\n\"\"\"\n\ndef writeDoc(filename_s,resultfile_s,path_s):\n origin_s = 'GF2/GF3'\n version_s = '4.0'\n provider_s = '中国海洋大学'\n author_s = '抹茶拿铁'\n pluginname_s = '地物标注'\n pluginclass_s = '标注'\n time_s = '2020-07-2020-11'\n doc = xml.Document()\n annotation = doc.createElement('annotation')\n source = doc.createElement('source')\n filename = doc.createElement('filename')\n origin = doc.createElement('origin')\n research = doc.createElement('research')\n version = doc.createElement('version')\n provider = doc.createElement('provider')\n author = doc.createElement('author')\n pluginname = doc.createElement('pluginname')\n pluginclass = doc.createElement('pluginclass')\n time = doc.createElement('time')\n segmentation = doc.createElement('segmentation')\n resultfile = doc.createElement('resultfile')\n filename.appendChild(doc.createTextNode(filename_s))\n origin.appendChild(doc.createTextNode(origin_s))\n version.appendChild(doc.createTextNode(version_s))\n provider.appendChild(doc.createTextNode(provider_s))\n author.appendChild(doc.createTextNode(author_s))\n pluginname.appendChild(doc.createTextNode(pluginname_s))\n pluginclass.appendChild(doc.createTextNode(pluginclass_s))\n time.appendChild(doc.createTextNode(time_s))\n resultfile.appendChild(doc.createTextNode(resultfile_s))\n doc.appendChild(annotation)\n annotation.appendChild(source)\n annotation.appendChild(research)\n annotation.appendChild(segmentation)\n source.appendChild(filename)\n source.appendChild(origin)\n research.appendChild(version)\n research.appendChild(provider)\n research.appendChild(author)\n research.appendChild(pluginname)\n research.appendChild(pluginclass)\n research.appendChild(time)\n segmentation.appendChild(resultfile)\n with open(path_s, 'wb') as fp:\n fp.write(doc.toprettyxml(indent='\\t',newl='\\n',encoding='utf-8'))\n fp.close()\n\npalette = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 102, 0, 0, 153, 0, 0, 204, 0, 0, 255, 0, 0, 0, 51, 0, 51, 51, 0, 102, 51, 0, 153, 51, 0, 204, 51, 0, 255, 51, 0, 0, 102, 0, 51, 102, 0, 102, 102, 0, 153, 102, 0, 204, 102, 0, 255, 102, 0, 0, 153, 0, 51, 153, 0, 102, 153, 0, 153, 153, 0, 204, 153, 0, 255, 153, 0, 0, 204, 0, 51, 204, 0, 102, 204, 0, 153, 204, 0, 204, 204, 0, 255, 204, 0, 0, 255, 0, 51, 255, 0, 102, 255, 0, 153, 255, 0, 204, 255, 0, 255, 255, 0, 0, 0, 51, 51, 0, 51, 102, 0, 51, 153, 0, 51, 204, 0, 51, 255, 0, 51, 0, 51, 51, 51, 51, 51, 102, 51, 51, 153, 51, 51, 204, 51, 51, 255, 51, 51, 0, 102, 51, 51, 102, 51, 102, 102, 51, 153, 102, 51, 204, 102, 51, 255, 102, 51, 0, 153, 51, 51, 153, 51, 102, 153, 51, 153, 153, 51, 204, 153, 51, 255, 153, 51, 0, 204, 51, 51, 204, 51, 102, 204, 51, 153, 204, 51, 204, 204, 51, 255, 204, 51, 0, 255, 51, 51, 255, 51, 102, 255, 51, 153, 255, 51, 204, 255, 51, 255, 255, 51, 0, 0, 102, 51, 0, 102, 102, 0, 102, 153, 0, 102, 204, 0, 102, 255, 0, 102, 0, 51, 102, 51, 51, 102, 102, 51, 102, 153, 51, 102, 204, 51, 102, 255, 51, 102, 0, 102, 102, 51, 102, 102, 102, 102, 102, 153, 102, 102, 204, 102, 102, 255, 102, 102, 0, 153, 102, 51, 153, 102, 102, 153, 102, 153, 153, 102, 204, 153, 102, 255, 153, 102, 0, 204, 102, 51, 204, 102, 102, 204, 102, 153, 204, 102, 204, 204, 102, 255, 204, 102, 0, 255, 102, 51, 255, 102, 102, 255, 102, 153, 255, 102, 204, 255, 102, 255, 255, 102, 0, 0, 153, 51, 0, 153, 102, 0, 153, 153, 0, 153, 204, 0, 153, 255, 0, 153, 0, 51, 153, 51, 51, 153, 102, 51, 153, 153, 51, 153, 204, 51, 153, 255, 51, 153, 0, 102, 153, 51, 102, 153, 102, 102, 153, 153, 102, 153, 204, 102, 153, 255, 102, 153, 0, 153, 153, 51, 153, 153, 102, 153, 153, 153, 153, 153, 204, 153, 153, 255, 153, 153, 0, 204, 153, 51, 204, 153, 102, 204, 153, 153, 204, 153, 204, 204, 153, 255, 204, 153, 0, 255, 153, 51, 255, 153, 102, 255, 153, 153, 255, 153, 204, 255, 153, 255, 255, 153, 0, 0, 204, 51, 0, 204, 102, 0, 204, 153, 0, 204, 204, 0, 204, 255, 0, 204, 0, 51, 204, 51, 51, 204, 102, 51, 204, 153, 51, 204, 204, 51, 204, 255, 51, 204, 0, 102, 204, 51, 102, 204, 102, 102, 204, 153, 102, 204, 204, 102, 204, 255, 102, 204, 0, 153, 204, 51, 153, 204, 102, 153, 204, 153, 153, 204, 204, 153, 204, 255, 153, 204, 0, 204, 204, 51, 204, 204, 102, 204, 204, 153, 204, 204, 204, 204, 204, 255, 204, 204, 0, 255, 204, 51, 255, 204, 102, 255, 204, 153, 255, 204, 204, 255, 204, 255, 255, 204, 0, 0, 255, 51, 0, 255, 102, 0, 255, 153, 0, 255, 204, 0, 255, 255, 0, 255, 0, 51, 255, 51, 51, 255, 102, 51, 255, 153, 51, 255, 204, 51, 255, 255, 51, 255, 0, 102, 255, 51, 102, 255, 102, 102, 255, 153, 102, 255, 204, 102, 255, 255, 102, 255, 0, 153, 255, 51, 153, 255, 102, 153, 255, 153, 153, 255, 204, 153, 255, 255, 153, 255, 0, 204, 255, 51, 204, 255, 102, 204, 255, 153, 204, 255, 204, 204, 255, 255, 204, 255, 0, 255, 255, 51, 255, 255, 102, 255, 255, 153, 255, 255, 204, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nmapping = [0, 15, 40, 45, 190, 220, 225]\n\ndef labels_encode(gt):\n # return labels map encoded from P mode image\n res = np.zeros_like(gt)\n for idx, label in enumerate(mapping):\n res[gt == label] = idx\n return res\n\ndef labels_decode(output):\n # return P mode image from labels map\n res = np.zeros_like(output)\n for i in range(7):\n res[output==i]=mapping[i]\n return res\ndef labels2RGB(labels):\n # return RGB image converted from labels\n img = Image.fromarray(labels.astype('uint8'))\n img.putpalette(palette)\n return img.convert('RGB')\n\n\n\n\n\"\"\"# Dataset\"\"\"\n\n\n\n# 1024\n# [array([134.35576, 181.84496, 179.46925, 141.47711], dtype=float32)] [array([142.3712 , 167.54785, 165.98781, 139.46089], dtype=float32)]\n# transform = transforms.Compose([\n# transforms.Normalize(mean=[134.35576, 181.84496, 179.46925, 141.47711],std=[142.3712 , 167.54785, 165.98781, 139.46089]),\n# ])\n\n# 768\n# transform = transforms.Compose([\n# transforms.Normalize(mean=[132.03269, 178.74885, 176.47111, 139.48150],std=[129.54710, 154.04905, 152.75477, 128.39875]),\n# ])\n\n# 512\ntransform = transforms.Compose([\n transforms.Normalize(mean=[127.40368, 171.65473, 169.60202, 135.26735],std=[110.52666, 132.01543, 131.15236, 111.38657]),\n])\n\nclass TestDSA(torch.utils.data.Dataset):\n \n def __init__(self):\n # files = os.listdir('/input_path')\n # newfiles = [data for data in files if re.match('.*tiff', data)]\n # self.len = newfiles.__len__()//4\n self.files = glob.glob('/input_path/test_A/*.tiff')\n self.len = self.files.__len__()//4\n\n\n \n def __getitem__(self, index):\n index = index+1\n data_dir = '/input_path/test_A/'\n HH_dir = data_dir + str(index) + '_HH.tiff'\n HV_dir = data_dir + str(index) + '_HV.tiff'\n VH_dir = data_dir + str(index) + '_VH.tiff'\n VV_dir = data_dir + str(index) + '_VV.tiff'\n # gt_dir = data_dir + str(index) + '_gt.png'\n img_HH = io.imread(HH_dir)\n mask = img_HH == 0\n img_HH = torch.from_numpy(img_HH.astype('float32')).unsqueeze(0)\n img_HV = torch.from_numpy(io.imread(HV_dir).astype('float32')).unsqueeze(0)\n img_VH = torch.from_numpy(io.imread(VH_dir).astype('float32')).unsqueeze(0)\n img_VV = torch.from_numpy(io.imread(VV_dir).astype('float32')).unsqueeze(0)\n # gt = np.array(Image.open(gt_dir).convert('P'))\n # gt = labels_encode(gt)\n # gt = torch.from_numpy(gt)\n img = torch.cat((img_HH, img_HV, img_VH, img_VV), 0)\n img[img>512]=512\n img = transform(img)\n return img,str(index),mask\n def __len__(self): \n return self.len\n\nclass TestDSB(torch.utils.data.Dataset):\n \n def __init__(self):\n # files = os.listdir('/input_path')\n # newfiles = [data for data in files if re.match('.*tiff', data)]\n # self.len = newfiles.__len__()//4\n self.files = glob.glob('/input_path/test_B/*.tiff')\n self.len = self.files.__len__()//4\n\n\n \n def __getitem__(self, index):\n index = index+1\n data_dir = '/input_path/test_B/'\n HH_dir = data_dir + str(index) + '_HH.tiff'\n HV_dir = data_dir + str(index) + '_HV.tiff'\n VH_dir = data_dir + str(index) + '_VH.tiff'\n VV_dir = data_dir + str(index) + '_VV.tiff'\n # gt_dir = data_dir + str(index) + '_gt.png'\n img_HH = io.imread(HH_dir)\n mask = img_HH == 0\n img_HH = torch.from_numpy(img_HH.astype('float32')).unsqueeze(0)\n img_HV = torch.from_numpy(io.imread(HV_dir).astype('float32')).unsqueeze(0)\n img_VH = torch.from_numpy(io.imread(VH_dir).astype('float32')).unsqueeze(0)\n img_VV = torch.from_numpy(io.imread(VV_dir).astype('float32')).unsqueeze(0)\n # gt = np.array(Image.open(gt_dir).convert('P'))\n # gt = labels_encode(gt)\n # gt = torch.from_numpy(gt)\n img = torch.cat((img_HH, img_HV, img_VH, img_VV), 0)\n img[img>512]=512\n img = transform(img)\n return img,str(index),mask\n def __len__(self): \n return self.len\n\nte_dsA = TestDSA()\ntest_loaderA = torch.utils.data.DataLoader(dataset=te_dsA, batch_size=8, shuffle=False, num_workers=2)\nte_dsB = TestDSB()\ntest_loaderB = torch.utils.data.DataLoader(dataset=te_dsB, batch_size=8, shuffle=False, num_workers=2)\n\n# class TestDS(torch.utils.data.Dataset):\n \n# def __init__(self):\n# # files = os.listdir('/input_path')\n# # newfiles = [data for data in files if re.match('.*tiff', data)]\n# # self.len = newfiles.__len__()//4\n# self.files = glob.glob('/input_path/*.tiff')\n# self.len = self.files.__len__()//4\n\n\n \n# def __getitem__(self, index):\n# index = index+1\n# data_dir = '/input_path/'\n# HH_dir = data_dir + str(index) + '_HH.tiff'\n# HV_dir = data_dir + str(index) + '_HV.tiff'\n# VH_dir = data_dir + str(index) + '_VH.tiff'\n# VV_dir = data_dir + str(index) + '_VV.tiff'\n# # gt_dir = data_dir + str(index) + '_gt.png'\n# img_HH = io.imread(HH_dir)\n# mask = img_HH == 0\n# img_HH = torch.from_numpy(img_HH.astype('float32')).unsqueeze(0)\n# img_HV = torch.from_numpy(io.imread(HV_dir).astype('float32')).unsqueeze(0)\n# img_VH = torch.from_numpy(io.imread(VH_dir).astype('float32')).unsqueeze(0)\n# img_VV = torch.from_numpy(io.imread(VV_dir).astype('float32')).unsqueeze(0)\n# # gt = np.array(Image.open(gt_dir).convert('P'))\n# # gt = labels_encode(gt)\n# # gt = torch.from_numpy(gt)\n# img = torch.cat((img_HH, img_HV, img_VH, img_VV), 0)\n# img[img>512]=512\n# img = transform(img)\n# return img,str(index),mask\n# def __len__(self): \n# return self.len\n\n# te_ds = TestDS()\n# test_loader = torch.utils.data.DataLoader(dataset=te_ds, batch_size=4, shuffle=False, num_workers=1)\n\n\"\"\"# read config\"\"\"\n\n\n\nstream = open('/workspace/code/ocr_cfg.yaml', 'r')\ncfg = yaml.load(stream, Loader=yaml.FullLoader)\n\n\"\"\"# Build model\"\"\"\n\n\n\n\n\nBN_MOMENTUM = 0.1\nALIGN_CORNERS = True\nrelu_inplace = True\n\nlogger = logging.getLogger(__name__)\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\ndef BNReLU(num_features, bn_type=None, **kwargs):\n return nn.Sequential(\n nn.BatchNorm2d(num_features, **kwargs),\n nn.ReLU()\n )\nclass SpatialGather_Module(nn.Module):\n \"\"\"\n Aggregate the context features according to the initial \n predicted probability distribution.\n Employ the soft-weighted method to aggregate the context.\n \"\"\"\n def __init__(self, cls_num=0, scale=1):\n super(SpatialGather_Module, self).__init__()\n self.cls_num = cls_num\n self.scale = scale\n\n def forward(self, feats, probs):\n batch_size, c, h, w = probs.size(0), probs.size(1), probs.size(2), probs.size(3)\n probs = probs.view(batch_size, c, -1)\n feats = feats.view(batch_size, feats.size(1), -1)\n feats = feats.permute(0, 2, 1) # batch x hw x c \n probs = F.softmax(self.scale * probs, dim=2)# batch x k x hw\n ocr_context = torch.matmul(probs, feats)\\\n .permute(0, 2, 1).unsqueeze(3)# batch x k x c\n return ocr_context\n\n\nclass _ObjectAttentionBlock(nn.Module):\n '''\n The basic implementation for object context block\n Input:\n N X C X H X W\n Parameters:\n in_channels : the dimension of the input feature map\n key_channels : the dimension after the key/query transform\n scale : choose the scale to downsample the input feature maps (save memory cost)\n bn_type : specify the bn type\n Return:\n N X C X H X W\n '''\n def __init__(self, \n in_channels, \n key_channels, \n scale=1, \n bn_type=None):\n super(_ObjectAttentionBlock, self).__init__()\n self.scale = scale\n self.in_channels = in_channels\n self.key_channels = key_channels\n self.pool = nn.MaxPool2d(kernel_size=(scale, scale))\n self.f_pixel = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.key_channels, bn_type=bn_type),\n nn.Conv2d(in_channels=self.key_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.key_channels, bn_type=bn_type),\n )\n self.f_object = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.key_channels, bn_type=bn_type),\n nn.Conv2d(in_channels=self.key_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.key_channels, bn_type=bn_type),\n )\n self.f_down = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.key_channels, bn_type=bn_type),\n )\n self.f_up = nn.Sequential(\n nn.Conv2d(in_channels=self.key_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0, bias=False),\n BNReLU(self.in_channels, bn_type=bn_type),\n )\n\n def forward(self, x, proxy):\n batch_size, h, w = x.size(0), x.size(2), x.size(3)\n if self.scale > 1:\n x = self.pool(x)\n\n query = self.f_pixel(x).view(batch_size, self.key_channels, -1)\n query = query.permute(0, 2, 1)\n key = self.f_object(proxy).view(batch_size, self.key_channels, -1)\n value = self.f_down(proxy).view(batch_size, self.key_channels, -1)\n value = value.permute(0, 2, 1)\n\n sim_map = torch.matmul(query, key)\n sim_map = (self.key_channels**-.5) * sim_map\n sim_map = F.softmax(sim_map, dim=-1) \n\n # add bg context ...\n context = torch.matmul(sim_map, value)\n context = context.permute(0, 2, 1).contiguous()\n context = context.view(batch_size, self.key_channels, *x.size()[2:])\n context = self.f_up(context)\n if self.scale > 1:\n context = F.interpolate(input=context, size=(h, w), mode='bilinear', align_corners=ALIGN_CORNERS)\n\n return context\n\nclass ObjectAttentionBlock2D(_ObjectAttentionBlock):\n def __init__(self, in_channels, key_channels, scale=1, bn_type=None):\n super(ObjectAttentionBlock2D, self).__init__(in_channels,key_channels,scale, bn_type=bn_type)\n\nclass SpatialOCR_Module(nn.Module):\n \"\"\"\n Implementation of the OCR module:\n We aggregate the global object representation to update the representation for each pixel.\n \"\"\"\n def __init__(self, in_channels, key_channels, out_channels, scale=1, dropout=0.1, bn_type=None):\n super(SpatialOCR_Module, self).__init__()\n self.object_context_block = ObjectAttentionBlock2D(in_channels, key_channels, scale, bn_type)\n _in_channels = 2 * in_channels\n\n self.conv_bn_dropout = nn.Sequential(\n nn.Conv2d(_in_channels, out_channels, kernel_size=1, padding=0, bias=False),\n BNReLU(out_channels, bn_type=bn_type),\n nn.Dropout2d(dropout)\n )\n\n def forward(self, feats, proxy_feats):\n context = self.object_context_block(feats, proxy_feats)\n\n output = self.conv_bn_dropout(torch.cat([context, feats], 1))\n\n return output\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=relu_inplace)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out = out + residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,\n bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion,\n momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=relu_inplace)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out = out + residual\n out = self.relu(out)\n\n return out\n\n\nclass HighResolutionModule(nn.Module):\n def __init__(self, num_branches, blocks, num_blocks, num_inchannels,\n num_channels, fuse_method, multi_scale_output=True):\n super(HighResolutionModule, self).__init__()\n self._check_branches(\n num_branches, blocks, num_blocks, num_inchannels, num_channels)\n\n self.num_inchannels = num_inchannels\n self.fuse_method = fuse_method\n self.num_branches = num_branches\n\n self.multi_scale_output = multi_scale_output\n\n self.branches = self._make_branches(\n num_branches, blocks, num_blocks, num_channels)\n self.fuse_layers = self._make_fuse_layers()\n self.relu = nn.ReLU(inplace=relu_inplace)\n\n def _check_branches(self, num_branches, blocks, num_blocks,\n num_inchannels, num_channels):\n if num_branches != len(num_blocks):\n error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(\n num_branches, len(num_blocks))\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n if num_branches != len(num_channels):\n error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(\n num_branches, len(num_channels))\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n if num_branches != len(num_inchannels):\n error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(\n num_branches, len(num_inchannels))\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n def _make_one_branch(self, branch_index, block, num_blocks, num_channels,\n stride=1):\n downsample = None\n if stride != 1 or \\\n self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.num_inchannels[branch_index],\n num_channels[branch_index] * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(num_channels[branch_index] * block.expansion,\n momentum=BN_MOMENTUM),\n )\n\n layers = []\n layers.append(block(self.num_inchannels[branch_index],\n num_channels[branch_index], stride, downsample))\n self.num_inchannels[branch_index] = \\\n num_channels[branch_index] * block.expansion\n for i in range(1, num_blocks[branch_index]):\n layers.append(block(self.num_inchannels[branch_index],\n num_channels[branch_index]))\n\n return nn.Sequential(*layers)\n\n def _make_branches(self, num_branches, block, num_blocks, num_channels):\n branches = []\n\n for i in range(num_branches):\n branches.append(\n self._make_one_branch(i, block, num_blocks, num_channels))\n\n return nn.ModuleList(branches)\n\n def _make_fuse_layers(self):\n if self.num_branches == 1:\n return None\n\n num_branches = self.num_branches\n num_inchannels = self.num_inchannels\n fuse_layers = []\n for i in range(num_branches if self.multi_scale_output else 1):\n fuse_layer = []\n for j in range(num_branches):\n if j > i:\n fuse_layer.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j],\n num_inchannels[i],\n 1,\n 1,\n 0,\n bias=False),\n nn.BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM)))\n elif j == i:\n fuse_layer.append(None)\n else:\n conv3x3s = []\n for k in range(i-j):\n if k == i - j - 1:\n num_outchannels_conv3x3 = num_inchannels[i]\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j],\n num_outchannels_conv3x3,\n 3, 2, 1, bias=False),\n nn.BatchNorm2d(num_outchannels_conv3x3, \n momentum=BN_MOMENTUM)))\n else:\n num_outchannels_conv3x3 = num_inchannels[j]\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j],\n num_outchannels_conv3x3,\n 3, 2, 1, bias=False),\n nn.BatchNorm2d(num_outchannels_conv3x3,\n momentum=BN_MOMENTUM),\n nn.ReLU(inplace=relu_inplace)))\n fuse_layer.append(nn.Sequential(*conv3x3s))\n fuse_layers.append(nn.ModuleList(fuse_layer))\n\n return nn.ModuleList(fuse_layers)\n\n def get_num_inchannels(self):\n return self.num_inchannels\n\n def forward(self, x):\n if self.num_branches == 1:\n return [self.branches[0](x[0])]\n\n for i in range(self.num_branches):\n x[i] = self.branches[i](x[i])\n\n x_fuse = []\n for i in range(len(self.fuse_layers)):\n y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])\n for j in range(1, self.num_branches):\n if i == j:\n y = y + x[j]\n elif j > i:\n width_output = x[i].shape[-1]\n height_output = x[i].shape[-2]\n y = y + F.interpolate(\n self.fuse_layers[i][j](x[j]),\n size=[height_output, width_output],\n mode='bilinear', align_corners=ALIGN_CORNERS)\n else:\n y = y + self.fuse_layers[i][j](x[j])\n x_fuse.append(self.relu(y))\n\n return x_fuse\n\n\nblocks_dict = {\n 'BASIC': BasicBlock,\n 'BOTTLENECK': Bottleneck\n}\n\n\nclass HighResolutionNet(nn.Module):\n\n def __init__(self, config, **kwargs):\n global ALIGN_CORNERS\n extra = cfg['MODEL']['EXTRA']\n super(HighResolutionNet, self).__init__()\n ALIGN_CORNERS = cfg['MODEL']['ALIGN_CORNERS']\n\n # stem net\n self.conv1 = nn.Conv2d(4, 64, kernel_size=3, stride=2, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1,\n bias=False)\n self.bn2 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=relu_inplace)\n\n self.stage1_cfg = extra['STAGE1']\n num_channels = self.stage1_cfg['NUM_CHANNELS'][0]\n block = blocks_dict[self.stage1_cfg['BLOCK']]\n num_blocks = self.stage1_cfg['NUM_BLOCKS'][0]\n self.layer1 = self._make_layer(block, 64, num_channels, num_blocks)\n stage1_out_channel = block.expansion*num_channels\n\n self.stage2_cfg = extra['STAGE2']\n num_channels = self.stage2_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage2_cfg['BLOCK']]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition1 = self._make_transition_layer(\n [stage1_out_channel], num_channels)\n self.stage2, pre_stage_channels = self._make_stage(\n self.stage2_cfg, num_channels)\n\n self.stage3_cfg = extra['STAGE3']\n num_channels = self.stage3_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage3_cfg['BLOCK']]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition2 = self._make_transition_layer(\n pre_stage_channels, num_channels)\n self.stage3, pre_stage_channels = self._make_stage(\n self.stage3_cfg, num_channels)\n\n self.stage4_cfg = extra['STAGE4']\n num_channels = self.stage4_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage4_cfg['BLOCK']]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition3 = self._make_transition_layer(\n pre_stage_channels, num_channels)\n self.stage4, pre_stage_channels = self._make_stage(\n self.stage4_cfg, num_channels, multi_scale_output=True)\n \n last_inp_channels = np.int(np.sum(pre_stage_channels))\n\n ocr_mid_channels = cfg['MODEL']['OCR']['MID_CHANNELS']\n ocr_key_channels = cfg['MODEL']['OCR']['KEY_CHANNELS']\n\n self.conv3x3_ocr = nn.Sequential(\n nn.Conv2d(last_inp_channels, ocr_mid_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(ocr_mid_channels),\n nn.ReLU(inplace=relu_inplace),\n )\n self.ocr_gather_head = SpatialGather_Module(cfg['DATASET']['NUM_CLASSES'])\n\n self.ocr_distri_head = SpatialOCR_Module(in_channels=ocr_mid_channels,\n key_channels=ocr_key_channels,\n out_channels=ocr_mid_channels,\n scale=1,\n dropout=0.05,\n )\n self.cls_head = nn.Conv2d(\n ocr_mid_channels, cfg['DATASET']['NUM_CLASSES'], kernel_size=1, stride=1, padding=0, bias=True)\n\n self.aux_head = nn.Sequential(\n nn.Conv2d(last_inp_channels, last_inp_channels,\n kernel_size=1, stride=1, padding=0),\n nn.BatchNorm2d(last_inp_channels),\n nn.ReLU(inplace=relu_inplace),\n nn.Conv2d(last_inp_channels, cfg['DATASET']['NUM_CLASSES'], \n kernel_size=1, stride=1, padding=0, bias=True)\n )\n\n def _make_transition_layer(\n self, num_channels_pre_layer, num_channels_cur_layer):\n num_branches_cur = len(num_channels_cur_layer)\n num_branches_pre = len(num_channels_pre_layer)\n\n transition_layers = []\n for i in range(num_branches_cur):\n if i < num_branches_pre:\n if num_channels_cur_layer[i] != num_channels_pre_layer[i]:\n transition_layers.append(nn.Sequential(\n nn.Conv2d(num_channels_pre_layer[i],\n num_channels_cur_layer[i],\n 3,\n 1,\n 1,\n bias=False),\n nn.BatchNorm2d(\n num_channels_cur_layer[i], momentum=BN_MOMENTUM),\n nn.ReLU(inplace=relu_inplace)))\n else:\n transition_layers.append(None)\n else:\n conv3x3s = []\n for j in range(i+1-num_branches_pre):\n inchannels = num_channels_pre_layer[-1]\n outchannels = num_channels_cur_layer[i] \\\n if j == i-num_branches_pre else inchannels\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(\n inchannels, outchannels, 3, 2, 1, bias=False),\n nn.BatchNorm2d(outchannels, momentum=BN_MOMENTUM),\n nn.ReLU(inplace=relu_inplace)))\n transition_layers.append(nn.Sequential(*conv3x3s))\n\n return nn.ModuleList(transition_layers)\n\n def _make_layer(self, block, inplanes, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample))\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _make_stage(self, layer_config, num_inchannels,\n multi_scale_output=True):\n num_modules = layer_config['NUM_MODULES']\n num_branches = layer_config['NUM_BRANCHES']\n num_blocks = layer_config['NUM_BLOCKS']\n num_channels = layer_config['NUM_CHANNELS']\n block = blocks_dict[layer_config['BLOCK']]\n fuse_method = layer_config['FUSE_METHOD']\n\n modules = []\n for i in range(num_modules):\n # multi_scale_output is only used last module\n if not multi_scale_output and i == num_modules - 1:\n reset_multi_scale_output = False\n else:\n reset_multi_scale_output = True\n modules.append(\n HighResolutionModule(num_branches,\n block,\n num_blocks,\n num_inchannels,\n num_channels,\n fuse_method,\n reset_multi_scale_output)\n )\n num_inchannels = modules[-1].get_num_inchannels()\n\n return nn.Sequential(*modules), num_inchannels\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n x = self.layer1(x)\n\n x_list = []\n for i in range(self.stage2_cfg['NUM_BRANCHES']):\n if self.transition1[i] is not None:\n x_list.append(self.transition1[i](x))\n else:\n x_list.append(x)\n y_list = self.stage2(x_list)\n\n x_list = []\n for i in range(self.stage3_cfg['NUM_BRANCHES']):\n if self.transition2[i] is not None:\n if i < self.stage2_cfg['NUM_BRANCHES']:\n x_list.append(self.transition2[i](y_list[i]))\n else:\n x_list.append(self.transition2[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n y_list = self.stage3(x_list)\n\n x_list = []\n for i in range(self.stage4_cfg['NUM_BRANCHES']):\n if self.transition3[i] is not None:\n if i < self.stage3_cfg['NUM_BRANCHES']:\n x_list.append(self.transition3[i](y_list[i]))\n else:\n x_list.append(self.transition3[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n x = self.stage4(x_list)\n\n # Upsampling\n x0_h, x0_w = x[0].size(2), x[0].size(3)\n x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n # print(x1.shape)\n # print(x2.shape)\n # print(x3.shape)\n feats = torch.cat([x[0], x1, x2, x3], 1)\n # print(x.shape)\n out_aux_seg = []\n\n # ocr\n out_aux = self.aux_head(feats)\n # compute contrast feature\n feats = self.conv3x3_ocr(feats)\n\n context = self.ocr_gather_head(feats, out_aux)\n feats = self.ocr_distri_head(feats, context)\n\n out = self.cls_head(feats)\n\n out_aux_seg.append(out_aux)\n out_aux_seg.append(out)\n\n return out_aux_seg\n\n def init_weights(self, pretrained='',):\n \n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.001)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n if os.path.isfile(pretrained):\n pretrained_dict = torch.load(pretrained)\n \n model_dict = self.state_dict() \n pretrained_dict = {k: v for k, v in pretrained_dict.items()\n if k in model_dict.keys()}\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n\ndef get_seg_model(cfg, **kwargs):\n model = HighResolutionNet(cfg, **kwargs)\n model.init_weights(cfg['MODEL']['PRETRAINED'])\n\n return model\nmodel = get_seg_model(cfg).cuda()\n\n\"\"\"# Load model\"\"\"\ncheckpoint = torch.load('/workspace/code/c_9436_512.pth')\n# checkpoint = torch.load('/workspace/code/c_9436_512.pth',map_location=torch.device('cpu'))\nmodel.load_state_dict(checkpoint['state_dict'])\n\n\n\n\"\"\"# Test model\"\"\"\n# def write_res(output,mask,name):\n# output[mask]=0\n# save_img=labels_decode(output)\n# save_img = Image.fromarray(save_img)\n# save_img.putpalette(palette)\n# save_img = save_img.convert('RGB')\n# save_img.save('/output_path/'+name+'_gt.png')\n# writeDoc(name+'_HH.tiff', name+'_gt.png', '/output_path/'+name+'.xml')\n\ndef write_resA(output,mask,name):\n output[mask]=0\n save_img=labels_decode(output)\n save_img = Image.fromarray(save_img)\n save_img.putpalette(palette)\n save_img = save_img.convert('RGB')\n save_img.save('/output_path/test_A/'+name+'_gt.png')\n writeDoc(name+'_HH.tiff', name+'_gt.png', '/output_path/test_A/'+name+'.xml')\ndef write_resB(output,mask,name):\n output[mask]=0\n save_img=labels_decode(output)\n save_img = Image.fromarray(save_img)\n save_img.putpalette(palette)\n save_img = save_img.convert('RGB')\n save_img.save('/output_path/test_B/'+name+'_gt.png')\n writeDoc(name+'_HH.tiff', name+'_gt.png', '/output_path/test_B/'+name+'.xml')\nwith torch.no_grad():\n model.eval()\n for img ,name,mask in test_loaderA:\n img = img.cuda()\n output = model(img)\n output = F.interpolate(input = output[1], size = (512, 512), mode = 'bilinear', align_corners=True)\n output = output.detach_().cpu()\n output = np.asarray(np.argmax(output, axis=1), dtype=np.uint8)\n for i in range(output.shape[0]):\n threading.Thread(target = write_resA,args=(output[i],mask[i],name[i])).start()\n # threading.Thread(target = write_res,args=(output[0],mask[0],name[0])).start()\n # threading.Thread(target = write_res,args=(output[1],mask[1],name[1])).start()\n # threading.Thread(target = write_res,args=(output[2],mask[2],name[2])).start()\n # threading.Thread(target = write_res,args=(output[3],mask[3],name[3])).start()\n for img ,name,mask in test_loaderB:\n img = img.cuda()\n output = model(img)\n output = F.interpolate(input = output[1], size = (512, 512), mode = 'bilinear', align_corners=True)\n output = output.detach_().cpu()\n output = np.asarray(np.argmax(output, axis=1), dtype=np.uint8)\n for i in range(output.shape[0]):\n threading.Thread(target = write_resB,args=(output[i],mask[i],name[i])).start()\n # threading.Thread(target = write_res,args=(output[0],mask[0],name[0])).start()\n # threading.Thread(target = write_res,args=(output[1],mask[1],name[1])).start()\n # threading.Thread(target = write_res,args=(output[2],mask[2],name[2])).start()\n # threading.Thread(target = write_res,args=(output[3],mask[3],name[3])).start()\n\n # for i in range(output.shape[0]):\n # output[i][mask[i]]=0\n # save_img=labels_decode(output[i])\n # save_img = Image.fromarray(save_img)\n # save_img.putpalette(palette)\n # save_img = save_img.convert('RGB')\n # save_img.save('/output_path/'+name[i]+'_gt.png')\n # writeDoc(name[i]+'_HH.tiff', name[i]+'_gt.png', '/output_path/'+name[i]+'.xml')\n\n\n\n\n\n" ]
[ [ "torch.nn.functional.softmax", "torch.nn.Dropout2d", "torch.load", "torch.cat", "torch.utils.data.DataLoader", "torch.no_grad", "numpy.zeros_like", "torch.nn.functional.interpolate", "numpy.argmax", "torch.nn.Sequential", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.init.normal_", "torch.nn.BatchNorm2d", "numpy.sum", "torch.nn.MaxPool2d", "torch.matmul", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
maneeshdisodia/pythonic_examples
[ "f722bfbe253bbcead111ba082550bdfd1c6046d3" ]
[ "multi_thread.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom threading import Thread\nfrom multiprocessing import Queue\n\ndf = pd.DataFrame(data=np.random.rand(100).reshape(10, 10))\n\nprint(df.head())\nrows = df.index\ncolumn = df.columns\n\nque = Queue()\n\n\n# long run\ndef long_run(row, col, pv):\n for r in row:\n for c in col:\n pv.at[r, c] = 1\n que.put(pv)\n return\n\n\nthreads = []\n\n\ndef thread_run(n, df):\n np_r = np.array_split(rows, n)\n for i in range(n):\n print(i)\n print('min =' + str(np_r[i].min()) + ' max = ' + str(np_r[i].max()))\n print()\n t = Thread(target=long_run,\n args=(rows[np_r[i].min():np_r[i].max()], column[:], df[np_r[i].min():np_r[i].max()]))\n threads.append(t)\n t.start()\n\n\nif __name__ == '__main__':\n thread_run(4, df)\n lst = []\n mydf = pd.DataFrame()\n while not que.empty():\n result = que.get()\n print('thread 1:::::>>>>>>>>')\n print(result)\n lst.append(result)\n\n print(lst)\n # for i in lst:\n # mydf = pd.concat([mydf,i], axis=1)\n # mydf.head()\n\n# from multiprocessing.pool import ThreadPool\n#\n#\n# def foo(bar, baz):\n# print('hello {0}'.format(bar))\n# return 'foo' + baz\n#\n#\n# pool = ThreadPool(processes=5)\n#\n# async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo\n#\n# # do some other stuff in the main process\n#\n# return_val = async_result.get() # get the return value from your function.\n" ]
[ [ "numpy.array_split", "numpy.random.rand", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
TapirLab/pdf-watermarkin
[ "f4e07f068ebb17e36fa2c8065f432ebd0d92a804" ]
[ "pdf_operations.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nThis program includes functions to add watermark to A4 PDFs. Also, miscellaneous\nfunctions are provided to harden OCR (Optical Character Recognition) process and\nmake encryption possible.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% A PDF Watermarking Script\n%% -------------------\n%% $Author: Halil Said Cankurtaran$,\n%% $Date: January 10th, 2020$,\n%% $Revision: 1.0$\n%% Tapir Lab.\n%% Copyright: Tapir Lab.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\"\"\"\n\nimport os\nimport glob\nfrom datetime import datetime\n\nimport cv2\nimport numpy as np\nimport pikepdf\n\nfrom pdf2image import convert_from_path\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import A4, landscape\nfrom PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger\n\n\ndef set_page(name, orientation):\n \"\"\"Create an empty A4 PDF page with `name` based on the `orientation`\"\"\"\n\n if orientation == 'landscape':\n empty_page = canvas.Canvas(name, pagesize=landscape(A4))\n else:\n empty_page = canvas.Canvas(name, pagesize=A4)\n\n return empty_page\n\n\ndef draw_image(canvas_, image, orientation):\n \"\"\"Draw given image by scaling to the size of canvas the in the correct orientation\n\n `canvas_` is the page created with `set_page` function. In case of need,\n reportlab.pdfgen.canvas can be used to create a custom canvas. However,\n since this function draws images after scaling to A4 paper dimensions, the\n drawn image may not be properly scaled to the size of a custom canvas.\n \"\"\"\n\n if orientation == 'landscape':\n canvas_.drawImage(image, 0, 0, width=A4[1], height=A4[0])\n else:\n canvas_.drawImage(image, 0, 0, width=A4[0], height=A4[1])\n\n\ndef blur_image(page, kernel=(5,5), sigma=1):\n \"\"\"Adds Gaussian noise w. `sigma` and applies Gaussian blur w. `kernel`\n\n If `sigma=0` then it is calculated based on kernel size with following:\n sigma = 0.3*((ksize-1)*0.5 - 1) ~~ 1.1 if ksize = 5\n\n Args:\n page (PIL.PngImagePlugin.PngImageFile):\n Page of PDF that is converted to 'PNG' with\n `pdf2image.convert_from_path` function.\n kernel (tuple, optional): Gaussian blur kernel size. Defaults to (5,5).\n sigma (float, optional): Gaussian blur sigma value. Defaults to 1.\n\n Returns:\n np.ndarray, dtype=np.uint8: Blurred image\n \"\"\"\n img = np.asarray(page) # Convert pages object to numpy array\n gauss = np.random.normal(0, sigma, img.size) # Create gaussian noise\n gauss = gauss.reshape(img.shape[0], img.shape[1], img.shape[2]).astype('uint8')\n img_gauss = cv2.add(img,gauss) # Add gaussian noise\n blurred_image = cv2.GaussianBlur(img_gauss, kernel, sigma) # Blur image\n\n return blurred_image\n\n\ndef pdf_to_image(path_to_pdf, output_folder, dpi=100, blur=True, kernel=(5,5), sigma=1):\n \"\"\"Converts pages to image, blurs if True and saves to output_folder.\n\n Args:\n path_to_pdf (str): path to input PDF\n output_folder (str): path of the folder that images will be saved\n dpi (int, optional): Dots Per Inch, conversion parameter. Default = 100.\n blur (bool, optional): Whether blur is needed or not. Defaults to True.\n kernel (tuple, optional): Gaussian blur kernel size. Defaults to (5,5).\n sigma (float, optional): Gaussian blur sigma value. Defaults to 1.\n \"\"\"\n pages = convert_from_path(path_to_pdf, dpi, fmt='PNG') # Convert to PNGs\n for (page, j) in zip(pages, range(len(pages))): # Iterate over pages\n png_output = os.path.join('.', os.path.join(output_folder, f'_{j}.png'))\n # Required to harden optical character recognition (OCR) process\n if blur:\n blurred_image = blur_image(page, kernel, sigma) # Apply blurring\n cv2.imwrite(png_output, blurred_image) # Save blurred image\n else:\n page.save(png_output, 'PNG') # Save non-blurry image\n\n\ndef image_to_pdf(images_folder, output_folder, orientation, remove_artifacts=False):\n \"\"\"Writes PNG images in the input_folder onto A4 pages by scaling the size.\n\n If images are not proportional to the dimensions of A4, the written image may be\n distorted. If you want to remove images after converting them to PDF,\n set `remove_artifacts` to `True`.\n\n Args:\n images_folder (str): Path to the folder that includes images.\n output_folder (str): Path to the folder that PDFs will be saved\n orientation (str): Orientation of page 'landscape' or 'portrait'.\n remoremove_artifacts (bool, optional):\n Whether to remove the input images or not. Defaults to False.\n \"\"\"\n # Read all \"*.png\" images in the images_folder\n path_to_images = sorted(glob.glob(os.path.join(images_folder,'*.png')))\n # Iterate over images and save them seperate A4 PDFs\n for (image,j) in zip(path_to_images, range(len(path_to_images))):\n canvas_ = set_page(os.path.join(output_folder,f'tmp_{j}.pdf'), orientation)\n draw_image(canvas_, image, orientation) # Draw image to page\n canvas_.save() # save PDF\n if remove_artifacts:\n os.remove(image)\n\n\ndef merge_pdfs(input_folder, path_to_output_pdf, remove_artifacts=False):\n \"\"\"Merges given input PDFs and writes merged version to `output_pdf`\n\n If `remove_artifacts` is `True`, then function removes input PDFs.\n\n Args:\n input_folder (str): PDFs that will be merged should be in this folder\n output_pdf (str): the path to output PDF, it both includes path and name\n remove_artifacts (bool, optional):\n Whether to remove the input file(s) or not. Defaults to False.\n \"\"\"\n pdf_merger = PdfFileMerger()\n input_pdfs = sorted(glob.glob(os.path.join(input_folder, \"*.pdf\")))\n for path in input_pdfs:\n pdf_merger.append(path)\n\n with open(path_to_output_pdf, 'wb') as output_pdf:\n pdf_merger.write(output_pdf)\n\n pdf_merger.close()\n\n if remove_artifacts:\n for pdf in input_pdfs:\n os.remove(pdf)\n\n\ndef pdf_to_image_to_pdf(input_pdf,\n tmp_folder,\n output_folder,\n orientation,\n remove_original=False,\n remove_artifacts=False):\n \"\"\"Converts PDF to images and merges as a PDF without blurring.\n\n Set the `remove_artifacts` parameter to clear temporary files created during\n the conversions. If it is `True`, temporary images and PDFs will be removed.\n Set the `remove_original` to `True' if you want to remove the input PDF.\n\n Args:\n input_pdf (str): Path to input PDF.\n output_folder (str): Path to the folder that processed PDF will be saved.\n remove_original (bool, optional):\n Whether remove input_pdf or not. Defaults to False.\n remove_artifacts (bool, optional):\n Whether to remove the prior processed file(s) or not. Default=False.\n\n Returns:\n str: Path of processed PDF.\n \"\"\"\n file_name = input_pdf.split(os.sep)[-1].split('.')[0]\n output_pdf = os.path.join(output_folder, file_name + '_im2pdf' + '.pdf')\n\n pdf_to_image(input_pdf, tmp_folder, blur=False)\n image_to_pdf(tmp_folder, tmp_folder, orientation, remove_artifacts)\n merge_pdfs(tmp_folder, output_pdf, remove_artifacts)\n\n if remove_original:\n os.remove(input_pdf)\n\n return output_pdf\n\n\ndef blur_pages_of_pdf(input_pdf,\n orientation,\n tmp_folder,\n output_folder,\n dpi=100,\n kernel=(5,5),\n sigma=1,\n remove_artifacts=False,\n ):\n \"\"\"Converts content of PDFs to images, blurs and then merges again\n\n Set the `remove_artifacts` parameter to `True` if you want to clear\n temporary files created during the conversion operations.\n\n Args:\n input_pdf (str): Path to input PDF\n orientation (str): Orientation of page 'landscape' or 'portrait'\n tmp_folder (str): Path to tmp folder that midproducts will be saved.\n output_folder (str): Path to the folder that processed PDF will be saved.\n dpi (int, optional): Dots Per Inch, conversion parameter. Default = 100.\n kernel (tuple, optional): Gaussian blur kernel size. Defaults to (5,5).\n sigma (float, optional): Gaussian blur sigma value. Defaults to 1.\n remove_artifacts (bool, optional):\n Whether to remove the prior processed file(s) or not. Default=False.\n\n Returns:\n [str]: path of output PDF\n \"\"\"\n file_name = input_pdf.split(os.sep)[-1].split('.')[0]\n output_pdf = os.path.join(output_folder, file_name + '_blurred' + '.pdf')\n # Convert pages of PDF to images and save to `tmp_folder`\n pdf_to_image(input_pdf, tmp_folder, dpi, True, kernel, sigma)\n # Write images to A4 PDF pages with `orientation` and save to `tmp_folder`\n image_to_pdf(tmp_folder, tmp_folder, orientation, remove_artifacts)\n # Merge PDFs in `tmp_folder` and write to `output_folder`\n # Remove PDFs in tmp_folder after writing operation\n merge_pdfs(tmp_folder, output_pdf, remove_artifacts)\n\n return output_pdf\n\n\ndef add_watermark(input_pdf, watermark, output_folder, remove_original=False):\n \"\"\"Adds watermark to each page of PDF and saves as '*_watermarked.pdf'\n\n Set the `remove_original` parameter to `True` if you want to remove, original\n `input_pdf` after watermarking operation.\n\n Args:\n input_pdf (str): Path to input PDF.\n watermark (str): Path to watermark.\n output_folder (str): The folder that processed PDFs will be saved.\n remove_original (bool, optional):\n Whether to remove the original file or not after watermarking.\n The default setting is False.\n\n Returns:\n str: Path of output PDF.\n \"\"\"\n file_name = input_pdf.split(os.sep)[-1].split('.')[0] # remove '.pdf'\n output_pdf = os.path.join(output_folder, file_name + '_watermarked' + '.pdf')\n watermark_page = PdfFileReader(watermark).getPage(0) # Read watermark\n\n pdf_reader = PdfFileReader(input_pdf) # Create reader object\n pdf_writer = PdfFileWriter() # Create writer object\n\n for i in range(pdf_reader.getNumPages()): # Add watermark to each page\n page = pdf_reader.getPage(i) # Get the page with number i\n page.mergePage(watermark_page) # Add watermark\n pdf_writer.addPage(page) # add page to the writer object\n\n with open(output_pdf, 'wb') as out:\n pdf_writer.write(out) # Write all watermarked pages to out file\n\n if remove_original:\n os.remove(input_pdf)\n\n return output_pdf\n\n\ndef move_processed_pdf(input_pdf, processed_folder):\n \"\"\"Moves `input_pdf` to `processed_folder`.\n\n If there is a PDF with same name in the `processed_folder`, instead of\n overwriting the PDF in the `processed_folder`, this function adds a postfix\n constructed as `\"_exists_\" + f'{rnd}' + \".pdf\"`. `rnd` is a uniformly\n generated random number which takes values in [0,100].\n\n Args:\n input_pdf (str): Path to input PDF.\n processed_folder (str): Path to folder PDF will be moved.\n \"\"\"\n # Extract file name\n file_name = input_pdf.split(os.sep)[-1].split('.')[0]\n # Define path to move PDF\n new_path_to_input_pdf = os.path.join(processed_folder, file_name + '.pdf')\n if os.path.exists(new_path_to_input_pdf): # Check whether PDF exists or not\n rnd = np.random.randint(0,100) # Generate a random number to postfix\n try:\n postfix = \"_exists_\" + f'{rnd}' + \".pdf\" # Create postfix\n file_name = file_name + postfix # Add postfix to file_name\n # Define path to move postfix added PDF\n if_input_pdf_is_exists = os.path.join(processed_folder, file_name)\n os.rename(input_pdf, if_input_pdf_is_exists) # Move PDF\n except Exception as error:\n print(\"Bad luck, random function returned an existing number\\n\")\n raise error\n else:\n os.rename(input_pdf, new_path_to_input_pdf)\n\n\ndef encrypt_and_add_metadata(input_pdf,\n output_folder,\n usr_pass,\n owner_pass,\n remove_original=False):\n \"\"\"Encrypts PDF, changes permissions and adds metadata to PDF.\n\n Default permissions let the user to print PDF but all other operations are\n restricted. In case you do not want to allow reading without a password,\n specify `usr_pass`. If you want to remove the original PDF after encryption\n set the `remove_original` parameter to `True`\n\n Args:\n input_pdf (str): path to input PDF\n output_folder (str): path to output folder\n usr_pass (str): user password to open PDF, if \"\", no pass required.\n owner_pass (str): owner password to edit PDF\n remove_original (bool, optional):\n Whether remove prior processed file(s) or not. Defaults to False.\n \"\"\"\n # Extract file_name from the path\n file_name = input_pdf.split(os.sep)[-1].split('.')[0]\n # Set output path of PDF\n output_pdf = os.path.join(output_folder, file_name + '_final' + '.pdf')\n\n # Metadata sections of PDF. For more information visit the link below.\n # https://www.adobe.io/open/standards/xmp.html#!adobe/xmp-docs/master/Namespaces.md\n # Dublin Core namespace: dc:title, dc:creator, dc:description, dc:subject, dc:format, dc:rights\n # XMP basic namespace: xmp:CreateDate, xmp:CreatorTool, xmp:ModifyDate, xmp:MetadataDate\n # XMP rights management namespace: xmpRights:WebStatement, xmpRights:Marked\n # XMP media management namespace: xmpMM:DocumentID\n pdf = pikepdf.Pdf.open(input_pdf) # Read PDF\n with pdf.open_metadata() as meta: # Add Metadata\n meta['dc:title'] = 'Lecture Notes'\n meta['dc:creator'] = 'Serhan Yarkan, Tapir Lab.' # Author\n meta['dc:description'] = 'Tapir Lab. Fall-2020 Lecture Notes'\n meta['dc:subject'] = 'Probability, statistics, communications...\\n\\\n ALL HAIL TAPIR!\\n\\\n tapirlab.com' # Keywords\n meta['dc:rights'] = 'Tapir Lab. License'\n meta['xmp:CreateDate'] = datetime.today().isoformat()\n meta['xmp:ModifyDate'] = datetime.today().isoformat()\n meta['xmp:CreatorTool'] = \"Tapir Lab.'s Automatic Watermarking Script\"\n meta['xmpRights:WebStatement'] = \"http://www.tapirlab.com\"\n\n # Set permissions of user\n permissions = pikepdf.Permissions(\n accessibility=False,\n extract=False,\n modify_annotation=False,\n modify_assembly=False,\n modify_form=False,\n modify_other=False,\n print_lowres=True,\n print_highres=True,\n )\n\n # Save PDF with added metadata and restricted permissions.\n pdf.save(output_pdf, encryption=pikepdf.Encryption(user=usr_pass,\n owner=owner_pass,\n allow=permissions,\n ))\n # Close PDF object\n pdf.close()\n\n if remove_original: # Remove original file if True\n os.remove(input_pdf)\n" ]
[ [ "numpy.asarray", "numpy.random.normal", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
otherman16/catalyst
[ "ccef2c7de7ff3869523a86f291b6a2390308bad5" ]
[ "catalyst/callbacks/metric.py" ]
[ "from typing import Any, Callable, Dict, List, TYPE_CHECKING, Union\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nimport logging\n\nimport numpy as np\n\nimport torch\n\nfrom catalyst.core.callback import Callback, CallbackNode, CallbackOrder\nfrom catalyst.tools.meters.averagevaluemeter import AverageValueMeter\nfrom catalyst.utils.distributed import get_distributed_mean\nfrom catalyst.utils.misc import get_dictkey_auto_fn\n\nif TYPE_CHECKING:\n from catalyst.core.runner import IRunner\n\nlogger = logging.getLogger(__name__)\n\n\nclass IMetricCallback(ABC, Callback):\n \"\"\"Callback abstraction for metric computation.\"\"\"\n\n def __init__(\n self,\n prefix: str,\n input_key: Union[str, List[str], Dict[str, str]] = \"targets\",\n output_key: Union[str, List[str], Dict[str, str]] = \"logits\",\n multiplier: float = 1.0,\n **metrics_kwargs,\n ):\n \"\"\"\n Args:\n prefix: key prefix to store computed\n batch/loader/epoch metrics\n input_key: input key to use for metric calculation;\n specifies our `y_true`\n output_key: output key to use for metric calculation;\n specifies our `y_pred`\n multiplier: scalar for metric reweighting\n **metrics_kwargs: extra metric params\n to pass for metric computation\n \"\"\"\n super().__init__(order=CallbackOrder.metric, node=CallbackNode.all)\n self.prefix = prefix\n self.input_key = input_key\n self.output_key = output_key\n self.multiplier = multiplier\n self.metrics_kwargs = metrics_kwargs\n\n self._get_input = get_dictkey_auto_fn(self.input_key)\n self._get_output = get_dictkey_auto_fn(self.output_key)\n\n kv_types = (dict, tuple, list, type(None))\n\n is_value_input = (\n isinstance(self.input_key, str) and self.input_key != \"__all__\"\n )\n is_value_output = (\n isinstance(self.output_key, str) and self.output_key != \"__all__\"\n )\n is_kv_input = (\n isinstance(self.input_key, kv_types) or self.input_key == \"__all__\"\n )\n is_kv_output = (\n isinstance(self.output_key, kv_types)\n or self.output_key == \"__all__\"\n )\n\n if hasattr(self, \"_compute_metric\"):\n pass # overridden in descendants\n elif is_value_input and is_value_output:\n self._compute_metric = self._compute_metric_value\n elif is_kv_input and is_kv_output:\n self._compute_metric = self._compute_metric_key_value\n else:\n raise NotImplementedError()\n\n @property\n @abstractmethod\n def metric_fn(self):\n \"\"\"Specifies used metric function.\"\"\"\n pass\n\n def _compute_metric_value(self, output: Dict, input: Dict):\n \"\"\"\n Compute metric for value-based case.\n For example accuracy on `y_pred` and `y_true`.\n\n Args:\n output: dictionary with output (`y_pred`) values\n for metric computation\n input: dictionary with input (`y_true`) values\n for metric computation\n\n Returns:\n computed metric\n \"\"\"\n output = self._get_output(output, self.output_key)\n input = self._get_input(input, self.input_key)\n\n metric = self.metric_fn(output, input, **self.metrics_kwargs)\n return metric\n\n def _compute_metric_key_value(self, output: Dict, input: Dict):\n \"\"\"\n Compute metric for key-value-based case.\n For example accuracy on `y_pred` and `y_true` and `sample_weights`.\n\n Args:\n output: dictionary with output (`y_pred`) values\n for metric computation\n input: dictionary with input (`y_true`, `sample_weights`)\n values for metric computation\n\n Returns:\n computed metric\n \"\"\"\n output = self._get_output(output, self.output_key)\n input = self._get_input(input, self.input_key)\n\n metric = self.metric_fn(**output, **input, **self.metrics_kwargs)\n return metric\n\n def _process_computed_metric(self, metric: Union[Dict, float]) -> Dict:\n \"\"\"\n Process metric for key-value-based logging.\n Scales by `multiplier`, add appropriate naming.\n\n Args:\n metric:\n\n Returns:\n Dict: processed scaled metric(s) with names\n \"\"\"\n if isinstance(metric, dict):\n metric = {\n f\"{self.prefix}{key}\": value * self.multiplier\n for key, value in metric.items()\n }\n elif isinstance(metric, (float, int, torch.Tensor)):\n metric = {f\"{self.prefix}\": metric * self.multiplier}\n else:\n raise NotImplementedError()\n return metric\n\n\nclass IBatchMetricCallback(IMetricCallback):\n \"\"\"\n Batch-based metric callback.\n Computes metric on batch and saves for logging.\n \"\"\"\n\n def on_batch_end(self, runner: \"IRunner\") -> None:\n \"\"\"Computes metrics and add them to batch metrics.\"\"\"\n metrics = self._compute_metric(runner.output, runner.input)\n metrics = self._process_computed_metric(metrics)\n runner.batch_metrics.update(**metrics)\n\n\nclass ILoaderMetricCallback(IMetricCallback):\n \"\"\"\n Loader-based metric callback.\n Stores input/output values during loaders run\n and computes metric in the end.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Init.\n\n Args:\n **kwargs: `IMetricCallback` params.\n \"\"\"\n super().__init__(**kwargs)\n\n self.input = defaultdict(lambda: [])\n self.output = defaultdict(lambda: [])\n\n def on_loader_start(self, runner: \"IRunner\"):\n \"\"\"Reinitialises internal storage.\"\"\"\n self.input = defaultdict(lambda: [])\n self.output = defaultdict(lambda: [])\n\n def on_batch_end(self, runner: \"IRunner\") -> None:\n \"\"\"Stores new input/output for the metric computation.\"\"\"\n output = self._get_output(runner.output, self.output_key)\n input = self._get_input(runner.input, self.input_key)\n\n for data, storage in zip((input, output), (self.input, self.output)):\n if isinstance(data, dict):\n for key, value in data.items():\n storage[key].append(value.detach().cpu().numpy())\n else:\n storage[\"_data\"].append(data.detach().cpu().numpy())\n\n def on_loader_end(self, runner: \"IRunner\"):\n \"\"\"Computes loader-based metric.\n\n Args:\n runner: current runner\n \"\"\"\n input = {\n key: torch.from_numpy(np.concatenate(self.input[key], axis=0))\n for key in self.input\n }\n output = {\n key: torch.from_numpy(np.concatenate(self.output[key], axis=0))\n for key in self.output\n }\n\n input = {self.input_key: input[\"_data\"]} if len(input) == 1 else input\n output = (\n {self.output_key: output[\"_data\"]} if len(output) == 1 else output\n )\n\n metrics = self._compute_metric(output, input)\n metrics = self._process_computed_metric(metrics)\n runner.loader_metrics.update(**metrics)\n\n\nclass BatchMetricCallback(IBatchMetricCallback):\n \"\"\"A callback that returns single metric on `runner.on_batch_end`.\"\"\"\n\n def __init__(\n self,\n prefix: str,\n metric_fn: Callable,\n input_key: Union[str, List[str], Dict[str, str]] = \"targets\",\n output_key: Union[str, List[str], Dict[str, str]] = \"logits\",\n multiplier: float = 1.0,\n **metric_kwargs,\n ):\n \"\"\"Init.\n\n Args:\n prefix: key prefix to store computed\n batch/loader/epoch metrics\n input_key: input key to use for metric calculation;\n specifies our `y_true`\n output_key: output key to use for metric calculation;\n specifies our `y_pred`\n multiplier: scalar for metric reweighting\n **metrics_kwargs: extra metric params\n to pass for metric computation\n \"\"\"\n super().__init__(\n prefix=prefix,\n input_key=input_key,\n output_key=output_key,\n multiplier=multiplier,\n **metric_kwargs,\n )\n self.metric = metric_fn\n\n @property\n def metric_fn(self):\n \"\"\"Specifies used metric function.\"\"\"\n return self.metric\n\n\nclass LoaderMetricCallback(ILoaderMetricCallback):\n \"\"\"A callback that returns single metric on `runner.on_batch_end`.\"\"\"\n\n def __init__(\n self,\n prefix: str,\n metric_fn: Callable,\n input_key: Union[str, List[str], Dict[str, str]] = \"targets\",\n output_key: Union[str, List[str], Dict[str, str]] = \"logits\",\n multiplier: float = 1.0,\n **metric_kwargs,\n ):\n \"\"\"Init.\n\n Args:\n prefix: key prefix to store computed\n batch/loader/epoch metrics\n input_key: input key to use for metric calculation;\n specifies our `y_true`\n output_key: output key to use for metric calculation;\n specifies our `y_pred`\n multiplier: scalar for metric reweighting\n **metrics_kwargs: extra metric params\n to pass for metric computation\n \"\"\"\n super().__init__(\n prefix=prefix,\n input_key=input_key,\n output_key=output_key,\n multiplier=multiplier,\n **metric_kwargs,\n )\n self.metric = metric_fn\n\n @property\n def metric_fn(self):\n \"\"\"Specifies used metric function.\"\"\"\n return self.metric\n\n\nclass MetricAggregationCallback(Callback):\n \"\"\"A callback to aggregate several metrics in one value.\"\"\"\n\n def __init__(\n self,\n prefix: str,\n metrics: Union[str, List[str], Dict[str, float]] = None,\n mode: str = \"mean\",\n scope: str = \"batch\",\n multiplier: float = 1.0,\n ) -> None:\n \"\"\"\n Args:\n prefix: new key for aggregated metric.\n metrics (Union[str, List[str], Dict[str, float]]): If not None,\n it aggregates only the values from the metric by these keys.\n for ``weighted_sum`` aggregation it must be a Dict[str, float].\n mode: function for aggregation.\n Must be either ``sum``, ``mean`` or ``weighted_sum``.\n multiplier: scale factor for the aggregated metric.\n \"\"\"\n super().__init__(\n order=CallbackOrder.metric_aggregation, node=CallbackNode.all\n )\n\n if prefix is None or not isinstance(prefix, str):\n raise ValueError(\"prefix must be str\")\n\n if mode in (\"sum\", \"mean\"):\n if metrics is not None and not isinstance(metrics, list):\n raise ValueError(\n \"For `sum` or `mean` mode the metrics must be \"\n \"None or list or str (not dict)\"\n )\n elif mode in (\"weighted_sum\", \"weighted_mean\"):\n if metrics is None or not isinstance(metrics, dict):\n raise ValueError(\n \"For `weighted_sum` or `weighted_mean` mode \"\n \"the metrics must be specified \"\n \"and must be a dict\"\n )\n else:\n raise NotImplementedError(\n \"mode must be `sum`, `mean` \"\n \"or `weighted_sum` or `weighted_mean`\"\n )\n\n assert scope in (\"batch\", \"loader\", \"epoch\")\n\n if isinstance(metrics, str):\n metrics = [metrics]\n\n self.prefix = prefix\n self.metrics = metrics\n self.mode = mode\n self.scope = scope\n self.multiplier = multiplier\n\n if mode in (\"sum\", \"weighted_sum\", \"weighted_mean\"):\n self.aggregation_fn = (\n lambda x: torch.sum(torch.stack(x)) * multiplier\n )\n if mode == \"weighted_mean\":\n weights_sum = sum(metrics.items())\n self.metrics = {\n key: weight / weights_sum\n for key, weight in metrics.items()\n }\n elif mode == \"mean\":\n self.aggregation_fn = (\n lambda x: torch.mean(torch.stack(x)) * multiplier\n )\n\n def _preprocess(self, metrics: Any) -> List[float]:\n if self.metrics is not None:\n if self.mode == \"weighted_sum\":\n result = [\n metrics[key] * value for key, value in self.metrics.items()\n ]\n else:\n result = [metrics[key] for key in self.metrics]\n else:\n result = list(metrics.values())\n return result\n\n def _process_metrics(self, metrics: Dict):\n metrics_processed = self._preprocess(metrics)\n metric_aggregated = self.aggregation_fn(metrics_processed)\n metrics[self.prefix] = metric_aggregated\n\n def on_batch_end(self, runner: \"IRunner\") -> None:\n \"\"\"Computes the metric and add it to the batch metrics.\n\n Args:\n runner: current runner\n \"\"\"\n if self.scope == \"batch\":\n self._process_metrics(runner.batch_metrics)\n\n def on_loader_end(self, runner: \"IRunner\"):\n \"\"\"Computes the metric and add it to the loader metrics.\n\n Args:\n runner: current runner\n \"\"\"\n if self.scope == \"loader\":\n self._process_metrics(runner.loader_metrics)\n\n def on_epoch_end(self, runner: \"IRunner\"):\n \"\"\"Computes the metric and add it to the epoch metrics.\n\n Args:\n runner: current runner\n \"\"\"\n if self.scope == \"epoch\":\n self._process_metrics(runner.epoch_metrics)\n\n\nclass MetricManagerCallback(Callback):\n \"\"\"\n Prepares metrics for logging, transferring values from PyTorch to numpy.\n \"\"\"\n\n def __init__(self):\n \"\"\"Init.\"\"\"\n super().__init__(\n order=CallbackOrder.logging - 1, node=CallbackNode.all,\n )\n self.meters: Dict[str, AverageValueMeter] = None\n\n @staticmethod\n def to_single_value(value: Any) -> float:\n \"\"\"Convert any value to float.\n\n Args:\n value: some value\n\n Returns:\n result\n \"\"\"\n if hasattr(value, \"item\"):\n value = value.item()\n\n value = float(value)\n return value\n\n @staticmethod\n def _process_metrics(metrics: Dict[str, Any]):\n output = {}\n for key, value in metrics.items():\n value = get_distributed_mean(value)\n value = MetricManagerCallback.to_single_value(value)\n output[key] = value\n return output\n\n def on_epoch_start(self, runner: \"IRunner\") -> None:\n \"\"\"Epoch start hook.\n\n Args:\n runner: current runner\n \"\"\"\n runner.epoch_metrics = defaultdict(None)\n\n def on_loader_start(self, runner: \"IRunner\") -> None:\n \"\"\"Loader start hook.\n\n Args:\n runner: current runner\n \"\"\"\n runner.loader_metrics = defaultdict(None)\n self.meters = defaultdict(AverageValueMeter)\n\n def on_batch_start(self, runner: \"IRunner\") -> None:\n \"\"\"Batch start hook.\n\n Args:\n runner: current runner\n \"\"\"\n runner.batch_metrics = defaultdict(None)\n\n def on_batch_end(self, runner: \"IRunner\") -> None:\n \"\"\"Batch end hook.\n\n Args:\n runner: current runner\n \"\"\"\n runner.batch_metrics = self._process_metrics(runner.batch_metrics)\n for key, value in runner.batch_metrics.items():\n self.meters[key].add(value, runner.batch_size)\n\n def on_loader_end(self, runner: \"IRunner\") -> None:\n \"\"\"Loader end hook.\n\n Args:\n runner: current runner\n \"\"\"\n for key, value in self.meters.items():\n value = value.mean\n runner.loader_metrics[key] = value\n for key, value in runner.loader_metrics.items():\n runner.epoch_metrics[f\"{runner.loader_key}_{key}\"] = value\n\n\n# backward compatibility\nMetricCallback = BatchMetricCallback\n\n__all__ = [\n \"IMetricCallback\",\n \"IBatchMetricCallback\",\n \"ILoaderMetricCallback\",\n \"BatchMetricCallback\",\n \"LoaderMetricCallback\",\n \"MetricCallback\",\n \"MetricAggregationCallback\",\n \"MetricManagerCallback\",\n]\n" ]
[ [ "numpy.concatenate", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RalfG/pyAscore
[ "9467276f22d230369b24fd56cd69eccb9e82d51c" ]
[ "test/test_id_parsers.py" ]
[ "import unittest\nimport os\nimport pickle\nfrom itertools import product\nfrom pyascore import id_parsers\nimport numpy as np\nfrom pyteomics import mass\n\nSTD_AA_MASS = mass.std_aa_mass\n\nclass TestMassCorrector(unittest.TestCase):\n corrector = id_parsers.MassCorrector()\n\n def test_n_term(self):\n res = \"X\"\n mass = 42.010565\n for i in range(6):\n \n c_res, c_pos, c_mass = self.corrector.correct(res, 0, round(mass, i))\n self.assertEqual(\n (c_res[0], c_pos[0], c_mass[0]),\n ('n', 0, mass)\n )\n\n res = \"M\"\n n_mod_mass = 42.010565\n mass = STD_AA_MASS[res] + n_mod_mass\n for i in range(6):\n\n c_res, c_pos, c_mass = self.corrector.correct(res, 1, round(mass, i))\n self.assertEqual(\n (c_res[0], c_pos[0], c_mass[0]),\n ('n', 0, n_mod_mass)\n )\n\n def test_n_term_combined(self):\n res = \"M\"\n n_mod_mass = 42.010565\n oxi_mass = 15.9949\n mass = STD_AA_MASS[res] + n_mod_mass + oxi_mass\n for i in range(6):\n\n c_res, c_pos, c_mass = self.corrector.correct(res, 1, round(mass, i))\n self.assertEqual(\n (c_res[0], c_pos[0], c_mass[0]),\n ('n', 0, n_mod_mass)\n )\n \n self.assertEqual(\n (c_res[1], c_pos[1], c_mass[1]),\n ('M', 1, oxi_mass)\n )\n\n def test_res(self):\n res = \"S\"\n phospho_mass = 79.966331\n mass = STD_AA_MASS[res] + phospho_mass\n for i in range(6):\n\n c_res, c_pos, c_mass = self.corrector.correct(res, 5, round(mass, i))\n self.assertEqual(\n (c_res[0], c_pos[0], c_mass[0]),\n (res, 5, phospho_mass)\n )\n\n def test_not_found(self):\n res = \"M\"\n phospho_mass = 79.966331\n mass = STD_AA_MASS[res] + phospho_mass\n for i in range(6):\n\n try:\n c_res, c_pos, c_mass = self.corrector.correct(res, 5, round(mass, i))\n\n except ValueError:\n continue\n\n def test_multiple(self):\n n_mod_mass = 42.010565\n oxi_mass = 15.9949\n phospho_mass = 79.966331\n\n peptide = \"MRAMSLVSNEGDSEQNEIR\"\n uncorrected_positions = np.array([1, 5])\n uncorrected_masses = np.array([STD_AA_MASS[\"M\"] + n_mod_mass + oxi_mass,\n STD_AA_MASS[\"S\"] + phospho_mass])\n\n true_positions = np.array([0, 1, 5])\n true_masses = np.array([n_mod_mass,\n oxi_mass,\n phospho_mass])\n\n corrected_positions, corrected_masses = self.corrector.correct_multiple(peptide,\n uncorrected_positions,\n uncorrected_masses)\n\n self.assertTrue(np.all(corrected_positions == true_positions),\n \"Positions are {}, not {}\".format(corrected_positions, true_positions))\n self.assertTrue(np.all(corrected_masses == true_masses),\n \"Masses are {}, not {}\".format(corrected_positions, true_positions))\n\n\ndef example_generator(file_name):\n with open(file_name, \"rb\") as source:\n examples = pickle.load(source)\n for e in examples:\n yield e\n\n\nclass TestIDExtractors(unittest.TestCase):\n\n program_list = [\"comet\", \"percolator\"]\n instrument_list = [\"qexactive\", \"velos\"]\n \n\n global_answers = {(\"comet\", \"qexactive\") : [\n dict(scan=2, charge_states=2, peptides=\"MRAMSLVSNEGDSEQNEIR\", mod_positions=np.array([ 1, 5, 8, 13])),\n dict(scan=3, charge_states=2, peptides=\"KEESEESDDDMGFGLFD\", mod_positions=np.array([ 4, 7, 11 ])),\n dict(scan=4, charge_states=2, peptides=\"KEESEESDDDMGFGLFD\", mod_positions=np.array([ 4, 7 ]))\n ],\n (\"comet\", \"velos\") : [\n dict(scan=2, charge_states=3, peptides=\"QADIQSTVLQINMPRGDLPVGNYQKMAKLADAR\", mod_positions=np.array([ 13, 23 ])),\n dict(scan=3, charge_states=4, peptides=\"ALSTCASHFTAVSVFYGTVIFIYLQPSSSHSMDTDK\", mod_positions=np.array([ 5, 10, 28, 32 ])),\n dict(scan=4, charge_states=2, peptides=\"LLVKKIVSLVR\", mod_positions=np.array([]))\n ],\n (\"percolator\", \"qexactive\") : [\n dict(scan=26840, charge_states=3, peptides=\"ATVPVAAATAAEGEGSPPAVAAVAGPPAAAEVGGGVGGSSR\", mod_positions=np.array([ 16 ])),\n dict(scan=27795, charge_states=2, peptides=\"GEADLFDSGDIFSTGTGSQSVER\", mod_positions=np.array([ 16 ])),\n dict(scan=22462, charge_states=3, peptides=\"LAEAPSPAPTPSPTPVEDLGPQTSTSPGR\", mod_positions=np.array([]))\n ],\n (\"percolator\", \"velos\") : [\n dict(scan=28126, charge_states=3, peptides=\"KGDVVHCWYTGTLQDGTVFDTNIQTSAK\", mod_positions=np.array([ 7 ])),\n dict(scan=33362, charge_states=3, peptides=\"HQILEQAVEDYAETVHQLSK\", mod_positions=np.array([])),\n dict(scan=28509, charge_states=3, peptides=\"RMATEVAADALGEEWKGYVVR\", mod_positions=np.array([]))\n ],\n }\n\n def test_pepxml_extractor(self):\n extractor = id_parsers.PepXMLExtractor()\n\n for prog, instr in product(self.program_list, self.instrument_list):\n file_name = \"_\".join([prog, instr, \"pepxml\", \"examples\"]) + \".pkl\"\n\n for ind, examp in enumerate(example_generator(\n os.path.join(\"test\", \"pyteomics_examples\", \"pepxml\", file_name)\n )):\n extracted_data = extractor.extract(examp)\n answers = self.global_answers[(prog, instr)]\n \n self.assertEqual(extracted_data[\"scans\"][0], answers[ind][\"scan\"])\n self.assertEqual(extracted_data[\"charge_states\"][0], answers[ind][\"charge_states\"])\n self.assertEqual(extracted_data[\"peptides\"][0], answers[ind][\"peptides\"])\n self.assertTrue(np.all(extracted_data[\"peptides\"][0] == answers[ind][\"peptides\"])) # Comparing arrays\n" ]
[ [ "numpy.all", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
harymitchell/mscs-ml
[ "4e284c79c9c30926c7ca24ac8bf082b4cefadddc" ]
[ "MLWorker/dataset_service.py" ]
[ "import numpy as np\r\nfrom numpy import ma\r\nimport pandas\r\nfrom bson.objectid import ObjectId\r\nfrom pymongo import MongoClient\r\nfrom settings import TEST_MONGO_HOST, TEST_MONGO_PORT, TEST_MONGO_USERNAME, TEST_MONGO_PASSWORD\r\nimport gridfs\r\nimport pprint\r\nimport StringIO\r\n\r\nclass dataset_service (object):\r\n \"\"\"Service which connects to Datasets via MongoDB\"\"\"\r\n\r\n def __init__(self, mongo_uri=None, db=None, worker_id=None, client=None):\r\n if client:\r\n self.client = client\r\n else:\r\n self.client = MongoClient(mongo_uri)\r\n self.db = self.client[db]\r\n self.fs = gridfs.GridFS(self.db)\r\n\r\n def retrieveAllDatasets(self):\r\n \"\"\"Returns all datasets for worker\"\"\"\r\n result = []\r\n for dataset in self.db.datasets.find():\r\n result.append(dataset)\r\n return result\r\n\r\n def getDatasetByID(self, identifier):\r\n # print (type(identifier))\r\n # print (identifier)\r\n # if type(identifier) is dict:\r\n # identifier = identifier['_id']\r\n # print (identifier)\r\n result = self.db.datasets.find_one({'_id': ObjectId(identifier)})\r\n if result.get('useGridFile') and result.get('gridFile_id'):\r\n result['data'] = self.fileToDF(result)\r\n return result\r\n\r\n def removeDataset(self, filter):\r\n \"\"\"Removes all datasets for filter\"\"\"\r\n self.db.datasets.remove(filter)\r\n \r\n def updateDataset(self, dataset, set_obj):\r\n \"\"\"Updates the given dataset\"\"\"\r\n return self.db.datasets.update_one(\r\n {'_id': dataset[\"_id\"]}, set_obj, \r\n upsert=False)\r\n \r\n def insertDataset(self, dataset):\r\n \"\"\"Inserts the given dataset\"\"\"\r\n return self.db.datasets.insert(dataset)\r\n \r\n def fileToDF(self, dataset):\r\n \"\"\"Returns a pandas dataframe containing the data from gridFile_id\"\"\"\r\n exists = self.fs.exists(dataset.get('gridFile_id'))\r\n if exists:\r\n file = self.fs.get(dataset.get('gridFile_id')) # names=None if dataset['hasHeaders'] == True else ['field'+str(i+1) for i in range(len(dataset['data'][0].items()))]\r\n df = pandas.read_csv(file)\r\n return df\r\n return dataset.get('data')\r\n \r\n def dataToNumpy(self, data):\r\n \"\"\"Takes array of dict and returns numpy array\r\n Currently, defaults to convert to float\"\"\"\r\n df = pandas.DataFrame(data)\r\n numpyMatrix = df.as_matrix().astype(np.float)\r\n return numpyMatrix\r\n \r\n @staticmethod\r\n def floatFromString(s):\r\n try:\r\n return float(s)\r\n except ValueError:\r\n return None\r\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
AliMakiGmail/SFD-CNN-TL
[ "96890a086cb170334f761a825a5fdcdc51444696" ]
[ "svm.py" ]
[ "#!/usr/bin/env python\n# Copyright 2019 Augusto Cunha and Axelle Pochet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this code and \n# associated documentation files, to deal in the code without restriction, \n# including without limitation the rights to use, copy, modify, merge, publish, distribute, \n# sublicense, and/or sell copies of the code, and to permit persons to whom the code is \n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or \n# substantial portions of the code.\n#\n# THE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT \n# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \n# OUT OF OR IN CONNECTION WITH THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.\n__license__ = \"MIT\"\n__author__ = \"Augusto Cunha, Axelle Pochet\"\n__email__ = \"[email protected], [email protected]\"\n__credits__ = [\"Augusto Cunha\", \"Axelle Pochet\", \"Helio Lopes\", \"Marcelo Gattass\"]\n\n################# all imports #################\nfrom __future__ import print_function\nimport numpy, os, time\nimport pandas as pd\nfrom tensorflow import set_random_seed\n\nnumpy.random.seed(1337)\nset_random_seed(1337)\n\nfrom keras.models import model_from_json\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import svm\nimport metrics\nfrom sklearn.externals import joblib\n\ndef load_model(modelJsonPath, modelWeightsPath):\n ################# load base model #################\n jsonFile = open(modelJsonPath, 'r')\n loadedModelJson = jsonFile.read()\n jsonFile.close()\n base_model = model_from_json(loadedModelJson)\n base_model.load_weights(modelWeightsPath)\n\n\n # remove last layers\n for i in range (7):\n base_model.layers.pop()\n base_model.outputs = [base_model.layers[-1].output]\n\n # freeze layers\n for layer in base_model.layers[:7]:\n layer.trainable = False\n\n return base_model\n\ndef data(X_train, Y_train, numberOfClasses = 2):\n x_train, x_test, y_train, y_test = train_test_split(X_train, Y_train, test_size=0.2, shuffle=True, random_state=1337)\n return x_train, y_train, x_test, y_test\n\ndef dataCV(trainFaultDirectory='dataset/fault/',trainNonFaultDirectory='dataset/nonfault/', modelJsonPath = 'base_model/model.json', modelWeightsPath = 'base_model/model.h5'):\n \n trainFaultURLList = os.listdir(trainFaultDirectory)\n trainNonFaultURLList = os.listdir(trainNonFaultDirectory)\n\n # read and save\n trainImageDataList = []\n trainClassesList = []\n for imageURL in trainFaultURLList:\n csv_file = trainFaultDirectory + imageURL\n df = pd.read_csv(csv_file, delimiter=' ', header = None)\n trainImageDataList.append(df.values)\n trainClassesList.append(1)\n \n for imageURL in trainNonFaultURLList:\n csv_file = trainNonFaultDirectory + imageURL\n df = pd.read_csv(csv_file, delimiter=' ', header = None)\n trainImageDataList.append(df.values)\n trainClassesList.append(0)\n \n # sparsify labels\n Y = trainClassesList\n\n # pass input as numpy arrays\n imageRows = 45\n imageCollumns = 45\n imageChannels = 1\n\n trainSamplesList = numpy.array( trainImageDataList) \n trainSamplesList = trainSamplesList.reshape( trainSamplesList.shape[0], imageRows, imageCollumns, imageChannels )\n trainSamplesList = trainSamplesList.astype( 'float32' )\n \n X = trainSamplesList\n ## extract features as new input\n X = load_model(modelJsonPath, modelWeightsPath).predict(X)\n x_train = X\n y_train = Y\n x_test = []\n y_test = []\n \n return x_train, y_train, x_test, y_test\n\ndef create_model(x_train, y_train, x_test, y_test, numFolds= 5, c=1, k='linear', save = True, baseName='femlpModel'):\n \"\"\"\n Model providing function:\n\n Create Keras model with SVM as classifier, compile test and generate metrics.\n \"\"\"\n ################# define SVM #################\n clf = svm.SVC(kernel = k, C = c, probability=True, random_state=1337)\n clf.fit(x_train, y_train)\n # Classify\n y = np_utils.to_categorical(y_test, 2)\n classesPredictionList = clf.predict(x_test) # 0 or 1\n classesProbaPredictionList = clf.predict_proba(x_test) # probability\n sensitivity, specificity, accuracy, precision, recall, F1_score, auc = metrics.generate_metrics(classesPredictionList,classesProbaPredictionList,y,verbose=False)\n \n if(save):\n joblib.dump(clf, \"output/\"+baseName+\".pkl\") \n \n print(\"Accuracy: {:.4f}\".format(accuracy))\n print(\"Sensitivity: {:.4f}\".format(sensitivity))\n print(\"Specificity: {:.4f}\".format(specificity))\n print(\"F1 Score: {:.4f}\".format(F1_score))\n print(\"AUC: {:.4f}\".format(auc))\n\ndef create_modelCV(x_train, y_train, x_test, y_test, numFolds= 5, c=1, k='linear'):\n \"\"\"\n Model providing function:\n\n Create Keras model with SVM as classifier, compile test and generate metrics.\n \"\"\"\n ### Cross-validation\n skf = StratifiedKFold(n_splits=numFolds, shuffle=True, random_state=1337)\n X = x_train\n Y = y_train\n sensitivitys, specificitys, accuracys, precisions, recalls, F1_scores, aucs = [[],[],[],[],[],[],[]]\n #kpbar = tqdm(total=numFolds, desc=\"Kfold\", leave=False)\n y = np_utils.to_categorical(Y, 2)\n Y = numpy.array(Y)\n for train_index, test_index in skf.split(X, Y):\n ################# define SVM #################\n clf = svm.SVC(kernel = k, C = c, probability=True, random_state=1337)\n clf.fit(X[train_index], Y[train_index])\n # Classify\n classesPredictionList = clf.predict(X[test_index]) # 0 or 1\n classesProbaPredictionList = clf.predict_proba(X[test_index]) # probability\n sensitivity, specificity, accuracy, precision, recall, F1_score, auc = metrics.generate_metrics(classesPredictionList,classesProbaPredictionList,y[test_index],verbose=False)\n sensitivitys.append(sensitivity)\n specificitys.append(specificity)\n accuracys.append(accuracy)\n precisions.append(precision)\n recalls.append(recall)\n F1_scores.append(F1_score)\n aucs.append(auc)\n \n sensitivitys = numpy.array(sensitivitys)\n specificitys = numpy.array(specificitys)\n accuracys = numpy.array(accuracys)\n precisions = numpy.array(precisions)\n recalls = numpy.array(recalls)\n F1_scores = numpy.array(F1_scores)\n aucs = numpy.array(aucs)\n print(\"Mean Accuracy: {:.4f} (+/- {:.4f})\".format(accuracys.mean(), accuracys.std()))\n print(\"Mean Sensitivity: {:.4f} (+/- {:.4f})\".format(sensitivitys.mean(), sensitivitys.std()))\n print(\"Mean Specificity: {:.4f} (+/- {:.4f})\".format(specificitys.mean(), specificitys.std()))\n print(\"Mean F1 Score: {:.4f} (+/- {:.4f})\".format(F1_scores.mean(), F1_scores.std()))\n print(\"Mean AUC: {:.4f} (+/- {:.4f})\".format(aucs.mean(), aucs.std()))\n\nif __name__ == '__main__':\n start_time = time.time()\n print(\"Loading dataset...\")\n X_train, Y_train, X_test, Y_test = dataCV()\n x_train, y_train, x_test, y_test = data(X_train, Y_train)\n print(\"Training...\")\n create_model(x_train, y_train, x_test, y_test, numFolds=5, c=10, k='rbf')\n print(\"Training with cross validation...\")\n create_modelCV(X_train, Y_train, X_test, Y_test, numFolds=5, c=10, k='rbf')\n print(\"--- {:.1f} seconds ---\".format(time.time() - start_time))\n" ]
[ [ "sklearn.externals.joblib.dump", "pandas.read_csv", "numpy.random.seed", "sklearn.model_selection.train_test_split", "sklearn.model_selection.StratifiedKFold", "sklearn.svm.SVC", "tensorflow.set_random_seed", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
gabrielsluz/SlowFast
[ "bd06eac47fa236b070fd9a3b39518eea08d02947" ]
[ "clevrer_dev/text_baseline/train_net.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\n\nimport numpy as np\nimport pprint\nimport torch\nimport copy\nfrom torch.utils.data import DataLoader\n\nimport slowfast.models.losses as losses\nimport slowfast.models.optimizer as optim\nimport slowfast.utils.checkpoint as cu\nimport slowfast.utils.logging as logging\nimport slowfast.utils.metrics as metrics\nimport slowfast.utils.misc as misc\nfrom slowfast.utils.meters import ClevrerTrainMeter, ClevrerValMeter\n#Clevrer specific\nfrom slowfast.datasets.clevrer_text import Clevrertext, Clevrertext_join, Clevrertext_des, Clevrertext_mc\nfrom slowfast.models.build import MODEL_REGISTRY\n\nlogger = logging.get_logger(__name__)\n\n\ndef train_epoch(\n train_loader, model, optimizer, train_meter, cur_epoch, cfg, test_imp=False\n):\n \"\"\"\n Perform the video training for one epoch.\n Args:\n train_loader (loader): video training loader.\n model (model): the video model to train.\n optimizer (optim): the optimizer to perform optimization on the model's\n parameters.\n train_meter (ClevrerTrainMeter): training meters to log the training performance.\n cur_epoch (int): current epoch of training.\n cfg (CfgNode): configs. Details can be found in\n slowfast/config/defaults.py\n \"\"\"\n test_counter = 0\n # Enable train mode.\n model.train()\n train_meter.iter_tic()\n data_size = len(train_loader)\n \n for cur_iter, sampled_batch in enumerate(train_loader): \n #Samples 2 batches. One for des and one for mc\n #There are much more des, then some batches are only des\n des_batch = sampled_batch['des']\n des_q = des_batch['question_dict']['question']\n des_ans = des_batch['question_dict']['ans']\n des_len = des_batch['question_dict']['len']\n # Transfer the data to the current GPU device.\n if cfg.NUM_GPUS:\n des_q = des_q.cuda(non_blocking=True)\n des_ans = des_ans.cuda()\n des_len = des_len.cuda(non_blocking=True)\n \n has_mc = sampled_batch['has_mc'][0]\n if has_mc:\n mc_batch = sampled_batch['mc']\n mc_q = mc_batch['question_dict']['question']\n mc_ans = mc_batch['question_dict']['ans']\n mc_len = mc_batch['question_dict']['len']\n if cfg.NUM_GPUS:\n mc_q = mc_q.cuda(non_blocking=True)\n mc_ans = mc_ans.cuda()\n mc_len = mc_len.cuda(non_blocking=True)\n\n # Update the learning rate.\n lr = optim.get_epoch_lr(cur_epoch + float(cur_iter) / data_size, cfg)\n optim.set_lr(optimizer, lr)\n\n train_meter.data_toc()\n\n #Separated batches\n #Des\n pred_des_ans = model(des_q, True)\n des_loss_fun = losses.get_loss_func('cross_entropy')(reduction=\"mean\")\n loss = des_loss_fun(pred_des_ans, des_ans)\n # check Nan Loss.\n misc.check_nan_losses(loss)\n #Backward pass\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n #Save for stats\n loss_des_val = loss\n\n #MC\n loss_mc_val = None\n if has_mc:\n pred_mc_ans = model(mc_q, False)\n mc_loss_fun = losses.get_loss_func('bce_logit')(reduction=\"mean\")\n loss = mc_loss_fun(pred_mc_ans, mc_ans) #Multiply by 4\n # check Nan Loss.\n misc.check_nan_losses(loss)\n #Backward pass\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n #Save for stats\n loss_mc_val = loss\n\n # #Non separated Not updated for same batch 2 questions:\n # pred_des_ans = model(des_q, True)\n # pred_mc_ans = model(mc_q, False)\n # # Explicitly declare reduction to mean.\n # des_loss_fun = losses.get_loss_func('cross_entropy')(reduction=\"mean\")\n # mc_loss_fun = losses.get_loss_func('bce_logit')(reduction=\"mean\")\n # # Compute the loss.\n # loss_des_val = des_loss_fun(pred_des_ans, des_ans)\n # loss_mc_val = mc_loss_fun(pred_mc_ans, mc_ans)\n # loss = loss_mc_val + loss_des_val\n # # check Nan Loss.\n # misc.check_nan_losses(loss)\n # # Perform the backward pass.\n # optimizer.zero_grad()\n # loss.backward()\n # # Update the parameters.\n # optimizer.step()\n\n top1_err, top5_err = None, None\n # Compute the errors.\n num_topks_correct = metrics.topks_correct(pred_des_ans, des_ans, (1, 5))\n top1_err, top5_err = [\n (1.0 - x / pred_des_ans.size(0)) * 100.0 for x in num_topks_correct\n ]\n if has_mc:\n diff_mc_ans = torch.abs(mc_ans - (torch.sigmoid(pred_mc_ans) >= 0.5).float()) #Errors\n mc_opt_err = 100 * torch.true_divide(diff_mc_ans.sum(), (4*mc_q.size()[0]))\n mc_q_err = 100 * torch.true_divide((diff_mc_ans.sum(dim=1, keepdim=True) != 0).float().sum(), mc_q.size()[0])\n # Copy the stats from GPU to CPU (sync point).\n loss_des_val, loss_mc_val, top1_err, top5_err, mc_opt_err, mc_q_err = (\n loss_des_val.item(),\n loss_mc_val.item(),\n top1_err.item(),\n top5_err.item(),\n mc_opt_err.item(),\n mc_q_err.item()\n )\n mb_size_mc = mc_q.size()[0]\n else:\n mc_opt_err, mc_q_err = None, None\n mb_size_mc = None\n loss_des_val, top1_err, top5_err = (\n loss_des_val.item(),\n top1_err.item(),\n top5_err.item()\n )\n #top1_err, top5_err, mc_opt_err, mc_q_err, loss_des, loss_mc, lr, mb_size\n # Update and log stats.\n train_meter.update_stats(\n top1_err,\n top5_err,\n mc_opt_err,\n mc_q_err,\n loss_des_val,\n loss_mc_val,\n lr,\n des_q.size()[0],\n mb_size_mc\n )\n train_meter.iter_toc() # measure allreduce for this meter\n train_meter.log_iter_stats(cur_epoch, cur_iter)\n train_meter.iter_tic()\n\n\n #For testing implementation\n if test_imp:\n print(\" --- Descriptive questions results --- \")\n # print(\"Des_q\")\n # print(des_q)\n print(\"Des_ans\")\n print(des_ans)\n #print(\"Des_ans_pred\")\n #print(pred_des_ans)\n print(\"Argmax => prediction\")\n print(torch.argmax(pred_des_ans, dim=1, keepdim=False))\n print(\"Top1_err and Top5err\")\n print(top1_err, top5_err)\n print(\"Loss_des_val = {}\".format(loss_des_val))\n if has_mc:\n print(\" --- Multiple Choice questions results --- \")\n # print(\"Mc_q\")\n # print(mc_q)\n # print(\"Mc errors pred x ans\")\n # print(torch.abs(mc_ans - (torch.sigmoid(pred_mc_ans) >= 0.5).float()))\n print(\"mc_opt_err = {} \\nmc_q_err = {}\".format(mc_opt_err, mc_q_err))\n print(\"Loss_mc_val = {}\".format(loss_mc_val))\n test_counter += 1\n if test_counter == 4: \n break\n\n # Log epoch stats.\n train_meter.log_epoch_stats(cur_epoch)\n train_meter.reset()\n\n\[email protected]_grad()\ndef eval_epoch(val_loader, model, val_meter, cur_epoch, cfg, test_imp=False):\n \"\"\"\n Evaluate the model on the val set.\n Args:\n val_loader (loader): data loader to provide validation data.\n model (model): model to evaluate the performance.\n val_meter (ClevrerValMeter): meter instance to record and calculate the metrics.\n cur_epoch (int): number of the current epoch of training.\n cfg (CfgNode): configs. Details can be found in\n slowfast/config/defaults.py\n \"\"\"\n test_counter = 0\n # Evaluation mode enabled. The running stats would not be updated.\n model.eval()\n val_meter.iter_tic()\n\n for cur_iter, sampled_batch in enumerate(val_loader):\n #Samples 2 batches. One for des and one for mc\n #There are much more des, then some batches are only des\n des_batch = sampled_batch['des']\n des_q = des_batch['question_dict']['question']\n des_ans = des_batch['question_dict']['ans']\n des_len = des_batch['question_dict']['len']\n # Transfer the data to the current GPU device.\n if cfg.NUM_GPUS:\n des_q = des_q.cuda(non_blocking=True)\n des_ans = des_ans.cuda()\n des_len = des_len.cuda(non_blocking=True)\n \n has_mc = sampled_batch['has_mc'][0]\n if has_mc:\n mc_batch = sampled_batch['mc']\n mc_q = mc_batch['question_dict']['question']\n mc_ans = mc_batch['question_dict']['ans']\n mc_len = mc_batch['question_dict']['len']\n if cfg.NUM_GPUS:\n mc_q = mc_q.cuda(non_blocking=True)\n mc_ans = mc_ans.cuda()\n mc_len = mc_len.cuda(non_blocking=True)\n\n val_meter.data_toc()\n\n # Explicitly declare reduction to mean.\n des_loss_fun = losses.get_loss_func('cross_entropy')(reduction=\"mean\")\n mc_loss_fun = losses.get_loss_func('bce_logit')(reduction=\"mean\")\n\n pred_des_ans = model(des_q, True)\n loss_des_val = des_loss_fun(pred_des_ans, des_ans)\n\n loss_mc_val = None\n if has_mc:\n pred_mc_ans = model(mc_q, False)\n loss_mc_val = mc_loss_fun(pred_mc_ans, mc_ans) \n\n # Compute the errors.\n num_topks_correct = metrics.topks_correct(pred_des_ans, des_ans, (1, 5))\n # Combine the errors across the GPUs.\n top1_err, top5_err = [\n (1.0 - x / pred_des_ans.size(0)) * 100.0 for x in num_topks_correct\n ]\n if has_mc:\n diff_mc_ans = torch.abs(mc_ans - (torch.sigmoid(pred_mc_ans) >= 0.5).float()) #Errors\n mc_opt_err = 100 * torch.true_divide(diff_mc_ans.sum(), (4*mc_q.size()[0]))\n mc_q_err = 100 * torch.true_divide((diff_mc_ans.sum(dim=1, keepdim=True) != 0).float().sum(), mc_q.size()[0])\n # Copy the stats from GPU to CPU (sync point).\n loss_des_val, loss_mc_val, top1_err, top5_err, mc_opt_err, mc_q_err = (\n loss_des_val.item(),\n loss_mc_val.item(),\n top1_err.item(),\n top5_err.item(),\n mc_opt_err.item(),\n mc_q_err.item()\n )\n mb_size_mc = mc_q.size()[0]\n else:\n mc_opt_err, mc_q_err = None, None\n mb_size_mc = None\n loss_des_val, top1_err, top5_err = (\n loss_des_val.item(),\n top1_err.item(),\n top5_err.item()\n )\n\n val_meter.iter_toc()\n #top1_err, top5_err, mc_opt_err, mc_q_err, loss_des, loss_mc, mb_size_des, mb_size_mc\n # Update and log stats.\n val_meter.update_stats(\n top1_err,\n top5_err,\n mc_opt_err,\n mc_q_err,\n loss_des_val,\n loss_mc_val,\n des_q.size()[0],\n mb_size_mc\n )\n val_meter.log_iter_stats(cur_epoch, cur_iter)\n val_meter.iter_tic()\n\n #For testing implementation\n if test_imp:\n print(\" --- Descriptive questions results --- \")\n # print(\"Des_q\")\n # print(des_q)\n print(\"Des_ans\")\n print(des_ans)\n #print(\"Des_ans_pred\")\n #print(pred_des_ans)\n print(\"Argmax => prediction\")\n print(torch.argmax(pred_des_ans, dim=1, keepdim=False))\n print(\"Top1_err and Top5err\")\n print(top1_err, top5_err)\n print(\"Loss_des_val = {}\".format(loss_des_val))\n if has_mc:\n print(\" --- Multiple Choice questions results --- \")\n # print(\"Mc_q\")\n # print(mc_q)\n # print(\"Mc errors pred x ans\")\n # print(torch.abs(mc_ans - (torch.sigmoid(pred_mc_ans) >= 0.5).float()))\n print(\"mc_opt_err = {} \\nmc_q_err = {}\".format(mc_opt_err, mc_q_err))\n print(\"Loss_mc_val = {}\".format(loss_mc_val))\n test_counter += 1\n if test_counter == 4: \n break\n\n # Log epoch stats.\n val_meter.log_epoch_stats(cur_epoch)\n val_meter.reset()\n\n\ndef build_clevrer_model(cfg, gpu_id=None):\n \"\"\"\n Builds and returns a CLEVRER Text model\n It is a separated function because it CLEVRER receives dataset specific parameters\n \"\"\"\n dataset = Clevrertext(cfg, 'train')\n vocab_len = dataset.get_vocab_len()\n ans_vocab_len = dataset.get_ans_vocab_len()\n vocab = dataset.get_vocab()\n\n if torch.cuda.is_available():\n assert (\n cfg.NUM_GPUS <= torch.cuda.device_count()\n ), \"Cannot use more GPU devices than available\"\n else:\n assert (\n cfg.NUM_GPUS == 0\n ), \"Cuda is not available. Please set `NUM_GPUS: 0 for running on CPUs.\"\n\n # Construct the model\n name = cfg.MODEL.MODEL_NAME\n model = MODEL_REGISTRY.get(name)(cfg, vocab_len, ans_vocab_len, vocab)\n\n if cfg.NUM_GPUS:\n if gpu_id is None:\n # Determine the GPU used by the current process\n cur_device = torch.cuda.current_device()\n else:\n cur_device = gpu_id\n # Transfer the model to the current GPU device\n model = model.cuda(device=cur_device)\n # Use multi-process data parallel model in the multi-gpu setting\n if cfg.NUM_GPUS > 1:\n # Make model replica operate on the current device\n model = torch.nn.parallel.DistributedDataParallel(\n module=model, device_ids=[cur_device], output_device=cur_device\n )\n return model\n\ndef build_dataloader(cfg, mode):\n des_dataset = Clevrertext_des(cfg, mode)\n mc_dataset = Clevrertext_mc(cfg, mode)\n dataset = Clevrertext_join(des_dataset, mc_dataset)\n dataloader = DataLoader(dataset, batch_size=cfg.TRAIN.BATCH_SIZE,\n shuffle= mode=='train', num_workers=cfg.DATA_LOADER.NUM_WORKERS,\n pin_memory=cfg.DATA_LOADER.PIN_MEMORY)\n return dataloader\n\n\ndef train(cfg):\n \"\"\"\n Train a video model for many epochs on train set and evaluate it on val set.\n Args:\n cfg (CfgNode): configs. Details can be found in\n slowfast/config/defaults.py\n \"\"\"\n # Set random seed from configs.\n np.random.seed(cfg.RNG_SEED)\n torch.manual_seed(cfg.RNG_SEED)\n\n # Setup logging format.\n logging.setup_logging(cfg.OUTPUT_DIR)\n # Print config.\n logger.info(\"Train with config:\")\n logger.info(pprint.pformat(cfg))\n\n # Build the video model and print model statistics.\n model = build_clevrer_model(cfg)\n\n # Construct the optimizer.\n optimizer = optim.construct_optimizer(model, cfg)\n\n # Load a checkpoint to resume training if applicable.\n start_epoch = cu.load_train_checkpoint(cfg, model, optimizer)\n # Create the video train and val loaders.\n if cfg.TRAIN.DATASET != 'Clevrertext_join':\n print(\"This train script does not support your dataset: -{}-. Only Clevrertext_join\".format(cfg.TRAIN.DATASET))\n exit()\n # Create the video train and val loaders.\n train_loader = build_dataloader(cfg, \"train\")\n val_loader = build_dataloader(cfg, \"val\")\n\n # Create meters.\n train_meter = ClevrerTrainMeter(len(train_loader), cfg)\n val_meter = ClevrerValMeter(len(val_loader), cfg)\n\n # Perform the training loop.\n logger.info(\"Start epoch: {}\".format(start_epoch + 1))\n for cur_epoch in range(start_epoch, cfg.SOLVER.MAX_EPOCH):\n # Shuffle the dataset.\n #loader.shuffle_dataset(train_loader, cur_epoch)\n # Train for one epoch.\n train_epoch(\n train_loader, model, optimizer, train_meter, cur_epoch, cfg\n )\n\n is_checkp_epoch = cu.is_checkpoint_epoch(\n cfg,\n cur_epoch,\n None,\n )\n is_eval_epoch = misc.is_eval_epoch(\n cfg, cur_epoch, None\n )\n\n # Save a checkpoint.\n if is_checkp_epoch:\n cu.save_checkpoint(cfg.OUTPUT_DIR, model, optimizer, cur_epoch, cfg)\n # Evaluate the model on validation set.\n if is_eval_epoch:\n eval_epoch(val_loader, model, val_meter, cur_epoch, cfg)\n\n\ndef test_implementation(cfg):\n \"\"\"\n Simulates a train and val epoch to check if the gradients are being updated,\n metrics are being calculated correctly\n Args:\n cfg (CfgNode): configs. Details can be found in\n slowfast/config/defaults.py\n \"\"\"\n # Set random seed from configs.\n np.random.seed(cfg.RNG_SEED)\n torch.manual_seed(cfg.RNG_SEED)\n\n # Setup logging format.\n logging.setup_logging(cfg.OUTPUT_DIR)\n # Print config.\n logger.info(\"Test implementation\")\n\n # Build the video model and print model statistics.\n model = build_clevrer_model(cfg)\n\n # Construct the optimizer.\n optimizer = optim.construct_optimizer(model, cfg)\n\n start_epoch = cu.load_train_checkpoint(cfg, model, optimizer)\n\n # Create the video train and val loaders.\n if cfg.TRAIN.DATASET != 'Clevrertext_join':\n print(\"This train script does not support your dataset: -{}-. Only Clevrertext_join\".format(cfg.TRAIN.DATASET))\n \n train_loader = build_dataloader(cfg, \"train\")\n val_loader = build_dataloader(cfg, \"val\")\n\n # Create meters.\n train_meter = ClevrerTrainMeter(len(train_loader), cfg)\n val_meter = ClevrerValMeter(len(val_loader), cfg)\n\n # Perform the training loop.\n logger.info(\"Start epoch: {}\".format(start_epoch + 1))\n # Train for one epoch.\n model_before = copy.deepcopy(model)\n cur_epoch = start_epoch\n train_epoch(\n train_loader, model, optimizer, train_meter, cur_epoch, cfg, test_imp=True\n )\n print(\"Check if parameters changed\")\n for (p_b_name, p_b), (p_name, p) in zip(model_before.named_parameters(), model.named_parameters()):\n if p.requires_grad:\n print(\"Parameter requires grad:\")\n print(p_name, p_b_name)\n assert (p_b != p).any()\n print(\"--Check--\")\n else:\n print(\"Parameter does not require grad:\")\n print(p_name)\n print(p)\n print(\"Val epoch\")\n eval_epoch(val_loader, model, val_meter, cur_epoch, cfg, test_imp=True)" ]
[ [ "torch.sigmoid", "numpy.random.seed", "torch.cuda.current_device", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available", "torch.cuda.device_count", "torch.nn.parallel.DistributedDataParallel", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dguari1/Emotrics
[ "8b807d97663d6deb8efab7c74b31ee42f9218d1b" ]
[ "eye_window.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 23 21:10:25 2017\n\n@author: Diego L.Guarin -- diego_guarin at meei.harvard.edu\n\"\"\"\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nimport numpy as np\nfrom utilities import find_circle_from_points\n\n\"\"\"\nThis window show the eye and allows the user to select 4 points around the iris, \nit then fits a circle around these points. The user can accept the circle or \nre-initialize the point selection\n\"\"\"\n\n\nclass ProcessEye(QtWidgets.QDialog):\n \n def __init__(self, image = None):\n super(ProcessEye, self).__init__()\n self.setWindowTitle('Eye Selection')\n self._circle = None\n self._image = image\n self.label_title = QtWidgets.QLabel()\n self.label_title.setText('Please click on four points around the iris')\n #self.label_title.setWordWrap(True) \n self.label_title.setMaximumWidth(500)\n self.view = View(self)\n if self._image is not None:\n self.view._image = self._image\n self.view.set_picture()\n self.buttonReset = QtWidgets.QPushButton('Clear', self)\n self.buttonReset.clicked.connect(self.view.handleClearView)\n \n self.buttonDone = QtWidgets.QPushButton('Done',self)\n self.buttonDone.clicked.connect(self.handleReturn)\n \n layout = QtWidgets.QGridLayout(self)\n layout.addWidget(self.label_title,0,0,1,2)\n layout.addWidget(self.view,1,0,1,2)\n layout.addWidget(self.buttonDone,2,0,1,1)\n layout.addWidget(self.buttonReset,2,1,1,1)\n \n \n \n def handleReturn(self):\n if self.view._counter == 4:\n self._circle = self.view._circle\n self.close()\n \nclass View(QtWidgets.QGraphicsView):\n \n def __init__(self, parent=None):\n super(View, self).__init__(parent)\n \n self._scene = QtWidgets.QGraphicsScene(self)\n self._photo = QtWidgets.QGraphicsPixmapItem()\n self._scene.addItem(self._photo)\n self.setScene(self._scene)\n self.setSceneRect(QtCore.QRectF(self.viewport().rect()))\n \n #this counts the number of click, if it reaches 4 then it stops accepting \n #more points and draws the cirlce\n self._counter = 0 \n self._circle = None\n #this accomulates the position of the clicks\n self._mouse_pos= np.array([]).reshape(0,2)\n self._image = None\n# pen = QtGui.QPen(QtCore.Qt.green)\n# Rec= QtCore.QRectF(150, 150,300,300)\n# self.scene().addEllipse(Rec, pen)\n\n\n \n \n def process_circle(self):\n x = np.array([self._mouse_pos[0,0],self._mouse_pos[1,0],self._mouse_pos[2,0],self._mouse_pos[3,0]])\n y = np.array([self._mouse_pos[0,1],self._mouse_pos[1,1],self._mouse_pos[2,1],self._mouse_pos[3,1]])\n circle = find_circle_from_points(x,y)\n self._circle = [int(circle[0]),int(circle[1]),int(circle[2])]\n \n \n Ellipse = QtWidgets.QGraphicsEllipseItem(0,0,self._circle[2]*2,self._circle[2]*2)\n #ellipse will be green\n pen = QtGui.QPen(QtCore.Qt.green)\n Ellipse.setPen(pen) \n #if I want to fill the ellipse i should do this:\n #brush = QtGui.QBrush(QtCore.Qt.green) \n #Ellipse.setPen(brush)\n \n #this is the position of the top-left corner of the ellipse.......\n Ellipse.setPos(circle[0]-self._circle[2],circle[1]-self._circle[2])\n Ellipse.setTransform(QtGui.QTransform()) \n self._scene.addItem(Ellipse)\n\n \n \n def mousePressEvent(self,event):\n \n if self._counter < 4:\n scenePos = self.mapToScene(event.pos())\n x = scenePos.x()\n y = scenePos.y()\n self._mouse_pos = np.concatenate((self._mouse_pos, [[float(x),float(y)]]), axis=0)\n pen = QtGui.QPen(QtCore.Qt.red)\n brush = QtGui.QBrush(QtCore.Qt.red)\n Rec= QtCore.QRectF(x, y,int(self._scene.width()*(1/100)+1),int(self._scene.width()*(1/100)+1))\n self._scene.addEllipse(Rec, pen, brush)\n \n QtWidgets.QGraphicsView.mousePressEvent(self, event)\n\n def mouseReleaseEvent(self,event):\n# start = QtCore.QPointF(self.mapToScene(self._start))\n# end = QtCore.QPointF(self.mapToScene(event.pos()))\n# self.scene().addItem(QtWidgets.QGraphicsLineItem(QtCore.QLineF(start, end)))\n# for point in (start, end):\n# text = self.scene().addSimpleText('(%d, %d)' % (point.x(), point.y()))\n# text.setBrush(QtCore.Qt.red)\n# text.setPos(point)\n self._counter +=1\n if self._counter == 4:\n self.process_circle()\n \n QtWidgets.QGraphicsView.mouseReleaseEvent(self, event)\n \n \n def set_picture(self):\n image = self._image.copy()\n height, width, channel = image.shape\n bytesPerLine = 3 * width\n img_Qt = QtGui.QImage(image.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)\n img_show = QtGui.QPixmap.fromImage(img_Qt)\n self._photo = QtWidgets.QGraphicsPixmapItem()\n self._photo.setPixmap(img_show) \n self._scene.addItem(self._photo)\n rect = QtCore.QRectF(self._photo.pixmap().rect())\n self.fitInView(rect)\n self.setSceneRect(rect)\n \n def resizeEvent(self, event):\n rect = QtCore.QRectF(self._photo.pixmap().rect())\n self.fitInView(rect)\n self.setSceneRect(rect)\n \n def handleClearView(self):\n self._scene.clear()\n #self.scene().removeItem(self._photo)\n self.set_picture()\n self._circle = None\n self._counter = 0\n self._mouse_pos= np.array([]).reshape(0,2)\n \n\n \n\nif __name__ == '__main__':\n\n import sys\n if not QtWidgets.QApplication.instance():\n app = QtWidgets.QApplication(sys.argv)\n else:\n app = QtWidgets.QApplication.instance()\n \n GUI = ProcessEye()\n #GUI.resize(640, 480)\n GUI.show()\n sys.exit(app.exec_()) \n " ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
comratvlad/cs231n.github.io
[ "63c72c3e8e88a6edfea7db7df604d715416ba15b" ]
[ "assignments/2019/assignment1/cs231n/vis_utils.py" ]
[ "from builtins import range\nfrom math import sqrt, ceil\n\nimport numpy as np\n\n\ndef visualize_grid(Xs, ubound=255.0, padding=1):\n \"\"\"\n Reshape a 4D tensor of image data to a grid for easy visualization.\n\n Inputs:\n - Xs: Data of shape (N, H, W, C)\n - ubound: Output grid will have values scaled to the range [0, ubound]\n - padding: The number of blank pixels between elements of the grid\n \"\"\"\n (N, H, W, C) = Xs.shape\n grid_size = int(ceil(sqrt(N)))\n grid_height = H * grid_size + padding * (grid_size - 1)\n grid_width = W * grid_size + padding * (grid_size - 1)\n grid = np.zeros((grid_height, grid_width, C))\n next_idx = 0\n y0, y1 = 0, H\n for y in range(grid_size):\n x0, x1 = 0, W\n for x in range(grid_size):\n if next_idx < N:\n img = Xs[next_idx]\n low, high = np.min(img), np.max(img)\n grid[y0:y1, x0:x1] = ubound * (img - low) / (high - low)\n # grid[y0:y1, x0:x1] = Xs[next_idx]\n next_idx += 1\n x0 += W + padding\n x1 += W + padding\n y0 += H + padding\n y1 += H + padding\n # grid_max = np.max(grid)\n # grid_min = np.min(grid)\n # grid = ubound * (grid - grid_min) / (grid_max - grid_min)\n return grid\n\n\ndef vis_grid(Xs):\n \"\"\" visualize a grid of images \"\"\"\n (N, H, W, C) = Xs.shape\n A = int(ceil(sqrt(N)))\n G = np.ones((A*H+A, A*W+A, C), Xs.dtype)\n G *= np.min(Xs)\n n = 0\n for y in range(A):\n for x in range(A):\n if n < N:\n G[y*H+y:(y+1)*H+y, x*W+x:(x+1)*W+x, :] = Xs[n,:,:,:]\n n += 1\n # normalize to [0,1]\n maxg = G.max()\n ming = G.min()\n G = (G - ming)/(maxg-ming)\n return G\n\n\ndef vis_nn(rows):\n \"\"\" visualize array of arrays of images \"\"\"\n N = len(rows)\n D = len(rows[0])\n H,W,C = rows[0][0].shape\n Xs = rows[0][0]\n G = np.ones((N*H+N, D*W+D, C), Xs.dtype)\n for y in range(N):\n for x in range(D):\n G[y*H+y:(y+1)*H+y, x*W+x:(x+1)*W+x, :] = rows[y][x]\n # normalize to [0,1]\n maxg = G.max()\n ming = G.min()\n G = (G - ming)/(maxg-ming)\n return G\n" ]
[ [ "numpy.max", "numpy.min", "numpy.zeros", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vlad-perevezentsev/numba-dppy
[ "9c8dabf929368db96c3a2abf42072178b6cd9634" ]
[ "numba_dppy/tests/njit_tests/dpnp/test_numpy_rng.py" ]
[ "################################################################################\n# Numba-DPPY\n#\n# Copyright 2020-2021 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n################################################################################\n\nimport dpctl\nimport numpy as np\nfrom numba import njit\nimport pytest\nfrom numba_dppy.testing import dpnp_debug\nfrom .dpnp_skip_test import dpnp_skip_test as skip_test\n\n# dpnp throws -30 (CL_INVALID_VALUE) when invoked with multiple kinds of\n# devices at runtime, so testing for level0 only\nlist_of_filter_strs = [\n # \"opencl:gpu:0\",\n \"level0:gpu:0\",\n # \"opencl:cpu:0\",\n]\n\n\[email protected](params=list_of_filter_strs)\ndef filter_str(request):\n return request.param\n\n\nlist_of_size = [\n 9,\n (2, 5),\n (3, 2, 4),\n]\n\nnone_size = [None]\n\n\[email protected](params=list_of_size)\ndef unary_size(request):\n return request.param\n\n\[email protected](params=list_of_size + none_size)\ndef three_arg_size(request):\n return request.param\n\n\nlist_of_one_arg = [\n (\"random_sample\", 0.0, 1.0),\n (\"ranf\", 0.0, 1.0),\n (\"sample\", 0.0, 1.0),\n (\"random\", 0.0, 1.0),\n (\"standard_exponential\", 0.0, None),\n (\"standard_normal\", None, None),\n (\"standard_cauchy\", None, None),\n]\n\n\[email protected](params=list_of_one_arg)\ndef one_arg_fn(request):\n func_str = \"def fn(size):\\n return np.random.\" + request.param[0] + \"(size)\"\n ldict = {}\n exec(func_str, globals(), ldict)\n fn = ldict[\"fn\"]\n return fn, request.param\n\n\ndef test_one_arg_fn(filter_str, one_arg_fn, unary_size, capfd):\n if skip_test(filter_str):\n pytest.skip()\n\n op, params = one_arg_fn\n name, low, high = params\n f = njit(op)\n with dpctl.device_context(filter_str), dpnp_debug():\n actual = f(unary_size)\n captured = capfd.readouterr()\n assert \"dpnp implementation\" in captured.out\n\n if low != None:\n assert np.all(actual >= low)\n if high != None:\n assert np.all(actual < high)\n\n\nlist_of_two_arg_fn = [\n (\"chisquare\", 3, 0, None),\n (\"exponential\", 3.0, 0, None),\n (\"gamma\", 2.0, 0, None),\n (\"geometric\", 0.35, 0, None),\n (\"poisson\", 5.0, 0, None),\n (\"rayleigh\", 2.0, 0, None),\n (\"standard_gamma\", 2.0, 0, None),\n (\"weibull\", 5.0, 0, None),\n]\n\n\[email protected](params=list_of_two_arg_fn)\ndef two_arg_fn(request):\n return request.param\n\n\ndef get_two_arg_fn(op_name):\n func_str = (\n \"def fn(first_arg, second_arg):\\n\\treturn np.random.\"\n + op_name\n + \"(first_arg, second_arg)\"\n )\n ldict = {}\n exec(func_str, globals(), ldict)\n fn = ldict[\"fn\"]\n return fn\n\n\ndef test_two_arg_fn(filter_str, two_arg_fn, unary_size, capfd):\n if skip_test(filter_str):\n pytest.skip()\n\n op_name, first_arg, low, high = two_arg_fn\n\n if op_name == \"gamma\":\n pytest.skip(\"AttributeError: 'NoneType' object has no attribute 'ravel'\")\n op = get_two_arg_fn(op_name)\n f = njit(op)\n with dpctl.device_context(filter_str), dpnp_debug():\n actual = f(first_arg, unary_size)\n captured = capfd.readouterr()\n assert \"dpnp implementation\" in captured.out\n\n if low != None and high == None:\n if np.isscalar(actual):\n assert actual >= low\n else:\n actual = actual.ravel()\n assert np.all(actual >= low)\n\n\nlist_of_three_arg_fn = [\n (\"randint\", 2, 23, 0, None),\n (\"random_integers\", 2, 23, 1, None),\n (\"beta\", 2.56, 0.8, 0, 1.0),\n (\"binomial\", 5, 0.0, 0, 1.0),\n (\"gumbel\", 0.5, 0.1, None, None),\n (\"laplace\", 0.0, 1.0, None, None),\n (\"lognormal\", 3.0, 1.0, None, None),\n (\"multinomial\", 100, np.array([1 / 7.0] * 5), 0, 100),\n (\"multivariate_normal\", (1, 2), [[1, 0], [0, 1]], None, None),\n (\"negative_binomial\", 1, 0.1, 0, None),\n (\"normal\", 0.0, 0.1, None, None),\n (\"uniform\", -1.0, 0.0, -1.0, 0.0),\n]\n\n\[email protected](params=list_of_three_arg_fn)\ndef three_arg_fn(request):\n return request.param\n\n\ndef get_three_arg_fn(op_name):\n func_str = (\n \"def fn(first_arg, second_arg, third_arg):\\n\\treturn np.random.\"\n + op_name\n + \"(first_arg, second_arg, third_arg)\"\n )\n ldict = {}\n exec(func_str, globals(), ldict)\n fn = ldict[\"fn\"]\n return fn\n\n\ndef test_three_arg_fn(filter_str, three_arg_fn, three_arg_size, capfd):\n if skip_test(filter_str):\n pytest.skip()\n\n op_name, first_arg, second_arg, low, high = three_arg_fn\n\n if op_name == \"multinomial\":\n pytest.skip(\"DPNP RNG Error: dpnp_rng_multinomial_c() failed\")\n elif op_name == \"multivariate_normal\":\n pytest.skip(\n \"No implementation of function Function(<class \"\n \"'numba_dppy.dpnp_glue.stubs.dpnp.multivariate_normal'>) found for signature\"\n )\n elif op_name == \"negative_binomial\":\n pytest.skip(\"DPNP RNG Error: dpnp_rng_negative_binomial_c() failed.\")\n elif op_name == \"gumbel\":\n pytest.skip(\"DPNP error\")\n\n op = get_three_arg_fn(op_name)\n f = njit(op)\n with dpctl.device_context(filter_str), dpnp_debug():\n actual = f(first_arg, second_arg, three_arg_size)\n captured = capfd.readouterr()\n assert \"dpnp implementation\" in captured.out\n\n if low != None and high == None:\n if second_arg:\n low = first_arg\n high = second_arg\n assert np.all(actual >= low)\n assert np.all(actual <= high)\n else:\n high = first_arg\n assert np.all(actual >= low)\n assert np.all(actual <= high)\n elif low != None and high != None:\n if np.isscalar(actual):\n assert actual >= low\n assert actual <= high\n else:\n actual = actual.ravel()\n assert np.all(actual >= low)\n assert np.all(actual <= high)\n\n\ndef test_rand(filter_str):\n if skip_test(filter_str):\n pytest.skip()\n\n @njit\n def f():\n c = np.random.rand(3, 2)\n return c\n\n with dpctl.device_context(filter_str), dpnp_debug():\n actual = f()\n\n actual = actual.ravel()\n assert np.all(actual >= 0.0)\n assert np.all(actual < 1.0)\n\n\ndef test_hypergeometric(filter_str, three_arg_size):\n if skip_test(filter_str):\n pytest.skip()\n\n @njit\n def f(ngood, nbad, nsamp, size):\n res = np.random.hypergeometric(ngood, nbad, nsamp, size)\n return res\n\n ngood, nbad, nsamp = 100, 2, 10\n with dpctl.device_context(filter_str), dpnp_debug():\n actual = f(ngood, nbad, nsamp, three_arg_size)\n\n if np.isscalar(actual):\n assert actual >= 0\n assert actual <= min(nsamp, ngood + nbad)\n else:\n actual = actual.ravel()\n assert np.all(actual >= 0)\n assert np.all(actual <= min(nsamp, ngood + nbad))\n" ]
[ [ "numpy.random.hypergeometric", "numpy.all", "numpy.random.rand", "numpy.isscalar", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qaz734913414/insightface
[ "4101fe608ca1d38604a23d53f32314ce8a28fe79", "4101fe608ca1d38604a23d53f32314ce8a28fe79" ]
[ "recognition/arcface_paddle/deploy/pdserving/web_service.py", "recognition/vpl/vpl.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom paddle_serving_server.web_service import WebService, Op\n\nimport numpy as np\nimport cv2\nimport base64\n\n\nclass ArcFaceOp(Op):\n def init_op(self):\n pass\n\n def preprocess(self, input_dicts, data_id, log_id):\n (_, input_dict), = input_dicts.items()\n data = base64.b64decode(input_dict[\"image\"])\n data = np.frombuffer(data, np.uint8)\n # Note: class variables(self.var) can only be used in process op mode\n img = cv2.imdecode(data, cv2.IMREAD_COLOR)\n img = cv2.resize(img,(112,112))\n # normalize to mean 0.5, std 0.5\n img = (img - 127.5) * 0.00784313725\n # BGR2RGB\n img = img[:, :, ::-1]\n img = img.transpose((2, 0, 1))\n img = np.expand_dims(img, 0)\n img = img.astype('float32')\n return {\"x\":img.copy()}, False, None, \"\"\n\n def postprocess(self, input_dicts, fetch_dict, log_id):\n out = fetch_dict[\"save_infer_model/scale_0.tmp_1\"]\n out_dict = {\"out\": out}\n\n return out_dict, None, \"\"\n\nclass ArcFaceService(WebService):\n def get_pipeline_response(self, read_op):\n arcface_op = ArcFaceOp(name=\"ArcFace\", input_ops=[read_op])\n return arcface_op\n\n\narcface_service = ArcFaceService(name=\"ArcFace\")\narcface_service.prepare_pipeline_config(\"config.yml\")\narcface_service.run_service()", "import logging\nimport os\n\nimport torch\nimport torch.distributed as dist\nfrom torch.nn import Module\nfrom torch.nn.functional import normalize, linear\nfrom torch.nn.parameter import Parameter\n\n\nclass VPL(Module):\n \"\"\"\n Modified from Partial-FC\n \"\"\"\n\n @torch.no_grad()\n def __init__(self, rank, local_rank, world_size, batch_size, resume,\n margin_softmax, num_classes, sample_rate=1.0, embedding_size=512, prefix=\"./\", cfg=None):\n super(VPL, self).__init__()\n #\n assert sample_rate==1.0\n assert not resume\n self.num_classes: int = num_classes\n self.rank: int = rank\n self.local_rank: int = local_rank\n self.device: torch.device = torch.device(\"cuda:{}\".format(self.local_rank))\n self.world_size: int = world_size\n self.batch_size: int = batch_size\n self.margin_softmax: callable = margin_softmax\n self.sample_rate: float = sample_rate\n self.embedding_size: int = embedding_size\n self.prefix: str = prefix\n self.num_local: int = num_classes // world_size + int(rank < num_classes % world_size)\n self.class_start: int = num_classes // world_size * rank + min(rank, num_classes % world_size)\n self.num_sample: int = int(self.sample_rate * self.num_local)\n\n self.weight_name = os.path.join(self.prefix, \"rank_{}_softmax_weight.pt\".format(self.rank))\n self.weight_mom_name = os.path.join(self.prefix, \"rank_{}_softmax_weight_mom.pt\".format(self.rank))\n\n self.weight = torch.normal(0, 0.01, (self.num_local, self.embedding_size), device=self.device)\n self.weight_mom: torch.Tensor = torch.zeros_like(self.weight)\n logging.info(\"softmax weight init successfully!\")\n logging.info(\"softmax weight mom init successfully!\")\n self.stream: torch.cuda.Stream = torch.cuda.Stream(local_rank)\n\n self.index = None\n self.update = lambda: 0\n self.sub_weight = Parameter(self.weight)\n self.sub_weight_mom = self.weight_mom\n\n #vpl variables\n\n self._iters = 0\n self.cfg = cfg\n self.vpl_mode = -1\n if self.cfg is not None:\n self.vpl_mode = self.cfg['mode']\n if self.vpl_mode>=0:\n self.register_buffer(\"queue\", torch.randn(self.num_local, self.embedding_size, device=self.device))\n self.queue = normalize(self.queue)\n self.register_buffer(\"queue_iters\", torch.zeros((self.num_local,), dtype=torch.long, device=self.device))\n self.register_buffer(\"queue_lambda\", torch.zeros((self.num_local,), dtype=torch.float32, device=self.device))\n\n\n def save_params(self):\n pass\n #torch.save(self.weight.data, self.weight_name)\n #torch.save(self.weight_mom, self.weight_mom_name)\n\n @torch.no_grad()\n def sample(self, total_label):\n index_positive = (self.class_start <= total_label) & (total_label < self.class_start + self.num_local)\n total_label[~index_positive] = -1\n total_label[index_positive] -= self.class_start\n return index_positive\n\n def forward(self, total_features, norm_weight):\n torch.cuda.current_stream().wait_stream(self.stream)\n logits = linear(total_features, norm_weight)\n return logits\n\n @torch.no_grad()\n def update(self):\n self.weight_mom[self.index] = self.sub_weight_mom\n self.weight[self.index] = self.sub_weight\n\n def prepare(self, label, optimizer):\n with torch.cuda.stream(self.stream):\n total_label = torch.zeros(\n size=[self.batch_size * self.world_size], device=self.device, dtype=torch.long)\n dist.all_gather(list(total_label.chunk(self.world_size, dim=0)), label)\n index_positive = self.sample(total_label)\n optimizer.state.pop(optimizer.param_groups[-1]['params'][0], None)\n optimizer.param_groups[-1]['params'][0] = self.sub_weight\n optimizer.state[self.sub_weight]['momentum_buffer'] = self.sub_weight_mom\n norm_weight = normalize(self.sub_weight)\n return total_label, norm_weight, index_positive\n\n @torch.no_grad()\n def prepare_queue_lambda(self, label, iters):\n self.queue_lambda[:] = 0.0\n if iters>self.cfg['start_iters']:\n allowed_delta = self.cfg['allowed_delta']\n if self.vpl_mode==0:\n past_iters = iters - self.queue_iters\n idx = torch.where(past_iters <= allowed_delta)[0]\n self.queue_lambda[idx] = self.cfg['lambda']\n\n if iters % 2000 == 0 and self.rank == 0:\n logging.info('[%d]use-lambda: %d/%d'%(iters,len(idx), self.num_local))\n\n @torch.no_grad()\n def set_queue(self, total_features, total_label, index_positive, iters):\n local_label = total_label[index_positive]\n sel_features = normalize(total_features[index_positive,:])\n self.queue[local_label,:] = sel_features\n self.queue_iters[local_label] = iters\n\n def forward_backward(self, label, features, optimizer, feature_w):\n self._iters += 1\n total_label, norm_weight, index_positive = self.prepare(label, optimizer)\n total_features = torch.zeros(\n size=[self.batch_size * self.world_size, self.embedding_size], device=self.device)\n dist.all_gather(list(total_features.chunk(self.world_size, dim=0)), features.data)\n total_features.requires_grad = True\n\n if feature_w is not None:\n total_feature_w = torch.zeros(\n size=[self.batch_size * self.world_size, self.embedding_size], device=self.device)\n dist.all_gather(list(total_feature_w.chunk(self.world_size, dim=0)), feature_w.data)\n\n if self.vpl_mode>=0:\n self.prepare_queue_lambda(total_label, self._iters)\n _lambda = self.queue_lambda.view(self.num_local, 1)\n injected_weight = norm_weight*(1.0-_lambda) + self.queue*_lambda\n injected_norm_weight = normalize(injected_weight)\n logits = self.forward(total_features, injected_norm_weight)\n else:\n logits = self.forward(total_features, norm_weight)\n\n logits = self.margin_softmax(logits, total_label)\n\n with torch.no_grad():\n max_fc = torch.max(logits, dim=1, keepdim=True)[0]\n dist.all_reduce(max_fc, dist.ReduceOp.MAX)\n\n # calculate exp(logits) and all-reduce\n logits_exp = torch.exp(logits - max_fc)\n logits_sum_exp = logits_exp.sum(dim=1, keepdims=True)\n dist.all_reduce(logits_sum_exp, dist.ReduceOp.SUM)\n\n # calculate prob\n logits_exp.div_(logits_sum_exp)\n\n # get one-hot\n grad = logits_exp\n index = torch.where(total_label != -1)[0]\n one_hot = torch.zeros(size=[index.size()[0], grad.size()[1]], device=grad.device)\n one_hot.scatter_(1, total_label[index, None], 1)\n\n # calculate loss\n loss = torch.zeros(grad.size()[0], 1, device=grad.device)\n loss[index] = grad[index].gather(1, total_label[index, None])\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n loss_v = loss.clamp_min_(1e-30).log_().mean() * (-1)\n\n # calculate grad\n grad[index] -= one_hot\n grad.div_(self.batch_size * self.world_size)\n\n logits.backward(grad)\n if total_features.grad is not None:\n total_features.grad.detach_()\n x_grad: torch.Tensor = torch.zeros_like(features, requires_grad=True)\n # feature gradient all-reduce\n dist.reduce_scatter(x_grad, list(total_features.grad.chunk(self.world_size, dim=0)))\n x_grad = x_grad * self.world_size\n #vpl set queue\n if self.vpl_mode>=0:\n if feature_w is None:\n self.set_queue(total_features.detach(), total_label, index_positive, self._iters)\n else:\n self.set_queue(total_feature_w, total_label, index_positive, self._iters)\n # backward backbone\n return x_grad, loss_v\n\n" ]
[ [ "numpy.frombuffer", "numpy.expand_dims" ], [ "torch.normal", "torch.nn.functional.normalize", "torch.cuda.stream", "torch.distributed.all_reduce", "torch.max", "torch.zeros", "torch.cuda.current_stream", "torch.randn", "torch.zeros_like", "torch.exp", "torch.no_grad", "torch.where", "torch.nn.parameter.Parameter", "torch.nn.functional.linear", "torch.cuda.Stream" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
seunghoonlee89/pyscf-ecCC-TCC
[ "9a14f9bcc63bc75f5939cb4d00eb47861d8d8989", "9a14f9bcc63bc75f5939cb4d00eb47861d8d8989", "2091566fb83c1474e40bf74f271be2ce4611f60c" ]
[ "pyscf/pbc/mp/kmp2.py", "pyscf/adc/uadc_ao2mo.py", "pyscf/cc/renorm_ccsd_t_slow.py" ]
[ "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Timothy Berkelbach <[email protected]>\n# James McClain <[email protected]>\n#\n\n\n'''\nkpoint-adapted and spin-adapted MP2\nt2[i,j,a,b] = <ij|ab> / D_ij^ab\n\nt2 and eris are never stored in full, only a partial\neri of size (nkpts,nocc,nocc,nvir,nvir)\n'''\n\nimport time\nimport numpy as np\nfrom scipy.linalg import block_diag\n\nfrom pyscf import lib\nfrom pyscf.lib import logger, einsum\nfrom pyscf.mp import mp2\nfrom pyscf.pbc.lib import kpts_helper\nfrom pyscf.lib.parameters import LARGE_DENOM\nfrom pyscf import __config__\n\nWITH_T2 = getattr(__config__, 'mp_mp2_with_t2', True)\n\n\ndef kernel(mp, mo_energy, mo_coeff, verbose=logger.NOTE, with_t2=WITH_T2):\n nmo = mp.nmo\n nocc = mp.nocc\n nvir = nmo - nocc\n nkpts = mp.nkpts\n\n eia = np.zeros((nocc,nvir))\n eijab = np.zeros((nocc,nocc,nvir,nvir))\n\n fao2mo = mp._scf.with_df.ao2mo\n kconserv = mp.khelper.kconserv\n emp2 = 0.\n oovv_ij = np.zeros((nkpts,nocc,nocc,nvir,nvir), dtype=mo_coeff[0].dtype)\n\n mo_e_o = [mo_energy[k][:nocc] for k in range(nkpts)]\n mo_e_v = [mo_energy[k][nocc:] for k in range(nkpts)]\n\n # Get location of non-zero/padded elements in occupied and virtual space\n nonzero_opadding, nonzero_vpadding = padding_k_idx(mp, kind=\"split\")\n\n if with_t2:\n t2 = np.zeros((nkpts, nkpts, nkpts, nocc, nocc, nvir, nvir), dtype=complex)\n else:\n t2 = None\n\n for ki in range(nkpts):\n for kj in range(nkpts):\n for ka in range(nkpts):\n kb = kconserv[ki,ka,kj]\n orbo_i = mo_coeff[ki][:,:nocc]\n orbo_j = mo_coeff[kj][:,:nocc]\n orbv_a = mo_coeff[ka][:,nocc:]\n orbv_b = mo_coeff[kb][:,nocc:]\n oovv_ij[ka] = fao2mo((orbo_i,orbv_a,orbo_j,orbv_b),\n (mp.kpts[ki],mp.kpts[ka],mp.kpts[kj],mp.kpts[kb]),\n compact=False).reshape(nocc,nvir,nocc,nvir).transpose(0,2,1,3) / nkpts\n for ka in range(nkpts):\n kb = kconserv[ki,ka,kj]\n\n # Remove zero/padded elements from denominator\n eia = LARGE_DENOM * np.ones((nocc, nvir), dtype=mo_energy[0].dtype)\n n0_ovp_ia = np.ix_(nonzero_opadding[ki], nonzero_vpadding[ka])\n eia[n0_ovp_ia] = (mo_e_o[ki][:,None] - mo_e_v[ka])[n0_ovp_ia]\n\n ejb = LARGE_DENOM * np.ones((nocc, nvir), dtype=mo_energy[0].dtype)\n n0_ovp_jb = np.ix_(nonzero_opadding[kj], nonzero_vpadding[kb])\n ejb[n0_ovp_jb] = (mo_e_o[kj][:,None] - mo_e_v[kb])[n0_ovp_jb]\n\n eijab = lib.direct_sum('ia,jb->ijab',eia,ejb)\n t2_ijab = np.conj(oovv_ij[ka]/eijab)\n if with_t2:\n t2[ki, kj, ka] = t2_ijab\n woovv = 2*oovv_ij[ka] - oovv_ij[kb].transpose(0,1,3,2)\n emp2 += np.einsum('ijab,ijab', t2_ijab, woovv).real\n\n emp2 /= nkpts\n\n return emp2, t2\n\n\ndef _padding_k_idx(nmo, nocc, kind=\"split\"):\n \"\"\"A convention used for padding vectors, matrices and tensors in case when occupation numbers depend on the\n k-point index.\n Args:\n nmo (Iterable): k-dependent orbital number;\n nocc (Iterable): k-dependent occupation numbers;\n kind (str): either \"split\" (occupied and virtual spaces are split) or \"joint\" (occupied and virtual spaces are\n the joint;\n\n Returns:\n Two lists corresponding to the occupied and virtual spaces for kind=\"split\". Each list contains integer arrays\n with indexes pointing to actual non-zero entries in the padded vector/matrix/tensor. If kind=\"joint\", a single\n list of arrays is returned corresponding to the entire MO space.\n \"\"\"\n if kind not in (\"split\", \"joint\"):\n raise ValueError(\"The 'kind' argument must be one of 'split', 'joint'\")\n\n if kind == \"split\":\n indexes_o = []\n indexes_v = []\n else:\n indexes = []\n\n nocc = np.array(nocc)\n nmo = np.array(nmo)\n nvirt = nmo - nocc\n dense_o = np.amax(nocc)\n dense_v = np.amax(nvirt)\n dense_nmo = dense_o + dense_v\n\n for k_o, k_nmo in zip(nocc, nmo):\n k_v = k_nmo - k_o\n if kind == \"split\":\n indexes_o.append(np.arange(k_o))\n indexes_v.append(np.arange(dense_v - k_v, dense_v))\n else:\n indexes.append(np.concatenate((\n np.arange(k_o),\n np.arange(dense_nmo - k_v, dense_nmo),\n )))\n\n if kind == \"split\":\n return indexes_o, indexes_v\n\n else:\n return indexes\n\n\ndef padding_k_idx(mp, kind=\"split\"):\n \"\"\"A convention used for padding vectors, matrices and tensors in case when occupation numbers depend on the\n k-point index.\n\n This implementation stores k-dependent Fock and other matrix in dense arrays with additional dimensions\n corresponding to k-point indexes. In case when the occupation numbers depend on the k-point index (i.e. a metal) or\n when some k-points have more Bloch basis functions than others the corresponding data structure has to be padded\n with entries that are not used (fictitious occupied and virtual degrees of freedom). Current convention stores these\n states at the Fermi level as shown in the following example.\n\n +----+--------+--------+--------+\n | | k=0 | k=1 | k=2 |\n | +--------+--------+--------+\n | | nocc=2 | nocc=3 | nocc=2 |\n | | nvir=4 | nvir=3 | nvir=3 |\n +====+========+========+========+\n | v3 | k0v3 | k1v2 | k2v2 |\n +----+--------+--------+--------+\n | v2 | k0v2 | k1v1 | k2v1 |\n +----+--------+--------+--------+\n | v1 | k0v1 | k1v0 | k2v0 |\n +----+--------+--------+--------+\n | v0 | k0v0 | | |\n +====+========+========+========+\n | Fermi level |\n +====+========+========+========+\n | o2 | | k1o2 | |\n +----+--------+--------+--------+\n | o1 | k0o1 | k1o1 | k2o1 |\n +----+--------+--------+--------+\n | o0 | k0o0 | k1o0 | k2o0 |\n +----+--------+--------+--------+\n\n In the above example, `get_nmo(mp, per_kpoint=True) == (6, 6, 5)`, `get_nocc(mp, per_kpoint) == (2, 3, 2)`. The\n resulting dense `get_nmo(mp) == 7` and `get_nocc(mp) == 3` correspond to padded dimensions. This function will\n return the following indexes corresponding to the filled entries of the above table:\n\n >>> padding_k_idx(mp, kind=\"split\")\n ([(0, 1), (0, 1, 2), (0, 1)], [(0, 1, 2, 3), (1, 2, 3), (1, 2, 3)])\n\n >>> padding_k_idx(mp, kind=\"joint\")\n [(0, 1, 3, 4, 5, 6), (0, 1, 2, 4, 5, 6), (0, 1, 4, 5, 6)]\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n kind (str): either \"split\" (occupied and virtual spaces are split) or \"joint\" (occupied and virtual spaces are\n the joint;\n\n Returns:\n Two lists corresponding to the occupied and virtual spaces for kind=\"split\". Each list contains integer arrays\n with indexes pointing to actual non-zero entries in the padded vector/matrix/tensor. If kind=\"joint\", a single\n list of arrays is returned corresponding to the entire MO space.\n \"\"\"\n return _padding_k_idx(mp.get_nmo(per_kpoint=True), mp.get_nocc(per_kpoint=True), kind=kind)\n\n\ndef padded_mo_energy(mp, mo_energy):\n \"\"\"\n Pads energies of active MOs.\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n mo_energy (ndarray): original non-padded molecular energies;\n\n Returns:\n Padded molecular energies.\n \"\"\"\n frozen_mask = get_frozen_mask(mp)\n padding_convention = padding_k_idx(mp, kind=\"joint\")\n nkpts = mp.nkpts\n\n result = np.zeros((nkpts, mp.nmo), dtype=mo_energy[0].dtype)\n for k in range(nkpts):\n result[np.ix_([k], padding_convention[k])] = mo_energy[k][frozen_mask[k]]\n\n return result\n\n\ndef padded_mo_coeff(mp, mo_coeff):\n \"\"\"\n Pads coefficients of active MOs.\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n mo_coeff (ndarray): original non-padded molecular coefficients;\n\n Returns:\n Padded molecular coefficients.\n \"\"\"\n frozen_mask = get_frozen_mask(mp)\n padding_convention = padding_k_idx(mp, kind=\"joint\")\n nkpts = mp.nkpts\n\n result = np.zeros((nkpts, mo_coeff[0].shape[0], mp.nmo), dtype=mo_coeff[0].dtype)\n for k in range(nkpts):\n result[np.ix_([k], np.arange(result.shape[1]), padding_convention[k])] = mo_coeff[k][:, frozen_mask[k]]\n\n return result\n\n\ndef _frozen_sanity_check(frozen, mo_occ, kpt_idx):\n '''Performs a few sanity checks on the frozen array and mo_occ.\n\n Specific tests include checking for duplicates within the frozen array.\n\n Args:\n frozen (array_like of int): The orbital indices that will be frozen.\n mo_occ (:obj:`ndarray` of int): The occupuation number for each orbital\n resulting from a mean-field-like calculation.\n kpt_idx (int): The k-point that `mo_occ` and `frozen` belong to.\n\n '''\n frozen = np.array(frozen)\n nocc = np.count_nonzero(mo_occ > 0)\n nvir = len(mo_occ) - nocc\n assert nocc, 'No occupied orbitals?\\n\\nnocc = %s\\nmo_occ = %s' % (nocc, mo_occ)\n all_frozen_unique = (len(frozen) - len(np.unique(frozen))) == 0\n if not all_frozen_unique:\n raise RuntimeError('Frozen orbital list contains duplicates!\\n\\nkpt_idx %s\\n'\n 'frozen %s' % (kpt_idx, frozen))\n if len(frozen) > 0 and np.max(frozen) > len(mo_occ) - 1:\n raise RuntimeError('Freezing orbital not in MO list!\\n\\nkpt_idx %s\\n'\n 'frozen %s\\nmax orbital idx %s' % (kpt_idx, frozen, len(mo_occ) - 1))\n\n\ndef get_nocc(mp, per_kpoint=False):\n '''Number of occupied orbitals for k-point calculations.\n\n Number of occupied orbitals for use in a calculation with k-points, taking into\n account frozen orbitals.\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n per_kpoint (bool, optional): True returns the number of occupied\n orbitals at each k-point. False gives the max of this list.\n\n Returns:\n nocc (int, list of int): Number of occupied orbitals. For return type, see description of arg\n `per_kpoint`.\n\n '''\n for i, moocc in enumerate(mp.mo_occ):\n if np.any(moocc % 1 != 0):\n raise RuntimeError(\"Fractional occupation numbers encountered @ kp={:d}: {}. This may have been caused by \"\n \"smearing of occupation numbers in the mean-field calculation. If so, consider \"\n \"executing mf.smearing_method = False; mf.mo_occ = mf.get_occ() prior to calling \"\n \"this\".format(i, moocc))\n if mp._nocc is not None:\n return mp._nocc\n elif mp.frozen is None:\n nocc = [np.count_nonzero(mp.mo_occ[ikpt]) for ikpt in range(mp.nkpts)]\n elif isinstance(mp.frozen, (int, np.integer)):\n nocc = [(np.count_nonzero(mp.mo_occ[ikpt]) - mp.frozen) for ikpt in range(mp.nkpts)]\n elif isinstance(mp.frozen[0], (int, np.integer)):\n [_frozen_sanity_check(mp.frozen, mp.mo_occ[ikpt], ikpt) for ikpt in range(mp.nkpts)]\n nocc = []\n for ikpt in range(mp.nkpts):\n max_occ_idx = np.max(np.where(mp.mo_occ[ikpt] > 0))\n frozen_nocc = np.sum(np.array(mp.frozen) <= max_occ_idx)\n nocc.append(np.count_nonzero(mp.mo_occ[ikpt]) - frozen_nocc)\n elif isinstance(mp.frozen[0], (list, np.ndarray)):\n nkpts = len(mp.frozen)\n if nkpts != mp.nkpts:\n raise RuntimeError('Frozen list has a different number of k-points (length) than passed in mean-field/'\n 'correlated calculation. \\n\\nCalculation nkpts = %d, frozen list = %s '\n '(length = %d)' % (mp.nkpts, mp.frozen, nkpts))\n [_frozen_sanity_check(frozen, mo_occ, ikpt) for ikpt, frozen, mo_occ in zip(range(nkpts), mp.frozen, mp.mo_occ)]\n\n nocc = []\n for ikpt, frozen in enumerate(mp.frozen):\n max_occ_idx = np.max(np.where(mp.mo_occ[ikpt] > 0))\n frozen_nocc = np.sum(np.array(frozen) <= max_occ_idx)\n nocc.append(np.count_nonzero(mp.mo_occ[ikpt]) - frozen_nocc)\n else:\n raise NotImplementedError\n\n assert any(np.array(nocc) > 0), ('Must have occupied orbitals! \\n\\nnocc %s\\nfrozen %s\\nmo_occ %s' %\n (nocc, mp.frozen, mp.mo_occ))\n\n if not per_kpoint:\n nocc = np.amax(nocc)\n\n return nocc\n\n\ndef get_nmo(mp, per_kpoint=False):\n '''Number of orbitals for k-point calculations.\n\n Number of orbitals for use in a calculation with k-points, taking into account\n frozen orbitals.\n\n Note:\n If `per_kpoint` is False, then the number of orbitals here is equal to max(nocc) + max(nvir),\n where each max is done over all k-points. Otherwise the number of orbitals is returned\n as a list of number of orbitals at each k-point.\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n per_kpoint (bool, optional): True returns the number of orbitals at each k-point.\n For a description of False, see Note.\n\n Returns:\n nmo (int, list of int): Number of orbitals. For return type, see description of arg\n `per_kpoint`.\n\n '''\n if mp._nmo is not None:\n return mp._nmo\n\n if mp.frozen is None:\n nmo = [len(mp.mo_occ[ikpt]) for ikpt in range(mp.nkpts)]\n elif isinstance(mp.frozen, (int, np.integer)):\n nmo = [len(mp.mo_occ[ikpt]) - mp.frozen for ikpt in range(mp.nkpts)]\n elif isinstance(mp.frozen[0], (int, np.integer)):\n [_frozen_sanity_check(mp.frozen, mp.mo_occ[ikpt], ikpt) for ikpt in range(mp.nkpts)]\n nmo = [len(mp.mo_occ[ikpt]) - len(mp.frozen) for ikpt in range(mp.nkpts)]\n elif isinstance(mp.frozen, (list, np.ndarray)):\n nkpts = len(mp.frozen)\n if nkpts != mp.nkpts:\n raise RuntimeError('Frozen list has a different number of k-points (length) than passed in mean-field/'\n 'correlated calculation. \\n\\nCalculation nkpts = %d, frozen list = %s '\n '(length = %d)' % (mp.nkpts, mp.frozen, nkpts))\n [_frozen_sanity_check(fro, mo_occ, ikpt) for ikpt, fro, mo_occ in zip(range(nkpts), mp.frozen, mp.mo_occ)]\n\n nmo = [len(mp.mo_occ[ikpt]) - len(mp.frozen[ikpt]) for ikpt in range(nkpts)]\n else:\n raise NotImplementedError\n\n assert all(np.array(nmo) > 0), ('Must have a positive number of orbitals!\\n\\nnmo %s\\nfrozen %s\\nmo_occ %s' %\n (nmo, mp.frozen, mp.mo_occ))\n\n if not per_kpoint:\n # Depending on whether there are more occupied bands, we want to make sure that\n # nmo has enough room for max(nocc) + max(nvir) number of orbitals for occupied\n # and virtual space\n nocc = mp.get_nocc(per_kpoint=True)\n nmo = np.max(nocc) + np.max(np.array(nmo) - np.array(nocc))\n\n return nmo\n\n\ndef get_frozen_mask(mp):\n '''Boolean mask for orbitals in k-point post-HF method.\n\n Creates a boolean mask to remove frozen orbitals and keep other orbitals for post-HF\n calculations.\n\n Args:\n mp (:class:`MP2`): An instantiation of an SCF or post-Hartree-Fock object.\n\n Returns:\n moidx (list of :obj:`ndarray` of `np.bool`): Boolean mask of orbitals to include.\n\n '''\n moidx = [np.ones(x.size, dtype=np.bool) for x in mp.mo_occ]\n if mp.frozen is None:\n pass\n elif isinstance(mp.frozen, (int, np.integer)):\n for idx in moidx:\n idx[:mp.frozen] = False\n elif isinstance(mp.frozen[0], (int, np.integer)):\n frozen = list(mp.frozen)\n for idx in moidx:\n idx[frozen] = False\n elif isinstance(mp.frozen[0], (list, np.ndarray)):\n nkpts = len(mp.frozen)\n if nkpts != mp.nkpts:\n raise RuntimeError('Frozen list has a different number of k-points (length) than passed in mean-field/'\n 'correlated calculation. \\n\\nCalculation nkpts = %d, frozen list = %s '\n '(length = %d)' % (mp.nkpts, mp.frozen, nkpts))\n [_frozen_sanity_check(fro, mo_occ, ikpt) for ikpt, fro, mo_occ in zip(range(nkpts), mp.frozen, mp.mo_occ)]\n for ikpt, kpt_occ in enumerate(moidx):\n kpt_occ[mp.frozen[ikpt]] = False\n else:\n raise NotImplementedError\n\n return moidx\n\n\ndef _add_padding(mp, mo_coeff, mo_energy):\n from pyscf.pbc import tools\n from pyscf.pbc.cc.ccsd import _adjust_occ\n nmo = mp.nmo\n nocc = mp.nocc\n nvir = nmo - nocc\n nkpts = mp.nkpts\n\n # Check if these are padded mo coefficients and energies\n if not np.all([x.shape[0] == nmo for x in mo_coeff]):\n mo_coeff = padded_mo_coeff(mp, mo_coeff)\n\n if not np.all([x.shape[0] == nmo for x in mo_energy]):\n mo_energy = padded_mo_energy(mp, mo_energy)\n return mo_coeff, mo_energy\n\n\ndef make_rdm1(mp, t2=None, kind=\"compact\"):\n r\"\"\"\n Spin-traced one-particle density matrix in the MO basis representation.\n The occupied-virtual orbital response is not included.\n\n dm1[p,q] = <q_alpha^\\dagger p_alpha> + <q_beta^\\dagger p_beta>\n\n The convention of 1-pdm is based on McWeeney's book, Eq (5.4.20).\n The contraction between 1-particle Hamiltonian and rdm1 is\n E = einsum('pq,qp', h1, rdm1)\n\n Args:\n mp (KMP2): a KMP2 kernel object;\n t2 (ndarray): a t2 MP2 tensor;\n kind (str): either 'compact' or 'padded' - defines behavior for k-dependent MO basis sizes;\n\n Returns:\n A k-dependent single-particle density matrix.\n \"\"\"\n if kind not in (\"compact\", \"padded\"):\n raise ValueError(\"The 'kind' argument should be either 'compact' or 'padded'\")\n d_imds = _gamma1_intermediates(mp, t2=t2)\n result = []\n padding_idxs = padding_k_idx(mp, kind=\"joint\")\n for (oo, vv), idxs in zip(zip(*d_imds), padding_idxs):\n oo += np.eye(*oo.shape)\n d = block_diag(oo, vv)\n d += d.conj().T\n if kind == \"padded\":\n result.append(d)\n else:\n result.append(d[np.ix_(idxs, idxs)])\n return result\n\n\ndef _gamma1_intermediates(mp, t2=None):\n # Memory optimization should be here\n if t2 is None:\n t2 = mp.t2\n if t2 is None:\n raise NotImplementedError(\"Run kmp2.kernel with `with_t2=True`\")\n nmo = mp.nmo\n nocc = mp.nocc\n nvir = nmo - nocc\n nkpts = mp.nkpts\n dtype = t2.dtype\n\n dm1occ = np.zeros((nkpts, nocc, nocc), dtype=dtype)\n dm1vir = np.zeros((nkpts, nvir, nvir), dtype=dtype)\n\n for ki in range(nkpts):\n for kj in range(nkpts):\n for ka in range(nkpts):\n kb = mp.khelper.kconserv[ki, ka, kj]\n\n dm1vir[kb] += einsum('ijax,ijay->yx', t2[ki][kj][ka].conj(), t2[ki][kj][ka]) * 2 -\\\n einsum('ijax,ijya->yx', t2[ki][kj][ka].conj(), t2[ki][kj][kb])\n dm1occ[kj] += einsum('ixab,iyab->xy', t2[ki][kj][ka].conj(), t2[ki][kj][ka]) * 2 -\\\n einsum('ixab,iyba->xy', t2[ki][kj][ka].conj(), t2[ki][kj][kb])\n return -dm1occ, dm1vir\n\n\nclass KMP2(mp2.MP2):\n def __init__(self, mf, frozen=None, mo_coeff=None, mo_occ=None):\n\n if mo_coeff is None: mo_coeff = mf.mo_coeff\n if mo_occ is None: mo_occ = mf.mo_occ\n\n self.mol = mf.mol\n self._scf = mf\n self.verbose = self.mol.verbose\n self.stdout = self.mol.stdout\n self.max_memory = mf.max_memory\n\n self.frozen = frozen\n\n##################################################\n# don't modify the following attributes, they are not input options\n self.kpts = mf.kpts\n self.mo_energy = mf.mo_energy\n self.nkpts = len(self.kpts)\n self.khelper = kpts_helper.KptsHelper(mf.cell, mf.kpts)\n self.mo_coeff = mo_coeff\n self.mo_occ = mo_occ\n self._nocc = None\n self._nmo = None\n self.e_corr = None\n self.e_hf = None\n self.t2 = None\n self._keys = set(self.__dict__.keys())\n\n get_nocc = get_nocc\n get_nmo = get_nmo\n get_frozen_mask = get_frozen_mask\n make_rdm1 = make_rdm1\n\n def kernel(self, mo_energy=None, mo_coeff=None, with_t2=WITH_T2):\n if mo_energy is None:\n mo_energy = self.mo_energy\n if mo_coeff is None:\n mo_coeff = self.mo_coeff\n if mo_energy is None or mo_coeff is None:\n log = logger.Logger(self.stdout, self.verbose)\n log.warn('mo_coeff, mo_energy are not given.\\n'\n 'You may need to call mf.kernel() to generate them.')\n raise RuntimeError\n\n mo_coeff, mo_energy = _add_padding(self, mo_coeff, mo_energy)\n\n # TODO: compute e_hf for non-canonical SCF\n self.e_hf = self._scf.e_tot\n\n self.e_corr, self.t2 = \\\n kernel(self, mo_energy, mo_coeff, verbose=self.verbose, with_t2=with_t2)\n logger.log(self, 'KMP2 energy = %.15g', self.e_corr)\n return self.e_corr, self.t2\nKRMP2 = KMP2\n\n\nfrom pyscf.pbc import scf\nscf.khf.KRHF.MP2 = lib.class_as_method(KRMP2)\nscf.kghf.KGHF.MP2 = None\nscf.krohf.KROHF.MP2 = None\n\n\nif __name__ == '__main__':\n from pyscf.pbc import gto, scf, mp\n\n cell = gto.Cell()\n cell.atom='''\n C 0.000000000000 0.000000000000 0.000000000000\n C 1.685068664391 1.685068664391 1.685068664391\n '''\n cell.basis = 'gth-szv'\n cell.pseudo = 'gth-pade'\n cell.a = '''\n 0.000000000, 3.370137329, 3.370137329\n 3.370137329, 0.000000000, 3.370137329\n 3.370137329, 3.370137329, 0.000000000'''\n cell.unit = 'B'\n cell.verbose = 5\n cell.build()\n\n # Running HF and MP2 with 1x1x2 Monkhorst-Pack k-point mesh\n kmf = scf.KRHF(cell, kpts=cell.make_kpts([1,1,2]), exxdiv=None)\n ehf = kmf.kernel()\n\n mymp = mp.KMP2(kmf)\n emp2, t2 = mymp.kernel()\n print(emp2 - -0.204721432828996)\n\n", "# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Samragni Banerjee <[email protected]>\n# Alexander Sokolov <[email protected]>\n#\n\nimport numpy as np\nimport pyscf.ao2mo as ao2mo\n\n### Integral transformation for integrals in Chemists' notation###\ndef transform_integrals_incore(myadc):\n\n occ_a = myadc.mo_coeff[0][:,:myadc._nocc[0]]\n occ_b = myadc.mo_coeff[1][:,:myadc._nocc[1]]\n vir_a = myadc.mo_coeff[0][:,myadc._nocc[0]:]\n vir_b = myadc.mo_coeff[1][:,myadc._nocc[1]:]\n\n nocc_a = occ_a.shape[1]\n nocc_b = occ_b.shape[1]\n nvir_a = vir_a.shape[1]\n nvir_b = vir_b.shape[1]\n n_oo = nocc_a * (nocc_a + 1) // 2\n n_OO = nocc_b * (nocc_b + 1) // 2\n n_vv = nvir_a * (nvir_a + 1) // 2\n n_VV = nvir_b * (nvir_b + 1) // 2\n ind_oo = np.tril_indices(nocc_a)\n ind_vv = np.tril_indices(nvir_a)\n ind_OO = np.tril_indices(nocc_b)\n ind_VV = np.tril_indices(nvir_b)\n \n eris = lambda:None\n\n # TODO: check if myadc._scf._eri is not None\n eris.oooo = ao2mo.general(myadc._scf._eri, (occ_a, occ_a, occ_a, occ_a), compact=False).reshape(nocc_a, nocc_a, nocc_a, nocc_a).copy()\n eris.ovoo = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, occ_a, occ_a), compact=False).reshape(nocc_a, nvir_a, nocc_a, nocc_a).copy()\n eris.ovov = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, occ_a, vir_a), compact=False).reshape(nocc_a, nvir_a, nocc_a, nvir_a).copy()\n eris.ovvo = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, vir_a, occ_a), compact=False).reshape(nocc_a, nvir_a, nvir_a, nocc_a).copy()\n eris.oovv = ao2mo.general(myadc._scf._eri, (occ_a, occ_a, vir_a, vir_a), compact=False).reshape(nocc_a, nocc_a, nvir_a, nvir_a).copy()\n eris.ovvv = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, vir_a, vir_a), compact=True).reshape(nocc_a, nvir_a, -1).copy()\n\n eris.OOOO = ao2mo.general(myadc._scf._eri, (occ_b, occ_b, occ_b, occ_b), compact=False).reshape(nocc_b, nocc_b, nocc_b, nocc_b).copy()\n eris.OVOO = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, occ_b, occ_b), compact=False).reshape(nocc_b, nvir_b, nocc_b, nocc_b).copy()\n eris.OVOV = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, occ_b, vir_b), compact=False).reshape(nocc_b, nvir_b, nocc_b, nvir_b).copy()\n eris.OOVV = ao2mo.general(myadc._scf._eri, (occ_b, occ_b, vir_b, vir_b), compact=False).reshape(nocc_b, nocc_b, nvir_b, nvir_b).copy()\n eris.OVVO = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, vir_b, occ_b), compact=False).reshape(nocc_b, nvir_b, nvir_b, nocc_b).copy()\n eris.OVVV = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, vir_b, vir_b), compact=True).reshape(nocc_b, nvir_b, -1).copy()\n\n eris.ooOO = ao2mo.general(myadc._scf._eri, (occ_a, occ_a, occ_b, occ_b), compact=False).reshape(nocc_a, nocc_a, nocc_b, nocc_b).copy()\n eris.ovOO = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, occ_b, occ_b), compact=False).reshape(nocc_a, nvir_a, nocc_b, nocc_b).copy()\n eris.ovOV = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, occ_b, vir_b), compact=False).reshape(nocc_a, nvir_a, nocc_b, nvir_b).copy()\n eris.ooVV = ao2mo.general(myadc._scf._eri, (occ_a, occ_a, vir_b, vir_b), compact=False).reshape(nocc_a, nocc_a, nvir_b, nvir_b).copy()\n eris.ovVO = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, vir_b, occ_b), compact=False).reshape(nocc_a, nvir_a, nvir_b, nocc_b).copy()\n eris.ovVV = ao2mo.general(myadc._scf._eri, (occ_a, vir_a, vir_b, vir_b), compact=True).reshape(nocc_a, nvir_a, -1).copy()\n\n eris.OVoo = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, occ_a, occ_a), compact=False).reshape(nocc_b, nvir_b, nocc_a, nocc_a).copy()\n eris.OOvv = ao2mo.general(myadc._scf._eri, (occ_b, occ_b, vir_a, vir_a), compact=False).reshape(nocc_b, nocc_b, nvir_a, nvir_a).copy()\n eris.OVov = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, occ_a, vir_a), compact=False).reshape(nocc_b, nvir_b, nocc_a, nvir_a).copy()\n eris.OVvo = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, vir_a, occ_a), compact=False).reshape(nocc_b, nvir_b, nvir_a, nocc_a).copy()\n eris.OVvv = ao2mo.general(myadc._scf._eri, (occ_b, vir_b, vir_a, vir_a), compact=True).reshape(nocc_b, nvir_b, -1).copy()\n\n if (myadc.method == \"adc(2)-x\" or myadc.method == \"adc(3)\"):\n eris.vvvv = ao2mo.general(myadc._scf._eri, (vir_a, vir_a, vir_a, vir_a), compact=True)\n eris.VVVV = ao2mo.general(myadc._scf._eri, (vir_b, vir_b, vir_b, vir_b), compact=True)\n eris.vvVV = ao2mo.general(myadc._scf._eri, (vir_a, vir_a, vir_b, vir_b), compact=True)\n\n return eris\n\ndef unpack_eri_1(eri, norb):\n\n n_oo = norb * (norb + 1) // 2\n ind_oo = np.tril_indices(norb)\n\n eri_ = None\n\n if len(eri.shape) == 3:\n if (eri.shape[0] == n_oo):\n eri_ = np.zeros((norb, norb, eri.shape[1], eri.shape[2]))\n eri_[ind_oo[0], ind_oo[1]] = eri\n eri_[ind_oo[1], ind_oo[0]] = eri\n\n elif (eri.shape[2] == n_oo):\n eri_ = np.zeros((eri.shape[0], eri.shape[1], norb, norb))\n eri_[:, :, ind_oo[0], ind_oo[1]] = eri\n eri_[:, :, ind_oo[1], ind_oo[0]] = eri\n else:\n raise TypeError(\"ERI dimensions don't match\")\n\n else: \n raise RuntimeError(\"ERI does not have a correct dimension\")\n\n return eri_\n\ndef unpack_eri_2s(eri, norb):\n\n n_oo = norb * (norb + 1) // 2\n ind_oo = np.tril_indices(norb)\n\n eri_ = None\n\n if len(eri.shape) == 2:\n if (eri.shape[0] != n_oo or eri.shape[1] != n_oo):\n raise TypeError(\"ERI dimensions don't match\")\n\n temp = np.zeros((n_oo, norb, norb))\n temp[:, ind_oo[0], ind_oo[1]] = eri\n temp[:, ind_oo[1], ind_oo[0]] = eri\n eri_ = np.zeros((norb, norb, norb, norb))\n eri_[ind_oo[0], ind_oo[1]] = temp\n eri_[ind_oo[1], ind_oo[0]] = temp\n else: \n raise RuntimeError(\"ERI does not have a correct dimension\")\n\n return eri_\n\ndef unpack_eri_2(eri, norb1, norb2):\n\n n_oo1 = norb1 * (norb1 + 1) // 2\n ind_oo1 = np.tril_indices(norb1)\n n_oo2 = norb2 * (norb2 + 1) // 2\n ind_oo2 = np.tril_indices(norb2)\n\n eri_ = None\n\n if len(eri.shape) == 2:\n if (eri.shape[0] != n_oo1 or eri.shape[1] != n_oo2):\n raise TypeError(\"ERI dimensions don't match\")\n\n temp = np.zeros((n_oo1, norb2, norb2))\n temp[:, ind_oo2[0], ind_oo2[1]] = eri\n temp[:, ind_oo2[1], ind_oo2[0]] = eri\n eri_ = np.zeros((norb1, norb1, norb2, norb2))\n eri_[ind_oo1[0], ind_oo1[1]] = temp\n eri_[ind_oo1[1], ind_oo1[0]] = temp\n else: \n raise RuntimeError(\"ERI does not have a correct dimension\")\n\n return eri_\n", "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <[email protected]>\n#\n\nimport time\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.cc import _ccsd\n\n'''\nR-CCSD(T)\n'''\n\n# t3 as ijkabc\n\n# JCP, 94, 442. Error in Eq (1), should be [ia] >= [jb] >= [kc]\ndef kernel(mycc, eris, t1=None, t2=None, verbose=logger.NOTE):\n if isinstance(verbose, logger.Logger):\n log = verbose\n else:\n log = logger.Logger(mycc.stdout, verbose)\n\n if t1 is None: t1 = mycc.t1\n if t2 is None: t2 = mycc.t2\n\n t1T = t1.T\n t2T = t2.transpose(2,3,0,1)\n\n nocc, nvir = t1.shape\n nmo = nocc + nvir\n mo_e = eris.fock.diagonal()\n e_occ, e_vir = mo_e[:nocc], mo_e[nocc:]\n eijk = lib.direct_sum('i,j,k->ijk', e_occ, e_occ, e_occ)\n\n eris_vvov = eris.get_ovvv().conj().transpose(1,3,0,2)\n eris_vooo = numpy.asarray(eris.ovoo).conj().transpose(1,0,3,2)\n eris_vvoo = numpy.asarray(eris.ovov).conj().transpose(1,3,0,2)\n fvo = eris.fock[nocc:,:nocc]\n def get_w(a, b, c):\n w = numpy.einsum('if,fkj->ijk', eris_vvov[a,b], t2T[c,:])\n w-= numpy.einsum('ijm,mk->ijk', eris_vooo[a,:], t2T[b,c])\n return w\n def get_v(a, b, c):\n v = numpy.einsum('ij,k->ijk', eris_vvoo[a,b], t1T[c])\n v+= numpy.einsum('ij,k->ijk', t2T[a,b], fvo[c])\n return v\n\n et = 0\n for a in range(nvir):\n for b in range(a+1):\n for c in range(b+1):\n d3 = eijk - e_vir[a] - e_vir[b] - e_vir[c]\n if a == c: # a == b == c\n d3 *= 6\n elif a == b or b == c:\n d3 *= 2\n\n wabc = get_w(a, b, c)\n wacb = get_w(a, c, b)\n wbac = get_w(b, a, c)\n wbca = get_w(b, c, a)\n wcab = get_w(c, a, b)\n wcba = get_w(c, b, a)\n vabc = get_v(a, b, c)\n vacb = get_v(a, c, b)\n vbac = get_v(b, a, c)\n vbca = get_v(b, c, a)\n vcab = get_v(c, a, b)\n vcba = get_v(c, b, a)\n zabc = r3(wabc + .5 * vabc) / d3\n zacb = r3(wacb + .5 * vacb) / d3\n zbac = r3(wbac + .5 * vbac) / d3\n zbca = r3(wbca + .5 * vbca) / d3\n zcab = r3(wcab + .5 * vcab) / d3\n zcba = r3(wcba + .5 * vcba) / d3\n\n et+= numpy.einsum('ijk,ijk', wabc, zabc.conj())\n et+= numpy.einsum('ikj,ijk', wacb, zabc.conj())\n et+= numpy.einsum('jik,ijk', wbac, zabc.conj())\n et+= numpy.einsum('jki,ijk', wbca, zabc.conj())\n et+= numpy.einsum('kij,ijk', wcab, zabc.conj())\n et+= numpy.einsum('kji,ijk', wcba, zabc.conj())\n\n et+= numpy.einsum('ijk,ijk', wacb, zacb.conj())\n et+= numpy.einsum('ikj,ijk', wabc, zacb.conj())\n et+= numpy.einsum('jik,ijk', wcab, zacb.conj())\n et+= numpy.einsum('jki,ijk', wcba, zacb.conj())\n et+= numpy.einsum('kij,ijk', wbac, zacb.conj())\n et+= numpy.einsum('kji,ijk', wbca, zacb.conj())\n\n et+= numpy.einsum('ijk,ijk', wbac, zbac.conj())\n et+= numpy.einsum('ikj,ijk', wbca, zbac.conj())\n et+= numpy.einsum('jik,ijk', wabc, zbac.conj())\n et+= numpy.einsum('jki,ijk', wacb, zbac.conj())\n et+= numpy.einsum('kij,ijk', wcba, zbac.conj())\n et+= numpy.einsum('kji,ijk', wcab, zbac.conj())\n\n et+= numpy.einsum('ijk,ijk', wbca, zbca.conj())\n et+= numpy.einsum('ikj,ijk', wbac, zbca.conj())\n et+= numpy.einsum('jik,ijk', wcba, zbca.conj())\n et+= numpy.einsum('jki,ijk', wcab, zbca.conj())\n et+= numpy.einsum('kij,ijk', wabc, zbca.conj())\n et+= numpy.einsum('kji,ijk', wacb, zbca.conj())\n\n et+= numpy.einsum('ijk,ijk', wcab, zcab.conj())\n et+= numpy.einsum('ikj,ijk', wcba, zcab.conj())\n et+= numpy.einsum('jik,ijk', wacb, zcab.conj())\n et+= numpy.einsum('jki,ijk', wabc, zcab.conj())\n et+= numpy.einsum('kij,ijk', wbca, zcab.conj())\n et+= numpy.einsum('kji,ijk', wbac, zcab.conj())\n\n et+= numpy.einsum('ijk,ijk', wcba, zcba.conj())\n et+= numpy.einsum('ikj,ijk', wcab, zcba.conj())\n et+= numpy.einsum('jik,ijk', wbca, zcba.conj())\n et+= numpy.einsum('jki,ijk', wbac, zcba.conj())\n et+= numpy.einsum('kij,ijk', wacb, zcba.conj())\n et+= numpy.einsum('kji,ijk', wabc, zcba.conj())\n et *= 2\n\n # denominator\n def get_y(a, b, c):\n y = numpy.einsum('i,j,k->ijk', t1T[a], t1T[b], t1T[c])\n y+= numpy.einsum('i,jk->ijk', t1T[a], t2T[b,c])\n y+= numpy.einsum('j,ik->ijk', t1T[b], t2T[a,c])\n y+= numpy.einsum('k,ij->ijk', t1T[c], t2T[a,b])\n return y \n\n denom = 0.5\n denom+= numpy.einsum('ia,ia', t1, t1)\n tmpt = t2 - 0.5*t2.transpose(0,1,3,2)\n tmpc = t2 + numpy.einsum('ia,jb->ijab', t1, t1) \n denom+= numpy.einsum('ijab,ijab', tmpt, tmpc)\n for a in range(nvir):\n for b in range(a+1):\n for c in range(b+1):\n d3 = eijk - e_vir[a] - e_vir[b] - e_vir[c]\n if a == c: # a == b == c\n d3 *= 6\n elif a == b or b == c:\n d3 *= 2\n\n wabc = get_w(a, b, c)\n wacb = get_w(a, c, b)\n wbac = get_w(b, a, c)\n wbca = get_w(b, c, a)\n wcab = get_w(c, a, b)\n wcba = get_w(c, b, a)\n vabc = get_v(a, b, c)\n vacb = get_v(a, c, b)\n vbac = get_v(b, a, c)\n vbca = get_v(b, c, a)\n vcab = get_v(c, a, b)\n vcba = get_v(c, b, a)\n zabc = r3(wabc + .5 * vabc) / d3\n zacb = r3(wacb + .5 * vacb) / d3\n zbac = r3(wbac + .5 * vbac) / d3\n zbca = r3(wbca + .5 * vbca) / d3\n zcab = r3(wcab + .5 * vcab) / d3\n zcba = r3(wcba + .5 * vcba) / d3\n yabc = get_y(a, b, c)\n yacb = get_y(a, c, b)\n ybac = get_y(b, a, c)\n ybca = get_y(b, c, a)\n ycab = get_y(c, a, b)\n ycba = get_y(c, b, a)\n\n denom+= numpy.einsum('ijk,ijk', yabc, zabc.conj())\n denom+= numpy.einsum('ikj,ijk', yacb, zabc.conj())\n denom+= numpy.einsum('jik,ijk', ybac, zabc.conj())\n denom+= numpy.einsum('jki,ijk', ybca, zabc.conj())\n denom+= numpy.einsum('kij,ijk', ycab, zabc.conj())\n denom+= numpy.einsum('kji,ijk', ycba, zabc.conj())\n\n denom+= numpy.einsum('ijk,ijk', yacb, zacb.conj())\n denom+= numpy.einsum('ikj,ijk', yabc, zacb.conj())\n denom+= numpy.einsum('jik,ijk', ycab, zacb.conj())\n denom+= numpy.einsum('jki,ijk', ycba, zacb.conj())\n denom+= numpy.einsum('kij,ijk', ybac, zacb.conj())\n denom+= numpy.einsum('kji,ijk', ybca, zacb.conj())\n\n denom+= numpy.einsum('ijk,ijk', ybac, zbac.conj())\n denom+= numpy.einsum('ikj,ijk', ybca, zbac.conj())\n denom+= numpy.einsum('jik,ijk', yabc, zbac.conj())\n denom+= numpy.einsum('jki,ijk', yacb, zbac.conj())\n denom+= numpy.einsum('kij,ijk', ycba, zbac.conj())\n denom+= numpy.einsum('kji,ijk', ycab, zbac.conj())\n\n denom+= numpy.einsum('ijk,ijk', ybca, zbca.conj())\n denom+= numpy.einsum('ikj,ijk', ybac, zbca.conj())\n denom+= numpy.einsum('jik,ijk', ycba, zbca.conj())\n denom+= numpy.einsum('jki,ijk', ycab, zbca.conj())\n denom+= numpy.einsum('kij,ijk', yabc, zbca.conj())\n denom+= numpy.einsum('kji,ijk', yacb, zbca.conj())\n\n denom+= numpy.einsum('ijk,ijk', ycab, zcab.conj())\n denom+= numpy.einsum('ikj,ijk', ycba, zcab.conj())\n denom+= numpy.einsum('jik,ijk', yacb, zcab.conj())\n denom+= numpy.einsum('jki,ijk', yabc, zcab.conj())\n denom+= numpy.einsum('kij,ijk', ybca, zcab.conj())\n denom+= numpy.einsum('kji,ijk', ybac, zcab.conj())\n\n denom+= numpy.einsum('ijk,ijk', ycba, zcba.conj())\n denom+= numpy.einsum('ikj,ijk', ycab, zcba.conj())\n denom+= numpy.einsum('jik,ijk', ybca, zcba.conj())\n denom+= numpy.einsum('jki,ijk', ybac, zcba.conj())\n denom+= numpy.einsum('kij,ijk', yacb, zcba.conj())\n denom+= numpy.einsum('kji,ijk', yabc, zcba.conj())\n denom *= 2\n\n print('denominator:', denom)\n log.info('R-CCSD(T) correction = %.15g', et/denom)\n return et/denom\n\ndef r3(w):\n return (4 * w + w.transpose(1,2,0) + w.transpose(2,0,1)\n - 2 * w.transpose(2,1,0) - 2 * w.transpose(0,2,1)\n - 2 * w.transpose(1,0,2))\n\n\nif __name__ == '__main__':\n from pyscf import gto\n from pyscf import scf\n from pyscf import cc\n\n mol = gto.M()\n numpy.random.seed(12)\n nocc, nvir = 5, 12\n eris = cc.ccsd._ChemistsERIs()\n eris.ovvv = numpy.random.random((nocc,nvir,nvir*(nvir+1)//2)) * .1\n eris.ovoo = numpy.random.random((nocc,nvir,nocc,nocc)) * .1\n eris.ovov = numpy.random.random((nocc,nvir,nocc,nvir)) * .1\n t1 = numpy.random.random((nocc,nvir)) * .1\n t2 = numpy.random.random((nocc,nocc,nvir,nvir)) * .1\n t2 = t2 + t2.transpose(1,0,3,2)\n mf = scf.RHF(mol)\n mcc = cc.CCSD(mf)\n f = numpy.random.random((nocc+nvir,nocc+nvir)) * .1\n eris.fock = f+f.T + numpy.diag(numpy.arange(nocc+nvir))\n print(kernel(mcc, eris, t1, t2) - -8.0038781018306828)\n\n mol = gto.Mole()\n mol.atom = [\n [8 , (0. , 0. , 0.)],\n [1 , (0. , -.957 , .587)],\n [1 , (0.2, .757 , .487)]]\n\n mol.basis = 'ccpvdz'\n mol.build()\n rhf = scf.RHF(mol)\n rhf.conv_tol = 1e-14\n rhf.scf()\n mcc = cc.CCSD(rhf)\n mcc.conv_tol = 1e-12\n mcc.ccsd()\n\n e3a = kernel(mcc, mcc.ao2mo())\n print(e3a - -0.0033300722698513989)\n" ]
[ [ "numpy.amax", "numpy.ix_", "numpy.conj", "scipy.linalg.block_diag", "numpy.unique", "numpy.einsum", "numpy.arange", "numpy.eye", "numpy.ones", "numpy.all", "numpy.max", "numpy.any", "numpy.count_nonzero", "numpy.array", "numpy.zeros", "numpy.where" ], [ "numpy.tril_indices", "numpy.zeros" ], [ "numpy.random.random", "numpy.random.seed", "numpy.einsum", "numpy.asarray", "numpy.arange" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kpertsch/softlearning
[ "e437995b707771f745e1fe4ca464e076292756ca", "14759ce1b617d91f6ebc45c3297cc27e8480877d", "14759ce1b617d91f6ebc45c3297cc27e8480877d" ]
[ "softlearning/environments/dm_control/suite/wrappers/action_scale_test.py", "tests/softlearning/examples/development/main_test.py", "softlearning/utils/tensorflow.py" ]
[ "import pytest\nimport numpy as np\nfrom dm_control import suite\n\nfrom action_scale import Wrapper as ActionScaleWrapper\n\n\ndef test_scale_action():\n seed = 0\n unwrapped_env = suite.load(\n domain_name=\"quadruped\", task_name=\"run\",\n task_kwargs={\"random\": seed})\n assert np.any(np.not_equal(unwrapped_env.action_spec().minimum, -1.0))\n assert np.any(np.not_equal(unwrapped_env.action_spec().maximum, 1.0))\n\n wrapped_env = ActionScaleWrapper(\n suite.load(\n domain_name=\"quadruped\",\n task_name=\"run\",\n task_kwargs={\"random\": seed}),\n minimum=-1,\n maximum=1)\n assert np.all(np.equal(wrapped_env.action_spec().minimum, -1.0))\n assert np.all(np.equal(wrapped_env.action_spec().maximum, 1.0))\n\n timestep_unwrapped = unwrapped_env.reset()\n timestep_wrapped = wrapped_env.reset()\n\n assert (set(timestep_unwrapped.observation.keys())\n == set(timestep_wrapped.observation.keys()))\n\n for key in timestep_unwrapped.observation.keys():\n np.testing.assert_allclose(\n timestep_unwrapped.observation[key],\n timestep_wrapped.observation[key])\n\n timestep_unwrapped = unwrapped_env.step(\n unwrapped_env.action_spec().maximum)\n\n assert np.any(\n wrapped_env.action_spec().maximum < unwrapped_env.action_spec().maximum)\n with pytest.raises(AssertionError):\n wrapped_env.step(unwrapped_env.action_spec().maximum)\n\n timestep_wrapped = wrapped_env.step(\n np.ones_like(unwrapped_env.action_spec().maximum))\n\n for key in timestep_unwrapped.observation.keys():\n np.testing.assert_allclose(\n timestep_unwrapped.observation[key],\n timestep_wrapped.observation[key])\n\n assert np.allclose(timestep_wrapped.reward, timestep_unwrapped.reward)\n", "import copy\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom examples.development.main import ExperimentRunner\n\nCONFIG = {\n 'Q_params': {\n 'kwargs': {\n 'hidden_layer_sizes': (10, 10),\n },\n 'type': 'double_feedforward_Q_function'\n },\n 'algorithm_params': {\n 'kwargs': {\n 'action_prior': 'uniform',\n 'discount': 0.99,\n 'epoch_length': 20,\n 'eval_deterministic': True,\n 'eval_n_episodes': 1,\n 'eval_render_kwargs': {},\n 'lr': 0.0003,\n 'n_epochs': 301,\n 'n_initial_exploration_steps': 10,\n 'n_train_repeat': 1,\n 'reward_scale': 1.0,\n 'save_full_state': False,\n 'target_entropy': 'auto',\n 'target_update_interval': 1,\n 'tau': 0.005,\n 'train_every_n_steps': 1\n },\n 'type': 'SAC'\n },\n 'environment_params': {\n 'training': {\n 'universe': 'gym',\n 'domain': 'Swimmer',\n 'task': 'v3',\n 'kwargs': {},\n },\n },\n 'git_sha':\n 'fb03db4b0ffafc61d8ea6d550e7fdebeecb34d15 '\n 'refactor/pick-utils-changes',\n 'mode':\n 'local',\n 'policy_params': {\n 'kwargs': {\n 'hidden_layer_sizes': (10, 10),\n 'squash': True\n },\n 'type': 'GaussianPolicy'\n },\n 'exploration_policy_params': {\n 'kwargs': {},\n 'type': 'UniformPolicy'\n },\n 'replay_pool_params': {\n 'kwargs': {\n 'max_size': 1000\n },\n 'type': 'SimpleReplayPool'\n },\n 'run_params': {\n 'checkpoint_at_end': True,\n 'checkpoint_frequency': 60,\n 'seed': 5666\n },\n 'sampler_params': {\n 'kwargs': {\n 'batch_size': 256,\n 'max_path_length': 10,\n 'min_pool_size': 15\n },\n 'type': 'SimpleSampler'\n },\n}\n\n\ndef assert_weights_not_equal(weights1, weights2):\n for weight1, weight2 in zip(weights1, weights2):\n assert not np.all(np.equal(weight1, weight2))\n\n\nclass TestExperimentRunner(tf.test.TestCase):\n\n def test_checkpoint_dict(self):\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n config = copy.deepcopy(CONFIG)\n\n experiment_runner = ExperimentRunner(config=config)\n\n session = experiment_runner._session\n experiment_runner._build()\n\n self.assertEqual(experiment_runner.algorithm._epoch, 0)\n self.assertEqual(experiment_runner.algorithm._timestep, 0)\n self.assertEqual(experiment_runner.algorithm._total_timestep, 0)\n self.assertFalse(experiment_runner.algorithm._training_started)\n\n self.assertEqual(experiment_runner.replay_pool.size, 0)\n self.assertEqual(session.run(experiment_runner.algorithm._alpha), 1.0)\n\n initial_policy_weights = experiment_runner.policy.get_weights()\n initial_Qs_weights = [Q.get_weights() for Q in experiment_runner.Qs]\n\n for i in range(10):\n experiment_runner.train()\n\n self.assertEqual(experiment_runner.algorithm._epoch, 9)\n self.assertEqual(experiment_runner.algorithm._timestep, 20)\n self.assertEqual(experiment_runner.algorithm._total_timestep, 200)\n self.assertTrue(experiment_runner.algorithm._training_started)\n self.assertNotEqual(\n session.run(experiment_runner.algorithm._alpha), 1.0)\n\n self.assertEqual(experiment_runner.replay_pool.size, 210)\n\n policy_weights = experiment_runner.policy.get_weights()\n Qs_weights = [Q.get_weights() for Q in experiment_runner.Qs]\n\n # Make sure that the training changed all the weights\n assert_weights_not_equal(initial_policy_weights, policy_weights)\n\n for initial_Q_weights, Q_weights in zip(initial_Qs_weights, Qs_weights):\n assert_weights_not_equal(initial_Q_weights, Q_weights)\n\n expected_alpha_value = 5.0\n session.run(\n tf.assign(experiment_runner.algorithm._log_alpha,\n np.log(expected_alpha_value)))\n self.assertEqual(\n session.run(experiment_runner.algorithm._alpha),\n expected_alpha_value)\n\n trainable_variables_1 = {\n 'policy': experiment_runner.policy.trainable_variables,\n 'Q0': experiment_runner.Qs[0].trainable_variables,\n 'Q1': experiment_runner.Qs[1].trainable_variables,\n 'target_Q0': (\n experiment_runner.algorithm._Q_targets[0].trainable_variables),\n 'target_Q1': (\n experiment_runner.algorithm._Q_targets[1].trainable_variables),\n 'log_alpha': [experiment_runner.algorithm._log_alpha],\n }\n trainable_variables_1_np = session.run(trainable_variables_1)\n\n assert set(\n variable\n for _, variables in trainable_variables_1.items()\n for variable in variables\n ) == set(\n variable for variable in tf.trainable_variables()\n if 'save_counter' not in variable.name)\n\n optimizer_variables_1 = {\n 'Q_optimizer_1': (\n experiment_runner.algorithm._Q_optimizers[0].variables()),\n 'Q_optimizer_2': (\n experiment_runner.algorithm._Q_optimizers[1].variables()),\n 'policy_optimizer': (\n experiment_runner.algorithm._policy_optimizer.variables()),\n 'alpha_optimizer': (\n experiment_runner.algorithm._alpha_optimizer.variables()),\n }\n optimizer_variables_1_np = session.run(optimizer_variables_1)\n\n checkpoint = experiment_runner.save()\n\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n experiment_runner_2 = ExperimentRunner(config=config)\n session = experiment_runner_2._session\n self.assertFalse(experiment_runner_2._built)\n\n experiment_runner_2.restore(checkpoint)\n\n trainable_variables_2 = {\n 'policy': experiment_runner_2.policy.trainable_variables,\n 'Q0': experiment_runner_2.Qs[0].trainable_variables,\n 'Q1': experiment_runner_2.Qs[1].trainable_variables,\n 'target_Q0': (\n experiment_runner_2.algorithm._Q_targets[0].trainable_variables\n ),\n 'target_Q1': (\n experiment_runner_2.algorithm._Q_targets[1].trainable_variables\n ),\n 'log_alpha': [experiment_runner_2.algorithm._log_alpha],\n }\n trainable_variables_2_np = session.run(trainable_variables_2)\n\n assert set(\n variable\n for _, variables in trainable_variables_2.items()\n for variable in variables\n ) == set(\n variable for variable in tf.trainable_variables()\n if 'save_counter' not in variable.name)\n\n optimizer_variables_2 = {\n 'Q_optimizer_1': (\n experiment_runner_2.algorithm._Q_optimizers[0].variables()),\n 'Q_optimizer_2': (\n experiment_runner_2.algorithm._Q_optimizers[1].variables()),\n 'policy_optimizer': (\n experiment_runner_2.algorithm._policy_optimizer.variables()),\n 'alpha_optimizer': (\n experiment_runner_2.algorithm._alpha_optimizer.variables()),\n }\n optimizer_variables_2_np = session.run(optimizer_variables_2)\n\n for i, (key, variables_1_np) in enumerate(trainable_variables_1_np.items()):\n print()\n variables_1_tf = trainable_variables_1[key]\n variables_2_tf = trainable_variables_2[key]\n variables_2_np = trainable_variables_2_np[key]\n for j, (variable_1_np, variable_2_np,\n variable_1_tf, variable_2_tf) in enumerate(\n zip(variables_1_np, variables_2_np,\n variables_1_tf, variables_2_tf)):\n allclose = np.allclose(variable_1_np, variable_2_np)\n variable_1_name = variable_1_tf.name\n variable_2_name = variable_2_tf.name\n\n print(f\"i: {i}; j: {j}; {key};\"\n f\" {allclose}; {variable_1_name}; {variable_2_name}\")\n\n if 'target_Q' in key:\n pass\n else:\n np.testing.assert_allclose(variable_1_np, variable_2_np)\n\n # for optimizer_key in optimizer_variables_1_np.keys():\n # variables_1_np = optimizer_variables_1_np[optimizer_key]\n # variables_2_np = optimizer_variables_2_np[optimizer_key]\n # for variable_1_np, variable_2_np in zip(\n # variables_1_np, variables_2_np):\n # np.testing.assert_allclose(variable_1_np, variable_2_np)\n\n for i in (0, 1):\n Q_variables_tf = trainable_variables_1[f'Q{i}']\n Q_variables_np = trainable_variables_1_np[f'Q{i}']\n target_Q_variables_tf = trainable_variables_2[f'target_Q{i}']\n target_Q_variables_np = trainable_variables_2_np[f'target_Q{i}']\n\n for j, (Q_np, target_Q_np, Q_tf, target_Q_tf) in enumerate(\n zip(Q_variables_np, target_Q_variables_np,\n Q_variables_tf, target_Q_variables_tf)):\n allclose = np.allclose(Q_np, target_Q_np)\n Q_name = Q_tf.name\n target_Q_name = target_Q_tf.name\n\n # print(f\"i: {i}; {allclose}; {Q_name}; {target_Q_name}\")\n\n self.assertEqual(experiment_runner_2.algorithm._epoch, 10)\n self.assertEqual(experiment_runner_2.algorithm._timestep, 0)\n self.assertEqual(\n session.run(experiment_runner_2.algorithm._alpha),\n expected_alpha_value)\n\n for i in range(10):\n experiment_runner_2.train()\n\n self.assertEqual(experiment_runner_2.algorithm._epoch, 19)\n self.assertEqual(experiment_runner_2.algorithm._timestep, 20)\n self.assertEqual(experiment_runner_2.algorithm._total_timestep, 400)\n self.assertTrue(experiment_runner_2.algorithm._training_started)\n\n def test_checkpoint_pool_reconstruction(self):\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n config = copy.deepcopy(CONFIG)\n\n config['run_params']['checkpoint_replay_pool'] = True\n experiment_runner = ExperimentRunner(config=config)\n\n session = experiment_runner._session\n experiment_runner._build()\n\n self.assertEqual(experiment_runner.algorithm._epoch, 0)\n self.assertEqual(experiment_runner.algorithm._timestep, 0)\n self.assertEqual(experiment_runner.algorithm._total_timestep, 0)\n self.assertFalse(experiment_runner.algorithm._training_started)\n\n self.assertEqual(experiment_runner.replay_pool.size, 0)\n self.assertEqual(session.run(experiment_runner.algorithm._alpha), 1.0)\n\n checkpoints = []\n while (experiment_runner.replay_pool.size\n < experiment_runner.replay_pool._max_size):\n for i in range(10):\n experiment_runner.train()\n checkpoints.append(experiment_runner.save())\n\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n experiment_runner_2 = ExperimentRunner(config=config)\n session = experiment_runner_2._session\n self.assertFalse(experiment_runner_2._built)\n\n experiment_runner_2.restore(checkpoints[-1])\n\n replay_pool_1 = experiment_runner.replay_pool\n replay_pool_2 = experiment_runner_2.replay_pool\n\n self.assertEqual(replay_pool_1._max_size, replay_pool_2._max_size)\n self.assertEqual(replay_pool_1.size, replay_pool_2.size)\n self.assertEqual(replay_pool_2._max_size, replay_pool_2.size)\n self.assertEqual(\n set(replay_pool_1.fields.keys()),\n set(replay_pool_2.fields.keys()))\n\n for field_name in replay_pool_1.fields.keys():\n np.testing.assert_array_equal(\n replay_pool_1.fields[field_name],\n replay_pool_2.fields[field_name])\n\n def test_training_env_evaluation_env(self):\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n config = copy.deepcopy(CONFIG)\n config['environment_params']['evaluation'] = (\n config['environment_params']['training'])\n\n config['run_params']['checkpoint_replay_pool'] = True\n experiment_runner = ExperimentRunner(config=config)\n\n session = experiment_runner._session\n experiment_runner._build()\n\n self.assertIsNot(experiment_runner.training_environment,\n experiment_runner.evaluation_environment)\n\n self.assertEqual(experiment_runner.algorithm._epoch, 0)\n self.assertEqual(experiment_runner.algorithm._timestep, 0)\n self.assertEqual(experiment_runner.algorithm._total_timestep, 0)\n self.assertFalse(experiment_runner.algorithm._training_started)\n\n self.assertEqual(experiment_runner.replay_pool.size, 0)\n self.assertEqual(session.run(experiment_runner.algorithm._alpha), 1.0)\n\n for i in range(2):\n experiment_runner.train()\n\n def test_uses_training_env_as_evaluation_env(self):\n tf.compat.v1.reset_default_graph()\n tf.keras.backend.clear_session()\n self.assertFalse(tf.compat.v1.trainable_variables())\n\n config = copy.deepcopy(CONFIG)\n\n self.assertNotIn('evaluation', config['environment_params'])\n\n config['run_params']['checkpoint_replay_pool'] = True\n experiment_runner = ExperimentRunner(config=config)\n\n session = experiment_runner._session\n experiment_runner._build()\n\n self.assertIs(experiment_runner.training_environment,\n experiment_runner.evaluation_environment)\n\n self.assertEqual(experiment_runner.algorithm._epoch, 0)\n self.assertEqual(experiment_runner.algorithm._timestep, 0)\n self.assertEqual(experiment_runner.algorithm._total_timestep, 0)\n self.assertFalse(experiment_runner.algorithm._training_started)\n\n self.assertEqual(experiment_runner.replay_pool.size, 0)\n self.assertEqual(session.run(experiment_runner.algorithm._alpha), 1.0)\n\n for i in range(2):\n experiment_runner.train()\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "from distutils.version import LooseVersion\n\nimport tensorflow as tf\n\n\nif LooseVersion(tf.__version__) > LooseVersion(\"2.00\"):\n from tensorflow import nest\nelse:\n from tensorflow.contrib.framework import nest\n\n\ndef initialize_tf_variables(session, only_uninitialized=True):\n variables = tf.compat.v1.global_variables() + tf.compat.v1.local_variables()\n\n def is_initialized(variable):\n try:\n session.run(variable)\n return True\n except tf.errors.FailedPreconditionError:\n return False\n\n return False\n\n if only_uninitialized:\n variables = [\n variable for variable in variables\n if not is_initialized(variable)\n ]\n\n session.run(tf.compat.v1.variables_initializer(variables))\n" ]
[ [ "numpy.allclose", "numpy.testing.assert_allclose" ], [ "numpy.log", "numpy.allclose", "tensorflow.compat.v1.trainable_variables", "tensorflow.test.main", "numpy.testing.assert_array_equal", "tensorflow.keras.backend.clear_session", "numpy.equal", "numpy.testing.assert_allclose", "tensorflow.trainable_variables", "tensorflow.compat.v1.reset_default_graph" ], [ "tensorflow.compat.v1.global_variables", "tensorflow.compat.v1.local_variables", "tensorflow.compat.v1.variables_initializer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Bhaskers-Blu-Org2/petridishnn
[ "bf800c695a7f0774106968a0fadc5150074269ad" ]
[ "petridish/analysis/old/model_analysis.py" ]
[ "import numpy as np\nimport re\nimport os\nimport bisect\nfrom petridish.utils.geometry import _convex_hull_from_points\nfrom functools import partial\nimport copy\nimport subprocess\nfrom tensorpack.utils.serialize import loads, dumps\n\nfrom petridish.analysis.old.common import (\n img_dir, ann_models_logs, experiment_list_fn, exp_dir_to_eidx,\n for_cust_exps, for_trial_stdouts, cust_exps_str_to_list,\n ExperimentRecord, cache_dir, filter_xy)\n\nINCLUDE_AUX_MA = False\nREQUIRED_EPOCH = 500\nFORCE_LOAD = False\n\ndef multi_add_from_log(log_fn):\n multi_add = 0.0\n n_params = -1.0\n with open(log_fn, 'rt') as fin:\n for line in fin:\n reret = re.search(r'(.*)multi-add.* ([0-9\\.]*)$', line.strip())\n if reret:\n try:\n prefix_reret = re.search(r'aux_preprocess', reret.group(1))\n if not prefix_reret or INCLUDE_AUX_MA:\n multi_add += float(reret.group(2))\n continue\n except:\n pass\n\n reret = re.search(r'#params=([0-9]*),', line)\n if reret:\n n_params = float(reret.group(1))\n break\n return multi_add, n_params\n\n\ndef val_err_from_log(log_fn):\n def tail(f, n):\n cmd = \"egrep \\\"Epoch ([0-9]*)|val_err: ([0-9\\\\.]*)$\\\" {}\".format(f)\n proc = subprocess.Popen(\n cmd,\n shell=True,\n stdout=subprocess.PIPE)\n lines = proc.stdout.readlines()\n return [line.decode('utf-8') for line in lines]\n\n lines = tail(log_fn, 100)\n min_ve_epoch = -1\n epoch = -1\n min_ve = 2.0\n for line in lines:\n reret = re.search(r'Epoch ([0-9]*)|val_err: ([0-9\\.]*)', line)\n if reret:\n if reret.group(1) is not None:\n try:\n new_epoch = int(reret.group(1))\n if min_ve_epoch == -1 and min_ve < 1.0:\n min_ve_epoch = new_epoch - 1\n epoch = new_epoch\n except:\n pass\n elif reret.group(2) is not None:\n try:\n ve = float(reret.group(2))\n if ve <= min_ve:\n min_ve = ve\n min_ve_epoch = epoch\n except:\n pass\n return min_ve, min_ve_epoch\n\n\ndef perf_from_log(log_fn):\n \"\"\"\n Args:\n log_fn : a stdout file xxx/stdout/triali/stdout.txt\n \"\"\"\n dn = os.path.dirname(log_fn)\n cache_fn = dn.replace('/', '__')\n cache_fn = os.path.join(cache_dir, cache_fn)\n if os.path.exists(cache_fn):\n with open(cache_fn, 'rb') as fin:\n ss = fin.read()\n try:\n ret = loads(ss)\n except:\n pass\n if ret and not FORCE_LOAD:\n return ret\n\n if os.path.exists(log_fn):\n min_ve, min_ve_epoch = val_err_from_log(log_fn)\n multi_add, n_params = multi_add_from_log(log_fn)\n ret = (min_ve, multi_add * 2. * 1e-9, min_ve_epoch)\n with open(cache_fn, 'wb') as fout:\n fout.write(dumps(ret))\n return ret\n else:\n return 2.0, -1.0, -1\n\n\ndef init_state_for_model_perf():\n # min_ve, multi_add, epoch when min_ve\n return []\n\n\ndef func_stdout_for_model_perf(log_fn, state, context):\n if context is not None:\n record = copy.deepcopy(context)\n else:\n context = ExperimentRecord()\n ve, fp, ep = perf_from_log(log_fn)\n record.set_new(ve=ve, fp=fp, ep=ep)\n if ve < 1.0:\n print(record)\n state.append(record)\n return state\n\n\ndef merge_state(state, required_epoch=REQUIRED_EPOCH):\n state = [x for x in state if x.ep > required_epoch]\n state.sort(key=lambda x : x.eidx)\n cnt = 0.0\n avg_ve = 0.0\n min_ve = 2.0\n ret = dict()\n for idx, x in enumerate(state):\n avg_ve += x.ve\n min_ve = min(min_ve, x.ve)\n cnt += 1.0\n if idx == len(state) - 1 or x.eidx != state[idx+1].eidx:\n avg_ve /= cnt + int(cnt < 1)\n ret[x.eidx] = (x.fp, avg_ve, min_ve)\n cnt = 0.0\n avg_ve = 0.0\n min_ve = 2.0\n return ret\n\ndef amoeba_A_scatter_xys():\n def xys_to_xs_ys(xys, name):\n return xys[::2], xys[1::2], name\n\n amoeba_a_xys = xys_to_xs_ys(\n [\n 0.8243604811532328, 3.717231330127244,\n 0.8561252293632995, 3.576010697624216,\n 0.9252184498039169, 3.4887507045800703,\n 0.9434581389491863, 3.4586750296823094,\n 0.9624620126404664, 3.6313001451135123\n ],\n name='Amoeba-A')\n\n amoeba_rl_xys = xys_to_xs_ys(\n [\n 1.092913063813967, 3.527370087427893,\n 1.1475961526929952, 3.474680690308576,\n 1.169610712015639, 3.5061571303503114,\n 1.2213824160800164, 3.491012556516316,\n 1.2270612714821967, 3.566073420241536,\n ],\n name='Amoeba-RL')\n\n amoeba_rand_xys = xys_to_xs_ys(\n [\n 0.950659606874303, 3.9451434944772914,\n 0.9871001283235192, 3.925532782461653,\n 0.9842045740738521, 3.94656104961443,\n 0.9486779079668519, 4.012716021251334,\n 0.9352593454301237, 4.012749601237663,\n ],\n name='Amoeba-Rand')\n\n return [amoeba_a_xys, amoeba_rl_xys, amoeba_rand_xys]\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--find_min', default=False, action='store_true')\n parser.add_argument('--stdout_fn', type=str, default=None)\n parser.add_argument('--log_root', type=str, default=None)\n parser.add_argument('--app_dir', type=str, default=None)\n parser.add_argument('--cust_exps', type=str, default=None)\n parser.add_argument('--include_aux_ma', default=False, action='store_true')\n parser.add_argument('--force_load', default=False, action='store_true')\n parser.add_argument('--required_epochs', default=REQUIRED_EPOCH, type=int)\n parser.add_argument('--plot_scatter', default=False, action='store_true')\n parser.add_argument('--plot_x_min', default=None, type=float)\n parser.add_argument('--plot_x_max', default=None, type=float)\n parser.add_argument('--plot_y_min', default=None, type=float)\n parser.add_argument('--plot_y_max', default=None, type=float)\n args = parser.parse_args()\n\n args.cust_exps = cust_exps_str_to_list(args.cust_exps)\n FORCE_LOAD = args.force_load\n REQUIRED_EPOCH = args.required_epochs\n INCLUDE_AUX_MA = args.include_aux_ma\n\n if args.cust_exps:\n func_exp_dir_for_model_perf = partial(\n for_trial_stdouts,\n func_stdout=func_stdout_for_model_perf\n )\n\n state = for_cust_exps(\n args.cust_exps,\n func_exp_dir_for_model_perf,\n init_state_for_model_perf())\n\n ret_dict = merge_state(state)\n\n #\n if args.plot_scatter:\n import matplotlib.pyplot as plt\n plt.close('all')\n\n fig, ax = plt.subplots()\n eindices = list(ret_dict.keys())\n fp_idx, ve_idx, min_ve_idx = 0, 1, 2\n xs = [ret_dict[eidx][fp_idx] for eidx in eindices]\n y_multiplier = 100.\n ys = [ret_dict[eidx][ve_idx] * y_multiplier for eidx in eindices]\n remain_indices = filter_xy(xs, ys, args)\n xs = [xs[i] for i in remain_indices]\n ys = [ys[i] for i in remain_indices]\n eindices = [eindices[i] for i in remain_indices]\n\n ax.scatter(xs, ys, label='Ours')\n for i, eidx in enumerate(eindices):\n ax.annotate(str(eidx), (xs[i], ys[i]))\n\n baselines = amoeba_A_scatter_xys()\n for baseline in baselines:\n _xs, _ys, _name = baseline\n ax.scatter(_xs, _ys, label=_name)\n\n plt.grid()\n plt.xlabel('GFLOPS')\n plt.ylabel('Test Error')\n plt.legend()\n plt.savefig(\n os.path.join(\n img_dir,\n 'cust_exps_{}_scatter.png'.format(\n '_'.join(args.cust_exps))\n ),\n dpi=plt.gcf().dpi, bbox_inches='tight'\n )\n\n print(ret_dict)\n with open('./temp/model_analysis_ret.bin', 'wb') as fout:\n fout.write(dumps(ret_dict))\n\n\n\n\n\n\n\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.subplots", "matplotlib.pyplot.gcf", "matplotlib.pyplot.grid", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
spragunr/jmu_ml_dimensionality_lab
[ "c6fe5adba8520f2a81f00556dcbf3574c1437016" ]
[ "code/good_dims.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 17 09:18:20 2020\n\n@author: spragunr\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nnum = 100\n\nD = np.zeros((num, 6))\nD[:,0] = np.random.randn(num)\nD[:,1] = np.random.random(num) \nD[np.random.randint(num, size=25), 2] = .5\nD[np.random.randint(num, size=25), 2] = 1.0\nD[:,3] = np.random.randn(num)\nD[:,4] = np.random.random(num) + .2 * D[:, 3]\nD[:,5] = D[:,1] * D[:,3]\n\nprint(D)\n\n\nplt.plot(D[:,1], D[:,5], '*')\nplt.plot(D[:,3], D[:,5], \"o\")\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(D[:,1], D[:, 3], D[:,5])\nplt.show()\nnp.savetxt('dims.csv', D, fmt='%.5f', delimiter=',')" ]
[ [ "numpy.random.random", "matplotlib.pyplot.plot", "numpy.random.randn", "numpy.random.randint", "numpy.savetxt", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhczhong/attention-is-all-you-need-pytorch
[ "f58eeb04e40575def05f5cb1fc2906d55aa05ebe" ]
[ "translate.py" ]
[ "''' Translate input text with trained model. '''\n\nimport torch\nimport torch.utils.data\nimport argparse\nfrom tqdm import tqdm\n\nfrom dataset import collate_fn, TranslationDataset\nfrom transformer.Translator import Translator\nfrom preprocess import read_instances_from_file, convert_instance_to_idx_seq\nfrom utils.postprocess import del_repeat\ndef main():\n '''Main Function'''\n\n parser = argparse.ArgumentParser(description='translate.py')\n\n parser.add_argument('-model', required=True,\n help='Path to model .pt file')\n parser.add_argument('-src', required=True,\n help='Source sequence to decode (one line per sequence)')\n parser.add_argument('-vocab', required=True,\n help='Source sequence to decode (one line per sequence)')\n parser.add_argument('-output', default='pred.txt',\n help=\"\"\"Path to output the predictions (each line will\n be the decoded sequence\"\"\")\n parser.add_argument('-beam_size', type=int, default=5,\n help='Beam size')\n parser.add_argument('-batch_size', type=int, default=30,\n help='Batch size')\n parser.add_argument('-n_best', type=int, default=1,\n help=\"\"\"If verbose is set, will output the n_best\n decoded sentences\"\"\")\n parser.add_argument('-no_cuda', action='store_true')\n\n opt = parser.parse_args()\n opt.cuda = not opt.no_cuda\n\n # Prepare DataLoader\n preprocess_data = torch.load(opt.vocab)\n preprocess_settings = preprocess_data['settings']\n test_src_word_insts = read_instances_from_file(\n opt.src,\n preprocess_settings.max_word_seq_len,\n preprocess_settings.keep_case)\n test_src_insts = convert_instance_to_idx_seq(\n test_src_word_insts, preprocess_data['dict']['src'])\n\n test_loader = torch.utils.data.DataLoader(\n TranslationDataset(\n src_word2idx=preprocess_data['dict']['src'],\n tgt_word2idx=preprocess_data['dict']['tgt'],\n src_insts=test_src_insts),\n num_workers=2,\n batch_size=opt.batch_size,\n collate_fn=collate_fn)\n \n encoder = torch.load(\"./49.pth\")[\"encoder\"]\n translator = Translator(encoder,opt)\n\n with open(opt.output, 'w') as f:\n for batch in tqdm(test_loader, mininterval=2, desc=' - (Test)', leave=False):\n all_hyp, all_scores = translator.translate_batch(*batch)\n for idx_seqs in all_hyp:\n for idx_seq in idx_seqs:\n pred_line = ' '.join([test_loader.dataset.tgt_idx2word[idx] for idx in idx_seq[:-1]])\n f.write(pred_line + '\\n')\n \n print('[Info] Finished.')\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pedrocarvalhodev/flask_api
[ "31f57626f6c5f94c600fb53867b490aee7c74f8c" ]
[ "flask_api/server.py" ]
[ "import os\nimport pandas as pd\nimport dill as pickle\nfrom flask import Flask, jsonify, request\nfrom utils import PreProcessing\n\napp = Flask(__name__)\n\[email protected]('/predict', methods=['POST'])\ndef apicall():\n\t\"\"\"API Call\n\t\n\tPandas dataframe (sent as a payload) from API Call\n\t\"\"\"\n\ttry:\n\t\ttest_json = request.get_json()\n\t\ttest = pd.read_json(test_json, orient='records')\n\n\t\t#To resolve the issue of TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'\n\t\ttest['Dependents'] = [str(x) for x in list(test['Dependents'])]\n\n\t\t#Getting the Loan_IDs separated out\n\t\tloan_ids = test['Loan_ID']\n\n\texcept Exception as e:\n\t\traise e\n\t\n\tclf = 'model_v1.pk'\n\t\n\tif test.empty:\n\t\treturn(bad_request())\n\telse:\n\t\t#Load the saved model\n\t\tprint(\"Loading the model...\")\n\t\tloaded_model = None\n\t\twith open('./models/'+clf,'rb') as f:\n\t\t\tloaded_model = pickle.load(f)\n\n\t\tprint(\"The model has been loaded...doing predictions now...\")\n\t\tpredictions = loaded_model.predict(test)\n\t\t\n\t\t\"\"\"Add the predictions as Series to a new pandas dataframe\n\t\t\t\t\t\t\t\tOR\n\t\t Depending on the use-case, the entire test data appended with the new files\n\t\t\"\"\"\n\t\tprediction_series = list(pd.Series(predictions))\n\n\t\tfinal_predictions = pd.DataFrame(list(zip(loan_ids, prediction_series)))\n\t\t\n\t\t\"\"\"We can be as creative in sending the responses.\n\t\t But we need to send the response codes as well.\n\t\t\"\"\"\n\t\tresponses = jsonify(predictions=final_predictions.to_json(orient=\"records\"))\n\t\tresponses.status_code = 200\n\n\t\treturn (responses)\n\n\[email protected](400)\ndef bad_request(error=None):\n\tmessage = {\n\t\t\t'status': 400,\n\t\t\t'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',\n\t}\n\tresp = jsonify(message)\n\tresp.status_code = 400\n\n\treturn resp" ]
[ [ "pandas.Series", "pandas.read_json" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
MartinoMensio/neural-symbolic-machines
[ "10683b8d7e0a97c2f6f35206deb5d3a31f4796c4" ]
[ "nsm/word_embeddings.py" ]
[ "import json\nimport numpy as np\nimport gensim\n\n\nclass EmbeddingModel(object):\n def __init__(\n self, vocab_file, embedding_file, normalize_embeddings=True):\n with open(embedding_file, 'rb') as f:\n self.embedding_mat = np.load(f)\n if normalize_embeddings:\n self.embedding_mat = self.embedding_mat / np.linalg.norm(\n self.embedding_mat, axis=1, keepdims=True)\n with open(vocab_file, 'r') as f:\n tks = json.load(f)\n self.vocab = dict(zip(tks, range(len(tks))))\n\n def __contains__(self, word):\n return word in self.vocab\n \n def __getitem__(self, word):\n if word in self.vocab:\n index = self.vocab[word]\n return self.embedding_mat[index]\n else:\n raise KeyError\n" ]
[ [ "numpy.load", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
gizatt/scene_generation
[ "cd978b4fe8ac58983894db3fb93d625c85578dd6" ]
[ "inverse_graphics/direct_pose_and_param_estimation/pose_head.py" ]
[ "import fvcore.nn.weight_init as weight_init\nimport numpy as np\nimport torch\nfrom detectron2.layers import Conv2d, ConvTranspose2d, cat, get_norm\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.utils.registry import Registry\n\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom scene_generation.utils.torch_quaternion import (\n quat2mat\n)\n\nROI_POSE_HEAD_REGISTRY = Registry(\"ROI_POSE_HEAD\")\n\n\n@ROI_POSE_HEAD_REGISTRY.register()\nclass RCNNPoseXyzHead(nn.Module):\n \"\"\"\n Takes an ROI an spits out estimates of the object XYZ pose.\n\n Operates by applying a number of convolutional + FC layers with\n a final soft classification output over a discretization of the\n pose xyz components.\n\n Layout is:\n \n conv layers --> FC layers --> N pose estimate bins --> final regression\n | |\n v v\n cross-entropy L1 loss\n loss\n\n \"\"\"\n\n def __init__(self, cfg, input_shape):\n super().__init__()\n\n # fmt: off\n num_conv = cfg.MODEL.ROI_POSE_XYZ_HEAD.NUM_CONV\n conv_dim = cfg.MODEL.ROI_POSE_XYZ_HEAD.CONV_DIM\n num_fc = cfg.MODEL.ROI_POSE_XYZ_HEAD.NUM_FC\n fc_dim = cfg.MODEL.ROI_POSE_XYZ_HEAD.FC_DIM\n norm = cfg.MODEL.ROI_POSE_XYZ_HEAD.NORM\n\n self.num_bins = cfg.MODEL.ROI_POSE_XYZ_HEAD.NUM_BINS\n self.xyz_bin_ranges = cfg.MODEL.ROI_POSE_XYZ_HEAD.XYZ_BIN_RANGES\n\n\n # fmt: on\n assert num_conv + num_fc > 0\n\n self._output_size = (input_shape.channels, input_shape.height, input_shape.width)\n\n num_output_params = self.num_bins * 3\n\n self.conv_norm_relus = []\n for k in range(num_conv):\n conv = Conv2d(\n self._output_size[0],\n conv_dim,\n kernel_size=3,\n padding=1,\n bias=not norm,\n norm=get_norm(norm, conv_dim),\n activation=F.relu,\n )\n self.add_module(\"conv{}\".format(k + 1), conv)\n self.conv_norm_relus.append(conv)\n self._output_size = (conv_dim, self._output_size[1], self._output_size[2])\n\n self.fcs = []\n for k in range(num_fc):\n if k == 0: \n # Takes 3x3 calibrations, rotations, and Hinfs as input as well\n fc = nn.Linear(np.prod(self._output_size) + 27, fc_dim)\n self._output_size = fc_dim\n elif k < num_fc - 1:\n fc = nn.Linear(np.prod(self._output_size), fc_dim)\n self._output_size = fc_dim\n else:\n fc = nn.Linear(np.prod(self._output_size), num_output_params)\n self._output_size = num_output_params\n self.add_module(\"fc{}\".format(k + 1), fc)\n self.fcs.append(fc)\n self._output_size = fc_dim\n\n # Temperature for softmax (gets exponentiated in the\n # forward pass to ensure it's always positive).\n self.log_T = torch.nn.Parameter(torch.log(torch.tensor([0.5])))\n self.log_T.requires_grad = True\n\n # Pre-compute xyz bin centers\n xyz_bin_corners = []\n xyz_bin_widths = []\n for k in range(3):\n bottom, top = self.xyz_bin_ranges[k]\n xyz_bin_widths.append( (top - bottom) / (self.num_bins - 1) )\n xyz_bin_corners.append(\n torch.linspace(bottom, top, steps=self.num_bins))\n self.register_buffer(\"xyz_bin_corners\", torch.stack(xyz_bin_corners))\n self.register_buffer(\"xyz_bin_widths\", torch.tensor(xyz_bin_widths))\n\n for layer in self.conv_norm_relus:\n weight_init.c2_msra_fill(layer)\n for layer in self.fcs:\n weight_init.c2_xavier_fill(layer)\n\n def forward(self, x, Kcs, rotations, Hinfs):\n for layer in self.conv_norm_relus:\n x = layer(x)\n if x.dim() > 2:\n x = torch.flatten(x, start_dim=1)\n Kcs = torch.flatten(Kcs, start_dim=1)\n rotations = torch.flatten(rotations, start_dim=1)\n Hinfs = torch.flatten(Hinfs, start_dim=1)\n x = torch.cat([x, Kcs, rotations, Hinfs], dim=-1)\n if len(self.fcs):\n for layer in self.fcs:\n x = F.relu(layer(x))\n x = x.reshape(x.shape[0], 3, self.num_bins)\n log_P = F.log_softmax(x / torch.exp(self.log_T), dim=-1)\n xyz_estimate = torch.sum(torch.exp(log_P) * self.xyz_bin_corners, dim=2)\n\n if self.training:\n get_event_storage().put_scalar(\"pose_xyz_log_T\", self.log_T)\n\n return xyz_estimate, log_P\n\n def pose_xyz_rcnn_loss(self, pose_xyz_estimate, log_P,\n instances, loss_weight=1.0, loss_type=\"l1\"):\n \"\"\"\n Compute the error between the estimated and actual pose.\n Args:\n pose_xyz_estimate (Tensor): A tensor of shape (B, 3) for batch size B.\n log_P (Tensor): A tensor of shape (B, 3, N_bins) for batch size B,\n and # of xyz bins N_bins.\n instances (list[Instances]): A list of N Instances, where N is the number of images\n in the batch. These instances are in 1:1\n correspondence with the pose estimates. The ground-truth labels (class, box, mask,\n ...) associated with each instance are stored in fields.\n loss_weight (float): A float to multiply the loss with.\n loss_type (string): 'l1' or 'l2'\n Returns:\n xyz_pose_loss (Tensor): A scalar tensor containing the loss.\n \"\"\"\n total_num_pose_estimates = pose_xyz_estimate.size(0)\n assert(pose_xyz_estimate.size(1) == 3)\n assert(log_P.size(0) == total_num_pose_estimates)\n assert(log_P.size(1) == 3)\n assert(log_P.size(2) == self.num_bins)\n\n # Gather up gt xyz poses from the list of Instances objects\n all_gt_pose_xyz = []\n for instances_per_image in instances:\n if len(instances_per_image) == 0:\n continue\n all_gt_pose_xyz.append(instances_per_image.gt_pose_quatxyz[:, -3:].to(device=pose_xyz_estimate.device))\n\n if len(all_gt_pose_xyz) == 0:\n return 0.\n\n all_gt_pose_xyz = cat(all_gt_pose_xyz, dim=0)\n assert all_gt_pose_xyz.numel() > 0, all_gt_pose_xyz.shape\n\n # Compute the bin index in which the ground truth xyz poses fall\n # by subtracting off the bin left boundaries and dividing by the bin widths\n distance_into_bins = all_gt_pose_xyz.detach() - self.xyz_bin_corners[:, 0]\n bin_indices = (distance_into_bins / self.xyz_bin_widths).floor()\n bin_indices = torch.clamp(bin_indices, 0, self.num_bins).long()\n\n active_log_probs = torch.stack(\n [log_P[k, range(3), bin_indices[k, :]]\n for k in range(total_num_pose_estimates)])\n pose_loss = torch.mean(-active_log_probs)\n\n if loss_type == \"l1\":\n pose_loss = pose_loss + F.l1_loss(\n pose_xyz_estimate, all_gt_pose_xyz, reduction=\"mean\"\n )\n elif loss_type == \"l2\":\n pose_loss = pose_loss + F.mse_loss(\n pose_xyz_estimate, all_gt_pose_xyz, reduction=\"mean\"\n )\n else:\n raise NotImplementedError(\"Unrecognized loss type: \", loss_type)\n\n pose_loss = pose_loss * loss_weight\n return pose_loss\n\n\n@ROI_POSE_HEAD_REGISTRY.register()\nclass RCNNPoseRpyHead(nn.Module):\n \"\"\"\n Takes an ROI an spits out estimates of the object pose RPY components.\n\n Operates by applying a number of convolutional + FC layers with\n a final soft classification output over a discretization of the\n pose rpy components.\n\n Layout is:\n \n conv layers --> FC layers --> N pose estimate bins --> final regression\n | |\n v v\n cross-entropy L1 loss\n loss\n\n RPY is treated differently than XYZ, as in the 3dRCNN paper (Kundu et al):\n XYZ is discretized over some range with loss taken directly, whereas RPY is\n discretized over the entire range [0, 2pi] with a complex loss that wraps\n around from 2pi to 0.\n \"\"\"\n\n def __init__(self, cfg, input_shape):\n super().__init__()\n\n # fmt: off\n num_conv = cfg.MODEL.ROI_POSE_RPY_HEAD.NUM_CONV\n conv_dim = cfg.MODEL.ROI_POSE_RPY_HEAD.CONV_DIM\n num_fc = cfg.MODEL.ROI_POSE_RPY_HEAD.NUM_FC\n fc_dim = cfg.MODEL.ROI_POSE_RPY_HEAD.FC_DIM\n norm = cfg.MODEL.ROI_POSE_RPY_HEAD.NORM\n\n self.num_bins = cfg.MODEL.ROI_POSE_RPY_HEAD.NUM_BINS\n\n # fmt: on\n assert num_conv + num_fc > 0\n\n self._output_size = (input_shape.channels, input_shape.height, input_shape.width)\n\n num_output_params = self.num_bins * 3\n\n self.conv_norm_relus = []\n for k in range(num_conv):\n conv = Conv2d(\n self._output_size[0],\n conv_dim,\n kernel_size=3,\n padding=1,\n bias=not norm,\n norm=get_norm(norm, conv_dim),\n activation=F.relu,\n )\n self.add_module(\"conv{}\".format(k + 1), conv)\n self.conv_norm_relus.append(conv)\n self._output_size = (conv_dim, self._output_size[1], self._output_size[2])\n\n self.fcs = []\n for k in range(num_fc):\n if k == 0: \n # Takes 3x3 calibrations + Hinfs + rotmats as input as well\n fc = nn.Linear(np.prod(self._output_size) + 27, fc_dim)\n self._output_size = fc_dim\n elif k < num_fc - 1:\n fc = nn.Linear(np.prod(self._output_size), fc_dim)\n self._output_size = fc_dim\n else:\n fc = nn.Linear(np.prod(self._output_size), num_output_params)\n self._output_size = num_output_params\n self.add_module(\"fc{}\".format(k + 1), fc)\n self.fcs.append(fc)\n self._output_size = fc_dim\n\n # Temperature for softmax (gets exponentiated in the\n # forward pass to ensure it's always positive).\n self.log_T = torch.nn.Parameter(torch.log(torch.tensor([0.5])))\n self.log_T.requires_grad = True\n\n # Pre-compute rpy bin centers -- to make computing the complex\n # expectation easier, prepare the real + imaginary component of\n # the complex exponential of each bin center.\n rpy_bin_corners = []\n rpy_bin_widths = []\n for k in range(3):\n bottom, top = -np.pi, np.pi\n rpy_bin_widths.append( (top - bottom) / (self.num_bins - 1) )\n rpy_bin_corners.append(\n torch.linspace(bottom, top, steps=self.num_bins))\n rpy_bin_corners = torch.stack(rpy_bin_corners)\n self.register_buffer(\"rpy_bin_corners\",\n rpy_bin_corners)\n self.register_buffer(\"rpy_bin_corners_real\",\n torch.cos(rpy_bin_corners))\n self.register_buffer(\"rpy_bin_corners_imag\",\n torch.sin(rpy_bin_corners))\n self.register_buffer(\"rpy_bin_widths\", torch.tensor(rpy_bin_widths))\n\n for layer in self.conv_norm_relus:\n weight_init.c2_msra_fill(layer)\n for layer in self.fcs:\n weight_init.c2_xavier_fill(layer)\n\n def forward(self, x, Kcs, rotations, Hinfs):\n for layer in self.conv_norm_relus:\n x = layer(x)\n if x.dim() > 2:\n x = torch.flatten(x, start_dim=1)\n Kcs = torch.flatten(Kcs, start_dim=1)\n rotations = torch.flatten(rotations, start_dim=1)\n Hinfs = torch.flatten(Hinfs, start_dim=1)\n x = torch.cat([x, Kcs, rotations, Hinfs], dim=-1)\n if len(self.fcs):\n for layer in self.fcs:\n x = F.relu(layer(x))\n x = x.reshape(x.shape[0], 3, self.num_bins)\n log_P = F.log_softmax(x / torch.exp(self.log_T), dim=-1)\n # To get the estimate, take the *complex* expectation -- see\n # eq. (2) in the 3dRCNN paper.\n P = torch.exp(log_P)\n real_total = torch.sum(P * self.rpy_bin_corners_real, dim=2)\n imag_total = torch.sum(P * self.rpy_bin_corners_imag, dim=2)\n rpy_estimate = torch.atan2(imag_total, real_total)\n\n if self.training:\n get_event_storage().put_scalar(\"pose_rpy_log_T\", self.log_T)\n\n\n return rpy_estimate, log_P\n\n def pose_rpy_rcnn_loss(self, pose_rpy_estimate, log_P,\n instances, loss_weight=1.0, loss_type=\"l1\"):\n \"\"\"\n Compute the error between the estimated and actual pose.\n Args:\n pose_rpy_estimate (Tensor): A tensor of shape (B, 3) for batch size B.\n P (Tensor): A tensor of shape (B, 3, N_bins) for batch size B,\n and # of rpy bins N_bins.\n instances (list[Instances]): A list of N Instances, where N is the number of images\n in the batch. These instances are in 1:1\n correspondence with the pose estimates. The ground-truth labels (class, box, mask,\n ...) associated with each instance are stored in fields.\n loss_weight (float): A float to multiply the loss with.\n loss_type (string): 'l1' or 'l2'\n Returns:\n rpy_pose_loss (Tensor): A scalar tensor containing the loss.\n \"\"\"\n total_num_pose_estimates = pose_rpy_estimate.size(0)\n assert(pose_rpy_estimate.size(1) == 3)\n assert(log_P.size(0) == total_num_pose_estimates)\n assert(log_P.size(1) == 3)\n assert(log_P.size(2) == self.num_bins)\n\n # Gather up gt rpy poses from the list of Instances objects\n all_gt_pose_rpy = []\n for instances_per_image in instances:\n if len(instances_per_image) == 0:\n continue\n all_gt_pose_rpy.append(instances_per_image.gt_pose_rpy.to(device=pose_rpy_estimate.device))\n\n if len(all_gt_pose_rpy) == 0:\n return 0.\n\n all_gt_pose_rpy = cat(all_gt_pose_rpy, dim=0)\n assert all_gt_pose_rpy.numel() > 0, all_gt_pose_rpy.shape\n\n # Compute the bin index in which the ground truth rpy poses fall\n # by subtracting off the bin left boundaries and dividing by the bin widths\n distance_into_bins = all_gt_pose_rpy.detach() - self.rpy_bin_corners[:, 0]\n bin_indices = (distance_into_bins / self.rpy_bin_widths).floor()\n bin_indices = torch.clamp(bin_indices, 0, self.num_bins).long()\n\n active_log_probs = torch.stack(\n [log_P[k, range(3), bin_indices[k, :]]\n for k in range(total_num_pose_estimates)])\n pose_loss = torch.mean(-active_log_probs)\n\n # In either loss case, collapse among the minimum (elementwise) loss among\n # the original angle estimate, as well as the angle estimate rotated left\n # and right by 2pi.\n pose_loss_0 = torch.abs(pose_rpy_estimate - all_gt_pose_rpy)\n pose_loss_1 = torch.abs(pose_rpy_estimate + np.pi*2. - all_gt_pose_rpy)\n pose_loss_2 = torch.abs(pose_rpy_estimate - np.pi*2. - all_gt_pose_rpy)\n pose_loss_min, _ = torch.min(torch.stack([pose_loss_0, pose_loss_1, pose_loss_2], dim=0), dim=0)\n if loss_type == \"l1\":\n pose_loss = pose_loss + torch.mean(pose_loss_min)\n elif loss_type == \"l2\":\n pose_loss = pose_loss + torch.mean(pose_loss_min**2.)\n else:\n raise NotImplementedError(\"Unrecognized loss type: \", loss_type)\n\n pose_loss = pose_loss * loss_weight\n return pose_loss\n\n\n@ROI_POSE_HEAD_REGISTRY.register()\nclass RCNNPose6DOFRotHead(nn.Module):\n \"\"\"\n Takes an ROI an spits out estimates of the object pose rotation estimate\n (in rotation matrix form).\n\n Operates by applying a number of convolutional + FC layers with\n that spit out a 6DOF overparameterized rotation format (following\n https://arxiv.org/pdf/1812.07035.pdf).\n\n Layout is:\n \n conv layers --> FC layers --> 6DOF representation -> postprocess into rotmat\n \"\"\"\n\n def __init__(self, cfg, input_shape):\n super().__init__()\n\n # fmt: off\n num_conv = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.NUM_CONV\n conv_dim = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.CONV_DIM\n num_fc = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.NUM_FC\n fc_dim = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.FC_DIM\n norm = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.NORM\n\n # fmt: on\n assert num_conv + num_fc > 0\n\n self._output_size = (input_shape.channels, input_shape.height, input_shape.width)\n\n num_output_params = 6\n\n self.conv_norm_relus = []\n for k in range(num_conv):\n conv = Conv2d(\n self._output_size[0],\n conv_dim,\n kernel_size=3,\n padding=1,\n bias=not norm,\n norm=get_norm(norm, conv_dim),\n activation=F.relu,\n )\n self.add_module(\"conv{}\".format(k + 1), conv)\n self.conv_norm_relus.append(conv)\n self._output_size = (conv_dim, self._output_size[1], self._output_size[2])\n\n self.fcs = []\n for k in range(num_fc):\n if k == 0: \n # Takes 3x3 calibrations + Hinfs + rotmats as input as well\n fc = nn.Linear(np.prod(self._output_size) + 27, fc_dim)\n self._output_size = fc_dim\n elif k < num_fc - 1:\n fc = nn.Linear(np.prod(self._output_size), fc_dim)\n self._output_size = fc_dim\n else:\n fc = nn.Linear(np.prod(self._output_size), num_output_params)\n self._output_size = num_output_params\n self.add_module(\"fc{}\".format(k + 1), fc)\n self.fcs.append(fc)\n self._output_size = fc_dim\n\n for layer in self.conv_norm_relus:\n weight_init.c2_msra_fill(layer)\n for layer in self.fcs:\n weight_init.c2_xavier_fill(layer)\n\n def forward(self, x, Kcs, rotations, Hinfs):\n for layer in self.conv_norm_relus:\n x = layer(x)\n if x.dim() > 2:\n x = torch.flatten(x, start_dim=1)\n Kcs = torch.flatten(Kcs, start_dim=1)\n rotations = torch.flatten(rotations, start_dim=1)\n Hinfs = torch.flatten(Hinfs, start_dim=1)\n x = torch.cat([x, Kcs, rotations, Hinfs], dim=-1)\n if len(self.fcs):\n for layer in self.fcs:\n x = F.relu(layer(x))\n x = x.reshape(x.shape[0], 2, 3)\n # We've predicted two 3-vectors -- normalize them\n # and form a rotation matrix from them referencing Appendix B\n # in https://arxiv.org/pdf/1812.07035.pdf\n a1 = x[:, 0, :]\n a2 = x[:, 1, :]\n b1 = F.normalize(a1, p=2, dim=1)\n # Sum is repeated out to [batch x 3] from [batch] so it\n # broadcast-multiplies with [batch x 3] b1 happily\n b2 = F.normalize(a2 - (torch.sum(b1*a2, dim=-1).view(-1, 1).expand(-1, 3)*b1), dim=1)\n b3 = torch.cross(b1, b2)\n R = torch.stack([b1, b2, b3], dim=-1)\n return R\n\n def pose_6DOF_rot_rcnn_loss(self, R_estimate,\n instances, loss_weight=1.0, loss_type=\"l1\"):\n \"\"\"\n Compute the error between the estimated and actual pose.\n Args:\n R_estimate (Tensor): A tensor of shape (B, 3, 3) for batch size B.\n instances (list[Instances]): A list of N Instances, where N is the number of images\n in the batch. These instances are in 1:1\n correspondence with the pose estimates. The ground-truth labels (class, box, mask,\n ...) associated with each instance are stored in fields.\n loss_weight (float): A float to multiply the loss with.\n loss_type (string): 'l1' or 'l2'\n Returns:\n loss (Tensor): A scalar tensor containing the loss.\n \"\"\"\n total_num_pose_estimates = R_estimate.size(0)\n assert(R_estimate.shape[-2:] == (3, 3))\n\n # Gather up gt rotation matrices from the list of Instances objects\n all_gt_pose_quat = []\n for instances_per_image in instances:\n if len(instances_per_image) == 0:\n continue\n all_gt_pose_quat.append(instances_per_image.gt_pose_quatxyz[:, :4].detach().to(device=R_estimate.device))\n\n if len(all_gt_pose_quat) == 0:\n return 0.\n\n all_gt_pose_quat = cat(all_gt_pose_quat, dim=0)\n assert all_gt_pose_quat.numel() > 0, all_gt_pose_quat.shape\n\n all_gt_pose_rotmat = quat2mat(all_gt_pose_quat)\n # Get rotation difference between predicted and target\n diff_rotations = torch.matmul(all_gt_pose_rotmat, torch.transpose(R_estimate, 1, 2)).contiguous()\n\n # Batch trace implementation from torch_quaternion.py \n rotation_matrix_vec = diff_rotations.reshape(*diff_rotations.shape[:-2], 9)\n m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(\n rotation_matrix_vec, chunks=9, dim=-1)\n trace = m00 + m11 + m22\n angle_errors = torch.acos(torch.clamp((trace - 1.)/2., -0.9999, 0.9999))\n if loss_type == \"l1\":\n pose_loss = torch.mean(angle_errors)\n elif loss_type == \"l2\":\n pose_loss = torch.mean(angle_errors**2.)\n else:\n raise NotImplementedError(\"Unrecognized loss type: \", loss_type)\n pose_loss = pose_loss * loss_weight\n return pose_loss\n\ndef build_pose_xyz_head(cfg, input_shape):\n name = cfg.MODEL.ROI_POSE_XYZ_HEAD.NAME\n return ROI_POSE_HEAD_REGISTRY.get(name)(cfg, input_shape)\n\n\ndef build_pose_rpy_head(cfg, input_shape):\n name = cfg.MODEL.ROI_POSE_RPY_HEAD.NAME\n return ROI_POSE_HEAD_REGISTRY.get(name)(cfg, input_shape)\n\ndef build_pose_6DOF_rot_head(cfg, input_shape):\n name = cfg.MODEL.ROI_POSE_6DOF_ROT_HEAD.NAME\n return ROI_POSE_HEAD_REGISTRY.get(name)(cfg, input_shape)" ]
[ [ "torch.mean", "torch.abs", "torch.transpose", "torch.nn.functional.l1_loss", "torch.cat", "torch.sin", "torch.sum", "torch.flatten", "torch.tensor", "torch.cos", "torch.linspace", "torch.exp", "torch.nn.functional.mse_loss", "torch.stack", "torch.atan2", "torch.nn.functional.normalize", "numpy.prod", "torch.chunk", "torch.clamp", "torch.cross" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chrelli/3DDD_social_mouse_tracker
[ "291d2ed90029628dd65db0ce3e8972b721159a15" ]
[ "recording/record_calib_npy.py" ]
[ "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 12 15:36:15 2018\n\n@author: chrelli\nadded unix time stamps to the first camera!\n\nWays to slim down the data:\n no unix time stamps?\n no color frame showing? - yes, helps a lot!\n no png compression? Totally fine at 30 fps!\n\nMajow to do list:\n - use arduino to synchronize? Yes, could send out synchronization time code to another unit: Problem: doesn't account for delay of arriving frames\n\n - use depth roi to slim down writing footprint\n\n - use LED roi to get blinking time stamps\n\n -\n\n## with connected device cam\nfrom pyrealsense import offline\noffline.save_depth_intrinsics(dev)\n\"\"\"\n\n#%% Import the nescessary stuff\n# basic OS stuff\nimport time, os, sys, shutil\nimport json\n# for math and plotting\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\n# small utilities\nimport csv\nfrom colour import Color\nfrom itertools import compress # for list selection with logical\nfrom tqdm import tqdm\n\n# for image manipulation\nimport cv2\n\n# for recording and connecting to the intel realsense librar\n#import pyrealsense as pyrs\n# add the realsense library\nsys.path.append(r'/usr/local/lib')\n# and load it!\nimport pyrealsense2 as rs\n\n\n#import multiprocessing\nfrom multiprocessing import Process\n\n# import handy Functions\nfrom utils.common_utils import *\nfrom utils.recording_utils import *\n\n\n\n#%% Parse some inputs\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Records cad and d images with no roi cut to disk. Also records timestamps and led traces using the auto LED mask. Currently, with no ROI, the program maxes out disk write speed around 45 fps.',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\nparser.add_argument('--ncams', type=int, default = 4 , choices=[1,2,3,4],\n help='number of cameras to stream')\n\nparser.add_argument('--fps',type=int, default = 30 , choices=[30,60],\n help='select fps to stream')\n\n#parser.add_argument(\"--singlecore\", help=\"disables mult.proc. for debugging on macbook, overrides ncams to 1\",\n# action=\"store_true\")\n\nparser.add_argument(\"--plots\", help=\"shows the live video while recording\",\n action=\"store_true\")\n\nargs = parser.parse_args()\n\n\n\n#%% Constants\n# frame_width,frame_height = 848,480\nframe_width,frame_height = 640,480\n\n\nfps_choice = args.fps\n# number of padding digits for the frame numbers\nn_padding_digits = 8\n\nprint('# cameras: '+str(args.ncams))\nprint('Frame size is '+str(frame_width)+'x'+str(frame_height)+' pixels.')\nprint('Grabbing frames at '+str(fps_choice)+' fps')\n\n\n# get the current timestring\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\n\n# reset the folder\n#data_folder = '/media/chrelli/Data0'\n#top_folder = data_folder + '/calibration_' + timestr\n#reset_folder_if_present(top_folder)\n#\n#top_folder_0 = top_folder\n#top_folder_1 = top_folder\n\n# reset the folders\ntop_folder_0 = '/media/chrelli/Data0' + '/calibration_' + timestr\ntop_folder_1 = '/media/chrelli/Data1' + '/calibration_' + timestr\n\nreset_folder_if_present(top_folder_0)\nreset_folder_if_present(top_folder_1)\n\n# also make the numpy folders\nnpy_folder_0 = top_folder_0+'/npy_raw'\nnpy_folder_1 = top_folder_1+'/npy_raw'\n\nreset_folder_if_present(npy_folder_0)\nreset_folder_if_present(npy_folder_1)\n\n\n#%% 8 bit color setup\nfps_color = (Color('White').rgb)\nts_color = (Color('Peru').rgb)\n\n# convert to 8 bit color\nfps_color=tuple(255*x for x in fps_color)\nts_color=tuple(255*x for x in ts_color)\n\n#%% Block for running\n# open the pyrealsense server\n#serv = pyrs.Service()\n\n# set the start time for the unix time stamp\nstart_time = time.time()\n\n\n\n# open up a realsense context and get a list of the devices!\nctx = rs.context()\n\ndevices = [ctx.devices[i] for i in range(args.ncams)]\n# sort the devices by their serial numbers\nserials = [devices[i].get_info(rs.camera_info.serial_number) for i in range(args.ncams)]\ndevices = [x for _,x in sorted(zip(serials,devices))]\n\n\n\ndef sub_function_trick(which_device,top_folder):\n show_frames = args.plots\n\n\n ####################\n #\n # DEVICE SETUP BLOCK\n #\n #####################\n\n # get the serial of that device\n device = devices[which_device]\n device_serial = device.get_info(rs.camera_info.serial_number)\n\n #set the preset\n advnc_mode = rs.rs400_advanced_mode(device)\n print(\"Advanced mode is\", \"enabled\" if advnc_mode.is_enabled() else \"disabled\")\n # run like\n # advnc_mode.load_json(json_string)\n\n # load the preset here!\n preset_folder = '/home/chrelli/git/3d_sandbox/mycetrack0p8/presets/'\n if device_serial[:3] == '740':\n preset_name = 'master60pp'\n else:\n preset_name = 'slave60pp'\n\n jsonFile = preset_folder+preset_name+'.json'\n jsonObj = json.load(open(jsonFile))\n json_string = str(jsonObj).replace(\"'\", '\\\"')\n print(\"Configuration \" + jsonFile + \" loaded\");\n time.sleep(1.)\n advnc_mode.load_json(json_string)\n print(\"Configuration \" + jsonFile + \" applied!\");\n\n if device_serial[:3] == '740':\n # master\n targetSyncMode = 1\n else:\n # slave\n targetSyncMode = 2\n device.first_depth_sensor().set_option(rs.option.inter_cam_sync_mode, targetSyncMode)\n\n\n # first, open up a config\n config = rs.config()\n\n # then open a pipeline\n pipeline = rs.pipeline()\n\n # enable the selected device and streams # RGB SPACE HERE\n config.enable_device(device_serial);\n config.enable_stream(rs.stream.depth, frame_width,frame_height, rs.format.z16, fps_choice)\n# config.enable_stream(rs.stream.color, frame_width,frame_height, rs.format.rgb8, fps_choice)\n\n config.enable_stream(rs.stream.color, frame_width,frame_height, rs.format.rgb8, fps_choice)\n config.enable_stream(rs.stream.infrared,1, frame_width,frame_height, rs.format.y8, fps_choice)\n\n print(\"PING after enabling the sync mode is {}\".format(device.first_depth_sensor().get_option(rs.option.inter_cam_sync_mode)))\n\n\n # Start streaming, call the stream 'cfg' for some reason, as pr example\n cfg = pipeline.start(config)\n\n # create an align object\n # alternative is to align to color, faster but less precise: align_to = rs.stream.color\n align_to = rs.stream.depth\n align = rs.align(align_to)\n\n\n print('dev '+str(which_device)+' serial is ' + device_serial)\n # Use the first three digits of the serial as a string to tag the device:\n device_tag = device_serial[0:3]\n\n if show_frames:\n # open a window for cv2\n window_title = \"dev\"+str(which_device)+\"(#\" + device_tag + \")\"\n cv2.namedWindow(window_title+'cad')\n\n # block for setting up a low-level fps estimation,\n cnt = 0 # a counter\n last = time.time() # start_time\n fps = 0 # initial fps value\n\n # save the camera intrinsics\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_sensor = cfg.get_device().first_depth_sensor()\n depth_scale = depth_sensor.get_depth_scale()\n print (\"Depth Scale is: \" , depth_scale)\n\n # this is how to get the intrinsics\n profile = cfg.get_stream(rs.stream.depth) # Fetch stream profile for depth stream\n intr = profile.as_video_stream_profile().get_intrinsics() # Downcast to video_stream_profile\n\n\n #% now make file and save time stamps and depth scaling and intrinsics etc\n # use the old naming convention\n\n parameternames = np.array(['cam_params.fx',\n 'cam_params.fy',\n 'cam_params.ppx',\n 'cam_params.ppy',\n 'd_scale',\n 'fps_choice',\n 'frame_width',\n 'frame_height'])\n parameters = np.array([intr.fx,\n intr.fy,\n intr.ppx,\n intr.ppy,\n depth_scale,\n fps_choice,\n intr.width,\n intr.height])\n\n # open a file for writint the parameters\n with open(top_folder+'/parameters_'+str(which_device)+'.csv','w') as intrfile:\n writer = csv.writer(intrfile, delimiter=',')\n writer.writerow(parameternames)\n writer.writerow(parameters)\n\n\n # load the automatic led mask from the constants folder!\n led_mask,led_logic,led_centroid = load_auto_roi(which_device)\n\n\n # open a file for time stamps\n tsfile = open(top_folder+'/timestamps_'+str(which_device)+'.csv','w')\n\n\n# ## HF try to open an HF file\n# import h5py\n# #TODO input from somewhere\n# hf = h5py.File(top_folder+'/dev'+str(which_device)+'_d_'+'.h5', 'w')\n# # also open one for the cad\n# hf_cad = h5py.File(top_folder+'/dev'+str(which_device)+'_cad_'+'.h5', 'w')\n\n # NPY ADDITION\n npy_folder = top_folder+'/npy_raw'\n\n\n # open a file for led stamps\n# ledsfile = open(top_folder+'/ledstamps_'+str(which_device)+'.csv','w')\n\n print('starting to stream from device '+str(which_device)+'!')\n # wait for a bit for the cam to warm up\n # and loop over 30 frames\n warmup_time = 2 # seconds\n warmup = 0\n while warmup < fps_choice*warmup_time:\n frames = pipeline.wait_for_frames()\n warmup += 1\n print('device '+str(which_device)+' is warmed up!')\n\n\n # START A CLOCK FOR THE FRAMES!\n FRAME_CLOCK = 0\n try:\n while True:\n\n if show_frames:\n # for counting frame rate\n cnt += 1\n if (cnt % 10) == 0:\n now = time.time() # after 10 frames\n dt = now - last # how long did it take?\n fps = 10/dt # calculate frame rate\n last = now # assign a new value to the 'last time'\n\n #################################\n #\n # R E A D B L O C K\n #\n #################################\n\n # Wait for a coherent pair of frames: depth and color\n frames = pipeline.wait_for_frames()\n\n # get the frame numbers and time stamps\n# ts = round(frames.get,2)\n ts = frames.get_timestamp()\n fn = frames.get_frame_number()\n\n # get the unix time stamp\n ts_unix = time.time()-start_time\n\n # run the alignment process\n aligned_frames = align.process(frames)\n depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n cad_frame = aligned_frames.get_color_frame()\n # also get one for the LED\n # depth_frame = frames.get_depth_frame()\n # color_frame = frames.get_color_frame()\n infrared_frame = frames.get_infrared_frame()\n\n\n # Convert images to numpy arrays\n depth = np.asanyarray(depth_frame.get_data())\n cad = np.asanyarray(cad_frame.get_data())\n c = np.asanyarray(infrared_frame.get_data())\n\n\n # get the LED value, round it a bit, could be profiled\n led_stamp = c[led_centroid[1],led_centroid[0]]\n\n # this is the writing block for the csv file, frame number and time stamp!\n# tsfile.write(str(FRAME_CLOCK)+','+str(fn)+','+str(ts)+','+str(ts_unix)+','+str(single_pixel_RGB2GRAY(led_stamp))+'\\n')\n tsfile.write(str(FRAME_CLOCK)+','+str(fn)+','+str(ts)+','+str(ts_unix)+','+str(led_stamp)+'\\n')\n\n # this is the writing block for the csv file, frame number and time stamp!\n #TODO put led with the others in same file?\n# ledsfile.write(str(single_pixel_RGB2GRAY(led_stamp))+'\\n')\n\n\n # write the depth frames to tiff (replace: send to queue)\n# cv2.imwrite(top_folder+'/dev'+str(which_device)+'_d_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.png', depth)\n# cv2.imwrite(top_folder+'/dev'+str(which_device)+'_cad_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.png', cad)\n\n# hf.create_dataset(str(FRAME_CLOCK), data=depth)\n# hf_cad.create_dataset(str(FRAME_CLOCK), data=cad)\n\n np.save(npy_folder+'/dev'+str(which_device)+'_d_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.npy',depth, allow_pickle = False)\n np.save(npy_folder+'/dev'+str(which_device)+'_cad_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.npy',cad, allow_pickle = False)\n\n\n # UPDATE CLOCK\n FRAME_CLOCK += 1\n\n #\n if show_frames:\n # add text and show the CAD frames\n cv2.putText(cad, window_title+', fps: '+str(fps)[:4], (0, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, fps_color)\n cv2.putText(cad, str(round(ts)), (0, frame_height-20), cv2.FONT_HERSHEY_SIMPLEX, 1, ts_color)\n cv2.imshow(window_title+'cad', cad)\n\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n # looks for a small q to nbe pressed\n # close the time stamp file\n tsfile.close\n\n # close the hf file\n# hf.close()\n# hf_cad.close()\n# ledsfile.close\n\n # stop the device\n pipeline.stop()\n print('pipeline from device '+str(which_device)+' is now closed!')\n break\n\n finally:\n tsfile.close\n\n # close the hf file\n# hf.close()\n# hf_cad.close()\n\n # stop the device\n pipeline.stop()\n print('pipeline from device '+str(which_device)+' is now closed!')\n\n\n#%% define helping funtions for the multiprocessing\n# these functions have to not be iterable.\n\ndef read_device_0():\n print('starting camera 1!')\n which_device = 0\n top_folder = top_folder_0\n sub_function_trick(which_device,top_folder)\n\ndef read_device_1():\n print('starting camera 2!')\n which_device = 1\n top_folder = top_folder_0\n sub_function_trick(which_device,top_folder)\n\ndef read_device_2():\n print('starting camera 3!')\n which_device = 2\n top_folder = top_folder_1\n sub_function_trick(which_device,top_folder)\n\ndef read_device_3():\n print('starting camera 4!')\n which_device = 3\n top_folder = top_folder_1\n sub_function_trick(which_device,top_folder)\n\n\n#%% run the processes on independent cores\nfrom multiprocessing import Process\nif __name__ == '__main__':\n if args.ncams == 4:\n print('starting 4 cams, with multiprocessing!')\n # start 4 worker processes\n Process(target=read_device_0).start()\n time.sleep(3.)\n Process(target=read_device_1).start()\n Process(target=read_device_2).start()\n Process(target=read_device_3).start()\n Process(target=blink_using_firmata_random).start()\n\n elif args.ncams == 3:\n print('starting 3 cams, with multiprocessing!')\n Process(target=read_device_0).start()\n Process(target=read_device_1).start()\n Process(target=read_device_2).start()\n Process(target=blink_using_firmata).start()\n\n elif args.ncams == 2:\n print('starting 2 cams, with multiprocessing!')\n Process(target=read_device_0).start()\n Process(target=read_device_1).start()\n Process(target=blink_using_firmata).start()\n\n elif args.ncams == 1:\n print('starting 1 cam, with multiprocessing!')\n Process(target=read_device_0).start()\n Process(target=blink_using_firmata).start()\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ahefnycmu/rpsp
[ "ff3aa3e89a91bb4afb7bad932d2c04691a727a63" ]
[ "rpsp/rpspnets/nn_diags.py" ]
[ "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 8 18:56:28 2017\n\n@author: ahefny\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nimport rpsp.globalconfig as globalconfig\n\nfrom rpsp.rpspnets.psr_lite.utils.nn import CallbackOp\n\nclass PredictionError(Exception):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n \ndef dbg_nn_skip_update(X, condition, msg):\n def fn(x):\n if not condition(x):\n print ('Skip update: '+msg, sep='')\n raise PredictionError(0)\n return CallbackOp(fn)(X)\n\ndef dbg_nn_raise_PredictionError(X, msg):\n def fn(x):\n errors = np.sum(np.abs(np.sum(x,axis=1))<1e-6)\n #print ('OUT: '+msg, errors, sep='')\n if errors > 10:\n print ('all zeros Error! Skip update: '+msg, errors, sep='')\n raise PredictionError(errors)\n return CallbackOp(fn)(X)\n\ndef dbg_raise_BadPrediction(X, msg):\n def fn(x):\n #print ('pred cost: ',x)\n if x > globalconfig.vars.args.dbg_prederror:\n print (msg+' Skip update. high pred cost (>%f)'%globalconfig.vars.args.dbg_prederror, x, sep='')\n raise PredictionError(-1)\n return CallbackOp(fn)(X)\n" ]
[ [ "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
christiaanlamers/sms-mip-ego
[ "3601efcb9cfe069e8543d3c29a6102ebbeb9a78c", "3601efcb9cfe069e8543d3c29a6102ebbeb9a78c" ]
[ "all_cnn_bi_skippy_cifar100.py", "load_acc_eval_train_hist.py" ]
[ "from __future__ import print_function\n\nimport numpy as np\n#np.random.seed(43)\nimport tensorflow as tf\ntf.set_random_seed(43)\n\nimport keras\n#from keras.datasets import mnist\nfrom keras.datasets import cifar100\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D,UpSampling2D,ZeroPadding2D,Concatenate\nfrom keras.layers import Layer#CHRIS to define a layer yourself\nimport os\nimport sys\nimport pandas as pd\nimport keras.backend as K\nimport math\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.regularizers import l2\n\nimport time #CHRIS added to measure runtime of training\nfrom pynvml import * #CHRIS needed to test gpu memory capacity\n#from fractions import gcd #CHRIS needed for proper upscaling\n\nimport setproctitle\nimport json\n\n#setproctitle.setproctitle('lamers c, do not use GPU 4-7, 9-15 please')\n\nclass TimedAccHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.accuracy_log = []\n self.timed = []\n self.start_time = time.time()\n \n def on_epoch_end(self, batch, logs={}):\n self.accuracy_log.append(logs.get('val_acc'))\n self.timed.append(time.time() - self.start_time)\n\ndef inv_gray(num):#TODO only for testing\n n = 0\n while num != 0:\n n = num ^ n\n num = num >> 1\n return n\n\nclass Skip_manager(object):\n def __init__(self,skip_ints,skip_ints_count):\n self.skip_ints= skip_ints\n self.skip_ints_count = skip_ints_count\n self.skip_connections = []\n self.layer_num = 0 #layer number of currently build layer\n \n def identity(self,num):\n return num\n \n def gray(self,num):\n return num ^ (num >> 1)\n \n def startpoint(self,func,num):\n return (func(num) >> self.layer_num) & 1\n \n def set_dropout(self,dropout_val):\n for i in range(len(self.skip_connections)):\n self.skip_connections[i][3] = dropout_val\n return\n \n def pad_and_connect(self, layer, incoming_layer):\n if K.int_shape(incoming_layer)[1] != K.int_shape(layer)[1] or K.int_shape(incoming_layer)[2] != K.int_shape(layer)[2]:\n pad_tpl1 = (int(np.floor(np.abs(K.int_shape(incoming_layer)[1]-K.int_shape(layer)[1])/2)),int(np.ceil(np.abs(K.int_shape(incoming_layer)[1]-K.int_shape(layer)[1])/2)))\n pad_tpl2 = (int(np.floor(np.abs(K.int_shape(incoming_layer)[2]-K.int_shape(layer)[2])/2)),int(np.ceil(np.abs(K.int_shape(incoming_layer)[2]-K.int_shape(layer)[2])/2)))\n #print(pad_tpl)\n if K.int_shape(incoming_layer)[1] < K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] < K.int_shape(layer)[2]:\n padded = ZeroPadding2D(padding=(pad_tpl1, pad_tpl2))(incoming_layer)\n layer = Concatenate()([layer, padded])\n elif K.int_shape(incoming_layer)[1] < K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] >= K.int_shape(layer)[2]:\n padded1 = ZeroPadding2D(padding=(pad_tpl1, 0))(incoming_layer)\n padded2 = ZeroPadding2D(padding=(0, pad_tpl2))(layer)\n layer = Concatenate()([padded1, padded2])\n elif K.int_shape(incoming_layer)[1] >= K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] < K.int_shape(layer)[2]:\n padded1 = ZeroPadding2D(padding=(0, pad_tpl2))(incoming_layer)\n padded2 = ZeroPadding2D(padding=(pad_tpl1, 0))(layer)\n layer= Concatenate()([padded1, padded2])\n else:\n #print(layer.shape)\n padded = ZeroPadding2D(padding=(pad_tpl1, pad_tpl2))(layer)\n #print(padded.shape)\n #print(incoming_layer.shape)\n layer= Concatenate()([padded, incoming_layer])\n else:\n layer= Concatenate()([layer, incoming_layer])\n return layer\n\n def pool_pad_connect(self, layer, incoming_layer,dropout_val):\n if K.int_shape(incoming_layer)[1] != K.int_shape(layer)[1] or K.int_shape(incoming_layer)[2] != K.int_shape(layer)[2]:\n #print('layer dimensions:')\n #print(K.int_shape(layer)[1], K.int_shape(layer)[2])\n #print('incoming_layer dimensions:')\n #print(K.int_shape(incoming_layer)[1], K.int_shape(incoming_layer)[2])\n if K.int_shape(incoming_layer)[1] < K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] < K.int_shape(layer)[2]:\n pass\n elif K.int_shape(incoming_layer)[1] < K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] >= K.int_shape(layer)[2]:\n scalar = int(np.ceil(K.int_shape(incoming_layer)[2] / K.int_shape(layer)[2]))\n incoming_layer = MaxPooling2D(pool_size=(1, scalar), strides=(1, scalar), padding='same')(incoming_layer)\n print('warning: code used that is not tested, see: all_cnn_bi_skippy.py --> pool_pad_connect()')\n elif K.int_shape(incoming_layer)[1] >= K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] < K.int_shape(layer)[2]:\n scalar = int(np.ceil(K.int_shape(incoming_layer)[1] / K.int_shape(layer)[1]))\n incoming_layer = MaxPooling2D(pool_size=(scalar, 1), strides=(scalar, 1), padding='same')(incoming_layer)\n print('warning: code used that is not tested, see: all_cnn_bi_skippy.py --> pool_pad_connect()')\n else: #K.int_shape(incoming_layer)[1] > K.int_shape(layer)[1] and K.int_shape(incoming_layer)[2] > K.int_shape(layer)[2]\n scalar_1 = int(np.ceil(K.int_shape(incoming_layer)[1] / K.int_shape(layer)[1]))\n scalar_2 = int(np.ceil(K.int_shape(incoming_layer)[2] / K.int_shape(layer)[2]))\n incoming_layer = MaxPooling2D(pool_size=(scalar_1, scalar_2), strides=(scalar_1, scalar_2), padding='same')(incoming_layer)\n #print('Did a max pool')\n if dropout_val is not None:\n incoming_layer = Dropout(dropout_val)(incoming_layer)\n return self.pad_and_connect(layer, incoming_layer)\n\n def start_skip(self,layer):\n for j in range(len(self.skip_ints)):\n if self.skip_ints_count[j] > 1 and self.startpoint(self.identity,self.skip_ints[j]):#CHRIS skip connections smaller than 2 are not made, thus mean no skip connection.\n self.skip_connections.append([layer,self.skip_ints_count[j],self.layer_num,None])#save layer output, skip counter, layer this skip connection starts (to remove duplicates)\n return layer\n \n def end_skip(self,layer,filters,kernel,regulizer,act):\n for j in range(len(self.skip_connections)):\n self.skip_connections[j][1] -= 1 #decrease skip connection counters\n j = 0\n prev_skip = -1\n connected = False #CHRIS check if an end skip connection is made\n while j < len(self.skip_connections):\n if self.skip_connections[j][1] <= 0:\n #print(prev_skip,self.skip_connections[j][2])\n if prev_skip != self.skip_connections[j][2]:#this removes skip connection duplicates (works because same skip connections are next to eachother) TODO maybe better to make more robust\n #CHRIS TODO add pooling, because this becomes too complex to train\n #layer = self.pad_and_connect(layer, self.skip_connections[j][0])#CHRIS warning! pad_and_connect does not do dropout!\n layer = self.pool_pad_connect(layer, self.skip_connections[j][0],self.skip_connections[j][3])\n connected = True#CHRIS an end skip connection is made\n #if upscaling is desired: (can result in enormous tensors though)\n #shape1 = K.int_shape(layer)\n #shape2 = K.int_shape(self.skip_connections[j][0])\n #gcd_x = gcd(shape1[1], shape2[1])\n #gcd_y = gcd(shape1[2], shape2[2])\n #scale1 =shape2[1] // gcd_x, shape2[2] // gcd_y\n #scale2 =shape1[1] // gcd_x, shape1[2] // gcd_y\n #upscaled1 = UpSampling2D(size=scale1, interpolation='nearest')(layer)\n #upscaled2 = UpSampling2D(size=scale2, interpolation='nearest')(self.skip_connections[j][0])\n #layer = keras.layers.Concatenate()([upscaled1, upscaled2])\n prev_skip = self.skip_connections[j][2]\n del self.skip_connections[j]\n else:\n j += 1\n if connected and K.int_shape(layer)[3] > filters:#CHRIS we only want projection if an end skip connection is made, hence: ''connected''\n #CHRIS convolution to bound amount of features\n #CHRIS can funcion as addition, or projection followed by addition\n layer = Conv2D(filters, (1,1), padding='same', kernel_regularizer=l2(regulizer), bias_regularizer=l2(regulizer))(layer)#CHRIS kernel value set to (1,1) in order to simply act as projection\n #layer = Activation(act)(layer)\n for j in range(len(self.skip_connections)):#CHRIS TODO this is a bit hacky\n self.skip_connections[j][1] += 1 #decrease skip connection counters\n return layer\n\n def connect_skip(self,layer,filters,kernel,regulizer,act):\n \n #end skip connections\n layer = self.end_skip(layer,filters,kernel,regulizer,act)\n for j in range(len(self.skip_connections)):#CHRIS TODO this is a bit hacky\n self.skip_connections[j][1] -= 1 #decrease skip connection counters\n \n #start skip connections\n layer = self.start_skip(layer)\n \n self.layer_num +=1 #increase layer number where currently building takes place\n return layer\n\n\ndef CNN_conf(cfg,epochs=1,test=False,gpu_no=0,verbose=0,save_name='skippy_test_train_hist',data_augmentation=False):\n batch_size = 100\n num_classes = 100\n num_predictions = 20\n logfile = 'mnist-cnn.log'\n savemodel = False\n\n # The data, shuffled and split between train and test sets:\n #(x_train, y_train), (x_test, y_test) = mnist.load_data()\n (x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine')#mnist.load_data()\n \n #CHRIS reshape only needed for mnist\n #x_train = x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)\n #x_test = x_test.reshape(x_test.shape[0],x_test.shape[1],x_test.shape[2],1)\n \n cfg_df = pd.DataFrame(cfg, index=[0])\n\n # Convert class vectors to binary class matrices.\n y_train = keras.utils.to_categorical(y_train.flatten(), num_classes)\n y_test = keras.utils.to_categorical(y_test.flatten(), num_classes)\n \n #print('skip steps:')\n #print([cfg['skint_0'],cfg['skint_1'],cfg['skint_2']],[cfg['skst_0'],cfg['skst_1'],cfg['skst_2']])\n #(skip_ints,skip_ints_count) passed to Skip_manager constructor TODO get from cfg vector\n skint_0 = 0\n skint_1 = 0\n skint_2 = 0\n skint_3 = 0\n skint_4 = 0\n \n network_depth = cfg['stack_0'] + cfg['stack_1'] + cfg['stack_2'] + cfg['stack_3'] + cfg['stack_4'] + cfg['stack_5'] + cfg['stack_6']+7\n if cfg['skstep_0'] > 1:\n cnt = 0\n skint_0 = 1\n while cnt <= network_depth:\n skint_0 = skint_0 << cfg['skstep_0']\n skint_0 += 1\n cnt += cfg['skstep_0']\n skint_0 = skint_0 << cfg['skstart_0']\n\n if cfg['skstep_1'] > 1:\n cnt = 0\n skint_1 = 1\n while cnt <= network_depth:\n skint_1 = skint_1 << cfg['skstep_1']\n skint_1 += 1\n cnt += cfg['skstep_1']\n skint_1 = skint_1 << cfg['skstart_1']\n\n if cfg['skstep_2'] > 1:\n cnt = 0\n skint_2 = 1\n while cnt <= network_depth:\n skint_2 = skint_2 << cfg['skstep_2']\n skint_2 += 1\n cnt += cfg['skstep_2']\n skint_2 = skint_2 << cfg['skstart_2']\n\n if cfg['skstep_3'] > 1:\n cnt = 0\n skint_3 = 1\n while cnt <= network_depth:\n skint_3 = skint_3 << cfg['skstep_3']\n skint_3 += 1\n cnt += cfg['skstep_3']\n skint_3 = skint_3 << cfg['skstart_3']\n\n if cfg['skstep_4'] > 1:\n cnt = 0\n skint_4 = 1\n while cnt <= network_depth:\n skint_4 = skint_4 << cfg['skstep_4']\n skint_4 += 1\n cnt += cfg['skstep_4']\n skint_4 = skint_4 << cfg['skstart_4']\n \n skip_manager = Skip_manager([skint_0,skint_1,skint_2,skint_3,skint_4],[cfg['skstep_0'],cfg['skstep_1'],cfg['skstep_2'],cfg['skstep_3'],cfg['skstep_4']])\n \n #skip_manager = Skip_manager([0,0,0,0,0],[cfg['skstep_0'],cfg['skstep_1'],cfg['skstep_2'],cfg['skstep_3'],cfg['skstep_4']])\n \n input1 = keras.layers.Input(shape=(x_train.shape[1],x_train.shape[2],x_train.shape[3]))\n layer=input1\n\n filter_amount = x_train.shape[3]#CHRIS the filter amount for the sake of skip connections lags a bit behind the stack it is in, so it must be assigned separately\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_0'],cfg['l2'],cfg['activation'])\n \n layer = Dropout(cfg['dropout_0'],input_shape=x_train.shape[1:])(layer)#CHRIS TODO reengage this line!\n skip_manager.set_dropout(cfg['dropout_0'])\n #CHRIS removed following:\n #layer = Conv2D(cfg['filters_0'], (cfg['k_0'], cfg['k_0']), padding='same',kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n #layer = Activation(cfg['activation'])(layer)#kernel_initializer='random_uniform',\n #layer = skip_manager.connect_skip(layer)\n\n \n #stack 0\n for i in range(cfg['stack_0']):\n filter_amount = cfg['filters_0']\n layer = Conv2D(cfg['filters_0'], (cfg['k_0'], cfg['k_0']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_0'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_0']>0):\n #maxpooling as cnn\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_1']\n layer = Conv2D(cfg['filters_1'], (cfg['k_1'], cfg['k_1']), strides=(cfg['s_0'], cfg['s_0']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_0'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_0'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_1'], cfg['k_1']), strides=(cfg['s_0'], cfg['s_0']), padding='same')(layer)\n layer = Dropout(cfg['dropout_1'])(layer)\n skip_manager.set_dropout(cfg['dropout_1'])\n \n #stack 1\n for i in range(cfg['stack_1']):\n filter_amount = cfg['filters_2']\n layer = Conv2D(cfg['filters_2'], (cfg['k_2'], cfg['k_2']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_2'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_1']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_3']\n layer = Conv2D(cfg['filters_3'], (cfg['k_3'], cfg['k_3']), strides=(cfg['s_1'], cfg['s_1']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_2'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_2'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_3'], cfg['k_3']), strides=(cfg['s_1'], cfg['s_1']), padding='same')(layer)\n layer = Dropout(cfg['dropout_2'])(layer)\n skip_manager.set_dropout(cfg['dropout_2'])\n\n #stack 2\n for i in range(cfg['stack_2']):\n filter_amount = cfg['filters_4']\n layer = Conv2D(cfg['filters_4'], (cfg['k_4'], cfg['k_4']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_4'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_2']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_5']\n layer = Conv2D(cfg['filters_5'], (cfg['k_5'], cfg['k_5']), strides=(cfg['s_2'], cfg['s_2']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_4'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_4'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_5'], cfg['k_5']), strides=(cfg['s_2'], cfg['s_2']), padding='same')(layer)\n layer = Dropout(cfg['dropout_3'])(layer)\n skip_manager.set_dropout(cfg['dropout_3'])\n\n #stack 3\n for i in range(cfg['stack_3']):\n filter_amount = cfg['filters_6']\n layer = Conv2D(cfg['filters_6'], (cfg['k_6'], cfg['k_6']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_6'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_3']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_7']\n layer = Conv2D(cfg['filters_7'], (cfg['k_7'], cfg['k_7']), strides=(cfg['s_3'], cfg['s_3']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_6'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_6'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_7'], cfg['k_7']), strides=(cfg['s_3'], cfg['s_3']), padding='same')(layer)\n layer = Dropout(cfg['dropout_4'])(layer)\n skip_manager.set_dropout(cfg['dropout_4'])\n\n #stack 4\n for i in range(cfg['stack_4']):\n filter_amount = cfg['filters_8']\n layer = Conv2D(cfg['filters_8'], (cfg['k_8'], cfg['k_8']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_8'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_4']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_9']\n layer = Conv2D(cfg['filters_9'], (cfg['k_9'], cfg['k_9']), strides=(cfg['s_4'], cfg['s_4']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_8'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_8'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_9'], cfg['k_9']), strides=(cfg['s_4'], cfg['s_4']), padding='same')(layer)\n layer = Dropout(cfg['dropout_5'])(layer)\n skip_manager.set_dropout(cfg['dropout_5'])\n\n #stack 5\n for i in range(cfg['stack_5']):\n filter_amount = cfg['filters_10']\n layer = Conv2D(cfg['filters_10'], (cfg['k_10'], cfg['k_10']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_10'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_5']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_11']\n layer = Conv2D(cfg['filters_11'], (cfg['k_11'], cfg['k_11']), strides=(cfg['s_5'], cfg['s_5']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_10'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_10'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_11'], cfg['k_11']), strides=(cfg['s_5'], cfg['s_5']), padding='same')(layer)\n layer = Dropout(cfg['dropout_6'])(layer)\n skip_manager.set_dropout(cfg['dropout_6'])\n\n #stack 6\n for i in range(cfg['stack_6']):\n filter_amount = cfg['filters_12']\n layer = Conv2D(cfg['filters_12'], (cfg['k_12'], cfg['k_12']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_12'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n if (cfg['stack_6']>0):\n if not (cfg['max_pooling']):\n filter_amount = cfg['filters_13']\n layer = Conv2D(cfg['filters_13'], (cfg['k_13'], cfg['k_13']), strides=(cfg['s_6'], cfg['s_6']), padding='same', kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = skip_manager.connect_skip(layer,filter_amount,cfg['k_12'],cfg['l2'],cfg['activation'])\n layer = Activation(cfg['activation'])(layer)\n else:\n #layer = skip_manager.end_skip(layer,filter_amount,cfg['k_12'],cfg['l2'],cfg['activation'])\n layer = MaxPooling2D(pool_size=(cfg['k_13'], cfg['k_13']), strides=(cfg['s_6'], cfg['s_6']), padding='same')(layer)\n layer = Dropout(cfg['dropout_7'])(layer)\n skip_manager.set_dropout(cfg['dropout_7'])\n\n #layer = input1#TODO remove this\n #global averaging\n if (cfg['global_pooling']):\n layer = GlobalAveragePooling2D()(layer)\n layer = Dropout(cfg['dropout_7'])(layer)\n else:\n layer = Flatten()(layer)\n \n \n #head\n if cfg['dense_size_0'] > 0:\n layer = Dense(cfg['dense_size_0'], kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = Activation(cfg['activation'])(layer)\n layer = Dropout(cfg['dropout_8'])(layer)\n if cfg['dense_size_1'] > 0:\n layer = Dense(cfg['dense_size_1'], kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n layer = Activation(cfg['activation'])(layer)\n layer = Dropout(cfg['dropout_9'])(layer)\n layer = Dense(num_classes, kernel_regularizer=l2(cfg['l2']), bias_regularizer=l2(cfg['l2']))(layer)\n out = Activation(cfg['activ_dense'])(layer)\n \n cfg['decay'] = cfg['lr'] / float(epochs)\n def step_decay(epoch):\n initial_lrate = cfg['lr']\n drop = 0.1\n epochs_drop = 20.0\n lrate = initial_lrate * math.pow(drop, \n math.floor((1+epoch)/epochs_drop))\n return lrate\n\n hist_func = TimedAccHistory()\n callbacks = [hist_func]\n if (cfg['step'] == True):\n callbacks = [LearningRateScheduler(step_decay),hist_func]\n cfg['decay'] = 0.\n\n # initiate RMSprop optimizer\n #opt = keras.optimizers.rmsprop(lr= cfg['lr'], decay=cfg['decay'])\n opt = keras.optimizers.SGD(lr=cfg['lr'], momentum=0.9, decay=cfg['decay'], nesterov=False)\n\n model = keras.models.Model(inputs=input1, outputs=out)\n\n # Let's train the model using RMSprop\n model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])#TODO 'adam' moet zijn: opt\n #model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\n if test:\n return model #TODO remove this, just for testing\n \n #print(\"amount of parameters:\")\n #print(model.count_params())\n #CHRIS test if gpu has enough memory\n #nvmlInit()\n #handle = nvmlDeviceGetHandleByIndex(int(gpu_no))\n #meminfo = nvmlDeviceGetMemoryInfo(handle)\n #max_size = meminfo.total #6689341440\n #if meminfo.free/1024.**2 < 1.0:\n # print('gpu is allready in use')\n #nvmlShutdown()\n #if model.count_params()*4*2 >= max_size:#CHRIS *4*2: 4 byte per parameter times 2 for backpropagation\n #print('network too large for memory')\n #return 1000000000.0*(model.count_params()*4*2/max_size), 5.0*(model.count_params()*4*2/max_size)\n\n #max_size = 32828802 * 2 #CHRIS twice as large as RESnet-34-like implementation\n #max_size = 129200130 #CHRIS twice as wide as RESnet-34-like implementation with batchsize=10, one network of this size was able to be ran on tritanium gpu\n max_size = 130374394 #CHRIS twice as wide as RESnet-34-like implementation with batchsize=100, one network of this size was able to be ran on tritanium gpu\n #if model.count_params() > max_size:\n #print('network too large for implementation')\n #return 1000000000.0*(model.count_params()/max_size), 5.0*(model.count_params()/max_size)\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n if not data_augmentation:#CHRIS data augmentation handles normalization\n x_train /= 255.\n x_test /= 255.\n\n if not data_augmentation:\n print('Not using data augmentation.')\n start = time.time()\n hist = model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n callbacks=callbacks,\n verbose=verbose,\n shuffle=True)\n stop = time.time()\n else:\n print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n featurewise_center=cfg['featurewise_center'], # set input mean to 0 over the dataset\n samplewise_center=cfg['samplewise_center'], # set each sample mean to 0\n featurewise_std_normalization=cfg['featurewise_std_normalization'], # divide inputs by std of the dataset\n samplewise_std_normalization=cfg['samplewise_std_normalization'], # divide each input by its std\n zca_epsilon=cfg['zca_epsilon'],\n zca_whitening=cfg['zca_whitening'], # apply ZCA whitening\n rotation_range=cfg['rotation_range'], # randomly rotate images in the range (degrees, 0 to 180)\n width_shift_range=cfg['width_shift_range'], # randomly shift images horizontally (fraction of total width)\n height_shift_range=cfg['height_shift_range'], # randomly shift images vertically (fraction of total height)\n shear_range=cfg['shear_range'],\n zoom_range=cfg['zoom_range'],\n channel_shift_range=cfg['channel_shift_range'],\n fill_mode=cfg['fill_mode'],#('constant','nearest',reflect','wrap')\n cval=cfg['cval'],\n horizontal_flip=cfg['horizontal_flip'], # randomly flip images\n vertical_flip=cfg['vertical_flip'], # randomly flip images\n rescale=1/255.0)\n datagen.fit(x_train)\n\n # Fit the model on the batches generated by datagen.flow().\n start = time.time()\n hist = model.fit_generator(datagen.flow(x_train, y_train,\n batch_size=batch_size), verbose=verbose,\n callbacks=callbacks,\n epochs=epochs, steps_per_epoch = len(x_train)/batch_size,\n validation_data=(x_test, y_test))\n stop = time.time()\n\n timer = stop-start\n #print('run-time:')\n #print(timer)\n\n #CHRIS append network training history to file\n eval_training_hist = [time.time(),hist.history['val_acc'], hist_func.timed]\n with open(save_name + '_eval_train_hist.json', 'a') as outfile:\n json.dump(eval_training_hist,outfile)\n outfile.write('\\n')\n\n if savemodel:\n model.save('best_model_mnist.h5')\n maxval = max(hist.history['val_acc'])\n #loss = -1 * math.log( 1.0 - max(hist.history['val_acc']) ) #np.amin(hist.history['val_loss'])\n loss = -1 * math.log(max(hist.history['val_acc']) ) #CHRIS minimizing this will maximize accuracy\n #print('max val_acc:')\n #print(max(hist.history['val_acc']))\n #print('loss:')\n #print(loss)\n #perf5 = max(hist.history['val_top_5_categorical_accuracy'])\n\n if logfile is not None:\n log_file = logfile #os.path.join(data_des, logfile)\n cfg_df['perf'] = maxval\n\n # save the configurations to log file\n if os.path.isfile(log_file): \n cfg_df.to_csv(log_file, mode='a', header=False, index=False)\n else:\n cfg_df.to_csv(log_file, mode='w', header=True, index=False)\n return timer,loss\n\n#CHRIS testcode\ndef test_skippy():\n from mipego.mipego import Solution #TODO remove this, only for testing\n from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace\n from keras.utils import plot_model\n #define the search space.\n #objective = obj_func('./all-cnn_bi.py')\n activation_fun = [\"softmax\"]\n activation_fun_conv = [\"elu\",\"relu\",\"tanh\",\"sigmoid\",\"selu\"]\n\n filters = OrdinalSpace([10, 100], 'filters') * 14 #TODO [0,100] should be [0,600]\n kernel_size = OrdinalSpace([1, 8], 'k') * 14\n strides = OrdinalSpace([1, 5], 's') * 7\n stack_sizes = OrdinalSpace([0, 4], 'stack') * 7 #TODO [0,4] should be [0,7]\n\n activation = NominalSpace(activation_fun_conv, \"activation\") # activation function\n activation_dense = NominalSpace(activation_fun, \"activ_dense\") # activation function for dense layer\n step = NominalSpace([True, False], \"step\") # step\n global_pooling = NominalSpace([True, False], \"global_pooling\") # global_pooling\n \n #skippy parameters\n skstart = OrdinalSpace([0, 50], 'skstart') * 5\n skstep = OrdinalSpace([1, 50], 'skstep') * 5\n max_pooling = NominalSpace([True, False], \"max_pooling\")\n dense_size = OrdinalSpace([0,2000],'dense_size')*2\n #skippy parameters\n\n drop_out = ContinuousSpace([1e-5, .9], 'dropout') * 10 # drop_out rate\n lr_rate = ContinuousSpace([1e-4, 1.0e-0], 'lr') # learning rate\n l2_regularizer = ContinuousSpace([1e-5, 1e-2], 'l2')# l2_regularizer\n\n search_space = stack_sizes * strides * filters * kernel_size * activation * activation_dense * drop_out * lr_rate * l2_regularizer * step * global_pooling * skstart * skstep * max_pooling * dense_size\n \n n_init_sample = 1\n samples = search_space.sampling(n_init_sample)\n print(samples)\n var_names = search_space.var_name.tolist()\n print(var_names)\n \n #a sample\n #samples = [[1, 1, 1, 1, 2, 3, 10, 10, 5, 10, 10, 10, 10, 3, 4, 2, 1, 3, 1, 3, 'relu', 'softmax', 0.7105013348601977, 0.24225495530708516, 0.5278997344637044, 0.7264822991098491, 0.0072338759099408985, 0.00010867041652507452, False, True]]\n\n #test parameters\n #original parameters\n #RESnet-34-like\n stack_0 = 1\n stack_1 = 6\n stack_2 = 4\n stack_3 = 4\n stack_4 = 6\n stack_5 = 6\n stack_6 = 6\n s_0=2#1#2\n s_1=2\n s_2=1#1\n s_3=2\n s_4=1\n s_5=2\n s_6=1\n filters_0=64\n filters_1=64\n filters_2=64\n filters_3=64\n filters_4=128\n filters_5=128\n filters_6=128\n filters_7=128\n filters_8=256\n filters_9=256\n filters_10=256\n filters_11=256\n filters_12=512\n filters_13=512\n k_0=7\n k_1=1\n k_2=3\n k_3=1\n k_4=3\n k_5=1\n k_6=3\n k_7=1\n k_8=3\n k_9=1\n k_10=3\n k_11=1\n k_12=3\n k_13=1\n activation='relu'\n activ_dense='softmax'\n dropout_0=0.001\n dropout_1=0.001\n dropout_2=0.001\n dropout_3=0.001\n dropout_4=0.001\n dropout_5=0.001\n dropout_6=0.001\n dropout_7=0.001\n dropout_8=0.001\n dropout_9=0.001\n lr=0.01\n l2=0.0001\n step=False#True\n global_pooling=True\n\n #skippy parameters\n om_en_om = 1\n ranges = [stack_6,stack_5,stack_4,stack_3,stack_2,stack_1,stack_0]\n for w in range(len(ranges)):#TODO testcode: remove\n om_en_om = om_en_om << 1\n for z in range(ranges[w]//2):\n om_en_om = om_en_om << 2\n om_en_om += 1\n om_en_om = om_en_om << 1\n skstart_0 = 1#inv_gray(om_en_om)#3826103921638#2**30-1\n skstart_1 = 1#19283461627361826#2**30-1\n skstart_2 = 1#473829102637452916#2**30-1\n skstart_3 = 1#473829102637452916#2**30-1\n skstart_4 = 1#473829102637452916#2**30-1\n skstep_0 = 2\n skstep_1 = 1\n skstep_2 = 1\n skstep_3 = 1\n skstep_4 = 1\n max_pooling = True\n dense_size_0 = 1000\n dense_size_1 = 0\n #skippy parameters\n\n #assembling parameters\n samples = [[stack_0, stack_1, stack_2, stack_3, stack_4, stack_5, stack_6, s_0, s_1, s_2, s_3, s_4, s_5, s_6, filters_0, filters_1, filters_2, filters_3, filters_4, filters_5, filters_6, filters_7, filters_8, filters_9, filters_10, filters_11, filters_12, filters_13,k_0, k_1, k_2, k_3, k_4, k_5, k_6, k_7, k_8, k_9, k_10, k_11, k_12, k_13, activation, activ_dense, dropout_0, dropout_1, dropout_2, dropout_3, dropout_4, dropout_5, dropout_6, dropout_7, dropout_8, dropout_9, lr, l2, step, global_pooling, skstart_0, skstart_1, skstart_2, skstart_3, skstart_4, skstep_0, skstep_1, skstep_2, skstep_3, skstep_4, max_pooling, dense_size_0, dense_size_1]]\n \n #var_names\n #['stack_0', 'stack_1', 'stack_2', 's_0', 's_1', 's_2', 'filters_0', 'filters_1', 'filters_2', 'filters_3', 'filters_4', 'filters_5', 'filters_6', 'k_0', 'k_1', 'k_2', 'k_3', 'k_4', 'k_5', 'k_6', 'activation', 'activ_dense', 'dropout_0', 'dropout_1', 'dropout_2', 'dropout_3', 'lr', 'l2', 'step', 'global_pooling']\n\n \n X = [Solution(s, index=k, var_name=var_names) for k, s in enumerate(samples)]\n vla = {'s_2': 7, 'lr': 0.005478541674651396, 'skstep_2': 4, 'dropout_8': 0.5440199827441856, 'k_12': 15, 'activ_dense': 'softmax', 'stack_4': 3, 'k_5': 2, 'dropout_4': 0.24617655948523018, 's_3': 6, 'k_11': 13, 'filters_10': 84, 'dropout_0': 0.0639815161048702, 'k_7': 13, 'filters_9': 178, 'k_1': 13, 'dropout_6': 0.1752239013431692, 'filters_7': 353, 'skstep_4': 6, 'skstart_2': 0, 'stack_0': 0, 'stack_5': 1, 's_5': 2, 'k_13': 6, 'filters_2': 110, 'filters_0': 248, 'skstart_1': 5, 'filters_6': 341, 'filters_8': 165, 'skstart_4': 2, 'l2': 0.0012874308061650037, 's_0': 9, 'global_pooling': False, 'stack_6': 1, 's_1': 2, 'skstep_0': 4, 'dropout_3': 0.495646008202597, 'skstart_0': 3, 'k_6': 2, 'filters_1': 61, 'dropout_2': 0.028121315386701783, 'stack_3': 2, 'filters_3': 299, 'stack_1': 3, 'max_pooling': True, 'filters_4': 259, 'filters_11': 207, 'k_3': 15, 'k_0': 15, 'dense_size_0': 1400, 'k_4': 10, 's_6': 5, 'dropout_9': 0.004273458743956573, 'skstep_3': 6, 'filters_5': 16, 's_4': 2, 'dropout_1': 0.42526328646019135, 'dense_size_1': 2990, 'k_10': 9, 'k_2': 4, 'skstep_1': 6, 'dropout_5': 0.3927105783290164, 'filters_12': 283, 'dropout_7': 0.01357058138235737, 'activation': 'selu', 'filters_13': 228, 'step': False, 'k_8': 2, 'k_9': 2, 'skstart_3': 1, 'stack_2': 3}\n print(X)\n print(X[0].to_dict())\n #cfg = [Solution(x, index=len(self.data) + i, var_name=self.var_names) for i, x in enumerate(X)]\n test = False\n if test:\n #model = CNN_conf(X[0].to_dict(),test=test)\n model = CNN_conf(vla,test=test)\n plot_model(model, to_file='model_skippy_test.png',show_shapes=True,show_layer_names=True)\n model.summary()\n print(model.count_params())\n print(str(model.count_params() * 4 * 2 / 1024/1024/1024) + ' Gb')\n else:\n #timer, loss = CNN_conf(X[0].to_dict(),test=test,epochs= 2000,verbose=1)\n timer, loss = CNN_conf(vla,test=test,epochs= 2000,verbose=1)\n print('timer, loss:')\n print(timer, loss)\n\nif __name__ == '__main__':#CHRIS TODO will this wreck the entire method?\n #system arguments (configuration)\n if len(sys.argv) > 2 and sys.argv[1] == '--cfg':\n cfg = eval(sys.argv[2])\n if len(sys.argv) > 3:\n gpu = sys.argv[3]\n epochs = int(sys.argv[4])\n save_name = str(sys.argv[5])\n \n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=str(gpu)\n print(CNN_conf(cfg,gpu_no=gpu,epochs=epochs,save_name=save_name))\n K.clear_session()\n else:\n print('switching to test mode')\n test_skippy()\n", "import json\nimport sys\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\n\nfile_name = str(sys.argv[1])\neval_data = []\nwith open(file_name) as f:\n for line in f:\n eval_data.append(json.loads(line))\nplt.xlabel('epochs')\n#plt.xlabel('time (hours)')\nplt.ylabel('accuracy')\n\nfor i in eval_data:\n y_train = i[1]\n y_val = i[2]\n x = i[3]\n for j in range(len(x)):\n x[j] /= 60*60\n x = [i + 1 for i in range(len(y))]\n plt.plot(x,y_train,'orange')\n plt.plot(x,y_val,'blue')\n\nplt.show()\n" ]
[ [ "tensorflow.set_random_seed", "pandas.DataFrame" ], [ "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ElTapia/computacion-grafica
[ "8d6ec5e1bd2426093f253da9a197a7b74bb656a9", "8d6ec5e1bd2426093f253da9a197a7b74bb656a9" ]
[ "Ejercicios/Ejercicio_6/grafica/scene_graph.py", "Ejercicios/Ejercicio_5/grafica/ex_curves.py" ]
[ "# coding=utf-8\r\n\"\"\"A simple scene graph class and functionality\"\"\"\r\n\r\nfrom OpenGL.GL import *\r\nimport OpenGL.GL.shaders\r\nimport numpy as np\r\nimport grafica.transformations as tr\r\nimport grafica.gpu_shape as gs\r\n\r\n__author__ = \"Daniel Calderon\"\r\n__license__ = \"MIT\"\r\n\r\n\r\nclass SceneGraphNode:\r\n \"\"\"\r\n A simple class to handle a scene graph\r\n Each node represents a group of objects\r\n Each leaf represents a basic figure (GPUShape)\r\n To identify each node properly, it MUST have a unique name\r\n \"\"\"\r\n def __init__(self, name):\r\n self.name = name\r\n self.transform = tr.identity()\r\n self.childs = []\r\n\r\n def clear(self):\r\n \"\"\"Freeing GPU memory\"\"\"\r\n\r\n for child in self.childs:\r\n child.clear()\r\n\r\n \r\n\r\n \r\ndef findNode(node, name):\r\n\r\n # The name was not found in this path\r\n if isinstance(node, gs.GPUShape):\r\n return None\r\n\r\n # This is the requested node\r\n if node.name == name:\r\n return node\r\n \r\n # All childs are checked for the requested name\r\n for child in node.childs:\r\n foundNode = findNode(child, name)\r\n if foundNode != None:\r\n return foundNode\r\n\r\n # No child of this node had the requested name\r\n return None\r\n\r\n\r\ndef findTransform(node, name, parentTransform=tr.identity()):\r\n\r\n # The name was not found in this path\r\n if isinstance(node, gs.GPUShape):\r\n return None\r\n\r\n newTransform = np.matmul(parentTransform, node.transform)\r\n\r\n # This is the requested node\r\n if node.name == name:\r\n return newTransform\r\n \r\n # All childs are checked for the requested name\r\n for child in node.childs:\r\n foundTransform = findTransform(child, name, newTransform)\r\n if isinstance(foundTransform, (np.ndarray, np.generic) ):\r\n return foundTransform\r\n\r\n # No child of this node had the requested name\r\n return None\r\n\r\n\r\ndef findPosition(node, name, parentTransform=tr.identity()):\r\n foundTransform = findTransform(node, name, parentTransform)\r\n\r\n if isinstance(foundTransform, (np.ndarray, np.generic) ):\r\n zero = np.array([[0,0,0,1]], dtype=np.float32).T\r\n foundPosition = np.matmul(foundTransform, zero)\r\n return foundPosition\r\n\r\n return None\r\n\r\n\r\ndef drawSceneGraphNode(node, pipeline, transformName, parentTransform=tr.identity(), mode = GL_TRIANGLES):\r\n assert(isinstance(node, SceneGraphNode))\r\n\r\n # Composing the transformations through this path\r\n newTransform = np.matmul(parentTransform, node.transform)\r\n\r\n # If the child node is a leaf, it should be a GPUShape.\r\n # Hence, it can be drawn with drawCall\r\n if len(node.childs) == 1 and isinstance(node.childs[0], gs.GPUShape):\r\n leaf = node.childs[0]\r\n glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, transformName), 1, GL_TRUE, newTransform)\r\n pipeline.drawCall(leaf, mode)\r\n\r\n # If the child node is not a leaf, it MUST be a SceneGraphNode,\r\n # so this draw function is called recursively\r\n else:\r\n for child in node.childs:\r\n drawSceneGraphNode(child, pipeline, transformName, newTransform, mode)\r\n\r\n", "# coding=utf-8\r\n\"\"\"Hermite and Bezier curves using python, numpy and matplotlib\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as mpl\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n__author__ = \"Daniel Calderon\"\r\n__license__ = \"MIT\"\r\n\r\n\r\ndef generateT(t):\r\n return np.array([[1, t, t**2, t**3]]).T\r\n\r\n\r\ndef hermiteMatrix(P1, P2, T1, T2):\r\n \r\n # Generate a matrix concatenating the columns\r\n G = np.concatenate((P1, P2, T1, T2), axis=1)\r\n \r\n # Hermite base matrix is a constant\r\n Mh = np.array([[1, 0, -3, 2], [0, 0, 3, -2], [0, 1, -2, 1], [0, 0, -1, 1]]) \r\n \r\n return np.matmul(G, Mh)\r\n\r\n\r\ndef bezierMatrix(P0, P1, P2, P3):\r\n \r\n # Generate a matrix concatenating the columns\r\n G = np.concatenate((P0, P1, P2, P3), axis=1)\r\n\r\n # Bezier base matrix is a constant\r\n Mb = np.array([[1, -3, 3, -1], [0, 3, -6, 3], [0, 0, 3, -3], [0, 0, 0, 1]])\r\n \r\n return np.matmul(G, Mb)\r\n\r\n\r\ndef plotCurve(ax, curve, label, color=(0,0,1)):\r\n \r\n xs = curve[:, 0]\r\n ys = curve[:, 1]\r\n zs = curve[:, 2]\r\n \r\n ax.plot(xs, ys, zs, label=label, color=color)\r\n \r\n\r\n# M is the cubic curve matrix, N is the number of samples between 0 and 1\r\ndef evalCurve(M, N):\r\n # The parameter t should move between 0 and 1\r\n ts = np.linspace(0.0, 1.0, N)\r\n \r\n # The computed value in R3 for each sample will be stored here\r\n curve = np.ndarray(shape=(N, 3), dtype=float)\r\n \r\n for i in range(len(ts)):\r\n T = generateT(ts[i])\r\n curve[i, 0:3] = np.matmul(M, T).T\r\n \r\n return curve\r\n\r\nif __name__ == \"__main__\":\r\n \r\n \"\"\"\r\n Example for Hermite curve\r\n \"\"\"\r\n \r\n P1 = np.array([[0, 0, 1]]).T\r\n P2 = np.array([[1, 0, 0]]).T\r\n T1 = np.array([[10, 0, 0]]).T\r\n T2 = np.array([[0, 10, 0]]).T\r\n \r\n GMh = hermiteMatrix(P1, P2, T1, T2)\r\n print(GMh)\r\n \r\n # Number of samples to plot\r\n N = 50\r\n \r\n hermiteCurve = evalCurve(GMh, N)\r\n \r\n # Setting up the matplotlib display for 3D\r\n fig = mpl.figure()\r\n ax = fig.gca(projection='3d')\r\n \r\n plotCurve(ax, hermiteCurve, \"Hermite curve\", (1,0,0))\r\n \r\n \"\"\"\r\n Example for Bezier curve\r\n \"\"\"\r\n \r\n R0 = np.array([[0, 0, 1]]).T\r\n R1 = np.array([[0, 1, 0]]).T\r\n R2 = np.array([[1, 0, 1]]).T\r\n R3 = np.array([[1, 1, 0]]).T\r\n \r\n GMb = bezierMatrix(R0, R1, R2, R3)\r\n bezierCurve = evalCurve(GMb, N)\r\n \r\n plotCurve(ax, bezierCurve, \"Bezier curve\")\r\n \r\n # Adding a visualization of the control points\r\n controlPoints = np.concatenate((R0, R1, R2, R3), axis=1)\r\n ax.scatter(controlPoints[0,:], controlPoints[1,:], controlPoints[2,:], color=(1,0,0))\r\n \r\n ax.set_xlabel('x')\r\n ax.set_ylabel('y')\r\n ax.set_zlabel('z')\r\n ax.legend()\r\n mpl.show()" ]
[ [ "numpy.array", "numpy.matmul" ], [ "numpy.linspace", "numpy.matmul", "numpy.ndarray", "numpy.concatenate", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RomaKoks/Practical_RL
[ "ddcb71f9e45d4e08fe04da6404cb0e312681b615" ]
[ "week05_explore/q_learning_agent.py" ]
[ "from collections import defaultdict\nimport random\nimport math\nimport numpy as np\n\n\nclass QLearningAgent:\n def __init__(self, alpha, epsilon, discount, get_legal_actions):\n \"\"\"\n Q-Learning Agent\n based on https://inst.eecs.berkeley.edu/~cs188/sp19/projects.html\n Instance variables you have access to\n - self.epsilon (exploration prob)\n - self.alpha (learning rate)\n - self.discount (discount rate aka gamma)\n\n Functions you should use\n - self.get_legal_actions(state) {state, hashable -> list of actions, each is hashable}\n which returns legal actions for a state\n - self.get_qvalue(state,action)\n which returns Q(state,action)\n - self.set_qvalue(state,action,value)\n which sets Q(state,action) := value\n !!!Important!!!\n Note: please avoid using self._qValues directly. \n There's a special self.get_qvalue/set_qvalue for that.\n \"\"\"\n\n self.get_legal_actions = get_legal_actions\n self._qvalues = defaultdict(lambda: defaultdict(lambda: 0))\n self.alpha = alpha\n self.epsilon = epsilon\n self.discount = discount\n\n def get_qvalue(self, state, action):\n \"\"\" Returns Q(state,action) \"\"\"\n return self._qvalues[state][action]\n\n def set_qvalue(self, state, action, value):\n \"\"\" Sets the Qvalue for [state,action] to the given value \"\"\"\n self._qvalues[state][action] = value\n\n def get_value(self, state):\n \"\"\"\n Compute your agent's estimate of V(s) using current q-values\n V(s) = max_over_action Q(state,action) over possible actions.\n Note: please take into account that q-values can be negative.\n \"\"\"\n possible_actions = self.get_legal_actions(state)\n\n # If there are no legal actions, return 0.0\n if len(possible_actions) == 0:\n return 0.0\n\n value = max([self.get_qvalue(state, a) for a in possible_actions])\n return value\n\n def update(self, state, action, reward, next_state, done):\n \"\"\"\n You should do your Q-Value update here:\n Q(s,a) := (1 - alpha) * Q(s,a) + alpha * (r + gamma * V(s'))\n \"\"\"\n\n # agent parameters\n gamma = self.discount\n learning_rate = self.alpha\n \n q = reward + gamma * (1 - done) * self.get_value(next_state)\n q = (1 - learning_rate) * self.get_qvalue(state, action) + learning_rate * q\n\n self.set_qvalue(state, action, q)\n\n def get_best_action(self, state):\n \"\"\"\n Compute the best action to take in a state (using current q-values). \n \"\"\"\n possible_actions = self.get_legal_actions(state)\n\n # If there are no legal actions, return None\n if len(possible_actions) == 0:\n return None\n\n idx = np.argmax([self.get_qvalue(state, a) for a in possible_actions])\n\n return possible_actions[idx]\n\n def get_action(self, state):\n \"\"\"\n Compute the action to take in the current state, including exploration. \n With probability self.epsilon, we should take a random action.\n otherwise - the best policy action (self.get_best_action).\n\n Note: To pick randomly from a list, use random.choice(list). \n To pick True or False with a given probablity, generate uniform number in [0, 1]\n and compare it with your probability\n \"\"\"\n\n # Pick Action\n possible_actions = self.get_legal_actions(state)\n action = None\n\n # If there are no legal actions, return None\n if len(possible_actions) == 0:\n return None\n\n # agent parameters:\n epsilon = self.epsilon\n\n if np.random.rand() < epsilon:\n return np.random.choice(possible_actions)\n \n return self.get_best_action(state)" ]
[ [ "numpy.random.rand", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PansoK/slp
[ "ac55154f063245e0e4ed584c59f16370d228d8a7" ]
[ "slp/modules/norm.py" ]
[ "import torch\nimport torch.nn as nn\n\n\ndef safe_norm(x, eps=1e-5, dim=-1, keepdim=True):\n return torch.sqrt(torch.sum(torch.square(x), dim=dim, keepdim=keepdim) + eps)\n\n\nclass LayerNormTf(nn.Module):\n def __init__(self, hidden_size: int, eps: float = 1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n Link: https://github.com/huggingface/pytorch-pretrained-BERT/blob/master/pytorch_pretrained_bert/modeling.py#L234\n \"\"\"\n super(LayerNormTf, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Calculate Layernorm the tf way\"\"\"\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n\n return self.weight * x + self.bias\n\n\nclass ScaleNorm(nn.Module):\n def __init__(self, hidden_size: int, eps=1e-5):\n super(ScaleNorm, self).__init__()\n self.eps = eps\n self.g = nn.Parameter(torch.tensor(hidden_size ** 0.5))\n\n def forward(self, x: torch.Tensor):\n scaled_norm = self.g / safe_norm(x, dim=-1, keepdim=True).clamp(min=self.eps)\n\n return scaled_norm * x\n\n\n# Default to pytorch layernorm\nLayerNorm = nn.LayerNorm\n" ]
[ [ "torch.ones", "torch.zeros", "torch.sqrt", "torch.tensor", "torch.square" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ruimashita/blueoil
[ "e65d64dc0604193e2658d8e0cd6ece09260b806e" ]
[ "blueoil/datasets/pascalvoc_2007_2012.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright 2018 The Blueoil Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nimport functools\n\nimport numpy as np\n\nfrom blueoil.utils.image import load_image\nfrom blueoil.datasets.base import ObjectDetectionBase\nfrom blueoil.datasets.pascalvoc_2007 import Pascalvoc2007\nfrom blueoil.datasets.pascalvoc_2012 import Pascalvoc2012\n\n\nclass Pascalvoc20072012(ObjectDetectionBase):\n classes = default_classes = [\n \"aeroplane\",\n \"bicycle\",\n \"bird\",\n \"boat\",\n \"bottle\",\n \"bus\",\n \"car\",\n \"cat\",\n \"chair\",\n \"cow\",\n \"diningtable\",\n \"dog\",\n \"horse\",\n \"motorbike\",\n \"person\",\n \"pottedplant\",\n \"sheep\",\n \"sofa\",\n \"train\",\n \"tvmonitor\",\n ]\n num_classes = len(classes)\n available_subsets = [\"train\", \"validation\", \"test\"]\n extend_dir = None\n\n @classmethod\n @functools.lru_cache(maxsize=None)\n def count_max_boxes(cls, skip_difficult=True):\n \"\"\"Count max boxes size over all subsets.\"\"\"\n num_max_boxes = 0\n\n for subset in cls.available_subsets:\n obj = cls(subset=subset, is_shuffle=False, skip_difficult=skip_difficult)\n gt_boxes_list = obj.annotations\n\n subset_max = max([len(gt_boxes) for gt_boxes in gt_boxes_list])\n if subset_max >= num_max_boxes:\n num_max_boxes = subset_max\n\n return num_max_boxes\n\n def __init__(\n self,\n subset=\"train\",\n is_standardize=True,\n is_shuffle=True,\n skip_difficult=True,\n *args,\n **kwargs\n ):\n super().__init__(\n subset=subset,\n *args,\n **kwargs,\n )\n\n self.is_standardize = is_standardize\n self.is_shuffle = is_shuffle\n self.skip_difficult = skip_difficult\n\n self._init_files_and_annotations(*args, **kwargs)\n\n def _init_files_and_annotations(self, *args, **kwargs):\n \"\"\"Create files and annotations.\"\"\"\n if self.subset == \"train\":\n subset = \"train_validation\"\n elif self.subset == \"validation\" or self.subset == \"test\":\n subset = \"test\"\n\n if subset == \"train_validation\":\n pascalvoc_2007 = Pascalvoc2007(subset=subset, skip_difficult=self.skip_difficult, *args, **kwargs)\n pascalvoc_2012 = Pascalvoc2012(subset=subset, skip_difficult=self.skip_difficult, *args, **kwargs)\n self.files = pascalvoc_2007.files + pascalvoc_2012.files\n self.annotations = pascalvoc_2007.annotations + pascalvoc_2012.annotations\n elif subset == \"test\":\n pascalvoc_2007 = Pascalvoc2007(subset=subset, skip_difficult=self.skip_difficult, *args, **kwargs)\n self.files = pascalvoc_2007.files\n self.annotations = pascalvoc_2007.annotations\n\n @property\n def num_max_boxes(self):\n # calculate by cls.count_max_boxes(self.skip_difficult)\n if self.skip_difficult:\n return 39\n else:\n return 56\n\n @property\n def num_per_epoch(self):\n return len(self.files)\n\n def __getitem__(self, i):\n target_file = self.files[i]\n image = load_image(target_file)\n\n gt_boxes = self.annotations[i]\n gt_boxes = np.array(gt_boxes)\n gt_boxes = gt_boxes.copy() # is it really needed?\n gt_boxes = self._fill_dummy_boxes(gt_boxes)\n\n return (image, gt_boxes)\n\n def __len__(self):\n return self.num_per_epoch\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
henrymidles/LidarBot
[ "f67b5ed77671abad7267a86f425192fc6d5aad42" ]
[ "Python/Client/remote_click_control.py" ]
[ "#!/usr/bin/env python3\n\nimport socket\nimport time\nimport math\nimport threading\nimport numpy as np\nfrom util import point_direction, point_distance\nfrom queue import Queue\n#from PythonRobotics.SLAM.ICP.iterative_closest_point import icp_matching\nfrom RasPi_coms import RasPi_coms\nfrom Turtle_UI import UI\nimport sys\n\nHOST = 'raspberrypi' # The server's hostname or IP address\nPORT = 65432 # The port used by the server\n\n\"\"\" \"\"\"\nclass LidarBot():\n def __init__(self):\n self.button_queue = Queue(32)\n self.running = True\n self.moving = False\n self.path_points = [[0,0], [0,0]]\n self.scan_points = [] #np.zeros(shape=(2,500))\n self.travel_points = [[0,0]]\n self.bot_actions = Queue()\n self.last_scan_points = np.zeros(shape=(2,500))\n\n self.mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.mysocket.connect((HOST, PORT))\n\n #self.exe_thread = threading.Thread(target=self.thread_execute_actions, args=())\n #self.exe_thread.start()\n\n self.t_ui = UI(self.get_click_point)\n\n self.Raspi = RasPi_coms(self.mysocket)\n #self.lidar_thread = threading.Thread(target=self.Raspi.run, args=())\n\n\n\n \"\"\" Runs when the screen is clicked, adds click position to a queue \"\"\"\n def get_click_point(self, x, y):\n # check if click is in a button\n for key in self.t_ui.buttons:\n if point_distance(self.t_ui.buttons[key]['pos'], [x,y]) < self.t_ui.buttons[key]['size']:\n self.button_queue.put(key)\n return\n # otherwise add it to path\n self.path_points[1] = [x,y]\n\n \"\"\" Run the ICP algorithm to calculate new position, this doesn't work quite right, yet \"\"\"\n def ICP_tracking(self, curpos):\n newsize = self.scan_points.shape[1]\n lastsize = self.last_scan_points.shape[1]\n if newsize > lastsize:\n pass\n #rot, trans = icp_matching(self.last_scan_points, self.scan_points[:lastsize, :lastsize])\n elif newsize < lastsize:\n pass\n #rot, trans = icp_matching(self.last_scan_points[:newsize, :newsize], self.scan_points)\n else:\n pass\n #rot, trans = icp_matching(self.last_scan_points, self.scan_points)\n #print(time.time() - startTime)\n if startPos == True:\n curpos[0] += trans[0]\n curpos[1] += trans[1]\n self.travel_points.append([curpos[0], curpos[1]])\n else:\n curpos[0] = trans[0]\n curpos[1] = trans[1]\n startPos = True\n #print(f\"{pos[0]} , {pos[1]}\")\n return curpos\n\n \"\"\" Check for new lidar data, this data is put in a queue \"\"\"\n def check_lidar_queue(self):\n if not self.Raspi.queue.empty():\n self.scan_points.clear()\n while not self.Raspi.queue.empty():\n self.scan_points.append(self.Raspi.queue.get())\n\n # self.last_scan_points = self.scan_points.copy()\n # self.scan_points = np.zeros(shape=(2, self.Lidar.queue.qsize()))\n # idx = 0\n # while not self.Lidar.queue.empty():\n # p = self.Lidar.queue.get()\n # self.scan_points[0][idx] = p[0]\n # self.scan_points[1][idx] = p[1]\n # idx += 1\n\n \"\"\" \"\"\"\n def thread_execute_actions(self):\n while self.running:\n if not self.bot_actions.empty():\n self.moving = True\n act = self.bot_actions.get()\n\n # First, turn to correct direction\n self.mysocket.sendall(bytes(act['turn_msg'], 'UTF-8'))\n timer = round(act['turn_time'], 1)\n percentLeft = 1.0\n while timer >= 0:\n print(f\"{round(timer, 1)}\", end='\\r')\n\n curDir = percentLeft * act['turn']\n curx = act['dist'] * math.sin(math.radians(curDir))\n cury = act['dist'] * math.cos(math.radians(curDir))\n self.path_points[1] = [curx, cury]\n time.sleep(0.1)\n timer -= 0.1\n percentLeft = timer / act['turn_time']\n\n time.sleep(0.5)\n\n # Then, move correct distance\n self.mysocket.sendall(bytes(act['dist_msg'], 'UTF-8'))\n timer = round(act['dist_time'], 1)\n percentLeft = 1.0\n while timer >= 0:\n print(f\"{round(timer, 1)}\", end='\\r')\n\n curDist = percentLeft * act['dist']\n self.path_points[1] = [0, curDist]\n\n time.sleep(0.1)\n timer -= 0.1\n percentLeft = timer / act['dist_time']\n\n print(\"\")\n self.moving = False\n self.mysocket.sendall(bytes('Done\\n', 'UTF-8'))\n\n #time.sleep(0.5)\n\n \"\"\" \"\"\"\n def estimate_action_time(self, distance=None, heading=None):\n if distance != None:\n steps = abs(distance) * 97 # 97 steps / cm\n elif heading != None:\n steps = abs(heading) *17 # 17 steps / degree\n else:\n return 0\n if steps > 3570:\n acceltime = 1.43\n constVtime = (steps - 3570) / 5000\n else:\n acceltime = math.sqrt(steps/7000)\n constVtime = 0.2 # The math is a little off for short movements, so add a buffer\n return acceltime + constVtime\n \n \n \"\"\" Check what buttons were pressed, and executes the appropriate function\"\"\"\n def check_button_queue(self):\n while not self.button_queue.empty():\n key = self.button_queue.get()\n if key == 'Go' and self.moving == False:\n dist = round(point_distance(self.path_points[0], self.path_points[1]))\n dir = round(math.degrees(point_direction(self.path_points[1]))) - 90\n print(f\"X: {self.path_points[1][0]} , Y: {self.path_points[1][1]} , Distance: {round(dist, 1)} , Direction: {round(dir, 1)}\")\n if dir > 180:\n dir -= 360\n dir = -dir\n \n action = {\n \"turn\": dir,\n \"dist\": dist,\n \"turn_msg\": f\"TRN {dir}\\n\",\n \"dist_msg\": f\"MOV {dist}\\n\",\n \"turn_time\": self.estimate_action_time(heading=dir),\n \"dist_time\": self.estimate_action_time(distance=dist)\n }\n self.bot_actions.put(action)\n\n elif key == 'Stop':\n print(\"STOP\")\n msg = f\"STP0\\n\"\n self.mysocket.sendall(bytes(msg, 'UTF-8'))\n\n \"\"\" Main loop, run continiously \"\"\"\n def main(self):\n #self.lidar_thread.start()\n lastDataTime = 0\n while self.running:\n \n #self.check_lidar_queue()\n \n newPoints = self.Raspi.sync_run()\n if newPoints != None:\n self.scan_points = newPoints\n print(f\"{round(time.time() - lastDataTime, 2)}\", end='\\r')\n lastDataTime = time.time()\n #self.check_button_queue()\n\n self.t_ui.clear()\n self.t_ui.draw_bot()\n self.t_ui.draw_buttons()\n if self.moving == False: self.t_ui.draw_basic_points(self.path_points, color='red')\n else: self.t_ui.draw_basic_points(self.path_points, color='green')\n\n\n self.t_ui.draw_basic_points(self.scan_points, color='black')\n self.t_ui.update()\n \n\n\n \"\"\"\" Stop the program \"\"\"\n def stop(self):\n self.running = False\n self.Raspi.running = False\n #self.lidar_thread.join()\n print(\"Closing\")\n time.sleep(1)\n self.mysocket.shutdown(0)\n time.sleep(1)\n self.mysocket.close()\n\nif __name__ == \"__main__\":\n\n Bot = LidarBot()\n\n try:\n print(\"Starting\")\n Bot.main()\n except KeyboardInterrupt:\n Bot.stop()\n\n\n\n\n\n # con.update()\n # msg = \"[,\"\n # for a in range(len(con.axis)):\n # msg += f\"{round(con.axis[a]*255)},\"\n # msg += ']'\n # s.sendall(bytes(msg, 'UTF-8'))\n\n # data = s.recv(8192).decode('UTF-8')\n # if data[0] != 'L':\n # print(\"No Start Byte\")\n # #print(data)\n # continue\n # points = data.split(';')\n # del points[0] # first item contains start byte, so remove it\n # turtle.penup()\n # turtle.clear()\n # wn.tracer(0) # This turns off screen updates \n # turtle.color('red')\n\n # for idx, point in enumerate(path):\n # turtle.setpos(point)\n # turtle.pendown()\n # turtle.dot()\n \n # turtle.penup()\n # turtle.color('black')\n # startTime = time.time()\n # try:\n # for idx, point in enumerate(points):\n # a, r = point.split(',')\n # a = float(a)/57.3\n # r = float(r)\n # x = -r*math.cos(a)\n # y = r*math.sin(a)\n # turtle.setpos(x,y)\n # turtle.pendown()\n # turtle.dot()\n # except ValueError as e:\n # print(f\"Error at :{idx}/{len(points)}, {point}\", )\n # wn.update()\n # print(f\"\\r{time.time() - startTime}\", end='')" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jakejhansen/minesweeper_solver
[ "5eaba3f3242f08cbbb69db56e7fde4d2cd104aec" ]
[ "q_learning/train_arg.py" ]
[ "\"\"\"\nThis module contains class definitions for open ai gym environments.\n\"\"\"\n\nimport argparse\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nfrom agent import QAgent\n\ndef setup_model(mode = 0):\n\n parser = argparse.ArgumentParser(prog=\"train.py\", description=\"Train Deep Q-Network for Minesweeper game\")\n\n # Atari ROM, TensorFlow model and output directory\n parser.add_argument('--model', dest='model_file', type=str, required=False, help=\"path to TensorFlow model file\")\n parser.add_argument('--out', dest='output_dir', type=str, default=\"./q_learning/output/\", help=\"output path models and screen captures\")\n\n parser.add_argument('--train', dest=\"is_train\", action=\"store_true\", help=\"training or only playing\")\n parser.add_argument('--randomstart', dest='random_start_wait', type=int, default=30, help=\"random number of frames to wait at start of episode\")\n parser.add_argument('--game', dest='game', type=str, default=\"DemonAttack-v0\", help=\"The game we play\")\n parser.add_argument('--env', dest='env', type=str, default=\"atari\", help=\"If we want to use atari or minesweeper\")\n\n parser.add_argument('--gpumemory', dest=\"gpu_memory\", type=float, default=0.5, help=\"The percentage of GPU memory allowed to be used by Tensorflow\")\n\n # Parameters network input (screens)\n parser.add_argument('--inputheight', dest=\"input_height\", type=int, default=84, help=\"screen input height\")\n parser.add_argument('--inputwidth', dest=\"input_width\", type=int, default=84, help=\"screen input width\") \n parser.add_argument('--historylength', dest=\"history_length\", type=int, default=4, help=\"Numbe of moves which are repeated in atari\")\n parser.add_argument('--mines-min', dest=\"mines_min\", type=int, default=5, help=\"The number of mines\")\n parser.add_argument('--mines-max', dest=\"mines_max\", type=int, default=7, help=\"The number of mines\")\n parser.add_argument('--nchannels', dest=\"nchannels\", type=int, default=4, help=\"screen input depth\")\n\n parser.add_argument('--network-type', dest='network_type', type=int, default=1, help=\"Different networks\")\n\n # Parameters CNN architecture\n parser.add_argument('--filtersizes', dest=\"filter_sizes\", type=str, default=\"8,4,3\", help=\"CNN filter sizes\")\n parser.add_argument('--filterstrides', dest=\"filter_strides\", type=str, default=\"4,2,1\", help=\"CNN filter strides\")\n parser.add_argument('--numfilters', dest=\"num_filters\", type=str, default=\"32,64,64\", help=\"CNN number of filters per layer\")\n parser.add_argument('--numhidden', dest=\"num_hidden\", type=int, default=512, help=\"CNN number of neurons in FC layer\")\n parser.add_argument('--duelingtype', dest=\"dueling_type\", default=None, type=str, help=\"Type of dueling enabled\")\n # See \n # http://cs231n.github.io/neural-networks-2/\n parser.add_argument('--bias-init', dest=\"bias_init\", type=float, default=0.01, help=\"The initial value of the biases\")\n\n # Parameters for training the CNN\n parser.add_argument('--num-iterations', dest=\"num_iterations\", type=int, default=50000000, help=\"Number of training iterations, i.e., number of passes, each pass using [batch size] number of examples\")\n parser.add_argument('--batchsize', dest=\"batch_size\", type=int, default=32, help=\"training batch size\")\n parser.add_argument('--trainfreq', dest=\"train_freq\", type=int, default=4, help=\"training frequency, default every frame\")\n parser.add_argument('--epsilonstep', dest=\"epsilon_step\", type=float, default=1e6, help=\"epsilon decrease step, linear annealing over iterations\")\n parser.add_argument('--learnrate', dest=\"learning_rate\", type=float, default=0.00025, help=\"optimization learning rate\")\n parser.add_argument('--learnratedecay', dest=\"learning_rate_decay\", type=float, default=0.98, help=\"learning rate decay\")\n parser.add_argument('--learnratestep', dest=\"learning_rate_step\", type=float, default=100000, help=\"learning rate decay step over iterations\")\n parser.add_argument('--learnratemin', dest=\"learning_rate_minimum\", type=float, default=0.0001, help=\"minimum learning rate\")\n parser.add_argument('--discount', dest=\"discount\", type=float, default=0.99, help=\"gamma for future discounted rewards\")\n parser.add_argument('--clipdelta', dest=\"clip_delta\", type=bool, default=True, help=\"clipping of error term in loss function\")\n parser.add_argument('--networkupdate', dest=\"network_update_rate\", type=float, default=10000, help=\"number of steps after which the Q-network is copied for predicting targets\")\n parser.add_argument('--batchaccumulator', dest=\"batch_accumulator\", type=str, default=\"mean\", help=\"batch accumulator in loss function (mean or sum)\")\n\n parser.add_argument('--replaycap', dest=\"replay_capacity\", type=int, default=int(1e6), help=\"maximum number of samples in replay memory\")\n parser.add_argument('--trainstart', dest=\"train_start\", type=int, default=50000, help=\"start training when replay memory is of this size\")\n\n # Parameters for evaluation of the model\n parser.add_argument('--evalfreq', dest=\"eval_frequency\", type=int, default=250000, help=\"frequency of model evaluation\")\n parser.add_argument('--evaliterations', dest=\"eval_iterations\", type=int, default=125000, help=\"number of games played in each evaluation\")\n parser.add_argument('--evalepsilon', dest=\"eval_epsilon\", type=float, default=0.05, help=\"epsilon random move when evaluating\")\n parser.add_argument('--minepsilon', dest=\"min_epsilon\", type=float, default=0.1, help=\"Lowest epsilon when exploring\")\n parser.add_argument('--num-steps', dest=\"num_steps\", type=int, default=5000, help=\"Number of test steps when playing, each step is an action\")\n parser.add_argument('--reward-recent-update', dest=\"reward_recent_update\", type=int, default=10000, help=\"The number of episodes before resetting recent reward\")\n parser.add_argument('--num-games', dest=\"num_games\", type=int, default=5000, help=\"Number of test games to play minesweeper\")\n\n # Parameters for outputting/debugging\n parser.add_argument('--intsummary', dest=\"interval_summary\", type=int, default=200, help=\"frequency of adding training summaries, currently depending on train_iteration\")\n parser.add_argument('--intcheckpoint', dest=\"interval_checkpoint\", type=int, default=10000, help=\"frequency of saving model checkpoints\")\n parser.add_argument('--memorycheckpoint', dest=\"memory_checkpoint\", type=int, default=int(1e5), help=\"Frequency of saving memory based on addition counter.\")\n parser.add_argument('--restore-memory', dest=\"restore_memory\", type=bool, default=False, help=\"If True, restore replay memory.\")\n parser.add_argument('--show', dest=\"show_game\", action=\"store_true\", help=\"show the Minesweeper game output\")\n parser.add_argument('--eval-mode', dest=\"eval_mode\", \n help=\"0 = evaluate models in range (only used for selecting the best model), 1 = test model win-rate by playing the game, 2 = win-rate for random mines\")\n parser.add_argument('--seed', dest=\"seed\", type=int, default=0, help=\"The random seed value. Default at 0 means deterministic for all ops in Tensorflow 1.4\")\n\n # Parse command line arguments and run the training process\n\n parser.set_defaults(game=\"minesweeper\")\n parser.set_defaults(env='minesweeper')\n parser.set_defaults(mines_min=6)\n parser.set_defaults(mines_max=6)\n\n parser.set_defaults(input_width=6)\n parser.set_defaults(input_height=6)\n parser.set_defaults(history_length=1)\n parser.set_defaults(train_freq=1) \n parser.set_defaults(nchannels=2)\n\n parser.set_defaults(discount=0.0)\n parser.set_defaults(network_type=1) # 2 is the one for the report graph results\n #parser.set_defaults(clip_delta=True) # This does not really seem to do much since the rewards are so small\n #parser.set_defaults(dueling_type=\"mean\") # Without this and with fc, the same network as Jacob\n\n parser.set_defaults(seed=0) # 9, 11\n\n if mode == 0: # Train\n print(\"Training the network\")\n parser.set_defaults(is_train=True)\n params = parser.parse_args()\n run_model(params)\n\n elif mode == 1: # Test minesweeper\n print(\"Test minesweeper model on 6x6 board with 6 mines\")\n parser.set_defaults(output_dir='./q_learning/output_best/')\n parser.set_defaults(eval_iterations=10000)\n parser.set_defaults(model_file='model-best')\n parser.set_defaults(eval_mode=1)\n params = parser.parse_args(args=[])\n run_model(params)\n\n elif mode == 2: # Evaluate for a different number of mines\n print(\"Test minesweeper model on 6x6 board with a random number of mines\")\n parser.set_defaults(output_dir='./output_best/')\n parser.set_defaults(eval_iterations=10000)\n parser.set_defaults(model_file='model-best-random')\n parser.set_defaults(eval_mode=2)\n params = parser.parse_args()\n\n print(\"\\nTesting with best model on random number of mines\")\n run_model(params)\n\n print(\"\\nTesting with best model on board with 6 mines\")\n params.model_file = \"model-best\"\n tf.reset_default_graph()\n run_model(params)\n\n elif mode == 3: # Play 10 games\n parser.set_defaults(show_game=True)\n parser.set_defaults(output_dir='./output_best/')\n parser.set_defaults(eval_iterations=10)\n parser.set_defaults(model_file='model-best')\n parser.set_defaults(eval_mode=1)\n params = parser.parse_args()\n run_model(params)\n\n# View tensorboard with \n# tensorboard --logdir output\n\ndef run_model(params):\n\n # https://stackoverflow.com/questions/11526975/set-random-seed-programwide-in-python\n # https://stackoverflow.com/questions/30517513/global-seed-for-multiple-numpy-imports\n random.seed(params.seed)\n np.random.seed(params.seed)\n # Must be called before Session\n # https://stackoverflow.com/questions/38469632/tensorflow-non-repeatable-results/40247201#40247201\n tf.set_random_seed(params.seed)\n\n qagent = QAgent(params)\n if params.is_train:\n qagent.fit()\n elif params.eval_mode == 0:\n qagent.evaluate_mine()\n elif params.eval_mode == 1:\n qagent.test_mine()\n elif params.eval_mode == 2:\n for mines in range(1, 13):\n params.mines_min=mines\n params.mines_max=mines\n print(\"Mines =\", mines)\n qagent.test_mine()\n tf.reset_default_graph()\n qagent = QAgent(params)\n\n\nif __name__ == \"__main__\":\n setup_model(1)" ]
[ [ "tensorflow.set_random_seed", "tensorflow.reset_default_graph", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
rhjohnstone/pytorch-lightning
[ "4cd7e77ad2471379eaf768c20d8a3284aeb8b0b5", "4cd7e77ad2471379eaf768c20d8a3284aeb8b0b5" ]
[ "tests/loops/test_training_loop_flow_scalar.py", "pytorch_lightning/plugins/training_type/ddp_spawn.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data._utils.collate import default_collate\n\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom pytorch_lightning.loops.optimization.optimizer_loop import Closure\nfrom pytorch_lightning.trainer.states import RunningStage\nfrom tests.helpers.boring_model import BoringModel, RandomDataset\nfrom tests.helpers.deterministic_model import DeterministicModel\nfrom tests.helpers.utils import no_warning_call\n\n\ndef test__training_step__flow_scalar(tmpdir):\n \"\"\"Tests that only training_step can be used.\"\"\"\n\n class TestModel(DeterministicModel):\n def training_step(self, batch, batch_idx):\n acc = self.step(batch, batch_idx)\n acc = acc + batch_idx\n self.training_step_called = True\n return acc\n\n def backward(self, loss, optimizer, optimizer_idx):\n return LightningModule.backward(self, loss, optimizer, optimizer_idx)\n\n model = TestModel()\n model.val_dataloader = None\n\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_train_batches=2,\n limit_val_batches=2,\n max_epochs=2,\n log_every_n_steps=1,\n enable_model_summary=False,\n )\n trainer.fit(model)\n\n # make sure correct steps were called\n assert model.training_step_called\n assert not model.training_step_end_called\n assert not model.training_epoch_end_called\n\n\ndef test__training_step__tr_step_end__flow_scalar(tmpdir):\n \"\"\"Tests that only training_step can be used.\"\"\"\n\n class TestModel(DeterministicModel):\n def training_step(self, batch, batch_idx):\n acc = self.step(batch, batch_idx)\n acc = acc + batch_idx\n self.training_step_called = True\n self.out = acc\n return acc\n\n def training_step_end(self, tr_step_output):\n assert self.out == tr_step_output\n assert self.count_num_graphs({\"loss\": tr_step_output}) == 1\n self.training_step_end_called = True\n return tr_step_output\n\n def backward(self, loss, optimizer, optimizer_idx):\n return LightningModule.backward(self, loss, optimizer, optimizer_idx)\n\n model = TestModel()\n model.val_dataloader = None\n\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_train_batches=2,\n limit_val_batches=2,\n max_epochs=2,\n log_every_n_steps=1,\n enable_model_summary=False,\n )\n trainer.fit(model)\n\n # make sure correct steps were called\n assert model.training_step_called\n assert model.training_step_end_called\n assert not model.training_epoch_end_called\n\n\ndef test__training_step__epoch_end__flow_scalar(tmpdir):\n \"\"\"Tests that only training_step can be used.\"\"\"\n\n class TestModel(DeterministicModel):\n def training_step(self, batch, batch_idx):\n acc = self.step(batch, batch_idx)\n acc = acc + batch_idx\n\n self.training_step_called = True\n return acc\n\n def training_epoch_end(self, outputs):\n self.training_epoch_end_called = True\n\n # verify we saw the current num of batches\n assert len(outputs) == 2\n\n for b in outputs:\n # time = 1\n assert len(b) == 1\n assert \"loss\" in b\n assert isinstance(b, dict)\n\n def backward(self, loss, optimizer, optimizer_idx):\n return LightningModule.backward(self, loss, optimizer, optimizer_idx)\n\n model = TestModel()\n model.val_dataloader = None\n\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_train_batches=2,\n limit_val_batches=2,\n max_epochs=2,\n log_every_n_steps=1,\n enable_model_summary=False,\n )\n trainer.fit(model)\n\n # make sure correct steps were called\n assert model.training_step_called\n assert not model.training_step_end_called\n assert model.training_epoch_end_called\n\n # assert epoch end metrics were added\n assert len(trainer.callback_metrics) == 0\n assert len(trainer.progress_bar_metrics) == 0\n\n trainer.state.stage = RunningStage.TRAINING\n # make sure training outputs what is expected\n batch_idx, batch = 0, next(iter(model.train_dataloader()))\n train_step_out = trainer.fit_loop.epoch_loop.batch_loop.run(batch, batch_idx)\n\n assert len(train_step_out) == 1\n train_step_out = train_step_out[0][0]\n assert isinstance(train_step_out[\"loss\"], torch.Tensor)\n assert train_step_out[\"loss\"].item() == 171\n\n # make sure the optimizer closure returns the correct things\n opt_closure = trainer.fit_loop.epoch_loop.batch_loop.optimizer_loop._make_closure(\n batch, batch_idx, 0, trainer.optimizers[0]\n )\n opt_closure_result = opt_closure()\n assert opt_closure_result.item() == 171\n\n\ndef test__training_step__step_end__epoch_end__flow_scalar(tmpdir):\n \"\"\"Checks train_step + training_step_end + training_epoch_end (all with scalar return from train_step).\"\"\"\n\n class TestModel(DeterministicModel):\n def training_step(self, batch, batch_idx):\n acc = self.step(batch, batch_idx)\n acc = acc + batch_idx\n\n self.training_step_called = True\n return acc\n\n def training_step_end(self, tr_step_output):\n assert isinstance(tr_step_output, torch.Tensor)\n assert self.count_num_graphs({\"loss\": tr_step_output}) == 1\n self.training_step_end_called = True\n return tr_step_output\n\n def training_epoch_end(self, outputs):\n self.training_epoch_end_called = True\n\n # verify we saw the current num of batches\n assert len(outputs) == 2\n\n for b in outputs:\n # time = 1\n assert len(b) == 1\n assert \"loss\" in b\n assert isinstance(b, dict)\n\n def backward(self, loss, optimizer, optimizer_idx):\n return LightningModule.backward(self, loss, optimizer, optimizer_idx)\n\n model = TestModel()\n model.val_dataloader = None\n\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_train_batches=2,\n limit_val_batches=2,\n max_epochs=2,\n log_every_n_steps=1,\n enable_model_summary=False,\n )\n trainer.fit(model)\n\n # make sure correct steps were called\n assert model.training_step_called\n assert model.training_step_end_called\n assert model.training_epoch_end_called\n\n # assert epoch end metrics were added\n assert len(trainer.callback_metrics) == 0\n assert len(trainer.progress_bar_metrics) == 0\n\n trainer.state.stage = RunningStage.TRAINING\n # make sure training outputs what is expected\n batch_idx, batch = 0, next(iter(model.train_dataloader()))\n train_step_out = trainer.fit_loop.epoch_loop.batch_loop.run(batch, batch_idx)\n\n assert len(train_step_out) == 1\n train_step_out = train_step_out[0][0]\n assert isinstance(train_step_out[\"loss\"], torch.Tensor)\n assert train_step_out[\"loss\"].item() == 171\n\n # make sure the optimizer closure returns the correct things\n opt_closure = trainer.fit_loop.epoch_loop.batch_loop.optimizer_loop._make_closure(\n batch, batch_idx, 0, trainer.optimizers[0]\n )\n opt_closure_result = opt_closure()\n assert opt_closure_result.item() == 171\n\n\ndef test_train_step_no_return(tmpdir):\n \"\"\"Tests that only training_step raises a warning when nothing is returned in case of\n automatic_optimization.\"\"\"\n\n class TestModel(BoringModel):\n def training_step(self, batch, batch_idx):\n self.training_step_called = True\n loss = self.step(batch[0])\n self.log(\"a\", loss, on_step=True, on_epoch=True)\n\n def training_epoch_end(self, outputs) -> None:\n assert len(outputs) == 0, outputs\n\n def validation_step(self, batch, batch_idx):\n self.validation_step_called = True\n\n def validation_epoch_end(self, outputs):\n assert len(outputs) == 0, outputs\n\n model = TestModel()\n trainer_args = dict(default_root_dir=tmpdir, fast_dev_run=2)\n trainer = Trainer(**trainer_args)\n\n Closure.warning_cache.clear()\n\n with pytest.warns(UserWarning, match=r\"training_step` returned `None\"):\n trainer.fit(model)\n\n assert model.training_step_called\n assert model.validation_step_called\n\n model = TestModel()\n model.automatic_optimization = False\n trainer = Trainer(**trainer_args)\n\n Closure.warning_cache.clear()\n\n with no_warning_call(UserWarning, match=r\"training_step` returned `None\"):\n trainer.fit(model)\n\n\ndef test_training_step_no_return_when_even(tmpdir):\n \"\"\"Tests correctness when some training steps have been skipped.\"\"\"\n\n class TestModel(BoringModel):\n def training_step(self, batch, batch_idx):\n self.training_step_called = True\n loss = self.step(batch[0])\n self.log(\"a\", loss, on_step=True, on_epoch=True)\n return loss if batch_idx % 2 else None\n\n model = TestModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_train_batches=4,\n limit_val_batches=1,\n max_epochs=4,\n enable_model_summary=False,\n logger=False,\n enable_checkpointing=False,\n )\n\n Closure.warning_cache.clear()\n\n with pytest.warns(UserWarning, match=r\".*training_step` returned `None.*\"):\n trainer.fit(model)\n\n trainer.state.stage = RunningStage.TRAINING\n\n # manually check a few batches\n for batch_idx, batch in enumerate(model.train_dataloader()):\n out = trainer.fit_loop.epoch_loop.batch_loop.run(batch, batch_idx)\n if not batch_idx % 2:\n assert out == []\n\n\ndef test_training_step_none_batches(tmpdir):\n \"\"\"Tests correctness when the train dataloader gives None for some steps.\"\"\"\n\n class TestModel(BoringModel):\n def __init__(self):\n super().__init__()\n self.counter = 0\n\n def collate_none_when_even(self, batch):\n if self.counter % 2 == 0:\n result = None\n else:\n result = default_collate(batch)\n self.counter += 1\n return result\n\n def train_dataloader(self):\n return DataLoader(RandomDataset(32, 4), collate_fn=self.collate_none_when_even)\n\n def on_train_batch_end(self, outputs, batch, batch_idx, dataloader_idx):\n if batch_idx % 2 == 0:\n assert outputs == []\n else:\n assert outputs\n\n model = TestModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n limit_val_batches=1,\n max_epochs=4,\n enable_model_summary=False,\n logger=False,\n enable_checkpointing=False,\n )\n\n with pytest.warns(UserWarning, match=r\".*train_dataloader yielded None.*\"):\n trainer.fit(model)\n", "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport os\nimport re\nfrom multiprocessing.queues import SimpleQueue\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nimport numpy as np\nimport torch\nimport torch.distributed\nimport torch.multiprocessing as mp\nfrom torch.nn import Module\nfrom torch.nn.parallel.distributed import DistributedDataParallel\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.overrides import LightningDistributedModule\nfrom pytorch_lightning.overrides.distributed import prepare_for_backward\nfrom pytorch_lightning.overrides.torch_distributed import broadcast_object_list\nfrom pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment\nfrom pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO\nfrom pytorch_lightning.plugins.training_type.parallel import ParallelPlugin\nfrom pytorch_lightning.trainer.states import TrainerFn\nfrom pytorch_lightning.utilities import (\n _TORCH_GREATER_EQUAL_1_7,\n _TORCH_GREATER_EQUAL_1_8,\n rank_zero_deprecation,\n rank_zero_warn,\n)\nfrom pytorch_lightning.utilities.apply_func import apply_to_collection, move_data_to_device\nfrom pytorch_lightning.utilities.cloud_io import atomic_save\nfrom pytorch_lightning.utilities.cloud_io import load as pl_load\nfrom pytorch_lightning.utilities.distributed import distributed_available\nfrom pytorch_lightning.utilities.distributed import group as _group\nfrom pytorch_lightning.utilities.distributed import (\n init_dist_connection,\n rank_zero_only,\n ReduceOp,\n sync_ddp_if_available,\n)\nfrom pytorch_lightning.utilities.enums import DistributedType\nfrom pytorch_lightning.utilities.model_helpers import is_overridden\nfrom pytorch_lightning.utilities.seed import reset_seed\nfrom pytorch_lightning.utilities.types import STEP_OUTPUT\n\nif _TORCH_GREATER_EQUAL_1_8:\n from pytorch_lightning.utilities.distributed import register_ddp_comm_hook\n\nlog = logging.getLogger(__name__)\n\n\nclass DDPSpawnPlugin(ParallelPlugin):\n \"\"\"Spawns processes using the :func:`torch.multiprocessing.spawn` method and joins processes after training\n finishes.\"\"\"\n\n distributed_backend = DistributedType.DDP_SPAWN\n\n def __init__(\n self,\n parallel_devices: Optional[List[torch.device]] = None,\n num_nodes: Optional[int] = None,\n cluster_environment: Optional[ClusterEnvironment] = None,\n checkpoint_io: Optional[CheckpointIO] = None,\n sync_batchnorm: Optional[bool] = None,\n ddp_comm_state: Optional[object] = None,\n ddp_comm_hook: Optional[callable] = None,\n ddp_comm_wrapper: Optional[callable] = None,\n **kwargs: Any,\n ):\n super().__init__(\n parallel_devices=parallel_devices,\n cluster_environment=cluster_environment,\n checkpoint_io=checkpoint_io,\n )\n if num_nodes is not None:\n rank_zero_deprecation(\n \"Argument `num_nodes` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. \"\n \"Notice that it will be overriden by the trainer setting.\"\n )\n self._num_nodes = num_nodes or 1\n if sync_batchnorm is not None:\n rank_zero_deprecation(\n \"Argument `sync_batchnorm` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. \"\n \"Notice that it will be overriden by the trainer setting.\"\n )\n self._sync_batchnorm = sync_batchnorm or False\n self._ddp_kwargs = kwargs\n self.num_processes = len(parallel_devices) if parallel_devices is not None else 0\n self.mp_queue = None\n self._ddp_comm_state = ddp_comm_state\n self._ddp_comm_hook = ddp_comm_hook\n self._ddp_comm_wrapper = ddp_comm_wrapper\n self._local_rank = 0\n self.set_world_ranks()\n\n @property\n def num_nodes(self) -> int:\n return self._num_nodes\n\n @num_nodes.setter\n def num_nodes(self, num_nodes: int) -> None:\n # note that world ranks is related to num_nodes, when resetting it, need to reset world ranks\n self._num_nodes = num_nodes\n self.set_world_ranks()\n\n @property\n def sync_batchnorm(self) -> bool:\n return self._sync_batchnorm\n\n @sync_batchnorm.setter\n def sync_batchnorm(self, sync_batchnorm: bool) -> None:\n self._sync_batchnorm = sync_batchnorm\n\n @property\n def local_rank(self) -> int:\n return self._local_rank\n\n def __getstate__(self):\n \"\"\"Makes this plugin pickleable without destroying the queue in the current process.\"\"\"\n state = self.__dict__.copy()\n state[\"mp_queue\"] = None\n return state\n\n def __setstate__(self, state):\n self.__dict__ = state\n\n @property\n def root_device(self):\n return self.parallel_devices[self.local_rank]\n\n @property\n def distributed_sampler_kwargs(self):\n distributed_sampler_kwargs = dict(num_replicas=(self.num_nodes * self.num_processes), rank=self.global_rank)\n return distributed_sampler_kwargs\n\n @property\n def _is_single_process_single_device(self):\n return True\n\n def setup(self) -> None:\n os.environ[\"MASTER_PORT\"] = str(self.cluster_environment.master_port())\n # pass in a state q\n smp = mp.get_context(\"spawn\")\n self.mp_queue = smp.SimpleQueue()\n\n def _setup_model(self, model: Module) -> DistributedDataParallel:\n \"\"\"Wraps the model into a :class:`~torch.nn.parallel.distributed.DistributedDataParallel` module.\"\"\"\n return DistributedDataParallel(module=model, device_ids=self.determine_ddp_device_ids(), **self._ddp_kwargs)\n\n def set_world_ranks(self, process_idx: int = 0) -> None:\n self._local_rank = process_idx\n if self.cluster_environment is None:\n return\n self.cluster_environment.set_global_rank(self.node_rank * self.num_processes + self.local_rank)\n self.cluster_environment.set_world_size(self.num_nodes * self.num_processes)\n rank_zero_only.rank = self.cluster_environment.global_rank()\n\n def get_mp_spawn_kwargs(self, trainer: Optional[\"pl.Trainer\"] = None) -> Dict[str, Any]:\n return {\"nprocs\": self.num_processes}\n\n def start_training(self, trainer: \"pl.Trainer\") -> None:\n self.spawn(self.new_process, trainer, self.mp_queue, return_result=False)\n # reset optimizers, since main process is never used for training and thus does not have a valid optim state\n trainer.optimizers = []\n\n def start_evaluating(self, trainer: \"pl.Trainer\") -> None:\n self.spawn(self.new_process, trainer, self.mp_queue, return_result=False)\n\n def start_predicting(self, trainer: \"pl.Trainer\") -> None:\n self.spawn(self.new_process, trainer, self.mp_queue, return_result=False)\n\n def spawn(self, function: Callable, *args: Any, return_result: bool = True, **kwargs: Any) -> Optional[Any]:\n \"\"\"Spawn processes that run the given function.\n\n Args:\n function: The function to spawn processes from.\n *args: Optional positional arguments that will be passed to the function in addition to the process index.\n These arguments must be pickleable.\n return_result: If ``True``, copies the output of the function from process 0 to the main process and\n returns it.\n **kwargs: Optional named arguments that will be passed to the function in addition to the process index.\n These arguments must be pickleable.\n\n Return:\n The output of the function of process 0.\n \"\"\"\n os.environ[\"MASTER_PORT\"] = str(self.cluster_environment.master_port())\n context = mp.get_context(\"spawn\")\n return_queue = context.SimpleQueue() if return_result else None\n mp.spawn(self._wrapped_function, args=(function, args, kwargs, return_queue), nprocs=self.num_processes)\n return return_queue.get() if return_result else None\n\n def _wrapped_function(\n self, process_idx: int, function: Callable, args: Any, kwargs: Any, return_queue: Optional[SimpleQueue]\n ) -> None:\n self._worker_setup(process_idx)\n result = function(*args, **kwargs)\n if return_queue is not None and self.local_rank == 0:\n return_queue.put(move_data_to_device(result, \"cpu\"))\n\n def _worker_setup(self, process_idx: int):\n reset_seed()\n self.set_world_ranks(process_idx)\n rank_zero_only.rank = self.global_rank\n init_dist_connection(\n self.cluster_environment, self.torch_distributed_backend, self.global_rank, self.world_size\n )\n\n def new_process(self, trainer: \"pl.Trainer\", mp_queue: SimpleQueue) -> None:\n self.mp_queue = mp_queue\n\n # move the model to the correct device\n self.model_to_device()\n\n if self.sync_batchnorm:\n self.model = self.configure_sync_batchnorm(self.model)\n\n # skip wrapping the model if we are not fitting as no gradients need to be exchanged\n trainer_fn = self.lightning_module.trainer.state.fn\n if trainer_fn == TrainerFn.FITTING:\n self.configure_ddp()\n\n self.barrier()\n\n results = trainer.run_stage()\n\n # persist info in ddp_spawn\n self.__transfer_distrib_spawn_state_on_fit_end(trainer, results)\n\n # ensure that spawned processes go through teardown before joining\n trainer._call_teardown_hook()\n\n def post_dispatch(self, trainer: \"pl.Trainer\"):\n # restore main state with best weights\n best_path = self.mp_queue.get()\n last_path = self.mp_queue.get()\n self._results = self.mp_queue.get()\n # get the `callback_metrics` and set it to the trainer\n # only in case the user does not override it.\n # TODO: Remove the if in v1.7\n if is_overridden(\"get_from_queue\", self.lightning_module):\n self.lightning_module.get_from_queue(self.mp_queue)\n else:\n self.get_from_queue(trainer, self.mp_queue)\n\n # recover the weights of the processes trained in the children\n self.__recover_child_process_weights(best_path, last_path)\n\n def pre_configure_ddp(self):\n # if unset, default `find_unused_parameters` `True`\n # Many models require setting this parameter to True, as there are corner cases\n # when not all parameter backward hooks are fired by the autograd engine even if require_grad is set to True.\n # This flag does come with a performance hit, so it is suggested to disable in cases where it is possible.\n self._ddp_kwargs[\"find_unused_parameters\"] = self._ddp_kwargs.get(\"find_unused_parameters\", True)\n # todo: PyTorch 1.7.0 DDP introduces `self.reducer._rebuild_buckets()` breaking manual_optimization\n if (\n _TORCH_GREATER_EQUAL_1_7\n and not self.lightning_module.automatic_optimization\n and not self._ddp_kwargs.get(\"find_unused_parameters\", False)\n ):\n rank_zero_warn(\n \"From PyTorch 1.7.0, Lightning ``manual_optimization`` needs to set ``find_unused_parameters=True`` \"\n \"to properly work with DDP.\"\n )\n self._ddp_kwargs[\"find_unused_parameters\"] = True\n\n def _register_ddp_hooks(self) -> None:\n # currently, DDP communication hooks only work with NCCL backend and SPSD (single process single device) mode\n # https://github.com/pytorch/pytorch/blob/v1.8.0/torch/nn/parallel/distributed.py#L1080-L1084\n if _TORCH_GREATER_EQUAL_1_8 and self.on_gpu and self._is_single_process_single_device:\n register_ddp_comm_hook(\n model=self._model,\n ddp_comm_state=self._ddp_comm_state,\n ddp_comm_hook=self._ddp_comm_hook,\n ddp_comm_wrapper=self._ddp_comm_wrapper,\n )\n\n def configure_ddp(self) -> None:\n self.pre_configure_ddp()\n self._model = self._setup_model(LightningDistributedModule(self.model))\n self._register_ddp_hooks()\n\n def determine_ddp_device_ids(self):\n if self.root_device.type == \"cpu\":\n return None\n return [self.root_device.index]\n\n def __transfer_distrib_spawn_state_on_fit_end(self, trainer: \"pl.Trainer\", results: Any) -> None:\n checkpoint_callback = trainer.checkpoint_callback\n best_model_path = checkpoint_callback.best_model_path if checkpoint_callback else None\n\n # requires to compute the state_dict on all processes in case Metrics are present\n state_dict = self.lightning_module.state_dict()\n\n if self.global_rank == 0 and self.mp_queue is not None:\n rank_zero_warn(\"cleaning up ddp environment...\")\n\n # save the last weights\n last_path = None\n if trainer.state.fn == TrainerFn.FITTING and best_model_path is not None and len(best_model_path) > 0:\n last_path = re.sub(\".ckpt\", \".tmp_end.ckpt\", best_model_path)\n atomic_save(state_dict, last_path)\n\n # todo, pass complete checkpoint as state dictionary\n self.mp_queue.put(best_model_path)\n self.mp_queue.put(last_path)\n self.mp_queue.put(results)\n # adds the `callback_metrics` to the queue\n # TODO: Remove the if in v1.7\n if is_overridden(\"add_to_queue\", self.lightning_module):\n self.lightning_module.add_to_queue(self.mp_queue)\n else:\n self.add_to_queue(trainer, self.mp_queue)\n\n def __recover_child_process_weights(self, best_path, last_path):\n # transfer back the best path to the trainer\n if self.lightning_module.trainer.checkpoint_callback:\n self.lightning_module.trainer.checkpoint_callback.best_model_path = best_path\n # todo, pass also best score\n\n # load last weights\n if last_path is not None and self.lightning_module.trainer.state.fn == TrainerFn.FITTING:\n ckpt = pl_load(last_path, map_location=lambda storage, loc: storage)\n self.lightning_module.load_state_dict(ckpt)\n\n def barrier(self, *args, **kwargs) -> None:\n if not distributed_available():\n return\n if _TORCH_GREATER_EQUAL_1_8 and torch.distributed.get_backend() == \"nccl\":\n torch.distributed.barrier(device_ids=self.determine_ddp_device_ids())\n else:\n torch.distributed.barrier()\n\n def broadcast(self, obj: object, src: int = 0) -> object:\n if not distributed_available():\n return obj\n obj = [obj]\n if self.global_rank != src:\n obj = [None]\n broadcast_object_list(obj, src, group=_group.WORLD)\n return obj[0]\n\n def model_to_device(self):\n if self.root_device.type == \"cuda\":\n # set the device on the spawned subprocesses\n torch.cuda.set_device(self.root_device)\n self.model.to(self.root_device)\n\n def pre_backward(self, closure_loss: torch.Tensor) -> None:\n \"\"\"Run before precision plugin executes backward.\"\"\"\n if not self.lightning_module.automatic_optimization:\n prepare_for_backward(self.model, closure_loss)\n\n def reduce(self, tensor, group: Optional[Any] = None, reduce_op: Union[ReduceOp, str] = \"mean\") -> torch.Tensor:\n \"\"\"Reduces a tensor from several distributed processes to one aggregated tensor.\n\n Args:\n tensor: the tensor to sync and reduce\n group: the process group to gather results from. Defaults to all processes (world)\n reduce_op: the reduction operation. Defaults to 'mean'/'avg'.\n Can also be a string 'sum' to calculate the sum during reduction.\n\n Return:\n reduced value, except when the input was not a tensor the output remains is unchanged\n \"\"\"\n if isinstance(tensor, torch.Tensor):\n tensor = sync_ddp_if_available(tensor, group, reduce_op=reduce_op)\n return tensor\n\n def training_step(self, *args, **kwargs) -> Optional[Any]:\n return self.model(*args, **kwargs)\n\n def validation_step(self, *args, **kwargs) -> Optional[STEP_OUTPUT]:\n if isinstance(self.model, DistributedDataParallel):\n # used when calling `trainer.fit`\n return self.model(*args, **kwargs)\n else:\n # used when calling `trainer.validate`\n return self.lightning_module.validation_step(*args, **kwargs)\n\n def test_step(self, *args, **kwargs) -> Optional[STEP_OUTPUT]:\n return self.lightning_module.test_step(*args, **kwargs)\n\n def predict_step(self, *args, **kwargs) -> Any:\n return self.lightning_module.predict_step(*args, **kwargs)\n\n def post_training_step(self):\n if not self.lightning_module.automatic_optimization:\n self.model.require_backward_grad_sync = True\n\n def add_to_queue(self, trainer: \"pl.Trainer\", queue: torch.multiprocessing.SimpleQueue) -> None:\n \"\"\"Appends the :attr:`trainer.callback_metrics` dictionary to the given queue. To avoid issues with memory\n sharing, we cast the data to numpy.\n\n Args:\n queue: the instance of the queue to append the data.\n \"\"\"\n callback_metrics: dict = apply_to_collection(\n trainer.callback_metrics, torch.Tensor, lambda x: x.cpu().numpy()\n ) # send as numpy to avoid issues with memory sharing\n queue.put(callback_metrics)\n\n def get_from_queue(self, trainer: \"pl.Trainer\", queue: torch.multiprocessing.SimpleQueue) -> None:\n \"\"\"Retrieve the :attr:`trainer.callback_metrics` dictionary from the given queue. To preserve consistency,\n we cast back the data to ``torch.Tensor``.\n\n Args:\n queue: the instance of the queue from where to get the data.\n \"\"\"\n # NOTE: `add_to_queue` needs to be called before\n callback_metrics: dict = queue.get()\n trainer.callback_metrics.update(apply_to_collection(callback_metrics, np.ndarray, lambda x: torch.tensor(x)))\n\n @classmethod\n def register_plugins(cls, plugin_registry: Dict) -> None:\n plugin_registry.register(\n \"ddp_spawn_find_unused_parameters_false\",\n cls,\n description=\"DDPSpawn Plugin with `find_unused_parameters` as False\",\n find_unused_parameters=False,\n )\n\n def teardown(self) -> None:\n if isinstance(self.model, DistributedDataParallel):\n self.model = self.lightning_module\n\n if self.on_gpu:\n # GPU teardown\n self.lightning_module.cpu()\n # clean up memory\n torch.cuda.empty_cache()\n" ]
[ [ "torch.utils.data._utils.collate.default_collate" ], [ "torch.cuda.set_device", "torch.multiprocessing.spawn", "torch.cuda.empty_cache", "torch.distributed.barrier", "torch.tensor", "torch.multiprocessing.get_context", "torch.distributed.get_backend" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nftqcd/nthmc
[ "010c70e297c904219e9d8a04cc20b9c75a4b61e5", "010c70e297c904219e9d8a04cc20b9c75a4b61e5", "010c70e297c904219e9d8a04cc20b9c75a4b61e5", "010c70e297c904219e9d8a04cc20b9c75a4b61e5" ]
[ "u1_2d/s_nthmc_l64_b4_t2_lr5e-4.py", "u1_2d/t_force_b25_l64_b6_cn10.py", "xy_1d/train.py", "u1_2d/reprod/t_fthmc_1_iop2_t32.py" ]
[ "import tensorflow as tf\nimport tensorflow.keras as tk\nimport numpy\nimport nthmc, ftr, evolve, forcetrain\n\ntrajLength = 4.0\nnstep = 8\n\nconf = nthmc.Conf(nbatch=32, nepoch=4, nstepEpoch=1024, nstepMixing=128, initDt=trajLength/nstep, stepPerTraj=nstep, trainDt=False, nthr=10, nthrIop=1, seed=7*11*13*7)\nop0 = (((1,2,-1,-2), (1,-2,-1,2)),\n ((1,1,2,-1,-1,-2), (1,1,-2,-1,-1,2), (1,2,-1,-1,-2,1), (1,-2,-1,-1,2,1)))\n# requires different coefficient bounds:\n# (1,2,-1,-2,1,-2,-1,2)\n# (1,2,-1,-2,1,2,-1,-2)\n# (1,-2,-1,2,1,-2,-1,2)\nop1 = (((2,-1,-2,1), (2,1,-2,-1)),\n ((2,2,-1,-2,-2,1), (2,2,1,-2,-2,-1), (2,-1,-2,-2,1,2), (2,1,-2,-2,-1,2)))\nfixedP = (1,2,-1,-2)\nfixedR0 = (2,2,1,-2,-2,-1)\nfixedR1 = (1,1,2,-1,-1,-2)\nconvP0 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,2), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvP1 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (2,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvR = lambda pad: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n), pad)\nconv = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n tk.layers.Conv2D(2, (3,3), activation=None, kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\ntransform = lambda: ftr.TransformChain([\n ftr.GenericStoutSmear(((0,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n])\nnthmc.setup(conf)\nrng = tf.random.Generator.from_seed(conf.seed)\nactionFun = lambda: nthmc.U1d2(beta=7.0, beta0=3.0, size=(64,64), transform=transform(), nbatch=conf.nbatch, rng=rng.split()[0])\nmcmcFun = lambda action: nthmc.Metropolis(conf, evolve.Omelyan2MN(conf, action))\n\nx0 = tf.constant(numpy.load('configs/s_hmc_l64_b4/conf.b4.0.n128.l64_64.08192.npy')[0:32], dtype=tf.float64)\nforcetrain.runInfer(conf, actionFun, mcmcFun, x0=x0, saveFile='configs/s_nthmc_l64_b4_t2_lr5e-4/conf', transformWeights='weights/t_force_b25_l64_b4_t2_lr5e-4')\n", "import tensorflow as tf\nimport tensorflow.keras as tk\nimport numpy\nimport nthmc, ftr, forcetrain\n\nconf = nthmc.Conf(nbatch=128, nepoch=1, nstepEpoch=1024, nstepMixing=128, nstepPostTrain=1024, initDt=0.2, stepPerTraj=10, nthr=20, nthrIop=2, seed=1234567)\nnthmc.setup(conf)\nop0 = (((1,2,-1,-2), (1,-2,-1,2)),\n ((1,1,2,-1,-1,-2), (1,1,-2,-1,-1,2), (1,2,-1,-1,-2,1), (1,-2,-1,-1,2,1)))\n# requires different coefficient bounds:\n# (1,2,-1,-2,1,-2,-1,2)\n# (1,2,-1,-2,1,2,-1,-2)\n# (1,-2,-1,2,1,-2,-1,2)\nop1 = (((2,-1,-2,1), (2,1,-2,-1)),\n ((2,2,-1,-2,-2,1), (2,2,1,-2,-2,-1), (2,-1,-2,-2,1,2), (2,1,-2,-2,-1,2)))\nfixedP = (1,2,-1,-2)\nfixedR0 = (2,2,1,-2,-2,-1)\nfixedR1 = (1,1,2,-1,-1,-2)\nconvP0 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,2), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvP1 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (2,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvR = lambda pad: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n), pad)\nconv = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(4, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n tk.layers.Conv2D(2, (3,3), activation=None, kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\ntransform = lambda: ftr.TransformChain([\n ftr.GenericStoutSmear(((0,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n])\nftr.checkDep(transform())\nrng = tf.random.Generator.from_seed(conf.seed)\nactionFun = lambda: nthmc.U1d2(beta=6.0, beta0=6.0, size=(64,64), transform=transform(), nbatch=conf.nbatch, rng=rng.split()[0])\nloss = lambda action: forcetrain.LossFun(action, betaMap=2.5, cNorm2=1.0, cNorm4=1.0, cNorm6=1.0, cNorm8=1.0, cNorm10=1.0, cNormInf=1.0)\nopt = tk.optimizers.Adam(learning_rate=0.001)\nmcmc = lambda action: nthmc.Metropolis(conf, evolve.Omelyan2MN(conf, action))\ndef loadConf(n):\n # n from 0 to 1023\n ab = 'abcdefgh'[n%8]\n k = n//8\n i = k//8\n j = k%8\n return tf.constant(numpy.load(f'configs/s_hmc_l64_b6_{ab}/conf.b6.0.n1024.l64_64.{8192*(i+1):05d}.npy', allow_pickle=False, fix_imports=False)[128*j:128*(j+1)], dtype=tf.float64)\nforcetrain.trainWithConfs(conf, loadConf, actionFun, loss, opt, loadWeights='weights/t_force_b25_l64_b5', saveWeights='weights/t_force_b25_l64_b6_cn10')\n", "import tensorflow.keras as tk\nimport nthmc\n\n#conf = Conf(nbatch=4, nepoch=2, nstepEpoch=20, initDt=0.1)\n#conf = Conf(nbatch=4, nepoch=2, nstepEpoch=2048, initDt=0.1)\nconf = nthmc.Conf(nbatch=128, nepoch=16, nstepEpoch=4096, initDt=0.4)\nnthmc.setup(conf)\n#action = OneD(transforms=[Ident()])\naction = nthmc.OneD(beta=6, transforms=[\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd'),\n nthmc.OneDNeighbor(mask='even'), nthmc.OneDNeighbor(mask='odd')])\nloss = nthmc.LossFun(action, cCosDiff=1.0, cTopoDiff=1.0, dHmin=0.5, topoFourierN=9)\nopt = tk.optimizers.Adam(learning_rate=0.001)\nx0 = action.initState(conf.nbatch)\nnthmc.run(conf, action, loss, opt, x0)\n", "import tensorflow as tf\nimport tensorflow.keras as tk\nimport sys\nsys.path.append('..')\nsys.path.append('../../lib')\nimport nthmc, ftr, forcetrain\nimport field\n\nconf = nthmc.Conf(nbatch=64, nepoch=1, nstepEpoch=1, nstepMixing=128, nstepPostTrain=0, initDt=0.2, stepPerTraj=10, nthr=32, nthrIop=2, seed=1234567)\nnthmc.setup(conf)\nop0 = (((1,2,-1,-2), (1,-2,-1,2)),\n ((1,1,2,-1,-1,-2), (1,1,-2,-1,-1,2), (1,2,-1,-1,-2,1), (1,-2,-1,-1,2,1)))\n# requires different coefficient bounds:\n# (1,2,-1,-2,1,-2,-1,2)\n# (1,2,-1,-2,1,2,-1,-2)\n# (1,-2,-1,2,1,-2,-1,2)\nop1 = (((2,-1,-2,1), (2,1,-2,-1)),\n ((2,2,-1,-2,-2,1), (2,2,1,-2,-2,-1), (2,-1,-2,-2,1,2), (2,1,-2,-2,-1,2)))\nfixedP = (1,2,-1,-2)\nfixedR0 = (2,2,1,-2,-2,-1)\nfixedR1 = (1,1,2,-1,-1,-2)\nconvP0 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(2, (3,2), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvP1 = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(2, (2,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\nconvR = lambda pad: ftr.PeriodicConv((\n tk.layers.Conv2D(2, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n), pad)\nconv = lambda: ftr.PeriodicConv((\n tk.layers.Conv2D(2, (3,3), activation='gelu', kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n tk.layers.Conv2D(2, (3,3), activation=None, kernel_initializer=tk.initializers.RandomNormal(), bias_initializer=tk.initializers.RandomNormal()),\n))\ntransform = lambda: ftr.TransformChain([\n ftr.GenericStoutSmear(((0,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op0, [(fixedP, convP0()), (fixedR0, convR((1,2)))], conv()),\n ftr.GenericStoutSmear(((0,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,0),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((0,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n ftr.GenericStoutSmear(((1,1),(2,2)), op1, [(fixedP, convP1()), (fixedR1, convR((2,1)))], conv()),\n])\nftr.checkDep(transform())\nrng = tf.random.Generator.from_seed(conf.seed)\nactionFun = lambda: nthmc.U1d2(beta=7.0, beta0=2.0, size=(16,16), transform=transform(), nbatch=conf.nbatch, rng=rng.split()[0])\nloss = lambda action: forcetrain.LossFun(action, betaMap=2.5, cNorm2=1.0, cNormInf=1.0)\nopt = tk.optimizers.Adam(learning_rate=0.001)\nmcmc = lambda action: nthmc.Metropolis(conf, nthmc.LeapFrog(conf, action))\nx, m, l = forcetrain.run(conf, actionFun, mcmc, loss, opt)\ntf.print('MCMC weights:', m.get_weights(), summarize=-1)\ntf.print('opt variables:', len(opt.variables()), opt.variables(), summarize=-1)\n" ]
[ [ "numpy.load", "tensorflow.keras.initializers.RandomNormal", "tensorflow.random.Generator.from_seed" ], [ "numpy.load", "tensorflow.keras.initializers.RandomNormal", "tensorflow.random.Generator.from_seed", "tensorflow.keras.optimizers.Adam" ], [ "tensorflow.keras.optimizers.Adam" ], [ "tensorflow.keras.initializers.RandomNormal", "tensorflow.random.Generator.from_seed", "tensorflow.keras.optimizers.Adam" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
pulp-platform/q-eegnet_wolf
[ "f028a727d4ae346b81539ed78ecba5f059c9029f", "f028a727d4ae346b81539ed78ecba5f059c9029f" ]
[ "test/cl/func/conv/testcase.py", "test/cl/net/layer4/testcase.py" ]
[ "\"\"\"\nThis file will test the convolution implementation\n\"\"\"\n\n__author__ = \"Tibor Schneider\"\n__email__ = \"[email protected]\"\n__version__ = \"1.0\"\n__license__ = \"Apache 2.0\"\n__copyright__ = \"\"\"\n Copyright (C) 2020 ETH Zurich. All rights reserved.\n\n Author: Tibor Schneider, ETH Zurich\n\n SPDX-License-Identifier: Apache-2.0\n\n Licensed under the Apache License, Version 2.0 (the License); you may\n not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an AS IS BASIS, WITHOUT\n WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\n\nimport random\nimport os\nimport numpy as np\nfrom test_utils import parse_output, TestLogger\nfrom header_file import HeaderFile, HeaderConstant, HeaderArray\nfrom makefile import Makefile\n\nTESTNAME = \"cl::func::conv\"\nRESULT_FILE = \"result.out\"\n\n\ndef gen_stimuli(size_a = 1125, size_b = 64):\n \"\"\"\n This function generates the stimuli (input and output) for the test\n \"\"\"\n vecA = [random.randint(-128, 127) for _ in range(size_a)]\n vecB = [random.randint(-128, 127) for _ in range(size_b)]\n result = list(np.convolve(vecA, vecB, mode=\"valid\"))\n return vecA, vecB, result\n\n\ndef test():\n \"\"\"\n Execute the tests\n Returns: (n_total, n_success)\n \"\"\"\n\n logger = TestLogger(TESTNAME)\n\n for size_a, size_b in [(155, 16), (1188, 64), (4096, 128)]:\n for conv_version in [0, 1, 2, 3]:\n\n # generate makefile\n mkf = Makefile()\n mkf.add_fc_test_source(\"test.c\")\n mkf.add_cl_test_source(\"cluster.c\")\n mkf.add_cl_prog_source(\"func/conv.c\")\n mkf.add_define(\"CONV_VERSION\", conv_version)\n mkf.write()\n\n # generate the stimuli\n vecA, vecB, vecExp = gen_stimuli(size_a, size_b)\n\n # prepare header file\n header = HeaderFile(\"test_stimuli.h\")\n header.add(HeaderConstant(\"LENGTH_A\", size_a))\n header.add(HeaderConstant(\"LENGTH_B\", size_b))\n header.add(HeaderConstant(\"LENGTH_RES\", len(vecExp)))\n header.add(HeaderArray(\"vecA\", \"int8_t\", vecA))\n header.add(HeaderArray(\"vecB\", \"int8_t\", vecB))\n header.add(HeaderArray(\"vecExp\", \"int32_t\", vecExp))\n header.write()\n\n # compile and run\n os.system(\"make clean all run > {}\".format(RESULT_FILE))\n\n # parse output\n result = parse_output(RESULT_FILE)\n\n casename = \"V{}, {}x{}\".format(conv_version, size_a, size_b)\n\n # log the result\n logger.show_subcase_result(casename, result)\n\n # return summary\n return logger.summary()\n", "\"\"\"\nThis file will test the convolution implementation\n\"\"\"\n\n__author__ = \"Tibor Schneider\"\n__email__ = \"[email protected]\"\n__version__ = \"1.0\"\n__license__ = \"Apache 2.0\"\n__copyright__ = \"\"\"\n Copyright (C) 2020 ETH Zurich. All rights reserved.\n\n Author: Tibor Schneider, ETH Zurich\n\n SPDX-License-Identifier: Apache-2.0\n\n Licensed under the Apache License, Version 2.0 (the License); you may\n not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an AS IS BASIS, WITHOUT\n WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\n\nimport random\nimport os\nimport numpy as np\nfrom test_utils import parse_output, TestLogger\nfrom header_file import HeaderFile, HeaderConstant, HeaderArray, align_array, align_array_size\nfrom makefile import Makefile\nfrom golden_model import GoldenModel\nimport functional as F\n\nTESTNAME = \"cl::net::layer4\"\nRESULT_FILE = \"result.out\"\n\nINPUT_FILENAME = \"../../../../data/verification.npz\"\nNET_FILENAME = \"../../../../data/net.npz\"\nCONFIG_FILENAME = \"../../../../data/config.json\"\n\n\ndef gen_stimuli(random_input, flip, reorder_bn):\n \"\"\"\n This function generates the stimuli (input and output) for the test\n \"\"\"\n model = GoldenModel(CONFIG_FILENAME, NET_FILENAME, clip_balanced=False, reorder_bn=reorder_bn)\n layer = model.layers[3]\n if random_input:\n x = np.random.randint(-60, 60, (model.F2, model.T // 8))\n else:\n x = np.load(INPUT_FILENAME)[\"layer3_activ\"][0, :, 0, :]\n x = F.quantize_to_int(x, layer.input_scale)\n y_exp = layer(x)\n if flip:\n x_flip = np.transpose(x)\n x_align = np.zeros((align_array_size(model.T // 8), model.F2), dtype=int)\n x_align[:model.T//8, :model.F2] = x_flip\n else:\n x_align = align_array(x)\n y_exp_align = align_array(y_exp)\n return x, x_align, y_exp, y_exp_align\n\n\ndef test():\n \"\"\"\n Execute the tests\n Returns: (n_total, n_success)\n \"\"\"\n\n logger = TestLogger(TESTNAME, show_title=False)\n\n for simd in [False, True]:\n for flip_layers in [False, True]:\n for parallel in [False, True]:\n for reorder in [False, True]:\n\n if not simd and (flip_layers or parallel or reorder):\n continue\n if parallel and not flip_layers:\n # not implemented\n continue\n\n # generate makefile\n mkf = Makefile()\n mkf.add_fc_test_source(\"test.c\")\n mkf.add_cl_test_source(\"cluster.c\")\n mkf.add_cl_prog_source(\"net/layer4.c\")\n mkf.add_cl_prog_source(\"net/net.c\")\n mkf.add_cl_prog_source(\"func/transform.c\")\n mkf.add_cl_prog_source(\"func/dotp.c\")\n\n if not simd:\n mkf.add_define(\"NO_SIMD\")\n\n if flip_layers:\n mkf.add_define(\"FLIP_LAYERS\")\n\n if parallel:\n mkf.add_define(\"PARALLEL\")\n\n if reorder:\n mkf.add_define(\"REORDER_BN\")\n\n mkf.write()\n\n random_input = False\n\n # generate the stimuli\n _, x_align, _, y_exp_align = gen_stimuli(random_input, flip_layers, reorder)\n\n # prepare header file\n header = HeaderFile(\"test_stimuli.h\")\n header.add(HeaderArray(\"x_vec\", \"int8_t\", x_align.ravel()))\n header.add(HeaderArray(\"y_exp_vec\", \"int8_t\", y_exp_align.ravel()))\n header.write()\n\n # compile and run\n os.system(\"make clean all run > {}\".format(RESULT_FILE))\n\n # parse output\n result = parse_output(RESULT_FILE)\n\n # log the result\n options = []\n if simd:\n options.append(\"simd\")\n if flip_layers:\n options.append(\"flip\")\n if parallel:\n options.append(\"par\")\n if reorder:\n options.append(\"reorder\")\n\n subcase_name = \"Layer 4 \"\n if options:\n subcase_name += \"; \".join(options)\n else:\n subcase_name += \"naive\"\n logger.show_subcase_result(subcase_name, result)\n\n # return summary\n return logger.summary()\n" ]
[ [ "numpy.convolve" ], [ "numpy.load", "numpy.transpose", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hoangdzung/DGI
[ "12203ec30bd3e09770e79da2d967b613b8c8e79d" ]
[ "test.py" ]
[ "import torch \nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch import nn\n\nfrom torch_geometric.nn import GCNConv\nfrom sklearn.linear_model import LogisticRegression\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom gumbel import gumbel_softmax\nfrom utils import process\n\nnum_epochs = 100000\nlr = 0.001\nweight_decay = 0\n\nclass GCNet(nn.Module):\n def __init__(self, num_features, num_embedding = 128):\n super(GCNet, self).__init__()\n self.conv = GCNConv(num_features, num_embedding, cached=True)\n\n def forward(self, x, edge_index):\n x = self.conv(x, edge_index)\n return x\n\nadj, features, labels, idx_train, idx_val, idx_test = process.load_data('cora')\n#features, _ = process.preprocess_features(features)\n\nfeatures = features.toarray()\n#features=np.array(features)\nnb_nodes = features.shape[0]\nft_size = features.shape[1]\nnb_classes = labels.shape[1]\nlabels = np.argmax(labels, 1)\n\nmodel = GCNet(ft_size)\nadj = Variable(torch.FloatTensor(adj.toarray()), requires_grad=False)\nfeatures = Variable(torch.FloatTensor(features), requires_grad=False)\nedge_index = torch.transpose(adj.nonzero(),0,1)\nedge_index = edge_index.long()\n\nif torch.cuda.is_available():\n model = model.cuda()\n adj = adj.cuda()\n features = features.cuda()\n edge_index = edge_index.cuda()\n\noptimizer = torch.optim.Adam(filter(lambda p : p.requires_grad, model.parameters()), lr=lr, weight_decay=weight_decay)\n\nsmallest_loss = 1e20\nembeddings_np = None \nbest_at = 0\n\nfor epoch in tqdm(range(num_epochs)):\n model.train()\n model.zero_grad()\n embeddings = model(features, edge_index)\n assign_tensor = gumbel_softmax(embeddings, temp=0.1,hard=True)\n assign_tensor_t = torch.transpose(assign_tensor, 0, 1)\n super_adj = assign_tensor_t @ adj @ assign_tensor # A' = S^T*A*S\n vol = super_adj.sum(1)\n diag = torch.diagonal(super_adj)\n norm_cut = (vol - diag)/(vol+1e-20)\n loss = norm_cut.sum() \n\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 2.0)\n optimizer.step()\n if loss.item() < smallest_loss:\n smallest_loss = loss.item()\n embeddings_np = embeddings.cpu().detach().numpy()\n X_train = embeddings_np[idx_train]\n Y_train = labels[idx_train]\n X_test = embeddings_np[idx_test]\n Y_test = labels[idx_test]\n clf = LogisticRegression(solver=\"lbfgs\", max_iter=4000)\n clf.fit(X_train, Y_train)\n print(loss.item(), clf.score(X_test, Y_test))\n\n\n# import pdb;pdb.set_trace()a\n" ]
[ [ "torch.diagonal", "torch.transpose", "sklearn.linear_model.LogisticRegression", "numpy.argmax", "torch.FloatTensor", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
satinder147/opencv-utilities
[ "ec2d0469949924dd89f8159e9c49191f3c43f720" ]
[ "opencv_utilities/bounding_rect.py" ]
[ "import cv2\nimport numpy as np\nimport time\n\n\ndef check(scale, text, font, line_width, box_width, box_height, offset, p=1):\n \"\"\"\n :param scale: parameter binary search is optimising\n :return: A boolean, whether this scale is ok or if p==2 sends back the string of words in each line.\n \"\"\"\n last_word = 0\n prev_line_break = 0\n strings = []\n word_height = None\n for i in range(len(text)):\n if text[i] == ' ':\n last_word = i\n word_width, word_height = cv2.getTextSize(text[prev_line_break:i+1], font, scale, line_width)[0]\n if word_width > box_width:\n i = last_word\n # print(\"The text is \"+text[prev_line_break:last_word],prev_line_break,last_word)\n if text[prev_line_break:last_word] == \" \" or last_word+1 == prev_line_break:\n return False\n strings.append(text[prev_line_break:last_word])\n prev_line_break = last_word+1\n strings.append(text[prev_line_break:len(text)])\n if p == 2:\n return strings \n if (len(strings) * word_height + (len(strings) - 1) * offset) < box_height:\n return True\n else:\n return False\n\n\ndef get_scale(text, font, line_width, box_width, box_height, offset):\n lo = 0\n hi = 100\n while hi-lo > 1:\n mid = lo+(hi-lo)//2\n if check(mid, text, font, line_width, box_width, \n box_height, offset):\n lo = mid\n else:\n hi = mid\n increment = 0.1\n precision = 5\n ans = lo\n for _ in range(precision):\n while check(ans+increment, text, font, line_width, box_width, box_height, offset):\n ans += increment\n increment /= 10\n return ans\n\n\ndef get_image(x, y, box_width, box_height, image, text, pad_percent_height, pad_percent_width, line_width, align=\"left\",\n font=cv2.FONT_HERSHEY_SIMPLEX, color=(255, 0, 0), rect=False):\n if rect:\n cv2.rectangle(image, (x, y), (x+box_width, y+box_height), (255, 0, 0), 1)\n padding = int(box_height*pad_percent_height)\n padding_width = int(pad_percent_width * box_width)\n box_width -= int(2*box_width*pad_percent_width)\n box_height -= int(2*box_height*pad_percent_height)\n offset = int(box_height/10)\n # print(box_width,box_height)\n ans = get_scale(text, font, line_width, box_width, box_height, offset)\n p = cv2.getTextSize(text, font, ans, line_width)\n x1 = x + padding_width\n y1 = y+p[0][1]+padding\n strings = check(ans, text, font, line_width, box_width, box_height, offset, p=2)\n\n for i in range(len(strings)):\n if align == 'left':\n cv2.putText(image, strings[i], (x1, y1), font, ans, color, line_width, cv2.LINE_AA)\n if align == 'center' or align == 'right':\n remaining = box_width-cv2.getTextSize(strings[i], font, ans, line_width)[0][0]\n if align == 'center':\n cv2.putText(image, strings[i], (x1+remaining//2, y1), font, ans, color, line_width,cv2.LINE_AA)\n else:\n cv2.putText(image, strings[i], (x1+remaining, y1), font, ans, color, line_width, cv2.LINE_AA)\n y1 += p[0][1]+offset\n return image\n\n\ndef get_transformed(text, pts_dest, img):\n\n pts_src = np.array([[0, 0], [600, 0], [600, 400], [0, 400]], dtype=float)\n src = np.zeros((400, 600, 3), dtype=np.uint8)\n src = get_image(0, 0, 600, 400, src, text, 0.05, 0.05, 3, 'center')\n h, status = cv2.findHomography(pts_src, pts_dest)\n im_temp = cv2.warpPerspective(src, h, (img.shape[1], img.shape[0]))\n grey = cv2.cvtColor(im_temp, cv2.COLOR_BGR2GRAY)\n mask = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY)[1]\n only_text = cv2.bitwise_and(im_temp, im_temp, mask=mask)\n only_back = cv2.bitwise_and(img, img, mask=cv2.bitwise_not(mask))\n result = cv2.bitwise_or(only_back, only_text)\n # cv2.imshow(\"result\",result)\n # cv2.waitKey(0)\n return result\n\n\nif __name__ == \"__main__\":\n \"\"\"\n As per my knowledge there is no method in opencv that can automatically scale text\n inside a bounding box. My code uses binary search to find the optimal scale to fit the largest\n text inside the box. Apart from this it also provides functionality to align text and provide padding\n inside the box. It is as simple as just passing the coordinates of the box and the text.\n \"\"\"\n st = time.time()\n text = '''I am Satinder Singh, engineering student from India.'''\n img = np.zeros((480, 640, 3), dtype=np.uint8)\n result = get_image(10, 10, 100, 100, img, text, 0.05, 0.05, 1)\n cv2.imshow(\"results\", result)\n cv2.waitKey(0)\n en = time.time()\n print(en-st)\n\n\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dangpzanco/dcase-task1
[ "72867cc5b8969d7ec55c5acfd30ebbc3a7246666" ]
[ "debugging/debug_validation.py" ]
[ "# Standard libraries\nimport pathlib\nimport glob\nimport platform\nimport pickle\nfrom datetime import datetime\nfrom pprint import pprint\n\n# Scientific stack\nimport numpy as np\nimport numpy.random as rnd\nimport pandas as pd\n\n# Chunked data\nimport zarr\n\n# Audio processing\nimport dcase_util as du\n\n# Pretty progress bar\nimport tqdm\n\nimport preprocessing as prep\n\nn_feats = 100\ndataset_name = f'numfeats{n_feats}'\n\n# db_path = '/media/zanco/DADOS/zanco/datasets/TUT-urban-acoustic-scenes-2018-development/'\ndb_path = '/media/zanco/DADOS/zanco/datasets/TAU-urban-acoustic-scenes-2019-development/'\n\n# db_path = 'E:/datasets/TUT-urban-acoustic-scenes-2018-development/'\n# db_path = 'E:/datasets/TAU-urban-acoustic-scenes-2019-development/'\n\n# version = '2018'\nversion = '2019'\n\n\npreprocessor = prep.DataPreprocessing(db_path=db_path,\n version=version,\n n_feats=n_feats, \n dataset_name=dataset_name,\n dataset_folder=f'../saved_features{version}',\n audio_preprocess='mid',\n feature_type='mel_spectrogram')\n# preprocessor.process(overwrite=False)\nfold_meta, fold_split = preprocessor.generate_fold_meta(overwrite=False)\n\ntrain_ids = fold_meta['identifier'][fold_split[0][0]]\nvalid_ids = fold_meta['identifier'][fold_split[0][1]]\n\nc = list(set(train_ids) & set(valid_ids))\n\nprint(len(c))\n\n\nseed = 0\nn_splits = 5\n# Get consistent results (same folds every time)\nrand_state = rnd.get_state() # get current PRNG state\nrnd.seed(seed)\n\n\n# Get training and evaluation example indexes\ntrain_ind = np.where(preprocessor.db_meta['example_type'].values == 'train')[0]\neval_ind = np.where(preprocessor.db_meta['example_type'].values == 'test')[0]\n\n# Split based on labels and identifiers\nfrom sklearn.model_selection import GroupKFold\nsplitter = GroupKFold(n_splits=n_splits)\nX = np.empty([train_ind.size,1])\ny = preprocessor.db_meta['scene_label'][train_ind]\nids = preprocessor.db_meta['identifier'][train_ind]\ntemp_fold_split = list(splitter.split(X=X,y=y,groups=ids))\n\n# Fix indexing\nfold_split = [[train_ind[x[0]], train_ind[x[1]]] for x in temp_fold_split]\n\n\n\n\n\nfrom sklearn.model_selection import (TimeSeriesSplit, KFold, ShuffleSplit,\n StratifiedKFold, GroupShuffleSplit,\n GroupKFold, StratifiedShuffleSplit)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Patch\nnp.random.seed(1338)\ncmap_data = plt.cm.Paired\ncmap_group = plt.cm.prism\ncmap_cv = plt.cm.coolwarm\nn_splits = 5\n\n\n# Generate the class/group data\n_, label_index = np.unique(preprocessor.db_meta['scene_label'][train_ind].values, return_inverse=True)\ny = label_index.astype('i1')\n\n_, id_index = np.unique(preprocessor.db_meta['identifier'][train_ind].values, return_inverse=True)\ngroups = id_index.astype(int)\n\ndef visualize_groups(classes, groups):\n # Visualize dataset groups\n fig, ax = plt.subplots()\n plot = ax.scatter(range(len(groups)), [.5] * len(groups), c=groups, marker='_',\n lw=50, cmap=cmap_group)\n ax.scatter(range(len(groups)), [3.5] * len(groups), c=classes, marker='_',\n lw=50, cmap=cmap_data)\n ax.set(ylim=[-1, 5], yticks=[.5, 3.5],\n yticklabels=['Data\\ngroup', 'Data\\nclass'], xlabel=\"Sample index\")\n fig.colorbar(plot)\n\n\nvisualize_groups(y, groups)\n\n\ndef plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):\n \"\"\"Create a sample plot for indices of a cross-validation object.\"\"\"\n\n # Generate the training/testing visualizations for each CV split\n for ii, (tr, tt) in enumerate(cv.split(X=X, y=y, groups=group)):\n # Fill in indices with the training/test groups\n indices = np.array([np.nan] * len(X))\n indices[tt] = 1\n indices[tr] = 0\n\n # Visualize the results\n plot = ax.scatter(range(len(indices)), [ii + .5] * len(indices),\n c=indices, marker='_', lw=lw, cmap=cmap_cv,\n vmin=-.2, vmax=1.2)\n\n fig.colorbar(plot)\n\n # Plot the data classes and groups at the end\n ax.scatter(range(len(X)), [ii + 1.5] * len(X),\n c=y, marker='_', lw=lw, cmap=cmap_data)\n\n ax.scatter(range(len(X)), [ii + 2.5] * len(X),\n c=group, marker='_', lw=lw, cmap=cmap_group)\n\n # Formatting\n yticklabels = list(range(n_splits)) + ['class', 'group']\n ax.set(yticks=np.arange(n_splits+2) + .5, yticklabels=yticklabels,\n xlabel='Sample index', ylabel=\"CV iteration\",\n ylim=[n_splits+2.2, -.2])\n ax.set_title('{}'.format(type(cv).__name__), fontsize=15)\n return ax\n\n\nfig, ax = plt.subplots()\n# cv = KFold(n_splits)\nplot_cv_indices(splitter, X, y, groups, ax, n_splits)\n\nplt.show()\nexit(0)\n\n\n" ]
[ [ "numpy.random.get_state", "numpy.random.seed", "numpy.unique", "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.where", "sklearn.model_selection.GroupKFold", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
robovish/Python-Projects
[ "1cdfa18c093af32cfc02ac7d08e2bdf682670470", "1cdfa18c093af32cfc02ac7d08e2bdf682670470" ]
[ "Data_Science/src/model.py", "finance/views/viewtemp.py" ]
[ "\n#load the libraries\nimport pandas as pd\nimport numpy as np\nfrom pandas_profiling import ProfileReport\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom joblib import dump, load\nimport os\n\npath = os.getcwd()\n\n#load data\ndata = pd.read_csv(os.path.join(path,\"data\",\"diabetes.csv\"))\n\n#replace zeros with NANs\ndata[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = data[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].replace(0,np.NaN)\n\n#function to impute the missing values with median based on Outcome class\ndef impute_median(data, var):\n temp = data[data[var].notnull()]\n temp = temp[[var, 'Outcome']].groupby(['Outcome'])[[var]].median()\n data.loc[(data['Outcome'] == 0 ) & (data[var].isnull()), var] = temp.loc[0 ,var]\n data.loc[(data['Outcome'] == 1 ) & (data[var].isnull()), var] = temp.loc[1 ,var]\n return data\n\n#impute values using the function\ndata = impute_median(data, 'Glucose')\ndata = impute_median(data, 'BloodPressure')\ndata = impute_median(data, 'SkinThickness')\ndata = impute_median(data, 'Insulin')\ndata = impute_median(data, 'BMI')\n\n#separate features and target as x & y\ny = data['Outcome']\nx = data.drop('Outcome', axis = 1)\ncolumns = x.columns\n\n#scale the values using a StandardScaler\nscaler = StandardScaler()\nscaler = scaler.fit(x)\nX = scaler.transform(x)\n\n#features DataFrame \nfeatures = pd.DataFrame(X, columns = columns)\n\n# Training\n#split data into training and test sets\nx_train, x_test, y_train, y_test = train_test_split(features, y, test_size = 0.2, random_state = 42)\n\n#define the model\nmodel = RandomForestClassifier(n_estimators=300, bootstrap = True, max_features = 'sqrt')\n\n#fit model to training data\nmodel.fit(x_train, y_train)\n\n#predict on test data\ny_pred = model.predict(x_test)\n\n#evaluate performance\n# print(classification_report(y_test, y_pred))\n\n# Dump Scaler object and Model object using joblib\n\ndump(scaler, os.path.join(path, \"resources\",\"scaler.joblib\"))\ndump(model, os.path.join(path, \"resources\",\"model.joblib\"))\n", "from datetime import date, datetime\nimport streamlit as st\nimport pandas as pd\nfrom mplfinance import *\nfrom pandas_datareader import data as pdr\n\nst.experimental_memo(persist='disk')\ndef get_historical_data(symbol, start_date = None):\n df = pdr.get_data_yahoo(symbol, start=start_date, end=datetime.now())\n df = df.rename(columns = {'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Adj Close': 'adj close', 'Volume': 'volume'})\n for i in df.columns:\n df[i] = df[i].astype(float)\n df.index = pd.to_datetime(df.index)\n if start_date:\n df = df[df.index >= start_date]\n return df\n\nst.title('mplfinance demo')\n\nc1, c2, c3 = st.columns([1,1,1])\nwith c1:\n symbol = st.selectbox('Choose stock symbol', options=['AAPL', 'MSFT', 'GOOG', 'AMZN'], index=1)\nwith c2:\n date_from = st.date_input('Show data from', date(2021, 10, 1))\nwith c3:\n st.markdown('&nbsp;')\n show_data = st.checkbox('Show data table', False)\n\nst.markdown('---')\n\nst.sidebar.subheader('Settings')\nst.sidebar.caption('Adjust charts settings and then press apply')\n\nwith st.sidebar.form('settings_form'):\n show_nontrading_days = st.checkbox('Show non-trading days', True)\n # https://github.com/matplotlib/mplfinance/blob/master/examples/styles.ipynb\n chart_styles = [\n 'default', 'binance', 'blueskies', 'brasil', \n 'charles', 'checkers', 'classic', 'yahoo',\n 'mike', 'nightclouds', 'sas', 'starsandstripes'\n ]\n chart_style = st.selectbox('Chart style', options=chart_styles, index=chart_styles.index('starsandstripes'))\n chart_types = [\n 'candle', 'ohlc', 'line', 'renko', 'pnf'\n ]\n chart_type = st.selectbox('Chart type', options=chart_types, index=chart_types.index('candle'))\n\n mav1 = st.number_input('Mav 1', min_value=3, max_value=30, value=3, step=1)\n mav2 = st.number_input('Mav 2', min_value=3, max_value=30, value=6, step=1)\n mav3 = st.number_input('Mav 3', min_value=3, max_value=30, value=9, step=1)\n\n st.form_submit_button('Apply')\n\ndata = get_historical_data(symbol, str(date_from))\n\nfig, ax = plot(\n data,\n title=f'{symbol}, {date_from}',\n type=chart_type,\n show_nontrading=show_nontrading_days,\n mav=(int(mav1),int(mav2),int(mav3)),\n volume=True,\n\n style=chart_style,\n figsize=(15,10),\n \n # Need this setting for Streamlit, see source code (line 778) here:\n # https://github.com/matplotlib/mplfinance/blob/master/src/mplfinance/plotting.py\n returnfig=True\n)\n\nst.pyplot(fig)\n\nif show_data:\n st.markdown('---')\n st.dataframe(data)\n" ]
[ [ "sklearn.preprocessing.StandardScaler", "sklearn.ensemble.RandomForestClassifier", "sklearn.model_selection.train_test_split", "pandas.DataFrame" ], [ "pandas.to_datetime" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
XJX777/FaceX-Zoo
[ "9d083ed58d77dca077bbdae3e8bbdc73f46d287f" ]
[ "face_sdk/core/model_handler/face_detection/FaceDetModelHandler.py" ]
[ "\"\"\"\n@author: JiXuan Xu, Jun Wang\n@date: 20201019\n@contact: [email protected] \n\"\"\"\n\nimport logging.config\nlogging.config.fileConfig(\"config/logging.conf\")\nlogger = logging.getLogger('sdk')\n\nimport torch\nimport numpy as np\nfrom math import ceil\nfrom itertools import product as product\nimport torch.backends.cudnn as cudnn\n\nfrom core.model_handler.BaseModelHandler import BaseModelHandler\nfrom utils.BuzException import *\n\n\nclass FaceDetModelHandler(BaseModelHandler):\n \"\"\"Implimentation of face detection model handler\n\n Attributes:\n model: the face detection model.\n device: use cpu or gpu to process.\n cfg(dict): testing config, inherit from the parent class.\n \"\"\"\n def __init__(self, model, device, cfg):\n \"\"\"\n Init FaceDetModelHandler settings. \n \"\"\"\n super().__init__(model, device, cfg)\n self.variance = self.cfg['variance']\n \n def inference_on_image(self, image):\n \"\"\"Get the inference of the image and process the inference result.\n\n Returns:\n A numpy array, the shape is N * (x, y, w, h, confidence), \n N is the number of detection box.\n \"\"\"\n cudnn.benchmark = True\n input_height, input_width, _ = image.shape\n try:\n image, scale = self._preprocess(image)\n except Exception as e:\n raise e\n self.model = self.model.to(self.device)\n image = torch.from_numpy(image).unsqueeze(0)\n with torch.no_grad():\n image = image.to(self.device)\n scale = scale.to(self.device)\n loc, conf, landms = self.model(image)\n dets = self._postprocess(loc, conf, scale, input_height, input_width)\n return dets\n\n def _preprocess(self, image):\n \"\"\"Preprocess the image, such as standardization and other operations.\n\n Returns:\n A numpy array list, the shape is channel * h * w.\n A tensor, the shape is 4.\n \"\"\"\n if not isinstance(image, np.ndarray):\n logger.error('The input should be the ndarray read by cv2!')\n raise InputError()\n img = np.float32(image)\n scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])\n img -= (104, 117, 123)\n img = img.transpose(2, 0, 1)\n return img, scale\n\n def _postprocess(self, loc, conf, scale, input_height, input_width):\n \"\"\"Postprecess the prediction result.\n Decode detection result, set the confidence threshold and do the NMS\n to keep the appropriate detection box. \n\n Returns:\n A numpy array, the shape is N * (x, y, w, h, confidence), \n N is the number of detection box.\n \"\"\"\n priorbox = PriorBox(self.cfg, image_size=(input_height, input_width))\n priors = priorbox.forward()\n priors = priors.to(self.device)\n prior_data = priors.data\n boxes = self.decode(loc.data.squeeze(0), prior_data, self.cfg['variance'])\n boxes = boxes * scale\n boxes = boxes.cpu().numpy()\n scores = conf.squeeze(0).data.cpu().numpy()[:, 1]\n\n # ignore low scores\n inds = np.where(scores > self.cfg['confidence_threshold'])[0]\n boxes = boxes[inds]\n scores = scores[inds]\n\n # keep top-K before NMS\n order = scores.argsort()[::-1]\n boxes = boxes[order]\n scores = scores[order]\n\n # do NMS\n nms_threshold = 0.2\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n keep = self.py_cpu_nms(dets, nms_threshold)\n dets = dets[keep, :]\n return dets\n\n # Adapted from https://github.com/chainer/chainercv\n def decode(self, loc, priors, variances):\n \"\"\"Decode locations from predictions using priors to undo\n the encoding we did for offset regression at train time.\n Args:\n loc (tensor): location predictions for loc layers,\n Shape: [num_priors,4]\n priors (tensor): Prior boxes in center-offset form.\n Shape: [num_priors,4].\n variances: (list[float]) Variances of priorboxes\n\n Return:\n decoded bounding box predictions\n \"\"\"\n boxes = torch.cat((priors[:, :2], priors[:, 2:]), 1)\n boxes[:, :2] = priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:]\n boxes[:, 2:] = priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])\n boxes[:, :2] -= boxes[:, 2:] / 2\n boxes[:, 2:] += boxes[:, :2]\n return boxes\n\n # Adapted from https://github.com/biubug6/Pytorch_Retinafacey\n def py_cpu_nms(self, dets, thresh):\n \"\"\"Python version NMS.\n\n Returns:\n The kept index after NMS.\n \"\"\"\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n return keep\n\n# Adapted from https://github.com/biubug6/Pytorch_Retinafacey\nclass PriorBox(object):\n \"\"\"Compute the suitable parameters of anchors for later decode operation\n\n Attributes:\n cfg(dict): testing config.\n image_size(tuple): the input image size.\n \"\"\"\n def __init__(self, cfg, image_size=None):\n \"\"\"\n Init priorBox settings related to the generation of anchors. \n \"\"\"\n super(PriorBox, self).__init__()\n self.min_sizes = cfg['min_sizes']\n self.steps = cfg['steps']\n self.image_size = image_size\n self.feature_maps = [[ceil(self.image_size[0]/step), ceil(self.image_size[1]/step)] for step in self.steps]\n self.name = \"s\"\n\n def forward(self):\n anchors = []\n for k, f in enumerate(self.feature_maps):\n min_sizes = self.min_sizes[k]\n for i, j in product(range(f[0]), range(f[1])):\n for min_size in min_sizes:\n s_kx = min_size / self.image_size[1]\n s_ky = min_size / self.image_size[0]\n dense_cx = [x * self.steps[k] / self.image_size[1] for x in [j + 0.5]]\n dense_cy = [y * self.steps[k] / self.image_size[0] for y in [i + 0.5]]\n for cy, cx in product(dense_cy, dense_cx):\n anchors += [cx, cy, s_kx, s_ky]\n # back to torch land\n output = torch.Tensor(anchors).view(-1, 4)\n return output\n" ]
[ [ "numpy.hstack", "numpy.maximum", "numpy.minimum", "torch.Tensor", "torch.cat", "torch.from_numpy", "torch.exp", "torch.no_grad", "numpy.float32", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Steven20210/cell_death_ML
[ "c1a380bb2f9f3e0279403cf76cb5f5193e771b5b" ]
[ "unsupervised_training.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport cv2\nfrom matplotlib import style\n# from sci_utilities import is_outlier\nimport pandas as pd\n\nstyle.use(\"ggplot\")\nfrom sklearn.cluster import MiniBatchKMeans\nfrom keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D\nimport pickle\nfrom sklearn.neighbors import NearestNeighbors\nfrom PIL import Image, ImageEnhance\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nlabel = [0, 1]\narray_label = np.asarray(label)\nnucleus_array = []\nindex = 0\ncolors = ['r.', 'g.', 'b', '']\n\n\ndef pca():\n dying = []\n extreme = []\n\n # outputs_array_in = open('layer_4_output_all2.array', 'rb')\n # output_array = pickle.load(outputs_array_in)\n outputs_array_in = open('sample_3.array', 'rb')\n output_array = pickle.load(outputs_array_in)\n\n labels_array_in = open('label_2.array', 'rb')\n labels_array = pickle.load(labels_array_in)\n\n # output_array1 = np.asarray(output_array)\n output_array1 = []\n imgs = []\n\n for i in output_array:\n for j in i:\n mean_pi, std_pi = cv2.meanStdDev(j)\n output_array1.append(std_pi[0][0])\n imgs.append(j)\n # output_array1.append(std_pi[0][0])\n # imgs.append(j)\n # for data in output_array1:\n # data_mean, data_std = cv2.meanStdDev(data)\n #\n # cut_off = data_std * 3\n #\n # lower_bound, upper_bound = data_mean - cut_off, data_mean + cut_off\n\n for img in output_array1:\n if img > 120:\n output_array1.remove(img)\n # optimal_bins = np.histogram_bin_edges(output_array1, bins='fd')\n\n q3, q1 = np.percentile(output_array1, [75, 25])\n iqr = q3 - q1\n h = 2 * iqr * (len(output_array1) ** (-1/3))\n optimal_bins = int((np.amax(output_array1) - np.amin(output_array1))/h)\n\n possible_hist = [1, 1.5, 2, 2.5, 3]\n\n saved_hist = []\n for i in range(len(possible_hist)):\n optimal_bins = int(possible_hist[i] * optimal_bins)\n # hist, axs = plt.subplots(1, len(possible_hist))\n # axs[1, i].set_title('PI Standard Deviation of H2O2-stimulated Nuclei Images (2650 images)', fontsize=10)\n # axs[1, i].set_xlabel(\"PI Standard Deviation\")\n # axs[1, i].set_ylabel(\"# of Images\")\n # axs[1, i].hist(output_array1, bins=optimal_bins, range=[0, 120])\n plt.title('PI Standard Deviation of H2O2-stimulated Nuclei Images (2650 images)', fontsize=10)\n plt.xlabel(\"PI Standard Deviation\")\n plt.ylabel(\"# of Images\")\n plt.hist(output_array1, bins=optimal_bins, range=[0, 120])\n saved = plt.savefig(\"histogram \" + str(possible_hist[i]) + \"x.png\")\n saved_hist.append(saved)\n # plt.show()\n # hist, bin_edges = np.histogram(output_array1)\n # for i in range(len(output_array1)):\n # if output_array1[i] > 36:\n # print(output_array1[i])\n # plt.imshow(imgs[i])\n # plt.show()\n\n return possible_hist, output_array1, optimal_bins\n\n # output_array1 = np.asarray(output_array1)\n\n # output_array1 = output_array1.reshape(output_array1.shape[-5], -1)\n\n # outputs_array_1 = np.transpose(output_array1, (1, 0, 2))\n\n # for x in outputs_array_1:\n # for x in output_array1:\n # transformed = StandardScaler().fit_transform(x)\n\n # components = PCA(n_components=2)\n #\n #\n # # principalComponents = components.fit_transform(transformed)\n #\n # principalComponents = components.fit_transform(output_array1)\n #\n # variance = components.explained_variance_ratio_\n #\n # print(variance)\n # principalDf = pd.DataFrame(data=principalComponents, columns=['principal component 1', 'principal component 2'])\n #\n # print(principalDf)\n # for i in range(len(principalComponents)):\n # # plt.plot(principalComponents[i][0], principalComponents[i][1], colors[labels_array[i]], markersize=5)\n # plt.plot(principalComponents[i][0], principalComponents[i][1], 'g.', markersize=5)\n #\n # plt.xlabel(\"PCA1 - \" + str(variance[0] * 100) + \" %\")\n # plt.ylabel(\"PCA2 - \" + str(variance[1] * 100) + \" %\")\n # plt.title('PCA Plot of the Output Values of Layer 4 of the Cell Death Classification Neural Network', fontsize=10)\n # for i in range(len(principalDf)):\n #\n # # if 0 <= principalDf.iloc[i][0] <= 15:\n # # #healthy_close.append(i)\n # # extreme.append(i)\n # if principalDf.iloc[i][0] <= 0:\n # extreme.append(i)\n # # elif principalDf.iloc[i][0] > 30:\n # # healthy_far.append(i)\n # else:\n # dying.append(i)\n # plt.legend(['dying cells', 'healthy cells'])\n\n\na, b, c = pca()\nprint(a, b, c)\n\ndef kmeans_clustering(X):\n total_clusters = len(np.unique(array_label))\n\n kmeans = MiniBatchKMeans(n_clusters= total_clusters)\n\n kmeans.fit(X)\n\n labels = kmeans.labels_\n\n centroids = kmeans.cluster_centers_\n\n index = 0\n index1 = 0\n index2 = 0\n\n print(labels)\n for i in labels:\n if i == 0:\n index += 1\n elif i == 1:\n index1 += 1\n elif i == 2:\n index2 += 1\n print(str(index) + \" : 0 ,\" + str(index1) + \" : 1 ,\" + str(index2) + \" : 2\")\n\n return centroids, labels\n\ndef show_cluster(centroids, labels, X):\n colors = [\"g.\", \"r.\", \"c.\", \"y.\"]\n\n x = []\n y = []\n\n for i in range(len(X)):\n #print(\"coordinate:\", X[i], \"label:\", labels[i])\n #plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize=10)\n x.append(X[i][0])\n y.append(X[i][1])\n for i in range(len(x)):\n plt.plot([i], x[i], \"g.\", markersize=10)\n plt.plot([i], y[i], 'r.', markersize=10)\n\n # x = np.asarray(x)\n # x = x.reshape(-1, 1)\n # y = np.asarray(y)\n #\n # cov = np.cov(x, y)\n #\n # print(cov)\n # reg = LinearRegression()\n # reg.fit(x, y)\n #\n # reg_predict = reg.predict(x)\n # plt.plot(x, reg_predict)\n # print(reg.coef_)\n\n\n\n\n plt.scatter(centroids[:, 0], centroids[:, 1], marker=\"x\", s=150, linewidths=5, zorder=10)\n plt.title(\"Weights\")\n plt.show()" ]
[ [ "numpy.amax", "matplotlib.pyplot.scatter", "matplotlib.style.use", "numpy.asarray", "matplotlib.pyplot.title", "numpy.unique", "numpy.amin", "numpy.percentile", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "sklearn.cluster.MiniBatchKMeans", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TomaszGolan/q-learning-maze
[ "2540acf09d939c1686060c58cbe52775e94304ed" ]
[ "nets.py" ]
[ "\"\"\"Quality functions\"\"\"\nimport tensorflow as tf\nimport numpy as np\nfrom settings import Moves, Settings\n\n\nclass Net01:\n \"\"\"My first attempt to approximate Q with NN\"\"\"\n\n def __init__(self, session, in_size, snapshot=None):\n \"\"\"Create a graph for NN\n\n session -- tensorflow session\n input_size -- input vector size (maze width x maze height)\n snapshot -- path to saved model\n \"\"\"\n self.sess = session\n\n # layers size\n self.in_size = in_size\n self.out_size = len(Moves.ALL)\n h01_size = Settings.NOF_HIDDEN_NEURONS\n h02_size = Settings.NOF_HIDDEN_NEURONS\n\n # placeholders for features and targets\n self.x = tf.placeholder(tf.float32, [None, in_size])\n self.y = tf.placeholder(tf.float32, [None, self.out_size])\n\n # weights\n w01 = tf.Variable(tf.random_normal([in_size, h01_size]))\n w02 = tf.Variable(tf.random_normal([h01_size, h02_size]))\n w03 = tf.Variable(tf.random_normal([h02_size, self.out_size]))\n\n # biases\n b01 = tf.Variable(tf.zeros([h01_size]))\n b02 = tf.Variable(tf.zeros([h02_size]))\n b03 = tf.Variable(tf.zeros([self.out_size]))\n\n # hidden layers\n h01 = tf.nn.relu(tf.add(tf.matmul(self.x, w01), b01))\n h02 = tf.nn.relu(tf.add(tf.matmul(h01, w02), b02))\n\n # output layer\n self.out = tf.add(tf.matmul(h02, w03), b03)\n\n # training\n loss = tf.reduce_mean(tf.losses.mean_squared_error(\n labels=self.y, predictions=self.out))\n\n self.train = \\\n tf.train.AdamOptimizer(Settings.LEARNING_RATE).minimize(loss)\n\n self.sess.run(tf.global_variables_initializer())\n\n def predict(self, state):\n \"\"\"Predict next move\"\"\"\n return self.sess.run(tf.argmax(self.out, 1),\n feed_dict={self.x: state})[0]\n\n def maxQ(self, state):\n \"\"\"Get max possible quality function value (for the next move)\"\"\"\n return np.max(self.sess.run(self.out, feed_dict={self.x: state})[0])\n\n def inference(self, state):\n \"\"\"Get network output\"\"\"\n return self.sess.run(self.out, feed_dict={self.x: state})[0]\n\n def training(self, inputs, targets):\n self.sess.run(self.train, feed_dict={self.x: inputs, self.y: targets})\n\n\ndef get_training_data(network, history):\n \"\"\"Prepare next batch of training data\"\"\"\n inputs = np.zeros((Settings.BATCH_SIZE, network.in_size))\n targets = np.zeros((Settings.BATCH_SIZE, network.out_size))\n\n # loop over random episodes from history\n for i, entry in enumerate(history.get_data(Settings.BATCH_SIZE)):\n state, action, reward, next_state, game_over = entry\n inputs[i] = state\n targets[i] = network.inference(state)\n if game_over:\n targets[i, action] = reward\n else:\n targets[i, action] = reward + \\\n Settings.GAMMA * network.maxQ(next_state)\n\n return inputs, targets\n" ]
[ [ "tensorflow.matmul", "tensorflow.losses.mean_squared_error", "tensorflow.zeros", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.train.AdamOptimizer", "tensorflow.argmax", "numpy.zeros", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
imsanjoykb/Health-AI
[ "2c033899fce81089f9fc8e4d79e453dc94742576" ]
[ "app.py files/app_stroke.py" ]
[ "from flask import Flask, render_template, request\nimport numpy as np\nimport pickle\n\n\napp = Flask(__name__)\nmodel = pickle.load(open('Stroke.pkl', 'rb'))\n\[email protected]('/',methods=['GET'])\ndef Home():\n return render_template('index.html')\n\[email protected](\"/predict\", methods=['POST'])\ndef predict():\n if request.method == 'POST':\n gender = request.form['gender']\n if gender == 'Male':\n gender_Male = 1\n gender_Female = 0\n else:\n gender_Male = 0\n gender_Female = 1\n\n age = float(request.form['age'])\n hypertension = int(request.form['hypertension'])\n heart_disease = int(request.form['heart_disease'])\n ever_married = int(request.form['ever_married'])\n Residence_type = int(request.form['Residence_type'])\n avg_glucose_level = float(request.form['avg_glucose_level'])\n bmi = float(request.form['bmi'])\n\n\n work_type = request.form['work_type']\n\n if work_type == 'Never_worked':\n work_type_Never_worked = 1\n work_type_Private = 0\n work_type_Self_employed = 0\n work_type_children = 0\n work_type_Govt_job = 0\n\n if work_type == 'Private':\n work_type_Never_worked = 0\n work_type_Private = 1\n work_type_Self_employed = 0\n work_type_children = 0\n work_type_Govt_job = 0\n\n elif work_type == \"Self_employed\":\n work_type_Never_worked = 0\n work_type_Private = 0\n work_type_Self_employed = 1\n work_type_children = 0\n work_type_Govt_job = 0\n\n elif work_type == \"children\":\n work_type_Never_worked = 0\n work_type_Private = 0\n work_type_Self_employed = 0\n work_type_children = 1\n work_type_Govt_job = 0\n\n else:\n work_type_Never_worked = 0\n work_type_Private = 0\n work_type_Self_employed = 0\n work_type_children = 0\n work_type_Govt_job = 1\n\n\n smoking_status = request.form['smoking_status']\n\n if smoking_status == \"formerly_smoked\":\n smoking_status_formerly_smoked = 1\n smoking_status_never_smoked = 0\n smoking_status_Smokes = 0\n smoking_status_Unknown = 0\n\n elif smoking_status == \"never_smoked\":\n smoking_status_formerly_smoked = 0\n smoking_status_never_smoked = 1\n smoking_status_Smokes = 0\n smoking_status_Unknown = 0\n\n elif smoking_status == \"Smokes\":\n smoking_status_formerly_smoked = 0\n smoking_status_never_smoked = 0\n smoking_status_Smokes = 1\n smoking_status_Unknown = 0\n\n else:\n smoking_status_formerly_smoked = 0\n smoking_status_never_smoked = 0\n smoking_status_Smokes = 0\n smoking_status_Unknown = 1\n\n\n values = np.array([[gender_Male,age, hypertension, heart_disease, ever_married,\n Residence_type, avg_glucose_level, bmi,\n work_type_Never_worked, work_type_Private,work_type_Self_employed, work_type_children,\n smoking_status_formerly_smoked, smoking_status_never_smoked, smoking_status_Smokes]])\n prediction = model.predict(values)\n\n return render_template('result.html', prediction=prediction)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Sam-Chanow/Bitcoin-IGASS
[ "c3babac66d6a0594c4d83479393c50a54af9572a" ]
[ "Predict.py" ]
[ "import torch\nimport sys\nfrom tqdm import tqdm\nfrom dataset import Dataset\nimport numpy as np\nimport tensorflow as tf\n\n#adding the model folder path\nsys.path.append('../model/')\nsys.path.append('../tensorflow_model/')\n\nimport model\nimport tf_model\n\nif __name__ == \"__main__\":\n if (len(sys.argv) > 1) and (sys.argv[1] == '-train'):\n #Build the dataset from BVBPRI data\n D = Dataset(['../data/compiled-datasets/BVBPRI/BVBPRI' + str(x) + '.pt' for x in range(0, 967)],tensor_data=True) #967\n D = iter(D)\n\n X = []\n count = 0\n\n for x in tqdm(D):\n x[1] = model.average_tensors(x[1]).tolist()\n #print(x[1])\n x[0] = model.build_labels(x[0])\n #print(x)\n X.append([x[0], x[1]])\n #print(L)\n #print(len(L[0][1]))\n #exit(0)\n count += 1\n #print(\"Tensor\", count, \"averaged.\")\n if count > 1000: break;\n\n\n #print(X[0])\n Y = [t[0] for t in X]\n X = [t[1] for t in X]\n\n #print(\"RAW Y:\", Y)\n\n tfm = tf_model.TFModel()\n data = tfm.preprocess(X, Y)\n\n print(\"DATA:\", [x for x, y in data])\n\n #exit(0)\n\n\n #print(\"DATA:\", y_labels)\n #exit(0)\n train_data, validation_data, test_data = tf_model.get_dataset_partitions(data, 967)\n print(\"VAL DATA:\", [x for x, y in validation_data])\n print(\"train take\", [x for x, y in train_data])\n #for i in iter(data):\n #print(i)\n\n #num = 300\n #D_eval = Dataset(['data/compiled-datasets/BVBPRI/BVBPRI' + str(x) + '.pt' for x in range(900, 966)], tensor_data=True)\n #D_eval = iter(D_eval)\n #X_eval = []\n #for x in D_eval:\n #x[1] = model.average_tensors(x[1]).tolist()\n #x[0] = model.build_labels(x[0])\n # print(x)\n #X_eval.append([x[0], x[1]])\n\n # Y_eval = [t[0] for t in X_eval]\n #X_eval = [t[1] for t in X_eval]\n\n #data_eval = tfm.preprocess(X_eval, Y_eval)\n\n #for evalu, gold in zip(tfm.evaluate(data_eval), Y_eval):\n # print(\"OUT:\", evalu)\n #print(\"GOLD:\", gold)\n\n tfm.train(train_data, validation_data)\n y_labels = np.concatenate([y for x, y in test_data], axis=0)\n x_data = np.concatenate([x for x, y in test_data], axis=0)\n score = tfm.evaluate(x_data, y_labels)\n print(f'Test loss: {score[0]} / Test accuracy: {score[1]}')\n\n\n #X = torch.tensor(([2, 9], [1, 5], [3, 6]), dtype=torch.float) # 3 X 2 tensor\n #Y = [torch.FloatTensor(l[0]) for l in X]\n #X = [l[1] for l in X]\n\n #X = torch.stack(X)\n #Y = torch.stack(Y)\n #print(X.size())\n\n\n\n #print(Y, X)\n #y = torch.tensor(([92], [100], [89]), dtype=torch.float) # 3 X 1 tensor\n #xPredicted = torch.tensor(([4, 8]), dtype=torch.float) # 1 X 2 tensor\n # scale units\n #X_max, _ = torch.max(X, 0)\n #xPredicted_max, _ = torch.max(xPredicted, 0)\n\n #X = torch.div(X, X_max)\n #xPredicted = torch.div(xPredicted, xPredicted_max)\n #y = y / 100 # max test score is 100\n #NN = Net.NNetwork()\n #Loss = []\n #for i in range(1000): # trains the NN 1,000 times\n # l = str(torch.mean((Y - NN(X)) ** 2).detach().item())\n #print(\"#\" + str(i) + \" Loss: \" + l) # mean sum squared loss\n # Loss.append(l)\n # NN.train(X, Y)\n #NN.saveWeights(NN)\n #torch.save(Loss, \"model/loss.pt\")\n #NN.predict()\n\n #Get the data to train on and the data to test on\n #scale the data to train on and test on\n #train the network on the data\n\n pass\n\n if (len(sys.argv) > 1) and (sys.argv[1] == '-test'):\n tfm = tf_model.TFModel()\n\n D = Dataset(['../temp_evaluate/evaluateBVBPRI.pt'], tensor_data=True) # 967\n D = iter(D)\n\n X = [[]]\n count = 0\n\n for x in tqdm(D):\n x = model.average_tensors(x).tolist()\n # print(x[1])\n # print(x)\n X[0].append(x)\n # print(L)\n # print(len(L[0][1]))\n # exit(0)\n count += 1\n # print(\"Tensor\", count, \"averaged.\")\n if count > 1000: break;\n\n # print(X[0])\n #X = [t[1] for t in X]\n\n # print(\"RAW Y:\", Y)\n\n tfm = tf_model.TFModel()\n data = tfm.preprocess_unlabeled(X)\n\n print(\"DATA:\", [x for x in data])\n\n score = tfm.predict(data)\n max_index = np.argmax(score[0])\n max_val = score[0][max_index]\n change = \"Bitcoin's price will rise tomorrow\" if max_index == 0 else \"Bitcoin's price will fall tomorrow\"\n confidence = str(int(max_val * 100)) + \"%\"\n output_screen = \"###########################\\n\" + change + \"\\n\" + \\\n \"Confidence is \" + confidence + \"\\n\" + \"###########################\"\n print(output_screen)\n\n" ]
[ [ "numpy.concatenate", "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
apapaion/menpo
[ "9834f0437ca3cbe6a972c2a62f7c970ae950cf32", "9834f0437ca3cbe6a972c2a62f7c970ae950cf32", "9834f0437ca3cbe6a972c2a62f7c970ae950cf32" ]
[ "menpo/transform/test/test_h_translation.py", "menpo/transform/test/test_image_tcoords.py", "menpo/image/test/test_image_warp.py" ]
[ "import numpy as np\nfrom numpy.testing import assert_allclose, assert_almost_equal\nfrom pytest import raises\n\nfrom menpo.transform import Translation\n\n\ndef test_1d_translation():\n t_vec = np.array([1])\n with raises(ValueError):\n Translation(t_vec)\n\n\ndef test_5d_translation():\n t_vec = np.ones(5)\n with raises(ValueError):\n Translation(t_vec)\n\n\ndef test_translation():\n t_vec = np.array([1, 2, 3])\n starting_vector = np.random.rand(10, 3)\n transform = Translation(t_vec)\n transformed = transform.apply(starting_vector)\n assert_allclose(starting_vector + t_vec, transformed)\n\n\ndef test_translation_2d_from_vector():\n params = np.array([1, 2])\n homo = np.array([[1, 0, params[0]], [0, 1, params[1]], [0, 0, 1]])\n\n tr = Translation.init_identity(2).from_vector(params)\n\n assert_almost_equal(tr.h_matrix, homo)\n\n\ndef test_translation_2d_as_vector():\n params = np.array([1, 2])\n vec = Translation(params).as_vector()\n assert_allclose(vec, params)\n\n\ndef test_translation_3d_from_vector():\n params = np.array([1, 2, 3])\n homo = np.array(\n [[1, 0, 0, params[0]], [0, 1, 0, params[1]], [0, 0, 1, params[2]], [0, 0, 0, 1]]\n )\n\n tr = Translation.init_identity(3).from_vector(params)\n\n assert_almost_equal(tr.h_matrix, homo)\n\n\ndef test_translation_3d_as_vector():\n params = np.array([1, 2, 3])\n vec = Translation(params).as_vector()\n assert_allclose(vec, params)\n\n\ndef test_translation_2d_n_parameters():\n trans = np.array([1, 2])\n t = Translation(trans)\n assert t.n_parameters == 2\n\n\ndef test_translation_3d_n_parameters():\n trans = np.array([1, 2, 3])\n t = Translation(trans)\n assert t.n_parameters == 3\n\n\ndef test_translation_from_list():\n t_a = Translation([3, 4])\n t_b = Translation(np.array([3, 4]))\n assert np.all(t_a.h_matrix == t_b.h_matrix)\n\n\ndef test_translation_identity_2d():\n assert_allclose(Translation.init_identity(2).h_matrix, np.eye(3))\n\n\ndef test_translation_identity_3d():\n assert_allclose(Translation.init_identity(3).h_matrix, np.eye(4))\n\n\ndef test_translation_decompose_optional():\n t = Translation.init_identity(2)\n d = t.decompose()\n assert np.all(d[0].h_matrix == t.h_matrix)\n", "import numpy as np\nfrom numpy.testing import assert_equal\n\nfrom menpo.transform import image_coords_to_tcoords, tcoords_to_image_coords\n\nIMG_SHAPE = (121, 251)\nTCOORDS = np.array([[0, 0], [0, 1], [1, 1], [1, 0], [0.5, 0.5]])\n\nIMG_COORDS = np.array([[120, 0], [0, 0], [0, 250], [120, 250], [60, 125]])\n\n\ndef test_tcoords_to_image_coords():\n assert_equal(tcoords_to_image_coords(IMG_SHAPE).apply(TCOORDS), IMG_COORDS)\n\n\ndef test_image_coords_to_tcoords():\n assert_equal(image_coords_to_tcoords(IMG_SHAPE).apply(IMG_COORDS), TCOORDS)\n", "from unittest.mock import PropertyMock\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose, assert_almost_equal\nfrom pytest import raises\n\nimport menpo\nimport menpo.io as mio\nfrom menpo.image import BooleanImage, Image, MaskedImage, OutOfMaskSampleError\nfrom menpo.image.interpolation import cv2_perspective_interpolation\nfrom menpo.shape import PointCloud, bounding_box\nfrom menpo.transform import Affine, Rotation, UniformScale\n\nCROP_COORDS = (np.array([70, 30]), np.array([169, 129]))\n\n\[email protected]()\ndef interpolation_method(mocker, method):\n # This uses the pytest-mock package in order to provide a fixture that will\n # mock the global variable in the image module that determines if OpenCV\n # should be used or not. Useful for running the unit tests with and without\n # opencv\n interp = PropertyMock()\n interp.return_value = method\n mocker.patch(\"menpo.image.base.cv2_perspective_interpolation\", new_callable=interp)\n\n\ndef opencv_and_scipy_interpolation(func):\n # This decorator combines the \"interpolation_method\" fixture from above\n # with a parameterize decorator to run unit tests with and without OpenCV\n parameterize = pytest.mark.parametrize(\n \"method\",\n [None, cv2_perspective_interpolation],\n ids=lambda x: \"opencv\" if x is not None else \"scipy\",\n )\n use_fixtures = pytest.mark.usefixtures(\"interpolation_method\")\n return use_fixtures(parameterize(func))\n\n\[email protected]()\ndef rgb_image():\n return mio.import_builtin_asset(\"takeo.ppm\")\n\n\[email protected]()\ndef gray_image():\n return mio.import_builtin_asset(\"takeo.ppm\").as_greyscale()\n\n\[email protected]()\ndef gray_template(gray_image):\n gray_template = gray_image.crop(*CROP_COORDS)\n mask = BooleanImage.init_blank(gray_template.shape)\n return gray_template, mask\n\n\[email protected]()\ndef target_transform():\n initial_params = np.array([0, 0, 0, 0, 70, 30])\n return Affine.init_identity(2).from_vector(initial_params)\n\n\ndef test_warp_gray(gray_image, gray_template, target_transform):\n gray_template, mask = gray_template\n warped_im = gray_image.warp_to_mask(mask, target_transform)\n\n assert warped_im.shape == gray_template.shape\n assert_allclose(warped_im.pixels, gray_template.pixels)\n\n\ndef test_warp_gray_batch(gray_image, gray_template, target_transform):\n gray_template, mask = gray_template\n warped_im = gray_image.warp_to_mask(mask, target_transform, batch_size=100)\n\n assert warped_im.shape == gray_template.shape\n assert_allclose(warped_im.pixels, gray_template.pixels)\n\n\ndef test_warp_multi(rgb_image, target_transform):\n rgb_template = rgb_image.crop(*CROP_COORDS)\n mask = BooleanImage.init_blank(rgb_template.shape)\n warped_im = rgb_image.warp_to_mask(mask, target_transform)\n\n assert warped_im.shape == rgb_template.shape\n assert_allclose(warped_im.pixels, rgb_template.pixels)\n\n\ndef test_warp_to_mask_boolean():\n b = BooleanImage.init_blank((10, 10))\n b.pixels[:, :5] = False\n template_mask = BooleanImage.init_blank((10, 10))\n template_mask.pixels[:5, :] = False\n t = Affine.init_identity(2)\n warped_mask = b.warp_to_mask(template_mask, t)\n assert type(warped_mask) == BooleanImage\n result = template_mask.pixels.copy()\n result[:, :5] = False\n assert np.all(result == warped_mask.pixels)\n\n\ndef test_warp_to_mask_image():\n img = Image.init_blank((10, 10), n_channels=2)\n img.pixels[:, :, :5] = 0.5\n template_mask = BooleanImage.init_blank((10, 10))\n template_mask.pixels[:, 5:, :] = False\n t = Affine.init_identity(2)\n warped_img = img.warp_to_mask(template_mask, t)\n assert type(warped_img) == MaskedImage\n result = Image.init_blank((10, 10), n_channels=2).pixels\n result[:, :5, :5] = 0.5\n assert np.all(result == warped_img.pixels)\n\n\ndef test_warp_to_mask_masked_image():\n mask = BooleanImage.init_blank((15, 15))\n # make a truncated mask on the original image\n mask.pixels[0, -1, -1] = False\n img = MaskedImage.init_blank((15, 15), n_channels=2, mask=mask, fill=2.5)\n template_mask = BooleanImage.init_blank((10, 10), fill=False)\n template_mask.pixels[:, :5, :5] = True\n t = Affine.init_identity(2)\n warped_img = img.warp_to_mask(template_mask, t)\n assert type(warped_img) == MaskedImage\n\n result = Image.init_blank((10, 10), n_channels=2).pixels\n result[:, :5, :5] = 2.5\n result_mask = BooleanImage.init_blank((10, 10), fill=False).pixels\n result_mask[:, :5, :5] = True\n assert warped_img.n_true_pixels() == 25\n assert_allclose(result, warped_img.pixels)\n assert_allclose(result_mask, warped_img.mask.pixels)\n\n\ndef test_warp_to_mask_masked_image_all_true():\n img = MaskedImage.init_blank((10, 10), fill=2.5)\n\n template_mask = BooleanImage.init_blank((10, 10), fill=False)\n template_mask.pixels[:, :5, :5] = True\n t = Affine.init_identity(2)\n warped_img = img.warp_to_mask(template_mask, t)\n assert type(warped_img) == MaskedImage\n\n\ndef test_warp_to_shape_equal_warp_to_mask():\n r = menpo.transform.UniformScale(2.0, n_dims=2)\n b = mio.import_builtin_asset(\"breakingbad.jpg\")\n m_shape = b.warp_to_shape((540, 960), r)\n m_mask = b.warp_to_mask(menpo.image.BooleanImage.init_blank((540, 960)), r)\n assert_allclose(m_shape.pixels, m_mask.pixels)\n\n\ndef test_warp_to_shape_batch():\n r = menpo.transform.Affine.init_identity(2)\n b = mio.import_builtin_asset(\"takeo.ppm\")\n m_shape = b.warp_to_shape(b.shape, r, batch_size=100)\n assert_allclose(m_shape.pixels, b.pixels)\n\n\ndef test_rescale_boolean():\n mask = BooleanImage.init_blank((100, 100))\n mask.resize((10, 10))\n\n\ndef test_rescale_return_transform():\n img = Image.init_blank((100, 100), n_channels=1)\n img.landmarks[\"test\"] = bounding_box([40, 40], [80, 80])\n cropped_img, transform = img.rescale(1.5, return_transform=True)\n img_back = cropped_img.warp_to_shape(img.shape, transform.pseudoinverse())\n assert_allclose(img_back.shape, img.shape)\n assert_allclose(img_back.pixels, img.pixels)\n assert_allclose(img_back.landmarks[\"test\"].points, img.landmarks[\"test\"].points)\n\n\ndef test_sample_image():\n im = Image.init_blank((100, 100), fill=2)\n p = PointCloud(np.array([[0, 0], [1, 0]]))\n\n arr = im.sample(p)\n assert_allclose(arr, [[2.0, 2.0]])\n\n\ndef test_sample_maskedimage():\n im = MaskedImage.init_blank((100, 100), fill=2)\n p = PointCloud(np.array([[0, 0], [1, 0]]))\n\n arr = im.sample(p)\n assert_allclose(arr, [[2.0, 2.0]])\n\n\ndef test_sample_maskedimage_error():\n m = np.zeros([100, 100], dtype=bool)\n im = MaskedImage.init_blank((100, 100), mask=m, fill=2)\n p = PointCloud(np.array([[0, 0], [1, 0]]))\n with raises(OutOfMaskSampleError):\n im.sample(p, verify_mask=True)\n\n\ndef test_sample_maskedimage_error_values():\n m = np.zeros([100, 100], dtype=bool)\n m[1, 0] = True\n im = MaskedImage.init_blank((100, 100), mask=m, fill=2)\n p = PointCloud(np.array([[0, 0], [1, 0]]))\n try:\n im.sample(p, verify_mask=True)\n # Expect exception!\n assert 0\n except OutOfMaskSampleError as e:\n sampled_mask = e.sampled_mask\n sampled_values = e.sampled_values\n assert_allclose(sampled_values, [[2.0, 2.0]])\n assert_allclose(sampled_mask, [[False, True]])\n\n\ndef test_sample_booleanimage():\n im = BooleanImage.init_blank((100, 100))\n im.pixels[0, 1, 0] = False\n p = PointCloud(np.array([[0, 0], [1, 0]]))\n\n arr = im.sample(p)\n assert_allclose(arr, [[True, False]])\n\n\n@opencv_and_scipy_interpolation\ndef test_transform_about_centre(method):\n pixels_16 = np.arange(16, dtype=float)\n image = Image(pixels_16.reshape(4, 4))\n transform = Rotation.init_from_2d_ccw_angle(180).compose_before(\n UniformScale(2, n_dims=2)\n )\n # rotate 180 + scale degrees\n transformed_img = image.transform_about_centre(transform, mode=\"nearest\", order=1)\n expected_pixels = np.concatenate(\n [np.linspace(15 - 2 * i, 12 - 2 * i, num=7)[None] for i in range(7)]\n )\n\n assert transformed_img.shape == (7, 7)\n assert_allclose(transformed_img.pixels[0], expected_pixels, rtol=1e-8, atol=1e-8)\n\n\n@opencv_and_scipy_interpolation\ndef test_zoom_image():\n im = Image.init_blank((100, 100), fill=0)\n # White square in the centre of size 10x10\n im.pixels[0, 45:55, 45:55] = 1.0\n\n # Zoom in 50% makes the white square 5 pixel bigger in theory (16x16)\n zim = im.zoom(1.5)\n assert np.count_nonzero(zim.pixels) == 256\n\n\ndef test_zoom_booleanimage():\n im = BooleanImage.init_blank((100, 100))\n im.pixels[0, 0, :] = False\n im.pixels[0, -1, :] = False\n im.pixels[0, :, 0] = False\n im.pixels[0, :, -1] = False\n\n zim = im.zoom(1.2)\n assert np.all(zim.pixels)\n\n\n@opencv_and_scipy_interpolation\ndef test_mirror_horizontal_image():\n image = Image(\n np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]])\n )\n image.landmarks[\"temp\"] = PointCloud(\n np.array([[1.0, 1.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0]])\n )\n mirrored_img = image.mirror(axis=0)\n assert_allclose(\n mirrored_img.pixels,\n np.array(\n [[[9.0, 10.0, 11.0, 12.0], [5.0, 6.0, 7.0, 8.0], [1.0, 2.0, 3.0, 4.0]]]\n ),\n )\n assert_allclose(\n mirrored_img.landmarks[\"temp\"].points,\n np.array([[1.0, 1.0], [1.0, 2.0], [0.0, 1.0], [0.0, 2.0]]),\n )\n\n\n@opencv_and_scipy_interpolation\ndef test_mirror_vertical_image():\n image = Image(\n np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]])\n )\n image.landmarks[\"temp\"] = PointCloud(\n np.array([[1.0, 0.0], [1.0, 1.0], [2.0, 1.0], [2.0, 2.0]])\n )\n mirrored_img = image.mirror()\n assert_allclose(\n mirrored_img.pixels,\n np.array(\n [[[4.0, 3.0, 2.0, 1.0], [8.0, 7.0, 6.0, 5.0], [12.0, 11.0, 10.0, 9.0]]]\n ),\n )\n assert_allclose(\n mirrored_img.landmarks[\"temp\"].points,\n np.array([[1.0, 3.0], [1.0, 2.0], [2.0, 2.0], [2.0, 1.0]]),\n )\n\n\ndef test_mirror_image_axis_error():\n with raises(ValueError):\n Image(np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]])).mirror(axis=2)\n\n\ndef test_mirror_masked_image():\n image = MaskedImage(np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]))\n mirrored_img = image.mirror()\n assert type(mirrored_img) == MaskedImage\n\n\ndef test_mirror_return_transform():\n img = Image.init_blank((100, 100), n_channels=1)\n img.landmarks[\"test\"] = bounding_box([40, 40], [80, 80])\n cropped_img, transform = img.mirror(return_transform=True)\n img_back = cropped_img.warp_to_shape(img.shape, transform.pseudoinverse())\n assert_allclose(img_back.shape, img.shape)\n assert_allclose(img_back.pixels, img.pixels)\n assert_allclose(img_back.landmarks[\"test\"].points, img.landmarks[\"test\"].points)\n\n\n@opencv_and_scipy_interpolation\ndef test_rotate_image_90_180():\n image = Image(\n np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]])\n )\n image.landmarks[\"temp\"] = PointCloud(\n np.array([[1.0, 1.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0]])\n )\n # rotate 90 degrees\n rotated_img = image.rotate_ccw_about_centre(theta=90, order=1, mode=\"nearest\")\n rotated_img.landmarks[\"temp\"] = rotated_img.landmarks[\"temp\"].constrain_to_bounds(\n rotated_img.bounds()\n )\n assert_allclose(\n rotated_img.pixels,\n np.array(\n [[[4.0, 8.0, 12.0], [3.0, 7.0, 11.0], [2.0, 6.0, 10.0], [1.0, 5.0, 9.0]]]\n ),\n )\n assert_almost_equal(\n rotated_img.landmarks[\"temp\"].points,\n np.array([[2.0, 1.0], [1.0, 1.0], [2.0, 2.0], [1.0, 2.0]]),\n )\n\n # rotate 180 degrees\n rotated_img = image.rotate_ccw_about_centre(theta=180, order=1, mode=\"nearest\")\n rotated_img.landmarks[\"temp\"] = rotated_img.landmarks[\"temp\"].constrain_to_bounds(\n rotated_img.bounds()\n )\n assert_allclose(\n rotated_img.pixels,\n np.array(\n [[[12.0, 11.0, 10.0, 9.0], [8.0, 7.0, 6.0, 5.0], [4.0, 3.0, 2.0, 1.0]]]\n ),\n )\n assert_almost_equal(\n rotated_img.landmarks[\"temp\"].points,\n np.array([[1.0, 2.0], [1.0, 1.0], [0.0, 2.0], [0.0, 1.0]]),\n )\n\n\ndef test_rotate_image_45():\n image = Image(\n np.array(\n [\n [1.0, 2.0, 3.0, 4.0],\n [5.0, 6.0, 7.0, 8.0],\n [9.0, 10.0, 11.0, 12.0],\n [13.0, 14.0, 15.0, 16.0],\n ]\n )\n )\n image.landmarks[\"temp\"] = PointCloud(\n np.array([[1.0, 1.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0]])\n )\n rotated_img = image.rotate_ccw_about_centre(theta=45, order=0)\n assert_allclose(\n rotated_img.pixels,\n np.array(\n [\n [\n [0.0, 0.0, 4.0, 0.0, 0.0],\n [0.0, 3.0, 7.0, 8.0, 0.0],\n [1.0, 6.0, 7.0, 11.0, 16.0],\n [0.0, 5.0, 10.0, 15.0, 15.0],\n [0.0, 0.0, 13.0, 14.0, 0.0],\n ]\n ]\n ),\n )\n assert_almost_equal(\n rotated_img.landmarks[\"temp\"].points,\n np.array([[2.121, 1.414], [1.414, 2.121], [2.828, 2.121], [2.121, 2.828]]),\n decimal=3,\n )\n\n\ndef test_rotate_return_transform():\n img = Image.init_blank((100, 100), n_channels=1)\n img.landmarks[\"test\"] = bounding_box([40, 40], [80, 80])\n cropped_img, transform = img.rotate_ccw_about_centre(60, return_transform=True)\n img_back = cropped_img.warp_to_shape(img.shape, transform.pseudoinverse())\n assert_allclose(img_back.shape, img.shape)\n assert_allclose(img_back.pixels, img.pixels)\n assert_allclose(img_back.landmarks[\"test\"].points, img.landmarks[\"test\"].points)\n\n\n@opencv_and_scipy_interpolation\ndef test_maskedimage_retain_shape():\n image = mio.import_builtin_asset(\"takeo.ppm\")\n image = image.as_masked()\n rotated_img = image.rotate_ccw_about_centre(theta=77, retain_shape=True)\n assert image.shape == rotated_img.shape\n assert type(rotated_img) == MaskedImage\n" ]
[ [ "numpy.eye", "numpy.ones", "numpy.all", "numpy.testing.assert_almost_equal", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array" ], [ "numpy.array" ], [ "numpy.linspace", "numpy.arange", "numpy.all", "numpy.count_nonzero", "numpy.testing.assert_allclose", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nkdnnlr/ECG-Heartbeat-Classification
[ "d75012794b17d0b3b8dd9026874c026445cf05c3" ]
[ "code/experiments/baseline_ptbdb.py" ]
[ "import pandas as pd\nimport numpy as np\n\nfrom keras import optimizers, losses, activations, models\nfrom keras.callbacks import (\n ModelCheckpoint,\n EarlyStopping,\n LearningRateScheduler,\n ReduceLROnPlateau,\n)\nfrom keras.layers import (\n Dense,\n Input,\n Dropout,\n Convolution1D,\n MaxPool1D,\n GlobalMaxPool1D,\n GlobalAveragePooling1D,\n concatenate,\n)\nfrom keras.metrics import AUC\nfrom sklearn.metrics import (\n accuracy_score,\n f1_score,\n average_precision_score,\n roc_auc_score,\n)\nfrom sklearn.model_selection import train_test_split\n\ndf_1 = pd.read_csv(\"../../data/ECG_Heartbeat_Classification/ptbdb_normal.csv\", header=None)\ndf_2 = pd.read_csv(\"../../data/ECG_Heartbeat_Classification/ptbdb_abnormal.csv\", header=None)\ndf = pd.concat([df_1, df_2])\n\ndf_train, df_test = train_test_split(\n df, test_size=0.2, random_state=1337, stratify=df[187]\n)\n\n\nY = np.array(df_train[187].values).astype(np.int8)\nX = np.array(df_train[list(range(187))].values)[..., np.newaxis]\n\nY_test = np.array(df_test[187].values).astype(np.int8)\nX_test = np.array(df_test[list(range(187))].values)[..., np.newaxis]\n\n\ndef get_model():\n nclass = 1\n inp = Input(shape=(187, 1))\n img_1 = Convolution1D(\n 16, kernel_size=5, activation=activations.relu, padding=\"valid\"\n )(inp)\n img_1 = Convolution1D(\n 16, kernel_size=5, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = MaxPool1D(pool_size=2)(img_1)\n img_1 = Dropout(rate=0.1)(img_1)\n img_1 = Convolution1D(\n 32, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = Convolution1D(\n 32, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = MaxPool1D(pool_size=2)(img_1)\n img_1 = Dropout(rate=0.1)(img_1)\n img_1 = Convolution1D(\n 32, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = Convolution1D(\n 32, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = MaxPool1D(pool_size=2)(img_1)\n img_1 = Dropout(rate=0.1)(img_1)\n img_1 = Convolution1D(\n 256, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = Convolution1D(\n 256, kernel_size=3, activation=activations.relu, padding=\"valid\"\n )(img_1)\n img_1 = GlobalMaxPool1D()(img_1)\n img_1 = Dropout(rate=0.2)(img_1)\n\n dense_1 = Dense(64, activation=activations.relu, name=\"dense_1\")(img_1)\n dense_1 = Dense(64, activation=activations.relu, name=\"dense_2\")(dense_1)\n dense_1 = Dense(nclass, activation=activations.sigmoid, name=\"dense_3_ptbdb\")(\n dense_1\n )\n\n model = models.Model(inputs=inp, outputs=dense_1)\n opt = optimizers.Adam(0.001)\n\n model.compile(optimizer=opt, loss=losses.binary_crossentropy, metrics=[\"acc\"])\n model.summary()\n return model\n\n\nmodel = get_model()\nfile_path = \"../../models/baseline_cnn_ptbdb.h5\"\ncheckpoint = ModelCheckpoint(\n file_path, monitor=\"val_acc\", verbose=1, save_best_only=True, mode=\"max\"\n)\nearly = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=5, verbose=1)\nredonplat = ReduceLROnPlateau(monitor=\"val_acc\", mode=\"max\", patience=3, verbose=2)\ncallbacks_list = [checkpoint, early, redonplat] # early\n\n# model.fit(X, Y, epochs=1000, verbose=2, callbacks=callbacks_list, validation_split=0.1)\nmodel.load_weights(file_path)\n\npred_test = model.predict(X_test)\npred_test = (pred_test > 0.5).astype(np.int8)\n\nf1 = f1_score(Y_test, pred_test)\nacc = accuracy_score(Y_test, pred_test)\nauroc = roc_auc_score(Y_test, pred_test)\nauprc = average_precision_score(Y_test, pred_test)\n\nprint(\"Test f1 score : %s \" % f1)\nprint(\"Test accuracy score : %s \" % acc)\nprint(\"AUROC score : %s \" % auroc)\nprint(\"AUPRC accuracy score : %s \" % auprc)\n" ]
[ [ "sklearn.metrics.roc_auc_score", "pandas.concat", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.metrics.average_precision_score", "sklearn.metrics.f1_score", "numpy.array", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
Harshitha-Nagapudi/NN_Project
[ "f0df170a33b6b35a00929a0104dc6ee04c5062a9" ]
[ "Improvements/gnnimprove.py" ]
[ "import torch.nn as nn\nimport torch.nn.functional as F\nimport math\nimport torch\nimport torch.optim as optim\nfrom torch.nn.parameter import Parameter\nfrom torch.nn.modules.module import Module\nfrom deeprobust.graph import utils\nfrom copy import deepcopy\nimport sys\nfrom scipy import stats\n\nimport tensorly as tl\ntl.set_backend('pytorch')\nfrom tensorly.decomposition import parafac, tucker, tensor_train, matrix_product_state\n\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom numba import njit\n\nclass GraphConvolution(Module):\n \"\"\"Simple GCN layer, similar to https://github.com/tkipf/pygcn\n \"\"\"\n\n def __init__(self, in_features, out_features, with_bias=True):\n super(GraphConvolution, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = Parameter(torch.FloatTensor(in_features, out_features))\n if with_bias:\n self.bias = Parameter(torch.FloatTensor(out_features))\n else:\n self.register_parameter('bias', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.weight.size(1))\n self.weight.data.uniform_(-stdv, stdv)\n if self.bias is not None:\n self.bias.data.uniform_(-stdv, stdv)\n\n def forward(self, input, adj):\n \"\"\" Graph Convolutional Layer forward function\n \"\"\"\n if input.data.is_sparse:\n support = torch.spmm(input, self.weight)\n else:\n support = torch.mm(input, self.weight)\n output = torch.spmm(adj, support)\n if self.bias is not None:\n return output + self.bias, support\n else:\n return output, support\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' \\\n + str(self.in_features) + ' -> ' \\\n + str(self.out_features) + ')'\n\nclass TGNN(nn.Module):\n def __init__(self, nfeat, nhid, nclass,\n dropout=0.5, lr=0.01, weight_decay=5e-4,\n with_relu=True, with_bias=True,\n format='Tucker', rank=32, pros='knn', euclidean=True,\n svd_rank=200, prune_thd=0.01,\n lambda_t = 1e-4, weight_decay_t=1e-5, topk=32,\n device=None):\n\n super(TGNN, self).__init__()\n\n assert device is not None, \"Please specify 'device'!\"\n self.device = device\n self.nfeat = nfeat\n self.hidden_sizes = [nhid]\n self.nclass = nclass\n self.gc1 = GraphConvolution(nfeat, nhid, with_bias=with_bias).to(device)\n self.gc2 = GraphConvolution(nhid, nclass, with_bias=with_bias).to(device)\n self.dropout = dropout\n self.lr = lr\n if not with_relu:\n self.weight_decay = 0\n else:\n self.weight_decay = weight_decay\n self.with_relu = with_relu\n self.with_bias = with_bias\n self.output = None\n self.best_model = None # not used\n self.best_output = None # not used\n self.best_A = None\n self.adj_norm = None\n self.features = None\n\n self.format = format\n self.rank = rank\n self.lamda_t = lambda_t\n self.weight_decay_t = weight_decay_t\n self.topk = topk\n\n self.pros = pros.split(',')\n\n self.euclidean = euclidean\n\n self.svd_rank = svd_rank\n self.prune_thd = prune_thd\n\n self.acc_lst = []\n\n def initialize(self):\n \"\"\"Initialize parameters of GCN.\n \"\"\"\n self.gc1.reset_parameters()\n self.gc2.reset_parameters()\n\n def truncatedSVD(self, data, k=50):\n \"\"\"Truncated SVD on input data.\n\n Parameters\n ----------\n data :\n input matrix to be decomposed\n k : int\n number of singular values and vectors to compute.\n\n Returns\n -------\n numpy.array\n reconstructed matrix.\n \"\"\"\n print('=== GCN-SVD: rank={} ==='.format(k))\n if sp.issparse(data):\n data = data.asfptype()\n U, S, V = sp.linalg.svds(data, k=k)\n print(\"rank_after = {}\".format(len(S.nonzero()[0])))\n diag_S = np.diag(S)\n else:\n U, S, V = np.linalg.svd(data)\n U = U[:, :k]\n S = S[:k]\n V = V[:k, :]\n print(\"rank_before = {}\".format(len(S.nonzero()[0])))\n diag_S = np.diag(S)\n print(\"rank_after = {}\".format(len(diag_S.nonzero()[0])))\n\n return U @ diag_S @ V\n\n def fit(self, features, adj, labels, idx_train, idx_val, train_iters=200,\n initialize=True, verbose=False, normalize=True, patience=500, **kwargs):\n\n self.device = self.gc1.weight.device\n if initialize:\n self.initialize()\n\n if 'svd' in self.pros:\n self.svd_adj = (adj+torch.eye(adj.size(0)).to(self.device)).cpu().numpy()\n self.svd_adj = self.truncatedSVD(data=self.svd_adj, k=self.svd_rank)\n self.svd_adj = torch.FloatTensor(self.svd_adj).to(self.device)\n self.svd_adj = torch.clamp(self.svd_adj, 0, 1)\n self.svd_adj = self.svd_adj.unsqueeze(0)\n\n if 'prune' in self.pros:\n self.prune_adj = (adj+torch.eye(adj.size(0)).to(self.device)).cpu().numpy()\n self.prune_adj = self.drop_dissimilar_edges(features=features.cpu().numpy(),\n adj=self.prune_adj)\n self.prune_adj = torch.FloatTensor(self.prune_adj.todense()).to(self.device)\n self.prune_adj = self.prune_adj.unsqueeze(0)\n\n if type(adj) is not torch.Tensor:\n features, adj, labels = utils.to_tensor(features, adj, labels, device=self.device)\n else:\n features = features.to(self.device)\n adj = adj.to(self.device)\n labels = labels.to(self.device)\n\n self.adj_org = (adj + torch.eye(adj.size(0)).to(self.device))\n\n if normalize:\n if utils.is_sparse_tensor(adj):\n adj_norm = utils.normalize_adj_tensor(adj, sparse=True)\n else:\n adj_norm = utils.normalize_adj_tensor(adj)\n else:\n adj_norm = adj\n\n self.adj_norm = adj_norm\n self.features = features\n self.labels = labels\n\n self._train_with_val(labels, idx_train, idx_val, train_iters, verbose)\n\n def forward(self, x, adj, A_bar=None, need_feats=False):\n x0 = x\n feats = [x0]\n\n adj1 = adj if A_bar is None else self.normalize(A_bar[0, :, :])\n x, support1 = self.gc1(x, adj1)\n\n if self.with_relu:\n x = F.relu(x)\n\n x = F.dropout(x, self.dropout, training=self.training)\n # print('training', self.training)\n x1 = x\n feats.append(x1)\n\n adj2 = adj if A_bar is None else self.normalize(A_bar[0, :, :])\n x, support2 = self.gc2(x, adj2)\n\n x2 = x\n feats.append(x2)\n\n if need_feats:\n return F.log_softmax(x, dim=1), feats\n\n return F.log_softmax(x, dim=1)\n\n def _norm_feat(self, X, p='l2'):\n if p == None:\n return X\n\n if p == 'l1':\n sum = 1 / (X.norm(p=1, dim=1, keepdim=True) + 1e-9).detach()\n sum[torch.isinf(sum)] = 0.\n X = X * sum\n return X\n\n if p == 'l2':\n sum = 1 / (X.norm(p=2, dim=1, keepdim=True) + 1e-9).detach()\n sum[torch.isinf(sum)] = 0.\n X = X * sum\n return X\n\n return None\n\n def normalize(self, adj):\n adj = torch.clamp(adj, 0, 1)\n normalized_adj = self._normalize(adj + torch.eye(adj.shape[0]).to(self.device))\n return normalized_adj\n\n def _normalize(self, mx):\n mx = torch.clamp(mx, 0, 1)\n rowsum = torch.abs(mx).sum(1)\n r_inv = rowsum.pow(-1/2).flatten()\n r_inv[torch.isinf(r_inv)] = 0.\n r_mat_inv = torch.diag(r_inv).detach()\n mx = r_mat_inv @ mx\n mx = mx @ r_mat_inv\n return mx\n\n def _knn(self, X, k=None):\n k = k if k is not None else self.topk\n topk = X.topk(k, dim=1)[1]\n ret = torch.zeros_like(X)\n for i in range(ret.size(0)):\n ret[i, topk[i]] = 1\n return ret\n\n def _get_knn(self, X, k=None):\n if self.is_binary:\n intersection = torch.mm(X, X.t())\n union = X.size(1) - torch.mm((1 - X), (1 - X).t())\n smooth = 1\n S = (intersection + smooth) / (union + smooth)\n else:\n X = self._norm_feat(X, p='l2')\n S = -torch.cdist(X, X)\n Z = self._knn(S, k=k).clone().detach().unsqueeze(0)\n return Z\n\n def _init_td(self):\n A = torch.stack([self.adj_org for _ in range(1)], dim=0)\n self.OA = A\n _, X = self.forward(self.features, self.adj_norm, A_bar=A, need_feats=True)\n\n self.T = [A]\n self.is_binary = [1]\n self.reg_name = ['ADJ']\n\n if 'knn' in self.pros:\n Z = self._get_knn(X[0])\n self.Z = Z\n self.T.append(self.Z)\n self.is_binary.append(1)\n self.reg_name.append('KNN%d'%self.topk)\n\n if 'svd' in self.pros:\n self.T.append(self.svd_adj)\n self.is_binary.append(0)\n self.reg_name.append('SVD%d'%self.svd_rank)\n\n if 'prune' in self.pros:\n self.T.append(self.prune_adj)\n self.is_binary.append(1)\n self.reg_name.append('PRUNE%.6f'%self.prune_thd)\n\n self.T = torch.cat(self.T, dim=0)\n\n T = self.T\n self.A = T[:1, :, :]\n\n if self.format == 'CP':\n weights, factors = parafac(T.transpose(1, 0), self.rank, init='random', normalize_factors=True)\n self.register_parameter('f0', Parameter(torch.zeros_like(factors[0]).to(self.device), requires_grad=True))\n self.register_parameter('f1', Parameter(torch.zeros_like(factors[1]).to(self.device), requires_grad=True))\n self.register_parameter('f2', Parameter(torch.zeros_like(factors[2]).to(self.device), requires_grad=True))\n self.register_parameter('of0', Parameter((factors[0]).to(self.device), requires_grad=False))\n self.register_parameter('of1', Parameter((factors[1]).to(self.device), requires_grad=False))\n self.register_parameter('of2', Parameter((factors[2]).to(self.device), requires_grad=False))\n self.register_parameter('weights', Parameter(torch.zeros_like(weights).to(self.device), requires_grad=True))\n self.register_parameter('oweights', Parameter((weights).to(self.device), requires_grad=False))\n elif self.format == 'Tucker':\n core, factors = tucker(T, rank=self.rank, init='random')\n self.register_parameter('f0', Parameter(torch.zeros_like(factors[0]).to(self.device), requires_grad=True))\n self.register_parameter('f1', Parameter(torch.zeros_like(factors[1]).to(self.device), requires_grad=True))\n self.register_parameter('f2', Parameter(torch.zeros_like(factors[2]).to(self.device), requires_grad=True))\n self.register_parameter('of0', Parameter((factors[0]).to(self.device), requires_grad=False))\n self.register_parameter('of1', Parameter((factors[1]).to(self.device), requires_grad=False))\n self.register_parameter('of2', Parameter((factors[2]).to(self.device), requires_grad=False))\n self.register_parameter('core',Parameter(torch.zeros_like(core).to(self.device), requires_grad=True))\n self.register_parameter('ocore', Parameter((core).to(self.device), requires_grad=False))\n elif self.format == 'TT':\n factors = matrix_product_state(T, rank=[1, self.rank, self.rank, 1])\n print([_.size() for _ in factors])\n self.register_parameter('f0', Parameter(torch.zeros_like(factors[0]).to(self.device), requires_grad=True))\n self.register_parameter('f1', Parameter(torch.zeros_like(factors[1]).to(self.device), requires_grad=True))\n self.register_parameter('f2', Parameter(torch.zeros_like(factors[2]).to(self.device), requires_grad=True))\n self.register_parameter('of0', Parameter((factors[0]).to(self.device), requires_grad=False))\n self.register_parameter('of1', Parameter((factors[1]).to(self.device), requires_grad=False))\n self.register_parameter('of2', Parameter((factors[2]).to(self.device), requires_grad=False))\n\n def forward_T(self):\n if self.format == 'CP':\n factors = [self.f0 + self.of0, self.f1 + self.of1, self.f2 + self.of2]\n core = self.weights + self.oweights\n T_bar = tl.cp_to_tensor((core, factors))\n T_bar = T_bar.transpose(1, 0) # avoid svd oom\n elif self.format == 'Tucker':\n factors = [self.f0 + self.of0, self.f1 + self.of1, self.f2 + self.of2]\n core = self.core + self.ocore\n T_bar = tl.tucker_to_tensor((core, factors))\n elif self.format == 'TT':\n factors = [self.f0 + self.of0, self.f1 + self.of1, self.f2 + self.of2]\n T_bar = tl.tt_to_tensor(factors)\n\n self.T_bar = T_bar\n self.A_bar = T_bar[:1]\n\n def rec_loss(self, X, Y):\n X = torch.clamp(X, 0, 1)\n return ((X - Y) ** 2).mean()\n\n def _gcn_step(self, i, optimizer_G, optimizer_T, idx_train, labels):\n self.train()\n optimizer_G.zero_grad()\n if optimizer_T is not None:\n optimizer_T.zero_grad()\n\n self.forward_T()\n\n output, X = self.forward(self.features, self.adj_norm, A_bar=self.A_bar, need_feats=True)\n\n loss_cls = F.nll_loss(output[idx_train], labels[idx_train])\n\n loss_reg, loss_adj = 0, 0\n\n if optimizer_T is not None:\n for r in range(self.T.size(0)):\n S0_normed = torch.clamp(self.T_bar[r], 0, 1)\n S0_normed_t = torch.clamp(self.T[r].detach(), 0, 1)\n\n loss = self.rec_loss(S0_normed, S0_normed_t)\n\n if r == 0:\n loss_adj = loss_adj + self.lamda_t * loss\n else:\n loss_reg = loss_reg + self.lamda_t * loss\n sys.stdout.flush()\n\n loss_train = loss_cls + (loss_reg * self.lamda_t + loss_adj * self.lamda_t)\n\n loss_train.backward()\n optimizer_G.step()\n if optimizer_T is not None:\n optimizer_T.step()\n\n def _train_with_val(self, labels, idx_train, idx_val, train_iters, verbose):\n if verbose:\n print('=== Initialization ===')\n self.eval()\n self._init_td()\n self.forward_T()\n\n if verbose:\n print('=== pre-training tensor model ===')\n\n g_parameters = []\n t_parameters = []\n for name, param in self.named_parameters():\n if name[:2] == 'gc':\n g_parameters.append(param)\n else:\n t_parameters.append(param)\n optimizer_T = optim.Adam(t_parameters, lr=self.lr, weight_decay=self.weight_decay_t) if len(t_parameters) > 0 else None\n optimizer_G = optim.Adam(g_parameters, lr=self.lr, weight_decay=self.weight_decay)\n\n if verbose:\n print('=== training gcn model ===')\n best_loss_val = 1e10\n best_acc_val = 0\n\n for i in range(train_iters):\n self._gcn_step(i, optimizer_G, optimizer_T, idx_train, labels)\n\n self.eval()\n self.forward_T()\n output = self.forward(self.features, self.adj_norm, self.A_bar)\n loss_val = F.nll_loss(output[idx_val], labels[idx_val])\n acc_val = utils.accuracy(output[idx_val], labels[idx_val])\n loss_cls = F.nll_loss(output[idx_train], labels[idx_train])\n acc_train = utils.accuracy(output[idx_train], labels[idx_train])\n\n if best_loss_val > loss_val:\n best_loss_val = loss_val\n self.output = output\n self.best_A = self.A_bar.clone().detach()\n weights = deepcopy(self.state_dict())\n\n if acc_val > best_acc_val:\n best_acc_val = acc_val\n self.output = output\n self.best_A = self.A_bar.clone().detach()\n weights = deepcopy(self.state_dict())\n\n print('Epoch: {:04d}'.format(i + 1),\n 'loss_val: {:.4f}'.format(loss_val.item()),\n 'loss_train: {:.4f}'.format(loss_cls.item()),\n 'acc_val: {:.4f}'.format(acc_val.item()),\n 'acc_train: {:.4f}'.format(acc_train.item()))\n\n if verbose:\n print('=== picking the best model according to the performance on validation ===')\n self.load_state_dict(weights)\n\n def test(self, idx_test):\n \"\"\"Evaluate GCN performance on test set.\n\n Parameters\n ----------\n idx_test :\n node testing indices\n \"\"\"\n self.eval()\n output = self.predict()\n # output = self.output\n loss_test = F.nll_loss(output[idx_test], self.labels[idx_test])\n acc_test = utils.accuracy(output[idx_test], self.labels[idx_test])\n print(\"Test set results:\",\n \"loss= {:.4f}\".format(loss_test.item()),\n \"accuracy= {:.4f}\".format(acc_test.item()))\n return acc_test\n\n\n def predict(self):\n # return self.output\n if(scores.A1 ==1):\n self.eval()\n else:\n print(\"features not considered as they're unnoticeable\")\n return self.forward(self.features, self.adj_norm, A_bar=self.best_A)\n\n def drop_dissimilar_edges(self, features, adj, metric='similarity'):\n \"\"\"Drop dissimilar edges.(Faster version using numba)\n \"\"\"\n if not sp.issparse(adj):\n adj = sp.csr_matrix(adj)\n\n adj_triu = sp.triu(adj, format='csr')\n\n if metric == 'distance':\n removed_cnt = dropedge_dis(adj_triu.data, adj_triu.indptr, adj_triu.indices, features, threshold=self.prune_thd)\n else:\n if self.euclidean:\n removed_cnt = dropedge_prune(adj_triu.data, adj_triu.indptr, adj_triu.indices, features, threshold=self.prune_thd)\n else:\n removed_cnt = dropedge_cosine(adj_triu.data, adj_triu.indptr, adj_triu.indices, features, threshold=self.prune_thd)\n print('removed %s edges in the original graph' % removed_cnt)\n modified_adj = adj_triu + adj_triu.transpose()\n return modified_adj\n\n def _drop_dissimilar_edges(self, features, adj):\n \"\"\"Drop dissimilar edges. (Slower version)\n \"\"\"\n if not sp.issparse(adj):\n adj = sp.csr_matrix(adj)\n modified_adj = adj.copy().tolil()\n\n # preprocessing based on features\n print('=== GCN-Jaccrad ===')\n edges = np.array(modified_adj.nonzero()).T\n removed_cnt = 0\n for edge in tqdm(edges):\n n1 = edge[0]\n n2 = edge[1]\n if n1 > n2:\n continue\n\n if self.euclidean:\n J = self._prune_similarity(features[n1], features[n2])\n\n if J < self.prune_thd:\n modified_adj[n1, n2] = 0\n modified_adj[n2, n1] = 0\n removed_cnt += 1\n else:\n # For not binary feature, use cosine similarity\n C = self._cosine_similarity(features[n1], features[n2])\n if C < self.prune_thd:\n modified_adj[n1, n2] = 0\n modified_adj[n2, n1] = 0\n removed_cnt += 1\n print('removed %s edges in the original graph' % removed_cnt)\n return modified_adj\n \n # New Updation\n def feature_scores(self):\n \"\"\"\n Compute feature scores for all possible feature changes.\n \"\"\"\n\n if self.cooc_constraint is None:\n self.compute_cooccurrence_constraint(self.influencer_nodes)\n logits = self.compute_logits()\n best_wrong_class = self.strongest_wrong_class(logits)\n gradient = self.gradient_wrt_x(self.label_u) - self.gradient_wrt_x(best_wrong_class)\n surrogate_loss = logits[self.label_u] - logits[best_wrong_class]\n\n gradients_flipped = (gradient * -1).tolil()\n gradients_flipped[self.X_obs.nonzero()] *= -1\n\n X_influencers = sp.lil_matrix(self.X_obs.shape)\n X_influencers[self.influencer_nodes] = self.X_obs[self.influencer_nodes]\n gradients_flipped = gradients_flipped.multiply((self.cooc_constraint + X_influencers) > 0)\n nnz_ixs = np.array(gradients_flipped.nonzero()).T\n\n sorting = np.argsort(gradients_flipped[tuple(nnz_ixs.T)]).A1\n sorted_ixs = nnz_ixs[sorting]\n grads = gradients_flipped[tuple(nnz_ixs[sorting].T)]\n\n scores = surrogate_loss - grads\n return sorted_ixs[::-1], scores.A1[::-1]\n\n def _prune_similarity(self, a, b):\n intersection = a.multiply(b).count_nonzero()\n J = intersection * 1.0 / (a.count_nonzero() + b.count_nonzero() - intersection)\n return J\n\n def _cosine_similarity(self, a, b):\n inner_product = (features[n1] * features[n2]).sum()\n C = inner_product / np.sqrt(np.square(a).sum() + np.square(b).sum())\n return C\n\ndef dropedge_prune(A, iA, jA, features, threshold):\n removed_cnt = 0\n for row in range(len(iA)-1):\n for i in range(iA[row], iA[row+1]):\n # print(row, jA[i], A[i])\n n1 = row\n n2 = jA[i]\n a, b = features[n1], features[n2]\n intersection = np.count_nonzero(np.multiply(a, b))\n # intersection = a.multiply(b).count_nonzero()\n J = intersection * 1.0 / (np.count_nonzero(a) + np.count_nonzero(b) - intersection)\n # J = intersection * 1.0 / (a.count_nonzero() + b.count_nonzero() - intersection)\n\n if J < threshold:\n A[i] = 0\n # A[n2, n1] = 0\n removed_cnt += 1\n return removed_cnt\n\n\n@njit\ndef dropedge_cosine(A, iA, jA, features, threshold):\n removed_cnt = 0\n for row in range(len(iA)-1):\n for i in range(iA[row], iA[row+1]):\n # print(row, jA[i], A[i])\n n1 = row\n n2 = jA[i]\n a, b = features[n1], features[n2]\n inner_product = (a * b).sum()\n C = inner_product / (np.sqrt(np.square(a).sum() + np.square(b).sum())+ 1e-6)\n\n if C < threshold:\n A[i] = 0\n # A[n2, n1] = 0\n removed_cnt += 1\n return removed_cnt\n\n@njit\ndef dropedge_dis(A, iA, jA, features, threshold):\n removed_cnt = 0\n for row in range(len(iA)-1):\n for i in range(iA[row], iA[row+1]):\n # print(row, jA[i], A[i])\n n1 = row\n n2 = jA[i]\n C = np.linalg.norm(features[n1] - features[n2])\n if C > threshold:\n A[i] = 0\n # A[n2, n1] = 0\n removed_cnt += 1\n\n return removed_cnt\n\n@njit\ndef dropedge_both(A, iA, jA, features, threshold1=2.5, threshold2=0.01):\n removed_cnt = 0\n for row in range(len(iA)-1):\n for i in range(iA[row], iA[row+1]):\n # print(row, jA[i], A[i])\n n1 = row\n n2 = jA[i]\n C1 = np.linalg.norm(features[n1] - features[n2])\n\n a, b = features[n1], features[n2]\n inner_product = (a * b).sum()\n C2 = inner_product / (np.sqrt(np.square(a).sum() + np.square(b).sum())+ 1e-6)\n if C1 > threshold1 or threshold2 < 0:\n A[i] = 0\n # A[n2, n1] = 0\n removed_cnt += 1\n\n return removed_cnt\n" ]
[ [ "numpy.diag", "torch.abs", "torch.nn.functional.nll_loss", "torch.nn.functional.dropout", "torch.cat", "torch.cdist", "torch.FloatTensor", "numpy.square", "numpy.linalg.svd", "torch.mm", "scipy.sparse.issparse", "torch.eye", "torch.nn.functional.relu", "numpy.count_nonzero", "torch.optim.Adam", "torch.isinf", "numpy.multiply", "torch.zeros_like", "scipy.sparse.csr_matrix", "scipy.sparse.linalg.svds", "scipy.sparse.triu", "torch.diag", "torch.nn.functional.log_softmax", "numpy.linalg.norm", "torch.clamp", "torch.spmm", "scipy.sparse.lil_matrix" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
LiYingwei/Regional-Homogeneity
[ "6b0b521ff6e9d1f4c3f25cb25518968047b5cca0" ]
[ "attack.py" ]
[ "from config import config as FLAGS\nimport tensorflow as tf\nfrom tensorpack import (BatchData)\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom RHP_ops import conv_with_rn\nfrom data import PNGDataFlow, save_images\nfrom networks import network\n\nfrom tensorpack.tfutils.tower import TowerContext\n\n\nclass Attacker:\n def __init__(self, sess):\n self.sess = sess\n self.step_size = FLAGS.step_size / 255.0\n self.max_epsilon = FLAGS.max_epsilon / 255.0\n # Prepare graph\n batch_shape = [FLAGS.batch_size, 299, 299, 3]\n self.x_input = tf.placeholder(tf.float32, shape=batch_shape)\n x_max = tf.clip_by_value(self.x_input + self.max_epsilon, 0., 1.0)\n x_min = tf.clip_by_value(self.x_input - self.max_epsilon, 0., 1.0)\n\n self.y_input = tf.placeholder(tf.int64, shape=batch_shape[0])\n i = tf.constant(0)\n self.x_adv, _, _, _, _ = tf.while_loop(self.stop, self.graph,\n [self.x_input, self.y_input, i, x_max, x_min])\n self.restore()\n\n def graph(self, x, y, i, x_max, x_min):\n with TowerContext(\"model_tower\", is_training=False):\n logits, _, endpoints = network.model(x, FLAGS.attack_networks[0])\n\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)\n noise = tf.gradients(loss, x)[0] if not FLAGS.universal else tf.zeros_like(x)\n with TowerContext('RHP_tower', is_training=False):\n with tf.variable_scope('RHP'):\n noise = conv_with_rn(noise)\n noise = noise / (tf.reduce_mean(tf.abs(noise), [1, 2, 3], keepdims=True) + 1e-12)\n x = x + self.step_size * tf.sign(noise)\n x = tf.clip_by_value(x, x_min, x_max)\n i = tf.add(i, 1)\n return x, y, i, x_max, x_min\n\n @staticmethod\n def stop(x, y, i, x_max, x_min):\n return tf.less(i, FLAGS.num_steps)\n\n def perturb(self, images, labels):\n batch_size = images.shape[0]\n if batch_size < FLAGS.batch_size:\n pad_num = FLAGS.batch_size - batch_size\n pad_img = np.zeros([pad_num, 299, 299, 3])\n images = np.concatenate([images, pad_img])\n pad_label = np.zeros([pad_num])\n labels = np.concatenate([labels, pad_label])\n adv_images = sess.run(self.x_adv, feed_dict={self.x_input: images, self.y_input: labels})\n return adv_images[:batch_size]\n\n def restore(self):\n network.restore(self.sess, FLAGS.attack_networks[0])\n RHP_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='RHP')\n RHP_variables_saver = tf.train.Saver(RHP_variables)\n ckpt_filename = tf.train.latest_checkpoint(FLAGS.RHP_savepath)\n RHP_variables_saver.restore(sess, ckpt_filename)\n\n\nif __name__ == '__main__':\n sess = tf.Session()\n model = Attacker(sess)\n df = PNGDataFlow(FLAGS.img_dir, FLAGS.test_list_filename, FLAGS.ground_truth_file,\n result_dir=None, img_num=FLAGS.img_num)\n df = BatchData(df, FLAGS.batch_size, remainder=True)\n df.reset_state()\n\n total_batch = int((df.ds.img_num - 1) / FLAGS.batch_size) + 1\n for batch_index, (x_batch, y_batch, name_batch) in tqdm(enumerate(df), total=total_batch):\n advs = model.perturb(x_batch, y_batch)\n save_images(advs, name_batch, FLAGS.result_dir)\n" ]
[ [ "tensorflow.clip_by_value", "tensorflow.sign", "tensorflow.constant", "tensorflow.while_loop", "tensorflow.train.latest_checkpoint", "tensorflow.less", "tensorflow.get_collection", "tensorflow.gradients", "tensorflow.placeholder", "numpy.concatenate", "tensorflow.zeros_like", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.add", "tensorflow.Session", "tensorflow.variable_scope", "tensorflow.train.Saver", "numpy.zeros", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
hmedina/KaSaAn
[ "83e4e31ff0e0062762aacfbc65bbdd290808bb51" ]
[ "KaSaAn/functions/snapshot_visualizer_subcomponent.py" ]
[ "#! /usr/bin/env python3\n\nimport ast\nimport squarify\nimport warnings\nimport networkx as nx\nimport matplotlib as mpl\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nfrom networkx.drawing.nx_agraph import graphviz_layout\nfrom typing import List, Tuple\nfrom ..core import KappaSnapshot, KappaComplex, KappaAgent\nfrom .snapshot_visualizer_patchwork import colorize_agents\n\n\ndef render_complexes_as_plain_graph(snapshot_file_name: str, sizes_requested: List[int], highlight_patterns: List[str],\n color_scheme_file_name: str, node_size: int, edge_width: float,\n fig_size: Tuple[float, float], print_distro: bool) -> List[plt.figure]:\n \"\"\"\"Take a KappaSnapshot, get complexes of a given size, render them as plain graphs, optionally highlighting\n certain patterns. See file under `KaSaAn.scripts` for usage.\"\"\"\n snapshot = KappaSnapshot(snapshot_file_name)\n if print_distro:\n print(\"Snapshot's distribution, size:abundance\\n\" + str(snapshot.get_size_distribution()))\n snapshot_agents = snapshot.get_agent_types_present()\n # get list of complexes to visualize, with abundances and sizes for weighting\n compl_list: List[KappaComplex] = []\n abund_list: List[int] = []\n sizes_list: List[int] = []\n if sizes_requested:\n # of requested sizes, get present ones; warn user if some requested not present\n sizes_to_view = list(set(snapshot.get_all_sizes()).intersection(sizes_requested))\n sizes_absent = list(set(sizes_requested).difference(set(snapshot.get_all_sizes())))\n if sizes_absent:\n warnings.warn('Requested size(s) <' + str(sizes_absent) + '> not found in size distribution, skipped.')\n if sizes_to_view:\n sizes_to_view.sort(reverse=True)\n for query_size in sizes_to_view:\n comps, abuns = zip(*snapshot.get_complexes_of_size(query_size))\n compl_list.extend(comps)\n abund_list.extend(abuns)\n sizes_list.extend([query_size] * len(abuns))\n else:\n raise ValueError('Snapshot did not contain any of the requested sizes.')\n else:\n compl_list, abund_list = zip(*snapshot.get_largest_complexes())\n sizes_list = [compl_list[0].get_size_of_complex()] * len(compl_list)\n # read or define color scheme\n # for user-defined coloring schemes, read the dictionary from a file, convert keys to KappaAgent\n if color_scheme_file_name:\n color_scheme = {}\n with open(color_scheme_file_name, 'r') as cs_file:\n coloring_scheme_raw = ast.literal_eval(cs_file.read())\n for key, value in coloring_scheme_raw.items():\n color_scheme[KappaAgent(key)] = value\n else:\n color_scheme = colorize_agents(snapshot_agents)\n # using squarify to define axis locations based on complex sizes\n fig_width = 1\n fig_height = 1\n fig_origin_x = 0\n fig_origin_y = 0\n norm_sizes = squarify.normalize_sizes(sizes_list, fig_width, fig_height)\n axis_rects: List[dict] = squarify.padded_squarify(norm_sizes, fig_origin_x, fig_origin_y, fig_width, fig_height)\n # for each complex, get the networkx graph and define node positions\n compl_graphs = [compl.to_networkx() for compl in compl_list]\n node_positions = [graphviz_layout(compl_graph, prog='sfdp') for compl_graph in compl_graphs]\n plotting_data = list(zip(compl_graphs, abund_list, axis_rects, node_positions))\n # figure list construction\n fig_list: List[plt.figure] = []\n # construct the all-agent figure\n fig_all = plt.figure(figsize=fig_size)\n for comp, abund, rect, npos in plotting_data:\n ax = fig_all.add_axes([rect['x'], rect['y'], rect['dx'], rect['dy']])\n ax.set_title(label='#: ' + str(abund), pad=-2*mpl.rcParams['axes.titlepad'])\n # try to assign color to nodes based on color scheme\n axis_color_list = []\n for node in comp.nodes.data():\n agent_name = node[1]['kappa'].get_agent_name()\n try:\n axis_color_list.append(color_scheme[KappaAgent(agent_name)])\n except KeyError as k_e:\n raise ValueError('Complex contains agent <' + agent_name + '> not found in coloring palette.') from k_e\n nx.draw(comp, pos=npos, ax=ax, node_color=axis_color_list, with_labels=False,\n node_size=node_size, width=edge_width)\n # construct the all-agent legend\n legend_entries = []\n for agent in snapshot_agents:\n patch_label = agent.get_agent_name()\n patch_color = color_scheme[agent] if agent in color_scheme else '#00000000'\n legend_entries.append(mpatches.Patch(label=patch_label, color=patch_color))\n fig_all.legend(handles=legend_entries)\n fig_list.append(fig_all)\n # construct the patter-specific figures\n if highlight_patterns:\n for string_pattern in highlight_patterns:\n kappa_query = KappaAgent(string_pattern)\n fig_patt = plt.figure(figsize=fig_size)\n for comp, abund, rect, npos in plotting_data:\n ax = fig_patt.add_axes([rect['x'], rect['y'], rect['dx'], rect['dy']])\n ax.set_title(label='#: ' + str(abund), pad=-2 * mpl.rcParams['axes.titlepad'])\n # try to assign color to nodes based on color scheme and user-supplied pattern\n axis_color_list = []\n for node in comp.nodes.data():\n node_agent = node[1]['kappa']\n try:\n if kappa_query in node_agent:\n axis_color_list.append(color_scheme[KappaAgent(kappa_query.get_agent_name())])\n else:\n axis_color_list.append('#00000000')\n except KeyError as k_e:\n raise ValueError('Complex contains agent <' + node_agent.get_agent_name() +\n '> not found in supplied palette.') from k_e\n nx.draw(comp, pos=npos, ax=ax, node_color=axis_color_list, with_labels=False,\n node_size=node_size, width=edge_width)\n patch_label = str(kappa_query)\n patch_color = color_scheme[KappaAgent(kappa_query.get_agent_name())]\n legend_entry = mpatches.Patch(label=patch_label, color=patch_color)\n fig_patt.legend(handles=[legend_entry])\n fig_list.append(fig_patt)\n return fig_list\n" ]
[ [ "matplotlib.patches.Patch", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EwoutH/seaborn
[ "630c08d7bd1c2a39362eda2389e8822357057775" ]
[ "doc/sphinxext/gallery_generator.py" ]
[ "\"\"\"\nSphinx plugin to run example scripts and create a gallery page.\n\nLightly modified from the mpld3 project.\n\n\"\"\"\nimport os\nimport os.path as op\nimport re\nimport glob\nimport token\nimport tokenize\nimport shutil\nimport warnings\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt # noqa: E402\n\n\n# Python 3 has no execfile\ndef execfile(filename, globals=None, locals=None):\n with open(filename, \"rb\") as fp:\n exec(compile(fp.read(), filename, 'exec'), globals, locals)\n\n\nRST_TEMPLATE = \"\"\"\n\n.. currentmodule:: seaborn\n\n.. _{sphinx_tag}:\n\n{docstring}\n\n.. image:: {img_file}\n\n**seaborn components used:** {components}\n\n.. raw:: html\n\n <div class=\"col-md-9\">\n\n.. literalinclude:: {fname}\n :lines: {end_line}-\n\n.. raw:: html\n\n </div>\n\n\"\"\"\n\n\nINDEX_TEMPLATE = \"\"\"\n\n.. raw:: html\n\n <style type=\"text/css\">\n .figure {{\n position: relative;\n float: left;\n margin: 10px;\n width: 180px;\n height: 200px;\n }}\n\n .figure img {{\n position: absolute;\n display: inline;\n left: 0;\n width: 170px;\n height: 170px;\n opacity:1.0;\n filter:alpha(opacity=100); /* For IE8 and earlier */\n }}\n\n .figure:hover img {{\n -webkit-filter: blur(3px);\n -moz-filter: blur(3px);\n -o-filter: blur(3px);\n -ms-filter: blur(3px);\n filter: blur(3px);\n opacity:1.0;\n filter:alpha(opacity=100); /* For IE8 and earlier */\n }}\n\n .figure span {{\n position: absolute;\n display: inline;\n left: 0;\n width: 170px;\n height: 170px;\n background: #000;\n color: #fff;\n visibility: hidden;\n opacity: 0;\n z-index: 100;\n }}\n\n .figure p {{\n position: absolute;\n top: 45%;\n width: 170px;\n font-size: 110%;\n }}\n\n .figure:hover span {{\n visibility: visible;\n opacity: .4;\n }}\n\n .caption {{\n position: absolute;\n width: 180px;\n top: 170px;\n text-align: center !important;\n }}\n </style>\n\n.. _{sphinx_tag}:\n\nExample gallery\n===============\n\n{toctree}\n\n{contents}\n\n.. raw:: html\n\n <div style=\"clear: both\"></div>\n\"\"\"\n\n\ndef create_thumbnail(infile, thumbfile,\n width=275, height=275,\n cx=0.5, cy=0.5, border=4):\n baseout, extout = op.splitext(thumbfile)\n\n im = matplotlib.image.imread(infile)\n rows, cols = im.shape[:2]\n x0 = int(cx * cols - .5 * width)\n y0 = int(cy * rows - .5 * height)\n xslice = slice(x0, x0 + width)\n yslice = slice(y0, y0 + height)\n thumb = im[yslice, xslice]\n thumb[:border, :, :3] = thumb[-border:, :, :3] = 0\n thumb[:, :border, :3] = thumb[:, -border:, :3] = 0\n\n dpi = 100\n fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)\n\n ax = fig.add_axes([0, 0, 1, 1], aspect='auto',\n frameon=False, xticks=[], yticks=[])\n if all(thumb.shape):\n ax.imshow(thumb, aspect='auto', resample=True,\n interpolation='bilinear')\n else:\n warnings.warn(\n f\"Bad thumbnail crop. {thumbfile} will be empty.\"\n )\n fig.savefig(thumbfile, dpi=dpi)\n return fig\n\n\ndef indent(s, N=4):\n \"\"\"indent a string\"\"\"\n return s.replace('\\n', '\\n' + N * ' ')\n\n\nclass ExampleGenerator:\n \"\"\"Tools for generating an example page from a file\"\"\"\n def __init__(self, filename, target_dir):\n self.filename = filename\n self.target_dir = target_dir\n self.thumbloc = .5, .5\n self.extract_docstring()\n with open(filename) as fid:\n self.filetext = fid.read()\n\n outfilename = op.join(target_dir, self.rstfilename)\n\n # Only actually run it if the output RST file doesn't\n # exist or it was modified less recently than the example\n file_mtime = op.getmtime(filename)\n if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime:\n self.exec_file()\n else:\n print(f\"skipping {self.filename}\")\n\n @property\n def dirname(self):\n return op.split(self.filename)[0]\n\n @property\n def fname(self):\n return op.split(self.filename)[1]\n\n @property\n def modulename(self):\n return op.splitext(self.fname)[0]\n\n @property\n def pyfilename(self):\n return self.modulename + '.py'\n\n @property\n def rstfilename(self):\n return self.modulename + \".rst\"\n\n @property\n def htmlfilename(self):\n return self.modulename + '.html'\n\n @property\n def pngfilename(self):\n pngfile = self.modulename + '.png'\n return \"_images/\" + pngfile\n\n @property\n def thumbfilename(self):\n pngfile = self.modulename + '_thumb.png'\n return pngfile\n\n @property\n def sphinxtag(self):\n return self.modulename\n\n @property\n def pagetitle(self):\n return self.docstring.strip().split('\\n')[0].strip()\n\n @property\n def plotfunc(self):\n match = re.search(r\"sns\\.(.+plot)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+map)\\(\", self.filetext)\n if match:\n return match.group(1)\n match = re.search(r\"sns\\.(.+Grid)\\(\", self.filetext)\n if match:\n return match.group(1)\n return \"\"\n\n @property\n def components(self):\n\n objects = re.findall(r\"sns\\.(\\w+)\\(\", self.filetext)\n\n refs = []\n for obj in objects:\n if obj[0].isupper():\n refs.append(f\":class:`{obj}`\")\n else:\n refs.append(f\":func:`{obj}`\")\n return \", \".join(refs)\n\n def extract_docstring(self):\n \"\"\" Extract a module-level docstring\n \"\"\"\n lines = open(self.filename).readlines()\n start_row = 0\n if lines[0].startswith('#!'):\n lines.pop(0)\n start_row = 1\n\n docstring = ''\n first_par = ''\n line_iter = lines.__iter__()\n tokens = tokenize.generate_tokens(lambda: next(line_iter))\n for tok_type, tok_content, _, (erow, _), _ in tokens:\n tok_type = token.tok_name[tok_type]\n if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):\n continue\n elif tok_type == 'STRING':\n docstring = eval(tok_content)\n # If the docstring is formatted with several paragraphs,\n # extract the first one:\n paragraphs = '\\n'.join(line.rstrip()\n for line in docstring.split('\\n')\n ).split('\\n\\n')\n if len(paragraphs) > 0:\n first_par = paragraphs[0]\n break\n\n thumbloc = None\n for i, line in enumerate(docstring.split(\"\\n\")):\n m = re.match(r\"^_thumb: (\\.\\d+),\\s*(\\.\\d+)\", line)\n if m:\n thumbloc = float(m.group(1)), float(m.group(2))\n break\n if thumbloc is not None:\n self.thumbloc = thumbloc\n docstring = \"\\n\".join([l for l in docstring.split(\"\\n\")\n if not l.startswith(\"_thumb\")])\n\n self.docstring = docstring\n self.short_desc = first_par\n self.end_line = erow + 1 + start_row\n\n def exec_file(self):\n print(f\"running {self.filename}\")\n\n plt.close('all')\n my_globals = {'pl': plt,\n 'plt': plt}\n execfile(self.filename, my_globals)\n\n fig = plt.gcf()\n fig.canvas.draw()\n pngfile = op.join(self.target_dir, self.pngfilename)\n thumbfile = op.join(\"example_thumbs\", self.thumbfilename)\n self.html = f\"<img src=../{self.pngfilename}>\"\n fig.savefig(pngfile, dpi=75, bbox_inches=\"tight\")\n\n cx, cy = self.thumbloc\n create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy)\n\n def toctree_entry(self):\n return f\" ./{op.splitext(self.htmlfilename)[0]}\\n\\n\"\n\n def contents_entry(self):\n return (\".. raw:: html\\n\\n\"\n \" <div class='figure align-center'>\\n\"\n \" <a href=./{}>\\n\"\n \" <img src=../_static/{}>\\n\"\n \" <span class='figure-label'>\\n\"\n \" <p>{}</p>\\n\"\n \" </span>\\n\"\n \" </a>\\n\"\n \" </div>\\n\\n\"\n \"\\n\\n\"\n \"\".format(self.htmlfilename,\n self.thumbfilename,\n self.plotfunc))\n\n\ndef main(app):\n static_dir = op.join(app.builder.srcdir, '_static')\n target_dir = op.join(app.builder.srcdir, 'examples')\n image_dir = op.join(app.builder.srcdir, 'examples/_images')\n thumb_dir = op.join(app.builder.srcdir, \"example_thumbs\")\n source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples'))\n if not op.exists(static_dir):\n os.makedirs(static_dir)\n\n if not op.exists(target_dir):\n os.makedirs(target_dir)\n\n if not op.exists(image_dir):\n os.makedirs(image_dir)\n\n if not op.exists(thumb_dir):\n os.makedirs(thumb_dir)\n\n if not op.exists(source_dir):\n os.makedirs(source_dir)\n\n banner_data = []\n\n toctree = (\"\\n\\n\"\n \".. toctree::\\n\"\n \" :hidden:\\n\\n\")\n contents = \"\\n\\n\"\n\n # Write individual example files\n for filename in sorted(glob.glob(op.join(source_dir, \"*.py\"))):\n\n ex = ExampleGenerator(filename, target_dir)\n\n banner_data.append({\"title\": ex.pagetitle,\n \"url\": op.join('examples', ex.htmlfilename),\n \"thumb\": op.join(ex.thumbfilename)})\n shutil.copyfile(filename, op.join(target_dir, ex.pyfilename))\n output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag,\n docstring=ex.docstring,\n end_line=ex.end_line,\n components=ex.components,\n fname=ex.pyfilename,\n img_file=ex.pngfilename)\n with open(op.join(target_dir, ex.rstfilename), 'w') as f:\n f.write(output)\n\n toctree += ex.toctree_entry()\n contents += ex.contents_entry()\n\n if len(banner_data) < 10:\n banner_data = (4 * banner_data)[:10]\n\n # write index file\n index_file = op.join(target_dir, 'index.rst')\n with open(index_file, 'w') as index:\n index.write(INDEX_TEMPLATE.format(sphinx_tag=\"example_gallery\",\n toctree=toctree,\n contents=contents))\n\n\ndef setup(app):\n app.connect('builder-inited', main)\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.gcf", "matplotlib.image.imread", "matplotlib.pyplot.close", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
VITA-Group/VGAI
[ "c36746383da42b011dddf182303f8c2618d5ca42" ]
[ "train_loc.py" ]
[ "import os\nimport sys\nimport time\nimport glob\nimport numpy as np\nimport torch\nimport logging\nimport argparse\nimport torch.nn as nn\nimport torch.utils\nimport torch.backends.cudnn as cudnn\n\nimport joint_network as models\nfrom dataset_loc import OneHopDataset\nfrom torch.utils.data import Dataset, DataLoader\nimport shutil\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith('__')\n and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(\"training\")\nparser.add_argument('arch', metavar='ARCH', default='vis_dagnn',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: vis_dagnn)')\nparser.add_argument('--data', type=str, default='../data', help='location of the data corpus')\nparser.add_argument('--batch-size', type=int, default=1, help='batch size')\nparser.add_argument('--learning_rate', type=float, default=0.0005, help='init learning rate')\nparser.add_argument('--momentum', type=float, default=0.9, help='momentum')\nparser.add_argument('--weight_decay', type=float, default=0, help='weight decay')\nparser.add_argument('--report_freq', type=float, default=50, help='report frequency')\nparser.add_argument('--gpu', type=int, default=0, help='gpu device id')\nparser.add_argument('--epochs', type=int, default=5, help='num of training epochs')\nparser.add_argument('--model_path', type=str, default='saved_models', help='path to save the model')\nparser.add_argument('--drop_path_prob', type=float, default=0.2, help='drop path probability')\nparser.add_argument('--seed', type=int, default=0, help='random seed')\nparser.add_argument('--decreasing_lr', default='5,10,15', help='decreasing strategy')\nparser.add_argument('--K', type=int, default=3, help='filter length')\nparser.add_argument('--vinit', type=float, default=3.0, help='maximum intial velocity')\nparser.add_argument('--radius', type=float, default=1.5, help='communication radius')\nparser.add_argument('--F', type=int, default=24, help='number of feature dimension')\nparser.add_argument('--comm-model', default='disk', choices=['disk', 'knn'], help='communication model')\nparser.add_argument('--K-neighbor', type=int, default=10, help='number of KNN neighbors')\nparser.add_argument('--mode', type=str, default='optimal', choices=['optimal', 'local', 'loc_dagnn', 'vis_dagnn', 'vis_grnn', 'loc_grnn'])\n\n\n\nargs = parser.parse_args()\n\n\ndef main():\n if not torch.cuda.is_available():\n logging.info('no gpu device available')\n sys.exit(1)\n np.random.seed(args.seed)\n torch.cuda.set_device(args.gpu)\n cudnn.benchmark = True\n torch.manual_seed(args.seed)\n cudnn.enabled=True\n torch.cuda.manual_seed(args.seed)\n logging.info('gpu device = %d' % args.gpu)\n logging.info(\"args = %s\", args)\n\n model = models.__dict__[args.arch](n_vis_out=args.F, K=args.K)\n model = model.cuda()\n\n\n train_criterion = torch.nn.SmoothL1Loss()\n criterion = torch.nn.SmoothL1Loss() #torch.nn.MSELoss(reduction='mean')\n train_criterion = train_criterion.cuda()\n criterion = criterion.cuda()\n\n\n train_criterion = train_criterion.cuda()\n criterion = criterion.cuda()\n decreasing_lr = list(map(int, args.decreasing_lr.split(',')))\n\n \n \n optimizer = torch.optim.Adam(\n model.parameters(),\n lr=args.learning_rate,\n weight_decay=args.weight_decay\n )\n \n if args.comm_model == 'disk':\n f_name = '{}_K_{}_n_vis_{}_R_{}_vinit_{}_comm_model_{}.pkl'.format(args.mode, args.K, args.F, args.radius, args.vinit, args.comm_model)\n else:\n f_name = '{}_K_{}_n_vis_{}_vinit_{}_comm_model_{}_K_neighbor_{}.pkl'.format(args.mode, args.K, args.F, args.vinit, args.comm_model, args.K_neighbor)\n\n\n drone_dataset = OneHopDataset(f_name=f_name, K=args.K, R=args.radius)\n num_train = len(drone_dataset)\n indices = list(range(num_train))\n split = int(np.floor(0.9 * num_train))\n\n train_queue = torch.utils.data.DataLoader(drone_dataset,batch_size=args.batch_size, num_workers=1, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]), pin_memory=True)\n \n valid_queue = torch.utils.data.DataLoader(drone_dataset,batch_size=1, num_workers=2, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:num_train]), pin_memory=True)\n \n print('Training Joint Network')\n #scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=decreasing_lr, gamma=0.1)\n for epoch in range(args.epochs):\n #scheduler.step()\n #logging.info('epoch %d lr %e', epoch, scheduler.get_lr()[0])\n train_loss = train_joint(train_queue, model, train_criterion, optimizer)\n valid_loss = infer_joint(valid_queue, model, criterion)\n #checkpoint_path = 'checkpoint_all_{}_{}_K_{}_n_vis_{}_R_{}_vinit_{}_comm_model_{}.tar'.format(args.mode, args.arch, args.K, args.F, args.radius, args.vinit, args.comm_model)\n #checkpoint_path = 'checkpoint_all_vis_{}_{}_latest.tar'.format(args.F, args.arch)\n if args.comm_model == 'disk':\n checkpoint_path = 'checkpoint_all_{}_{}_K_{}_n_vis_{}_R_{}_vinit_{}_comm_model_{}.tar'.format(args.mode, args.arch, args.K, args.F, args.radius, args.vinit, args.comm_model)\n else:\n checkpoint_path = 'checkpoint_all_{}_{}_K_{}_n_vis_{}_vinit_{}_comm_model_{}_K_neighbor_{}.tar'.format(args.mode, args.arch, args.K, args.F, args.vinit, args.comm_model, args.K_neighbor)\n\n if True: \n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'loss': valid_loss,\n }, filename=checkpoint_path)\n best_valid_loss = valid_loss\n print('epoch ' + str(epoch) + ' train loss ' + str(train_loss) + ' valid loss ' + str(valid_loss))\n\ndef train_joint(train_queue, model, criterion, optimizer):\n\n objs = AvgrageMeter()\n model.train()\n print('len of train queue = {}'.format(len(train_queue)))\n total_loss = 0\n for step, sample_batched in enumerate(train_queue, 0):\n #x_img = sample_batched['x_img'].float().cuda().squeeze(0)\n x_agg = sample_batched['x_agg'].float().cuda().squeeze(0)\n a_nets = sample_batched['anets'].float().cuda().squeeze(0)\n actions = sample_batched['actions'].float().cuda().squeeze(0)\n if args.arch == 'vis_grnn':\n input_state = torch.from_numpy(np.zeros((x_img.shape[0], args.F))).float().cuda()\n pred_agg, pred = model(x_img, a_nets, input_state)\n elif args.arch == 'loc_dagnn':\n pred = model(x_agg, a_nets)\n elif args.arch == 'loc_grnn':\n input_state = torch.from_numpy(np.zeros((x_agg.shape[0], 6))).float().cuda()\n pred_agg, pred = model(x_agg, a_nets, input_state)\n\n else:\n pred_agg, pred = model(x_img, a_nets)\n loss = criterion(pred, actions)\n #print('loss = {}'.format(loss))\n total_loss += loss\n if step % 1 == 0:\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n total_loss = 0\n\n\n n = pred.size(0) \n objs.update(loss.item(), n)\n if step % args.report_freq == 0:\n print('-----')\n print('train step ' + str(step) + ' loss ' + str(objs.avg))\n #print('pred = {}'.format(pred))\n #print('actions = {}'.format(actions))\n print('-----')\n \n return objs.avg\n\n\n\ndef infer_joint(valid_queue, model, criterion):\n objs = AvgrageMeter()\n model.eval()\n\n for step, sample_batched in enumerate(valid_queue, 0):\n #x_img = sample_batched['x_img'].float().cuda().squeeze(0)\n x_agg = sample_batched['x_agg'].float().cuda().squeeze(0)\n a_nets = sample_batched['anets'].float().cuda().squeeze(0)\n actions = sample_batched['actions'].float().cuda().squeeze(0)\n if args.arch == 'vis_grnn':\n input_state = torch.from_numpy(np.zeros((x_img.shape[0], args.F))).float().cuda()\n _, pred = model(x_img, a_nets, input_state)\n elif args.arch == 'loc_dagnn':\n pred = model(x_agg, a_nets)\n elif args.arch == 'loc_grnn':\n input_state = torch.from_numpy(np.zeros((x_agg.shape[0], 6))).float().cuda()\n pred_agg, pred = model(x_agg, a_nets, input_state)\n else:\n _, pred = model(x_img, a_nets)\n loss = criterion(pred, actions)\n\n\n \n n = pred.size(0) \n objs.update(loss.item(), n)\n if step % args.report_freq == 0:\n print('-----')\n print('valid step ' + str(step) + ' loss ' + str(objs.avg))\n print('-----')\n\n return objs.avg\n\n\n\nclass AvgrageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.avg = 0\n self.sum = 0\n self.cnt = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n\n\ndef accuracy(output, target, topk=(1,)):\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0/batch_size))\n return res\n\n\ndef save_checkpoint(state, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n\n\nif __name__ == '__main__':\n main() \n\n" ]
[ [ "torch.nn.SmoothL1Loss", "torch.cuda.set_device", "torch.cuda.manual_seed", "numpy.random.seed", "torch.manual_seed", "torch.utils.data.sampler.SubsetRandomSampler", "torch.cuda.is_available", "numpy.floor", "numpy.zeros", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RoderickLi/python-snippet
[ "7cc672c455a768864cf38d6bbebdf8337b9c510c" ]
[ "data-mining/model2http-api.py" ]
[ "import tensorflow as tf\ndef save_model_to_serving(model, export_version, export_path='model/'):\n print(model.input, model.output)\n signature = tf.saved_model.signature_def_utils.predict_signature_def( \n inputs={'img_input': model.input[0], # mutil input support\n 'extra_input': model.input[1], \n }, \n \n outputs={'outputs': model.output}\n )\n export_path = os.path.join(\n tf.compat.as_bytes(export_path),\n tf.compat.as_bytes(str(export_version)))\n builder = tf.saved_model.builder.SavedModelBuilder(export_path)\n legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n builder.add_meta_graph_and_variables(\n sess=K.get_session(), \n tags=[tf.saved_model.tag_constants.SERVING], \n signature_def_map={ \n 'serving_default': signature, \n },\n legacy_init_op=legacy_init_op)\n builder.save()\nsave_model_to_serving(good_naive, \"1\", './save_to_serving') # save to different directory according to the second params indicating version\n\nimport requests\nimport json\npayload = {\n \"instances\": [\n {\n \"img_input\": img_input_1.tolist(), #x_val[0][0].tolist(),\n \"extra_input\": extra_input_1.tolist(), # x_val[1][0].tolist(),\n }\n ]\n}\nurl = 'http://example.com/predict'\nr = requests.post(url, json=payload)\npred = json.loads(r.content.decode('utf-8'))\npred\n" ]
[ [ "tensorflow.compat.as_bytes", "tensorflow.saved_model.builder.SavedModelBuilder", "tensorflow.tables_initializer", "tensorflow.saved_model.signature_def_utils.predict_signature_def" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
SHTUPLUS/ContextLab
[ "4e12f0af9d0640f29c763b915f02de763b577200" ]
[ "contextlab/utils/layer_misc.py" ]
[ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\n__all__ = ['ConvBNReLU']\n\n\nclass ConvBNReLU(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n norm_layer=nn.BatchNorm2d,\n with_relu=True,\n stride=1,\n padding=0,\n dilation=1,\n groups=1,\n bias=True,\n padding_mode='zeros'):\n super(ConvBNReLU, self).__init__()\n self.conv = nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n padding_mode=padding_mode)\n self.bn = norm_layer(out_channels)\n self.with_relu = with_relu\n if with_relu:\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n if self.with_relu:\n x = self.relu(x)\n return x\n\n\nclass GraphAdjNetwork(nn.Module):\n def __init__(self,\n pair_function,\n in_channels,\n channel_stride):\n super(GraphAdjNetwork, self).__init__()\n self.pair_function = pair_function\n\n if pair_function == 'embedded_gaussian':\n inter_channel = in_channels // channel_stride\n self.phi = ConvBNReLU(\n in_channels=in_channels,\n out_channels=inter_channel,\n kernel_size=1,\n bias=False,\n norm_layer=nn.BatchNorm2d\n )\n self.theta = ConvBNReLU(\n in_channels=in_channels,\n out_channels=inter_channel,\n kernel_size=1,\n bias=False,\n norm_layer=nn.BatchNorm2d\n )\n elif pair_function == 'gaussian':\n pass\n elif pair_function == 'diff_learnable':\n self.learnable_adj_conv = ConvBNReLU(\n in_channels=in_channels,\n out_channels=1,\n kernel_size=1,\n bias=False,\n norm_layer=nn.BatchNorm2d\n )\n elif pair_function == 'sum_learnable':\n self.learnable_adj_conv = ConvBNReLU(\n in_channels=in_channels,\n out_channels=1,\n kernel_size=1,\n bias=False,\n norm_layer=nn.BatchNorm2d\n )\n elif pair_function == 'cat_learnable':\n self.learnable_adj_conv = ConvBNReLU(\n in_channels=in_channels*2,\n out_channels=1,\n kernel_size=1,\n bias=False,\n norm_layer=nn.BatchNorm2d\n )\n else:\n raise NotImplementedError\n\n def forward(self, x):\n \"\"\"\n Args:\n x (Tensor):\n (B, N, C)\n \"\"\"\n if self.pair_function == 'gaussian':\n adj = self.gaussian(x, x.permute(0, 2, 1))\n elif self.pair_function == 'embedded_gaussian':\n x = x.permute(0, 2, 1).unsqueeze(-1)\n x_1 = self.phi(x) # B, C, N, 1\n x_2 = self.theta(x) # B, C, N, 1\n adj = self.gaussian(\n x_1.squeeze(-1).permute(0, 2, 1), x_2.squeeze(-1))\n elif self.pair_function == 'diff_learnable':\n adj = self.diff_learnable_adj(x.unsqueeze(2), x.unsqueeze(1))\n elif self.pair_function == 'sum_learnable':\n adj = self.sum_learnable_adj(x.unsqueeze(2), x.unsqueeze(1))\n elif self.pair_function == 'cat_learnable':\n adj = self.cat_learnable_adj(x.unsqueeze(2), x.unsqueeze(1))\n else:\n raise NotImplementedError(self.pair_function)\n\n return adj\n\n def gaussian(self, x_1, x_2):\n \"\"\"\n Args:\n x_1:\n x_2:\n Return:\n adj: normalized in the last dimenstion\n \"\"\"\n # (B, N, C) X (B, C, N) --> (B, N, N)\n adj = torch.bmm(x_1, x_2) # B, N, N\n adj = F.softmax(adj, dim=-1) # B, N, N\n return adj\n\n def diff_learnable_adj(self, x_1, x_2):\n \"\"\"\n Learnable attention from the difference of the feature \n\n Return:\n adj: normalzied at the last dimension\n \"\"\"\n # x1:(B,N,1,C)\n # x2:(B,1,N,C)\n feature_diff = x_1 - x_2 # (B, N, N, C)\n feature_diff = feature_diff.permute(0, 3, 1, 2) # (B, C, N, N)\n adj = self.learnable_adj_conv(feature_diff) # (B, 1, N, N)\n adj = adj.squeeze(1) # (B, N, N)\n # Use the number of nodes as the normalization factor\n adj = adj / adj.size(-1) # (B, N, N)\n\n return adj\n\n def sum_learnable_adj(self, x_1, x_2):\n \"\"\"\n Learnable attention from the difference of the feature \n\n Return:\n adj: normalzied at the last dimension\n \"\"\"\n # x1:(B,N,1,C)\n # x2:(B,1,N,C)\n feature_diff = x_1 + x_2 # (B, N, N, C)\n feature_diff = feature_diff.permute(0, 3, 1, 2) # (B, C, N, N)\n adj = self.learnable_adj_conv(feature_diff) # (B, 1, N, N)\n adj = adj.squeeze(1) # (B, N, N)\n # Use the number of nodes as the normalization factor\n adj = adj / adj.size(-1) # (B, N, N)\n\n return adj\n\n def cat_learnable_adj(self, x_1, x_2):\n \"\"\"\n Learable attention from the concatnation of the features\n \"\"\"\n x_1 = x_1.repeat(1, 1, x_1.size(1), 1) # B, N, N, C\n x_2 = x_2.repeat(1, x_2.size(2), 1, 1) # B, N, N, C\n feature_cat = torch.cat([x_1, x_2], dim=-1) # B, N, N, 2C\n # import pdb; pdb.set_trace()\n feature_cat = feature_cat.permute(0, 3, 1, 2) # B, 2C, N, N\n adj = self.learnable_adj_conv(feature_cat) # B, 1, N, N\n adj = adj.squeeze(1) # (B, N, N)\n # Use the number of nodes as the normalization factor\n adj = adj / adj.size(-1) # (B, N, N)\n\n return adj\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.nn.Conv2d", "torch.bmm", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
herobd/GAN_aug
[ "b240da32d4f3ae9a00a9d395ac8f29728623f6b4" ]
[ "models/base_model.py" ]
[ "import os\nimport torch\nfrom collections import OrderedDict\nfrom abc import ABC, abstractmethod\nfrom . import networks\n\n\nclass BaseModel(ABC):\n \"\"\"This class is an abstract base class (ABC) for models.\n To create a subclass, you need to implement the following five functions:\n -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).\n -- <set_input>: unpack data from dataset and apply preprocessing.\n -- <forward>: produce intermediate results.\n -- <optimize_parameters>: calculate losses, gradients, and update network weights.\n -- <modify_commandline_options>: (optionally) add model-specific options and set default options.\n \"\"\"\n\n def __init__(self, opt):\n \"\"\"Initialize the BaseModel class.\n\n Parameters:\n opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n\n When creating your custom class, you need to implement your own initialization.\n In this fucntion, you should first call <BaseModel.__init__(self, opt)>\n Then, you need to define four lists:\n -- self.loss_names (str list): specify the training losses that you want to plot and save.\n -- self.model_names (str list): specify the images that you want to display and save.\n -- self.visual_names (str list): define networks used in our training.\n -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.\n \"\"\"\n self.opt = opt\n self.gpu_ids = opt.gpu_ids\n self.isTrain = opt.isTrain\n self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU\n self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir\n if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.\n torch.backends.cudnn.benchmark = True\n self.loss_names = []\n self.model_names = []\n self.visual_names = []\n self.optimizers = []\n self.image_paths = []\n self.metric = 0 # used for learning rate policy 'plateau'\n\n @staticmethod\n def modify_commandline_options(parser, is_train):\n \"\"\"Add new model-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n \"\"\"\n return parser\n\n @abstractmethod\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n Parameters:\n input (dict): includes the data itself and its metadata information.\n \"\"\"\n pass\n\n @abstractmethod\n def forward(self):\n \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n pass\n\n @abstractmethod\n def optimize_parameters(self):\n \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n pass\n\n def setup(self, opt):\n \"\"\"Load and print networks; create schedulers\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n if self.isTrain:\n self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]\n if not self.isTrain or opt.continue_train:\n load_suffix = 'iter_%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch\n aux = self.load_networks(load_suffix)\n else:\n aux = None\n self.print_networks(opt.verbose)\n return aux\n\n def eval(self):\n \"\"\"Make models eval mode during test time\"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n net.eval()\n\n def test(self):\n \"\"\"Forward function used in test time.\n\n This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop\n It also calls <compute_visuals> to produce additional visualization results\n \"\"\"\n with torch.no_grad():\n self.forward()\n self.compute_visuals()\n\n def compute_visuals(self):\n \"\"\"Calculate additional output images for visdom and HTML visualization\"\"\"\n pass\n\n def get_image_paths(self):\n \"\"\" Return image paths that are used to load current data\"\"\"\n return self.image_paths\n\n def update_learning_rate(self):\n \"\"\"Update learning rates for all the networks; called at the end of every epoch\"\"\"\n for scheduler in self.schedulers:\n if self.opt.lr_policy == 'plateau':\n scheduler.step(self.metric)\n else:\n scheduler.step()\n\n lr = self.optimizers[0].param_groups[0]['lr']\n print('learning rate = %.7f' % lr)\n\n def get_current_visuals(self):\n \"\"\"Return visualization images. train.py will display these images with visdom, and save the images to a HTML\"\"\"\n visual_ret = OrderedDict()\n for name in self.visual_names:\n if isinstance(name, str):\n visual_ret[name] = getattr(self, name)\n return visual_ret\n\n def get_current_losses(self):\n \"\"\"Return traning losses / errors. train.py will print out these errors on console, and save them to a file\"\"\"\n errors_ret = OrderedDict()\n for name in self.loss_names:\n if isinstance(name, str):\n errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number\n return errors_ret\n\n def save_networks(self, epoch, aux):\n \"\"\"Save all the networks to the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n save_filename = '%s_net_%s.pth' % (epoch, name)\n save_path = os.path.join(self.save_dir, save_filename)\n net = getattr(self, 'net' + name)\n\n if len(self.gpu_ids) > 0 and torch.cuda.is_available():\n torch.save(net.module.cpu().state_dict(), save_path)\n net.cuda(self.gpu_ids[0])\n else:\n torch.save(net.cpu().state_dict(), save_path)\n save_filename = '%s_aux.pth' % (epoch)\n save_path = os.path.join(self.save_dir, save_filename)\n torch.save(aux,save_path)\n\n def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):\n \"\"\"Fix InstanceNorm checkpoints incompatibility (prior to 0.4)\"\"\"\n key = keys[i]\n if i + 1 == len(keys): # at the end, pointing to a parameter/buffer\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'running_mean' or key == 'running_var'):\n if getattr(module, key) is None:\n state_dict.pop('.'.join(keys))\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'num_batches_tracked'):\n state_dict.pop('.'.join(keys))\n else:\n self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)\n\n def load_networks(self, epoch):\n \"\"\"Load all the networks from the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n load_filename = '%s_net_%s.pth' % (epoch, name)\n load_path = os.path.join(self.save_dir, load_filename)\n net = getattr(self, 'net' + name)\n if isinstance(net, torch.nn.DataParallel):\n net = net.module\n print('loading the model from %s' % load_path)\n # if you are using PyTorch newer than 0.4 (e.g., built from\n # GitHub source), you can remove str() on self.device\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n\n # patch InstanceNorm checkpoints prior to 0.4\n for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop\n self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))\n net.load_state_dict(state_dict)\n load_filename = '%s_aux.pth' % (epoch)\n load_path = os.path.join(self.save_dir, load_filename)\n if os.path.exists(load_path):\n return torch.load(load_path)\n else:\n return None\n\n def print_networks(self, verbose):\n \"\"\"Print the total number of parameters in the network and (if verbose) network architecture\n\n Parameters:\n verbose (bool) -- if verbose: print the network architecture\n \"\"\"\n print('---------- Networks initialized -------------')\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n if verbose:\n print(net)\n print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))\n print('-----------------------------------------------')\n\n def set_requires_grad(self, nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of networks\n requires_grad (bool) -- whether the networks require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n\n def get_optimizer_states(self):\n return [o.state_dict() for o in self.optimizers]\n def set_optimizer_states(self,states):\n for i,s in enumerate(states):\n self.optimizers[i].load_state_dict(s)\n def get_scheduler_states(self):\n return [o.state_dict() for o in self.schedulers]\n def set_scheduler_states(self,states):\n for i,s in enumerate(states):\n self.schedulers[i].load_state_dict(s)\n" ]
[ [ "torch.load", "torch.no_grad", "torch.cuda.is_available", "torch.device", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jdekarske/axopy
[ "a60abb44a12c5e833b9033170825773bb0691394", "a60abb44a12c5e833b9033170825773bb0691394", "a60abb44a12c5e833b9033170825773bb0691394" ]
[ "axopy/pipeline/sources.py", "tests/test_gui.py", "examples/devices.py" ]
[ "\"\"\"Data streams for processing with a pipeline.\"\"\"\n\nimport warnings\nimport numpy as np\n\n\ndef segment(data, length, overlap=0):\n \"\"\"Generate segments of an array.\n\n Each segment is of a specified length and optional overlap with the\n previous segment. Only segments of the specified length are retrieved (if\n segments don't fit evenly into the data).\n\n Parameters\n ----------\n data : array, shape (n_channels, n_samples)\n Data to segment.\n length : int\n Number of samples to retrieve in each chunk.\n overlap : int, optional\n Number of overlapping samples in consecutive chunks.\n\n Yields\n ------\n segment : array (n_channels, length)\n Segment of the input array.\n\n Examples\n --------\n Segment a 2-channel recording:\n\n >>> import numpy as np\n >>> from axopy.pipeline import segment\n >>> x = np.arange(8).reshape(2, 4)\n >>> x\n array([[0, 1, 2, 3],\n [4, 5, 6, 7]])\n >>> seg = segment(x, 2)\n >>> next(seg)\n array([[0, 1],\n [4, 5]])\n >>> next(seg)\n array([[2, 3],\n [6, 7]])\n\n Consecutive segments with overlapping samples agree:\n\n >>> seg = segment(x, 3, overlap=2)\n >>> next(seg)\n array([[0, 1, 2],\n [4, 5, 6]])\n >>> next(seg)\n array([[1, 2, 3],\n [5, 6, 7]])\n \"\"\"\n data = np.atleast_2d(data)\n n = data.shape[1]\n for f, t in segment_indices(n, length, overlap=overlap):\n yield data[:, f:t]\n\n\ndef segment_indices(n, length, overlap=0):\n \"\"\"Generate indices to segment an array.\n\n Each segment is of a specified length with optional overlap with the\n previous segment. Only segments of the specified length are retrieved if\n they don't fit evenly into the the total length. The indices returned are\n meant to be used for slicing, e.g. ``data[:, from:to]``.\n\n Parameters\n ----------\n n : int\n Number of samples to segment up.\n length : int\n Length of each segment.\n overlap : int, optional\n Number of overlapping samples in consecutive segments.\n\n Yields\n ------\n from : int\n Index of the beginning of the segment with respect to the input array.\n to : int\n Index of the end of the segement with respect to the input array.\n\n Examples\n --------\n Basic usage -- segment a 6-sample recording into segments of length 2:\n\n >>> import numpy as np\n >>> from axopy.pipeline import segment_indices\n >>> list(segment_indices(6, 2))\n [(0, 2), (2, 4), (4, 6)]\n\n Overlapping segments:\n\n >>> list(segment_indices(11, 5, overlap=2))\n [(0, 5), (3, 8), (6, 11)]\n \"\"\"\n skip = length - overlap\n\n if (n - length) % skip != 0:\n warnings.warn(\"Data (length {}) cannot be chunked evenly into \"\n \"segments of length {} with overlap {}\".format(\n n, length, overlap),\n UserWarning)\n\n for i in range(0, n, skip):\n if i + length <= n:\n yield i, i + length\n", "import pytest\nimport os\nfrom PyQt5 import QtCore, QtWidgets\nimport numpy as np\nfrom axopy import util\nfrom axopy.gui.main import _MainWindow, Container, _SessionConfig\nfrom axopy.gui.graph import SignalWidget\nfrom axopy.gui.canvas import Canvas, Circle, Cross, Line, Text, Rectangle\n\n\ndef exercise_item(item):\n \"\"\"Put a canvas item through the motions.\"\"\"\n assert hasattr(item, 'qitem')\n\n item.x = 0.5\n item.y = -0.5\n assert item.pos == (0.5, -0.5)\n\n item.pos = 1, 1\n assert item.x == 1\n assert item.y == 1\n\n item.visible = False\n item.opacity = 0.4\n\n item.hide()\n assert not item.visible\n\n item.show()\n assert item.visible\n\n\ndef test_main_window(qtbot):\n win = _MainWindow()\n\n # create and set container manually\n c2 = Container()\n win.set_container(c2)\n assert win._layout.currentWidget() == c2\n\n # implicitly create and set container\n c = win.new_container()\n assert win._layout.currentWidget() == c\n\n win.set_status(\"status message\")\n\n def on_key_press(key):\n assert key == util.key_a\n\n win.key_pressed.connect(on_key_press)\n\n qtbot.keyClicks(c, 'a')\n\n\ndef test_container_widget():\n c = Container()\n c.set_widget(QtWidgets.QWidget())\n\n\ndef test_container_layout():\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(QtWidgets.QPushButton())\n layout.addWidget(Canvas())\n\n c = Container()\n c.set_layout(layout)\n\n\ndef test_session_info_bad_type():\n with pytest.raises(TypeError):\n _SessionConfig({'obj': object})\n\n\ndef test_session_info_no_subject(qtbot, mocker):\n mocker.patch.object(QtWidgets.QMessageBox, 'warning',\n return_value=QtWidgets.QMessageBox.Ok)\n\n w = _SessionConfig({'subject': str})\n qtbot.add_widget(w)\n\n with qtbot.assertNotEmitted(w.finished):\n qtbot.keyPress(w, QtCore.Qt.Key_Return)\n\n\ndef test_session_info_types(qtbot):\n w = _SessionConfig({\n 'subject': str,\n 'group': ('a', 'b'),\n 'age': int,\n 'height': float,\n })\n qtbot.add_widget(w)\n\n qtbot.keyClicks(w.widgets['subject'], 'p0')\n qtbot.keyClicks(w.widgets['age'], '99')\n qtbot.keyClicks(w.widgets['height'], '46.2')\n qtbot.keyPress(w, QtCore.Qt.Key_Return)\n\n expected = {'subject': 'p0', 'group': 'a', 'age': 99, 'height': 46.2}\n assert w.results == expected\n\n\ndef test_container():\n c = Container()\n c.set_widget(QtWidgets.QWidget())\n\n\ndef test_signal_widget():\n w = SignalWidget()\n\n w.plot(np.random.randn(4, 100))\n assert w.n_channels == 4\n\n # adjusts to plotting data with different shape\n w.plot(np.random.randn(10, 1000))\n assert w.n_channels == 10\n\n\ndef test_canvas():\n c = Canvas()\n c.add_item(Circle(0.1))\n c.add_item(Circle(0.1).qitem)\n\n\[email protected]('cls,args,kwargs', [\n (Circle, [0.05], dict()),\n (Cross, [], dict(size=0.08, linewidth=0.02)),\n (Line, [0, 0, 1, 1], dict()),\n (Text, ['hello'], dict()),\n (Rectangle, [0.5, 0.5], dict(x=0.5, y=0.5)),\n])\ndef test_items(cls, args, kwargs):\n item = cls(*args, **kwargs)\n exercise_item(item)\n\n\ndef test_rectangle():\n it = Rectangle(0.1, 0.1)\n assert it.width == 0.1\n", "\"\"\"\nBuilt-In Devices\n================\n\nThis example demonstrates some input devices built into AxoPy for testing. Pass\nthe following options to try out different devices:\n\nrainbow\n Basic use of an NoiseGenerator to show lots of colorful random data.\nkeyboard\n Basic use of a Keyboard to show roughly-timed keyboard inputs.\nkeystick\n Neat use of a filter to get joystick-like inputs from a keyboard.\nemgsim\n A silly EMG simulator that uses smoothed 'wasd' key presses to modulate the\n amplitude of Gaussian noise -- they kinda look like EMG signals!\nmouse\n Basic use of a Mouse for velocity input.\n\"\"\"\n\nimport sys\nimport argparse\nimport numpy as np\nfrom axopy.task import Oscilloscope\nfrom axopy.experiment import Experiment\nfrom axopy.daq import NoiseGenerator, Keyboard, Mouse\nfrom axopy.pipeline import Pipeline, Callable, Windower, Filter\n\n\ndef rainbow():\n dev = NoiseGenerator(rate=2000, num_channels=16, read_size=200)\n run(dev)\n\n\ndef keyboard():\n dev = Keyboard()\n # need a windower to show something interesting in the oscilloscope\n pipeline = Pipeline([Windower(10)])\n run(dev, pipeline)\n\n\ndef keystick():\n dev = Keyboard(rate=20, keys=list('wasd'))\n pipeline = Pipeline([\n # window to average over\n Windower(10),\n # mean along rows\n Callable(lambda x: np.mean(x, axis=1, keepdims=True)),\n # window to show in the oscilloscope\n Windower(60)\n ])\n run(dev, pipeline)\n\n\ndef emgsim():\n # sampling rate of the simulated EMG data\n fs = 2000\n # update rate of the generated data\n update_rate = 20\n # gain to use in noise generation\n gain = 0.25\n # number of seconds of data the oscilloscope shows\n osc_view_time = 5\n\n samp_per_input = int(fs / update_rate)\n\n pipeline = Pipeline([\n # get keyboard inputs of past second\n Windower(update_rate),\n # take mean over last second and apply a gain\n Callable(lambda x: np.mean(x, axis=1, keepdims=True)),\n # generate noise with amplitude of previous output\n Callable(lambda x, k: gain * x * np.random.randn(x.shape[0], k),\n func_args=(samp_per_input,)),\n # window for pretty display in oscilloscope\n Windower(osc_view_time * update_rate * samp_per_input),\n ])\n\n dev = Keyboard(rate=update_rate, keys=list('wasd'))\n run(dev, pipeline)\n\n\ndef mouse():\n dev = Mouse(rate=20)\n pipeline = Pipeline([\n # just for scaling the input since it's in pixels\n Callable(lambda x: x/100),\n # window to show in the oscilloscope\n Windower(40)\n ])\n run(dev, pipeline)\n\n\ndef run(dev, pipeline=None):\n # run an experiment with just an oscilloscope task\n Experiment(daq=dev, subject='test').run(Oscilloscope(pipeline))\n\n\nif __name__ == '__main__':\n functions = {\n 'rainbow': rainbow,\n 'keyboard': keyboard,\n 'keystick': keystick,\n 'emgsim': emgsim,\n 'mouse': mouse,\n }\n\n parser = argparse.ArgumentParser(usage=__doc__)\n parser.add_argument(\n 'function',\n help='Function in the example script to run.')\n args = parser.parse_args()\n\n if args.function not in functions:\n print(\"{} isn't a function in the example.\".format(args.function))\n sys.exit(-1)\n else:\n functions[args.function]()\n" ]
[ [ "numpy.atleast_2d" ], [ "numpy.random.randn" ], [ "numpy.random.randn", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
h3nnn4n/colosseum_renderer
[ "e8fb2e94ca333b4465b2cb4283822338f07d69ff" ]
[ "renderer/renderer.py" ]
[ "#!/usr/bin/env python3\n\nimport itertools\nimport sys\nfrom time import sleep, time\n\nimport numpy as np\nimport pygame\nfrom pygame.colordict import THECOLORS as colors\n\n\ndef load_image(name):\n image = pygame.image.load(name).convert_alpha()\n return image\n\n\ndef get_food_sprite():\n image = load_image(\"./renderer/sprites/food.png\")\n image = pygame.transform.scale(image, (20, 30))\n return image\n\n\ndef get_base_sprite():\n image = load_image(\"./renderer/sprites/base.png\")\n image = pygame.transform.scale(image, (20, 20))\n return image\n\n\ndef get_actor_sprite():\n image = load_image(\"./renderer/sprites/actor.png\")\n image = pygame.transform.scale(image, (20, 20))\n return image\n\n\nclass Renderer:\n def __init__(self):\n pygame.init()\n self.size = 600 * 1.5, 600 * 1.5\n self.screen = pygame.display.set_mode(self.size)\n self._data = None\n self._current_tick = None\n self.clock = pygame.time.Clock()\n self.font = pygame.font.Font(pygame.font.get_default_font(), 16)\n\n self.food_sprite = get_food_sprite()\n self.actor_sprite = get_actor_sprite()\n self.base_sprite = get_base_sprite()\n\n # FIXME: This should be read from the replay file\n self._scale = np.array(self.size) / np.array([40, 40])\n\n # Update the game state 30 times per second\n self.tick_duration = 1.0 / 30.0\n self._target_frame_duration = 1.0 / 60.0\n\n self._frame_timer = time()\n self._tick_timer = time()\n\n self.color_map = {}\n\n self.agent_colors = [\n colors[\"cadetblue\"],\n colors[\"mediumorchid3\"],\n colors[\"yellow3\"],\n colors[\"darkolivegreen3\"],\n ]\n\n def set_data(self, data):\n self._data = data\n self._current_tick = 0\n\n first_data = data[0]\n bases = first_data[\"world_state\"][\"bases\"]\n agent_ids = [base[\"owner_id\"] for base in bases]\n\n for index, agent_id in enumerate(agent_ids):\n self.color_map[agent_id] = self.agent_colors[index]\n\n def _advance_tick(self):\n now = time()\n if now - self._tick_timer < self.tick_duration:\n return\n\n self._tick_timer = now\n\n self._current_tick += 1\n if self._current_tick >= len(self._data):\n self._current_tick = 0\n\n @property\n def data(self):\n return self._data[self._current_tick]\n\n def update(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n self.clock.tick()\n self._advance_tick()\n\n self.screen.fill(colors[\"white\"])\n\n world_state = self.data[\"world_state\"]\n actions = list(\n itertools.chain.from_iterable(\n [x[\"actions\"] for x in self.data[\"agent_actions\"]]\n )\n )\n foods = world_state[\"foods\"]\n actors = world_state[\"actors\"]\n bases = world_state[\"bases\"]\n\n # FIXME: Each agent should have its own color\n for base in bases:\n self._draw_base(base)\n\n for actor in actors:\n position = np.array(actor[\"position\"]) * self._scale\n self._draw_actor(position, actor[\"owner_id\"])\n\n for action in actions:\n if action.get(\"actor_id\") == actor[\"id\"]:\n if action[\"action\"] == \"move\":\n pygame.draw.line(\n self.screen,\n colors[\"gray\"],\n np.array(actor[\"position\"]) * self._scale,\n np.array(action[\"target\"]) * self._scale,\n 2,\n )\n if action[\"action\"] == \"attack\":\n pygame.draw.line(\n self.screen,\n colors[\"red\"],\n np.array(actor[\"position\"]) * self._scale,\n np.array(self._get_object_position(action[\"target\"]))\n * self._scale,\n 4,\n )\n\n for food in foods:\n position = np.array(food[\"position\"]) * self._scale\n self._draw_food(position)\n\n now = time()\n diff = self._target_frame_duration - (now - self._frame_timer)\n if diff < self._target_frame_duration and diff > 0:\n sleep(diff)\n\n self._text(f\"fps: {self.clock.get_fps():6.2f}\", (10, 10))\n self._text(f\" {diff:.4f} (ms)\", (10, 30))\n self._frame_timer = time()\n\n pygame.display.flip()\n\n def _get_object_position(self, object_id):\n objects = [\n self.data[\"world_state\"][\"foods\"],\n self.data[\"world_state\"][\"actors\"],\n self.data[\"world_state\"][\"bases\"],\n ]\n\n for obj in itertools.chain.from_iterable(objects):\n if obj[\"id\"] == object_id:\n return obj[\"position\"]\n\n def _text(self, text, position, antialias=True, color=(220, 230, 225)):\n text_surface = self.font.render(text, antialias, color)\n self.screen.blit(text_surface, dest=position)\n\n def _draw_actor(self, position, owner_id):\n color = self.color_map[owner_id]\n pygame.draw.circle(self.screen, color, position, 14, 0)\n self.screen.blit(self.actor_sprite, position + np.array([-10, -10]))\n\n def _draw_base(self, base):\n position = np.array(base[\"position\"]) * self._scale\n color = self.color_map[base[\"owner_id\"]]\n pygame.draw.circle(self.screen, color, position, 14, 0)\n self.screen.blit(self.base_sprite, position + np.array([-10, -10]))\n\n self._text(\n f\"food: {base['food']:.1f}\",\n position + np.array([-7, -22]),\n color=colors[\"brown3\"],\n )\n\n def _draw_food(self, position):\n self.screen.blit(self.food_sprite, position + np.array([-10, -25]))\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dcortie/refnx
[ "037434fa0a64755f72c540d75063986bd517ab10", "037434fa0a64755f72c540d75063986bd517ab10" ]
[ "refnx/analysis/test/test_globalfitting.py", "refnx/analysis/test/test_bounds.py" ]
[ "\"\"\"\nTest co-refinement of datasets by fitting 3 neutron reflectivity datasets. The\noverall construction of the models can be done in a few different ways.\n\"\"\"\nimport os.path\n\nimport numpy as np\nfrom numpy.testing import (\n assert_,\n assert_equal,\n assert_almost_equal,\n assert_allclose,\n)\n\nfrom refnx.analysis import CurveFitter, Objective, GlobalObjective, Transform\nfrom refnx.dataset import ReflectDataset\nfrom refnx.reflect import Slab, SLD, ReflectModel\n\nSEED = 1\n\n\nclass TestGlobalFitting:\n def setup_method(self):\n self.pth = os.path.dirname(os.path.abspath(__file__))\n\n self.si = SLD(2.07, name=\"Si\")\n self.sio2 = SLD(3.47, name=\"SiO2\")\n self.d2o = SLD(6.36, name=\"d2o\")\n self.h2o = SLD(-0.56, name=\"h2o\")\n self.cm3 = SLD(3.5, name=\"cm3\")\n self.polymer = SLD(2, name=\"polymer\")\n\n self.sio2_l = self.sio2(40, 3)\n self.polymer_l = self.polymer(200, 3)\n\n self.structure = (\n self.si | self.sio2_l | self.polymer_l | self.d2o(0, 3)\n )\n\n fname = os.path.join(self.pth, \"c_PLP0011859_q.txt\")\n\n self.dataset = ReflectDataset(fname)\n self.model = ReflectModel(self.structure, bkg=2e-7)\n self.objective = Objective(\n self.model,\n self.dataset,\n use_weights=False,\n transform=Transform(\"logY\"),\n )\n self.global_objective = GlobalObjective([self.objective])\n\n def test_residuals_length(self):\n # the residuals should be the same length as the data\n residuals = self.global_objective.residuals()\n assert_equal(residuals.size, len(self.dataset))\n\n def test_globalfitting(self):\n # smoke test for can the global fitting run?\n # also tests that global fitting gives same output as\n # normal fitting (for a single dataset)\n self.model.scale.setp(vary=True, bounds=(0.1, 2))\n self.model.bkg.setp(vary=True, bounds=(1e-10, 8e-6))\n self.structure[-1].rough.setp(vary=True, bounds=(0.2, 6))\n self.sio2_l.thick.setp(vary=True, bounds=(0.2, 80))\n self.polymer_l.thick.setp(bounds=(0.01, 400), vary=True)\n self.polymer_l.sld.real.setp(vary=True, bounds=(0.01, 4))\n\n self.objective.transform = Transform(\"logY\")\n\n starting = np.array(self.objective.parameters)\n with np.errstate(invalid=\"raise\"):\n g = CurveFitter(self.global_objective)\n res_g = g.fit()\n\n # need the same starting point\n self.objective.setp(starting)\n f = CurveFitter(self.objective)\n res_f = f.fit()\n\n # individual and global should give the same fit.\n assert_almost_equal(res_g.x, res_f.x)\n\n def test_multipledataset_corefinement(self):\n # test corefinement of three datasets\n data361 = ReflectDataset(os.path.join(self.pth, \"e361r.txt\"))\n data365 = ReflectDataset(os.path.join(self.pth, \"e365r.txt\"))\n data366 = ReflectDataset(os.path.join(self.pth, \"e366r.txt\"))\n\n si = SLD(2.07, name=\"Si\")\n sio2 = SLD(3.47, name=\"SiO2\")\n d2o = SLD(6.36, name=\"d2o\")\n h2o = SLD(-0.56, name=\"h2o\")\n cm3 = SLD(3.47, name=\"cm3\")\n polymer = SLD(1, name=\"polymer\")\n\n structure361 = si | sio2(10, 4) | polymer(200, 3) | d2o(0, 3)\n structure365 = si | structure361[1] | structure361[2] | cm3(0, 3)\n structure366 = si | structure361[1] | structure361[2] | h2o(0, 3)\n\n structure365[-1].rough = structure361[-1].rough\n structure366[-1].rough = structure361[-1].rough\n\n structure361[1].thick.setp(vary=True, bounds=(0, 20))\n structure361[2].thick.setp(\n value=200.0, bounds=(200.0, 250.0), vary=True\n )\n structure361[2].sld.real.setp(vary=True, bounds=(0, 2))\n structure361[2].vfsolv.setp(value=5.0, bounds=(0.0, 100.0), vary=True)\n\n model361 = ReflectModel(structure361, bkg=2e-5)\n model365 = ReflectModel(structure365, bkg=2e-5)\n model366 = ReflectModel(structure366, bkg=2e-5)\n\n model361.bkg.setp(vary=True, bounds=(1e-6, 5e-5))\n model365.bkg.setp(vary=True, bounds=(1e-6, 5e-5))\n model366.bkg.setp(vary=True, bounds=(1e-6, 5e-5))\n\n objective361 = Objective(model361, data361)\n objective365 = Objective(model365, data365)\n objective366 = Objective(model366, data366)\n\n global_objective = GlobalObjective(\n [objective361, objective365, objective366]\n )\n # are the right numbers of parameters varying?\n assert_equal(len(global_objective.varying_parameters()), 7)\n\n # can we set the parameters?\n global_objective.setp(np.array([1e-5, 10, 212, 1, 10, 1e-5, 1e-5]))\n\n f = CurveFitter(global_objective)\n f.fit()\n\n indiv_chisqr = np.sum(\n [objective.chisqr() for objective in global_objective.objectives]\n )\n\n # the overall chi2 should be sum of individual chi2\n global_chisqr = global_objective.chisqr()\n assert_almost_equal(global_chisqr, indiv_chisqr)\n\n # now check that the parameters were held in common correctly.\n slabs361 = structure361.slabs()\n slabs365 = structure365.slabs()\n slabs366 = structure366.slabs()\n\n assert_equal(slabs365[0:2, 0:5], slabs361[0:2, 0:5])\n assert_equal(slabs366[0:2, 0:5], slabs361[0:2, 0:5])\n assert_equal(slabs365[-1, 3], slabs361[-1, 3])\n assert_equal(slabs366[-1, 3], slabs361[-1, 3])\n\n # check that the residuals are the correct lengths\n res361 = objective361.residuals()\n res365 = objective365.residuals()\n res366 = objective366.residuals()\n res_global = global_objective.residuals()\n assert_allclose(res_global[0 : len(res361)], res361, rtol=1e-5)\n assert_allclose(\n res_global[len(res361) : len(res361) + len(res365)],\n res365,\n rtol=1e-5,\n )\n assert_allclose(\n res_global[len(res361) + len(res365) :], res366, rtol=1e-5\n )\n\n repr(global_objective)\n", "import pickle\n\nfrom refnx.analysis import Interval, PDF\n\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_, assert_almost_equal\nfrom scipy.stats import norm, truncnorm, uniform\n\n\nclass TestBounds:\n def setup_method(self):\n pass\n\n def test_interval(self):\n # open interval should have logp of 0\n interval = Interval()\n assert_equal(interval.logp(0), 0)\n\n # semi closed interval\n interval.ub = 1000\n assert_equal(interval.logp(0), 0)\n assert_equal(interval.logp(1001), -np.inf)\n\n # you should be able to send in multiple values\n assert_equal(\n interval.logp(np.array([1.0, 1002.0])), np.array([0, -np.inf])\n )\n\n # fully closed interval\n interval.lb = -1000\n assert_equal(interval.logp(-1001), -np.inf)\n assert_equal(interval.lb, -1000)\n assert_equal(interval.ub, 1000)\n assert_equal(interval.logp(0), np.log(1 / 2000.0))\n\n # you should be able to send in multiple values\n assert_equal(\n interval.logp(np.array([1.0, 2.0])),\n np.array([np.log(1 / 2000.0)] * 2),\n )\n\n # try and set lb higher than ub\n interval.lb = 1002\n assert_equal(interval.lb, 1000)\n assert_equal(interval.ub, 1002)\n\n # if val is outside closed range then rvs is used\n vals = interval.valid(np.linspace(990, 1005, 100))\n assert_(np.max(vals) <= 1002)\n assert_(np.min(vals) >= 1000)\n assert_(np.isfinite(interval.logp(vals)).all())\n\n # if bounds are semi-open then val is reflected from lb\n interval.ub = None\n interval.lb = 1002\n x = np.linspace(990, 1001, 10)\n vals = interval.valid(x)\n assert_almost_equal(vals, 2 * interval.lb - x)\n assert_equal(interval.valid(1003), 1003)\n\n # if bounds are semi-open then val is reflected from ub\n interval.lb = None\n interval.ub = 1002\n x = np.linspace(1003, 1005, 10)\n vals = interval.valid(x)\n assert_almost_equal(vals, 2 * interval.ub - x)\n assert_equal(interval.valid(1001), 1001)\n\n # ppf for Interval\n interval.lb = -10.0\n interval.ub = 10.0\n rando = np.random.uniform(size=10)\n assert_equal(interval.invcdf(rando), uniform.ppf(rando, -10, 20))\n\n def test_repr(self):\n p = Interval(-5, 5)\n q = eval(repr(p))\n assert_equal(q.lb, p.lb)\n assert_equal(q.ub, p.ub)\n p = Interval()\n q = eval(repr(p))\n assert_equal(q.lb, p.lb)\n assert_equal(q.ub, p.ub)\n\n def test_pdf(self):\n pdf = PDF(norm)\n\n # even if it's really far out it's still a valid value\n assert_equal(pdf.valid(1003), 1003)\n # logp\n assert_equal(pdf.logp(0), norm.logpdf(0))\n\n # examine dist with finite support\n pdf = PDF(truncnorm(-1, 1))\n assert_equal(pdf.logp(-2), -np.inf)\n assert_equal(pdf.logp(-0.5), truncnorm.logpdf(-0.5, -1, 1))\n\n # obtain a random value of a bounds instance\n vals = pdf.rvs(size=1000)\n assert_(np.min(vals) >= -1)\n assert_(np.min(vals) <= 1)\n\n # test a uniform distribution\n pdf = PDF(uniform(1, 9))\n assert_equal(pdf.logp(2), np.log(1.0 / 9.0))\n assert_equal(pdf.logp(10.0), np.log(1.0 / 9.0))\n\n # test the invcdf\n rando = np.random.uniform(size=10)\n pdf = PDF(truncnorm(-1, 1))\n assert_equal(pdf.invcdf(rando), truncnorm.ppf(rando, -1, 1))\n\n def test_pickle(self):\n bounds = PDF(norm(1.0, 2.0))\n pkl = pickle.dumps(bounds)\n pickle.loads(pkl)\n\n bounds = Interval()\n pkl = pickle.dumps(bounds)\n pickle.loads(pkl)\n\n def test_user_pdf(self):\n pdf = UserPDF()\n bounds = PDF(pdf)\n\n assert_equal(bounds.valid(1.0), 1)\n bounds.rvs(1)\n assert_equal(bounds.logp(1.0), 0)\n\n\nclass UserPDF:\n def __init__(self):\n pass\n\n def logpdf(self, v):\n return 0.0\n\n def rvs(self, size=1, random_state=None):\n return np.random.random(size)\n\n def ppf(self, q):\n return 1\n\n def invcdf(self, q):\n return 1\n" ]
[ [ "numpy.errstate", "numpy.testing.assert_almost_equal", "numpy.array", "numpy.testing.assert_equal" ], [ "numpy.testing.assert_equal", "numpy.log", "numpy.random.random", "numpy.linspace", "numpy.min", "scipy.stats.uniform.ppf", "scipy.stats.truncnorm", "scipy.stats.truncnorm.logpdf", "numpy.testing.assert_almost_equal", "scipy.stats.norm.logpdf", "scipy.stats.norm", "scipy.stats.uniform", "numpy.max", "numpy.random.uniform", "numpy.array", "scipy.stats.truncnorm.ppf" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
destenson/tensorflow--tensorflow
[ "7f84d88d39f236e5c0cea492a2248782e696c972" ]
[ "tensorflow/python/keras/_impl/keras/backend.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=protected-access\n# pylint: disable=redefined-outer-name\n# pylint: disable=redefined-builtin\n\"\"\"Keras backend API.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport os\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session as session_module\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes as dtypes_module\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.layers import base as tf_base_layers\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import ctc_ops as ctc\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import gradients as gradients_module\nfrom tensorflow.python.ops import image_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import logging_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import tensor_array_grad # pylint: disable=unused-import\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variables as variables_module\nfrom tensorflow.python.training import moving_averages\nfrom tensorflow.python.util import tf_inspect\n\n\npy_all = all\npy_sum = sum\n\n# INTERNAL UTILS\n\n# This is the default internal TF session used by Keras.\n# It can be set manually via `set_session(sess)`.\n_SESSION = None\n\n# This dictionary holds a mapping {graph: learning_phase}.\n# A learning phase is a bool tensor used to run Keras models in\n# either train mode (learning_phase == 1) or test mode (learning_phase == 0).\n_GRAPH_LEARNING_PHASES = {}\n\n# This dictionary holds a mapping {graph: UID_DICT}.\n# each UID_DICT is a dictionary mapping name prefixes to a current index,\n# used for generating graph-specific string UIDs\n# for various names (e.g. layer names).\n_GRAPH_UID_DICTS = {}\n\n# This boolean flag can be set to True to leave variable initialization\n# up to the user.\n# Change its value via `manual_variable_initialization(value)`.\n_MANUAL_VAR_INIT = False\n\n# The type of float to use throughout a session.\n_FLOATX = 'float32'\n\n# Epsilon fuzz factor used throughout the codebase.\n_EPSILON = 10e-8\n\n# Default image data format, one of \"channels_last\", \"channels_first\".\n_IMAGE_DATA_FORMAT = 'channels_last'\n\n\ndef backend():\n \"\"\"Publicly accessible method for determining the current backend.\n\n Only exists for API compatibility with multi-backend Keras.\n\n Returns:\n The string \"tensorflow\".\n \"\"\"\n return 'tensorflow'\n\n\ndef epsilon():\n \"\"\"Returns the value of the fuzz factor used in numeric expressions.\n\n Returns:\n A float.\n\n Example:\n ```python\n >>> keras.backend.epsilon()\n 1e-08\n ```\n \"\"\"\n return _EPSILON\n\n\ndef set_epsilon(value):\n \"\"\"Sets the value of the fuzz factor used in numeric expressions.\n\n Arguments:\n value: float. New value of epsilon.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> K.epsilon()\n 1e-08\n >>> K.set_epsilon(1e-05)\n >>> K.epsilon()\n 1e-05\n ```\n \"\"\"\n global _EPSILON\n _EPSILON = value\n\n\ndef floatx():\n \"\"\"Returns the default float type, as a string.\n\n E.g. 'float16', 'float32', 'float64'.\n\n Returns:\n String, the current default float type.\n\n Example:\n ```python\n >>> keras.backend.floatx()\n 'float32'\n ```\n \"\"\"\n return _FLOATX\n\n\ndef set_floatx(value):\n \"\"\"Sets the default float type.\n\n Arguments:\n value: String; 'float16', 'float32', or 'float64'.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> K.floatx()\n 'float32'\n >>> K.set_floatx('float16')\n >>> K.floatx()\n 'float16'\n ```\n\n Raises:\n ValueError: In case of invalid value.\n \"\"\"\n global _FLOATX\n if value not in {'float16', 'float32', 'float64'}:\n raise ValueError('Unknown floatx type: ' + str(value))\n _FLOATX = str(value)\n\n\ndef cast_to_floatx(x):\n \"\"\"Cast a Numpy array to the default Keras float type.\n\n Arguments:\n x: Numpy array.\n\n Returns:\n The same Numpy array, cast to its new type.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> K.floatx()\n 'float32'\n >>> arr = numpy.array([1.0, 2.0], dtype='float64')\n >>> arr.dtype\n dtype('float64')\n >>> new_arr = K.cast_to_floatx(arr)\n >>> new_arr\n array([ 1., 2.], dtype=float32)\n >>> new_arr.dtype\n dtype('float32')\n ```\n \"\"\"\n return np.asarray(x, dtype=_FLOATX)\n\n\ndef image_data_format():\n \"\"\"Returns the default image data format convention.\n\n Returns:\n A string, either `'channels_first'` or `'channels_last'`\n\n Example:\n ```python\n >>> keras.backend.image_data_format()\n 'channels_first'\n ```\n \"\"\"\n return _IMAGE_DATA_FORMAT\n\n\ndef set_image_data_format(data_format):\n \"\"\"Sets the value of the image data format convention.\n\n Arguments:\n data_format: string. `'channels_first'` or `'channels_last'`.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> K.image_data_format()\n 'channels_first'\n >>> K.set_image_data_format('channels_last')\n >>> K.image_data_format()\n 'channels_last'\n ```\n\n Raises:\n ValueError: In case of invalid `data_format` value.\n \"\"\"\n global _IMAGE_DATA_FORMAT\n if data_format not in {'channels_last', 'channels_first'}:\n raise ValueError('Unknown data_format:', data_format)\n _IMAGE_DATA_FORMAT = str(data_format)\n\n\ndef get_uid(prefix=''):\n \"\"\"Associates a string prefix with an integer counter in a TensorFlow graph.\n\n Arguments:\n prefix: String prefix to index.\n\n Returns:\n Unique integer ID.\n\n Example:\n\n ```\n >>> get_uid('dense')\n 1\n >>> get_uid('dense')\n 2\n ```\n \"\"\"\n graph = ops.get_default_graph()\n if graph not in tf_base_layers.PER_GRAPH_LAYER_NAME_UIDS:\n tf_base_layers.PER_GRAPH_LAYER_NAME_UIDS[graph] = collections.defaultdict(\n int)\n layer_name_uids = tf_base_layers.PER_GRAPH_LAYER_NAME_UIDS[graph]\n layer_name_uids[prefix] += 1\n return layer_name_uids[prefix]\n\n\ndef reset_uids():\n per_graph_layer_name_uids = tf_base_layers.PER_GRAPH_LAYER_NAME_UIDS\n keys = list(per_graph_layer_name_uids.keys())\n for key in keys:\n del per_graph_layer_name_uids[key]\n\n\ndef clear_session():\n \"\"\"Destroys the current TF graph and creates a new one.\n\n Useful to avoid clutter from old models / layers.\n \"\"\"\n global _SESSION\n global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned\n ops.reset_default_graph()\n reset_uids()\n _SESSION = None\n phase = array_ops.placeholder(dtype='bool', name='keras_learning_phase')\n _GRAPH_LEARNING_PHASES = {}\n _GRAPH_LEARNING_PHASES[ops.get_default_graph()] = phase\n\n\ndef manual_variable_initialization(value):\n \"\"\"Sets the manual variable initialization flag.\n\n This boolean flag determines whether\n variables should be initialized\n as they are instantiated (default), or if\n the user should handle the initialization\n (e.g. via `tf.initialize_all_variables()`).\n\n Arguments:\n value: Python boolean.\n \"\"\"\n global _MANUAL_VAR_INIT\n _MANUAL_VAR_INIT = value\n\n\ndef learning_phase():\n \"\"\"Returns the learning phase flag.\n\n The learning phase flag is a bool tensor (0 = test, 1 = train)\n to be passed as input to any Keras function\n that uses a different behavior at train time and test time.\n\n Returns:\n Learning phase (scalar integer tensor or Python integer).\n \"\"\"\n graph = ops.get_default_graph()\n if graph not in _GRAPH_LEARNING_PHASES:\n phase = array_ops.placeholder(dtype='bool', name='keras_learning_phase')\n _GRAPH_LEARNING_PHASES[graph] = phase\n return _GRAPH_LEARNING_PHASES[graph]\n\n\ndef set_learning_phase(value):\n \"\"\"Sets the learning phase to a fixed value.\n\n Arguments:\n value: Learning phase value, either 0 or 1 (integers).\n\n Raises:\n ValueError: if `value` is neither `0` nor `1`.\n \"\"\"\n global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned\n if value not in {0, 1}:\n raise ValueError('Expected learning phase to be ' '0 or 1.')\n _GRAPH_LEARNING_PHASES[ops.get_default_graph()] = value\n\n\ndef get_session():\n \"\"\"Returns the TF session to be used by the backend.\n\n If a default TensorFlow session is available, we will return it.\n\n Else, we will return the global Keras session.\n\n If no global Keras session exists at this point:\n we will create a new global session.\n\n Note that you can manually set the global session\n via `K.set_session(sess)`.\n\n Returns:\n A TensorFlow session.\n \"\"\"\n global _SESSION\n if ops.get_default_session() is not None:\n session = ops.get_default_session()\n else:\n if _SESSION is None:\n if not os.environ.get('OMP_NUM_THREADS'):\n config = config_pb2.ConfigProto(allow_soft_placement=True)\n else:\n num_thread = int(os.environ.get('OMP_NUM_THREADS'))\n config = config_pb2.ConfigProto(\n intra_op_parallelism_threads=num_thread, allow_soft_placement=True)\n _SESSION = session_module.Session(config=config)\n session = _SESSION\n if not _MANUAL_VAR_INIT:\n with session.graph.as_default():\n _initialize_variables(session)\n return session\n\n\ndef set_session(session):\n \"\"\"Sets the global TensorFlow session.\n\n Arguments:\n session: A TF Session.\n \"\"\"\n global _SESSION\n _SESSION = session\n\n\n# DEVICE MANIPULATION\n\n\nclass _TfDeviceCaptureOp(object):\n \"\"\"Class for capturing the TF device scope.\"\"\"\n\n def __init__(self):\n self.device = None\n\n def _set_device(self, device):\n \"\"\"This method captures TF's explicit device scope setting.\"\"\"\n self.device = device\n\n\ndef _get_current_tf_device():\n \"\"\"Return explicit device of current context, otherwise returns `None`.\n\n Returns:\n If the current device scope is explicitly set, it returns a string with\n the device (`CPU` or `GPU`). If the scope is not explicitly set, it will\n return `None`.\n \"\"\"\n g = ops.get_default_graph()\n op = _TfDeviceCaptureOp()\n g._apply_device_functions(op)\n return op.device\n\n\ndef _is_current_explicit_device(device_type):\n \"\"\"Check if the current device is explicitly set on the device type specified.\n\n Arguments:\n device_type: A string containing `GPU` or `CPU` (case-insensitive).\n\n Returns:\n A boolean indicating if the current device scope is explicitly set on the\n device type.\n\n Raises:\n ValueError: If the `device_type` string indicates an unsupported device.\n \"\"\"\n device_type = device_type.upper()\n if device_type not in ['CPU', 'GPU']:\n raise ValueError('device_type should be either \"CPU\" or \"GPU\".')\n device = _get_current_tf_device()\n return device is not None and device.device_type == device_type.upper()\n\n\ndef _get_available_gpus():\n \"\"\"Get a list of available gpu devices (formatted as strings).\n\n Returns:\n A list of available GPU devices.\n \"\"\"\n devices = get_session().list_devices()\n return [x.name for x in devices if x.device_type == 'GPU']\n\n\ndef _has_nchw_support():\n \"\"\"Check whether the current scope supports NCHW ops.\n\n Tensorflow does not support NCHW on CPU. Therefore we check if we are not\n explicitly put on\n CPU, and have GPUs available. In this case there will be soft-placing on the\n GPU device.\n\n Returns:\n bool: if the current scope device placement would support nchw\n \"\"\"\n explicitly_on_cpu = _is_current_explicit_device('CPU')\n gpus_available = bool(_get_available_gpus())\n return not explicitly_on_cpu and gpus_available\n\n\n# VARIABLE MANIPULATION\n\n\ndef _to_tensor(x, dtype):\n \"\"\"Convert the input `x` to a tensor of type `dtype`.\n\n Arguments:\n x: An object to be converted (numpy array, list, tensors).\n dtype: The destination type.\n\n Returns:\n A tensor.\n \"\"\"\n return ops.convert_to_tensor(x, dtype=dtype)\n\n\ndef is_sparse(tensor):\n \"\"\"Returns whether a tensor is a sparse tensor.\n\n Arguments:\n tensor: A tensor instance.\n\n Returns:\n A boolean.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> a = K.placeholder((2, 2), sparse=False)\n >>> print(K.is_sparse(a))\n False\n >>> b = K.placeholder((2, 2), sparse=True)\n >>> print(K.is_sparse(b))\n True\n ```\n \"\"\"\n return isinstance(tensor, sparse_tensor.SparseTensor)\n\n\ndef to_dense(tensor):\n \"\"\"Converts a sparse tensor into a dense tensor and returns it.\n\n Arguments:\n tensor: A tensor instance (potentially sparse).\n\n Returns:\n A dense tensor.\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> b = K.placeholder((2, 2), sparse=True)\n >>> print(K.is_sparse(b))\n True\n >>> c = K.to_dense(b)\n >>> print(K.is_sparse(c))\n False\n ```\n \"\"\"\n if is_sparse(tensor):\n return sparse_ops.sparse_tensor_to_dense(tensor)\n else:\n return tensor\n\n\nname_scope = ops.name_scope\n\n\ndef variable(value, dtype=None, name=None, constraint=None):\n \"\"\"Instantiates a variable and returns it.\n\n Arguments:\n value: Numpy array, initial value of the tensor.\n dtype: Tensor type.\n name: Optional name string for the tensor.\n constraint: Optional projection function to be\n applied to the variable after an optimizer update.\n\n Returns:\n A variable instance (with Keras metadata included).\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val, dtype='float64', name='example_var')\n >>> K.dtype(kvar)\n 'float64'\n >>> print(kvar)\n example_var\n >>> kvar.eval()\n array([[ 1., 2.],\n [ 3., 4.]])\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if hasattr(value, 'tocoo'):\n sparse_coo = value.tocoo()\n indices = np.concatenate((np.expand_dims(sparse_coo.row, 1), np.expand_dims(\n sparse_coo.col, 1)), 1)\n v = sparse_tensor.SparseTensor(\n indices=indices, values=sparse_coo.data, dense_shape=sparse_coo.shape)\n v._keras_shape = sparse_coo.shape\n v._uses_learning_phase = False\n return v\n v = variables_module.Variable(\n value,\n dtype=dtypes_module.as_dtype(dtype),\n name=name,\n constraint=constraint)\n if isinstance(value, np.ndarray):\n v._keras_shape = value.shape\n elif hasattr(value, 'get_shape'):\n v._keras_shape = int_shape(value)\n v._uses_learning_phase = False\n return v\n\n\ndef _initialize_variables(session):\n \"\"\"Utility to initialize uninitialized variables on the fly.\"\"\"\n variables = variables_module.global_variables()\n candidate_vars = []\n for v in variables:\n if not getattr(v, '_keras_initialized', False):\n candidate_vars.append(v)\n if candidate_vars:\n # This step is expensive, so we only run it on variables not already\n # marked as initialized.\n is_initialized = session.run(\n [variables_module.is_variable_initialized(v) for v in candidate_vars])\n uninitialized_vars = []\n for flag, v in zip(is_initialized, candidate_vars):\n if not flag:\n uninitialized_vars.append(v)\n v._keras_initialized = True\n if uninitialized_vars:\n session.run(variables_module.variables_initializer(uninitialized_vars))\n\n\ndef constant(value, dtype=None, shape=None, name=None):\n \"\"\"Creates a constant tensor.\n\n Arguments:\n value: A constant value (or list)\n dtype: The type of the elements of the resulting tensor.\n shape: Optional dimensions of resulting tensor.\n name: Optional name for the tensor.\n\n Returns:\n A Constant Tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n return constant_op.constant(value, dtype=dtype, shape=shape, name=name)\n\n\ndef is_keras_tensor(x):\n \"\"\"Returns whether `x` is a Keras tensor.\n\n A \"Keras tensor\" is a tensor that was returned by a Keras layer,\n (`Layer` class) or by `Input`.\n\n Arguments:\n x: A candidate tensor.\n\n Returns:\n A boolean: Whether the argument is a Keras tensor.\n\n Raises:\n ValueError: In case `x` is not a symbolic tensor.\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> from keras.layers import Input, Dense\n >>> np_var = numpy.array([1, 2])\n >>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor.\n ValueError\n >>> k_var = tf.placeholder('float32', shape=(1,1))\n >>> K.is_keras_tensor(k_var) # A variable indirectly created outside of\n keras is not a Keras tensor.\n False\n >>> keras_var = K.variable(np_var)\n >>> K.is_keras_tensor(keras_var) # A variable created with the keras\n backend is not a Keras tensor.\n False\n >>> keras_placeholder = K.placeholder(shape=(2, 4, 5))\n >>> K.is_keras_tensor(keras_placeholder) # A placeholder is not a Keras\n tensor.\n False\n >>> keras_input = Input([10])\n >>> K.is_keras_tensor(keras_input) # An Input is a Keras tensor.\n True\n >>> keras_layer_output = Dense(10)(keras_input)\n >>> K.is_keras_tensor(keras_layer_output) # Any Keras layer output is a\n Keras tensor.\n True\n ```\n \"\"\"\n if not isinstance(x, (ops.Tensor,\n variables_module.Variable,\n sparse_tensor.SparseTensor)):\n raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) +\n '`. Expected a symbolic tensor instance.')\n return hasattr(x, '_keras_history')\n\n\ndef placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):\n \"\"\"Instantiates a placeholder tensor and returns it.\n\n Arguments:\n shape: Shape of the placeholder\n (integer tuple, may include `None` entries).\n ndim: Number of axes of the tensor.\n At least one of {`shape`, `ndim`} must be specified.\n If both are specified, `shape` is used.\n dtype: Placeholder type.\n sparse: Boolean, whether the placeholder should have a sparse type.\n name: Optional name string for the placeholder.\n\n Returns:\n Tensor instance (with Keras metadata included).\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> input_ph = K.placeholder(shape=(2, 4, 5))\n >>> input_ph\n <tf.Tensor 'Placeholder_4:0' shape=(2, 4, 5) dtype=float32>\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if not shape:\n if ndim:\n shape = tuple([None for _ in range(ndim)])\n if sparse:\n x = array_ops.sparse_placeholder(dtype, shape=shape, name=name)\n else:\n x = array_ops.placeholder(dtype, shape=shape, name=name)\n x._uses_learning_phase = False\n return x\n\n\ndef is_placeholder(x):\n \"\"\"Returns whether `x` is a placeholder.\n\n Arguments:\n x: A candidate placeholder.\n\n Returns:\n Boolean.\n \"\"\"\n try:\n return x.op.type == 'Placeholder'\n except AttributeError:\n return False\n\n\ndef shape(x):\n \"\"\"Returns the symbolic shape of a tensor or variable.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A symbolic shape (which is itself a tensor).\n\n Examples:\n\n ```python\n # TensorFlow example\n >>> from keras import backend as K\n >>> tf_session = K.get_session()\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> input = keras.backend.placeholder(shape=(2, 4, 5))\n >>> K.shape(kvar)\n <tf.Tensor 'Shape_8:0' shape=(2,) dtype=int32>\n >>> K.shape(input)\n <tf.Tensor 'Shape_9:0' shape=(3,) dtype=int32>\n # To get integer shape (Instead, you can use K.int_shape(x))\n >>> K.shape(kvar).eval(session=tf_session)\n array([2, 2], dtype=int32)\n >>> K.shape(input).eval(session=tf_session)\n array([2, 4, 5], dtype=int32)\n ```\n \"\"\"\n return array_ops.shape(x)\n\n\ndef int_shape(x):\n \"\"\"Returns the shape of tensor or variable as a tuple of int or None entries.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tuple of integers (or None entries).\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> input = K.placeholder(shape=(2, 4, 5))\n >>> K.int_shape(input)\n (2, 4, 5)\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> K.int_shape(kvar)\n (2, 2)\n ```\n \"\"\"\n try:\n return tuple(x.get_shape().as_list())\n except ValueError:\n return None\n\n\ndef ndim(x):\n \"\"\"Returns the number of axes in a tensor, as an integer.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n Integer (scalar), number of axes.\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> input = K.placeholder(shape=(2, 4, 5))\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> K.ndim(input)\n 3\n >>> K.ndim(kvar)\n 2\n ```\n \"\"\"\n dims = x.get_shape()._dims\n if dims is not None:\n return len(dims)\n return None\n\n\ndef dtype(x):\n \"\"\"Returns the dtype of a Keras tensor or variable, as a string.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n String, dtype of `x`.\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> K.dtype(K.placeholder(shape=(2,4,5)))\n 'float32'\n >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))\n 'float32'\n >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))\n 'float64'\n # Keras variable\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]))\n >>> K.dtype(kvar)\n 'float32_ref'\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')\n >>> K.dtype(kvar)\n 'float32_ref'\n ```\n \"\"\"\n return x.dtype.base_dtype.name\n\n\ndef eval(x):\n \"\"\"Evaluates the value of a variable.\n\n Arguments:\n x: A variable.\n\n Returns:\n A Numpy array.\n\n Examples:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')\n >>> K.eval(kvar)\n array([[ 1., 2.],\n [ 3., 4.]], dtype=float32)\n ```\n \"\"\"\n return to_dense(x).eval(session=get_session())\n\n\ndef zeros(shape, dtype=None, name=None):\n \"\"\"Instantiates an all-zeros variable and returns it.\n\n Arguments:\n shape: Tuple of integers, shape of returned Keras variable\n dtype: String, data type of returned Keras variable\n name: String, name of returned Keras variable\n\n Returns:\n A variable (including Keras metadata), filled with `0.0`.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.zeros((3,4))\n >>> K.eval(kvar)\n array([[ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.]], dtype=float32)\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n return variable(\n init_ops.constant_initializer(0., dtype=tf_dtype)(shape), dtype, name)\n\n\ndef ones(shape, dtype=None, name=None):\n \"\"\"Instantiates an all-ones tensor variable and returns it.\n\n Arguments:\n shape: Tuple of integers, shape of returned Keras variable.\n dtype: String, data type of returned Keras variable.\n name: String, name of returned Keras variable.\n\n Returns:\n A Keras variable, filled with `1.0`.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.ones((3,4))\n >>> K.eval(kvar)\n array([[ 1., 1., 1., 1.],\n [ 1., 1., 1., 1.],\n [ 1., 1., 1., 1.]], dtype=float32)\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n return variable(\n init_ops.constant_initializer(1., dtype=tf_dtype)(shape), dtype, name)\n\n\ndef eye(size, dtype=None, name=None):\n \"\"\"Instantiate an identity matrix and returns it.\n\n Arguments:\n size: Integer, number of rows/columns.\n dtype: String, data type of returned Keras variable.\n name: String, name of returned Keras variable.\n\n Returns:\n A Keras variable, an identity matrix.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.eye(3)\n >>> K.eval(kvar)\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]], dtype=float32)\n ```\n\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n return variable(linalg_ops.eye(size, dtype=tf_dtype), dtype, name)\n\n\ndef zeros_like(x, dtype=None, name=None):\n \"\"\"Instantiates an all-zeros variable of the same shape as another tensor.\n\n Arguments:\n x: Keras variable or Keras tensor.\n dtype: String, dtype of returned Keras variable.\n None uses the dtype of x.\n name: String, name for the variable to create.\n\n Returns:\n A Keras variable with the shape of x filled with zeros.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.random.random((2,3)))\n >>> kvar_zeros = K.zeros_like(kvar)\n >>> K.eval(kvar_zeros)\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n ```\n \"\"\"\n return array_ops.zeros_like(x, dtype=dtype, name=name)\n\n\ndef ones_like(x, dtype=None, name=None):\n \"\"\"Instantiates an all-ones variable of the same shape as another tensor.\n\n Arguments:\n x: Keras variable or tensor.\n dtype: String, dtype of returned Keras variable.\n None uses the dtype of x.\n name: String, name for the variable to create.\n\n Returns:\n A Keras variable with the shape of x filled with ones.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.random.random((2,3)))\n >>> kvar_ones = K.ones_like(kvar)\n >>> K.eval(kvar_ones)\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n ```\n \"\"\"\n return array_ops.ones_like(x, dtype=dtype, name=name)\n\n\ndef identity(x, name=None):\n \"\"\"Returns a tensor with the same content as the input tensor.\n\n Arguments:\n x: The input tensor.\n name: String, name for the variable to create.\n\n Returns:\n A tensor of the same shape, type and content.\n \"\"\"\n return array_ops.identity(x, name=name)\n\n\ndef random_uniform_variable(shape, low, high, dtype=None, name=None, seed=None):\n \"\"\"Instantiates a variable with values drawn from a uniform distribution.\n\n Arguments:\n shape: Tuple of integers, shape of returned Keras variable.\n low: Float, lower boundary of the output interval.\n high: Float, upper boundary of the output interval.\n dtype: String, dtype of returned Keras variable.\n name: String, name of returned Keras variable.\n seed: Integer, random seed.\n\n Returns:\n A Keras variable, filled with drawn samples.\n\n Example:\n ```python\n # TensorFlow example\n >>> kvar = K.random_uniform_variable((2,3), 0, 1)\n >>> kvar\n <tensorflow.python.ops.variables.Variable object at 0x10ab40b10>\n >>> K.eval(kvar)\n array([[ 0.10940075, 0.10047495, 0.476143 ],\n [ 0.66137183, 0.00869417, 0.89220798]], dtype=float32)\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n if seed is None:\n # ensure that randomness is conditioned by the Numpy RNG\n seed = np.random.randint(10e8)\n value = init_ops.random_uniform_initializer(\n low, high, dtype=tf_dtype, seed=seed)(shape)\n return variable(value, dtype=dtype, name=name)\n\n\ndef random_normal_variable(shape, mean, scale, dtype=None, name=None,\n seed=None):\n \"\"\"Instantiates a variable with values drawn from a normal distribution.\n\n Arguments:\n shape: Tuple of integers, shape of returned Keras variable.\n mean: Float, mean of the normal distribution.\n scale: Float, standard deviation of the normal distribution.\n dtype: String, dtype of returned Keras variable.\n name: String, name of returned Keras variable.\n seed: Integer, random seed.\n\n Returns:\n A Keras variable, filled with drawn samples.\n\n Example:\n ```python\n # TensorFlow example\n >>> kvar = K.random_normal_variable((2,3), 0, 1)\n >>> kvar\n <tensorflow.python.ops.variables.Variable object at 0x10ab12dd0>\n >>> K.eval(kvar)\n array([[ 1.19591331, 0.68685907, -0.63814116],\n [ 0.92629528, 0.28055015, 1.70484698]], dtype=float32)\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n if seed is None:\n # ensure that randomness is conditioned by the Numpy RNG\n seed = np.random.randint(10e8)\n value = init_ops.random_normal_initializer(\n mean, scale, dtype=tf_dtype, seed=seed)(shape)\n return variable(value, dtype=dtype, name=name)\n\n\ndef count_params(x):\n \"\"\"Returns the static number of elements in a variable or tensor.\n\n Arguments:\n x: Variable or tensor.\n\n Returns:\n Integer, the number of scalars in `x`.\n\n Example:\n ```python\n >>> kvar = K.zeros((2,3))\n >>> K.count_params(kvar)\n 6\n >>> K.eval(kvar)\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n ```\n \"\"\"\n return np.prod(x.get_shape().as_list())\n\n\ndef cast(x, dtype):\n \"\"\"Casts a tensor to a different dtype and returns it.\n\n You can cast a Keras variable but it still returns a Keras tensor.\n\n Arguments:\n x: Keras tensor (or variable).\n dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).\n\n Returns:\n Keras tensor with dtype `dtype`.\n\n Example:\n ```python\n >>> from keras import backend as K\n >>> input = K.placeholder((2, 3), dtype='float32')\n >>> input\n <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>\n # It doesn't work in-place as below.\n >>> K.cast(input, dtype='float16')\n <tf.Tensor 'Cast_1:0' shape=(2, 3) dtype=float16>\n >>> input\n <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>\n # you need to assign it.\n >>> input = K.cast(input, dtype='float16')\n >>> input\n <tf.Tensor 'Cast_2:0' shape=(2, 3) dtype=float16>\n ```\n \"\"\"\n return math_ops.cast(x, dtype)\n\n\n# UPDATES OPS\n\n\ndef update(x, new_x):\n return state_ops.assign(x, new_x)\n\n\ndef update_add(x, increment):\n \"\"\"Update the value of `x` by adding `increment`.\n\n Arguments:\n x: A Variable.\n increment: A tensor of same shape as `x`.\n\n Returns:\n The variable `x` updated.\n \"\"\"\n return state_ops.assign_add(x, increment)\n\n\ndef update_sub(x, decrement):\n \"\"\"Update the value of `x` by subtracting `decrement`.\n\n Arguments:\n x: A Variable.\n decrement: A tensor of same shape as `x`.\n\n Returns:\n The variable `x` updated.\n \"\"\"\n return state_ops.assign_sub(x, decrement)\n\n\ndef moving_average_update(x, value, momentum):\n \"\"\"Compute the moving average of a variable.\n\n Arguments:\n x: A Variable.\n value: A tensor with the same shape as `variable`.\n momentum: The moving average momentum.\n\n Returns:\n An Operation to update the variable.\n \"\"\"\n return moving_averages.assign_moving_average(\n x, value, momentum, zero_debias=False)\n\n\n# LINEAR ALGEBRA\n\n\ndef dot(x, y):\n \"\"\"Multiplies 2 tensors (and/or variables) and returns a *tensor*.\n\n When attempting to multiply a nD tensor\n with a nD tensor, it reproduces the Theano behavior.\n (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A tensor, dot product of `x` and `y`.\n\n Examples:\n ```python\n # dot product between tensors\n >>> x = K.placeholder(shape=(2, 3))\n >>> y = K.placeholder(shape=(3, 4))\n >>> xy = K.dot(x, y)\n >>> xy\n <tf.Tensor 'MatMul_9:0' shape=(2, 4) dtype=float32>\n ```\n\n ```python\n # dot product between tensors\n >>> x = K.placeholder(shape=(32, 28, 3))\n >>> y = K.placeholder(shape=(3, 4))\n >>> xy = K.dot(x, y)\n >>> xy\n <tf.Tensor 'MatMul_9:0' shape=(32, 28, 4) dtype=float32>\n ```\n\n ```python\n # Theano-like behavior example\n >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)\n >>> y = K.ones((4, 3, 5))\n >>> xy = K.dot(x, y)\n >>> K.int_shape(xy)\n (2, 4, 5)\n ```\n \"\"\"\n if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2):\n x_shape = []\n for i, s in zip(int_shape(x), array_ops.unstack(array_ops.shape(x))):\n if i is not None:\n x_shape.append(i)\n else:\n x_shape.append(s)\n x_shape = tuple(x_shape)\n y_shape = []\n for i, s in zip(int_shape(y), array_ops.unstack(array_ops.shape(y))):\n if i is not None:\n y_shape.append(i)\n else:\n y_shape.append(s)\n y_shape = tuple(y_shape)\n y_permute_dim = list(range(ndim(y)))\n y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim\n xt = array_ops.reshape(x, [-1, x_shape[-1]])\n yt = array_ops.reshape(\n array_ops.transpose(y, perm=y_permute_dim), [y_shape[-2], -1])\n return array_ops.reshape(\n math_ops.matmul(xt, yt), x_shape[:-1] + y_shape[:-2] + y_shape[-1:])\n if is_sparse(x):\n out = sparse_ops.sparse_tensor_dense_matmul(x, y)\n else:\n out = math_ops.matmul(x, y)\n return out\n\n\ndef batch_dot(x, y, axes=None):\n \"\"\"Batchwise dot product.\n\n `batch_dot` is used to compute dot product of `x` and `y` when\n `x` and `y` are data in batch, i.e. in a shape of\n `(batch_size, :)`.\n `batch_dot` results in a tensor or variable with less dimensions\n than the input. If the number of dimensions is reduced to 1,\n we use `expand_dims` to make sure that ndim is at least 2.\n\n Arguments:\n x: Keras tensor or variable with `ndim >= 2`.\n y: Keras tensor or variable with `ndim >= 2`.\n axes: list of (or single) int with target dimensions.\n The lengths of `axes[0]` and `axes[1]` should be the same.\n\n Returns:\n A tensor with shape equal to the concatenation of `x`'s shape\n (less the dimension that was summed over) and `y`'s shape\n (less the batch dimension and the dimension that was summed over).\n If the final rank is 1, we reshape it to `(batch_size, 1)`.\n\n Examples:\n Assume `x = [[1, 2], [3, 4]]` and `y = [[5, 6], [7, 8]]`\n `batch_dot(x, y, axes=1) = [[17, 53]]` which is the main diagonal\n of `x.dot(y.T)`, although we never have to calculate the off-diagonal\n elements.\n\n Shape inference:\n Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`.\n If `axes` is (1, 2), to find the output shape of resultant tensor,\n loop through each dimension in `x`'s shape and `y`'s shape:\n\n * `x.shape[0]` : 100 : append to output shape\n * `x.shape[1]` : 20 : do not append to output shape,\n dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1)\n * `y.shape[0]` : 100 : do not append to output shape,\n always ignore first dimension of `y`\n * `y.shape[1]` : 30 : append to output shape\n * `y.shape[2]` : 20 : do not append to output shape,\n dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2)\n `output_shape` = `(100, 30)`\n\n ```python\n >>> x_batch = K.ones(shape=(32, 20, 1))\n >>> y_batch = K.ones(shape=(32, 30, 20))\n >>> xy_batch_dot = K.batch_dot(x_batch, y_batch, axes=[1, 2])\n >>> K.int_shape(xy_batch_dot)\n (32, 1, 30)\n ```\n \"\"\"\n if isinstance(axes, int):\n axes = (axes, axes)\n x_ndim = ndim(x)\n y_ndim = ndim(y)\n if x_ndim > y_ndim:\n diff = x_ndim - y_ndim\n y = array_ops.reshape(y,\n array_ops.concat(\n [array_ops.shape(y), [1] * (diff)], axis=0))\n elif y_ndim > x_ndim:\n diff = y_ndim - x_ndim\n x = array_ops.reshape(x,\n array_ops.concat(\n [array_ops.shape(x), [1] * (diff)], axis=0))\n else:\n diff = 0\n if ndim(x) == 2 and ndim(y) == 2:\n if axes[0] == axes[1]:\n out = math_ops.reduce_sum(math_ops.multiply(x, y), axes[0])\n else:\n out = math_ops.reduce_sum(\n math_ops.multiply(array_ops.transpose(x, [1, 0]), y), axes[1])\n else:\n if axes is not None:\n adj_x = None if axes[0] == ndim(x) - 1 else True\n adj_y = True if axes[1] == ndim(y) - 1 else None\n else:\n adj_x = None\n adj_y = None\n out = math_ops.matmul(x, y, adjoint_a=adj_x, adjoint_b=adj_y)\n if diff:\n if x_ndim > y_ndim:\n idx = x_ndim + y_ndim - 3\n else:\n idx = x_ndim - 1\n out = array_ops.squeeze(out, list(range(idx, idx + diff)))\n if ndim(out) == 1:\n out = expand_dims(out, 1)\n return out\n\n\ndef transpose(x):\n \"\"\"Transposes a tensor and returns it.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n\n Examples:\n ```python\n >>> var = K.variable([[1, 2, 3], [4, 5, 6]])\n >>> K.eval(var)\n array([[ 1., 2., 3.],\n [ 4., 5., 6.]], dtype=float32)\n >>> var_transposed = K.transpose(var)\n >>> K.eval(var_transposed)\n array([[ 1., 4.],\n [ 2., 5.],\n [ 3., 6.]], dtype=float32)\n ```\n\n ```python\n >>> input = K.placeholder((2, 3))\n >>> input\n <tf.Tensor 'Placeholder_11:0' shape=(2, 3) dtype=float32>\n >>> input_transposed = K.transpose(input)\n >>> input_transposed\n <tf.Tensor 'transpose_4:0' shape=(3, 2) dtype=float32>\n\n ```\n \"\"\"\n return array_ops.transpose(x)\n\n\ndef gather(reference, indices):\n \"\"\"Retrieves the elements of indices `indices` in the tensor `reference`.\n\n Arguments:\n reference: A tensor.\n indices: An integer tensor of indices.\n\n Returns:\n A tensor of same type as `reference`.\n \"\"\"\n return array_ops.gather(reference, indices)\n\n\n# ELEMENT-WISE OPERATIONS\n\n\ndef max(x, axis=None, keepdims=False):\n \"\"\"Maximum value in a tensor.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to find maximum values.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with maximum values of `x`.\n \"\"\"\n return math_ops.reduce_max(x, axis=axis, keep_dims=keepdims)\n\n\ndef min(x, axis=None, keepdims=False):\n \"\"\"Minimum value in a tensor.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to find minimum values.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with miminum values of `x`.\n \"\"\"\n return math_ops.reduce_min(x, axis=axis, keep_dims=keepdims)\n\n\ndef sum(x, axis=None, keepdims=False):\n \"\"\"Sum of the values in a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to sum over.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with sum of `x`.\n \"\"\"\n return math_ops.reduce_sum(x, axis=axis, keep_dims=keepdims)\n\n\ndef prod(x, axis=None, keepdims=False):\n \"\"\"Multiplies the values in a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to compute the product.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with the product of elements of `x`.\n \"\"\"\n return math_ops.reduce_prod(x, axis=axis, keep_dims=keepdims)\n\n\ndef cumsum(x, axis=0):\n \"\"\"Cumulative sum of the values in a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to compute the sum.\n\n Returns:\n A tensor of the cumulative sum of values of `x` along `axis`.\n \"\"\"\n return math_ops.cumsum(x, axis=axis)\n\n\ndef cumprod(x, axis=0):\n \"\"\"Cumulative product of the values in a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to compute the product.\n\n Returns:\n A tensor of the cumulative product of values of `x` along `axis`.\n \"\"\"\n return math_ops.cumprod(x, axis=axis)\n\n\ndef var(x, axis=None, keepdims=False):\n \"\"\"Variance of a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to compute the variance.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with the variance of elements of `x`.\n \"\"\"\n if x.dtype.base_dtype == dtypes_module.bool:\n x = math_ops.cast(x, floatx())\n m = math_ops.reduce_mean(x, axis=axis, keep_dims=True)\n devs_squared = math_ops.square(x - m)\n return math_ops.reduce_mean(\n devs_squared, axis=axis, keep_dims=keepdims)\n\n\ndef std(x, axis=None, keepdims=False):\n \"\"\"Standard deviation of a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to compute the standard deviation.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n Returns:\n A tensor with the standard deviation of elements of `x`.\n \"\"\"\n return math_ops.sqrt(var(x, axis=axis, keepdims=keepdims))\n\n\ndef mean(x, axis=None, keepdims=False):\n \"\"\"Mean of a tensor, alongside the specified axis.\n\n Arguments:\n x: A tensor or variable.\n axis: A list of integer. Axes to compute the mean.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1 for each entry in `axis`. If `keep_dims` is `True`,\n the reduced dimensions are retained with length 1.\n\n Returns:\n A tensor with the mean of elements of `x`.\n \"\"\"\n if x.dtype.base_dtype == dtypes_module.bool:\n x = math_ops.cast(x, floatx())\n return math_ops.reduce_mean(x, axis=axis, keep_dims=keepdims)\n\n\ndef any(x, axis=None, keepdims=False):\n \"\"\"Bitwise reduction (logical OR).\n\n Arguments:\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n keepdims: whether the drop or broadcast the reduction axes.\n\n Returns:\n A uint8 tensor (0s and 1s).\n \"\"\"\n x = math_ops.cast(x, dtypes_module.bool)\n return math_ops.reduce_any(x, axis=axis, keep_dims=keepdims)\n\n\ndef all(x, axis=None, keepdims=False):\n \"\"\"Bitwise reduction (logical AND).\n\n Arguments:\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n keepdims: whether the drop or broadcast the reduction axes.\n\n Returns:\n A uint8 tensor (0s and 1s).\n \"\"\"\n x = math_ops.cast(x, dtypes_module.bool)\n return math_ops.reduce_all(x, axis=axis, keep_dims=keepdims)\n\n\ndef argmax(x, axis=-1):\n \"\"\"Returns the index of the maximum value along an axis.\n\n Arguments:\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.argmax(x, axis)\n\n\ndef argmin(x, axis=-1):\n \"\"\"Returns the index of the minimum value along an axis.\n\n Arguments:\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.argmin(x, axis)\n\n\ndef square(x):\n \"\"\"Element-wise square.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.square(x)\n\n\ndef abs(x):\n \"\"\"Element-wise absolute value.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.abs(x)\n\n\ndef sqrt(x):\n \"\"\"Element-wise square root.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n zero = _to_tensor(0., x.dtype.base_dtype)\n inf = _to_tensor(np.inf, x.dtype.base_dtype)\n x = clip_ops.clip_by_value(x, zero, inf)\n return math_ops.sqrt(x)\n\n\ndef exp(x):\n \"\"\"Element-wise exponential.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.exp(x)\n\n\ndef log(x):\n \"\"\"Element-wise log.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.log(x)\n\n\ndef logsumexp(x, axis=None, keepdims=False):\n \"\"\"Computes log(sum(exp(elements across dimensions of a tensor))).\n\n This function is more numerically stable than log(sum(exp(x))).\n It avoids overflows caused by taking the exp of large inputs and\n underflows caused by taking the log of small inputs.\n\n Arguments:\n x: A tensor or variable.\n axis: An integer, the axis to reduce over.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`, the reduced dimension is\n retained with length 1.\n\n Returns:\n The reduced tensor.\n \"\"\"\n return math_ops.reduce_logsumexp(x, axis=axis, keep_dims=keepdims)\n\n\ndef round(x):\n \"\"\"Element-wise rounding to the closest integer.\n\n In case of tie, the rounding mode used is \"half to even\".\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.round(x)\n\n\ndef sign(x):\n \"\"\"Element-wise sign.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.sign(x)\n\n\ndef pow(x, a):\n \"\"\"Element-wise exponentiation.\n\n Arguments:\n x: Tensor or variable.\n a: Python integer.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.pow(x, a)\n\n\ndef clip(x, min_value, max_value):\n \"\"\"Element-wise value clipping.\n\n Arguments:\n x: Tensor or variable.\n min_value: Python float or integer.\n max_value: Python float or integer.\n\n Returns:\n A tensor.\n \"\"\"\n if max_value is not None and max_value < min_value:\n max_value = min_value\n if max_value is None:\n max_value = np.inf\n min_value = _to_tensor(min_value, x.dtype.base_dtype)\n max_value = _to_tensor(max_value, x.dtype.base_dtype)\n return clip_ops.clip_by_value(x, min_value, max_value)\n\n\ndef equal(x, y):\n \"\"\"Element-wise equality between two tensors.\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.equal(x, y)\n\n\ndef not_equal(x, y):\n \"\"\"Element-wise inequality between two tensors.\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.not_equal(x, y)\n\n\ndef greater(x, y):\n \"\"\"Element-wise truth value of (x > y).\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.greater(x, y)\n\n\ndef greater_equal(x, y):\n \"\"\"Element-wise truth value of (x >= y).\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.greater_equal(x, y)\n\n\ndef less(x, y):\n \"\"\"Element-wise truth value of (x < y).\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.less(x, y)\n\n\ndef less_equal(x, y):\n \"\"\"Element-wise truth value of (x <= y).\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A bool tensor.\n \"\"\"\n return math_ops.less_equal(x, y)\n\n\ndef maximum(x, y):\n \"\"\"Element-wise maximum of two tensors.\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.maximum(x, y)\n\n\ndef minimum(x, y):\n \"\"\"Element-wise minimum of two tensors.\n\n Arguments:\n x: Tensor or variable.\n y: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.minimum(x, y)\n\n\ndef sin(x):\n \"\"\"Computes sin of x element-wise.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.sin(x)\n\n\ndef cos(x):\n \"\"\"Computes cos of x element-wise.\n\n Arguments:\n x: Tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return math_ops.cos(x)\n\n\ndef normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=1e-3):\n \"\"\"Computes mean and std for batch then apply batch_normalization on batch.\n\n Arguments:\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\n Returns:\n A tuple length of 3, `(normalized_tensor, mean, variance)`.\n \"\"\"\n mean, var = nn.moments(\n x, reduction_axes, shift=None, name=None, keep_dims=False)\n if sorted(reduction_axes) == list(range(ndim(x)))[:-1]:\n normed = nn.batch_normalization(x, mean, var, beta, gamma, epsilon)\n else:\n # need broadcasting\n target_shape = []\n for axis in range(ndim(x)):\n if axis in reduction_axes:\n target_shape.append(1)\n else:\n target_shape.append(array_ops.shape(x)[axis])\n target_shape = array_ops.stack(target_shape)\n\n broadcast_mean = array_ops.reshape(mean, target_shape)\n broadcast_var = array_ops.reshape(var, target_shape)\n if gamma is None:\n broadcast_gamma = None\n else:\n broadcast_gamma = array_ops.reshape(gamma, target_shape)\n if beta is None:\n broadcast_beta = None\n else:\n broadcast_beta = array_ops.reshape(beta, target_shape)\n normed = nn.batch_normalization(x, broadcast_mean, broadcast_var,\n broadcast_beta, broadcast_gamma, epsilon)\n return normed, mean, var\n\n\ndef batch_normalization(x, mean, var, beta, gamma, epsilon=1e-3):\n \"\"\"Applies batch normalization on x given mean, var, beta and gamma.\n\n I.e. returns:\n `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta`\n\n Arguments:\n x: Input tensor or variable.\n mean: Mean of batch.\n var: Variance of batch.\n beta: Tensor with which to center the input.\n gamma: Tensor by which to scale the input.\n epsilon: Fuzz factor.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.batch_normalization(x, mean, var, beta, gamma, epsilon)\n\n\n# SHAPE OPERATIONS\n\n\ndef concatenate(tensors, axis=-1):\n \"\"\"Concatenates a list of tensors alongside the specified axis.\n\n Arguments:\n tensors: list of tensors to concatenate.\n axis: concatenation axis.\n\n Returns:\n A tensor.\n \"\"\"\n if axis < 0:\n rank = ndim(tensors[0])\n if rank:\n axis %= rank\n else:\n axis = 0\n\n if py_all([is_sparse(x) for x in tensors]):\n return sparse_ops.sparse_concat(axis, tensors)\n else:\n return array_ops.concat([to_dense(x) for x in tensors], axis)\n\n\ndef reshape(x, shape):\n \"\"\"Reshapes a tensor to the specified shape.\n\n Arguments:\n x: Tensor or variable.\n shape: Target shape tuple.\n\n Returns:\n A tensor.\n \"\"\"\n return array_ops.reshape(x, shape)\n\n\ndef permute_dimensions(x, pattern):\n \"\"\"Permutes axes in a tensor.\n\n Arguments:\n x: Tensor or variable.\n pattern: A tuple of\n dimension indices, e.g. `(0, 2, 1)`.\n\n Returns:\n A tensor.\n \"\"\"\n return array_ops.transpose(x, perm=pattern)\n\n\ndef resize_images(x, height_factor, width_factor, data_format):\n \"\"\"Resizes the images contained in a 4D tensor.\n\n Arguments:\n x: Tensor or variable to resize.\n height_factor: Positive integer.\n width_factor: Positive integer.\n data_format: One of `\"channels_first\"`, `\"channels_last\"`.\n\n Returns:\n A tensor.\n\n Raises:\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n \"\"\"\n if data_format == 'channels_first':\n original_shape = int_shape(x)\n new_shape = array_ops.shape(x)[2:]\n new_shape *= constant_op.constant(\n np.array([height_factor, width_factor]).astype('int32'))\n x = permute_dimensions(x, [0, 2, 3, 1])\n x = image_ops.resize_nearest_neighbor(x, new_shape)\n x = permute_dimensions(x, [0, 3, 1, 2])\n x.set_shape((None, None, original_shape[2] * height_factor\n if original_shape[2] is not None else None,\n original_shape[3] * width_factor\n if original_shape[3] is not None else None))\n return x\n elif data_format == 'channels_last':\n original_shape = int_shape(x)\n new_shape = array_ops.shape(x)[1:3]\n new_shape *= constant_op.constant(\n np.array([height_factor, width_factor]).astype('int32'))\n x = image_ops.resize_nearest_neighbor(x, new_shape)\n x.set_shape((None, original_shape[1] * height_factor\n if original_shape[1] is not None else None,\n original_shape[2] * width_factor\n if original_shape[2] is not None else None, None))\n return x\n else:\n raise ValueError('Invalid data_format:', data_format)\n\n\ndef resize_volumes(x, depth_factor, height_factor, width_factor, data_format):\n \"\"\"Resizes the volume contained in a 5D tensor.\n\n Arguments:\n x: Tensor or variable to resize.\n depth_factor: Positive integer.\n height_factor: Positive integer.\n width_factor: Positive integer.\n data_format: One of `\"channels_first\"`, `\"channels_last\"`.\n\n Returns:\n A tensor.\n\n Raises:\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n \"\"\"\n if data_format == 'channels_first':\n output = repeat_elements(x, depth_factor, axis=2)\n output = repeat_elements(output, height_factor, axis=3)\n output = repeat_elements(output, width_factor, axis=4)\n return output\n elif data_format == 'channels_last':\n output = repeat_elements(x, depth_factor, axis=1)\n output = repeat_elements(output, height_factor, axis=2)\n output = repeat_elements(output, width_factor, axis=3)\n return output\n else:\n raise ValueError('Invalid data_format:', data_format)\n\n\ndef repeat_elements(x, rep, axis):\n \"\"\"Repeats the elements of a tensor along an axis, like `np.repeat`.\n\n If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output\n will have shape `(s1, s2 * rep, s3)`.\n\n Arguments:\n x: Tensor or variable.\n rep: Python integer, number of times to repeat.\n axis: Axis along which to repeat.\n\n Returns:\n A tensor.\n \"\"\"\n x_shape = x.get_shape().as_list()\n # For static axis\n if x_shape[axis] is not None:\n # slices along the repeat axis\n splits = array_ops.split(value=x,\n num_or_size_splits=x_shape[axis],\n axis=axis)\n # repeat each slice the given number of reps\n x_rep = [s for s in splits for _ in range(rep)]\n return concatenate(x_rep, axis)\n\n # Here we use tf.tile to mimic behavior of np.repeat so that\n # we can handle dynamic shapes (that include None).\n # To do that, we need an auxiliary axis to repeat elements along\n # it and then merge them along the desired axis.\n\n # Repeating\n auxiliary_axis = axis + 1\n x_shape = array_ops.shape(x)\n x_rep = array_ops.expand_dims(x, axis=auxiliary_axis)\n reps = np.ones(len(x.get_shape()) + 1)\n reps[auxiliary_axis] = rep\n x_rep = array_ops.tile(x_rep, reps)\n\n # Merging\n reps = np.delete(reps, auxiliary_axis)\n reps[axis] = rep\n reps = array_ops.constant(reps, dtype='int32')\n x_shape *= reps\n x_rep = array_ops.reshape(x_rep, x_shape)\n\n # Fix shape representation\n x_shape = x.get_shape().as_list()\n x_rep.set_shape(x_shape)\n x_rep._keras_shape = tuple(x_shape)\n return x_rep\n\n\ndef repeat(x, n):\n \"\"\"Repeats a 2D tensor.\n\n if `x` has shape (samples, dim) and `n` is `2`,\n the output will have shape `(samples, 2, dim)`.\n\n Arguments:\n x: Tensor or variable.\n n: Python integer, number of times to repeat.\n\n Returns:\n A tensor.\n \"\"\"\n assert ndim(x) == 2\n x = array_ops.expand_dims(x, 1)\n pattern = array_ops.stack([1, n, 1])\n return array_ops.tile(x, pattern)\n\n\ndef arange(start, stop=None, step=1, dtype='int32'):\n \"\"\"Creates a 1D tensor containing a sequence of integers.\n\n The function arguments use the same convention as\n Theano's arange: if only one argument is provided,\n it is in fact the \"stop\" argument.\n\n The default type of the returned tensor is `'int32'` to\n match TensorFlow's default.\n\n Arguments:\n start: Start value.\n stop: Stop value.\n step: Difference between two successive values.\n dtype: Integer dtype to use.\n\n Returns:\n An integer tensor.\n\n \"\"\"\n # Match the behavior of numpy and Theano by returning an empty seqence.\n if stop is None and start < 0:\n start = 0\n result = math_ops.range(start, limit=stop, delta=step, name='arange')\n if dtype != 'int32':\n result = cast(result, dtype)\n return result\n\n\ndef tile(x, n):\n \"\"\"Creates a tensor by tiling `x` by `n`.\n\n Arguments:\n x: A tensor or variable\n n: A list of integer. The length must be the same as the number of\n dimensions in `x`.\n\n Returns:\n A tiled tensor.\n \"\"\"\n if isinstance(n, int):\n n = [n]\n return array_ops.tile(x, n)\n\n\ndef flatten(x):\n \"\"\"Flatten a tensor.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor, reshaped into 1-D\n \"\"\"\n return array_ops.reshape(x, [-1])\n\n\ndef batch_flatten(x):\n \"\"\"Turn a nD tensor into a 2D tensor with same 0th dimension.\n\n In other words, it flattens each data samples of a batch.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n x = array_ops.reshape(x, array_ops.stack([-1, prod(shape(x)[1:])]))\n return x\n\n\ndef expand_dims(x, axis=-1):\n \"\"\"Adds a 1-sized dimension at index \"axis\".\n\n Arguments:\n x: A tensor or variable.\n axis: Position where to add a new axis.\n\n Returns:\n A tensor with expanded dimensions.\n \"\"\"\n return array_ops.expand_dims(x, axis)\n\n\ndef squeeze(x, axis):\n \"\"\"Removes a 1-dimension from the tensor at index \"axis\".\n\n Arguments:\n x: A tensor or variable.\n axis: Axis to drop.\n\n Returns:\n A tensor with the same data as `x` but reduced dimensions.\n \"\"\"\n return array_ops.squeeze(x, [axis])\n\n\ndef temporal_padding(x, padding=(1, 1)):\n \"\"\"Pads the middle dimension of a 3D tensor.\n\n Arguments:\n x: Tensor or variable.\n padding: Tuple of 2 integers, how many zeros to\n add at the start and end of dim 1.\n\n Returns:\n A padded 3D tensor.\n \"\"\"\n assert len(padding) == 2\n pattern = [[0, 0], [padding[0], padding[1]], [0, 0]]\n return array_ops.pad(x, pattern)\n\n\ndef spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None):\n \"\"\"Pads the 2nd and 3rd dimensions of a 4D tensor.\n\n Arguments:\n x: Tensor or variable.\n padding: Tuple of 2 tuples, padding pattern.\n data_format: One of `channels_last` or `channels_first`.\n\n Returns:\n A padded 4D tensor.\n\n Raises:\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n \"\"\"\n assert len(padding) == 2\n assert len(padding[0]) == 2\n assert len(padding[1]) == 2\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n if data_format == 'channels_first':\n pattern = [[0, 0], [0, 0], list(padding[0]), list(padding[1])]\n else:\n pattern = [[0, 0], list(padding[0]), list(padding[1]), [0, 0]]\n return array_ops.pad(x, pattern)\n\n\ndef spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None):\n \"\"\"Pads 5D tensor with zeros along the depth, height, width dimensions.\n\n Pads these dimensions with respectively\n \"padding[0]\", \"padding[1]\" and \"padding[2]\" zeros left and right.\n\n For 'channels_last' data_format,\n the 2nd, 3rd and 4th dimension will be padded.\n For 'channels_first' data_format,\n the 3rd, 4th and 5th dimension will be padded.\n\n Arguments:\n x: Tensor or variable.\n padding: Tuple of 3 tuples, padding pattern.\n data_format: One of `channels_last` or `channels_first`.\n\n Returns:\n A padded 5D tensor.\n\n Raises:\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n\n \"\"\"\n assert len(padding) == 3\n assert len(padding[0]) == 2\n assert len(padding[1]) == 2\n assert len(padding[2]) == 2\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n if data_format == 'channels_first':\n pattern = [[0, 0], [0, 0], [padding[0][0], padding[0][1]],\n [padding[1][0], padding[1][1]], [padding[2][0], padding[2][1]]]\n else:\n pattern = [[0, 0], [padding[0][0], padding[0][1]],\n [padding[1][0], padding[1][1]], [padding[2][0],\n padding[2][1]], [0, 0]]\n return array_ops.pad(x, pattern)\n\n\ndef stack(x, axis=0):\n \"\"\"Stacks a list of rank `R` tensors into a rank `R+1` tensor.\n\n Arguments:\n x: List of tensors.\n axis: Axis along which to perform stacking.\n\n Returns:\n A tensor.\n \"\"\"\n return array_ops.stack(x, axis=axis)\n\n\ndef one_hot(indices, num_classes):\n \"\"\"Computes the one-hot representation of an integer tensor.\n\n Arguments:\n indices: nD integer tensor of shape\n `(batch_size, dim1, dim2, ... dim(n-1))`\n num_classes: Integer, number of classes to consider.\n\n Returns:\n (n + 1)D one hot representation of the input\n with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`\n\n Returns:\n The one-hot tensor.\n \"\"\"\n return array_ops.one_hot(indices, depth=num_classes, axis=-1)\n\n\ndef reverse(x, axes):\n \"\"\"Reverse a tensor along the specified axes.\n\n Arguments:\n x: Tensor to reverse.\n axes: Integer or iterable of integers.\n Axes to reverse.\n\n Returns:\n A tensor.\n \"\"\"\n if isinstance(axes, int):\n axes = [axes]\n return array_ops.reverse(x, axes)\n\n\n# VALUE MANIPULATION\n\n\ndef get_value(x):\n \"\"\"Returns the value of a variable.\n\n Arguments:\n x: input variable.\n\n Returns:\n A Numpy array.\n \"\"\"\n return x.eval(session=get_session())\n\n\ndef batch_get_value(tensors):\n \"\"\"Returns the value of more than one tensor variable.\n\n Arguments:\n tensors: list of ops to run.\n\n Returns:\n A list of Numpy arrays.\n \"\"\"\n if tensors:\n return get_session().run(tensors)\n else:\n return []\n\n\ndef set_value(x, value):\n \"\"\"Sets the value of a variable, from a Numpy array.\n\n Arguments:\n x: Tensor to set to a new value.\n value: Value to set the tensor to, as a Numpy array\n (of the same shape).\n \"\"\"\n value = np.asarray(value, dtype=dtype(x))\n tf_dtype = dtypes_module.as_dtype(x.dtype.name.split('_')[0])\n if hasattr(x, '_assign_placeholder'):\n assign_placeholder = x._assign_placeholder\n assign_op = x._assign_op\n else:\n assign_placeholder = array_ops.placeholder(tf_dtype, shape=value.shape)\n assign_op = x.assign(assign_placeholder)\n x._assign_placeholder = assign_placeholder\n x._assign_op = assign_op\n get_session().run(assign_op, feed_dict={assign_placeholder: value})\n\n\ndef batch_set_value(tuples):\n \"\"\"Sets the values of many tensor variables at once.\n\n Arguments:\n tuples: a list of tuples `(tensor, value)`.\n `value` should be a Numpy array.\n \"\"\"\n if tuples:\n assign_ops = []\n feed_dict = {}\n for x, value in tuples:\n value = np.asarray(value, dtype=dtype(x))\n tf_dtype = dtypes_module.as_dtype(x.dtype.name.split('_')[0])\n if hasattr(x, '_assign_placeholder'):\n assign_placeholder = x._assign_placeholder\n assign_op = x._assign_op\n else:\n assign_placeholder = array_ops.placeholder(tf_dtype, shape=value.shape)\n assign_op = x.assign(assign_placeholder)\n x._assign_placeholder = assign_placeholder\n x._assign_op = assign_op\n assign_ops.append(assign_op)\n feed_dict[assign_placeholder] = value\n get_session().run(assign_ops, feed_dict=feed_dict)\n\n\ndef print_tensor(x, message=''):\n \"\"\"Prints `message` and the tensor value when evaluated.\n\n Note that `print_tensor` returns a new tensor identical to `x`\n which should be used in the following code. Otherwise the\n print operation is not taken into account during evaluation.\n\n Example:\n\n ```python\n >>> x = K.print_tensor(x, message=\"x is: \")\n ```\n\n Arguments:\n x: Tensor to print.\n message: Message to print jointly with the tensor.\n\n Returns:\n The same tensor `x`, unchanged.\n \"\"\"\n return logging_ops.Print(x, [x], message)\n\n\n# GRAPH MANIPULATION\n\n\nclass Function(object):\n \"\"\"Runs a computation graph.\n\n Arguments:\n inputs: Feed placeholders to the computation graph.\n outputs: Output tensors to fetch.\n updates: Additional update ops to be run at function call.\n name: a name to help users identify what this function does.\n \"\"\"\n\n def __init__(self, inputs, outputs, updates=None, name=None,\n **session_kwargs):\n updates = updates or []\n if not isinstance(inputs, (list, tuple)):\n raise TypeError('`inputs` to a TensorFlow backend function '\n 'should be a list or tuple.')\n if not isinstance(outputs, (list, tuple)):\n raise TypeError('`outputs` of a TensorFlow backend function '\n 'should be a list or tuple.')\n if not isinstance(updates, (list, tuple)):\n raise TypeError('`updates` in a TensorFlow backend function '\n 'should be a list or tuple.')\n self.inputs = list(inputs)\n self.outputs = list(outputs)\n with ops.control_dependencies(self.outputs):\n updates_ops = []\n for update in updates:\n if isinstance(update, tuple):\n p, new_p = update\n updates_ops.append(state_ops.assign(p, new_p))\n else:\n # assumed already an op\n updates_ops.append(update)\n self.updates_op = control_flow_ops.group(*updates_ops)\n self.name = name\n self.session_kwargs = session_kwargs\n\n def __call__(self, inputs):\n if not isinstance(inputs, (list, tuple)):\n raise TypeError('`inputs` should be a list or tuple.')\n feed_dict = {}\n for tensor, value in zip(self.inputs, inputs):\n if is_sparse(tensor):\n sparse_coo = value.tocoo()\n indices = np.concatenate((np.expand_dims(sparse_coo.row, 1),\n np.expand_dims(sparse_coo.col, 1)), 1)\n value = (indices, sparse_coo.data, sparse_coo.shape)\n feed_dict[tensor] = value\n session = get_session()\n updated = session.run(\n self.outputs + [self.updates_op],\n feed_dict=feed_dict,\n **self.session_kwargs)\n return updated[:len(self.outputs)]\n\n\ndef function(inputs, outputs, updates=None, **kwargs):\n \"\"\"Instantiates a Keras function.\n\n Arguments:\n inputs: List of placeholder tensors.\n outputs: List of output tensors.\n updates: List of update ops.\n **kwargs: Passed to `tf.Session.run`.\n\n Returns:\n Output values as Numpy arrays.\n\n Raises:\n ValueError: if invalid kwargs are passed in.\n \"\"\"\n if kwargs:\n for key in kwargs:\n if (key not in tf_inspect.getargspec(session_module.Session.run)[0] and\n key not in tf_inspect.getargspec(Function.__init__)[0]):\n msg = ('Invalid argument \"%s\" passed to K.function with Tensorflow '\n 'backend') % key\n raise ValueError(msg)\n return Function(inputs, outputs, updates=updates, **kwargs)\n\n\ndef gradients(loss, variables):\n \"\"\"Returns the gradients of `variables` w.r.t. `loss`.\n\n Arguments:\n loss: Scalar tensor to minimize.\n variables: List of variables.\n\n Returns:\n A gradients tensor.\n \"\"\"\n return gradients_module.gradients(\n loss, variables, colocate_gradients_with_ops=True)\n\n\ndef stop_gradient(variables):\n \"\"\"Returns `variables` but with zero gradient w.r.t. every other variable.\n\n Arguments:\n variables: Tensor or list of tensors to consider constant with respect\n to any other variable.\n\n\n Returns:\n A single tensor or a list of tensors (depending on the passed argument)\n that has no gradient with respect to any other variable.\n \"\"\"\n if isinstance(variables, (list, tuple)):\n return map(array_ops.stop_gradient, variables)\n return array_ops.stop_gradient(variables)\n\n\n# CONTROL FLOW\n\n\ndef rnn(step_function,\n inputs,\n initial_states,\n go_backwards=False,\n mask=None,\n constants=None,\n unroll=False):\n \"\"\"Iterates over the time dimension of a tensor.\n\n Arguments:\n step_function: RNN step function.\n Parameters;\n input; tensor with shape `(samples, ...)` (no time dimension),\n representing input for the batch of samples at a certain\n time step.\n states; list of tensors.\n Returns;\n output; tensor with shape `(samples, output_dim)`\n (no time dimension).\n new_states; list of tensors, same length and shapes\n as 'states'. The first state in the list must be the\n output tensor at the previous timestep.\n inputs: tensor of temporal data of shape `(samples, time, ...)`\n (at least 3D).\n initial_states: tensor with shape (samples, output_dim)\n (no time dimension),\n containing the initial values for the states used in\n the step function.\n go_backwards: boolean. If True, do the iteration over the time\n dimension in reverse order and return the reversed sequence.\n mask: binary tensor with shape `(samples, time, 1)`,\n with a zero for every element that is masked.\n constants: a list of constant values passed at each step.\n unroll: whether to unroll the RNN or to use a symbolic loop\n (`while_loop` or `scan` depending on backend).\n\n Returns:\n A tuple, `(last_output, outputs, new_states)`.\n last_output: the latest output of the rnn, of shape `(samples, ...)`\n outputs: tensor with shape `(samples, time, ...)` where each\n entry `outputs[s, t]` is the output of the step function\n at time `t` for sample `s`.\n new_states: list of tensors, latest states returned by\n the step function, of shape `(samples, ...)`.\n\n Raises:\n ValueError: if input dimension is less than 3.\n ValueError: if `unroll` is `True` but input timestep is not a fixed\n number.\n ValueError: if `mask` is provided (not `None`) but states is not provided\n (`len(states)` == 0).\n \"\"\"\n ndim = len(inputs.get_shape())\n if ndim < 3:\n raise ValueError('Input should be at least 3D.')\n axes = [1, 0] + list(range(2, ndim))\n inputs = array_ops.transpose(inputs, (axes))\n\n if mask is not None:\n if mask.dtype != dtypes_module.bool:\n mask = math_ops.cast(mask, dtypes_module.bool)\n if len(mask.get_shape()) == ndim - 1:\n mask = expand_dims(mask)\n mask = array_ops.transpose(mask, axes)\n\n if constants is None:\n constants = []\n\n global uses_learning_phase # pylint: disable=global-variable-undefined\n uses_learning_phase = False\n\n if unroll:\n if not inputs.get_shape()[0]:\n raise ValueError('Unrolling requires a ' 'fixed number of timesteps.')\n states = initial_states\n successive_states = []\n successive_outputs = []\n\n input_list = array_ops.unstack(inputs)\n if go_backwards:\n input_list.reverse()\n\n if mask is not None:\n mask_list = array_ops.unstack(mask)\n if go_backwards:\n mask_list.reverse()\n\n for inp, mask_t in zip(input_list, mask_list):\n output, new_states = step_function(inp, states + constants)\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase = True\n\n # tf.where needs its condition tensor\n # to be the same shape as its two\n # result tensors, but in our case\n # the condition (mask) tensor is\n # (nsamples, 1), and A and B are (nsamples, ndimensions).\n # So we need to\n # broadcast the mask to match the shape of A and B.\n # That's what the tile call does,\n # it just repeats the mask along its second dimension\n # n times.\n tiled_mask_t = array_ops.tile(mask_t,\n array_ops.stack(\n [1, array_ops.shape(output)[1]]))\n\n if not successive_outputs:\n prev_output = zeros_like(output)\n else:\n prev_output = successive_outputs[-1]\n\n output = array_ops.where(tiled_mask_t, output, prev_output)\n\n return_states = []\n for state, new_state in zip(states, new_states):\n # (see earlier comment for tile explanation)\n tiled_mask_t = array_ops.tile(mask_t,\n array_ops.stack(\n [1,\n array_ops.shape(new_state)[1]]))\n return_states.append(array_ops.where(tiled_mask_t, new_state, state))\n states = return_states\n successive_outputs.append(output)\n successive_states.append(states)\n last_output = successive_outputs[-1]\n new_states = successive_states[-1]\n outputs = array_ops.stack(successive_outputs)\n else:\n for inp in input_list:\n output, states = step_function(inp, states + constants)\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase = True\n successive_outputs.append(output)\n successive_states.append(states)\n last_output = successive_outputs[-1]\n new_states = successive_states[-1]\n outputs = array_ops.stack(successive_outputs)\n\n else:\n if go_backwards:\n inputs = reverse(inputs, 0)\n\n states = tuple(initial_states)\n\n time_steps = array_ops.shape(inputs)[0]\n outputs, _ = step_function(inputs[0], initial_states + constants)\n output_ta = tensor_array_ops.TensorArray(\n dtype=outputs.dtype, size=time_steps, tensor_array_name='output_ta')\n input_ta = tensor_array_ops.TensorArray(\n dtype=inputs.dtype, size=time_steps, tensor_array_name='input_ta')\n input_ta = input_ta.unstack(inputs)\n time = constant_op.constant(0, dtype='int32', name='time')\n\n if mask is not None:\n if not states:\n raise ValueError('No initial states provided! '\n 'When using masking in an RNN, you should '\n 'provide initial states '\n '(and your step function should return '\n 'as its first state at time `t` '\n 'the output at time `t-1`).')\n if go_backwards:\n mask = reverse(mask, 0)\n\n mask_ta = tensor_array_ops.TensorArray(\n dtype=dtypes_module.bool,\n size=time_steps,\n tensor_array_name='mask_ta')\n mask_ta = mask_ta.unstack(mask)\n\n def _step(time, output_ta_t, *states):\n \"\"\"RNN step function.\n\n Arguments:\n time: Current timestep value.\n output_ta_t: TensorArray.\n *states: List of states.\n\n Returns:\n Tuple: `(time + 1,output_ta_t) + tuple(new_states)`\n \"\"\"\n current_input = input_ta.read(time)\n mask_t = mask_ta.read(time)\n output, new_states = step_function(current_input,\n tuple(states) + tuple(constants))\n if getattr(output, '_uses_learning_phase', False):\n global uses_learning_phase # pylint: disable=global-variable-undefined\n uses_learning_phase = True\n for state, new_state in zip(states, new_states):\n new_state.set_shape(state.get_shape())\n tiled_mask_t = array_ops.tile(mask_t,\n array_ops.stack(\n [1, array_ops.shape(output)[1]]))\n output = array_ops.where(tiled_mask_t, output, states[0])\n new_states = [\n array_ops.where(tiled_mask_t, new_states[i], states[i])\n for i in range(len(states))\n ]\n output_ta_t = output_ta_t.write(time, output)\n return (time + 1, output_ta_t) + tuple(new_states)\n else:\n\n def _step(time, output_ta_t, *states):\n \"\"\"RNN step function.\n\n Arguments:\n time: Current timestep value.\n output_ta_t: TensorArray.\n *states: List of states.\n\n Returns:\n Tuple: `(time + 1,output_ta_t) + tuple(new_states)`\n \"\"\"\n current_input = input_ta.read(time)\n output, new_states = step_function(current_input,\n tuple(states) + tuple(constants))\n if getattr(output, '_uses_learning_phase', False):\n global uses_learning_phase # pylint: disable=global-variable-undefined\n uses_learning_phase = True\n for state, new_state in zip(states, new_states):\n new_state.set_shape(state.get_shape())\n output_ta_t = output_ta_t.write(time, output)\n return (time + 1, output_ta_t) + tuple(new_states)\n\n final_outputs = control_flow_ops.while_loop(\n cond=lambda time, *_: time < time_steps,\n body=_step,\n loop_vars=(time, output_ta) + states,\n parallel_iterations=32,\n swap_memory=True)\n last_time = final_outputs[0]\n output_ta = final_outputs[1]\n new_states = final_outputs[2:]\n\n outputs = output_ta.stack()\n last_output = output_ta.read(last_time - 1)\n\n axes = [1, 0] + list(range(2, len(outputs.get_shape())))\n outputs = array_ops.transpose(outputs, axes)\n last_output._uses_learning_phase = uses_learning_phase\n return last_output, outputs, new_states\n\n\ndef switch(condition, then_expression, else_expression):\n \"\"\"Switches between two operations depending on a scalar value.\n\n Note that both `then_expression` and `else_expression`\n should be symbolic tensors of the *same shape*.\n\n Arguments:\n condition: tensor (`int` or `bool`).\n then_expression: either a tensor, or a callable that returns a tensor.\n else_expression: either a tensor, or a callable that returns a tensor.\n\n Returns:\n The selected tensor.\n\n Raises:\n ValueError: If rank of `condition` is greater than rank of expressions.\n \"\"\"\n if condition.dtype != dtypes_module.bool:\n condition = math_ops.cast(condition, 'bool')\n cond_ndim = ndim(condition)\n if not cond_ndim:\n if not callable(then_expression):\n\n def then_expression_fn():\n return then_expression\n else:\n then_expression_fn = then_expression\n if not callable(else_expression):\n\n def else_expression_fn():\n return else_expression\n else:\n else_expression_fn = else_expression\n x = control_flow_ops.cond(condition, then_expression_fn, else_expression_fn)\n else:\n # tf.where needs its condition tensor\n # to be the same shape as its two\n # result tensors\n if callable(then_expression):\n then_expression = then_expression()\n if callable(else_expression):\n else_expression = else_expression()\n expr_ndim = ndim(then_expression)\n if cond_ndim > expr_ndim:\n raise ValueError('Rank of `condition` should be less than or'\n ' equal to rank of `then_expression` and '\n '`else_expression`. ndim(condition)=' + str(cond_ndim) +\n ', ndim(then_expression)'\n '=' + str(expr_ndim))\n if cond_ndim > 1:\n ndim_diff = expr_ndim - cond_ndim\n cond_shape = array_ops.concat(\n [array_ops.shape(condition), [1] * ndim_diff], axis=0)\n condition = array_ops.reshape(condition, cond_shape)\n expr_shape = array_ops.shape(then_expression)\n shape_diff = expr_shape - cond_shape\n tile_shape = array_ops.where(shape_diff > 0, expr_shape,\n array_ops.ones_like(expr_shape))\n condition = array_ops.tile(condition, tile_shape)\n x = array_ops.where(condition, then_expression, else_expression)\n return x\n\n\ndef in_train_phase(x, alt, training=None):\n \"\"\"Selects `x` in train phase, and `alt` otherwise.\n\n Note that `alt` should have the *same shape* as `x`.\n\n Arguments:\n x: What to return in train phase\n (tensor or callable that returns a tensor).\n alt: What to return otherwise\n (tensor or callable that returns a tensor).\n training: Optional scalar tensor\n (or Python boolean, or Python integer)\n specifying the learning phase.\n\n Returns:\n Either `x` or `alt` based on the `training` flag.\n the `training` flag defaults to `K.learning_phase()`.\n \"\"\"\n if training is None:\n training = learning_phase()\n uses_learning_phase = True\n else:\n uses_learning_phase = False\n\n if training is 1 or training is True:\n if callable(x):\n return x()\n else:\n return x\n\n elif training is 0 or training is False:\n if callable(alt):\n return alt()\n else:\n return alt\n\n # else: assume learning phase is a placeholder tensor.\n x = switch(training, x, alt)\n if uses_learning_phase:\n x._uses_learning_phase = True\n return x\n\n\ndef in_test_phase(x, alt, training=None):\n \"\"\"Selects `x` in test phase, and `alt` otherwise.\n\n Note that `alt` should have the *same shape* as `x`.\n\n Arguments:\n x: What to return in test phase\n (tensor or callable that returns a tensor).\n alt: What to return otherwise\n (tensor or callable that returns a tensor).\n training: Optional scalar tensor\n (or Python boolean, or Python integer)\n specifying the learning phase.\n\n Returns:\n Either `x` or `alt` based on `K.learning_phase`.\n \"\"\"\n return in_train_phase(alt, x, training=training)\n\n\n# NN OPERATIONS\n\n\ndef relu(x, alpha=0., max_value=None):\n \"\"\"Rectified linear unit.\n\n With default values, it returns element-wise `max(x, 0)`.\n\n Arguments:\n x: A tensor or variable.\n alpha: A scalar, slope of negative section (default=`0.`).\n max_value: Saturation threshold.\n\n Returns:\n A tensor.\n \"\"\"\n if alpha != 0.:\n negative_part = nn.relu(-x)\n x = nn.relu(x)\n if max_value is not None:\n max_value = _to_tensor(max_value, x.dtype.base_dtype)\n zero = _to_tensor(0., x.dtype.base_dtype)\n x = clip_ops.clip_by_value(x, zero, max_value)\n if alpha != 0.:\n alpha = _to_tensor(alpha, x.dtype.base_dtype)\n x -= alpha * negative_part\n return x\n\n\ndef elu(x, alpha=1.):\n \"\"\"Exponential linear unit.\n\n Arguments:\n x: A tensor or variable to compute the activation function for.\n alpha: A scalar, slope of positive section.\n\n Returns:\n A tensor.\n \"\"\"\n res = nn.elu(x)\n if alpha == 1:\n return res\n else:\n return array_ops.where(x > 0, res, alpha * res)\n\n\ndef softmax(x):\n \"\"\"Softmax of a tensor.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.softmax(x)\n\n\ndef softplus(x):\n \"\"\"Softplus of a tensor.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.softplus(x)\n\n\ndef softsign(x):\n \"\"\"Softsign of a tensor.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.softsign(x)\n\n\ndef categorical_crossentropy(target, output, from_logits=False):\n \"\"\"Categorical crossentropy between an output tensor and a target tensor.\n\n Arguments:\n target: A tensor of the same shape as `output`.\n output: A tensor resulting from a softmax\n (unless `from_logits` is True, in which\n case `output` is expected to be the logits).\n from_logits: Boolean, whether `output` is the\n result of a softmax, or is a tensor of logits.\n\n Returns:\n Output tensor.\n \"\"\"\n # Note: nn.softmax_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n # scale preds so that the class probas of each sample sum to 1\n output /= math_ops.reduce_sum(\n output, axis=len(output.get_shape()) - 1, keep_dims=True)\n # manual computation of crossentropy\n epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = clip_ops.clip_by_value(output, epsilon_, 1. - epsilon_)\n return -math_ops.reduce_sum(\n target * math_ops.log(output),\n axis=len(output.get_shape()) - 1)\n else:\n return nn.softmax_cross_entropy_with_logits(labels=target, logits=output)\n\n\ndef sparse_categorical_crossentropy(target, output, from_logits=False):\n \"\"\"Categorical crossentropy with integer targets.\n\n Arguments:\n target: An integer tensor.\n output: A tensor resulting from a softmax\n (unless `from_logits` is True, in which\n case `output` is expected to be the logits).\n from_logits: Boolean, whether `output` is the\n result of a softmax, or is a tensor of logits.\n\n Returns:\n Output tensor.\n \"\"\"\n # Note: nn.sparse_softmax_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_)\n output = math_ops.log(output)\n\n output_shape = output.get_shape()\n targets = cast(flatten(target), 'int64')\n logits = array_ops.reshape(output, [-1, int(output_shape[-1])])\n res = nn.sparse_softmax_cross_entropy_with_logits(\n labels=targets, logits=logits)\n if len(output_shape) == 3:\n # if our output includes timesteps we need to reshape\n return array_ops.reshape(res, array_ops.shape(output)[:-1])\n else:\n return res\n\n\ndef binary_crossentropy(target, output, from_logits=False):\n \"\"\"Binary crossentropy between an output tensor and a target tensor.\n\n Arguments:\n target: A tensor with the same shape as `output`.\n output: A tensor.\n from_logits: Whether `output` is expected to be a logits tensor.\n By default, we consider that `output`\n encodes a probability distribution.\n\n Returns:\n A tensor.\n \"\"\"\n # Note: nn.softmax_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n # transform back to logits\n epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_)\n output = math_ops.log(output / (1 - output))\n return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)\n\n\ndef sigmoid(x):\n \"\"\"Element-wise sigmoid.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.sigmoid(x)\n\n\ndef hard_sigmoid(x):\n \"\"\"Segment-wise linear approximation of sigmoid.\n\n Faster than sigmoid.\n Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.\n In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n x = (0.2 * x) + 0.5\n zero = _to_tensor(0., x.dtype.base_dtype)\n one = _to_tensor(1., x.dtype.base_dtype)\n x = clip_ops.clip_by_value(x, zero, one)\n return x\n\n\ndef tanh(x):\n \"\"\"Element-wise tanh.\n\n Arguments:\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.tanh(x)\n\n\ndef dropout(x, level, noise_shape=None, seed=None):\n \"\"\"Sets entries in `x` to zero at random, while scaling the entire tensor.\n\n Arguments:\n x: tensor\n level: fraction of the entries in the tensor\n that will be set to 0.\n noise_shape: shape for randomly generated keep/drop flags,\n must be broadcastable to the shape of `x`\n seed: random seed to ensure determinism.\n\n Returns:\n A tensor.\n \"\"\"\n retain_prob = 1. - level\n if seed is None:\n seed = np.random.randint(10e6)\n # the dummy 1. works around a TF bug\n # (float32_ref vs. float32 incompatibility)\n return nn.dropout(x * 1., retain_prob, noise_shape, seed=seed)\n\n\ndef l2_normalize(x, axis=None):\n \"\"\"Normalizes a tensor wrt the L2 norm alongside the specified axis.\n\n Arguments:\n x: Tensor or variable.\n axis: axis along which to perform normalization.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.l2_normalize(x, dim=axis)\n\n\ndef in_top_k(predictions, targets, k):\n \"\"\"Returns whether the `targets` are in the top `k` `predictions`.\n\n Arguments:\n predictions: A tensor of shape `(batch_size, classes)` and type `float32`.\n targets: A 1D tensor of length `batch_size` and type `int32` or `int64`.\n k: An `int`, number of top elements to consider.\n\n Returns:\n A 1D tensor of length `batch_size` and type `bool`.\n `output[i]` is `True` if `predictions[i, targets[i]]` is within top-`k`\n values of `predictions[i]`.\n \"\"\"\n return nn.in_top_k(predictions, targets, k)\n\n\n# CONVOLUTIONS\n\n\ndef _preprocess_conv2d_input(x, data_format):\n \"\"\"Transpose and cast the input before the conv2d.\n\n Arguments:\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n Returns:\n A tensor.\n \"\"\"\n tf_data_format = 'NHWC'\n if data_format == 'channels_first':\n if not _has_nchw_support():\n x = array_ops.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC\n else:\n tf_data_format = 'NCHW'\n return x, tf_data_format\n\n\ndef _preprocess_conv3d_input(x, data_format):\n \"\"\"Transpose and cast the input before the conv3d.\n\n Arguments:\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n Returns:\n A tensor.\n \"\"\"\n tf_data_format = 'NDHWC'\n if data_format == 'channels_first':\n if not _has_nchw_support():\n x = array_ops.transpose(x, (0, 2, 3, 4, 1))\n else:\n tf_data_format = 'NCDHW'\n return x, tf_data_format\n\n\ndef _preprocess_padding(padding):\n \"\"\"Convert keras' padding to tensorflow's padding.\n\n Arguments:\n padding: string, one of 'same' , 'valid'\n\n Returns:\n a string, one of 'SAME', 'VALID'.\n\n Raises:\n ValueError: if invalid `padding'`\n \"\"\"\n if padding == 'same':\n padding = 'SAME'\n elif padding == 'valid':\n padding = 'VALID'\n else:\n raise ValueError('Invalid padding:', padding)\n return padding\n\n\ndef conv1d(x,\n kernel,\n strides=1,\n padding='valid',\n data_format=None,\n dilation_rate=1):\n \"\"\"1D convolution.\n\n Arguments:\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: stride integer.\n padding: string, `\"same\"`, `\"causal\"` or `\"valid\"`.\n data_format: string, one of \"channels_last\", \"channels_first\".\n dilation_rate: integer dilate rate.\n\n Returns:\n A tensor, result of 1D convolution.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n kernel_shape = kernel.get_shape().as_list()\n if padding == 'causal':\n # causal (dilated) convolution:\n left_pad = dilation_rate * (kernel_shape[0] - 1)\n x = temporal_padding(x, (left_pad, 0))\n padding = 'valid'\n padding = _preprocess_padding(padding)\n if data_format == 'channels_last':\n tf_data_format = 'NWC'\n else:\n tf_data_format = 'NCW'\n x = nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=(dilation_rate,),\n strides=(strides,),\n padding=padding,\n data_format=tf_data_format)\n return x\n\n\ndef conv2d(x,\n kernel,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1)):\n \"\"\"2D convolution.\n\n Arguments:\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow data format\n for inputs/kernels/outputs.\n dilation_rate: tuple of 2 integers.\n\n Returns:\n A tensor, result of 2D convolution.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n x = nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=dilation_rate,\n strides=strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef conv2d_transpose(x,\n kernel,\n output_shape,\n strides=(1, 1),\n padding='valid',\n data_format=None):\n \"\"\"2D deconvolution (i.e.\n\n transposed convolution).\n\n Arguments:\n x: Tensor or variable.\n kernel: kernel tensor.\n output_shape: 1D int tensor for the output shape.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n\n Returns:\n A tensor, result of transposed 2D convolution.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n if isinstance(output_shape, (tuple, list)):\n output_shape = array_ops.stack(output_shape)\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n output_shape = (output_shape[0], output_shape[2], output_shape[3],\n output_shape[1])\n if output_shape[0] is None:\n output_shape = (array_ops.shape(x)[0],) + tuple(output_shape[1:])\n output_shape = array_ops.stack(list(output_shape))\n\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = nn.conv2d_transpose(\n x,\n kernel,\n output_shape,\n strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef separable_conv2d(x,\n depthwise_kernel,\n pointwise_kernel,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1)):\n \"\"\"2D convolution with separable filters.\n\n Arguments:\n x: input tensor\n depthwise_kernel: convolution kernel for the depthwise convolution.\n pointwise_kernel: kernel for the 1x1 convolution.\n strides: strides tuple (length 2).\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: tuple of integers,\n dilation rates for the separable convolution.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = nn.separable_conv2d(\n x,\n depthwise_kernel,\n pointwise_kernel,\n strides=strides,\n padding=padding,\n rate=dilation_rate,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef depthwise_conv2d(x,\n depthwise_kernel,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1)):\n \"\"\"2D convolution with separable filters.\n\n Arguments:\n x: input tensor\n depthwise_kernel: convolution kernel for the depthwise convolution.\n strides: strides tuple (length 2).\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: tuple of integers,\n dilation rates for the separable convolution.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = nn.depthwise_conv2d(\n x,\n depthwise_kernel,\n strides=strides,\n padding=padding,\n rate=dilation_rate,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef conv3d(x,\n kernel,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1, 1)):\n \"\"\"3D convolution.\n\n Arguments:\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n dilation_rate: tuple of 3 integers.\n\n Returns:\n A tensor, result of 3D convolution.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n padding = _preprocess_padding(padding)\n x = nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=dilation_rate,\n strides=strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = array_ops.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef conv3d_transpose(x,\n kernel,\n output_shape,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None):\n \"\"\"3D deconvolution (i.e.\n\n transposed convolution).\n\n Arguments:\n x: input tensor.\n kernel: kernel tensor.\n output_shape: 1D int tensor for the output shape.\n strides: strides tuple.\n padding: string, \"same\" or \"valid\".\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n\n Returns:\n A tensor, result of transposed 3D convolution.\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n if isinstance(output_shape, (tuple, list)):\n output_shape = array_ops.stack(output_shape)\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n output_shape = (output_shape[0], output_shape[2], output_shape[3],\n output_shape[4], output_shape[1])\n if output_shape[0] is None:\n output_shape = (array_ops.shape(x)[0],) + tuple(output_shape[1:])\n output_shape = array_ops.stack(list(output_shape))\n\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NDHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = nn.conv3d_transpose(\n x,\n kernel,\n output_shape,\n strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = array_ops.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef pool2d(x,\n pool_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n pool_mode='max'):\n \"\"\"2D Pooling.\n\n Arguments:\n x: Tensor or variable.\n pool_size: tuple of 2 integers.\n strides: tuple of 2 integers.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n pool_mode: string, `\"max\"` or `\"avg\"`.\n\n Returns:\n A tensor, result of 2D pooling.\n\n Raises:\n ValueError: if `data_format` is neither `\"channels_last\"` or\n `\"channels_first\"`.\n ValueError: if `pool_mode` is neither `\"max\"` or `\"avg\"`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n pool_size = (1,) + pool_size + (1,)\n else:\n strides = (1, 1) + strides\n pool_size = (1, 1) + pool_size\n\n if pool_mode == 'max':\n x = nn.max_pool(\n x, pool_size, strides, padding=padding, data_format=tf_data_format)\n elif pool_mode == 'avg':\n x = nn.avg_pool(\n x, pool_size, strides, padding=padding, data_format=tf_data_format)\n else:\n raise ValueError('Invalid pooling mode:', pool_mode)\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef pool3d(x,\n pool_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None,\n pool_mode='max'):\n \"\"\"3D Pooling.\n\n Arguments:\n x: Tensor or variable.\n pool_size: tuple of 3 integers.\n strides: tuple of 3 integers.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n pool_mode: string, `\"max\"` or `\"avg\"`.\n\n Returns:\n A tensor, result of 3D pooling.\n\n Raises:\n ValueError: if `data_format` is neither `\"channels_last\"` or\n `\"channels_first\"`.\n ValueError: if `pool_mode` is neither `\"max\"` or `\"avg\"`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NDHWC':\n strides = (1,) + strides + (1,)\n pool_size = (1,) + pool_size + (1,)\n else:\n strides = (1, 1) + strides\n pool_size = (1, 1) + pool_size\n\n if pool_mode == 'max':\n x = nn.max_pool3d(\n x, pool_size, strides, padding=padding, data_format=tf_data_format)\n elif pool_mode == 'avg':\n x = nn.avg_pool3d(\n x, pool_size, strides, padding=padding, data_format=tf_data_format)\n else:\n raise ValueError('Invalid pooling mode:', pool_mode)\n\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = array_ops.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef local_conv1d(inputs, kernel, kernel_size, strides, data_format=None):\n \"\"\"Apply 1D conv with un-shared weights.\n\n Arguments:\n inputs: 3D tensor with shape: (batch_size, steps, input_dim)\n kernel: the unshared weight for convolution,\n with shape (output_length, feature_dim, filters)\n kernel_size: a tuple of a single integer,\n specifying the length of the 1D convolution window\n strides: a tuple of a single integer,\n specifying the stride length of the convolution\n data_format: the data format, channels_first or channels_last\n\n Returns:\n the tensor after 1d conv with un-shared weights, with shape (batch_size,\n output_length, filters)\n\n Raises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n stride = strides[0]\n kernel_shape = int_shape(kernel)\n output_length = kernel_shape[0]\n feature_dim = kernel_shape[1]\n\n xs = []\n for i in range(output_length):\n slice_length = slice(i * stride, i * stride + kernel_size[0])\n xs.append(reshape(inputs[:, slice_length, :], (1, -1, feature_dim)))\n x_aggregate = concatenate(xs, axis=0)\n # Shape: `(output_length, batch_size, filters)`.\n output = batch_dot(x_aggregate, kernel)\n return permute_dimensions(output, (1, 0, 2))\n\n\ndef local_conv2d(inputs,\n kernel,\n kernel_size,\n strides,\n output_shape,\n data_format=None):\n \"\"\"Apply 2D conv with un-shared weights.\n\n Arguments:\n inputs: 4D tensor with shape:\n (batch_size, filters, new_rows, new_cols)\n if data_format='channels_first'\n or 4D tensor with shape:\n (batch_size, new_rows, new_cols, filters)\n if data_format='channels_last'.\n kernel: the unshared weight for convolution,\n with shape (output_items, feature_dim, filters)\n kernel_size: a tuple of 2 integers, specifying the\n width and height of the 2D convolution window.\n strides: a tuple of 2 integers, specifying the strides\n of the convolution along the width and height.\n output_shape: a tuple with (output_row, output_col)\n data_format: the data format, channels_first or channels_last\n\n Returns:\n A 4d tensor with shape:\n (batch_size, filters, new_rows, new_cols)\n if data_format='channels_first'\n or 4D tensor with shape:\n (batch_size, new_rows, new_cols, filters)\n if data_format='channels_last'.\n\n Raises:\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n\n stride_row, stride_col = strides\n output_row, output_col = output_shape\n kernel_shape = int_shape(kernel)\n feature_dim = kernel_shape[1]\n filters = kernel_shape[2]\n\n xs = []\n for i in range(output_row):\n for j in range(output_col):\n slice_row = slice(i * stride_row, i * stride_row + kernel_size[0])\n slice_col = slice(j * stride_col, j * stride_col + kernel_size[1])\n if data_format == 'channels_first':\n xs.append(\n reshape(inputs[:, :, slice_row, slice_col], (1, -1, feature_dim)))\n else:\n xs.append(\n reshape(inputs[:, slice_row, slice_col, :], (1, -1, feature_dim)))\n\n x_aggregate = concatenate(xs, axis=0)\n output = batch_dot(x_aggregate, kernel)\n output = reshape(output, (output_row, output_col, -1, filters))\n\n if data_format == 'channels_first':\n output = permute_dimensions(output, (2, 3, 0, 1))\n else:\n output = permute_dimensions(output, (2, 0, 1, 3))\n return output\n\n\ndef bias_add(x, bias, data_format=None):\n \"\"\"Adds a bias vector to a tensor.\n\n Arguments:\n x: Tensor or variable.\n bias: Bias tensor to add.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: In one of the two cases below:\n 1. invalid `data_format` argument.\n 2. invalid bias shape.\n the bias should be either a vector or\n a tensor with ndim(x) - 1 dimension\n \"\"\"\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format ' + str(data_format))\n bias_shape = int_shape(bias)\n if len(bias_shape) != 1 and len(bias_shape) != ndim(x) - 1:\n raise ValueError(\n 'Unexpected bias dimensions %d, expect to be 1 or %d dimensions' %\n (len(bias_shape), ndim(x)))\n if ndim(x) == 5:\n if data_format == 'channels_first':\n if len(bias_shape) == 1:\n x += reshape(bias, (1, bias_shape[0], 1, 1, 1))\n else:\n x += reshape(bias, (1, bias_shape[3]) + bias_shape[:3])\n elif data_format == 'channels_last':\n if len(bias_shape) == 1:\n x += reshape(bias, (1, 1, 1, bias_shape[0]))\n else:\n x += reshape(bias, (1,) + bias_shape)\n elif ndim(x) == 4:\n if data_format == 'channels_first':\n if len(bias_shape) == 1:\n x += reshape(bias, (1, bias_shape[0], 1, 1))\n else:\n x += reshape(bias, (1, bias_shape[2]) + bias_shape[:2])\n elif data_format == 'channels_last':\n if len(bias_shape) == 1:\n x = nn.bias_add(x, bias, data_format='NHWC')\n else:\n x += reshape(bias, (1,) + bias_shape)\n elif ndim(x) == 3:\n if data_format == 'channels_first':\n if len(bias_shape) == 1:\n x += reshape(bias, (1, bias_shape[0], 1))\n else:\n x += reshape(bias, (1, bias_shape[1], bias_shape[0]))\n elif data_format == 'channels_last':\n if len(bias_shape) == 1:\n x += reshape(bias, (1, 1, bias_shape[0]))\n else:\n x += reshape(bias, (1,) + bias_shape)\n else:\n x = nn.bias_add(x, bias)\n return x\n\n\n# RANDOMNESS\n\n\ndef random_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with normal distribution of values.\n\n Arguments:\n shape: A tuple of integers, the shape of tensor to create.\n mean: A float, mean of the normal distribution to draw samples.\n stddev: A float, standard deviation of the normal distribution\n to draw samples.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n Returns:\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return random_ops.random_normal(\n shape, mean=mean, stddev=stddev, dtype=dtype, seed=seed)\n\n\ndef random_uniform(shape, minval=0.0, maxval=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with uniform distribution of values.\n\n Arguments:\n shape: A tuple of integers, the shape of tensor to create.\n minval: A float, lower boundary of the uniform distribution\n to draw samples.\n maxval: A float, upper boundary of the uniform distribution\n to draw samples.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n Returns:\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return random_ops.random_uniform(\n shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed)\n\n\ndef random_binomial(shape, p=0.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with random binomial distribution of values.\n\n Arguments:\n shape: A tuple of integers, the shape of tensor to create.\n p: A float, `0. <= p <= 1`, probability of binomial distribution.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n Returns:\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return array_ops.where(\n random_ops.random_uniform(shape, dtype=dtype, seed=seed) <= p,\n array_ops.ones(shape, dtype=dtype), array_ops.zeros(shape, dtype=dtype))\n\n\ndef truncated_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with truncated random normal distribution of values.\n\n The generated values follow a normal distribution\n with specified mean and standard deviation,\n except that values whose magnitude is more than\n two standard deviations from the mean are dropped and re-picked.\n\n Arguments:\n shape: A tuple of integers, the shape of tensor to create.\n mean: Mean of the values.\n stddev: Standard deviation of the values.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n Returns:\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return random_ops.truncated_normal(\n shape, mean, stddev, dtype=dtype, seed=seed)\n\n\n# CTC\n# TensorFlow has a native implementation, but it uses sparse tensors\n# and therefore requires a wrapper for Keras. The functions below convert\n# dense to sparse tensors and also wraps up the beam search code that is\n# in TensorFlow's CTC implementation\n\n\ndef ctc_label_dense_to_sparse(labels, label_lengths):\n \"\"\"Converts CTC labels from dense to sparse.\n\n Arguments:\n labels: dense CTC labels.\n label_lengths: length of the labels.\n\n Returns:\n A sparse tensor representation of the labels.\n \"\"\"\n label_shape = array_ops.shape(labels)\n num_batches_tns = array_ops.stack([label_shape[0]])\n max_num_labels_tns = array_ops.stack([label_shape[1]])\n\n def range_less_than(_, current_input):\n return array_ops.expand_dims(\n math_ops.range(label_shape[1]), 0) < array_ops.fill(\n max_num_labels_tns, current_input)\n\n init = math_ops.cast(\n array_ops.fill([1, label_shape[1]], 0), dtypes_module.bool)\n dense_mask = functional_ops.scan(\n range_less_than, label_lengths, initializer=init, parallel_iterations=1)\n dense_mask = dense_mask[:, 0, :]\n\n label_array = array_ops.reshape(\n array_ops.tile(math_ops.range(0, label_shape[1]), num_batches_tns),\n label_shape)\n label_ind = array_ops.boolean_mask(label_array, dense_mask)\n\n batch_array = array_ops.transpose(\n array_ops.reshape(\n array_ops.tile(math_ops.range(0, label_shape[0]), max_num_labels_tns),\n reverse(label_shape, 0)))\n batch_ind = array_ops.boolean_mask(batch_array, dense_mask)\n indices = array_ops.transpose(\n array_ops.reshape(concatenate([batch_ind, label_ind], axis=0), [2, -1]))\n\n vals_sparse = array_ops.gather_nd(labels, indices)\n\n return sparse_tensor.SparseTensor(\n math_ops.to_int64(indices), vals_sparse, math_ops.to_int64(label_shape))\n\n\ndef ctc_batch_cost(y_true, y_pred, input_length, label_length):\n \"\"\"Runs CTC loss algorithm on each batch element.\n\n Arguments:\n y_true: tensor `(samples, max_string_length)`\n containing the truth labels.\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_pred`.\n label_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_true`.\n\n Returns:\n Tensor with shape (samples,1) containing the\n CTC loss of each element.\n \"\"\"\n label_length = math_ops.to_int32(array_ops.squeeze(label_length))\n input_length = math_ops.to_int32(array_ops.squeeze(input_length))\n sparse_labels = math_ops.to_int32(\n ctc_label_dense_to_sparse(y_true, label_length))\n\n y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + 1e-8)\n\n return array_ops.expand_dims(\n ctc.ctc_loss(\n inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1)\n\n\ndef ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1):\n \"\"\"Decodes the output of a softmax.\n\n Can use either greedy search (also known as best path)\n or a constrained dictionary search.\n\n Arguments:\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, )` containing the sequence length for\n each batch item in `y_pred`.\n greedy: perform much faster best-path search if `true`.\n This does not use a dictionary.\n beam_width: if `greedy` is `false`: a beam search decoder will be used\n with a beam of this width.\n top_paths: if `greedy` is `false`,\n how many of the most probable paths will be returned.\n\n Returns:\n Tuple:\n List: if `greedy` is `true`, returns a list of one element that\n contains the decoded sequence.\n If `false`, returns the `top_paths` most probable\n decoded sequences.\n Important: blank labels are returned as `-1`.\n Tensor `(top_paths, )` that contains\n the log probability of each decoded sequence.\n \"\"\"\n y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + 1e-8)\n input_length = math_ops.to_int32(input_length)\n\n if greedy:\n (decoded, log_prob) = ctc.ctc_greedy_decoder(\n inputs=y_pred, sequence_length=input_length)\n else:\n (decoded, log_prob) = ctc.ctc_beam_search_decoder(\n inputs=y_pred,\n sequence_length=input_length,\n beam_width=beam_width,\n top_paths=top_paths)\n decoded_dense = [\n sparse_ops.sparse_to_dense(\n st.indices, st.dense_shape, st.values, default_value=-1)\n for st in decoded\n ]\n return (decoded_dense, log_prob)\n\n\n# HIGH ORDER FUNCTIONS\n\n\ndef map_fn(fn, elems, name=None, dtype=None):\n \"\"\"Map the function fn over the elements elems and return the outputs.\n\n Arguments:\n fn: Callable that will be called upon each element in elems\n elems: tensor\n name: A string name for the map node in the graph\n dtype: Output data type.\n\n Returns:\n Tensor with dtype `dtype`.\n \"\"\"\n return functional_ops.map_fn(fn, elems, name=name, dtype=dtype)\n\n\ndef foldl(fn, elems, initializer=None, name=None):\n \"\"\"Reduce elems using fn to combine them from left to right.\n\n Arguments:\n fn: Callable that will be called upon each element in elems and an\n accumulator, for instance `lambda acc, x: acc + x`\n elems: tensor\n initializer: The first value used (`elems[0]` in case of None)\n name: A string name for the foldl node in the graph\n\n Returns:\n Tensor with same type and shape as `initializer`.\n \"\"\"\n return functional_ops.foldl(fn, elems, initializer=initializer, name=name)\n\n\ndef foldr(fn, elems, initializer=None, name=None):\n \"\"\"Reduce elems using fn to combine them from right to left.\n\n Arguments:\n fn: Callable that will be called upon each element in elems and an\n accumulator, for instance `lambda acc, x: acc + x`\n elems: tensor\n initializer: The first value used (`elems[-1]` in case of None)\n name: A string name for the foldr node in the graph\n\n Returns:\n Same type and shape as initializer\n \"\"\"\n return functional_ops.foldr(fn, elems, initializer=initializer, name=name)\n\n\n# Load Keras default configuration from config file if present.\n_keras_base_dir = os.path.expanduser('~')\n_keras_dir = os.path.join(_keras_base_dir, '.keras')\n_config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json'))\nif os.path.exists(_config_path):\n try:\n _config = json.load(open(_config_path))\n except ValueError:\n _config = {}\n _floatx = _config.get('floatx', floatx())\n assert _floatx in {'float16', 'float32', 'float64'}\n _epsilon = _config.get('epsilon', epsilon())\n assert isinstance(_epsilon, float)\n _image_data_format = _config.get('image_data_format', image_data_format())\n assert _image_data_format in {'channels_last', 'channels_first'}\n set_floatx(_floatx)\n set_epsilon(_epsilon)\n set_image_data_format(_image_data_format)\n\n# Save config file.\nif not os.path.exists(_keras_dir):\n try:\n os.makedirs(_keras_dir)\n except OSError:\n # Except permission denied and potential race conditions\n # in multi-threaded environments.\n pass\n\nif not os.path.exists(_config_path):\n _config = {\n 'floatx': floatx(),\n 'epsilon': epsilon(),\n 'backend': 'tensorflow',\n 'image_data_format': image_data_format()\n }\n try:\n with open(_config_path, 'w') as f:\n f.write(json.dumps(_config, indent=4))\n except IOError:\n # Except permission denied.\n pass\n" ]
[ [ "tensorflow.python.ops.math_ops.log", "tensorflow.python.ops.variables.is_variable_initialized", "tensorflow.python.ops.array_ops.split", "tensorflow.python.ops.array_ops.sparse_placeholder", "tensorflow.python.ops.state_ops.assign_sub", "tensorflow.python.ops.math_ops.reduce_any", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.ops.ctc_ops.ctc_loss", "tensorflow.python.ops.array_ops.stop_gradient", "tensorflow.python.ops.array_ops.fill", "tensorflow.python.ops.math_ops.abs", "tensorflow.python.ops.sparse_ops.sparse_concat", "tensorflow.python.ops.nn.conv2d_transpose", "tensorflow.python.ops.math_ops.reduce_logsumexp", "tensorflow.python.ops.math_ops.less", "tensorflow.python.ops.clip_ops.clip_by_value", "tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.framework.ops.reset_default_graph", "tensorflow.python.ops.array_ops.tile", "tensorflow.python.ops.math_ops.cumprod", "tensorflow.python.ops.ctc_ops.ctc_greedy_decoder", "tensorflow.python.ops.sparse_ops.sparse_tensor_dense_matmul", "tensorflow.python.ops.math_ops.equal", "numpy.delete", "tensorflow.python.ops.nn.bias_add", "tensorflow.python.ops.nn.moments", "numpy.array", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.reverse", "tensorflow.python.ops.gradients.gradients", "tensorflow.python.ops.nn.softplus", "tensorflow.python.ops.nn.depthwise_conv2d", "tensorflow.python.util.tf_inspect.getargspec", "tensorflow.python.ops.nn.avg_pool3d", "tensorflow.python.ops.array_ops.pad", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.ops.math_ops.greater_equal", "numpy.expand_dims", "tensorflow.python.ops.nn.in_top_k", "numpy.asarray", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.ops.nn.separable_conv2d", "tensorflow.python.ops.linalg_ops.eye", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.ops.math_ops.exp", "tensorflow.python.ops.array_ops.gather_nd", "tensorflow.python.ops.math_ops.to_int32", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.training.moving_averages.assign_moving_average", "tensorflow.python.ops.array_ops.where", "tensorflow.python.framework.ops.get_default_session", "tensorflow.python.ops.ctc_ops.ctc_beam_search_decoder", "tensorflow.python.ops.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.python.ops.math_ops.minimum", "tensorflow.python.ops.tensor_array_ops.TensorArray", "tensorflow.python.ops.variables.global_variables", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.math_ops.pow", "tensorflow.python.ops.nn.sigmoid_cross_entropy_with_logits", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.nn.avg_pool", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.nn.max_pool", "tensorflow.python.ops.math_ops.cos", "tensorflow.python.ops.functional_ops.map_fn", "tensorflow.python.ops.nn.softsign", "tensorflow.python.ops.nn.convolution", "tensorflow.python.ops.nn.tanh", "tensorflow.python.ops.math_ops.sin", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.init_ops.random_uniform_initializer", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.math_ops.sqrt", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.math_ops.round", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.ops.math_ops.argmin", "numpy.random.randint", "tensorflow.python.ops.math_ops.to_int64", "tensorflow.python.ops.nn.sigmoid", "tensorflow.python.ops.functional_ops.foldr", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.ops.math_ops.reduce_prod", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.math_ops.reduce_min", "tensorflow.python.ops.sparse_ops.sparse_to_dense", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.nn.relu", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.ops.math_ops.cumsum", "tensorflow.python.ops.nn.elu", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.ops.init_ops.random_normal_initializer", "tensorflow.python.ops.math_ops.multiply", "tensorflow.python.ops.nn.l2_normalize", "tensorflow.python.ops.math_ops.maximum", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.ops.nn.max_pool3d", "tensorflow.python.ops.nn.softmax", "tensorflow.python.ops.logging_ops.Print", "tensorflow.python.ops.math_ops.greater", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.math_ops.not_equal", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.ops.math_ops.argmax", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.random_ops.truncated_normal", "tensorflow.python.ops.nn.dropout", "tensorflow.python.ops.array_ops.one_hot", "tensorflow.python.ops.image_ops.resize_nearest_neighbor", "tensorflow.python.client.session.Session", "tensorflow.python.ops.variables.variables_initializer", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.nn.conv3d_transpose", "tensorflow.python.ops.math_ops.less_equal", "tensorflow.python.ops.functional_ops.scan", "tensorflow.python.ops.nn.softmax_cross_entropy_with_logits", "tensorflow.python.ops.math_ops.sign", "tensorflow.python.ops.functional_ops.foldl", "tensorflow.python.ops.random_ops.random_normal", "tensorflow.python.ops.array_ops.boolean_mask", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.nn.batch_normalization" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "1.0", "1.2" ] } ]
sourcery-ai-bot/Megatron-LM
[ "f27f44e2c49d1cb39b2288bef6f7d837e11094cb" ]
[ "megatron/data/indexed_dataset.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n# copied from fairseq/fairseq/data/indexed_dataset.py\n# Removed IndexedRawTextDataset since it relied on Fairseq dictionary\n# other slight modifications to remove fairseq dependencies\n# Added document index to index file and made it accessible.\n# An empty sentence no longer separates documents.\n\nfrom functools import lru_cache\nimport os\nimport shutil\nimport struct\nfrom itertools import accumulate\n\nimport numpy as np\nimport torch\nfrom megatron import print_rank_0\n\n\ndef __best_fitting_dtype(vocab_size=None):\n if vocab_size is not None and vocab_size < 65500:\n return np.uint16\n else:\n return np.int32\n\n\ndef get_available_dataset_impl():\n return ['lazy', 'cached', 'mmap']\n\n\ndef infer_dataset_impl(path):\n if IndexedDataset.exists(path):\n with open(index_file_path(path), 'rb') as f:\n magic = f.read(8)\n if magic == IndexedDataset._HDR_MAGIC:\n return 'cached'\n elif magic == MMapIndexedDataset.Index._HDR_MAGIC[:8]:\n return 'mmap'\n else:\n return None\n else:\n print(f\"Dataset does not exist: {path}\")\n print(\"Path should be a basename that both .idx and .bin can be appended to get full filenames.\")\n return None\n\n\ndef make_builder(out_file, impl, vocab_size=None):\n if impl == 'mmap':\n return MMapIndexedDatasetBuilder(out_file, dtype=__best_fitting_dtype(vocab_size))\n else:\n return IndexedDatasetBuilder(out_file)\n\n\ndef make_dataset(path, impl, skip_warmup=False):\n if not IndexedDataset.exists(path):\n print(f\"Dataset does not exist: {path}\")\n print(\"Path should be a basename that both .idx and .bin can be appended to get full filenames.\")\n return None\n if impl == 'infer':\n impl = infer_dataset_impl(path)\n if impl == 'lazy' and IndexedDataset.exists(path):\n return IndexedDataset(path)\n elif impl == 'cached' and IndexedDataset.exists(path):\n return IndexedCachedDataset(path)\n elif impl == 'mmap' and MMapIndexedDataset.exists(path):\n return MMapIndexedDataset(path, skip_warmup)\n print(f\"Unknown dataset implementation: {impl}\")\n return None\n\n\ndef dataset_exists(path, impl):\n if impl == 'mmap':\n return MMapIndexedDataset.exists(path)\n else:\n return IndexedDataset.exists(path)\n\n\ndef read_longs(f, n):\n a = np.empty(n, dtype=np.int64)\n f.readinto(a)\n return a\n\n\ndef write_longs(f, a):\n f.write(np.array(a, dtype=np.int64))\n\n\ndtypes = {\n 1: np.uint8,\n 2: np.int8,\n 3: np.int16,\n 4: np.int32,\n 5: np.int64,\n 6: np.float,\n 7: np.double,\n 8: np.uint16\n}\n\n\ndef code(dtype):\n for k in dtypes.keys():\n if dtypes[k] == dtype:\n return k\n raise ValueError(dtype)\n\n\ndef index_file_path(prefix_path):\n return prefix_path + '.idx'\n\n\ndef data_file_path(prefix_path):\n return prefix_path + '.bin'\n\n\ndef create_doc_idx(sizes):\n doc_idx = [0]\n for i, s in enumerate(sizes):\n if s == 0:\n doc_idx.append(i + 1)\n return doc_idx\n\n\nclass IndexedDataset(torch.utils.data.Dataset):\n \"\"\"Loader for IndexedDataset\"\"\"\n _HDR_MAGIC = b'TNTIDX\\x00\\x00'\n\n def __init__(self, path):\n super().__init__()\n self.path = path\n self.data_file = None\n self.read_index(path)\n\n def read_index(self, path):\n with open(index_file_path(path), 'rb') as f:\n magic = f.read(8)\n assert magic == self._HDR_MAGIC, (\n 'Index file doesn\\'t match expected format. '\n 'Make sure that --dataset-impl is configured properly.'\n )\n version = f.read(8)\n assert struct.unpack('<Q', version) == (1,)\n code, self.element_size = struct.unpack('<QQ', f.read(16))\n self.dtype = dtypes[code]\n self._len, self.s = struct.unpack('<QQ', f.read(16))\n self.doc_count = struct.unpack('<Q', f.read(8))\n self.dim_offsets = read_longs(f, self._len + 1)\n self.data_offsets = read_longs(f, self._len + 1)\n self.sizes = read_longs(f, self.s)\n self.doc_idx = read_longs(f, self.doc_count)\n\n def read_data(self, path):\n self.data_file = open(data_file_path(path), 'rb', buffering=0)\n\n def check_index(self, i):\n if i < 0 or i >= self._len:\n raise IndexError('index out of range')\n\n def __del__(self):\n if self.data_file:\n self.data_file.close()\n\n # @lru_cache(maxsize=8)\n def __getitem__(self, idx):\n if not self.data_file:\n self.read_data(self.path)\n if isinstance(idx, int):\n i = idx\n self.check_index(i)\n tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]\n a = np.empty(tensor_size, dtype=self.dtype)\n self.data_file.seek(self.data_offsets[i] * self.element_size)\n self.data_file.readinto(a)\n return a\n elif isinstance(idx, slice):\n start, stop, step = idx.indices(len(self))\n if step != 1:\n raise ValueError(\"Slices into indexed_dataset must be contiguous\")\n sizes = self.sizes[self.dim_offsets[start]:self.dim_offsets[stop]]\n size = sum(sizes)\n a = np.empty(size, dtype=self.dtype)\n self.data_file.seek(self.data_offsets[start] * self.element_size)\n self.data_file.readinto(a)\n offsets = list(accumulate(sizes))\n return np.split(a, offsets[:-1])\n\n def __len__(self):\n return self._len\n\n def num_tokens(self, index):\n return self.sizes[index]\n\n def size(self, index):\n return self.sizes[index]\n\n @staticmethod\n def exists(path):\n return (\n os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path))\n )\n\n @property\n def supports_prefetch(self):\n return False # avoid prefetching to save memory\n\n\nclass IndexedCachedDataset(IndexedDataset):\n\n def __init__(self, path):\n super().__init__(path)\n self.cache = None\n self.cache_index = {}\n\n @property\n def supports_prefetch(self):\n return True\n\n def prefetch(self, indices):\n if all(i in self.cache_index for i in indices):\n return\n if not self.data_file:\n self.read_data(self.path)\n indices = sorted(set(indices))\n total_size = sum(\n self.data_offsets[i + 1] - self.data_offsets[i] for i in indices\n )\n\n self.cache = np.empty(total_size, dtype=self.dtype)\n ptx = 0\n self.cache_index.clear()\n for i in indices:\n self.cache_index[i] = ptx\n size = self.data_offsets[i + 1] - self.data_offsets[i]\n a = self.cache[ptx: ptx + size]\n self.data_file.seek(self.data_offsets[i] * self.element_size)\n self.data_file.readinto(a)\n ptx += size\n if self.data_file:\n # close and delete data file after prefetch so we can pickle\n self.data_file.close()\n self.data_file = None\n\n # @lru_cache(maxsize=8)\n def __getitem__(self, idx):\n if isinstance(idx, int):\n i = idx\n self.check_index(i)\n tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]\n a = np.empty(tensor_size, dtype=self.dtype)\n ptx = self.cache_index[i]\n np.copyto(a, self.cache[ptx: ptx + a.size])\n return a\n elif isinstance(idx, slice):\n return [self[i] for i in range(*idx.indices(len(self)))]\n\n\nclass IndexedDatasetBuilder(object):\n element_sizes = {\n np.uint8: 1,\n np.int8: 1,\n np.int16: 2,\n np.int32: 4,\n np.int64: 8,\n np.float: 4,\n np.double: 8\n }\n\n def __init__(self, out_file, dtype=np.int32):\n self.out_file = open(out_file, 'wb')\n self.dtype = dtype\n self.data_offsets = [0]\n self.dim_offsets = [0]\n self.sizes = []\n self.element_size = self.element_sizes[self.dtype]\n self.doc_idx = [0]\n\n def add_item(self, tensor):\n bytes = self.out_file.write(np.array(tensor.numpy(), dtype=self.dtype))\n self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size)\n for s in tensor.size():\n self.sizes.append(s)\n self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size()))\n\n def end_document(self):\n self.doc_idx.append(len(self.sizes))\n\n def merge_file_(self, another_file):\n index = IndexedDataset(another_file)\n assert index.dtype == self.dtype\n\n begin = self.data_offsets[-1]\n for offset in index.data_offsets[1:]:\n self.data_offsets.append(begin + offset)\n self.sizes.extend(index.sizes)\n begin = self.dim_offsets[-1]\n for dim_offset in index.dim_offsets[1:]:\n self.dim_offsets.append(begin + dim_offset)\n\n with open(data_file_path(another_file), 'rb') as f:\n while True:\n data = f.read(1024)\n if data:\n self.out_file.write(data)\n else:\n break\n\n def finalize(self, index_file):\n self.out_file.close()\n with open(index_file, 'wb') as index:\n index.write(b'TNTIDX\\x00\\x00')\n index.write(struct.pack('<Q', 1))\n index.write(struct.pack('<QQ', code(self.dtype), self.element_size))\n index.write(struct.pack('<QQ', len(self.data_offsets) - 1, len(self.sizes)))\n index.write(struct.pack('<Q', len(self.doc_idx)))\n write_longs(index, self.dim_offsets)\n write_longs(index, self.data_offsets)\n write_longs(index, self.sizes)\n write_longs(index, self.doc_idx)\n\n\ndef _warmup_mmap_file(path):\n with open(path, 'rb') as stream:\n while stream.read(100 * 1024 * 1024):\n pass\n\n\nclass MMapIndexedDataset(torch.utils.data.Dataset):\n class Index(object):\n _HDR_MAGIC = b'MMIDIDX\\x00\\x00'\n\n @classmethod\n def writer(cls, path, dtype):\n class _Writer(object):\n def __enter__(self):\n self._file = open(path, 'wb')\n\n self._file.write(cls._HDR_MAGIC)\n self._file.write(struct.pack('<Q', 1))\n self._file.write(struct.pack('<B', code(dtype)))\n\n return self\n\n @staticmethod\n def _get_pointers(sizes):\n dtype_size = dtype().itemsize\n address = 0\n pointers = []\n\n for size in sizes:\n pointers.append(address)\n address += size * dtype_size\n\n return pointers\n\n def write(self, sizes, doc_idx):\n pointers = self._get_pointers(sizes)\n\n self._file.write(struct.pack('<Q', len(sizes)))\n self._file.write(struct.pack('<Q', len(doc_idx)))\n\n sizes = np.array(sizes, dtype=np.int32)\n self._file.write(sizes.tobytes(order='C'))\n del sizes\n\n pointers = np.array(pointers, dtype=np.int64)\n self._file.write(pointers.tobytes(order='C'))\n del pointers\n\n doc_idx = np.array(doc_idx, dtype=np.int64)\n self._file.write(doc_idx.tobytes(order='C'))\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._file.close()\n\n return _Writer()\n\n def __init__(self, path, skip_warmup=False):\n with open(path, 'rb') as stream:\n magic_test = stream.read(9)\n assert self._HDR_MAGIC == magic_test, (\n 'Index file doesn\\'t match expected format. '\n 'Make sure that --dataset-impl is configured properly.'\n )\n version = struct.unpack('<Q', stream.read(8))\n assert (1,) == version\n\n dtype_code, = struct.unpack('<B', stream.read(1))\n self._dtype = dtypes[dtype_code]\n self._dtype_size = self._dtype().itemsize\n\n self._len = struct.unpack('<Q', stream.read(8))[0]\n self._doc_count = struct.unpack('<Q', stream.read(8))[0]\n offset = stream.tell()\n\n if not skip_warmup:\n print_rank_0(\" warming up index mmap file...\")\n _warmup_mmap_file(path)\n\n self._bin_buffer_mmap = np.memmap(path, mode='r', order='C')\n self._bin_buffer = memoryview(self._bin_buffer_mmap)\n print_rank_0(\" reading sizes...\")\n self._sizes = np.frombuffer(\n self._bin_buffer,\n dtype=np.int32,\n count=self._len,\n offset=offset)\n print_rank_0(\" reading pointers...\")\n self._pointers = np.frombuffer(self._bin_buffer, dtype=np.int64, count=self._len,\n offset=offset + self._sizes.nbytes)\n print_rank_0(\" reading document index...\")\n self._doc_idx = np.frombuffer(self._bin_buffer, dtype=np.int64, count=self._doc_count,\n offset=offset + self._sizes.nbytes + self._pointers.nbytes)\n\n def __del__(self):\n self._bin_buffer_mmap._mmap.close()\n del self._bin_buffer_mmap\n\n @property\n def dtype(self):\n return self._dtype\n\n @property\n def sizes(self):\n return self._sizes\n\n @property\n def doc_idx(self):\n return self._doc_idx\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n return self._pointers[i], self._sizes[i]\n\n def __len__(self):\n return self._len\n\n def __init__(self, path, skip_warmup=False):\n super().__init__()\n\n self._path = None\n self._index = None\n self._bin_buffer = None\n\n self._do_init(path, skip_warmup)\n\n def __getstate__(self):\n return self._path\n\n def __setstate__(self, state):\n self._do_init(state)\n\n def _do_init(self, path, skip_warmup):\n self._path = path\n self._index = self.Index(index_file_path(self._path), skip_warmup)\n\n if not skip_warmup:\n print_rank_0(\" warming up data mmap file...\")\n _warmup_mmap_file(data_file_path(self._path))\n print_rank_0(\" creating numpy buffer of mmap...\")\n self._bin_buffer_mmap = np.memmap(data_file_path(self._path), mode='r', order='C')\n print_rank_0(\" creating memory view of numpy buffer...\")\n self._bin_buffer = memoryview(self._bin_buffer_mmap)\n\n def __del__(self):\n self._bin_buffer_mmap._mmap.close()\n del self._bin_buffer_mmap\n del self._index\n\n def __len__(self):\n return len(self._index)\n\n # @lru_cache(maxsize=8)\n def __getitem__(self, idx):\n if isinstance(idx, int):\n ptr, size = self._index[idx]\n np_array = np.frombuffer(self._bin_buffer, dtype=self._index.dtype,\n count=size, offset=ptr)\n return np_array\n elif isinstance(idx, slice):\n start, stop, step = idx.indices(len(self))\n if step != 1:\n raise ValueError(\"Slices into indexed_dataset must be contiguous\")\n ptr = self._index._pointers[start]\n sizes = self._index._sizes[idx]\n offsets = list(accumulate(sizes))\n total_size = sum(sizes)\n np_array = np.frombuffer(self._bin_buffer, dtype=self._index.dtype,\n count=total_size, offset=ptr)\n return np.split(np_array, offsets[:-1])\n\n def get(self, idx, offset=0, length=None):\n \"\"\" Retrieves a single item from the dataset with the option to only\n return a portion of the item.\n\n get(idx) is the same as [idx] but get() does not support slicing.\n \"\"\"\n ptr, size = self._index[idx]\n if length is None:\n length = size - offset\n ptr += offset * np.dtype(self._index.dtype).itemsize\n return np.frombuffer(self._bin_buffer, dtype=self._index.dtype,\n count=length, offset=ptr)\n\n @property\n def sizes(self):\n return self._index.sizes\n\n @property\n def doc_idx(self):\n return self._index.doc_idx\n\n def get_doc_idx(self):\n return self._index._doc_idx\n\n def set_doc_idx(self, doc_idx_):\n self._index._doc_idx = doc_idx_\n\n @property\n def supports_prefetch(self):\n return False\n\n @staticmethod\n def exists(path):\n return (\n os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path))\n )\n\n\nclass MMapIndexedDatasetBuilder(object):\n def __init__(self, out_file, dtype=np.int64):\n self._data_file = open(out_file, 'wb')\n self._dtype = dtype\n self._sizes = []\n self._doc_idx = [0]\n\n def add_item(self, tensor):\n np_array = np.array(tensor.numpy(), dtype=self._dtype)\n self._data_file.write(np_array.tobytes(order='C'))\n self._sizes.append(np_array.size)\n\n def end_document(self):\n self._doc_idx.append(len(self._sizes))\n\n def merge_file_(self, another_file):\n # Concatenate index\n index = MMapIndexedDataset.Index(index_file_path(another_file))\n assert index.dtype == self._dtype\n\n for size in index.sizes:\n self._sizes.append(size)\n\n # Concatenate data\n with open(data_file_path(another_file), 'rb') as f:\n shutil.copyfileobj(f, self._data_file)\n\n def finalize(self, index_file):\n self._data_file.close()\n\n with MMapIndexedDataset.Index.writer(index_file, self._dtype) as index:\n index.write(self._sizes, self._doc_idx)\n" ]
[ [ "numpy.split", "numpy.memmap", "numpy.dtype", "numpy.frombuffer", "numpy.copyto", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mvdelt/detectron2
[ "c320a6f0e6facb9c5d6dda8263c8e76834c04246", "c320a6f0e6facb9c5d6dda8263c8e76834c04246" ]
[ "detectron2/evaluation/panoptic_evaluation.py", "projects/DensePose/densepose/engine/trainer.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\nimport contextlib\nimport io\nimport itertools\nimport json\nimport logging\nimport numpy as np\nimport os\nimport tempfile\nfrom collections import OrderedDict\nfrom PIL import Image\nfrom tabulate import tabulate\n\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.utils import comm\nfrom detectron2.utils.file_io import PathManager\n\nfrom .evaluator import DatasetEvaluator\n\nlogger = logging.getLogger(__name__)\n\n\nclass COCOPanopticEvaluator(DatasetEvaluator):\n \"\"\"\n Evaluate Panoptic Quality metrics on COCO using PanopticAPI.\n It saves panoptic segmentation prediction in `output_dir`\n\n It contains a synchronize call and has to be called from all workers.\n \"\"\"\n\n def __init__(self, dataset_name, output_dir):\n \"\"\"\n Args:\n dataset_name (str): name of the dataset\n output_dir (str): output directory to save results for evaluation\n \"\"\"\n self._metadata = MetadataCatalog.get(dataset_name)\n self._thing_contiguous_id_to_dataset_id = {\n v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()\n }\n self._stuff_contiguous_id_to_dataset_id = {\n v: k for k, v in self._metadata.stuff_dataset_id_to_contiguous_id.items()\n }\n\n PathManager.mkdirs(output_dir)\n # self._predictions_json = os.path.join(output_dir, \"predictions.json\")\n self._predictions_json = os.path.join(output_dir, \"predictionsTestJ.json\")\n\n def reset(self):\n self._predictions = []\n\n def _convert_category_id(self, segment_info):\n isthing = segment_info.pop(\"isthing\", None)\n if isthing is None:\n # the model produces panoptic category id directly. No more conversion needed\n return segment_info\n if isthing is True:\n segment_info[\"category_id\"] = self._thing_contiguous_id_to_dataset_id[\n segment_info[\"category_id\"]\n ]\n else:\n segment_info[\"category_id\"] = self._stuff_contiguous_id_to_dataset_id[\n segment_info[\"category_id\"]\n ]\n return segment_info\n\n def process(self, inputs, outputs):\n\n # print('j) COCOPanopticEvaluator.process starts!!! cococococococococococococococococo')\n # print(f'j) inputs: {inputs}') \n # print(f'j) len(inputs): {len(inputs)}') # 1 (예상대로임. 테스트시에는 뱃치사이즈가 1이라고 어디서 봤음.)\n # print(f'j) outputs: {outputs}') \n # print(f'j) len(outputs): {len(outputs)}') # 1\n\n from panopticapi.utils import id2rgb \n\n for input, output in zip(inputs, outputs):\n # i.21.3.29.21:26) \n # 여기(COCOPanopticEvaluator)서는 output[\"panoptic_seg\"] 를 이용한다!! \n # CityscapesSemSegEvaluator 에선 output[\"sem_seg\"] 를, \n # CityscapesInstanceEvaluator 에선 output[\"instances\"] 를 이용함!! \n # Det2 문서의 모델 아웃풋 부분 보면, 모델의 아웃풋인 list[dict] 의 각 dict(하나의 이미지에 대응)가 가질수있는 키들 중 \n # 이렇게 3가지(\"instances\", \"sem_seg\", \"panoptic_seg\") 가 주요 키들임. \n # Det2 내장 panoptic deeplab 플젝의 train_net.py 의 Trainer.build_evaluator 메서드 보면 \n # 이 3개의 이밸류에이터(DatasetEvaluator 클래스) 를 리스트에 담아서 DatasetEvaluator's' 로 만들어주고있지. \n panoptic_img, segments_info = output[\"panoptic_seg\"] \n panoptic_img = panoptic_img.cpu().numpy()\n if segments_info is None:\n\n # i. 현재 내플젝(panoptic deeplab 이용한 치과파노라마 panoptic seg 플젝) 에선 아래의 print 가 출력됨. /21.3.26.16:06.\n # print('j) (코드조사용 출력) 모델이내뱉은 아웃풋에 segments_info 가 없음!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') \n #\n # i.21.3.26.21:42) ->즉, 바로아래의 Det2 기존 코멘트 설명대로일거임 아마도. \n # 즉, 아래에서의 panoptic_label 변수(이게 모델(panoptic deeplab)이 출력한 정보인거지)는\n # 그냥 단순히 category_id * label_divisor + instance_id 로 계산된것인듯.\n # 그래서, self._predictions_json json파일(현재 내 구글드라이브에 저장되게해놨지) 열어보면\n # cityscapes 의 방식이랑 좀 다른것을 볼수있음. \n\n # If \"segments_info\" is None, we assume \"panoptic_img\" is a\n # H*W int32 image storing the panoptic_id in the format of\n # category_id * label_divisor + instance_id. We reserve -1 for\n # VOID label, and add 1 to panoptic_img since the official\n # evaluation script uses 0 for VOID label.\n label_divisor = self._metadata.label_divisor\n segments_info = []\n for panoptic_label in np.unique(panoptic_img):\n if panoptic_label == -1:\n # VOID region.\n continue\n pred_class = panoptic_label // label_divisor\n isthing = (\n pred_class in self._metadata.thing_dataset_id_to_contiguous_id.values()\n )\n segments_info.append(\n {\n \"id\": int(panoptic_label) + 1, # i. TODO 내플젝할때는 +1 제거해야함 /21.3.27.14:21. # i. ->다시생각해보니, 걍 +1을 해주든 +123을 해주든 상관없이 똑같을듯..?? 아직제대로생각완료못함. /21.3.28.12:59.\n # \"id\": int(panoptic_label), # i. 내플젝 위해 +1 제거. /21.3.27.14:19. \n \"category_id\": int(pred_class),\n \"isthing\": bool(isthing), # i. 얘도 안적혀잇음...엥?? /21.3.26.16:12. ->_convert_category_id 에서 pop해주자나;;; /21.3.26.18:40.\n }\n )\n # Official evaluation script uses 0 for VOID label. # i. TODO 음.. 기존Det2코멘트가 틀린것같은데.. +1 해줄필요없을것같은데??? 내생각맞나테스트해보자. /21.3.28.13:09. \n panoptic_img += 1 \n # i. TODO ->내플젝에선 이거(panoptic_img += 1) 코멘트아웃해주면 될듯. # i. ->다시생각해보니, 걍 +1을 해주든 +123을 해주든 상관없이 똑같을듯..?? 아직제대로생각완료못함. /21.3.28.12:59. \n # 내플젝에선 백그라운드도 하나의 foreground 처럼 프레딕션해주고있는데(시각화를위해),\n # 그 백그라운드의 id가 0이니까. self._predictions_json json파일(현재 내 구글드라이브에 저장되게해놨지) 열어보면\n # 모델(panoptic deeplab)이 프레딕션한 결과가 어떻게 출력되었나 확인가능. /21.3.26.20:22.\n # i.21.3.26.23:03) 참고로, 혹시나중에 까먹을까봐 적으면, \n # 보통은 panoptic seg 태스크에서 백그라운드는 프레딕션시 클래스 선택지에서 없게해줌. 그게 평가방식상 점수 유리하니까. coco 나 cityscapes 의 panoptic seg 평가시.\n # 그래서 시각화시키면 백그라운드가 없음. 백그라운드도 전부 foreground 클래스들이 죄다 덮어버림(그래도 점수 안깎임).\n # 근데 나는 시각화출력시에 백그라운드도 보여줘야 예쁘니까 백그라운드도 foreground 클래스중 하나로 해준거고.\n\n # else:\n # i. 현재 내플젝(panoptic deeplab 이용한 치과파노라마 panoptic seg 플젝) 에선 얜 출력안되고있음. /21.3.26.16:06.\n # print('j) (코드조사용 출력) 모델이내뱉은 아웃풋에 segments_info 가 있음!!!!!!')\n\n file_name = os.path.basename(input[\"file_name\"]) # i. ex) (하나의 input 에서) 'file_name': '/content/datasetsJ/panopticSeg_dentPanoJ/inputOriPano/val/imp4_188.jpg' /21.3.26.22:49.\n file_name_png = os.path.splitext(file_name)[0] + \".png\" # i. ex) imp4_188.png 이런식으로 되겠지. /21.3.26.22:49.\n with io.BytesIO() as out:\n Image.fromarray(id2rgb(panoptic_img)).save(out, format=\"PNG\")\n segments_info = [self._convert_category_id(x) for x in segments_info]\n\n # print(f'j) io.BytesIO() as out, out.getvalue(): {out.getvalue()}') # b'\\x89PNG\\r\\n\\x1a\\n\\x00\\~~~~~~~~~~' \n\n self._predictions.append(\n {\n \"image_id\": input[\"image_id\"], # i. ex) 'imp4_188' /21.3.26.22:52.\n \"file_name\": file_name_png, # i. ex) imp4_188.png /21.3.26.22:49.\n # i. 이것만 출력안됨. 뭐지?????? /21.3.26.16:11. \n # ->죠아래에서 pop 해주잖아;; 이거 pop 안해주면 json.dumps 안됨(TypeError: Object of type bytes is not JSON serializable). /21.3.26.18:40.\n \"png_string\": out.getvalue(), \n \"segments_info\": segments_info,\n }\n )\n\n def evaluate(self):\n comm.synchronize()\n\n # print('j) COCOPanopticEvaluator.evaluate starts!!! cococococococococococococococococo')\n\n self._predictions = comm.gather(self._predictions)\n self._predictions = list(itertools.chain(*self._predictions))\n if not comm.is_main_process():\n return\n\n # PanopticApi requires local files\n gt_json = PathManager.get_local_path(self._metadata.panoptic_json) # i. COCO형식으로 변환된 어노json파일 경로./21.3.10.12:02.에적어뒀던것. /21.3.26.13:26. \n gt_folder = PathManager.get_local_path(self._metadata.panoptic_root) # i. COCO형식으로 변환된 어노png파일들 있는 디렉토리./21.3.10.12:02.에적어뒀던것. /21.3.26.13:26. \n\n with tempfile.TemporaryDirectory(prefix=\"panoptic_eval\") as pred_dir:\n logger.info(\"Writing all panoptic predictions to {} ...\".format(pred_dir))\n for p in self._predictions:\n with open(os.path.join(pred_dir, p[\"file_name\"]), \"wb\") as f:\n f.write(p.pop(\"png_string\"))\n\n with open(gt_json, \"r\") as f:\n json_data = json.load(f)\n json_data[\"annotations\"] = self._predictions\n with PathManager.open(self._predictions_json, \"w\") as f:\n f.write(json.dumps(json_data))\n\n from panopticapi.evaluation import pq_compute\n\n # with contextlib.redirect_stdout(io.StringIO()):\n # i.21.3.27.18:34) print 출력좀 확인하려고 내가 좀 바꿔줌.\n ioJ = io.StringIO()\n with contextlib.redirect_stdout(ioJ):\n pq_res = pq_compute(\n gt_json, # i. COCO형식으로 변환된 어노json파일 경로. /21.3.26.22:41.\n PathManager.get_local_path(self._predictions_json), # i. 모델(현재 panoptic deeplab)의 출력 json 경로.(위에서 gt_json 의 \"annotations\"를 바꿔서 만들어줬지.) /21.3.26.22:42.\n gt_folder=gt_folder, # i. COCO형식으로 변환된 어노png파일들 있는 디렉토리. /21.3.26.22:55.\n pred_folder=pred_dir, # i. 모델이 출력한 png 들을 넣어준 디렉토리 경로. (현재 임시디렉토리로 되어있지. 참고로 위에서 각 픽셀값들에다 +1해줬지. 내플젝에선 +1필요없을듯하지만.) /21.3.26.23:06. \n )\n print(f'j) got stdout: \\n{ioJ.getvalue()}') \n\n res = {}\n res[\"PQ\"] = 100 * pq_res[\"All\"][\"pq\"]\n res[\"SQ\"] = 100 * pq_res[\"All\"][\"sq\"]\n res[\"RQ\"] = 100 * pq_res[\"All\"][\"rq\"]\n res[\"PQ_th\"] = 100 * pq_res[\"Things\"][\"pq\"]\n res[\"SQ_th\"] = 100 * pq_res[\"Things\"][\"sq\"]\n res[\"RQ_th\"] = 100 * pq_res[\"Things\"][\"rq\"]\n res[\"PQ_st\"] = 100 * pq_res[\"Stuff\"][\"pq\"]\n res[\"SQ_st\"] = 100 * pq_res[\"Stuff\"][\"sq\"]\n res[\"RQ_st\"] = 100 * pq_res[\"Stuff\"][\"rq\"]\n\n results = OrderedDict({\"panoptic_seg\": res})\n _print_panoptic_results(pq_res)\n\n return results\n\n\ndef _print_panoptic_results(pq_res):\n headers = [\"\", \"PQ\", \"SQ\", \"RQ\", \"#categories\"]\n data = []\n for name in [\"All\", \"Things\", \"Stuff\"]:\n row = [name] + [pq_res[name][k] * 100 for k in [\"pq\", \"sq\", \"rq\"]] + [pq_res[name][\"n\"]]\n data.append(row)\n table = tabulate(\n data, headers=headers, tablefmt=\"pipe\", floatfmt=\".3f\", stralign=\"center\", numalign=\"center\"\n )\n logger.info(\"Panoptic Evaluation Results:\\n\" + table)\n\n\nif __name__ == \"__main__\":\n from detectron2.utils.logger import setup_logger\n\n logger = setup_logger()\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--gt-json\")\n parser.add_argument(\"--gt-dir\")\n parser.add_argument(\"--pred-json\")\n parser.add_argument(\"--pred-dir\")\n args = parser.parse_args()\n\n from panopticapi.evaluation import pq_compute\n\n with contextlib.redirect_stdout(io.StringIO()):\n pq_res = pq_compute(\n args.gt_json, args.pred_json, gt_folder=args.gt_dir, pred_folder=args.pred_dir\n )\n _print_panoptic_results(pq_res)\n", "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport logging\nimport os\nfrom collections import OrderedDict\nfrom typing import List, Optional\nimport torch\nfrom torch import nn\n\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.config import CfgNode\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.evaluation import (\n COCOEvaluator,\n DatasetEvaluator,\n DatasetEvaluators,\n LVISEvaluator,\n inference_on_dataset,\n print_csv_format,\n)\nfrom detectron2.solver.build import get_default_optimizer_params, maybe_add_gradient_clipping\nfrom detectron2.utils import comm\nfrom detectron2.utils.events import EventWriter, get_event_storage\n\nfrom densepose import DensePoseDatasetMapperTTA, DensePoseGeneralizedRCNNWithTTA, load_from_cfg\nfrom densepose.data import (\n DatasetMapper,\n build_combined_loader,\n build_detection_test_loader,\n build_detection_train_loader,\n build_inference_based_loaders,\n has_inference_based_loaders,\n)\nfrom densepose.evaluation import DensePoseCOCOEvaluator\nfrom densepose.modeling.cse import Embedder\n\n\nclass SampleCountingLoader:\n def __init__(self, loader):\n self.loader = loader\n\n def __iter__(self):\n it = iter(self.loader)\n storage = get_event_storage()\n while True:\n try:\n batch = next(it)\n num_inst_per_dataset = {}\n for data in batch:\n dataset_name = data[\"dataset\"]\n if dataset_name not in num_inst_per_dataset:\n num_inst_per_dataset[dataset_name] = 0\n num_inst = len(data[\"instances\"])\n num_inst_per_dataset[dataset_name] += num_inst\n for dataset_name in num_inst_per_dataset:\n storage.put_scalar(f\"batch/{dataset_name}\", num_inst_per_dataset[dataset_name])\n yield batch\n except StopIteration:\n break\n\n\nclass SampleCountMetricPrinter(EventWriter):\n def __init__(self):\n self.logger = logging.getLogger(__name__)\n\n def write(self):\n storage = get_event_storage()\n batch_stats_strs = []\n for key, buf in storage.histories().items():\n if key.startswith(\"batch/\"):\n batch_stats_strs.append(f\"{key} {buf.avg(20)}\")\n self.logger.info(\", \".join(batch_stats_strs))\n\n\nclass Trainer(DefaultTrainer):\n @classmethod\n def extract_embedder_from_model(cls, model: nn.Module) -> Optional[Embedder]:\n if isinstance(model, nn.parallel.DistributedDataParallel):\n model = model.module\n if hasattr(model, \"roi_heads\") and hasattr(model.roi_heads, \"embedder\"):\n return model.roi_heads.embedder\n return None\n\n # TODO: the only reason to copy the base class code here is to pass the embedder from\n # the model to the evaluator; that should be refactored to avoid unnecessary copy-pasting\n @classmethod\n def test(cls, cfg: CfgNode, model: nn.Module, evaluators: List[DatasetEvaluator] = None):\n \"\"\"\n Args:\n cfg (CfgNode):\n model (nn.Module):\n evaluators (list[DatasetEvaluator] or None): if None, will call\n :meth:`build_evaluator`. Otherwise, must have the same length as\n ``cfg.DATASETS.TEST``.\n\n Returns:\n dict: a dict of result metrics\n \"\"\"\n logger = logging.getLogger(__name__)\n if isinstance(evaluators, DatasetEvaluator):\n evaluators = [evaluators]\n if evaluators is not None:\n assert len(cfg.DATASETS.TEST) == len(evaluators), \"{} != {}\".format(\n len(cfg.DATASETS.TEST), len(evaluators)\n )\n\n results = OrderedDict()\n for idx, dataset_name in enumerate(cfg.DATASETS.TEST):\n data_loader = cls.build_test_loader(cfg, dataset_name)\n # When evaluators are passed in as arguments,\n # implicitly assume that evaluators can be created before data_loader.\n if evaluators is not None:\n evaluator = evaluators[idx]\n else:\n try:\n embedder = cls.extract_embedder_from_model(model)\n evaluator = cls.build_evaluator(cfg, dataset_name, embedder=embedder)\n except NotImplementedError:\n logger.warn(\n \"No evaluator found. Use `DefaultTrainer.test(evaluators=)`, \"\n \"or implement its `build_evaluator` method.\"\n )\n results[dataset_name] = {}\n continue\n results_i = inference_on_dataset(model, data_loader, evaluator)\n results[dataset_name] = results_i\n if comm.is_main_process():\n assert isinstance(\n results_i, dict\n ), \"Evaluator must return a dict on the main process. Got {} instead.\".format(\n results_i\n )\n logger.info(\"Evaluation results for {} in csv format:\".format(dataset_name))\n print_csv_format(results_i)\n\n if len(results) == 1:\n results = list(results.values())[0]\n return results\n\n @classmethod\n def build_evaluator(\n cls,\n cfg: CfgNode,\n dataset_name: str,\n output_folder: Optional[str] = None,\n embedder: Embedder = None,\n ) -> DatasetEvaluators:\n if output_folder is None:\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n evaluators = []\n evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\n if evaluator_type == \"coco\":\n evaluators.append(COCOEvaluator(dataset_name, output_dir=output_folder))\n elif evaluator_type == \"lvis\":\n evaluators.append(LVISEvaluator(dataset_name, output_dir=output_folder))\n if cfg.MODEL.DENSEPOSE_ON:\n evaluators.append(\n DensePoseCOCOEvaluator(dataset_name, True, output_folder, embedder=embedder)\n )\n return DatasetEvaluators(evaluators)\n\n @classmethod\n def build_optimizer(cls, cfg: CfgNode, model: nn.Module):\n params = get_default_optimizer_params(\n model,\n base_lr=cfg.SOLVER.BASE_LR,\n weight_decay=cfg.SOLVER.WEIGHT_DECAY,\n weight_decay_norm=cfg.SOLVER.WEIGHT_DECAY_NORM,\n bias_lr_factor=cfg.SOLVER.BIAS_LR_FACTOR,\n weight_decay_bias=cfg.SOLVER.WEIGHT_DECAY_BIAS,\n overrides={\n \"features\": {\n \"lr\": cfg.SOLVER.BASE_LR * cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.FEATURES_LR_FACTOR,\n },\n \"embeddings\": {\n \"lr\": cfg.SOLVER.BASE_LR * cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBEDDING_LR_FACTOR,\n },\n },\n )\n optimizer = torch.optim.SGD(\n params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM, nesterov=cfg.SOLVER.NESTEROV\n )\n return maybe_add_gradient_clipping(cfg, optimizer)\n\n @classmethod\n def build_test_loader(cls, cfg: CfgNode, dataset_name):\n return build_detection_test_loader(cfg, dataset_name, mapper=DatasetMapper(cfg, False))\n\n @classmethod\n def build_train_loader(cls, cfg: CfgNode):\n data_loader = build_detection_train_loader(cfg, mapper=DatasetMapper(cfg, True))\n if not has_inference_based_loaders(cfg):\n return data_loader\n model = cls.build_model(cfg)\n model.to(cfg.BOOTSTRAP_MODEL.DEVICE)\n DetectionCheckpointer(model).resume_or_load(cfg.BOOTSTRAP_MODEL.WEIGHTS, resume=False)\n inference_based_loaders, ratios = build_inference_based_loaders(cfg, model)\n loaders = [data_loader] + inference_based_loaders\n ratios = [1.0] + ratios\n combined_data_loader = build_combined_loader(cfg, loaders, ratios)\n sample_counting_loader = SampleCountingLoader(combined_data_loader)\n return sample_counting_loader\n\n def build_writers(self):\n writers = super().build_writers()\n writers.append(SampleCountMetricPrinter())\n return writers\n\n @classmethod\n def test_with_TTA(cls, cfg: CfgNode, model):\n logger = logging.getLogger(\"detectron2.trainer\")\n # In the end of training, run an evaluation with TTA\n # Only support some R-CNN models.\n logger.info(\"Running inference with test-time augmentation ...\")\n transform_data = load_from_cfg(cfg)\n model = DensePoseGeneralizedRCNNWithTTA(\n cfg, model, transform_data, DensePoseDatasetMapperTTA(cfg)\n )\n evaluators = [\n cls.build_evaluator(\n cfg, name, output_folder=os.path.join(cfg.OUTPUT_DIR, \"inference_TTA\")\n )\n for name in cfg.DATASETS.TEST\n ]\n res = cls.test(cfg, model, evaluators)\n res = OrderedDict({k + \"_TTA\": v for k, v in res.items()})\n return res\n" ]
[ [ "numpy.unique" ], [ "torch.optim.SGD" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
catalyst-cooperative/epacems_ramp_rates
[ "5a5ea6f9571823f7ef3f9c66abb4d9acb79820be" ]
[ "tests/features/test_build_features.py" ]
[ "import pytest\nimport pandas as pd\nimport numpy as np\n\nfrom ramprate.build_features import _find_uptime\n\n\ndef test__find_uptime_start_and_end_nonzero():\n dt_idx = pd.date_range(start=\"2020-01-01 00:00\", periods=6, freq=\"h\", tz=\"UTC\")\n data = [2, 2, 0, 0, 0, 2]\n\n # downtime=True\n # first zero after non-zero\n shutdown = pd.to_datetime([\"2020-01-01 02:00\"], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([\"2020-01-01 04:00\"], utc=True)\n expected = pd.DataFrame({\"shutdown\": shutdown, \"startup\": startup})\n actual = _find_uptime(pd.Series(data, index=dt_idx), downtime=True)\n pd.testing.assert_frame_equal(actual, expected)\n # end points ('startup') are after start points ('shutdown')\n assert actual.diff(axis=1)[\"startup\"].dt.total_seconds().fillna(1).ge(0).all()\n\n # downtime=False\n # last zero before non-zero\n startup = pd.to_datetime([pd.NaT, \"2020-01-01 04:00\"], utc=True)\n # first zero after non-zero\n shutdown = pd.to_datetime([\"2020-01-01 02:00\", pd.NaT], utc=True)\n expected = pd.DataFrame({\"startup\": startup, \"shutdown\": shutdown})\n actual = _find_uptime(pd.Series(data, index=dt_idx))\n pd.testing.assert_frame_equal(actual, expected)\n # end points ('shutdown') are after start points ('startup')\n assert actual.diff(axis=1)[\"shutdown\"].dt.total_seconds().fillna(1).ge(0).all()\n\n\ndef test__find_uptime_all_zeros():\n dt_idx = pd.date_range(start=\"2020-01-01 00:00\", periods=6, freq=\"h\", tz=\"UTC\")\n data = [0, 0, 0, 0, 0, 0]\n\n # downtime=True\n # first zero after non-zero\n shutdown = pd.to_datetime([pd.NaT], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([pd.NaT], utc=True)\n expected = pd.DataFrame({\"shutdown\": shutdown, \"startup\": startup})\n actual = _find_uptime(pd.Series(data, index=dt_idx), downtime=True)\n pd.testing.assert_frame_equal(actual, expected)\n\n # downtime=False\n # first zero after non-zero\n shutdown = pd.to_datetime([], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([], utc=True)\n expected = pd.DataFrame({\"startup\": startup, \"shutdown\": shutdown})\n actual = _find_uptime(pd.Series(data, index=dt_idx))\n pd.testing.assert_frame_equal(actual, expected)\n\n\ndef test__find_uptime_no_zeros():\n dt_idx = pd.date_range(start=\"2020-01-01 00:00\", periods=6, freq=\"h\", tz=\"UTC\")\n data = [5, 5, 5, 5, 5, 5]\n\n # downtime=True\n # first zero after non-zero\n shutdown = pd.to_datetime([], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([], utc=True)\n expected = pd.DataFrame({\"shutdown\": shutdown, \"startup\": startup})\n actual = _find_uptime(pd.Series(data, index=dt_idx), downtime=True)\n pd.testing.assert_frame_equal(actual, expected)\n\n # downtime=False\n # first zero after non-zero\n shutdown = pd.to_datetime([pd.NaT], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([pd.NaT], utc=True)\n expected = pd.DataFrame({\"startup\": startup, \"shutdown\": shutdown})\n actual = _find_uptime(pd.Series(data, index=dt_idx))\n pd.testing.assert_frame_equal(actual, expected)\n\n\ndef test__find_uptime_start_zero_end_zero():\n dt_idx = pd.date_range(start=\"2020-01-01 00:00\", periods=6, freq=\"h\", tz=\"UTC\")\n data = [0, 2, 2, 0, 2, 0]\n\n # downtime=True\n # first zero after non-zero\n shutdown = pd.to_datetime([pd.NaT, \"2020-01-01 03:00\", \"2020-01-01 05:00\"], utc=True)\n # last zero before non-zero\n startup = pd.to_datetime([\"2020-01-01 00:00\", \"2020-01-01 03:00\", pd.NaT], utc=True)\n expected = pd.DataFrame({\"shutdown\": shutdown, \"startup\": startup})\n actual = _find_uptime(pd.Series(data, index=dt_idx), downtime=True)\n pd.testing.assert_frame_equal(actual, expected)\n # end points ('startup') are after start points ('shutdown')\n assert actual.diff(axis=1)[\"startup\"].dt.total_seconds().fillna(1).ge(0).all()\n\n # downtime=False\n # last zero before non-zero\n startup = pd.to_datetime([\"2020-01-01 00:00\", \"2020-01-01 03:00\"], utc=True)\n # first zero after non-zero\n shutdown = pd.to_datetime([\"2020-01-01 03:00\", \"2020-01-01 05:00\"], utc=True)\n expected = pd.DataFrame({\"startup\": startup, \"shutdown\": shutdown})\n actual = _find_uptime(pd.Series(data, index=dt_idx))\n pd.testing.assert_frame_equal(actual, expected)\n # end points ('shutdown') are after start points ('startup')\n assert actual.diff(axis=1)[\"shutdown\"].dt.total_seconds().fillna(1).ge(0).all()\n" ]
[ [ "pandas.to_datetime", "pandas.Series", "pandas.DataFrame", "pandas.testing.assert_frame_equal", "pandas.date_range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
nguyenvu2589/Numerical
[ "23eee7d31a8871d5d53871ebc9950866cf11ad23" ]
[ "cubicsplines.py" ]
[ "import numpy as np\nimport re\nimport matplotlib.pyplot as plt\n\ndebug = False\n\n\n# Takes a string of points in the string form: '(-1,3), (0,5), (3,1), (4,1), (5,1)'\n# and optionally, the graph resolution.\n# Prints the cubic spline functions to stdout and displays an interpolated line plot\n# Example usage: cubicSpline('(-1,3), (0,5), (3,1), (4,1), (5,1)')\n# or cubicSpline('(-1,3), (0,5), (3,1), (4,1), (5,1)', resolution=2) for a low resolution graph.\n\ndef cubicSpline(points, resolution=100):\n if not points:\n raise Exception('You must provide in data points.')\n return\n\n # Parse the coordinate inputs\n if not points.count('(') == points.count(')'):\n raise Exception('Input coordinates were malformed.')\n return\n\n coordinates = re.findall(r'\\(.*?\\)', points)\n\n coordinates = [item.replace('(', '').replace(')', '') for item in coordinates]\n\n # Split and convert values\n x = []\n y = []\n for coordinate in coordinates:\n try:\n x_val, y_val = [float(num) for num in coordinate.split(',')]\n x.append(x_val)\n y.append(y_val)\n except ValueError:\n raise Exception('Input coordinates were malformed.')\n\n if not len(x) == len(y):\n raise Exception('Length of X and Y arrays must be equal.')\n exit(1)\n\n # Sort the input, just in case\n y = [y for (x, y) in sorted(zip(x, y))]\n x.sort()\n\n # Get the number of inputs\n n = len(x)\n\n # Solve for little delta\n delta = np.zeros((n - 1, 1))\n for i in range(0, n - 1):\n delta[i] = x[i + 1] - x[i]\n\n # Solve for big delta\n Delta = np.zeros((n - 1, 1))\n for i in range(0, n - 1):\n Delta[i] = y[i + 1] - y[i]\n\n if debug:\n print(delta)\n print(Delta)\n\n A = np.zeros((n, n))\n\n A[0, 0] = 1\n A[n - 1, n - 1] = 1\n\n for i in range(1, n - 1):\n A[i, i - 1] = delta[i - 1]\n A[i, i] = 2 * (delta[i - 1] + delta[i])\n A[i, i + 1] = delta[i]\n\n b = np.zeros((n, 1))\n\n for i in range(1, n - 1):\n b[i] = (3 * ((Delta[i] / delta[i]) - (Delta[i - 1] / delta[i - 1])))\n\n # Solve for c coefficients\n ci = np.linalg.solve(A, b)\n\n if debug:\n print(ci)\n\n # Solve for d coefficients\n di = np.zeros((n - 1, 1))\n for i in range(0, n - 1):\n di[i] = (ci[i + 1] - ci[i]) / (3 * delta[i])\n\n if debug:\n print(di)\n\n # Solve for b coefficients\n bi = np.zeros((n - 1, 1))\n for i in range(0, n - 1):\n bi[i] = (Delta[i] / delta[i]) - (delta[i] / 3) * (2 * ci[i] + ci[i + 1])\n\n # And finally, let's get our formulas!\n Si = []\n formulas = []\n for i in range(0, n - 1):\n tempFormula = \"{0} + {1}* (x_val - {2}) + {3}* (x_val - {4})**2 + {5}* (x_val - {6})**3\"\n tempFormula = tempFormula.format(str(y[i]), str(bi[i]), str(x[i]), str(ci[i]), str(x[i]), str(di[i]), str(x[i]))\n\n # ugly but formats the formula nice\n tempFormula = re.sub(' +', ' ', tempFormula.replace('[', ' ').replace(']', ' '))\n tempString = ((\"S{0}(x) = \" + tempFormula).format(str(i + 1)).replace('**', '^')\n .replace('x_val', 'x').replace('- -', '+ ').replace('x - 0', 'x'))\n formulas.append(tempFormula)\n Si.append(tempString)\n\n for i in range(0, len(Si)):\n print(Si[i])\n\n x_vals = []\n y_vals = []\n # Set up the plot\n for i in range(0, n - 1):\n xf = np.linspace(x[i], x[i + 1], resolution)\n yf = []\n\n for j in range(0, resolution):\n # Due to Python's variable declarations we have x_val references in the formulas,\n # but PEP 8 will complain the value is unused. It's not.\n x_val = xf[j]\n yf.append(eval(formulas[i]))\n\n x_vals.extend(xf)\n y_vals.extend(yf)\n\n plt.plot(x, y, 'o', x_vals, y_vals, '-')\n\n plt.legend(['Input X Values', 'Cubic Spline curve'], loc='best')\n plt.title('Cubic Spline Interpolation')\n # plt.show()\n\n#cubicSpline('(0,1),(2,2),(3,4)')\n\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linalg.solve", "matplotlib.pyplot.title", "numpy.linspace", "matplotlib.pyplot.plot", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jinglescode/python-signal-processing
[ "c3de02b12905f14a2350377d7f4a868bd7a40bc7" ]
[ "splearn/data/sample_ssvep.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"A 40-target SSVEP dataset recorded from a single subject.\n\"\"\"\nimport numpy as np\nfrom scipy.io import loadmat\nimport os\n\n\nclass SampleSSVEPData():\n r\"\"\"\n A 40-target SSVEP dataset recorded from a single subject.\n \n Data description:\n Original Data shape : (40, 9, 1250, 6) [# of targets, # of channels, # of sampling points, # of blocks]\n Stimulus frequencies : 8.0 - 15.8 Hz with an interval of 0.2 Hz\n Stimulus phases : 0pi, 0.5pi, 1.0pi, and 1.5pi\n Number of channels : 9 (1: Pz, 2: PO5,3: PO3, 4: POz, 5: PO4, 6: PO6, 7: O1, 8: Oz, and 9: O2)\n Number of recording blocks : 6\n Length of an epoch : 5 seconds\n Sampling rate : 250 Hz\n Args:\n path: str, default: None\n Path to ssvepdata.mat file\n Usage:\n >>> from splearn.cross_decomposition.trca import TRCA\n >>> from splearn.data.sample_ssvep import SampleSSVEPData\n >>> \n >>> data = SampleSSVEPData()\n >>> eeg = data.get_data()\n >>> labels = data.get_targets()\n >>> print(\"eeg.shape:\", eeg.shape)\n >>> print(\"labels.shape:\", labels.shape)\n Reference:\n https://www.pnas.org/content/early/2015/10/14/1508080112.abstract\n \"\"\"\n def __init__(self, path=None):\n if path is None:\n path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"sample\")\n \n # Get EEG data\n data = loadmat(os.path.join(path,\"ssvep.mat\"))\n data = data[\"eeg\"]\n data = data.transpose([3,0,1,2])\n self.data = data\n \n # Prepare targets\n n_blocks, n_targets, n_channels, n_samples = self.data.shape\n targets = np.tile(np.arange(0, n_targets+0), (1, n_blocks))\n targets = targets.reshape((n_blocks, n_targets))\n self.targets = targets\n \n # Prepare targets frequencies\n self.stimulus_frequencies = np.array([8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,8.4,9.4,10.4,11.4,12.4,13.4,14.4,15.4,8.6,9.6,10.6,11.6,12.6,13.6,14.6,15.6,8.8,9.8,10.8,11.8,12.8,13.8,14.8,15.8])\n \n targets_frequencies = np.tile(self.stimulus_frequencies, (1, n_blocks))\n targets_frequencies = targets_frequencies.reshape((n_blocks, n_targets))\n self.targets_frequencies = targets_frequencies\n\n self.sampling_rate = 250\n self.channels = [\"Pz\", \"PO5\",\"PO3\", \"POz\", \"PO4\", \"PO6\", \"O1\", \"Oz\", \"O2\"]\n \n def get_data(self):\n r\"\"\"\n Data shape: (6, 40, 9, 1250) [# of blocks, # of targets, # of channels, # of sampling points]\n \"\"\"\n return self.data\n \n def get_targets(self):\n r\"\"\"\n Targets index from 0 to 39. Shape: (6, 40) [# of blocks, # of targets]\n \"\"\"\n return self.targets\n \n def get_stimulus_frequencies(self):\n r\"\"\"\n A list of frequencies of each stimulus:\n [8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,8.4,9.4,10.4,11.4,12.4,13.4,14.4,15.4,8.6,9.6,10.6,11.6,12.6,13.6,14.6,15.6,8.8,9.8,10.8,11.8,12.8,13.8,14.8,15.8]\n \"\"\"\n return self.stimulus_frequencies\n \n def get_targets_frequencies(self):\n r\"\"\"\n Targets by frequencies, range between 8.0 Hz to 15.8 Hz.\n Shape: (6, 40) [# of blocks, # of targets]\n \"\"\"\n return self.targets_frequencies\n\n\nif __name__ == \"__main__\":\n from splearn.data.sample_ssvep import SampleSSVEPData\n \n data = SampleSSVEPData()\n eeg = data.get_data()\n labels = data.get_targets()\n print(\"eeg.shape:\", eeg.shape)\n print(\"labels.shape:\", labels.shape)\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.tile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
khoehlein/CNNs-for-Wind-Field-Downscaling
[ "eb8418d4d893fcb2beb929abb241281b7a9b6a95", "eb8418d4d893fcb2beb929abb241281b7a9b6a95", "eb8418d4d893fcb2beb929abb241281b7a9b6a95", "eb8418d4d893fcb2beb929abb241281b7a9b6a95" ]
[ "networks/modular_downscaling_model/core_modules/ResUNetSuper.py", "networks/modular_downscaling_model/base_modules/ConvBlock.py", "TrainingScriptLocLin.py", "networks/modular_downscaling_model/input_modules/interpolation/SubsamplingModuleHR.py" ]
[ "import torch.nn as nn\nfrom networks.modular_downscaling_model.base_modules import ConvBlock, ResNetMultiBlock, ConvMultiBlock\nfrom networks.modular_downscaling_model.core_modules.unet_template import BaseUNet\nfrom networks.modular_downscaling_model.core_modules.unet_template.SkipConnectionModule import SkipConnectionModule\nfrom networks.modular_downscaling_model.core_modules.unet_template.DecodingModule import DecodingModule\n\n\nclass ResUNetSuper(BaseUNet):\n \"\"\"\n This is a U-Net with Residual Blocks that directly performs upsampling on low-res input.\n The difference to the \"old\" (legacy) Residual U-Net is that after processing the input in low-res\n resolution we directly upsampling to the target resolution and perform encoding and decoding to the\n final image. This works better than the usual procedure (inserting a U-Net inbetween input processing\n and supersampling blocks). Dropout in both encode and decode parts improve overfitting\n (control with use_dropout_decode). However, one can use dropout in the encoding layers only.\n Note that we operate on low-resolution inputs as this reduced the size of the network. Operating on\n high-res is also possible (disable init_upsampling), however this increases the network size and the\n time to complete the training, and it does not lead to better results. There is also an option\n to add an additional convolution layer block to process the (upsampled) input (with feature_channels).\n \"\"\"\n\n __options__ = {\n 'input_channels': 4,\n 'kernel_size': 3,\n 'padding_mode': 'replication',\n 'leaky_slope': 0.2,\n 'dropout_rate': 0.1,\n 'batch_norm': True,\n 'interpolation_mode': 'bilinear',\n 'residual_blocks_per_module': 1,\n 'layers_per_residual_block': 2,\n 'use_dropout_decode': True,\n 'init_upsampling': True,\n 'init_convolution': False,\n 'feature_channels': 64,\n }\n\n def __init__(self, **kwargs):\n super(ResUNetSuper, self).__init__(**kwargs)\n self._build_unet()\n self.output_channels = self.model.outer_channels\n\n def _processing_module(\n self,\n input_channels, **kwargs\n ):\n module = ResNetMultiBlock(\n input_channels=input_channels, feature_channels=input_channels, kernel_size=self.kernel_size,\n padding_mode=self.padding_mode,\n leaky_slope=self.leaky_slope, dropout_rate=self.dropout_rate,\n use_batch_norm=self.batch_norm,\n num_resnet_blocks=self.residual_blocks_per_module,\n num_hidden_layers=self.layers_per_residual_block,\n )\n return module\n\n def _downsampling_module(\n self,\n input_channels, output_channels, scale_factor, **kwargs\n ):\n module = ConvBlock(\n input_channels=input_channels, output_channels=output_channels,\n stride=scale_factor, kernel_size=self.kernel_size,\n padding_mode=self.padding_mode,\n leaky_slope=self.leaky_slope, dropout_rate=self.dropout_rate,\n use_batch_norm=self.batch_norm,\n )\n return module\n\n def _upsampling_resolution_module(\n self,\n input_channels, output_channels, scale_factor, **kwargs\n ):\n module = nn.Upsample(scale_factor=scale_factor, mode=self.interpolation_mode)\n\n # block = [nn.Upsample(scale_factor=scale_factor, mode=self.interpolation_mode)]\n\n # block += [ConvBlock(\n # input_channels=input_channels, output_channels=output_channels,\n # kernel_size=self.kernel_size,\n # padding_mode=self.padding_mode,\n # leaky_slope=self.leaky_slope, dropout_rate=self.dropout_rate,\n # use_batch_norm=self.batch_norm\n # )]\n\n # module = nn.Sequential(*block)\n return module\n\n def _upsampling_feature_module(\n self,\n input_channels, output_channels, scale_factor, **kwargs\n ):\n module = ConvBlock(\n input_channels=input_channels, output_channels=output_channels,\n kernel_size=self.kernel_size,\n padding_mode=self.padding_mode,\n leaky_slope=self.leaky_slope, dropout_rate=self.dropout_rate,\n use_batch_norm=self.batch_norm\n )\n return module\n\n def _processing_module_decode(\n self,\n input_channels, **kwargs\n ):\n module = ResNetMultiBlock(\n input_channels=input_channels, feature_channels=input_channels, kernel_size=self.kernel_size,\n padding_mode=self.padding_mode,\n leaky_slope=self.leaky_slope, dropout_rate=0.0,\n use_batch_norm=self.batch_norm,\n num_resnet_blocks=self.residual_blocks_per_module,\n num_hidden_layers=self.layers_per_residual_block,\n )\n return module\n\n def _decoding_module(\n self,\n input_channels, output_channels, scale_factor, **kwargs\n ):\n if self.use_dropout_decode:\n module = DecodingModule(\n self._upsampling_module(input_channels, output_channels, scale_factor, **kwargs),\n self._processing_module(output_channels, **kwargs),\n inner_channels=input_channels,\n outer_channels=output_channels\n )\n else:\n module = DecodingModule(\n self._upsampling_module(input_channels, output_channels, scale_factor, **kwargs),\n self._processing_module_decode(output_channels, **kwargs),\n inner_channels=input_channels,\n outer_channels=output_channels\n )\n return module\n\n def _build_init_module(self, input_channels, output_channels):\n \"\"\"\n Build an input module to process the data. For now, we assume that input has been processed\n beforehand and we just deal with this processed input. No raw data processing is supported by default.\n However, enabling init convolution enables the network to cope with raw data, as well.\n Then, see that the input_channels match the number of input features.\n \"\"\"\n block = []\n if self.init_upsampling:\n # upsample image to final target resolution\n block += [nn.Upsample(scale_factor=(4, 3), mode=self.interpolation_mode)]\n\n if self.init_convolution:\n # process the input with a convolution block\n block += ConvBlock(\n input_channels=input_channels, output_channels=output_channels,\n kernel_size=self.kernel_size,\n padding_mode=self.padding_mode,\n leaky_slope=self.leaky_slope, dropout_rate=self.dropout_rate,\n use_batch_norm=self.batch_norm\n )\n\n self.upsample_input = nn.Sequential(*block)\n\n def _build_unet(self):\n \"\"\"\n This function overrides the BaseUNet function to build a U-Net. Note that we do not perform\n a \"default\" standard U-Net but included 3 additional encoding / decoding layers to reduce\n the target high-res resolution to small dimension and vice versa.\n \"\"\"\n # handle either processed input or raw input data\n init_output_channels = self.feature_channels if self.init_convolution else self.input_channels\n self._build_init_module(self.input_channels, init_output_channels)\n\n model = self._skip_connection_module(\n 6 * init_output_channels, 7 * init_output_channels,\n (2, 2),\n inner_module=None\n )\n model = self._skip_connection_module(\n 5 * init_output_channels, 6 * init_output_channels,\n (2, 2),\n inner_module=model\n )\n model = self._skip_connection_module(\n 4 * init_output_channels, 5 * init_output_channels,\n (3, 3),\n inner_module=model\n )\n\n model = self._skip_connection_module(\n 3 * init_output_channels, 4 * init_output_channels,\n (2, 1),\n inner_module=model\n )\n\n model = self._skip_connection_module(\n 2 * init_output_channels, 3 * init_output_channels,\n (1, 3),\n inner_module=model\n )\n\n model = self._skip_connection_module(\n init_output_channels, 2 * init_output_channels,\n (2, 1),\n inner_module=model\n )\n\n self.model = model\n\n def forward(self, features):\n \"\"\"\n The difference to the standard forward method is that we first upsample the image\n to the target resolution\n \"\"\"\n output = self.upsample_input(features)\n output = self.model(output)\n return output\n\n\nif __name__ == '__main__':\n model = ResUNetSuper()\n print(model)\n", "import numbers\nimport torch.nn as nn\nfrom networks.modular_downscaling_model.base_modules import ParametricModule\n\n\nclass ConvBlock(ParametricModule):\n\n __options__ = {\n 'input_channels': None,\n 'output_channels': None,\n 'kernel_size': 5,\n 'stride': (1, 1), # can be used for downsampling\n 'padding': 'keep_dimensions',\n 'padding_mode': 'replication',\n 'use_batch_norm': True,\n 'leaky_slope': 0.2, 'dropout_rate': 0.0\n }\n\n def __init__(self, **kwargs):\n super(ConvBlock, self).__init__(**kwargs)\n self._require_not_none('input_channels', 'output_channels')\n assert(isinstance(self.stride, (tuple, list)))\n if self.padding == 'keep_dimensions':\n # compute padding to keep same dimension\n if isinstance(self.kernel_size, numbers.Number):\n kernel_size_half = (self.kernel_size // 2, ) * 2\n elif isinstance(self.kernel_size, (tuple, list)):\n kernel_size_half = (self.kernel_size[0] // 2, self.kernel_size[1] // 2)\n else:\n raise Exception()\n self.padding = kernel_size_half\n else:\n assert(isinstance(self.padding, (int, tuple, list)))\n conv_block = []\n p = self.padding\n if not self.padding == 0 or self.padding == (0, 0) or self.padding == [0, 0]:\n if isinstance(self.padding, (tuple, list)) and len(self.padding) == 2:\n # handle asymmetric case\n self.padding = (self.padding[1], self.padding[1], self.padding[0], self.padding[0])\n p = 0\n if self.padding_mode == 'reflection':\n conv_block += [nn.ReflectionPad2d(self.padding)]\n elif self.padding_mode == 'replication':\n conv_block += [nn.ReplicationPad2d(self.padding)]\n elif self.padding_mode == 'zero':\n # conv_block += [nn.ZeroPad2d(padding)]\n p = self.padding\n else:\n raise NotImplementedError('Padding mode <{}> not implemented'.format(self.padding_mode))\n conv_block += [\n nn.Conv2d(self.input_channels, self.output_channels, kernel_size=self.kernel_size, stride=self.stride, padding=p)\n ]\n # Batch normalization\n if self.use_batch_norm:\n conv_block += [nn.BatchNorm2d(self.output_channels)]\n # LeakyReLU\n if isinstance(self.leaky_slope, (int, float)):\n if self.leaky_slope != 1.0:\n conv_block += [nn.LeakyReLU(float(self.leaky_slope), inplace=True)]\n elif self.leaky_slope == 'p':\n conv_block += [nn.PReLU(num_parameters=self.output_channels)]\n else:\n raise Exception()\n # Dropout layer\n if self.dropout_rate > 0.0:\n conv_block += [nn.Dropout2d(self.dropout_rate, inplace=False)]\n self.conv_block = nn.Sequential(*conv_block)\n\n def forward(self, x):\n output = self.conv_block(x)\n return output\n\n\nif __name__ == '__main__':\n c = ConvBlock(input_channels=1, target_channels=2)", "import numpy as np\nimport os\nimport argparse\nimport json\nimport torch\n\n# import matplotlib.pyplot as plt\n\nfrom data import GridConfigurator, DataConfigurator\nfrom data.datasets import NearestNeighborData\nfrom networks.modular_downscaling_model import ModelConfigurator\nfrom losses import LossConfigurator\nfrom training.localized_linear_model import TrainingConfigurator\n\n\ndef get_model_indices(geometry, step=3, offset=1):\n s = 0\n indices = []\n if isinstance(geometry, dict):\n mask = geometry[list(geometry.keys())[0]].mask\n else:\n mask = geometry.mask\n for i, row in enumerate(mask):\n c = int(np.sum(1 - row))\n if i % step == offset % step:\n current_indices = np.arange(c) + s\n indices.append(current_indices[offset::step])\n s += c\n indices = np.concatenate(indices).astype(int)\n print('[INFO] Model indices:', indices)\n return indices\n\n\nprint(\"[INFO] Running TrainingScript.py in directory <{}>\".format(os.getcwd()))\n\nparser = argparse.ArgumentParser()\nparser.add_argument('config_path', type=str, help=\"absolute or relative path to config file\")\nparser.add_argument('gpu', type=int, help='ID of CUDA device to use')\nopt = parser.parse_args()\n\nassert opt.config_path.endswith('.json')\n\nwith open(opt.config_path, encoding='utf-8') as f:\n config = json.load(f)\n\nconfig[\"training\"].update({\"gpu\": opt.gpu})\n\ntorch.set_num_threads(4)\n\ngrids = GridConfigurator().build_grids(config['grids'])\n\ndatasets = DataConfigurator(grids=grids).build_dataset(config['data'])\n\nfor step_name in ['training', 'validation', 'test']:\n if step_name in datasets:\n step_data = datasets['training']\n if step_name == 'training':\n grids.fit_transform(datasets['training'])\n else:\n grids.transform(datasets['validation'])\n\nprint('[INFO] Building model.')\n\nmodel = ModelConfigurator(grids=grids).build_model(config['model'])\nmodel.set_model_index(\n datasets['training'].geometry_lr, datasets['training'].geometry_hr,\n # model_index=get_model_indices(datasets['training'].geometry_hr)\n)\n\n# plt.figure()\n# plt.scatter(model.model_index_lon, model.model_index_lat)\n# plt.show()\n\nprint(model)\n\ndatasets = {\n step_name: NearestNeighborData(\n datasets[step_name],\n model_index=model.model_index,\n k=model.num_nearest_neighbors_lr,\n name=step_name\n )\n for step_name in datasets.keys()\n}\n\nlosses = LossConfigurator().build_losses(config['losses'])\n\nconfig['training'].update({'residual_interpolation_mode': None})\n\ntraining_process = TrainingConfigurator().build_training_process(\n grids,\n datasets,\n losses,\n model,\n config['training']\n)\n\ntraining_process.save_config(config)\n\ntraining_process.run()\n", "import numbers\nimport torch.nn as nn\nfrom networks.modular_downscaling_model.base_modules import ParametricModule\n\n\nclass SubsamplingModuleHR(ParametricModule):\n __options__ = {\n 'channels': 6,\n 'scale_factor': (4, 3),\n 'padding_mode': 'replication'\n }\n\n def __init__(self, **kwargs):\n super(SubsamplingModuleHR, self).__init__(**kwargs)\n if isinstance(self.scale_factor, numbers.Number):\n self.scale_factor = [self.scale_factor] * 2\n self.input_channels = self.channels\n self.output_channels = self.channels\n # kernel_size = [2 * f - 1 for f in self.scale_factor]\n # sigma = self.scale_factor\n self._build_padding_layer(self.scale_factor)\n self.filter = nn.AvgPool2d(kernel_size=self.scale_factor, stride=self.scale_factor)\n\n def _build_padding_layer(self, kernel_size):\n assert isinstance(kernel_size, (list, tuple))\n padding = [k // 2 for k in kernel_size]\n if not padding == (0, 0) or padding == [0, 0]:\n if isinstance(padding, (tuple, list)) and len(padding) == 2:\n # handle asymmetric case\n padding = (padding[1], padding[1], padding[0], padding[0])\n if self.padding_mode == 'reflection':\n layer = nn.ReflectionPad2d(padding)\n elif self.padding_mode == 'replication':\n layer = nn.ReplicationPad2d(padding)\n elif self.padding_mode == 'zero':\n layer = nn.ZeroPad2d(padding)\n else:\n raise NotImplementedError('Padding mode <{}> not implemented'.format(self.padding_mode))\n self.padding_module = layer\n else:\n self.padding_module = None\n\n def forward(self, input_hr):\n assert input_hr.size(1) == self.channels\n output = input_hr\n if self.padding_module is not None:\n output = self.padding_module(output)\n output = self.filter(output)\n return output\n\n\nif __name__ == '__main__':\n model = SubsamplingModuleHR()\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Upsample" ], [ "torch.nn.Sequential", "torch.nn.ReflectionPad2d", "torch.nn.Dropout2d", "torch.nn.PReLU", "torch.nn.Conv2d", "torch.nn.BatchNorm2d", "torch.nn.ReplicationPad2d" ], [ "numpy.concatenate", "numpy.arange", "torch.set_num_threads", "numpy.sum" ], [ "torch.nn.ZeroPad2d", "torch.nn.AvgPool2d", "torch.nn.ReflectionPad2d", "torch.nn.ReplicationPad2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nicolas998/ifis_tools
[ "f7b06473a916324fc37937bc5e9034cc57bc1623" ]
[ "ifis_tools/from_taudem.py" ]
[ "import pandas as pd \nimport geopandas as gp\nimport numpy as np \nimport pylab as pl \nfrom struct import pack, unpack\nimport io\nimport gdal\nfrom osgeo import ogr\nimport osgeo\n#from wmf import wmf \npd.options.mode.chained_assignment = None\n\ndef read_raster(path_map,isDEMorDIR=False,dxp=None, noDataP = None,isDIR = False,DIRformat = 'r.watershed'):\n 'Funcion: read_map\\n'\\\n 'Descripcion: Lee un mapa raster soportado por GDAL.\\n'\\\n 'Parametros Obligatorios:.\\n'\\\n ' -path_map: path donde se encuentra el mapa.\\n'\\\n 'Parametros Opcionales:.\\n'\\\n ' -isDEMorDIR: Pasa las propiedades de los mapas al modulo cuencas \\n'\\\n ' escrito en fortran \\n'\\\n ' -dxp: tamano plano del mapa\\n'\\\n ' -noDataP: Valor para datos nulos en el mapa (-9999)\\n'\\\n ' -DIRformat: donde se ha conseguido el mapa dir (r.watershed) \\n'\\\n ' - r.watershed: mapa de direcciones obtenido por la funcion de GRASS\\n'\\\n ' - opentopo: mapa de direcciones de http://www.opentopography.org/\\n'\\\n ' -isDIR: (FALSE) es este un mapa de direcciones\\n'\\\n 'Retorno:.\\n'\\\n ' Si no es DEM o DIR retorna todas las propieades del elemento en un vector.\\n'\\\n ' En el siguiente orden: ncols,nrows,xll,yll,dx,nodata.\\n'\\\n ' Si es DEM o DIR le pasa las propieades a cuencas para el posterior trazado.\\n'\\\n ' de cuencas y link_ids.\\n' \\\n #Abre el mapa\n direction=gdal.Open(path_map)\n #Projection\n proj = osgeo.osr.SpatialReference(wkt=direction.GetProjection())\n EPSG_code = proj.GetAttrValue('AUTHORITY',1)\n #lee la informacion del mapa\n ncols=direction.RasterXSize\n nrows=direction.RasterYSize\n banda=direction.GetRasterBand(1)\n noData=banda.GetNoDataValue()\n geoT=direction.GetGeoTransform()\n dx=geoT[1]\n dy = np.abs(geoT[-1])\n xll=geoT[0]; yll=geoT[3]-nrows*dy\n #lee el mapa\n Mapa=direction.ReadAsArray()\n direction.FlushCache()\n del direction\n return Mapa.T.astype(float),[ncols,nrows,xll,yll,dx,dy,noData],EPSG_code\n\ndef save_array2raster(Array, ArrayProp, path, EPSG = 4326, Format = 'GTiff'):\n dst_filename = path\n #Formato de condiciones del mapa\n x_pixels = Array.shape[0] # number of pixels in x\n y_pixels = Array.shape[1] # number of pixels in y\n PIXEL_SIZE_x = ArrayProp[4] # size of the pixel... \n PIXEL_SIZE_y = ArrayProp[5] # size of the pixel...\n x_min = ArrayProp[2]\n y_max = ArrayProp[3] + ArrayProp[5] * ArrayProp[1] # x_min & y_max are like the \"top left\" corner.\n driver = gdal.GetDriverByName(Format)\n #Para encontrar el formato de GDAL\n NP2GDAL_CONVERSION = {\n \"uint8\": 1,\n \"int8\": 1,\n \"uint16\": 2,\n \"int16\": 3,\n \"uint32\": 4,\n \"int32\": 5,\n \"float32\": 6,\n \"float64\": 7,\n \"complex64\": 10,\n \"complex128\": 11,\n }\n gdaltype = NP2GDAL_CONVERSION[Array.dtype.name]\n # Crea el driver\n dataset = driver.Create(\n dst_filename,\n x_pixels,\n y_pixels,\n 1,\n gdaltype,)\n #coloca la referencia espacial\n dataset.SetGeoTransform((\n x_min, # 0\n PIXEL_SIZE_x, # 1\n 0, # 2\n y_max, # 3\n 0, # 4\n -PIXEL_SIZE_y))\n #coloca la proyeccion a partir de un EPSG\n proj = osgeo.osr.SpatialReference()\n texto = 'EPSG:' + str(EPSG)\n proj.SetWellKnownGeogCS( texto )\n dataset.SetProjection(proj.ExportToWkt())\n #Coloca el nodata\n band = dataset.GetRasterBand(1)\n if ArrayProp[-1] is None:\n band.SetNoDataValue(wmf.cu.nodata.astype(int).max())\n else:\n band.SetNoDataValue(int(ArrayProp[-1]))\n #Guarda el mapa\n dataset.GetRasterBand(1).WriteArray(Array.T)\n dataset.FlushCache()\n\ndef rainfall_raster_ranks(path_rain_frame, path_ranks):\n # Reads a raster of the rainfall fields and creates a raster with the ranks \n m, p, epsg = read_raster(path_rain_frame)\n rank = np.arange(1,m.size+1)\n rank = rank.reshape(m.shape)\n save_array2raster(rank , p, path_ranks+'.tif', EPSG=int(epsg))\n # Creates a ranks polygon based on the raster ranks.\n src_ds = gdal.Open(path_ranks+'.tif')\n srcband = src_ds.GetRasterBand(1)\n #Create output datasource\n spatialReference = osgeo.osr.SpatialReference()\n spatialReference.ImportFromEPSG(int(epsg))\n dst_layername = path_ranks\n drv = ogr.GetDriverByName(\"ESRI Shapefile\")\n dst_ds = drv.CreateDataSource( dst_layername + \".shp\" )\n dst_layer = dst_ds.CreateLayer(dst_layername, spatialReference )\n gdal.Polygonize( srcband, None, dst_layer, -1, [], callback=None )\n dst_ds.Destroy()\n\ndef saveBin(lid, lid_vals, count, fn):\n io_buffer_size = 4+4*100000\n if count > 0:\n lid = (lid[lid_vals > 1])\n lid_vals = (lid_vals[lid_vals > 1])\n fh = io.open(fn, 'wb', io_buffer_size)\n fh.write(pack('<I', count))\n for vals in zip(lid, lid_vals):\n fh.write(pack('<If', *vals))\n fh.close()\n\nclass network:\n \n def __init__(self, net_path, hills_path = None, hills_epsg = 2163):\n '''Defines the network class that contains all the requirements to set up a project for\n hlm'''\n #Defines the initial partameters for the network\n self.network = gp.read_file(net_path) \n self.network['link'] = self.network['LINKNO']\n self.network.set_index('LINKNO', inplace=True) \n self.network_centroids = None\n self.network_ranks = None\n #computes the area for each hillslope\n if hills_path is not None:\n self.hills = gp.read_file(hills_path)\n self.hills.rename(columns={'DN':'link'}, inplace = True)\n self.hills.set_index('link', inplace = True)\n self.hills.to_crs(epsg = hills_epsg, inplace = True)\n idx = self.hills.index.intersection(self.network.index)\n self.network['area'] = self.hills.loc[idx].geometry.area/1e6\n print('Area of each hillslope computed from the hills shapefile')\n \n \n def network2points(self):\n '''Converts the network elements to centroids, ideal to get the \n rainfall ranks references'''\n x =[]\n y = []\n for link in self.network.index:\n geo = self.network.loc[link, 'geometry']\n x.append(geo.centroid.x)\n y.append(geo.centroid.y)\n net_centroids = gp.GeoDataFrame(self.network[['link','strmOrder']], geometry = gp.points_from_xy(x, y),\n crs = self.network.crs)\n self.network_centroids = net_centroids\n print('Centroids had been saved under self.network_centroids')\n #return net_centroids\n \n def get_rainfall_lookup(self, path_rain_ranks):\n '''Generates the lookup table between the links and a rainfall that is going to be used\n the rain ranks must be the one obtained with *rainfall_raster_ranks*. By now this operation\n is done one to one.'''\n # Reads the rainfall ranks and project it\n rain_ranks = gp.read_file(path_rain_ranks)\n rain_ranks = rain_ranks.to_crs(self.network.crs)\n print('1. rain ranks readed and projected to the current crs')\n # Checks if centroids are already defined\n if self.network_centroids is None:\n print('2. Network points not defined, defining them...')\n self.network2points()\n print('3. Network points defined') \n # Performs the spatial join\n points_ranked = gp.sjoin(self.network_centroids, rain_ranks, how = 'left', op = 'within')\n self.rain_ranks = points_ranked\n print('4. ranks obtained results stored in self.rain_ranks')\n \n def rain2links(self, rain, path_rain = None):\n '''Converts a grid (tif) file of rainfall to the shape of the network \n using the lookup table obtained by *get_rainfall_lookup*'''\n if rain is None:\n if path_rain is not None:\n #Read and transform rainfall to its ranks \n rain, p, ep = read_raster(path_rain)\n rain = rain.T\n rain = rain.reshape(rain.size)\n else:\n print('Error: No rain variable, no path to rain variable')\n else:\n rain = rain.reshape(rain.size)\n #Put the rinfall in links \n self.rain_ranks['rain'] = 0\n self.rain_ranks['rain'] = rain[self.rain_ranks['FID']]\n # Return the links and the rainfall \n return self.rain_ranks['rain']\n \n def write_rvr(self, path, sub_net = None):\n '''Writes and rvr file based on a network extracted from the base network'''\n #Selects the subnet if it is avaiable\n if sub_net is not None:\n net_elem = sub_net\n else:\n net_elem = self.network\n #Writes the rvr file for HLM\n with open(path,'w',newline='\\n') as f:\n f.write('%d\\n' % net_elem.shape[0])\n f.write('\\n')\n for link in net_elem.index:\n f.write('%d\\n' % link)\n if net_elem.loc[link,'USLINKNO1'] == -1:\n f.write('0\\n')\n else:\n f.write('2 %d %d\\n' % (net_elem.loc[link,'USLINKNO1'], net_elem.loc[link,'USLINKNO2']))\n f.write('\\n')\n f.close()\n \n def get_subnet(self, link):\n '''Allows to define a new network inside of the base network'''\n lista = [link]\n count = 0\n while count < len(lista) or count > self.network.shape[0]:\n link = lista[count]\n if self.network.loc[link, 'USLINKNO1'] != -1:\n lista.append(self.network.loc[link, 'USLINKNO1'])\n lista.append(self.network.loc[link, 'USLINKNO2'])\n count += 1\n return network(self.network.loc[lista])\n \n def get_prm(self):\n for_prm = self.network[['DSContArea','Length','area']]\n for_prm['DSContArea'] = for_prm['DSContArea'] / 1e6\n for_prm.shape[0] == self.network.shape[0]\n\n for_prm.loc[for_prm['Length'] == 0, 'Length'] = 1\n for_prm.loc[for_prm['area'] == 0, 'area'] = 1/1e4\n for_prm.loc[np.isnan(for_prm.prm['area']), 'area'] = 1/1e4\n for_prm['Length'] = for_prm['Length'] / 1000\n self.prm = for_prm\n \n def set_prm_for_model(self, model = 608):\n if model == 608 or model == 609:\n attr = {'vh':0.02,'a_r':1.67,'a':3.2e-6,'b':17,'c':5.4e-7,'d':32,\n 'k3':2.045e-6,'ki_fac':0.07,'TopDepth':0.1,'NoFlow':1.48,'Td':999,\n 'Beta':1.67,'lambda1':0.4,'lambda2':-0.1,'vo':0.435}\n self.prm_format = {'DSContArea':'%.3f','Length':'%.3f','area':'%.5f',\n 'vh':'%.4f','a_r':'%.4f','a':'%.2e','b':'%.1f','c':'%.2e','d':'%.1f',\n 'k3':'%.2e','ki_fac':'%.3f','TopDepth':'%.3f','NoFlow':'%.3f','Td':'%.2f',\n 'Beta':'%.3f','lambda1':'%.3f','lambda2':'%.2f','vo':'%.3f'}\n self.prm = self.prm.assign(**attr)\n elif model == 254 or model == 253 or model == 256:\n self.prm_format = {'DSContArea':'%.3f','Length':'%.3f','area':'%.5f'}\n \n def write_prm(self, path):\n with open(path,'w',newline='\\n') as f:\n f.write('%d\\n\\n' % self.prm.shape[0])\n for link in self.prm.index:\n f.write('%d\\n' % link)\n for c,k in zip(self.prm.loc[link],self.prm_format.keys()):\n fm = self.prm_format[k]+' '\n f.write(fm % c)\n f.write('\\n\\n')\n \n def write_Global(self, path2global, model_uid = 604,\n date1 = None, date2 = None, rvrFile = None, rvrType = 0, rvrLink = 0, prmFile = None, prmType = 0, initialFile = None,\n initialType = 1,rainType = 5, rainPath = None, evpFile = 'evap.mon', datResults = None,\n nComponents = 1, Components = [0], controlFile = None, baseGlobal = None, noWarning = False, snapType = 0,\n snapPath = '', snapTime = '', evpFromSysPath = False):\n '''Creates a global file for the current project.\n - model_uid: is the number of hte model goes from 601 to 604.\n - date1 and date2: initial date and end date\n - rvrFile: path to rvr file.\n - rvrType: 0: .rvr file, 1: databse .dbc file.\n - rvrLink: 0: all the domain, N: number of the linkid.\n - prmFile: path to prm file.\n - prmType: 0: .prm file, 1: databse .dbc file.\n - initialFile: path to file with initial conditions.\n - initialType: type of initial file:\n - 0: ini, 1: uini, 2: rec, 3: .dbc\n - rainType: number inficating the type of the rain to be used.\n - 1: plain text with rainfall data for each link.\n - 3: Database.\n - 4: Uniform storm file: .ustr\n - 5: Binary data with the unix time\n - rainPath: path to the folder containning the binary files of the rain.\n or path to the file with the dabase\n - evpFile: path to the file with the values of the evp.\n - datResults: File where .dat files will be written.\n - nComponents: Number of results to put in the .dat file.\n - Components: Number of each component to write: [0,1,2,...,N]\n - controlFile: File with the number of the links to write.\n - baseGlobal: give the option to use a base global that is not the default\n - snapType: type of snapshot to make with the model:\n - 0: no snapshot, 1: .rec file, 2: to database, 3: to hdf5, 4:\n recurrent hdf5\n - snapPath: path to the snapshot.\n - snapTime: time interval between snapshots (min)\n - evpFromSysPath: add the path of the system to the evp file.'''\n #Open the base global file and creates tyhe template\n if baseGlobal is not None:\n f = open(baseGlobal, 'r')\n L = f.readlines()\n f.close()\n else:\n L = Globals['60X']\n t = []\n for i in L:\n t += i\n Base = Template(''.join(t))\n # Databse rainfall \n if rainType == 3 and rainPath is None:\n rainPath = '/Dedicated/IFC/model_eval/forcing_rain51_5435_s4.dbc'\n if rvrType == 1 and rvrFile is None:\n rvrFile = '/Dedicated/IFC/model_eval/topo51.dbc'\n #Chang the evp path \n if evpFromSysPath:\n evpFile = Path + evpFile\n # Creates the default Dictionary.\n Default = {\n 'model_uid' : model_uid,\n 'date1': date1,\n 'date2': date2,\n 'rvrFile': rvrFile,\n 'rvrType': str(rvrType),\n 'rvrLink': str(rvrLink),\n 'prmFile': prmFile,\n 'prmType': str(prmType),\n 'initialFile': initialFile,\n 'initialType': initialType,\n 'rainType': str(rainType),\n 'rainPath': rainPath,\n 'evpFile': evpFile,\n 'datResults': datResults,\n 'controlFile': controlFile,\n 'snapType': str(snapType),\n 'snapPath': snapPath,\n 'snapTime': str(snapTime),\n 'nComp': str(nComponents)\n }\n if date1 is not None:\n Default.update({'unix1': aux.__datetime2unix__(Default['date1'])})\n else:\n Default.update({'unix1': '$'+'unix1'})\n if date2 is not None:\n Default.update({'unix2': aux.__datetime2unix__(Default['date2'])})\n else:\n Default.update({'unix2': '$'+'unix2'})\n #Update the list of components to write\n for n, c in enumerate(Components):\n Default.update({'Comp'+str(n): 'State'+str(c)})\n if nComponents <= 9:\n for c in range(9-nComponents):\n Default.update({'Comp'+str(8-c): 'XXXXX'})\n #Check for parameters left undefined\n D = {}\n for k in Default.keys():\n if Default[k] is not None:\n D.update({k: Default[k]})\n else:\n if noWarning:\n print('Warning: parameter ' + k +' left undefined model wont run')\n D.update({k: '$'+k})\n #Update parameter on the base and write global \n f = open(path2global,'w', newline='\\n')\n f.writelines(Base.substitute(D))\n f.close()\n #Erase unused print components\n f = open(path2global,'r')\n L = f.readlines()\n f.close()\n flag = True\n while flag:\n try:\n L.remove('XXXXX\\n')\n except:\n flag = False\n f = open(path2global,'w', newline='\\n')\n f.writelines(L)\n f.close()\n\n\n def write_runfile(self, path, process, jobName = 'job',nCores = 56, nSplit = 1, queue = 'IFC'):\n '''Writes the .sh file that runs the model\n Parameters:\n - path: path where the run file is stored.\n - process: dictionary with the parameters for each process to be launch:\n eg: proc = {'Global1.gbl':{'nproc': 12, 'secondplane': True}}\n - ncores: Number of cores.\n - nsplit: Total number of cores for each group.\n - queue: name of the argon queue to run the process'''\n #Define the size of the group of cores\n if nCores%nSplit == 0:\n Groups = int(nCores / nSplit)\n else:\n Groups = int(nCores / 2)\n #Define the header text.\n L = ['#!/bin/sh\\n#$ -N '+jobName+'\\n#$ -j y\\n#$ -cwd\\n#$ -pe smp '+str(nCores)+'\\n####$ -l mf=16G\\n#$ -q '+str(queue)+'\\n\\n/bin/echo Running on host: `hostname`.\\n/bin/echo In directory: `pwd`\\n/bin/echo Starting on: `date`\\n']\n f = open(path,'w', newline='\\n')\n f.write(L[0])\n f.write('\\n')\n\n for k in process.keys():\n secondplane = ' \\n'\n if process[k]['secondplane']:\n secondplane = ' &\\n'\n if process[k]['nproc'] > nCores:\n process[k]['nproc'] = nCores \n f.write('mpirun -np '+str(process[k]['nproc'])+' /Users/nicolas/Tiles/dist/bin/asynch '+k+secondplane)\n f.close()\n\n \n \n\n" ]
[ [ "numpy.isnan", "numpy.arange", "numpy.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jsnlp/snorkel-tutorials
[ "b4cda9f918daf77f4011ec1598c08d9bd7e51c39", "b4cda9f918daf77f4011ec1598c08d9bd7e51c39" ]
[ "spam/02_spam_data_augmentation_tutorial.py", "spam/utils.py" ]
[ "# -*- coding: utf-8 -*-\n# %% [markdown]\n# # 📈 Snorkel Intro Tutorial: Data Augmentation\n\n# %% [markdown]\n# In this tutorial, we will walk through the process of using *transformation functions* (TFs) to perform data augmentation.\n# Like the labeling tutorial, our goal is to train a classifier to YouTube comments as `SPAM` or `HAM` (not spam).\n# In the [previous tutorial](https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/01_spam_tutorial.ipynb),\n# we demonstrated how to label training sets programmatically with Snorkel.\n# In this tutorial, we'll assume that step has already been done, and start with labeled training data,\n# which we'll aim to augment using transformation functions.\n#\n# %% [markdown] {\"tags\": [\"md-exclude\"]}\n# * For more details on the task, check out the [labeling tutorial](https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/01_spam_tutorial.ipynb)\n# * For an overview of Snorkel, visit [snorkel.org](https://snorkel.org)\n# * You can also check out the [Snorkel API documentation](https://snorkel.readthedocs.io/)\n#\n# %% [markdown]\n# Data augmentation is a popular technique for increasing the size of labeled training sets by applying class-preserving transformations to create copies of labeled data points.\n# In the image domain, it is a crucial factor in almost every state-of-the-art result today and is quickly gaining\n# popularity in text-based applications.\n# Snorkel models the data augmentation process by applying user-defined *transformation functions* (TFs) in sequence.\n# You can learn more about data augmentation in\n# [this blog post about our NeurIPS 2017 work on automatically learned data augmentation](https://snorkel.org/blog/tanda/).\n#\n# The tutorial is divided into four parts:\n# 1. **Loading Data**: We load a [YouTube comments dataset](http://www.dt.fee.unicamp.br/~tiago//youtubespamcollection/).\n# 2. **Writing Transformation Functions**: We write Transformation Functions (TFs) that can be applied to training data points to generate new training data points.\n# 3. **Applying Transformation Functions to Augment Our Dataset**: We apply a sequence of TFs to each training data point, using a random policy, to generate an augmented training set.\n# 4. **Training a Model**: We use the augmented training set to train an LSTM model for classifying new comments as `SPAM` or `HAM`.\n\n# %% [markdown] {\"tags\": [\"md-exclude\"]}\n# This next cell takes care of some notebook-specific housekeeping.\n# You can ignore it.\n\n# %% {\"tags\": [\"md-exclude\"]}\nimport os\nimport random\n\nimport numpy as np\n\n# Make sure we're running from the spam/ directory\nif os.path.basename(os.getcwd()) == \"snorkel-tutorials\":\n os.chdir(\"spam\")\n\n# Turn off TensorFlow logging messages\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\n# For reproducibility\nseed = 0\nos.environ[\"PYTHONHASHSEED\"] = str(seed)\nnp.random.seed(0)\nrandom.seed(0)\n\n# %% [markdown] {\"tags\": [\"md-exclude\"]}\n# If you want to display all comment text untruncated, change `DISPLAY_ALL_TEXT` to `True` below.\n\n# %% {\"tags\": [\"md-exclude\"]}\nimport pandas as pd\n\n\nDISPLAY_ALL_TEXT = False\n\npd.set_option(\"display.max_colwidth\", 0 if DISPLAY_ALL_TEXT else 50)\n\n# %% [markdown] {\"tags\": [\"md-exclude\"]}\n# This next cell makes sure a spaCy English model is downloaded.\n# If this is your first time downloading this model, restart the kernel after executing the next cell.\n\n# %% {\"tags\": [\"md-exclude\"]}\n# Download the spaCy english model\n# ! python -m spacy download en_core_web_sm\n\n# %% [markdown]\n# ## 1. Loading Data\n\n# %% [markdown]\n# We load the Kaggle dataset and create Pandas DataFrame objects for the `train` and `test` sets.\n# The two main columns in the DataFrames are:\n# * **`text`**: Raw text content of the comment\n# * **`label`**: Whether the comment is `SPAM` (1) or `HAM` (0).\n#\n# For more details, check out the [labeling tutorial](https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/01_spam_tutorial.ipynb).\n\n# %%\nfrom utils import load_spam_dataset\n\ndf_train, df_test = load_spam_dataset(load_train_labels=True)\n\n# We pull out the label vectors for ease of use later\nY_train = df_train[\"label\"].values\nY_test = df_test[\"label\"].values\n\n\n# %%\ndf_train.head()\n\n# %% [markdown]\n# ## 2. Writing Transformation Functions (TFs)\n#\n# Transformation functions are functions that can be applied to a training data point to create another valid training data point of the same class.\n# For example, for image classification problems, it is common to rotate or crop images in the training data to create new training inputs.\n# Transformation functions should be atomic e.g. a small rotation of an image, or changing a single word in a sentence.\n# We then compose multiple transformation functions when applying them to training data points.\n#\n# Common ways to augment text includes replacing words with their synonyms, or replacing names entities with other entities.\n# More info can be found\n# [here](https://towardsdatascience.com/data-augmentation-in-nlp-2801a34dfc28) or\n# [here](https://towardsdatascience.com/these-are-the-easiest-data-augmentation-techniques-in-natural-language-processing-you-can-think-of-88e393fd610).\n# Our basic modeling assumption is that applying these operations to a comment generally shouldn't change whether it is `SPAM` or not.\n#\n# Transformation functions in Snorkel are created with the\n# [`transformation_function` decorator](https://snorkel.readthedocs.io/en/master/packages/_autosummary/augmentation/snorkel.augmentation.transformation_function.html#snorkel.augmentation.transformation_function),\n# which wraps a function that takes in a single data point and returns a transformed version of the data point.\n# If no transformation is possible, a TF can return `None` or the original data point.\n# If all the TFs applied to a data point return `None`, the data point won't be included in\n# the augmented dataset when we apply our TFs below.\n#\n# Just like the `labeling_function` decorator, the `transformation_function` decorator\n# accepts `pre` argument for `Preprocessor` objects.\n# Here, we'll use a\n# [`SpacyPreprocessor`](https://snorkel.readthedocs.io/en/master/packages/_autosummary/preprocess/snorkel.preprocess.nlp.SpacyPreprocessor.html#snorkel.preprocess.nlp.SpacyPreprocessor).\n\n# %%\nfrom snorkel.preprocess.nlp import SpacyPreprocessor\n\nspacy = SpacyPreprocessor(text_field=\"text\", doc_field=\"doc\", memoize=True)\n\n# %%\nimport names\nfrom snorkel.augmentation import transformation_function\n\n# Pregenerate some random person names to replace existing ones with\n# for the transformation strategies below\nreplacement_names = [names.get_full_name() for _ in range(50)]\n\n\n# Replace a random named entity with a different entity of the same type.\n@transformation_function(pre=[spacy])\ndef change_person(x):\n person_names = [ent.text for ent in x.doc.ents if ent.label_ == \"PERSON\"]\n # If there is at least one person name, replace a random one. Else return None.\n if person_names:\n name_to_replace = np.random.choice(person_names)\n replacement_name = np.random.choice(replacement_names)\n x.text = x.text.replace(name_to_replace, replacement_name)\n return x\n\n\n# Swap two adjectives at random.\n@transformation_function(pre=[spacy])\ndef swap_adjectives(x):\n adjective_idxs = [i for i, token in enumerate(x.doc) if token.pos_ == \"ADJ\"]\n # Check that there are at least two adjectives to swap.\n if len(adjective_idxs) >= 2:\n idx1, idx2 = sorted(np.random.choice(adjective_idxs, 2, replace=False))\n # Swap tokens in positions idx1 and idx2.\n x.text = \" \".join(\n [\n x.doc[:idx1].text,\n x.doc[idx2].text,\n x.doc[1 + idx1 : idx2].text,\n x.doc[idx1].text,\n x.doc[1 + idx2 :].text,\n ]\n )\n return x\n\n\n# %% [markdown]\n# We add some transformation functions that use `wordnet` from [NLTK](https://www.nltk.org/) to replace different parts of speech with their synonyms.\n\n# %% {\"tags\": [\"md-exclude-output\"]}\nimport nltk\nfrom nltk.corpus import wordnet as wn\n\nnltk.download(\"wordnet\")\n\n\ndef get_synonym(word, pos=None):\n \"\"\"Get synonym for word given its part-of-speech (pos).\"\"\"\n synsets = wn.synsets(word, pos=pos)\n # Return None if wordnet has no synsets (synonym sets) for this word and pos.\n if synsets:\n words = [lemma.name() for lemma in synsets[0].lemmas()]\n if words[0].lower() != word.lower(): # Skip if synonym is same as word.\n # Multi word synonyms in wordnet use '_' as a separator e.g. reckon_with. Replace it with space.\n return words[0].replace(\"_\", \" \")\n\n\ndef replace_token(spacy_doc, idx, replacement):\n \"\"\"Replace token in position idx with replacement.\"\"\"\n return \" \".join([spacy_doc[:idx].text, replacement, spacy_doc[1 + idx :].text])\n\n\n@transformation_function(pre=[spacy])\ndef replace_verb_with_synonym(x):\n # Get indices of verb tokens in sentence.\n verb_idxs = [i for i, token in enumerate(x.doc) if token.pos_ == \"VERB\"]\n if verb_idxs:\n # Pick random verb idx to replace.\n idx = np.random.choice(verb_idxs)\n synonym = get_synonym(x.doc[idx].text, pos=\"v\")\n # If there's a valid verb synonym, replace it. Otherwise, return None.\n if synonym:\n x.text = replace_token(x.doc, idx, synonym)\n return x\n\n\n@transformation_function(pre=[spacy])\ndef replace_noun_with_synonym(x):\n # Get indices of noun tokens in sentence.\n noun_idxs = [i for i, token in enumerate(x.doc) if token.pos_ == \"NOUN\"]\n if noun_idxs:\n # Pick random noun idx to replace.\n idx = np.random.choice(noun_idxs)\n synonym = get_synonym(x.doc[idx].text, pos=\"n\")\n # If there's a valid noun synonym, replace it. Otherwise, return None.\n if synonym:\n x.text = replace_token(x.doc, idx, synonym)\n return x\n\n\n@transformation_function(pre=[spacy])\ndef replace_adjective_with_synonym(x):\n # Get indices of adjective tokens in sentence.\n adjective_idxs = [i for i, token in enumerate(x.doc) if token.pos_ == \"ADJ\"]\n if adjective_idxs:\n # Pick random adjective idx to replace.\n idx = np.random.choice(adjective_idxs)\n synonym = get_synonym(x.doc[idx].text, pos=\"a\")\n # If there's a valid adjective synonym, replace it. Otherwise, return None.\n if synonym:\n x.text = replace_token(x.doc, idx, synonym)\n return x\n\n\n# %%\ntfs = [\n change_person,\n swap_adjectives,\n replace_verb_with_synonym,\n replace_noun_with_synonym,\n replace_adjective_with_synonym,\n]\n\n# %% [markdown]\n# Let's check out a few examples of transformed data points to see what our TFs are doing.\n\n# %%\nfrom utils import preview_tfs\n\npreview_tfs(df_train, tfs)\n\n# %% [markdown]\n# We notice a couple of things about the TFs.\n#\n# * Sometimes they make trivial changes (`\"website\"` to `\"web site\"` for replace_noun_with_synonym).\n# This can still be helpful for training our model, because it teaches the model to be invariant to such small changes.\n# * Sometimes they introduce incorrect grammar to the sentence (e.g. `swap_adjectives` swapping `\"young\"` and `\"more\"` above).\n#\n# The TFs are expected to be heuristic strategies that indeed preserve the class most of the time, but\n# [don't need to be perfect](https://arxiv.org/pdf/1901.11196.pdf).\n# This is especially true when using automated\n# [data augmentation techniques](https://snorkel.org/blog/tanda/)\n# which can learn to avoid particularly corrupted data points.\n# As we'll see below, Snorkel is compatible with such learned augmentation policies.\n\n# %% [markdown]\n# ## 3. Applying Transformation Functions\n\n# %% [markdown]\n# We'll first define a `Policy` to determine what sequence of TFs to apply to each data point.\n# We'll start with a [`RandomPolicy`](https://snorkel.readthedocs.io/en/master/packages/_autosummary/augmentation/snorkel.augmentation.RandomPolicy.html)\n# that samples `sequence_length=2` TFs to apply uniformly at random per data point.\n# The `n_per_original` argument determines how many augmented data points to generate per original data point.\n\n# %%\nfrom snorkel.augmentation import RandomPolicy\n\nrandom_policy = RandomPolicy(\n len(tfs), sequence_length=2, n_per_original=2, keep_original=True\n)\n\n# %% [markdown]\n# In some cases, we can do better than uniform random sampling.\n# We might have domain knowledge that some TFs should be applied more frequently than others,\n# or have trained an [automated data augmentation model](https://snorkel.org/blog/tanda/)\n# that learned a sampling distribution for the TFs.\n# Snorkel supports this use case with a\n# [`MeanFieldPolicy`](https://snorkel.readthedocs.io/en/master/packages/_autosummary/augmentation/snorkel.augmentation.MeanFieldPolicy.html),\n# which allows you to specify a sampling distribution for the TFs.\n# We give higher probabilities to the `replace_[X]_with_synonym` TFs, since those provide more information to the model.\n\n# %%\nfrom snorkel.augmentation import MeanFieldPolicy\n\nmean_field_policy = MeanFieldPolicy(\n len(tfs),\n sequence_length=2,\n n_per_original=2,\n keep_original=True,\n p=[0.05, 0.05, 0.3, 0.3, 0.3],\n)\n\n# %% [markdown]\n# To apply one or more TFs that we've written to a collection of data points according to our policy, we use a\n# [`PandasTFApplier`](https://snorkel.readthedocs.io/en/master/packages/_autosummary/augmentation/snorkel.augmentation.PandasTFApplier.html)\n# because our data points are represented with a Pandas DataFrame.\n\n# %% {\"tags\": [\"md-exclude-output\"]}\nfrom snorkel.augmentation import PandasTFApplier\n\ntf_applier = PandasTFApplier(tfs, mean_field_policy)\ndf_train_augmented = tf_applier.apply(df_train)\nY_train_augmented = df_train_augmented[\"label\"].values\n\n# %%\nprint(f\"Original training set size: {len(df_train)}\")\nprint(f\"Augmented training set size: {len(df_train_augmented)}\")\n\n# %% [markdown]\n# We have almost doubled our dataset using TFs!\n# Note that despite `n_per_original` being set to 2, our dataset may not exactly triple in size,\n# because sometimes TFs return `None` instead of a new data point\n# (e.g. `change_person` when applied to a sentence with no persons).\n# If you prefer to have exact proportions for your dataset, you can have TFs that can't perform a\n# valid transformation return the original data point rather than `None` (as they do here).\n\n\n# %% [markdown]\n# ## 4. Training A Model\n#\n# Our final step is to use the augmented data to train a model. We train an LSTM (Long Short Term Memory) model, which is a very standard architecture for text processing tasks.\n\n# %% [markdown] {\"tags\": [\"md-exclude\"]}\n# The next cell makes Keras results reproducible. You can ignore it.\n\n# %% {\"tags\": [\"md-exclude\"]}\nimport tensorflow as tf\n\nsession_conf = tf.compat.v1.ConfigProto(\n intra_op_parallelism_threads=1, inter_op_parallelism_threads=1\n)\n\ntf.compat.v1.set_random_seed(0)\nsess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)\ntf.compat.v1.keras.backend.set_session(sess)\n\n# %% [markdown]\n# Now we'll train our LSTM on both the original and augmented datasets to compare performance.\n\n# %% {\"tags\": [\"md-exclude-output\"]}\nfrom utils import featurize_df_tokens, get_keras_lstm\n\nX_train = featurize_df_tokens(df_train)\nX_train_augmented = featurize_df_tokens(df_train_augmented)\nX_test = featurize_df_tokens(df_test)\n\n\ndef train_and_test(X_train, Y_train, X_test=X_test, Y_test=Y_test, num_buckets=30000):\n # Define a vanilla LSTM model with Keras\n lstm_model = get_keras_lstm(num_buckets)\n lstm_model.fit(X_train, Y_train, epochs=5, verbose=0)\n preds_test = lstm_model.predict(X_test)[:, 0] > 0.5\n return (preds_test == Y_test).mean()\n\n\nacc_augmented = train_and_test(X_train_augmented, Y_train_augmented)\nacc_original = train_and_test(X_train, Y_train)\n\n# %%\nprint(f\"Test Accuracy (original training data): {100 * acc_original:.1f}%\")\nprint(f\"Test Accuracy (augmented training data): {100 * acc_augmented:.1f}%\")\n\n\n# %% [markdown]\n# So using the augmented dataset indeed improved our model!\n# There is a lot more you can do with data augmentation, so try a few ideas\n# out on your own!\n", "import glob\nimport os\nimport subprocess\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\nfrom snorkel.classification.data import DictDataset, DictDataLoader\n\n\ndef load_spam_dataset(load_train_labels: bool = False, split_dev_valid: bool = False):\n if os.path.basename(os.getcwd()) == \"snorkel-tutorials\":\n os.chdir(\"spam\")\n try:\n subprocess.run([\"bash\", \"download_data.sh\"], check=True, stderr=subprocess.PIPE)\n except subprocess.CalledProcessError as e:\n print(e.stderr.decode())\n raise e\n filenames = sorted(glob.glob(\"data/Youtube*.csv\"))\n\n dfs = []\n for i, filename in enumerate(filenames, start=1):\n df = pd.read_csv(filename)\n # Lowercase column names\n df.columns = map(str.lower, df.columns)\n # Remove comment_id field\n df = df.drop(\"comment_id\", axis=1)\n # Add field indicating source video\n df[\"video\"] = [i] * len(df)\n # Rename fields\n df = df.rename(columns={\"class\": \"label\", \"content\": \"text\"})\n # Shuffle order\n df = df.sample(frac=1, random_state=123).reset_index(drop=True)\n dfs.append(df)\n\n df_train = pd.concat(dfs[:4])\n df_dev = df_train.sample(100, random_state=123)\n\n if not load_train_labels:\n df_train[\"label\"] = np.ones(len(df_train[\"label\"])) * -1\n df_valid_test = dfs[4]\n df_valid, df_test = train_test_split(\n df_valid_test, test_size=250, random_state=123, stratify=df_valid_test.label\n )\n\n if split_dev_valid:\n return df_train, df_dev, df_valid, df_test\n else:\n return df_train, df_test\n\n\ndef get_keras_logreg(input_dim, output_dim=2):\n model = tf.keras.Sequential()\n if output_dim == 1:\n loss = \"binary_crossentropy\"\n activation = tf.nn.sigmoid\n else:\n loss = \"categorical_crossentropy\"\n activation = tf.nn.softmax\n dense = tf.keras.layers.Dense(\n units=output_dim,\n input_dim=input_dim,\n activation=activation,\n kernel_regularizer=tf.keras.regularizers.l2(0.001),\n )\n model.add(dense)\n opt = tf.keras.optimizers.Adam(lr=0.01)\n model.compile(optimizer=opt, loss=loss, metrics=[\"accuracy\"])\n return model\n\n\ndef get_keras_lstm(num_buckets, embed_dim=16, rnn_state_size=64):\n lstm_model = tf.keras.Sequential()\n lstm_model.add(tf.keras.layers.Embedding(num_buckets, embed_dim))\n lstm_model.add(tf.keras.layers.LSTM(rnn_state_size, activation=tf.nn.relu))\n lstm_model.add(tf.keras.layers.Dense(1, activation=tf.nn.sigmoid))\n lstm_model.compile(\"Adagrad\", \"binary_crossentropy\", metrics=[\"accuracy\"])\n return lstm_model\n\n\ndef get_keras_early_stopping(patience=10, monitor=\"val_acc\"):\n \"\"\"Stops training if monitor value doesn't exceed the current max value after patience num of epochs\"\"\"\n return tf.keras.callbacks.EarlyStopping(\n monitor=monitor, patience=patience, verbose=1, restore_best_weights=True\n )\n\n\ndef map_pad_or_truncate(string, max_length=30, num_buckets=30000):\n \"\"\"Tokenize text, pad or truncate to get max_length, and hash tokens.\"\"\"\n ids = tf.keras.preprocessing.text.hashing_trick(\n string, n=num_buckets, hash_function=\"md5\"\n )\n return ids[:max_length] + [0] * (max_length - len(ids))\n\n\ndef featurize_df_tokens(df):\n return np.array(list(map(map_pad_or_truncate, df.text)))\n\n\ndef preview_tfs(df, tfs):\n transformed_examples = []\n for f in tfs:\n for i, row in df.sample(frac=1, random_state=2).iterrows():\n transformed_or_none = f(row)\n # If TF returned a transformed example, record it in dict and move to next TF.\n if transformed_or_none is not None:\n transformed_examples.append(\n OrderedDict(\n {\n \"TF Name\": f.name,\n \"Original Text\": row.text,\n \"Transformed Text\": transformed_or_none.text,\n }\n )\n )\n break\n return pd.DataFrame(transformed_examples)\n\n\ndef df_to_features(vectorizer, df, split):\n \"\"\"Convert pandas DataFrame containing spam data to bag-of-words PyTorch features.\"\"\"\n words = [row.text for i, row in df.iterrows()]\n\n if split == \"train\":\n feats = vectorizer.fit_transform(words)\n else:\n feats = vectorizer.transform(words)\n X = feats.todense()\n Y = df[\"label\"].values\n return X, Y\n\n\ndef create_dict_dataloader(X, Y, split, **kwargs):\n \"\"\"Create a DictDataLoader for bag-of-words features.\"\"\"\n ds = DictDataset.from_tensors(torch.FloatTensor(X), torch.LongTensor(Y), split)\n return DictDataLoader(ds, **kwargs)\n\n\ndef get_pytorch_mlp(hidden_dim, num_layers):\n layers = []\n for _ in range(num_layers):\n layers.extend([nn.Linear(hidden_dim, hidden_dim), nn.ReLU()])\n return nn.Sequential(*layers)\n" ]
[ [ "tensorflow.compat.v1.get_default_graph", "tensorflow.compat.v1.ConfigProto", "numpy.random.seed", "numpy.random.choice", "tensorflow.compat.v1.keras.backend.set_session", "tensorflow.compat.v1.set_random_seed", "pandas.set_option" ], [ "torch.nn.Sequential", "pandas.concat", "pandas.read_csv", "torch.LongTensor", "tensorflow.keras.layers.Embedding", "tensorflow.keras.layers.Dense", "tensorflow.keras.regularizers.l2", "tensorflow.keras.Sequential", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "torch.nn.Linear", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.LSTM", "torch.FloatTensor", "tensorflow.keras.preprocessing.text.hashing_trick", "torch.nn.ReLU", "tensorflow.keras.callbacks.EarlyStopping" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
JiarunLiu/mixmo-pytorch
[ "a9ad674122d9b6512094b8292280a4045bb5a400" ]
[ "mixmo/core/loss.py" ]
[ "\"\"\"\nBase loss definitions\n\"\"\"\nfrom collections import OrderedDict\nimport copy\nimport torch\nimport torch.nn as nn\n\nfrom mixmo.utils import misc, logger\n\nLOGGER = logger.get_logger(__name__, level=\"DEBUG\")\n\n\nclass AbstractLoss(nn.modules.loss._Loss):\n \"\"\"\n Base loss class defining printing and logging utilies\n \"\"\"\n def __init__(self, config_args, device, config_loss=None):\n self.device = device\n self.config_args = config_args or {}\n self.config_loss = config_loss or {}\n self.name = self.config_loss[\"display_name\"]\n nn.modules.loss._Loss.__init__(self)\n\n def print_details(self):\n LOGGER.info(f\"Using loss: {self.config_loss} with name: {self.name}\")\n\n def start_accumulator(self):\n self._accumulator_loss = 0\n self._accumulator_len = 0\n\n def get_accumulator_stats(self, format=\"short\", split=None):\n \"\"\"\n Gather tracked stats into a dictionary as formatted strings\n \"\"\"\n if not self._accumulator_len:\n return {}\n\n stats = OrderedDict({})\n loss_value = self._accumulator_loss / self._accumulator_len\n\n if format == \"long\":\n assert split is not None\n key = split + \"/\" + self.name\n stats[key] = {\n \"value\": loss_value,\n \"string\": f\"{loss_value:.5}\",\n }\n else:\n # make it as short as possibe to fit on one line of tqdm postfix\n loss_string = f\"{loss_value:.3}\".replace(\"e-0\", \"-\").replace(\"e-\", \"-\")\n stats[self.name] = loss_string\n\n return stats\n\n def forward(self, input, target):\n current_loss = self._forward(input, target)\n self._accumulator_loss += current_loss.detach().to(\"cpu\").numpy()\n self._accumulator_len += 1\n return current_loss\n\n def _forward(self, input, target):\n raise NotImplementedError\n\n\nclass SoftCrossEntropyLoss(AbstractLoss):\n \"\"\"\n Soft CrossEntropy loss that specifies the proper forward function for AbstractLoss\n \"\"\"\n def _forward(self, input, target):\n \"\"\"\n Cross entropy that accepts soft targets\n Args:\n pred: predictions for neural network\n targets: targets, can be soft\n size_average: if false, sum is returned instead of mean\n\n Examples::\n\n input = torch.FloatTensor([[1.1, 2.8, 1.3], [1.1, 2.1, 4.8]])\n input = torch.autograd.Variable(out, requires_grad=True)\n\n target = torch.FloatTensor([[0.05, 0.9, 0.05], [0.05, 0.05, 0.9]])\n target = torch.autograd.Variable(y1)\n loss = cross_entropy(input, target)\n loss.backward()\n \"\"\"\n if len(target.size()) == 1:\n target = torch.nn.functional.one_hot(target, num_classes=input.size(-1))\n target = target.to(torch.float).to(self.device)\n logsoftmax = torch.nn.LogSoftmax(dim=1)\n\n return torch.mean(torch.sum(-target * logsoftmax(input), dim=1))\n\n\n\nDICT_LOSS_STANDARD = {\n \"soft_cross_entropy\": SoftCrossEntropyLoss,\n}\n\n\nclass WrapperLoss(AbstractLoss):\n \"\"\"\n Wrapper around the multiple losses. Initialized from listloss.\n \"\"\"\n def __init__(self, config_loss, config_args, device):\n AbstractLoss.__init__(\n self,\n config_args=config_args,\n config_loss=config_loss,\n device=device,\n )\n self.losses = self._init_get_losses()\n self.regularized_network = None\n\n def _init_get_losses(self):\n \"\"\"\n Initialize and gather losses from listloss\n \"\"\"\n losses = []\n for ic, config_loss in enumerate(self.config_loss[\"listloss\"]):\n if config_loss[\"coeff\"] == \"<num_members\":\n config_loss[\"coeff\"] = (1. if ic < self.config_args[\"num_members\"] else 0)\n if config_loss[\"coeff\"] == 0:\n LOGGER.debug(f\"Skip loss: {config_loss}\")\n continue\n\n loss_callable = get_loss(config_loss, device=self.device, config_args=self.config_args)\n loss = copy.deepcopy(config_loss)\n loss[\"callable\"] = loss_callable\n losses.append(loss)\n return losses\n\n def print_details(self):\n return\n\n def start_accumulator(self):\n AbstractLoss.start_accumulator(self)\n for loss in self.losses:\n loss[\"callable\"].start_accumulator()\n\n def get_accumulator_stats(self, format=\"short\", split=None):\n \"\"\"\n Gather tracked stats into a dictionary as formatted strings\n \"\"\"\n if not self._accumulator_len:\n return {}\n\n stats = AbstractLoss.get_accumulator_stats(self, format=format, split=split)\n\n if format == \"long\":\n # tensorboard logs\n if self.config_loss.get(\"l2_reg\"):\n l2_reg = self.l2_reg().detach().to(\"cpu\").numpy()\n stats[\"general/l2_reg\"] = {\n \"value\": l2_reg,\n \"string\": f\"{l2_reg:.4}\",\n }\n for loss in self.losses:\n substats = loss[\"callable\"].get_accumulator_stats(\n format=format,\n split=split,\n )\n misc.clean_update(stats, substats)\n\n return stats\n\n def _forward(self, input, target):\n \"\"\"\n Perform loss forwards for each sublosses and l2 reg\n \"\"\"\n computed_losses = [self._forward_subloss(loss, input, target) for loss in self.losses]\n stacked_computed_losses = torch.stack(computed_losses)\n final_loss = stacked_computed_losses.sum()\n\n if self.config_loss.get(\"l2_reg\"):\n final_loss = final_loss + self.l2_reg() * float(self.config_loss.get(\"l2_reg\"))\n return final_loss\n\n def _forward_subloss(self, loss, input, target):\n \"\"\"\n Standard loss forward for one of the sublosses\n \"\"\"\n coeff = float(loss[\"coeff\"])\n subloss_input = self._match_item(loss[\"input\"], dict_tensors=input)\n subloss_target = self._match_item(loss[\"target\"], dict_tensors=target)\n loss = loss[\"callable\"](input=subloss_input, target=subloss_target)\n return loss * coeff\n\n @staticmethod\n def _match_item(name, dict_tensors):\n if misc.is_none(name):\n return None\n if name in dict_tensors:\n return dict_tensors[str(name)]\n raise ValueError(name)\n\n def set_regularized_network(self, network):\n if self.config_loss.get(\"l2_reg\"):\n self.regularized_network = network\n LOGGER.warning(f\"Set l2 regularization on {network.__class__.__name__}\")\n\n def l2_reg(self,):\n \"\"\"\n Compute l2 regularization/weight decay over the non-excluded parameters\n \"\"\"\n assert self.regularized_network is not None\n\n # Retrieve non excluded parameters\n params = list(self.regularized_network.parameters())\n\n # Iterate over all parameters to decay\n l2_reg = None\n for W in params:\n if l2_reg is None:\n l2_reg = torch.sum(torch.pow(W, 2))\n else:\n l2_reg = l2_reg + torch.sum(torch.pow(W, 2))\n assert l2_reg is not None\n\n return l2_reg\n\n\ndef get_loss(config_loss, device=None, config_args=None):\n \"\"\"\n Construct loss object, wrapped if there are multiple losses\n \"\"\"\n loss_name = config_loss[\"name\"]\n if loss_name == \"multitask\":\n loss = WrapperLoss(config_args=config_args, device=device, config_loss=config_loss)\n elif loss_name in DICT_LOSS_STANDARD:\n loss = DICT_LOSS_STANDARD[loss_name](\n config_loss=config_loss, config_args=config_args, device=device\n )\n else:\n raise Exception(f\"Loss {loss_name} not implemented\")\n loss.print_details()\n return loss\n" ]
[ [ "torch.stack", "torch.nn.modules.loss._Loss.__init__", "torch.nn.LogSoftmax", "torch.pow" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KevinKecc/caffe2
[ "a2b6c6e2f0686358a84277df65e9489fb7d9ddb2", "a2b6c6e2f0686358a84277df65e9489fb7d9ddb2", "a2b6c6e2f0686358a84277df65e9489fb7d9ddb2", "a2b6c6e2f0686358a84277df65e9489fb7d9ddb2" ]
[ "caffe2/python/operator_test/mkl_speed_test.py", "caffe2/python/operator_test/matmul_op_test.py", "caffe2/python/checkpoint_test.py", "caffe2/python/load_save_test.py" ]
[ "# Copyright (c) 2016-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport unittest\n\nimport numpy as np\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core, workspace, test_util\n\n\[email protected](not workspace.C.has_mkldnn, \"Skipping as we do not have mkldnn.\")\nclass TestMKLBasic(test_util.TestCase):\n def testReLUSpeed(self):\n X = np.random.randn(128, 4096).astype(np.float32)\n mkl_do = core.DeviceOption(caffe2_pb2.MKLDNN)\n # Makes sure that feed works.\n workspace.FeedBlob(\"X\", X)\n workspace.FeedBlob(\"X_mkl\", X, device_option=mkl_do)\n net = core.Net(\"test\")\n # Makes sure that we can run relu.\n net.Relu(\"X\", \"Y\")\n net.Relu(\"X_mkl\", \"Y_mkl\", device_option=mkl_do)\n workspace.CreateNet(net)\n workspace.RunNet(net)\n # makes sure that the results are good.\n np.testing.assert_allclose(\n workspace.FetchBlob(\"Y\"),\n workspace.FetchBlob(\"Y_mkl\"),\n atol=1e-10,\n rtol=1e-10)\n runtime = workspace.BenchmarkNet(net.Proto().name, 1, 100, True)\n\n # The returned runtime is the time of\n # [whole_net, cpu_op, mkl_op]\n # so we will assume that the MKL one runs faster than the CPU one.\n\n # Note(Yangqing): in fact, it seems that in optimized mode, this is\n # not always guaranteed - MKL runs slower than the Eigen vectorized\n # version, so I am turning this assertion off.\n #self.assertTrue(runtime[1] >= runtime[2])\n\n print(\"Relu CPU runtime {}, MKL runtime {}.\".format(runtime[1], runtime[2]))\n\n\n def testConvSpeed(self):\n # We randomly select a shape to test the speed. Intentionally we\n # test a batch size of 1 since this may be the most frequent use\n # case for MKL during deployment time.\n X = np.random.rand(1, 256, 27, 27).astype(np.float32) - 0.5\n W = np.random.rand(192, 256, 3, 3).astype(np.float32) - 0.5\n b = np.random.rand(192).astype(np.float32) - 0.5\n mkl_do = core.DeviceOption(caffe2_pb2.MKLDNN)\n # Makes sure that feed works.\n workspace.FeedBlob(\"X\", X)\n workspace.FeedBlob(\"W\", W)\n workspace.FeedBlob(\"b\", b)\n workspace.FeedBlob(\"X_mkl\", X, device_option=mkl_do)\n workspace.FeedBlob(\"W_mkl\", W, device_option=mkl_do)\n workspace.FeedBlob(\"b_mkl\", b, device_option=mkl_do)\n net = core.Net(\"test\")\n # Makes sure that we can run relu.\n net.Conv([\"X\", \"W\", \"b\"], \"Y\", pad=1, stride=1, kernel=3)\n net.Conv([\"X_mkl\", \"W_mkl\", \"b_mkl\"], \"Y_mkl\",\n pad=1, stride=1, kernel=3, device_option=mkl_do)\n workspace.CreateNet(net)\n workspace.RunNet(net)\n # makes sure that the results are good.\n np.testing.assert_allclose(\n workspace.FetchBlob(\"Y\"),\n workspace.FetchBlob(\"Y_mkl\"),\n atol=1e-2,\n rtol=1e-2)\n runtime = workspace.BenchmarkNet(net.Proto().name, 1, 100, True)\n\n print(\"Conv CPU runtime {}, MKL runtime {}.\".format(runtime[1], runtime[2]))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2016-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport inspect\n\nimport numpy as np\n\nfrom hypothesis import assume, given, settings\nimport hypothesis.strategies as st\n\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core\nimport caffe2.python.hypothesis_test_util as hu\n\n\nclass TestMatMul(hu.HypothesisTestCase):\n @given(\n M=st.integers(min_value=1, max_value=10),\n K=st.integers(min_value=1, max_value=10),\n N=st.integers(min_value=1, max_value=10),\n trans_a=st.booleans(),\n trans_b=st.booleans(),\n **hu.gcs\n )\n def test_matmul(self, M, K, N, trans_a, trans_b, gc, dc):\n X = np.random.rand(M, K).astype(np.float32) - 0.5\n if trans_a:\n X = X.transpose()\n\n Y = np.random.rand(K, N).astype(np.float32) - 0.5\n if trans_b:\n Y = Y.transpose()\n\n op = core.CreateOperator(\n 'MatMul', ['X', 'Y'], 'out', trans_a=trans_a, trans_b=trans_b\n )\n\n def matmul_ref(X, Y, trans_a, trans_b):\n XX = X.transpose() if trans_a else X\n YY = Y.transpose() if trans_b else Y\n return (XX.dot(YY), )\n\n # Check against numpy reference\n self.assertReferenceChecks(gc, op, [X, Y, trans_a, trans_b], matmul_ref)\n # Check over multiple devices\n self.assertDeviceChecks(dc, op, [X, Y], [0])\n # Gradient check wrt X\n self.assertGradientChecks(gc, op, [X, Y], 0, [0])\n # Gradient check wrt Y\n self.assertGradientChecks(gc, op, [X, Y], 1, [0])\n\n @given(\n M=st.integers(min_value=1, max_value=10),\n K=st.integers(min_value=1, max_value=10),\n N=st.integers(min_value=1, max_value=10),\n axis_a=st.sampled_from([-3, -2, -1, 1, 2, 3]),\n axis_b=st.sampled_from([-3, -2, -1, 1, 2, 3]),\n trans_a=st.booleans(),\n trans_b=st.booleans(),\n **hu.gcs\n )\n def test_matmul_axis(\n self, M, K, N, axis_a, axis_b, trans_a, trans_b, gc, dc\n ):\n X = np.random.rand(M, K).astype(np.float32) - 0.5\n if trans_a:\n X = X.transpose()\n shape_x = [X.shape[0], 1, 1, 1]\n shape_x[axis_a] = X.shape[1]\n X = X.reshape(*shape_x)\n\n Y = np.random.rand(K, N).astype(np.float32) - 0.5\n if trans_b:\n Y = Y.transpose()\n shape_y = [Y.shape[0], 1, 1, 1]\n shape_y[axis_b] = Y.shape[1]\n Y = Y.reshape(*shape_y)\n op = core.CreateOperator(\n 'MatMul', ['X', 'Y'],\n 'out',\n axis_a=axis_a,\n axis_b=axis_b,\n trans_a=trans_a,\n trans_b=trans_b\n )\n\n def size_to_dim(X, axis):\n dim = 1\n for i in range(axis):\n dim *= X.shape[i]\n return dim\n\n def size_from_dim(X, axis):\n dim = 1\n for i in range(axis, X.ndim):\n dim *= X.shape[i]\n return dim\n\n def reshape(X, axis):\n dim_0, dim_1 = size_to_dim(X, axis), size_from_dim(X, axis)\n return X.reshape(dim_0, dim_1)\n\n def canonical_axis(axis, ndim):\n return ndim + axis if axis < 0 else axis\n\n def matmul_ref(X, Y, axis_a, axis_b, trans_a, trans_b):\n can_axis_a = canonical_axis(axis_a, X.ndim)\n can_axis_b = canonical_axis(axis_b, Y.ndim)\n X, Y = reshape(X, can_axis_a), reshape(Y, can_axis_b)\n XX = X.transpose() if trans_a else X\n YY = Y.transpose() if trans_b else Y\n return (XX.dot(YY), )\n\n # Check against numpy reference\n self.assertReferenceChecks(\n gc, op, [X, Y, axis_a, axis_b, trans_a, trans_b], matmul_ref\n )\n # Check over multiple devices\n self.assertDeviceChecks(dc, op, [X, Y], [0])\n # Gradient check wrt X\n self.assertGradientChecks(gc, op, [X, Y], 0, [0])\n # Gradient check wrt Y\n self.assertGradientChecks(gc, op, [X, Y], 1, [0])\n\n\nclass TestBatchMatMul(hu.HypothesisTestCase):\n @settings(max_examples=30)\n @given(\n C=st.integers(min_value=0, max_value=3), # number of batch dims\n M=st.integers(min_value=1, max_value=10),\n K=st.integers(min_value=1, max_value=10),\n N=st.integers(min_value=1, max_value=10),\n trans_a=st.booleans(),\n trans_b=st.booleans(),\n dtype=st.sampled_from([np.float32, np.float16]),\n **hu.gcs\n )\n def test_batch_matmul(self, C, M, K, N, trans_a, trans_b, dtype, gc, dc):\n if dtype == np.float16:\n # fp16 is only supported with CUDA\n assume(gc.device_type == caffe2_pb2.CUDA)\n dc = [d for d in dc if d.device_type == caffe2_pb2.CUDA]\n\n batch_dims = np.random.randint(\n low=1,\n high=3,\n size=C,\n dtype=np.int64).tolist()\n X = np.random.rand(*(batch_dims + [M, K])).astype(dtype) - 0.5\n if trans_a:\n X = X.swapaxes(-1, -2)\n Y = np.random.rand(*(batch_dims + [K, N])).astype(dtype) - 0.5\n if trans_b:\n Y = Y.swapaxes(-1, -2)\n\n op = core.CreateOperator(\n 'BatchMatMul', ['X', 'Y'], 'out', trans_a=trans_a, trans_b=trans_b\n )\n\n def matmul_ref(X, Y, trans_a, trans_b, dtype):\n XX = (X.swapaxes(-1, -2) if trans_a else X).astype(np.float32)\n YY = (Y.swapaxes(-1, -2) if trans_b else Y).astype(np.float32)\n return (np.matmul(XX, YY).astype(dtype),)\n\n # relaxing the \"threshold\" for fp16 to 150x of the default\n def relax_fp16_check(check_func, *args, **kwargs):\n # inspect the default \"threshold\" value in check_func\n argspec = inspect.getargspec(check_func)\n threshold = argspec.defaults[\n argspec.args.index('threshold') -\n (len(argspec.args) - len(argspec.defaults))]\n\n if dtype == np.float16:\n threshold = 150 * threshold\n check_func(*args, threshold=threshold, **kwargs)\n\n # Check against numpy reference\n relax_fp16_check(self.assertReferenceChecks, gc, op, [X, Y, trans_a, trans_b, dtype], matmul_ref)\n # Check over multiple devices\n relax_fp16_check(self.assertDeviceChecks, dc, op, [X, Y], [0])\n # Gradient check wrt X\n relax_fp16_check(self.assertGradientChecks, gc, op, [X, Y], 0, [0])\n # Gradient check wrt Y\n relax_fp16_check(self.assertGradientChecks, gc, op, [X, Y], 1, [0])\n\n\nif __name__ == \"__main__\":\n import unittest\n unittest.main()\n", "# Copyright (c) 2016-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom caffe2.python.schema import Struct, ConstRecord\nfrom caffe2.python import core, workspace\nfrom caffe2.python.session import LocalSession\nfrom caffe2.python.dataset import Dataset\nfrom caffe2.python.pipeline import pipe\nfrom caffe2.python.checkpoint import (\n CheckpointManager, MultiNodeCheckpointManager, Job, JobRunner,\n UploadTaskGroupBuilder)\nfrom caffe2.python.net_builder import ops\nfrom caffe2.python.task import Node, Task, TaskGroup, WorkspaceType, Cluster\nfrom caffe2.python.test_util import TestCase\nfrom caffe2.python.dataio import ReaderWithLimit\n\nimport numpy as np\nimport os\nimport shutil\nimport tempfile\n\ndef build_pipeline(node_id):\n with Node('trainer_%d' % node_id):\n with Job.current().init_group, Task():\n data_arr = Struct(('val', np.array(list(range(10)))))\n data = ConstRecord(ops, data_arr)\n ds = Dataset(data, name='dataset:%d' % node_id)\n full_reader = ds.reader(ops)\n total = ops.Const([100])\n\n def inc_total(rec):\n ops.Add([total, rec.val()], [total])\n\n epoch_reader = ReaderWithLimit(full_reader, num_iter=3)\n pipe(epoch_reader, processor=inc_total)\n Job.current().add_stop_signal(epoch_reader.data_finished())\n return [total]\n\n\nEXPECTED_TOTALS = [103, 115, 136, 145]\n\n\ndef local_copy_op(src, dest):\n def copy_op(inputs, outputs):\n shutil.copyfile(src, dest)\n return copy_op\n\n\nclass UploadToLocalFile(UploadTaskGroupBuilder):\n def __init__(self, dest_dir):\n self.dest_dir = dest_dir\n\n def build(self, epoch, checkpoint_manager):\n with TaskGroup(WorkspaceType.GLOBAL) as upload_task_group:\n for node, manager in checkpoint_manager._node_managers:\n with Node(str(node)), Task():\n src_path = manager._db_name(epoch)\n dest_path = os.path.join(self.dest_dir, str(node))\n ops.Python((local_copy_op,\n [src_path, dest_path], {}))([], [])\n return upload_task_group\n\nclass TestCheckpoint(TestCase):\n def run_with(self, builder):\n with Cluster():\n with Job() as job:\n outputs = build_pipeline(node_id=0)\n output_fetcher = Task(step=core.Net('empty'), outputs=outputs)\n\n def fetch_total(session):\n session.run(output_fetcher)\n return output_fetcher.outputs()[0].fetch()\n\n session, checkpoint = builder()\n compiled_job = job.compile(LocalSession)\n num_epochs = JobRunner(compiled_job, checkpoint)(session)\n self.assertEquals(num_epochs, len(EXPECTED_TOTALS))\n self.assertEquals(fetch_total(session), EXPECTED_TOTALS[-1])\n\n for initial_epoch in range(1, num_epochs + 1):\n session, checkpoint = builder()\n JobRunner(\n compiled_job,\n checkpoint, resume_from_epoch=initial_epoch)(session)\n self.assertEquals(fetch_total(session), EXPECTED_TOTALS[-1])\n\n for epoch in range(1, num_epochs + 1):\n session.run(checkpoint.load(epoch))\n self.assertEquals(fetch_total(session),\n EXPECTED_TOTALS[epoch - 1])\n\n def test_single_checkpoint(self):\n # test single node\n try:\n tmpdir = tempfile.mkdtemp()\n\n def builder():\n ws = workspace.C.Workspace()\n session = LocalSession(ws)\n checkpoint = CheckpointManager(tmpdir, 'temp_node', 'minidb')\n return session, checkpoint\n\n self.run_with(builder)\n finally:\n shutil.rmtree(tmpdir)\n\n # test multi-node\n try:\n tmpdir = tempfile.mkdtemp()\n\n def builder():\n ws = workspace.C.Workspace()\n session = LocalSession(ws)\n checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')\n return session, checkpoint\n\n self.run_with(builder)\n finally:\n shutil.rmtree(tmpdir)\n\n def test_ckpt_name_and_load_model_from_ckpts(self):\n try:\n num_nodes = 3\n tmpdir = tempfile.mkdtemp()\n # First, check if the checkpoint name generation mechanism is\n # correct.\n checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')\n with Cluster():\n with Job() as job:\n for node_id in range(num_nodes):\n build_pipeline(node_id)\n compiled_job = job.compile(LocalSession)\n checkpoint.init(compiled_job.nodes_to_checkpoint())\n\n for node_id in range(num_nodes):\n epoch = 5\n node_name = 'trainer_%d' % node_id\n expected_db_name = tmpdir + '/' + node_name + '.5'\n self.assertEquals(\n checkpoint.get_ckpt_db_name(node_name, epoch),\n expected_db_name)\n shutil.rmtree(tmpdir)\n\n # Next, check mechanism to load model from checkpoints.\n tmpdir = tempfile.mkdtemp()\n workspace.ResetWorkspace()\n for node_id in range(num_nodes):\n ws = workspace.C.Workspace()\n session = LocalSession(ws)\n checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')\n with Cluster():\n with Job() as job:\n build_pipeline(node_id)\n compiled_job = job.compile(LocalSession)\n job_runner = JobRunner(compiled_job, checkpoint)\n num_epochs = job_runner(session)\n self.assertEquals(num_epochs, len(EXPECTED_TOTALS))\n\n # There are 12 global blobs after finishing up the job runner.\n # (only blobs on init_group are checkpointed)\n self.assertEquals(len(ws.blobs), 12)\n\n ws = workspace.C.Workspace()\n session = LocalSession(ws)\n self.assertEquals(len(ws.blobs), 0)\n model_blob_names = ['trainer_1/task_2/GivenTensorInt64Fill:0',\n 'trainer_2/task_2/GivenTensorInt64Fill:0']\n checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')\n with Cluster():\n with Job() as job:\n for node_id in range(num_nodes):\n build_pipeline(node_id)\n compiled_job = job.compile(LocalSession)\n job_runner = JobRunner(compiled_job, checkpoint)\n job_runner.load_blobs_from_checkpoints(\n blob_names=model_blob_names, epoch=1, session=session)\n\n # Check that we can successfully load from checkpoints of epochs\n # 1 to 4, but not epoch 5.\n for epoch in range(1, 5):\n self.assertTrue(\n job_runner.load_blobs_from_checkpoints(\n blob_names=model_blob_names, epoch=epoch,\n session=session))\n # Check that all the model blobs are loaded.\n for blob_name in model_blob_names:\n self.assertTrue(ws.has_blob(blob_name))\n self.assertEquals(\n ws.fetch_blob(blob_name),\n np.array([EXPECTED_TOTALS[epoch - 1]]))\n self.assertFalse(\n job_runner.load_blobs_from_checkpoints(\n blob_names=model_blob_names, epoch=5, session=session))\n\n finally:\n shutil.rmtree(tmpdir)\n\n def test_upload_checkpoint(self):\n try:\n tmpdir = tempfile.mkdtemp()\n upload_dir = os.path.join(tmpdir, \"upload\")\n os.mkdir(upload_dir)\n num_nodes = 3\n\n # The uploaded files do not exist yet.\n for node_id in range(num_nodes):\n node_name = 'trainer_%d' % node_id\n upload_path = os.path.join(upload_dir, node_name)\n self.assertFalse(os.path.exists(upload_path))\n\n # Create and run the job runner.\n for node_id in range(3):\n ws = workspace.C.Workspace()\n session = LocalSession(ws)\n checkpoint = MultiNodeCheckpointManager(tmpdir, 'minidb')\n with Cluster():\n with Job() as job:\n build_pipeline(node_id)\n compiled_job = job.compile(LocalSession)\n local_upload_builder = UploadToLocalFile(upload_dir)\n job_runner = JobRunner(\n compiled_job, checkpoint,\n upload_task_group_builder=local_upload_builder)\n num_epochs = job_runner(session)\n self.assertEquals(num_epochs, len(EXPECTED_TOTALS))\n\n # The uploaded files should exist now.\n for node_id in range(num_nodes):\n node_name = 'trainer_%d' % node_id\n upload_path = os.path.join(upload_dir, node_name)\n self.assertTrue(os.path.exists(upload_path))\n\n finally:\n shutil.rmtree(tmpdir)\n", "# Copyright (c) 2016-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport errno\nimport hypothesis.strategies as st\nfrom hypothesis import given\nimport numpy as np\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core, test_util, workspace\n\nif workspace.has_gpu_support:\n DEVICES = [caffe2_pb2.CPU, caffe2_pb2.CUDA]\n max_gpuid = workspace.NumCudaDevices() - 1\nelse:\n DEVICES = [caffe2_pb2.CPU]\n max_gpuid = 0\n\n\n# Utility class for other loading tests, don't add test functions here\n# Inherit from this test instead. If you add a test here,\n# each derived class will inherit it as well and cause test duplication\nclass TestLoadSaveBase(test_util.TestCase):\n\n def __init__(self, methodName, db_type='minidb'):\n super(TestLoadSaveBase, self).__init__(methodName)\n self._db_type = db_type\n\n @given(src_device_type=st.sampled_from(DEVICES),\n src_gpu_id=st.integers(min_value=0, max_value=max_gpuid),\n dst_device_type=st.sampled_from(DEVICES),\n dst_gpu_id=st.integers(min_value=0, max_value=max_gpuid))\n def load_save(self, src_device_type, src_gpu_id,\n dst_device_type, dst_gpu_id):\n workspace.ResetWorkspace()\n dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,\n np.int16, np.int32, np.int64, np.uint8, np.uint16]\n arrays = [np.random.permutation(6).reshape(2, 3).astype(T)\n for T in dtypes]\n src_device_option = core.DeviceOption(\n src_device_type, src_gpu_id)\n dst_device_option = core.DeviceOption(\n dst_device_type, dst_gpu_id)\n\n for i, arr in enumerate(arrays):\n self.assertTrue(workspace.FeedBlob(str(i), arr, src_device_option))\n self.assertTrue(workspace.HasBlob(str(i)))\n\n try:\n # Saves the blobs to a local db.\n tmp_folder = tempfile.mkdtemp()\n op = core.CreateOperator(\n \"Save\",\n [str(i) for i in range(len(arrays))], [],\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"), db_type=self._db_type)\n self.assertTrue(workspace.RunOperatorOnce(op))\n\n # Reset the workspace so that anything we load is surely loaded\n # from the serialized proto.\n workspace.ResetWorkspace()\n self.assertEqual(len(workspace.Blobs()), 0)\n\n def _LoadTest(keep_device, device_type, gpu_id, blobs, loadAll):\n \"\"\"A helper subfunction to test keep and not keep.\"\"\"\n op = core.CreateOperator(\n \"Load\",\n [], blobs,\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"), db_type=self._db_type,\n device_option=dst_device_option,\n keep_device=keep_device,\n load_all=loadAll)\n self.assertTrue(workspace.RunOperatorOnce(op))\n for i, arr in enumerate(arrays):\n self.assertTrue(workspace.HasBlob(str(i)))\n fetched = workspace.FetchBlob(str(i))\n self.assertEqual(fetched.dtype, arr.dtype)\n np.testing.assert_array_equal(\n workspace.FetchBlob(str(i)), arr)\n proto = caffe2_pb2.BlobProto()\n proto.ParseFromString(workspace.SerializeBlob(str(i)))\n self.assertTrue(proto.HasField('tensor'))\n self.assertEqual(proto.tensor.device_detail.device_type,\n device_type)\n if device_type == caffe2_pb2.CUDA:\n self.assertEqual(proto.tensor.device_detail.cuda_gpu_id,\n gpu_id)\n\n blobs = [str(i) for i in range(len(arrays))]\n # Load using device option stored in the proto, i.e.\n # src_device_option\n _LoadTest(1, src_device_type, src_gpu_id, blobs, 0)\n # Load again, but this time load into dst_device_option.\n _LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0)\n # Load back to the src_device_option to see if both paths are able\n # to reallocate memory.\n _LoadTest(1, src_device_type, src_gpu_id, blobs, 0)\n # Reset the workspace, and load directly into the dst_device_option.\n workspace.ResetWorkspace()\n _LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0)\n\n # Test load all which loads all blobs in the db into the workspace.\n workspace.ResetWorkspace()\n _LoadTest(1, src_device_type, src_gpu_id, [], 1)\n # Load again making sure that overwrite functionality works.\n _LoadTest(1, src_device_type, src_gpu_id, [], 1)\n # Load again with different device.\n _LoadTest(0, dst_device_type, dst_gpu_id, [], 1)\n workspace.ResetWorkspace()\n _LoadTest(0, dst_device_type, dst_gpu_id, [], 1)\n finally:\n # clean up temp folder.\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def saveFile(self, tmp_folder, db_type):\n dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,\n np.int16, np.int32, np.int64, np.uint8, np.uint16]\n arrays = [np.random.permutation(6).reshape(2, 3).astype(T)\n for T in dtypes]\n\n for i, arr in enumerate(arrays):\n self.assertTrue(workspace.FeedBlob(str(i), arr))\n self.assertTrue(workspace.HasBlob(str(i)))\n\n # Saves the blobs to a local db.\n tmp_file = os.path.join(tmp_folder, \"db\")\n op = core.CreateOperator(\n \"Save\",\n [str(i) for i in range(len(arrays))], [],\n absolute_path=1,\n db=tmp_file, db_type=db_type)\n workspace.RunOperatorOnce(op)\n return tmp_file, arrays\n\n\nclass TestLoadSave(TestLoadSaveBase):\n\n def testLoadSave(self):\n self.load_save()\n\n def testRepeatedArgs(self):\n dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,\n np.int16, np.int32, np.int64, np.uint8, np.uint16]\n arrays = [np.random.permutation(6).reshape(2, 3).astype(T)\n for T in dtypes]\n\n for i, arr in enumerate(arrays):\n self.assertTrue(workspace.FeedBlob(str(i), arr))\n self.assertTrue(workspace.HasBlob(str(i)))\n\n # Saves the blobs to a local db.\n tmp_folder = tempfile.mkdtemp()\n op = core.CreateOperator(\n \"Save\",\n [str(i) for i in range(len(arrays))] * 2, [],\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"), db_type=self._db_type)\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def testLoadExcessblobs(self):\n tmp_folder = tempfile.mkdtemp()\n tmp_file, arrays = self.saveFile(tmp_folder, self._db_type)\n\n op = core.CreateOperator(\n \"Load\",\n [], [str(i) for i in range(len(arrays))] * 2,\n absolute_path=1,\n db=tmp_file, db_type=self._db_type,\n load_all=False)\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def testTruncatedFile(self):\n tmp_folder = tempfile.mkdtemp()\n tmp_file, arrays = self.saveFile(tmp_folder, self._db_type)\n\n with open(tmp_file, 'wb+') as fdest:\n fdest.seek(20, os.SEEK_END)\n fdest.truncate()\n\n op = core.CreateOperator(\n \"Load\",\n [], [str(i) for i in range(len(arrays))],\n absolute_path=1,\n db=tmp_file, db_type=self._db_type,\n load_all=False)\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n\n op = core.CreateOperator(\n \"Load\",\n [], [],\n absolute_path=1,\n db=tmp_file, db_type=self._db_type,\n load_all=True)\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(op)\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def testBlobNameOverrides(self):\n original_names = ['blob_a', 'blob_b', 'blob_c']\n new_names = ['x', 'y', 'z']\n blobs = [np.random.permutation(6) for i in range(3)]\n for i, blob in enumerate(blobs):\n self.assertTrue(workspace.FeedBlob(original_names[i], blob))\n self.assertTrue(workspace.HasBlob(original_names[i]))\n self.assertEqual(len(workspace.Blobs()), 3)\n\n try:\n # Saves the blobs to a local db.\n tmp_folder = tempfile.mkdtemp()\n with self.assertRaises(RuntimeError):\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"Save\", original_names, [],\n absolute_path=1,\n strip_prefix='.temp',\n blob_name_overrides=new_names,\n db=os.path.join(tmp_folder, \"db\"),\n db_type=self._db_type\n )\n )\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"Save\", original_names, [],\n absolute_path=1,\n blob_name_overrides=new_names,\n db=os.path.join(tmp_folder, \"db\"),\n db_type=self._db_type\n )\n )\n )\n self.assertTrue(workspace.ResetWorkspace())\n self.assertEqual(len(workspace.Blobs()), 0)\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"Load\", [], [],\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"),\n db_type=self._db_type,\n load_all=1\n )\n )\n )\n self.assertEqual(len(workspace.Blobs()), 3)\n for i, name in enumerate(new_names):\n self.assertTrue(workspace.HasBlob(name))\n self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())\n # moved here per @cxj's suggestion\n load_new_names = ['blob_x', 'blob_y', 'blob_z']\n # load 'x' into 'blob_x'\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"Load\", [], load_new_names[0:1],\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"),\n db_type=self._db_type,\n source_blob_names=new_names[0:1]\n )\n )\n )\n # we should have 'blob_a/b/c/' and 'blob_x' now\n self.assertEqual(len(workspace.Blobs()), 4)\n for i, name in enumerate(load_new_names[0:1]):\n self.assertTrue(workspace.HasBlob(name))\n self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())\n self.assertTrue(\n workspace.RunOperatorOnce(\n core.CreateOperator(\n \"Load\", [], load_new_names[0:3],\n absolute_path=1,\n db=os.path.join(tmp_folder, \"db\"),\n db_type=self._db_type,\n source_blob_names=new_names[0:3]\n )\n )\n )\n # we should have 'blob_a/b/c/' and 'blob_x/y/z' now\n self.assertEqual(len(workspace.Blobs()), 6)\n for i, name in enumerate(load_new_names[0:3]):\n self.assertTrue(workspace.HasBlob(name))\n self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())\n finally:\n # clean up temp folder.\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def testMissingFile(self):\n tmp_folder = tempfile.mkdtemp()\n tmp_file = os.path.join(tmp_folder, \"missing_db\")\n\n op = core.CreateOperator(\n \"Load\",\n [], [],\n absolute_path=1,\n db=tmp_file, db_type=self._db_type,\n load_all=True)\n with self.assertRaises(RuntimeError):\n try:\n workspace.RunOperatorOnce(op)\n except RuntimeError as e:\n print(e)\n raise\n try:\n shutil.rmtree(tmp_folder)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.random.randn", "numpy.random.rand" ], [ "numpy.matmul", "numpy.random.rand", "numpy.random.randint" ], [ "numpy.array" ], [ "numpy.random.permutation" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zbloss/TransformerModel
[ "da4712fe5631accd22156f129e69c98b4ffe1146" ]
[ "transformer_model/masker.py" ]
[ "import tensorflow as tf\n\n\nclass Masker(object):\n\n def __init__(self):\n \"\"\"\n This class holds a collection of masking functions that are used across the entire package.\n \"\"\"\n\n @staticmethod\n def create_padding_mask(seq):\n \"\"\"\n :param seq: the sequence to mask\n :return: the padding mask in the form of (batch_size, 1, 1, seq_len)\n \"\"\"\n seq = tf.cast(tf.math.equal(seq, 0), tf.float32)\n\n # add extra dimensions to add the padding\n # to the attention logits.\n return seq[:, tf.newaxis, tf.newaxis, :]\n\n @staticmethod\n def create_look_ahead_mask(size):\n \"\"\"\n :param size:\n :return: the mask for hiding unseen values for training purposes in the form of (seq_len, seq_len)\n \"\"\"\n mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)\n return mask\n\n def create_masks(self, inp, tar):\n \"\"\"\n :param self:\n :param inp: The feature tensor to mask.\n :param tar: The target tensor to mask\n :return: the Encoder, Combined, and Decoder masks\n \"\"\"\n # Encoder padding mask\n enc_padding_mask = self.create_padding_mask(inp)\n\n # Used in the 2nd attention block in the decoder.\n # This padding mask is used to mask the encoder outputs.\n dec_padding_mask = self.create_padding_mask(inp)\n\n # Used in the 1st attention block in the decoder.\n # It is used to pad and mask future tokens in the input received by\n # the decoder.\n look_ahead_mask = self.create_look_ahead_mask(tf.shape(tar)[1])\n dec_target_padding_mask = self.create_padding_mask(tar)\n combined_mask = tf.maximum(dec_target_padding_mask, look_ahead_mask)\n\n return enc_padding_mask, combined_mask, dec_padding_mask\n" ]
[ [ "tensorflow.maximum", "tensorflow.ones", "tensorflow.math.equal", "tensorflow.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
ysakanaka/coco
[ "ebd5c30ccc83910755e379322b23d60a4b72ef38", "ebd5c30ccc83910755e379322b23d60a4b72ef38" ]
[ "code-experiments/build/python/python/solvers.py", "code-postprocessing/cocopp/pplogloss.py" ]
[ "from __future__ import absolute_import, division, print_function\nimport numpy as np\n\n# ===============================================\n# the most basic example solver\n# ===============================================\ndef random_search(fun, lbounds, ubounds, budget):\n \"\"\"Efficient implementation of uniform random search between\n `lbounds` and `ubounds`\n \"\"\"\n lbounds, ubounds = np.array(lbounds), np.array(ubounds)\n dim, x_min, f_min = len(lbounds), None, None\n max_chunk_size = 1 + 4e4 / dim\n while budget > 0:\n chunk = int(max([1, min([budget, max_chunk_size])]))\n # about five times faster than \"for k in range(budget):...\"\n X = lbounds + (ubounds - lbounds) * np.random.rand(chunk, dim)\n if fun.number_of_constraints > 0:\n C = [fun.constraint(x) for x in X] # call constraints\n F = [fun(x) for i, x in enumerate(X) if np.all(C[i] <= 0)]\n else:\n F = [fun(x) for x in X]\n if fun.number_of_objectives == 1:\n index = np.argmin(F) if len(F) else None\n if index is not None and (f_min is None or F[index] < f_min):\n x_min, f_min = X[index], F[index]\n budget -= chunk\n return x_min\n", "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Module for computing aRT loss ratio\n\nThis module outputs figures and tables showing aRT loss ratios.\nComparisons are based on computing the ratio between an aRT value and a\nreference (best) aRT value (or the inverse)\n\n\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nfrom pdb import set_trace\nimport numpy as np\nfrom matplotlib import pyplot as plt\ntry:\n from matplotlib.transforms import blended_transform_factory as blend\nexcept ImportError:\n # compatibility matplotlib 0.8\n from matplotlib.transforms import blend_xy_sep_transform as blend\nfrom matplotlib import mlab as mlab\nfrom six import advance_iterator\n\nfrom . import toolsstats, toolsdivers, bestalg, testbedsettings, genericsettings, captions\nfrom .pptex import writeFEvals2\nfrom .ppfig import save_figure, consecutiveNumbers\n\n\"\"\"\naRT loss ratio of an algorithm A for comparison to a reference/best algorithm.\nThis works only as comparison to a set of algorithms that reach at least the\nsame target values. Let f=f_A(EVALS) be the smallest target value such that the\naverage running time of algorithm A was smaller than or equal to EVALS.\nLet aRT_A=EVALS, if aRT_ref(next difficult f) < EVALS and\naRT_A=aRT_A(f_A(EVALS)) otherwise (we have aRT_A(f_A(EVALS)) <= EVALS).\nThe aRT loss ratio for algorithm A is defined as:\n Loss_A = stat_fcts(exp(CrE_A) * aRT_A / aRT_ref(f))\n\n + where f is a function of EVALS and stat_fcts is the desired statistics\n over the values from all functions (or a subgroup of functions), for\n example the geometric mean, min, max or any quantile. More specific: we\n plot versus 'the budget EVALS' the geometric mean (line) and Box-Whisker\n error bars at EVALS=2*D, 10*D, 100*D,...: a box between 25% and 75% with\n the median as additional symbol, a line with \"T\" as end-marker between\n 10% and 90% (the box covers the line) and a single point for min, max.\n For a function subgroup the Box-Whisker is replaced with the four or five\n actual points with the function number written.\n Caption: aRT loss ratio: average running time, aRT (measured in number\n of function evaluations), divided by the best aRT seen in the reference\n algorithm for the respectively same function and target function value,\n plotted versus number of function evaluations for the functions\n $f_1$--$f_{24}$ in dimension $D=XXX$, corrected by the\n parameter-crafting-effort $\\exp(CrE)==YYY$. Line: geometric mean over all\n functions. Box-Whisker error bars: 25-75\\%-percentile range with median\n (box), 10-90\\%-percentile range (line), and minimum and maximum aRT loss\n ratio (points). Alternative Box-Whisker sentence: Points: aRT loss ratio\n for each function.\n + The problem: how to find out CrE_A? Possible solution: ask for input in\n the script and put the given number into the caption and put exp(CrE_A)\n as small symbol on the y-axis of the figure for cross-checking.\n + This should make a collection of graphs for all functions and all\n subgroups which gives an additional page in the 'single algorithm'\n template. Respective tables could be side-by-side the graphs.\n + Example for how to read the graph: a loss ratio of 4 for aRT=20D means,\n that the function value reached with aRT=20D could be reached with the\n respective reference algorithm in aRT_ref=5D function evaluations on average.\n Therefore, given a budget of 20*D function evaluations, the reference\n algorithm could have further improved the function value using the\n remaining 15*D ($75\\%=1-1/4$) function evaluations.\n\nDetails: if aRT_A = aRT_A(f_A(EVALS)) always, the x-axis of plots between\ndifferent algorithms becomes incomparable. Also could aRT_A < aRT_ref,\neven though aRT_ref reaches a better f-value for the given EVALS.\n\n\"\"\"\n\n\"\"\"OLD STUFF:\naRT loss ratio: average running time, aRT (measured in number\n of function evaluations), divided by the reference aRT seen in BBOB-best2009 for\n the respectively same function and target function value, plotted versus\n number of function evaluations for the functions $f_1$--$f_{24}$ in\n dimension $D=XXX$, corrected by the parameter-crafting-effort\n $\\exp(CrE)==YYY$. Line: geometric mean over all functions. Box-Whisker\n error bars: 25-75\\%-percentile range with median (box),\n 10-90\\%-percentile range (line), and minimum and maximum aRT loss ratio\n (points).\nTable:\n\\aRT\\ loss ratio (see also Figure~\\ref{fig:aRTgraphs}) vs.\\ a given budget\n$\\FEvals$. Each cross ({\\color{blue}$+$}) represents a single function. The\ntarget value \\ftarget\\ used for a given \\FEvals\\ is the smallest (best) recorded\nfunction value such that $\\aRT(\\ftarget)\\le\\FEvals$ for the presented algorithm.\nShown is \\FEvals\\ divided by the respective best $\\aRT(\\ftarget)$ from BBOB-2009\nfor functions $f_1$--$f_{24}$ in 5-D and 20-D. Line: geometric mean. Box-Whisker\nerror bar: 25-75\\%-ile with median (box), 10-90\\%-ile (caps), and minimum and\nmaximum \\aRT\\ loss ratio (points). The vertical line gives the maximal number of\nfunction evaluations in a single trial in this function subset.\n\n\\aRT\\ loss ratio. The aRT of the considered algorithm, the budget, is shown in\nthe first column. For the loss ratio the budget is divided by the aRT for the\nrespective best result from BBOB-2009 (see also Table~\\ref{tab:aRTloss}).\nThe last row $\\text{RL}_{\\text{US}}/\\text{D}$ gives the number of function\nevaluations in unsuccessful runs divided by dimension. Shown are the smallest,\n10\\%-ile, 25\\%-ile, 50\\%-ile, 75\\%-ile and 90\\%-ile value (smaller values are\nbetter). The aRT Loss ratio equals to one for the respective best algorithm from\nBBOB-2009. Typical median values are between ten and hundred.\n\n\\aRT\\ loss ratio. The aRT of the considered algorithm, the budget, is shown in\nthe first column. For the loss ratio the budget is divided by the aRT for the\nrespective best result from BBOB-2009 (see also Figure~\\ref{fig:aRTlogloss}).\nThe last row $\\text{RL}_{\\text{US}}/\\text{D}$ gives the number of function\nevaluations in unsuccessful runs divided by dimension. Shown are the smallest,\n10\\%-ile, 25\\%-ile, 50\\%-ile, 75\\%-ile and 90\\%-ile value (smaller values are\nbetter). The aRT Loss ratio equals to one for the respective best algorithm\nfrom BBOB-2009. Typical median values are between ten and hundred.\n\nsuch that $\\aRT(\\ftarget)\\le\\FEvals$ for the\n Shown is \\FEvals\\ divided by the respective best $\\aRT(\\ftarget)$ from BBOB-2009\n %\n for functions $f_1$--$f_{24}$ in 5-D and 20-D.\n %\n % Each \\aRT\\ is multiplied by $\\exp(\\CrE)$ correcting for the parameter crafting effort.\n\"\"\"\n\n\ndef table_caption():\n table_caption = r\"\"\"%\n \\aRT\\ loss ratio versus the budget in number of $f$-evaluations\n divided by dimension.\n For each given budget \\FEvals, the target value \\ftarget\\ is computed\n as the best target $!!F!!$-value reached within the\n budget by the given algorithm.\n Shown is then the \\aRT\\ to reach \\ftarget\\ for the given algorithm\n or the budget, if !!THE-REF-ALG!!\n reached a better target within the budget,\n divided by the \\aRT\\ of !!THE-REF-ALG!! to reach \\ftarget.\n Line: geometric mean. Box-Whisker error bar: 25-75\\%-ile with median\n (box), 10-90\\%-ile (caps), and minimum and maximum \\aRT\\ loss ratio\n (points). The vertical line gives the maximal number of function evaluations\n in a single trial in this function subset. See also\n Figure~\\ref{fig:aRTlogloss} for results on each function subgroup.\\cocoversion\n \"\"\"\n\n table_caption = captions.replace(table_caption)\n\n return table_caption\n\n\ndef figure_caption():\n caption = r\"\"\"%\n \\aRT\\ loss ratios (see Figure~\\ref{tab:aRTloss} for details).\n\n Each cross ({\\color{blue}$+$}) represents a single function, the line\n is the geometric mean.\n \"\"\"\n\n # Currently all scenarios have the same caption.\n return caption\n\nevalf = None\nf_thresh = 1.e-8\nwhiskerscolor = 'b'\nboxescolor = 'b'\nmedianscolor = 'r'\ncapscolor = 'k'\nflierscolor = 'b'\n\ndef detERT(entry, funvals):\n # could be more efficient given that funvals is sorted...\n res = []\n for f in funvals:\n idx = (entry.target <= f)\n try:\n res.append(entry.ert[idx][0])\n except IndexError:\n res.append(np.inf)\n return res\n\ndef detf(entry, evals):\n \"\"\"Determines a function value given a number of evaluations.\n\n Let A be the algorithm considered. Let f=f_A(evals) be the smallest\n target value such that the average running time of algorithm A was\n smaller than or equal to evals.\n\n :keyword DataSet entry: data set\n :keyword list evals: numbers of function evaluations considered\n\n :Returns: list of the target function values\n\n \"\"\"\n res = []\n for fevals in evals:\n tmp = (entry.ert <= fevals)\n #set_trace()\n #if len(entry.target[tmp]) == 0:\n #set_trace()\n idx = np.argmin(entry.target[tmp])\n res.append(max(entry.target[idx], f_thresh))\n #res2.append(entry.ert[dix])\n #TODO np.min(empty)\n return res\n\ndef generateData(dsList, evals, CrE_A):\n res = {}\n\n D = set(i.dim for i in dsList).pop() # should have only one element\n #if D == 3:\n #set_trace()\n\n refalgentries = bestalg.load_reference_algorithm(testbedsettings.current_testbed.reference_algorithm_filename)\n\n for fun, tmpdsList in dsList.dictByFunc().items():\n assert len(tmpdsList) == 1\n entry = tmpdsList[0]\n\n refalgentry = refalgentries[(D, fun)]\n\n #aRT_A\n f_A = detf(entry, evals)\n\n aRT_ref = detERT(refalgentry, f_A)\n aRT_A = detERT(entry, f_A)\n nextreff = []\n for i in f_A:\n if i == 0.:\n nextreff.append(0.)\n else:\n tmp = refalgentry.target[refalgentry.target < i]\n try:\n nextreff.append(tmp[0])\n except IndexError:\n nextreff.append(i * 10.**(-0.2)) # TODO: this is a hack\n\n aRT_ref_nextreff = detERT(refalgentry, nextreff)\n\n for i in range(len(aRT_A)):\n # nextreff[i] >= f_thresh: this is tested because if it is not true\n # aRT_ref_nextreff[i] is supposed to be infinite.\n if nextreff[i] >= f_thresh and aRT_ref_nextreff[i] < evals[i]: # is different from the specification...\n aRT_A[i] = evals[i]\n\n # For test purpose:\n #if fun % 10 == 0:\n # aRT_A[-2] = 1.\n # aRT_ref[-2] = np.inf\n aRT_A = np.array(aRT_A)\n aRT_ref = np.array(aRT_ref)\n loss_A = np.exp(CrE_A) * aRT_A / aRT_ref\n assert (np.isnan(loss_A) == False).all()\n #set_trace()\n #if np.isnan(loss_A).any() or np.isinf(loss_A).any() or (loss_A == 0.).any():\n # txt = 'Problem with entry %s' % str(entry)\n # warnings.warn(txt)\n # #set_trace()\n res[fun] = loss_A\n\n return res\n\ndef boxplot(x, notch=0, sym='b+', positions=None, widths=None):\n \"\"\"Makes a box and whisker plot.\n\n Adapted from matplotlib.axes 0.98.5.2\n Modified such that the caps are set to the 10th and 90th\n percentiles, and to have some control on the colors.\n\n call signature::\n\n boxplot(x, notch=0, sym='+', positions=None, widths=None)\n\n Make a box and whisker plot for each column of *x* or each\n vector in sequence *x*. The box extends from the lower to\n upper quartile values of the data, with a line at the median.\n The whiskers extend from the box to show the range of the\n data. Flier points are those past the end of the whiskers.\n\n - *notch* = 0 (default) produces a rectangular box plot.\n - *notch* = 1 will produce a notched box plot\n\n *sym* (default 'b+') is the default symbol for flier points.\n Enter an empty string ('') if you don't want to show fliers.\n\n *whis* (default 1.5) defines the length of the whiskers as\n a function of the inner quartile range. They extend to the\n most extreme data point within ( ``whis*(75%-25%)`` ) data range.\n\n *positions* (default 1,2,...,n) sets the horizontal positions of\n the boxes. The ticks and limits are automatically set to match\n the positions.\n\n *widths* is either a scalar or a vector and sets the width of\n each box. The default is 0.5, or ``0.15*(distance between extreme\n positions)`` if that is smaller.\n\n *x* is an array or a sequence of vectors.\n\n Returns a dictionary mapping each component of the boxplot\n to a list of the :class:`matplotlib.lines.Line2D`\n instances created.\n\n Copyright (c) 2002-2009 John D. Hunter; All Rights Reserved\n \"\"\"\n whiskers, caps, boxes, medians, fliers = [], [], [], [], []\n\n # convert x to a list of vectors\n if hasattr(x, 'shape'):\n if len(x.shape) == 1:\n if hasattr(x[0], 'shape'):\n x = list(x)\n else:\n x = [x,]\n elif len(x.shape) == 2:\n nr, nc = x.shape\n if nr == 1:\n x = [x]\n elif nc == 1:\n x = [x.ravel()]\n else:\n x = [x[:, i] for i in range(nc)]\n else:\n raise ValueError(\"input x can have no more than 2 dimensions\")\n if not hasattr(x[0], '__len__'):\n x = [x]\n col = len(x)\n\n # get some plot info\n if positions is None:\n positions = range(1, col + 1)\n if widths is None:\n distance = max(positions) - min(positions)\n widths = min(0.15*max(distance, 1.0), 0.5)\n if isinstance(widths, float) or isinstance(widths, int):\n widths = np.ones((col,), float) * widths\n\n # loop through columns, adding each to plot\n for i, pos in enumerate(positions):\n d = np.ravel(x[i])\n # get median and quartiles\n wisk_lo, q1, med, q3, wisk_hi = mlab.prctile(d, [10, 25, 50, 75, 90])\n # get high extreme\n #iq = q3 - q1\n #hi_val = q3 + whis*iq\n #wisk_hi = np.compress( d <= hi_val , d )\n #if len(wisk_hi) == 0:\n #wisk_hi = q3\n #else:\n #wisk_hi = max(wisk_hi)\n ## get low extreme\n #lo_val = q1 - whis*iq\n #wisk_lo = np.compress( d >= lo_val, d )\n #if len(wisk_lo) == 0:\n #wisk_lo = q1\n #else:\n #wisk_lo = min(wisk_lo)\n # get fliers - if we are showing them\n flier_hi = []\n flier_lo = []\n flier_hi_x = []\n flier_lo_x = []\n if len(sym) != 0:\n flier_hi = np.compress(d > wisk_hi, d)\n flier_lo = np.compress(d < wisk_lo, d)\n flier_hi_x = np.ones(flier_hi.shape[0]) * pos\n flier_lo_x = np.ones(flier_lo.shape[0]) * pos\n\n # get x locations for fliers, whisker, whisker cap and box sides\n box_x_min = pos - widths[i] * 0.5\n box_x_max = pos + widths[i] * 0.5\n\n wisk_x = np.ones(2) * pos\n\n cap_x_min = pos - widths[i] * 0.25\n cap_x_max = pos + widths[i] * 0.25\n cap_x = [cap_x_min, cap_x_max]\n\n # get y location for median\n med_y = [med, med]\n\n # calculate 'regular' plot\n if notch == 0:\n # make our box vectors\n box_x = [box_x_min, box_x_max, box_x_max, box_x_min, box_x_min]\n box_y = [q1, q1, q3, q3, q1]\n # make our median line vectors\n med_x = [box_x_min, box_x_max]\n # calculate 'notch' plot\n else:\n raise NotImplementedError\n notch_max = med #+ 1.57*iq/np.sqrt(len(d))\n notch_min = med #- 1.57*iq/np.sqrt(len(d))\n if notch_max > q3:\n notch_max = q3\n if notch_min < q1:\n notch_min = q1\n # make our notched box vectors\n box_x = [box_x_min, box_x_max, box_x_max, cap_x_max, box_x_max,\n box_x_max, box_x_min, box_x_min, cap_x_min, box_x_min,\n box_x_min]\n box_y = [q1, q1, notch_min, med, notch_max, q3, q3, notch_max,\n med, notch_min, q1]\n # make our median line vectors\n med_x = [cap_x_min, cap_x_max]\n med_y = [med, med]\n\n doplot = plt.plot\n whiskers.extend(doplot(wisk_x, [q1, wisk_lo], color=whiskerscolor, linestyle='--'))\n whiskers.extend(doplot(wisk_x, [q3, wisk_hi], color=whiskerscolor, linestyle='--'))\n caps.extend(doplot(cap_x, [wisk_hi, wisk_hi], color=capscolor, linestyle='-'))\n caps.extend(doplot(cap_x, [wisk_lo, wisk_lo], color=capscolor, linestyle='-'))\n boxes.extend(doplot(box_x, box_y, color=boxescolor, linestyle='-'))\n medians.extend(doplot(med_x, med_y, color=medianscolor, linestyle='-'))\n fliers.extend(doplot(flier_hi_x, flier_hi, sym,\n flier_lo_x, flier_lo, sym))\n\n # fix our axes/ticks up a little\n newlimits = min(positions)-0.5, max(positions)+0.5\n plt.gca().set_xlim(newlimits)\n plt.gca().set_xticks(positions)\n\n return dict(whiskers=whiskers, caps=caps, boxes=boxes,\n medians=medians, fliers=fliers)\n\ndef plot(xdata, ydata):\n \"\"\"Plot the aRT log loss figures.\n\n Two cases: box-whisker plot is used for representing the data of all\n functions, otherwise all data is represented using crosses.\n\n \"\"\"\n res = []\n\n tmp = list(10**np.mean(i[np.isfinite(i)]) for i in ydata)\n res.extend(plt.plot(xdata, tmp, ls='-', color='k', lw=3, #marker='+',\n markersize=20, markeredgewidth=3))\n\n if max(len(i) for i in ydata) < 20: # TODO: subgroups of function, hopefully.\n for i, y in enumerate(ydata):\n # plot all single data points\n if (np.isfinite(y) == False).any():\n assert not (np.isinf(y) * y > 0.).any()\n assert not np.isnan(y).any()\n\n ax = plt.gca()\n trans = blend(ax.transData, ax.transAxes)\n res.extend(plt.plot((xdata[i], ), (0., ),\n marker='+', color=flierscolor,\n ls='', markersize=20, markeredgewidth=3,\n transform=trans, clip_on=False))\n res.append(plt.text(xdata[i], 0.02, '%d' % len(y[np.isinf(y)]),\n transform=trans, horizontalalignment='left',\n verticalalignment='bottom'))\n y = y[np.isfinite(y)]\n if len(y) == 0:\n continue\n\n res.extend(plt.plot([xdata[i]]*len(y), 10**np.array(y),\n marker='+', color=flierscolor,\n ls='', markersize=20, markeredgewidth=3))\n\n # plot dashed vertical line between min and max\n plt.plot([xdata[i]]*2, 10**np.array([min(y), max(y)]),\n color='k', # marker='+',\n ls='--', linewidth=2) #, markersize=20, markeredgewidth=3)\n # plot min and max with different symbol\n #plt.plot([xdata[i]], 10**min(np.array(y)),\n # marker='+', color='k',\n # ls='', markersize=20, markeredgewidth=3)\n #plt.plot([xdata[i]], 10**max(np.array(y)),\n # marker='+', color='k',\n # ls='', markersize=20, markeredgewidth=3)\n else:\n for i, y in enumerate(ydata):\n # plot all single data points\n if (np.isfinite(y) == False).any():\n assert not (np.isinf(y) * y > 0.).any()\n assert not np.isnan(y).any()\n\n ax = plt.gca()\n trans = blend(ax.transData, ax.transAxes)\n res.extend(plt.plot((xdata[i], ), (0, ),\n marker='.', color='k',\n ls='', markersize=20, markeredgewidth=3,\n transform=trans, clip_on=False))\n res.append(plt.text(xdata[i], 0.02, '%d' % len(y[np.isinf(y)]),\n transform=trans, horizontalalignment='left',\n verticalalignment='bottom'))\n y = y[np.isfinite(y)]\n\n dictboxwhisker = boxplot(list(10**np.array(i) for i in ydata),\n sym='', notch=0, widths=None,\n positions=xdata)\n #'medians', 'fliers', 'whiskers', 'boxes', 'caps'\n plt.setp(dictboxwhisker['medians'], lw=3)\n plt.setp(dictboxwhisker['boxes'], lw=3)\n plt.setp(dictboxwhisker['caps'], lw=3)\n plt.setp(dictboxwhisker['whiskers'], lw=3)\n for i in dictboxwhisker.values():\n res.extend(i)\n res.extend(plt.plot(xdata, list(10**min(i) for i in ydata), marker='.',\n markersize=20, color='k', ls=''))\n res.extend(plt.plot(xdata, list(10**max(i) for i in ydata), marker='.',\n markersize=20, color='k', ls=''))\n\n return res\n\ndef beautify():\n \"\"\"Format the figure.\"\"\"\n\n a = plt.gca()\n a.set_yscale('log')\n ymin = 1e-2\n ymax = 1e4\n plt.ylim(ymin=ymin, ymax=ymax)\n ydata = np.power(10., np.arange(np.log10(ymin), np.log10(ymax)+1))\n yticklabels = list(str(i) for i in range(int(np.log10(ymin)),\n int(np.log10(ymax)+1)))\n plt.yticks(ydata, yticklabels)\n\n plt.xlabel('log10 of FEvals / dimension')\n plt.ylabel('log10 of aRT loss ratio')\n #a.yaxis.grid(True, which='minor')\n a.yaxis.grid(True, which='major')\n\ndef generateTable(dsList, CrE=0., outputdir='.', info='default'):\n \"\"\"Generates aRT loss ratio tables.\n\n :param DataSetList dsList: input data set\n :param float CrE: crafting effort (see COCO documentation)\n :param string outputdir: output folder (must exist)\n :param string info: string suffix for output file names\n\n \"\"\"\n\n # If there is no reference algorithm.\n if not bestalg.load_reference_algorithm(testbedsettings.current_testbed.reference_algorithm_filename):\n return\n\n #Set variables\n prcOfInterest = [0, 10, 25, 50, 75, 90]\n for d, dsdim in dsList.dictByDim().items():\n maxevals = []\n funcs = []\n mFE = []\n\n for i in dsdim:\n maxevals.append(max(i.ert[np.isinf(i.ert) == False]))\n funcs.append(i.funcId)\n mFE.append(max(i.maxevals))\n\n maxevals = max(maxevals)\n mFE = max(mFE)\n EVALS = [2.*d]\n EVALS.extend(10.**(np.arange(1, np.log10(1e-9 + maxevals * 1./d))) * d)\n #Set variables: Done\n data = generateData(dsList, EVALS, CrE)\n\n generateSingleTableTex(dsList, funcs, mFE, d, prcOfInterest, EVALS,\n data, outputdir, info)\n generateSingleTableHtml(dsList, funcs, mFE, d, prcOfInterest, EVALS,\n data, outputdir, info)\n\n\ndef generateSingleTableTex(dsList, funcs, mFE, d, prcOfInterest, EVALS, data,\n outputdir='.', info='default'):\n \"\"\"Generates single aRT loss ratio table.\n\n :param DataSetList dsList: input data set\n :param funcs:\n :param mFE:\n :param d:\n :param prcOfInterest:\n :param EVALS:\n :param data:\n :param string outputdir: output folder (must exist)\n :param string info: string suffix for output file names\n\n \"\"\"\n\n res = []\n\n tmp = \"\\\\textbf{\\\\textit{f}\\\\raisebox{-0.35ex}{%d}--\" \\\n \"\\\\textit{f}\\\\raisebox{-0.35ex}{%d} in %d-D}, maxFE/D=%s\" \\\n % (min(funcs), max(funcs), d, writeFEvals2(int(mFE/d), maxdigits=6))\n\n res.append(r\" & \\multicolumn{\" + str(len(prcOfInterest)) + \"}{|c}{\" + tmp + \"}\")\n\n header = [\"\\\\#FEs/D\"]\n for i in prcOfInterest:\n if i == 0:\n tmp = \"best\"\n elif i == 50:\n tmp = \"\\\\textbf{med}\"\n else:\n tmp = \"%d\\\\%%\" % i\n header.append(tmp)\n\n #set_trace()\n res.append(\" & \".join(header))\n for i in range(len(EVALS)):\n tmpdata = list(data[f][i] for f in data)\n #set_trace()\n tmpdata = toolsstats.prctile(tmpdata, prcOfInterest)\n # format entries\n #tmp = [writeFEvals(EVALS[i]/d, '.0')]\n if EVALS[i]/d < 200:\n tmp = [writeFEvals2(EVALS[i]/d, 3)]\n else:\n tmp = [writeFEvals2(EVALS[i]/d, 1)]\n for j in tmpdata:\n # tmp.append(writeFEvals(j, '.2'))\n # tmp.append(writeFEvals2(j, 2))\n if j == 0.:\n tmp.append(\"~\\\\,0\")\n elif j < 1:\n tmp.append(\"~\\\\,%1.2f\" % j)\n elif j < 10:\n tmp.append(\"\\\\hspace*{1ex}%1.1f\" % j)\n elif j < 100:\n tmp.append(\"%2.0f\" % j)\n else:\n ar = (\"%1.1e\" % j).split('e')\n tmp.append(ar[0] + 'e' + str(int(ar[1])))\n # print(tmp[-1])\n res.append(\" & \".join(tmp))\n\n # add last line: runlength distribution for which 1e-8 was not reached.\n tmp = [r\"$\\text{RL}_{\\text{US}}$/D\"]\n tmpdata = []\n for i in dsList:\n it = reversed(i.evals)\n curline = None\n nextline = advance_iterator(it)\n while nextline[0] <= f_thresh:\n curline = nextline[1:]\n nextline = advance_iterator(it)\n if curline is None:\n tmpdata.extend(i.maxevals)\n else:\n tmpdata.extend(i.maxevals[np.isnan(curline)])\n\n #set_trace()\n if tmpdata: # if it is not empty\n tmpdata = toolsstats.prctile(tmpdata, prcOfInterest)\n for j in tmpdata:\n tmp.append(writeFEvals2(j/d, 1))\n res.append(\" & \".join(tmp))\n\n res = (r\"\\\\\"+ \"\\n\").join(res)\n res = r\"\\begin{tabular}{c|\" + len(prcOfInterest) * \"l\" +\"}\\n\" + res\n #res = r\"\\begin{tabular}{ccccc}\" + \"\\n\" + res\n res = res + \"\\n\" + r\"\\end{tabular}\" + \"\\n\"\n\n filename = os.path.join(outputdir, 'pploglosstable_%02dD_%s.tex' % (d, info))\n f = open(filename, 'w')\n f.write(res)\n f.close()\n if genericsettings.verbose:\n print(\"Wrote aRT loss ratio table in %s.\" % filename)\n\ndef generateSingleTableHtml(dsList, funcs, mFE, d, prcOfInterest, EVALS, data,\n outputdir='.', info='default'):\n \"\"\"Generates single aRT loss ratio table.\n\n :param DataSetList dsList: input data set\n :param funcs:\n :param mFE:\n :param d:\n :param prcOfInterest:\n :param EVALS:\n :param data:\n :param string outputdir: output folder (must exist)\n :param string info: string suffix for output file names\n\n \"\"\"\n\n res = []\n\n header = [\"<thead>\\n<tr>\\n<th>#FEs/D</td>\\n\"]\n for i in prcOfInterest:\n if i == 0:\n tmp = \"best\"\n elif i == 50:\n tmp = \"med\"\n else:\n tmp = \"%d %%\" % i\n header.append(\"<td>%s</td>\\n\" % tmp)\n\n #set_trace()\n res.append(\"\".join(header))\n res.append(\"</tr>\\n</thead>\\n\")\n\n # add footer line: runlength distribution for which 1e-8 was not reached.\n res.append(\"<tfoot>\\n<tr>\\n\")\n tmp = [\"<th>RL<sub>US</sub>/D</td>\\n\"]\n tmpdata = []\n for i in dsList:\n it = reversed(i.evals)\n curline = None\n nextline = advance_iterator(it)\n while nextline[0] <= f_thresh:\n curline = nextline[1:]\n nextline = advance_iterator(it)\n if curline is None:\n tmpdata.extend(i.maxevals)\n else:\n tmpdata.extend(i.maxevals[np.isnan(curline)])\n\n #set_trace()\n if tmpdata: # if it is not empty\n tmpdata = toolsstats.prctile(tmpdata, prcOfInterest)\n for j in tmpdata:\n tmp.append(\"<td>%s</td>\\n\" % writeFEvals2(j/d, 1))\n res.append(\"\".join(tmp))\n\n res.append(\"</tr>\\n</tfoot>\\n\")\n\n # add data\n res.append(\"<tbody>\\n\")\n for i in range(len(EVALS)):\n tmpdata = list(data[f][i] for f in data)\n #set_trace()\n tmpdata = toolsstats.prctile(tmpdata, prcOfInterest)\n\n res.append(\"<tr>\\n\")\n\n # format entries\n #tmp = [writeFEvals(EVALS[i]/d, '.0')]\n\n if EVALS[i]/d < 200:\n tmp = writeFEvals2(EVALS[i]/d, 3)\n else:\n tmp = writeFEvals2(EVALS[i]/d, 1)\n\n tmp = [\"<th sorttable_customkey=\\\"%f\\\">%s</th>\\n\" % ((EVALS[i]/d), tmp)]\n\n for j in tmpdata:\n # tmp.append(writeFEvals(j, '.2'))\n # tmp.append(writeFEvals2(j, 2))\n if j == 0.:\n tmp1 = \"0\"\n elif j < 1:\n tmp1 = \"%1.2f\" % j\n elif j < 10:\n tmp1 = \"%1.1f\" % j\n elif j < 100:\n tmp1 = \"%2.0f\" % j\n else:\n ar = (\"%1.1e\" % j).split('e')\n tmp1 = ar[0] + 'e' + str(int(ar[1]))\n\n tmp.append(\"<td sorttable_customkey=\\\"%f\\\">%s</td>\\n\" % (j, tmp1))\n\n res.append(\"\".join(tmp))\n res.append(\"</tr>\\n\")\n\n res.append(\"</tbody>\\n\")\n\n res = (\"\").join(res)\n\n function = \"<p><b><i>f</i><sub>%d</sub>&ndash;<i>f</i><sub>%d</sub> \" \\\n \"in %d-D</b>, maxFE/D=%s</p>\\n\" \\\n % (min(funcs), max(funcs), d, writeFEvals2(int(mFE/d), maxdigits=6))\n\n res = function + \"<table class=\\\"sortable\\\">\\n\" + res\n res = res + \"</table>\\n\"\n\n filename = os.path.join(outputdir, 'pplogloss.html')\n lines = []\n with open(filename) as infile:\n for line in infile:\n if '<!--tables-->' in line:\n lines.append(res)\n lines.append(line)\n\n with open(filename, 'w') as outfile:\n for line in lines:\n outfile.write(line)\n\n toolsdivers.replace_in_file(os.path.join(outputdir, 'pplogloss.html'), '??COCOVERSION??',\n '<br />Data produced with COCO %s' % (toolsdivers.get_version_label(None)))\n\n if genericsettings.verbose:\n print(\"Wrote aRT loss ratio table in %s.\" % filename)\n\ndef generateFigure(dsList, CrE=0., isStoringXRange=True, outputdir='.',\n info='default'):\n \"\"\"Generates aRT loss ratio figures.\n\n :param DataSetList dsList: input data set\n :param float CrE: crafting effort (see COCO documentation)\n :param bool isStoringXRange: if set to True, the first call to this\n function sets the global\n :py:data:`evalf` and all subsequent\n calls will use this value as boundaries\n in the generated figures.\n :param string outputdir: output folder (must exist)\n :param string info: string suffix for output file names\n\n \"\"\"\n\n #plt.rc(\"axes\", labelsize=20, titlesize=24)\n #plt.rc(\"xtick\", labelsize=20)\n #plt.rc(\"ytick\", labelsize=20)\n #plt.rc(\"font\", size=20)\n #plt.rc(\"legend\", fontsize=20)\n\n # If there is no reference algorithm.\n if not bestalg.load_reference_algorithm(testbedsettings.current_testbed.reference_algorithm_filename):\n return\n\n if isStoringXRange:\n global evalf\n else:\n evalf = None\n\n # do not aggregate over dimensions\n for d, dsdim in sorted(dsList.dictByDim().items()):\n maxevals = max(max(i.ert[np.isinf(i.ert) == False]) for i in dsdim)\n EVALS = [2.*d]\n EVALS.extend(10.**(np.arange(1, np.ceil(1e-9 + np.log10(maxevals * 1./d))))*d)\n if not evalf:\n evalf = (np.log10(EVALS[0]/d), np.log10(EVALS[-1]/d))\n\n data = generateData(dsdim, EVALS, CrE)\n ydata = []\n for i in range(len(EVALS)):\n #Aggregate over functions.\n ydata.append(np.log10(list(data[f][i] for f in data)))\n\n xdata = np.log10(np.array(EVALS)/d)\n xticklabels = ['']\n xticklabels.extend('%d' % i for i in xdata[1:])\n plot(xdata, ydata)\n\n filename = os.path.join(outputdir, 'pplogloss_%02dD_%s' % (d, info))\n plt.xticks(xdata, xticklabels)\n #Is there an upper bound?\n\n if CrE > 0 and len(set(dsdim.dictByFunc().keys())) >= 20:\n #TODO: hopefully this means we are not considering function groups.\n plt.text(0.01, 0.98, 'CrE = %5g' % CrE, fontsize=20,\n horizontalalignment='left', verticalalignment='top',\n transform=plt.gca().transAxes,\n bbox=dict(facecolor='w'))\n\n plt.axhline(1., color='k', ls='-', zorder=-1)\n plt.axvline(x=np.log10(max(i.mMaxEvals()/d for i in dsdim)), color='k')\n funcs = set(i.funcId for i in dsdim)\n if len(funcs) > 1:\n text = consecutiveNumbers(sorted(funcs), 'f')\n else:\n text = 'f%d' % (funcs.pop())\n text = text + ', %d-D' % d\n plt.text(0.5, 0.93, text, horizontalalignment=\"center\",\n transform=plt.gca().transAxes)\n beautify()\n if evalf:\n plt.xlim(xmin=evalf[0]-0.5, xmax=evalf[1]+0.5)\n\n save_figure(filename, dsdim[0].algId)\n\n #plt.show()\n plt.close()\n\n #plt.rcdefaults()\n\ndef main(dsList, CrE=0., isStoringXRange=True, outputdir='.', info='default'):\n \"\"\"Generates aRT loss ratio boxplot figures.\n\n Calls method generateFigure.\n\n \"\"\"\n generateFigure(dsList, CrE, isStoringXRange, outputdir, info)\n" ]
[ [ "numpy.all", "numpy.array", "numpy.argmin", "numpy.random.rand" ], [ "matplotlib.transforms.blend_xy_sep_transform", "matplotlib.pyplot.plot", "numpy.argmin", "numpy.exp", "matplotlib.pyplot.gca", "matplotlib.pyplot.close", "numpy.ravel", "numpy.isnan", "matplotlib.pyplot.ylim", "numpy.log10", "numpy.array", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.axhline", "matplotlib.mlab.prctile", "numpy.isfinite", "numpy.compress", "numpy.ones", "matplotlib.pyplot.xlim", "matplotlib.pyplot.setp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks", "numpy.isinf" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kamalsharma2/horovod
[ "69c33290f8cc43073fade45619e80d9ffb3b9653" ]
[ "test/utils/spark_common.py" ]
[ "# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport contextlib\nimport os\nimport platform\nimport pytest\nimport stat\nimport sys\nimport threading\nimport time\n\nfrom tempfile import TemporaryDirectory\n\nimport numpy as np\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.linalg import DenseVector, VectorUDT\nfrom pyspark.sql.types import FloatType, IntegerType, StructField, StructType\n\nfrom horovod.runner.common.util import secret\nfrom horovod.spark.common.store import LocalStore\nfrom horovod.spark.common.util import _wait_file_available_on_dbfs, _get_spark_df_saved_file_list\nfrom horovod.spark.driver.driver_service import SparkDriverService, SparkDriverClient\nfrom horovod.spark.task.task_service import SparkTaskService, SparkTaskClient\n\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'utils'))\n\nfrom common import tempdir, temppath\n\n# Spark will fail to initialize correctly locally on Mac OS without this\nif platform.system() == 'Darwin':\n os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES'\n\n\nclass CallbackBackend(object):\n def run(self, fn, args=(), kwargs={}, env={}):\n return [fn(*args, **kwargs)] * self.num_processes()\n\n def num_processes(self):\n return 1\n\n\[email protected]\ndef local_store():\n with tempdir() as tmp:\n store = LocalStore(tmp)\n yield store\n\n\[email protected]\ndef spark_session(app, cores=2, gpus=0, max_failures=1, *args):\n from pyspark import SparkConf\n from pyspark.sql import SparkSession\n\n with TemporaryDirectory() as tmpdir:\n metastore_path = os.path.join(tmpdir, 'metastore')\n\n # start a single worker with given cores when gpus are present\n # max failures are ignored when gpus in that case\n master = 'local-cluster[1,{},1024]'.format(cores) if gpus > 0 \\\n else 'local[{},{}]'.format(cores, max_failures)\n conf = SparkConf().setAppName(app).setMaster(master)\n conf = conf.setAll([\n ('spark.ui.showConsoleProgress', 'false'),\n ('spark.test.home', os.environ.get('SPARK_HOME')),\n ('spark.locality.wait', '0'),\n ('spark.unsafe.exceptionOnMemoryLeak', 'true'),\n ('spark.ui.enabled', 'false'),\n ('spark.local.dir', os.path.join(tmpdir, 'tmp')),\n ('spark.sql.warehouse.dir', os.path.join(tmpdir, 'warehouse')),\n ('javax.jdo.option.ConnectionURL',\n f'jdbc:derby:;databaseName={metastore_path};create=true'),\n ])\n\n with temppath() as temp_filename:\n if gpus > 0:\n with open(temp_filename, 'wb') as temp_file:\n addresses = ', '.join('\\\\\"{}\\\\\"'.format(i) for i in range(gpus))\n temp_file.write(b'echo {\\\\\"name\\\\\": \\\\\"gpu\\\\\", \\\\\"addresses\\\\\": [' +\n addresses.encode('ascii') + b']}')\n\n os.chmod(temp_file.name, stat.S_IRWXU | stat.S_IXGRP | stat.S_IRGRP |\n stat.S_IROTH | stat.S_IXOTH)\n\n # the single worker takes all gpus discovered, and a single executor will get them\n # each task on that executor will get a single gpu\n conf = conf.setAll([\n ('spark.worker.resource.gpu.discoveryScript', temp_filename),\n ('spark.worker.resource.gpu.amount', str(gpus)),\n ('spark.task.resource.gpu.amount', '1'),\n ('spark.executor.resource.gpu.amount', str(gpus)),\n ])\n\n session = SparkSession \\\n .builder \\\n .config(conf=conf) \\\n .getOrCreate()\n\n try:\n yield session\n finally:\n session.stop()\n\n\ndef fn():\n return 0\n\n\[email protected]\ndef spark_driver_service(num_proc, initial_np=None, fn=fn, args=(), kwargs={},\n key=None, nics=None, verbose=2):\n initial_np = initial_np or num_proc\n key = key or secret.make_secret_key()\n driver = SparkDriverService(initial_np, num_proc, fn, args, kwargs, key, nics)\n client = SparkDriverClient(driver.addresses(), key, verbose)\n\n try:\n yield driver, client, key\n finally:\n driver.shutdown()\n\n\[email protected]\ndef spark_task_service(index, key=None, nics=None, match_intf=False,\n minimum_command_lifetime_s=0, verbose=2):\n key = key or secret.make_secret_key()\n task = SparkTaskService(index, key, nics, minimum_command_lifetime_s, verbose)\n client = SparkTaskClient(index, task.addresses(), key, verbose, match_intf)\n\n try:\n yield task, client, key\n finally:\n task.shutdown()\n\n\ndef with_features(raw_df, feature_cols):\n vector_assembler = VectorAssembler().setInputCols(feature_cols).setOutputCol('features')\n pipeline = Pipeline().setStages([vector_assembler])\n\n df = pipeline.fit(raw_df).transform(raw_df)\n return df\n\n\ndef create_xor_data(spark):\n data = [[0, 0, 0.0, 0.1], [0, 1, 1.0, 0.2], [1, 0, 1.0, 0.3], [1, 1, 0.0, 0.4]]\n schema = StructType([StructField('x1', IntegerType()),\n StructField('x2', IntegerType()),\n StructField('y', FloatType()),\n StructField('weight', FloatType())])\n raw_df = create_test_data_from_schema(spark, data, schema)\n df = with_features(raw_df, ['x1', 'x2'])\n return df\n\n\ndef create_xor_data_with_val(spark):\n data = [[0, 0, 0.0, 0.1, 1], [0, 1, 1.0, 0.2, 0], [1, 0, 1.0, 0.3, 1], [1, 1, 0.0, 0.4, 0],\n [0, 0, 0.0, 0.1, 1], [0, 1, 1.0, 0.2, 0], [1, 0, 1.0, 0.3, 1], [1, 1, 0.0, 0.4, 0]]\n schema = StructType([StructField('x1', IntegerType()),\n StructField('x2', IntegerType()),\n StructField('y', FloatType()),\n StructField('weight', FloatType()),\n StructField('val', IntegerType())])\n raw_df = create_test_data_from_schema(spark, data, schema)\n df = with_features(raw_df, ['x1', 'x2'])\n return df\n\n\ndef create_noisy_xor_data(spark):\n schema = StructType([StructField('x1', FloatType()),\n StructField('x2', FloatType()),\n StructField('y', FloatType()),\n StructField('weight', FloatType())])\n data = [[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0]]\n n = 1024\n weights = np.random.uniform(0, 1, n)\n\n samples = []\n noise = np.random.normal(0, 0.1, [n, 2])\n for i, eps in enumerate(noise):\n original = data[i % len(data)]\n sample = original[0:2] + eps\n samples.append(sample.tolist() + [original[2]] + [float(weights[i])])\n\n raw_df = create_test_data_from_schema(spark, samples, schema)\n df = with_features(raw_df, ['x1', 'x2'])\n return df\n\n\ndef create_noisy_xor_data_with_val(spark):\n schema = StructType([StructField('x1', FloatType()),\n StructField('x2', FloatType()),\n StructField('y', FloatType()),\n StructField('weight', FloatType()),\n StructField('val', IntegerType())])\n data = [[0.0, 0.0, 0.0, 0], [0.0, 1.0, 1.0, 1], [1.0, 0.0, 1.0, 0], [1.0, 1.0, 0.0, 1]]\n n = 1024\n weights = np.random.uniform(0, 1, n)\n\n samples = []\n noise = np.random.normal(0, 0.1, [n, 2])\n for i, eps in enumerate(noise):\n original = data[i % len(data)]\n sample = original[0:2] + eps\n samples.append(sample.tolist() + [original[2]] + [float(weights[i])] + [original[3]])\n\n raw_df = create_test_data_from_schema(spark, samples, schema)\n df = with_features(raw_df, ['x1', 'x2'])\n return df\n\n\ndef create_mnist_data(spark):\n features = DenseVector([1.0] * 64)\n label_vec = DenseVector([0.0, 0.0, 1.0] + [0.0] * 7)\n label = 2.0\n data = [[features, label_vec, label]] * 10\n schema = StructType([StructField('features', VectorUDT()),\n StructField('label_vec', VectorUDT()),\n StructField('label', FloatType())])\n df = create_test_data_from_schema(spark, data, schema)\n return df\n\n\ndef create_test_data_from_schema(spark, data, schema):\n return spark.createDataFrame(data, schema=schema)\n\n\ndef test_wait_file_available_on_dbfs():\n with tempdir() as d:\n pq_dir = os.path.join(d, 'test_ev')\n os.makedirs(pq_dir)\n file1_path = os.path.join(pq_dir, 'file1')\n file2_path = os.path.join(pq_dir, 'file2')\n url1 = 'file://' + file1_path.replace(os.sep, '/')\n url2 = 'file://' + file2_path.replace(os.sep, '/')\n\n url_list = [url1, url2]\n\n def create_file(p):\n with open(p, 'w'):\n pass\n\n # 1. test all files exists.\n create_file(file1_path)\n create_file(file2_path)\n _wait_file_available_on_dbfs(url_list)\n\n # 2. test one file does not exists. Raise error.\n os.remove(file2_path)\n with pytest.raises(\n RuntimeError,\n match='Timeout while waiting for all parquet-store files to appear'\n ):\n _wait_file_available_on_dbfs(url_list)\n\n # 3. test one file accessible after 1 second.\n def delay_create_file2():\n time.sleep(1)\n create_file(file2_path)\n\n threading.Thread(target=delay_create_file2()).start()\n\n _wait_file_available_on_dbfs(url_list)\n\n\ndef test_get_spark_df_input_files(spark):\n with tempdir() as d:\n pq_dir = os.path.join(d, 'test_spark_df_output')\n with spark_session('test_get_spark_df_input_files') as spark:\n spark.range(100).repartition(4).write.parquet(pq_dir)\n\n pq_files = _get_spark_df_saved_file_list(pq_dir)\n pq_files = sorted(pq_files)\n assert len(pq_files) == 4\n for i in range(4):\n assert pq_files[i].startswith('part-0000' + str(i))\n" ]
[ [ "numpy.random.uniform", "numpy.random.normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kecsap/cleanlab
[ "e592e2ae2278018c8fdac33f20fd58659a825c3d", "e54adb5f7ec7537c02dd9f3eff473765a087c707" ]
[ "tests/test_latent.py", "cleanlab/pruning.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function, absolute_import, division, unicode_literals, with_statement\n\n\nfrom cleanlab import latent_algebra, latent_estimation\nimport numpy as np\nimport pytest\n\n\ns = [0] * 10 + [1] * 5 + [2] * 15\nnm = np.array([\n [1.0, 0.0, 0.2],\n [0.0, 0.7, 0.2],\n [0.0, 0.3, 0.6]\n])\n\n\ndef test_latent_py_ps_inv():\n ps, py, inv = latent_algebra.compute_ps_py_inv_noise_matrix(s, nm)\n assert(all(abs(np.dot(inv, ps) - py) < 1e-3))\n assert(all(abs(np.dot(nm, py) - ps) < 1e-3))\n return ps, py, inv\n\n\ndef test_latent_inv():\n ps, py, inv = test_latent_py_ps_inv()\n inv2 = latent_algebra.compute_inv_noise_matrix(py, nm)\n assert(np.all(abs(inv - inv2) < 1e-3))\n\n\ndef test_latent_nm():\n ps, py, inv = test_latent_py_ps_inv()\n nm2 = latent_algebra.compute_noise_matrix_from_inverse(ps, inv, py)\n assert(np.all(abs(nm - nm2) < 1e-3))\n\n\ndef test_latent_py():\n ps, py, inv = test_latent_py_ps_inv()\n py2 = latent_algebra.compute_py(ps, nm, inv)\n assert(np.all(abs(py - py2) < 1e-3))\n\n\ndef test_latent_py_warning():\n ps, py, inv = test_latent_py_ps_inv()\n with pytest.raises(TypeError) as e:\n with pytest.warns(UserWarning) as w:\n py2 = latent_algebra.compute_py(\n ps = np.array([[[0.1, 0.3, 0.6]]]),\n noise_matrix = nm,\n inverse_noise_matrix = inv,\n )\n py2 = latent_algebra.compute_py(\n ps = np.array([[0.1], [0.2], [0.7]]),\n noise_matrix = nm,\n inverse_noise_matrix = inv,\n )\n assert(True)\n\n\ndef test_compute_py_err():\n ps, py, inv = test_latent_py_ps_inv()\n try:\n py = latent_algebra.compute_py(\n ps = ps,\n noise_matrix = nm,\n inverse_noise_matrix = inv,\n py_method = 'marginal_ps',\n )\n except ValueError as e:\n assert('y_count' in str(e))\n with pytest.raises(ValueError) as e:\n py = latent_algebra.compute_py(\n ps = ps,\n noise_matrix = nm,\n inverse_noise_matrix = inv,\n py_method = 'marginal_ps',\n )\n\n\ndef test_compute_py_marginal_ps():\n ps, py, inv = test_latent_py_ps_inv()\n cj = nm * ps * len(s)\n y_count = cj.sum(axis = 0)\n py2 = latent_algebra.compute_py(\n ps = ps,\n noise_matrix = nm,\n inverse_noise_matrix = inv,\n py_method = 'marginal_ps',\n y_count = y_count\n )\n assert(all(abs(py - py2) < 1e-2))\n\n\ndef test_pyx():\n psx = np.array([\n [0.1, 0.3, 0.6],\n [0.1, 0.0, 0.9],\n [0.1, 0.0, 0.9],\n [1.0, 0.0, 0.0],\n [0.1, 0.8, 0.1],\n ])\n ps, py, inv = test_latent_py_ps_inv()\n pyx = latent_algebra.compute_pyx(psx, nm, inv)\n assert(np.all(np.sum(pyx, axis = 1) - 1 < 1e-4))\n\n\ndef test_pyx_error(): \n psx = np.array([0.1, 0.3, 0.6])\n ps, py, inv = test_latent_py_ps_inv()\n try:\n pyx = latent_algebra.compute_pyx(psx, nm, inv)\n except ValueError as e:\n assert('should be (N, K)' in str(e))\n with pytest.raises(ValueError) as e:\n pyx = latent_algebra.compute_pyx(psx, nm, inv)", "# coding: utf-8\n\n# ## Pruning\n# \n# #### Contains methods for estimating the latent indices of all label errors.\n# This code uses advanced multiprocessing to speed up computation.\n# see: https://research.wmz.ninja/articles/2018/03/ (link continued below)\n# on-sharing-large-arrays-when-using-pythons-multiprocessing.html\n# This approach supports posix and nt OS's: i.e. Windows, Mac, and Linux\n\n\nfrom __future__ import (\n print_function, absolute_import, division, unicode_literals, with_statement)\nfrom sklearn.preprocessing import MultiLabelBinarizer\nimport multiprocessing\nfrom multiprocessing.sharedctypes import RawArray\nimport sys\nimport os\nimport time\nfrom cleanlab.util import (value_counts, round_preserving_row_totals,\n onehot2int, int2onehot, )\nimport numpy as np\n\n# tqdm is a module used to print time-to-complete when multiprocessing is used.\n# This module is not necessary, and therefore is not a package dependency, but \n# when installed it improves user experience for large datasets.\ntry:\n import tqdm\n\n tqdm_exists = True\nexcept ImportError as e:\n tqdm_exists = False\n import warnings\n\n w = '''If you want to see estimated completion times\n while running methods in cleanlab.pruning, install tqdm\n via \"pip install tqdm\".'''\n warnings.warn(w)\n\n# Leave at least this many examples in each class after\n# pruning, regardless if noise estimates are larger.\nMIN_NUM_PER_CLASS = 5\n\n# For python 2/3 compatibility, define pool context manager\n# to support the 'with' statement in Python 2\nif sys.version_info[0] == 2:\n from contextlib import contextmanager\n\n\n @contextmanager\n def multiprocessing_context(*args, **kwargs):\n pool = multiprocessing.Pool(*args, **kwargs)\n yield pool\n pool.terminate()\nelse:\n multiprocessing_context = multiprocessing.Pool\n\n# Globals to be shared across threads in multiprocessing\nmp_params = {} # parameters passed to multiprocessing helper functions\n\n\n# Multiprocessing Helper functions\n\n\ndef _to_np_array(mp_arr, dtype=\"int32\", shape=None): # pragma: no cover\n \"\"\"multipropcessing Helper function to convert a multiprocessing\n RawArray to a numpy array.\"\"\"\n arr = np.frombuffer(mp_arr, dtype=dtype)\n if shape is None:\n return arr\n return arr.reshape(shape)\n\n\ndef _init(\n __s,\n __s_counts,\n __prune_count_matrix,\n __pcm_shape,\n __psx,\n __psx_shape,\n __multi_label,\n): # pragma: no cover\n \"\"\"Shares memory objects across child processes.\n ASSUMES none of these will be changed by child processes!\"\"\"\n\n mp_params['s'] = __s\n mp_params['s_counts'] = __s_counts\n mp_params['prune_count_matrix'] = __prune_count_matrix\n mp_params['pcm_shape'] = __pcm_shape\n mp_params['psx'] = __psx\n mp_params['psx_shape'] = __psx_shape\n mp_params['multi_label'] = __multi_label\n\n\ndef _get_shared_data(): # pragma: no cover\n \"\"\"multiprocessing helper function to extract numpy arrays from\n shared RawArray types used to shared data across process.\"\"\"\n\n s_counts = _to_np_array(mp_params['s_counts'])\n prune_count_matrix = _to_np_array(\n mp_arr=mp_params['prune_count_matrix'],\n shape=mp_params['pcm_shape'],\n )\n psx = _to_np_array(\n mp_arr=mp_params['psx'],\n dtype='float32',\n shape=mp_params['psx_shape'],\n )\n multi_label = mp_params['multi_label']\n if multi_label: # Shared data is passed as one-hot encoded matrix\n print('before', mp_params['s'])\n s = onehot2int(_to_np_array(\n mp_arr=mp_params['s'],\n shape=(psx.shape[0], psx.shape[1]),\n ))\n print('after', s)\n else:\n s = _to_np_array(mp_params['s'])\n return s, s_counts, prune_count_matrix, psx, multi_label\n\n\ndef _prune_by_class(k, args=None):\n \"\"\"multiprocessing Helper function for get_noise_indices()\n that assumes globals and produces a mask for class k for each example by\n removing the examples with *smallest probability* of\n belonging to their given class label.\n\n Parameters\n ----------\n k : int (between 0 and num classes - 1)\n The class of interest.\"\"\"\n\n if args: # Single processing - params are passed in\n s, s_counts, prune_count_matrix, psx, multi_label = args\n else: # Multiprocessing - data is shared across sub-processes\n s, s_counts, prune_count_matrix, psx, multi_label = _get_shared_data()\n\n if s_counts[k] > MIN_NUM_PER_CLASS: # No prune if not MIN_NUM_PER_CLASS\n num_errors = s_counts[k] - prune_count_matrix[k][k]\n # Get rank of smallest prob of class k for examples with noisy label k\n s_filter = np.array(\n [k in lst for lst in s]) if multi_label else s == k\n class_probs = psx[:, k]\n rank = np.partition(class_probs[s_filter], num_errors)[num_errors]\n return s_filter & (class_probs < rank)\n else:\n return np.zeros(len(s), dtype=bool)\n\n\ndef _prune_by_count(k, args=None):\n \"\"\"multiprocessing Helper function for get_noise_indices() that assumes\n globals and produces a mask for class k for each example by\n removing the example with noisy label k having *largest margin*,\n where\n margin of example := prob of given label - max prob of non-given labels\n\n Parameters\n ----------\n k : int (between 0 and num classes - 1)\n The true, hidden label class of interest.\"\"\"\n\n if args: # Single processing - params are passed in\n s, s_counts, prune_count_matrix, psx, multi_label = args\n else: # Multiprocessing - data is shared across sub-processes\n s, s_counts, prune_count_matrix, psx, multi_label = _get_shared_data()\n\n noise_mask = np.zeros(len(psx), dtype=bool)\n psx_k = psx[:, k]\n K = len(s_counts)\n if s_counts[k] <= MIN_NUM_PER_CLASS: # No prune if not MIN_NUM_PER_CLASS\n return np.zeros(len(s), dtype=bool)\n for j in range(K): # j is true label index (k is noisy label index)\n num2prune = prune_count_matrix[j][k]\n # Only prune for noise rates, not diagonal entries\n if k != j and num2prune > 0:\n # num2prune'th largest p(true class k) - p(noisy class k)\n # for x with true label j\n margin = psx[:, j] - psx_k\n s_filter = np.array(\n [k in lst for lst in s]\n ) if multi_label else s == k\n cut = -np.partition(-margin[s_filter], num2prune - 1)[num2prune - 1]\n noise_mask = noise_mask | (s_filter & (margin >= cut))\n return noise_mask\n\n\ndef _self_confidence(args, _psx): # pragma: no cover\n \"\"\"multiprocessing Helper function for get_noise_indices() that assumes\n global psx and computes the self confidence (prob of given label)\n for an example (row in psx) given the example index idx\n and its label l.\n np.mean(psx[]) enables this code to work for multi-class l.\"\"\"\n (idx, l) = args\n return np.mean(_psx[idx, l])\n\n\ndef multiclass_crossval_predict(pyx, labels):\n \"\"\"Returns an numpy 2D array of one-hot encoded\n multiclass predictions. Each row in the array\n provides the predictions for a particular example.\n The boundary condition used to threshold predictions\n is computed by maximizing the F1 ROC curve.\n\n Parameters\n ----------\n pyx : np.array (shape (N, K))\n P(label=k|x) is a NxK matrix with K probs for each of N examples.\n This is the probability distribution over all K classes, for each\n pyx should have been computed out of sample (holdout or crossval).\n\n labels : list of lists (length N)\n These are multiclass labels. Each list in the list contains all the\n labels for that example.\"\"\"\n\n from sklearn.metrics import f1_score\n boundaries = np.arange(0.05, 0.9, .05)\n labels_one_hot = MultiLabelBinarizer().fit_transform(labels)\n f1s = [f1_score(\n labels_one_hot, (pyx > boundary).astype(np.uint8), average='micro',\n ) for boundary in boundaries]\n boundary = boundaries[np.argmax(f1s)]\n pred = (pyx > boundary).astype(np.uint8)\n return pred\n\n\ndef get_noise_indices(\n s,\n psx,\n inverse_noise_matrix=None,\n confident_joint=None,\n frac_noise=1.0,\n num_to_remove_per_class=None,\n prune_method='prune_by_noise_rate',\n sorted_index_method=None,\n multi_label=False,\n n_jobs=None,\n verbose=0,\n):\n \"\"\"Returns the indices of most likely (confident) label errors in s. The\n number of indices returned is specified by frac_of_noise. When\n frac_of_noise = 1.0, all \"confident\" estimated noise indices are returned.\n * If you encounter the error 'psx is not defined', try setting n_jobs = 1.\n\n Parameters\n ----------\n\n s : np.array\n A binary vector of labels, s, which may contain mislabeling. \"s\" denotes\n the noisy label instead of \\tilde(y), for ASCII encoding reasons.\n\n psx : np.array (shape (N, K))\n P(s=k|x) is a matrix with K (noisy) probabilities for each of the N\n examples x.\n This is the probability distribution over all K classes, for each\n example, regarding whether the example has label s==k P(s=k|x).\n psx should have been computed using 3+ fold cross-validation.\n\n inverse_noise_matrix : np.array of shape (K, K), K = number of classes\n A conditional probability matrix of the form P(y=k_y|s=k_s) representing\n the estimated fraction observed examples in each class k_s, that are\n mislabeled examples from every other class k_y. If None, the\n inverse_noise_matrix will be computed from psx and s.\n Assumes columns of inverse_noise_matrix sum to 1.\n\n confident_joint : np.array (shape (K, K), type int) (default: None)\n A K,K integer matrix of count(s=k, y=k). Estimates a a confident\n subset of the joint distribution of the noisy and true labels P_{s,y}.\n Each entry in the matrix contains the number of examples confidently\n counted into every pair (s=j, y=k) classes.\n\n frac_noise : float\n When frac_of_noise = 1.0, return all \"confident\" estimated noise indices.\n Value in range (0, 1] that determines the fraction of noisy example\n indices to return based on the following formula for example class k.\n frac_of_noise * number_of_mislabeled_examples_in_class_k, or equivalently\n frac_of_noise * inverse_noise_rate_class_k * num_examples_with_s_equal_k\n\n num_to_remove_per_class : list of int of length K (# of classes)\n e.g. if K = 3, num_to_remove_per_class = [5, 0, 1] would return\n the indices of the 5 most likely mislabeled examples in class s = 0,\n and the most likely mislabeled example in class s = 1.\n ***Only set this parameter if prune_method == 'prune_by_class'\n You may use with prune_method == 'prune_by_noise_rate', but\n if num_to_remove_per_class == k, then either k-1, k, or k+1\n examples may be removed for any class. This is because noise rates\n are floats, and rounding may cause a one-off. If you need exactly\n 'k' examples removed from every class, you should use 'prune_by_class'.\n\n prune_method : str (default: 'prune_by_noise_rate')\n Possible Values: 'prune_by_class', 'prune_by_noise_rate', or 'both'.\n Method used for pruning.\n 1. 'prune_by_noise_rate': works by removing examples with\n *high probability* of being mislabeled for every non-diagonal\n in the prune_counts_matrix (see pruning.py).\n 2. 'prune_by_class': works by removing the examples with *smallest\n probability* of belonging to their given class label for every class.\n 3. 'both': Finds the examples satisfying (1) AND (2) and\n removes their set conjunction.\n\n sorted_index_method : str [None, 'prob_given_label', 'normalized_margin']\n If None, returns a boolean mask (true if example at index is label error)\n If not None, returns an array of the label error indices\n (instead of a bool mask) where error indices are ordered by the either:\n 'normalized_margin' := normalized margin (p(s = k) - max(p(s != k)))\n 'prob_given_label' := [psx[i][labels[i]] for i in label_errors_idx]\n\n multi_label : bool\n If true, s should be an iterable (e.g. list) of iterables, containing a\n list of labels for each example, instead of just a single label.\n\n n_jobs : int (Windows users may see a speed-up with n_jobs = 1)\n Number of processing threads used by multiprocessing. Default None\n sets to the number of processing threads on your CPU.\n Set this to 1 to REMOVE parallel processing (if its causing issues).\n\n verbose : int\n If 0, no print statements. If 1, prints when multiprocessing happens.\"\"\"\n\n # Set-up number of multiprocessing threads\n if n_jobs is None:\n n_jobs = multiprocessing.cpu_count()\n else:\n assert (n_jobs >= 1)\n\n # Number of examples in each class of s\n if multi_label:\n s_counts = value_counts([i for lst in s for i in lst])\n else:\n s_counts = value_counts(s)\n # Number of classes s\n K = len(psx.T)\n # Boolean set to true if dataset is large\n big_dataset = K * len(s) > 1e8\n # Ensure labels are of type np.array()\n s = np.asarray(s)\n\n if confident_joint is None:\n from cleanlab.latent_estimation import compute_confident_joint\n confident_joint = compute_confident_joint(\n s=s,\n psx=psx,\n multi_label=multi_label,\n )\n\n # Leave at least MIN_NUM_PER_CLASS examples per class.\n # NOTE prune_count_matrix is transposed (relative to confident_joint)\n prune_count_matrix = keep_at_least_n_per_class(\n prune_count_matrix=confident_joint.T,\n n=MIN_NUM_PER_CLASS,\n frac_noise=frac_noise,\n )\n\n if num_to_remove_per_class is not None:\n # Estimate joint probability distribution over label errors\n psy = prune_count_matrix / np.sum(prune_count_matrix, axis=1)\n noise_per_s = psy.sum(axis=1) - psy.diagonal()\n # Calibrate s.t. noise rates sum to num_to_remove_per_class\n tmp = (psy.T * num_to_remove_per_class / noise_per_s).T\n np.fill_diagonal(tmp, s_counts - num_to_remove_per_class)\n prune_count_matrix = round_preserving_row_totals(tmp)\n\n if n_jobs > 1: # Prepare multiprocessing shared data\n if multi_label:\n _s = RawArray('I', int2onehot(s).flatten())\n else:\n _s = RawArray('I', s)\n _s_counts = RawArray('I', s_counts)\n _prune_count_matrix = RawArray(\n 'I', prune_count_matrix.flatten())\n _psx = RawArray(\n 'f', psx.flatten())\n else: # Multiprocessing is turned off. Create tuple with all parameters\n args = (s, s_counts, prune_count_matrix, psx, multi_label)\n\n # Perform Pruning with threshold probabilities from BFPRT algorithm in O(n)\n # Operations are parallelized across all CPU processes\n if prune_method == 'prune_by_class' or prune_method == 'both':\n if n_jobs > 1: # parallelize\n with multiprocessing_context(\n n_jobs,\n initializer=_init,\n initargs=(_s, _s_counts, _prune_count_matrix,\n prune_count_matrix.shape, _psx, psx.shape,\n multi_label),\n ) as p:\n if verbose:\n print('Parallel processing label errors by class.')\n sys.stdout.flush()\n if big_dataset and tqdm_exists:\n noise_masks_per_class = list(\n tqdm.tqdm(p.imap(_prune_by_class, range(K)), total=K),\n )\n else:\n noise_masks_per_class = p.map(_prune_by_class, range(K))\n else: # n_jobs = 1, so no parallelization\n noise_masks_per_class = [_prune_by_class(k, args) for k in range(K)]\n label_errors_mask = np.stack(noise_masks_per_class).any(axis=0)\n\n if prune_method == 'both':\n label_errors_mask_by_class = label_errors_mask\n\n if prune_method == 'prune_by_noise_rate' or prune_method == 'both':\n if n_jobs > 1: # parallelize\n with multiprocessing_context(\n n_jobs,\n initializer=_init,\n initargs=(_s, _s_counts, _prune_count_matrix,\n prune_count_matrix.shape, _psx, psx.shape,\n multi_label),\n ) as p:\n if verbose:\n print('Parallel processing label errors by noise rate.')\n sys.stdout.flush()\n if big_dataset and tqdm_exists:\n noise_masks_per_class = list(\n tqdm.tqdm(p.imap(_prune_by_count, range(K)), total=K)\n )\n else:\n noise_masks_per_class = p.map(_prune_by_count, range(K))\n else: # n_jobs = 1, so no parallelization\n noise_masks_per_class = [_prune_by_count(k, args) for k in range(K)]\n label_errors_mask = np.stack(noise_masks_per_class).any(axis=0)\n\n if prune_method == 'both':\n label_errors_mask = label_errors_mask & label_errors_mask_by_class\n\n # Remove label errors if given label == model prediction\n if multi_label:\n pred = multiclass_crossval_predict(psx, s)\n s = MultiLabelBinarizer().fit_transform(s)\n else:\n pred = psx.argmax(axis=1)\n for i, pred_label in enumerate(pred):\n if multi_label and np.all(pred_label == s[i]) or \\\n not multi_label and pred_label == s[i]:\n label_errors_mask[i] = False\n\n if sorted_index_method is not None:\n er = order_label_errors(label_errors_mask, psx, s, sorted_index_method)\n return er\n\n return label_errors_mask\n\n\ndef keep_at_least_n_per_class(prune_count_matrix, n, frac_noise=1.0):\n \"\"\"Make sure every class has at least n examples after removing noise.\n Functionally, increase each column, increases the diagonal term #(y=k,s=k)\n of prune_count_matrix until it is at least n, distributing the amount\n increased by subtracting uniformly from the rest of the terms in the\n column. When frac_of_noise = 1.0, return all \"confidently\" estimated\n noise indices, otherwise this returns frac_of_noise fraction of all\n the noise counts, with diagonal terms adjusted to ensure column\n totals are preserved.\n\n Parameters\n ----------\n\n prune_count_matrix : np.array of shape (K, K), K = number of classes\n A counts of mislabeled examples in every class. For this function.\n NOTE prune_count_matrix is transposed relative to confident_joint.\n\n n : int\n Number of examples to make sure are left in each class.\n\n frac_noise : float\n When frac_of_noise = 1.0, return all estimated noise indices.\n Value in range (0, 1] that determines the fraction of noisy example\n indices to return based on the following formula for example class k.\n frac_of_noise * number_of_mislabeled_examples_in_class_k, or\n frac_of_noise * inverse_noise_rate_class_k * num_examples_s_equal_k\n\n Output\n ------\n\n prune_count_matrix : np.array of shape (K, K), K = number of classes\n Number of examples to remove from each class, for every other class.\"\"\"\n\n prune_count_matrix_diagonal = np.diagonal(prune_count_matrix)\n\n # Set diagonal terms less than n, to n.\n new_diagonal = np.maximum(prune_count_matrix_diagonal, n)\n\n # Find how much diagonal terms were increased.\n diff_per_col = new_diagonal - prune_count_matrix_diagonal\n\n # Count non-zero, non-diagonal items per column\n # np.maximum(*, 1) makes this never 0 (we divide by this next)\n num_noise_rates_per_col = np.maximum(\n np.count_nonzero(prune_count_matrix, axis=0) - 1.,\n 1.,\n )\n\n # Uniformly decrease non-zero noise rates by the same amount\n # that the diagonal items were increased\n new_mat = prune_count_matrix - diff_per_col / num_noise_rates_per_col\n\n # Originally zero noise rates will now be negative, fix them back to zero\n new_mat[new_mat < 0] = 0\n\n # Round diagonal terms (correctly labeled examples)\n np.fill_diagonal(new_mat, new_diagonal)\n\n # Reduce (multiply) all noise rates (non-diagonal) by frac_noise and\n # increase diagonal by the total amount reduced in each column\n # to preserve column counts.\n new_mat = reduce_prune_counts(new_mat, frac_noise)\n\n # These are counts, so return a matrix of ints.\n return round_preserving_row_totals(new_mat).astype(int)\n\n\ndef reduce_prune_counts(prune_count_matrix, frac_noise=1.0):\n \"\"\"Reduce (multiply) all prune counts (non-diagonal) by frac_noise and\n increase diagonal by the total amount reduced in each column to\n preserve column counts.\n\n Parameters\n ----------\n\n prune_count_matrix : np.array of shape (K, K), K = number of classes\n A counts of mislabeled examples in every class. For this function, it\n does not matter what the rows or columns are, but the diagonal terms\n reflect the number of correctly labeled examples.\n\n frac_noise : float\n When frac_of_noise = 1.0, return all estimated noise indices.\n Value in range (0, 1] that determines the fraction of noisy example\n indices to return based on the following formula for example class k.\n frac_of_noise * number_of_mislabeled_examples_in_class_k, or\n frac_of_noise * inverse_noise_rate_class_k * num_examples_s_equal_k.\"\"\"\n\n new_mat = prune_count_matrix * frac_noise\n np.fill_diagonal(new_mat, prune_count_matrix.diagonal())\n np.fill_diagonal(new_mat, prune_count_matrix.diagonal() +\n np.sum(prune_count_matrix - new_mat, axis=0))\n\n # These are counts, so return a matrix of ints.\n return new_mat.astype(int)\n\n\ndef order_label_errors(\n label_errors_bool,\n psx,\n labels,\n sorted_index_method='normalized_margin',\n):\n \"\"\"Sorts label errors by normalized margin.\n See https://arxiv.org/pdf/1810.05369.pdf (eqn 2.2)\n eg. normalized_margin = prob_label - max_prob_not_label\n\n Parameters\n ----------\n label_errors_bool : np.array (bool)\n Contains True if the index of labels is an error, o.w. false\n\n psx : np.array (shape (N, K))\n P(s=k|x) is a matrix with K probabilities for all N examples x.\n This is the probability distribution over all K classes, for each\n example, regarding whether the example has label s==k P(s=k|x). psx\n should computed using 3 (or higher) fold cross-validation.\n\n labels : np.array\n A binary vector of labels, which may contain label errors.\n\n sorted_index_method : str ['normalized_margin', 'prob_given_label']\n Method to order label error indices (instead of a bool mask), either:\n 'normalized_margin' := normalized margin (p(s = k) - max(p(s != k)))\n 'prob_given_label' := [psx[i][labels[i]] for i in label_errors_idx]\n\n Returns\n -------\n label_errors_idx : np.array (int)\n Return the index integers of the label errors, ordered by\n the normalized margin.\"\"\"\n\n # Convert bool mask to index mask\n label_errors_idx = np.arange(len(labels))[label_errors_bool]\n # self confidence is the holdout probability that an example\n # belongs to its given class label\n self_confidence = np.array(\n [np.mean(psx[i][labels[i]]) for i in label_errors_idx]\n )\n if sorted_index_method == 'prob_given_label':\n return label_errors_idx[np.argsort(self_confidence)]\n else: # sorted_index_method == 'normalized_margin'\n margin = self_confidence - psx[label_errors_bool].max(axis=1)\n return label_errors_idx[np.argsort(margin)]\n" ]
[ [ "numpy.dot", "numpy.array", "numpy.sum" ], [ "numpy.partition", "numpy.maximum", "numpy.sum", "numpy.asarray", "numpy.arange", "sklearn.preprocessing.MultiLabelBinarizer", "numpy.stack", "numpy.all", "numpy.frombuffer", "numpy.argmax", "numpy.mean", "numpy.fill_diagonal", "numpy.count_nonzero", "numpy.argsort", "numpy.array", "numpy.diagonal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
deepakkumar1984/ml-api
[ "8d09e9ef99c39838cd2f2db1e70226b8d6cbc77e", "8d09e9ef99c39838cd2f2db1e70226b8d6cbc77e" ]
[ "ml/pipelinecomponents.py", "vis/rcnn/processing/bbox_regression.py" ]
[ "import simplejson as json\nimport os\nimport pickle\nimport jsonpickle\nimport numpy\nimport pandas\nfrom keras import datasets\nfrom keras.models import model_from_json\nfrom pandas import read_csv\nfrom sklearn.model_selection import cross_validate, train_test_split, cross_val_predict\nfrom sklearn.preprocessing import Imputer\nfrom keras.utils import np_utils\nfrom ml import scikitlearn, mxnetfactory\nfrom Interface import projectmgr\nfrom sklearn import preprocessing, feature_selection\n\nprojectfolder = \"\"\nmodel_type = \"\"\nname = \"\"\noptionslist = {}\njobid = \"\"\n\ndef init(self, name, modeltype, jobid=None):\n self.projectfolder = \"./data/\" + name\n self.name = name\n self.jobid = jobid\n self.model_type = modeltype\n\ndef addOption(options):\n for op in options:\n optionslist[op] = options[op]\n\ndef data_loadcsv(pipeline):\n try:\n filename = projectfolder + \"/dataset/\" + pipeline[\"options\"][\"filename\"]\n if pipeline['options']['column_header'] == True:\n dataframe = read_csv(filename, delim_whitespace=pipeline['options']['delim_whitespace'], dtype={'a': numpy.float32})\n else:\n dataframe = read_csv(filename, delim_whitespace=pipeline['options']['delim_whitespace'], header=None, dtype={'a': numpy.float32})\n\n return dataframe\n except Exception as e:\n raise Exception(\"data_loadcsv: \" + str(e))\n\ndef data_loadsample(pipeline):\n dataset_name = pipeline[\"options\"][\"dataset_name\"]\n if dataset_name == \"cifar10\":\n (X_train, Y_train), (X_test, Y_test) = datasets.cifar10.load_data()\n elif dataset_name == \"cifar100\":\n (X_train, Y_train), (X_test, Y_test) = datasets.cifar100.load_data()\n elif dataset_name == \"imdb\":\n (X_train, Y_train), (X_test, Y_test) = datasets.imdb.load_data(path=\"imdb.npz\",\n num_words=None,\n skip_top=0,\n maxlen=None,\n seed=113,\n start_char=1,\n oov_char=2,\n index_from=3)\n elif dataset_name == \"reuters\":\n (X_train, Y_train), (X_test, Y_test) = datasets.reuters.load_data(path=\"reuters.npz\",\n num_words=None,\n skip_top=0,\n maxlen=None,\n test_split=0.2,\n seed=113,\n start_char=1,\n oov_char=2,\n index_from=3)\n elif dataset_name == \"mnist\":\n (X_train, Y_train), (X_test, Y_test) = datasets.mnist.load_data()\n elif dataset_name == \"boston_housing\":\n (X_train, Y_train), (X_test, Y_test) = datasets.boston_housing.load_data()\n\n return (X_train, Y_train), (X_test, Y_test)\n\ndef data_testtrainsplit(X, Y, pipeline):\n test_size = 0.25\n random_state = 42\n if \"test_split\" in pipeline[\"options\"]:\n test_size = pipeline[\"options\"][\"test_size\"]\n\n if \"random_state\" in pipeline[\"options\"]:\n random_state = pipeline[\"options\"][\"random_state\"]\n\n X_train, Y_train, X_test, Y_test = train_test_split(X, Y, test_size=test_size, random_state=random_state)\n return X_train, Y_train, X_test, Y_test\n\ndef data_getxy(dataframe, pipeline):\n try:\n X_frame = dataframe[pipeline['options']['xcols']]\n Y_frame = dataframe[pipeline['options']['ycols']]\n\n return (X_frame,Y_frame)\n except Exception as e:\n raise Exception(\"data_getxy: \" + str(e))\n\ndef data_getx(dataframe, pipeline):\n try:\n X_frame = dataframe[pipeline['options']['xcols']]\n return (X_frame, 0)\n except Exception as e:\n raise Exception(\"data_getxy: \" + str(e))\n\ndef data_handlemissing(dataframe, pipeline):\n try:\n if pipeline['options']['type'] == \"dropcolumns\":\n thresh = pipeline['options']['thresh']\n if thresh == -1:\n dataframe.dropna(axis=1, how=\"all\", inplace=True)\n elif thresh == 0:\n dataframe.dropna(axis=1, how=\"any\", inplace=True)\n elif thresh > 0:\n dataframe.dropna(axis=1, thresh=thresh, inplace=True)\n elif pipeline['options']['type'] == \"droprows\":\n thresh = pipeline['options']['thresh']\n if thresh == -1:\n dataframe.dropna(axis=0, how=\"all\", inplace=True)\n elif thresh == 0:\n dataframe.dropna(axis=0, how=\"any\", inplace=True)\n elif thresh > 0:\n dataframe.dropna(axis=0, thresh=thresh)\n elif pipeline['options']['type'] == \"fillmissing\":\n strategy = pipeline['options']['strategy']\n imp = Imputer(missing_values='NaN', strategy=strategy, axis=0)\n array = imp.fit_transform(dataframe.values)\n dataframe = pandas.DataFrame(array, columns = dataframe.columns)\n\n return dataframe\n except Exception as e:\n raise Exception(\"data_handlemissing: \" + str(e))\n\ndef data_preprocess(dataframe, pipeline):\n try:\n method = pipeline['options']['method']\n data = dataframe.values\n module = eval(\"preprocessing.\" + method)()\n m = getattr(module, \"fit_transform\")\n data = m(data)\n return pandas.DataFrame(data, columns = dataframe.columns)\n except Exception as e:\n raise Exception(\"data_preprocess: \" + str(e))\n\ndef image_preprocess(X, Y, pipeline):\n try:\n normalize = pipeline[\"options\"][\"normalize\"]\n encode = pipeline[\"options\"][\"encode\"]\n reshape = False\n if \"reshape\" in pipeline[\"options\"]:\n reshape = True\n pixels = pipeline[\"options\"][\"reshape\"][\"pixels\"]\n width = pipeline[\"options\"][\"reshape\"][\"width\"]\n height = pipeline[\"options\"][\"reshape\"][\"height\"]\n\n if reshape is True:\n X = X.reshape(X.shape[0], pixels, width, height).astype('float32')\n else:\n X = X.astype('float32')\n\n if normalize is True:\n X = X/255\n\n if encode is True:\n Y = np_utils.to_categorical(Y)\n\n num_classes = Y.shape[1]\n\n return X,Y,num_classes\n except Exception as e:\n raise Exception(\"image_preprocess: \" + str(e))\n\ndef data_featureselection(X, Y, pipeline):\n try:\n method = pipeline[\"options\"]['method']\n transform = pipeline[\"options\"]['transform']\n args = {}\n for p in pipeline[\"options\"]:\n if \"method\" in p:\n continue\n if \"transform\" in p:\n continue\n\n if \"score_func\" in p:\n scorefunc = eval(\"feature_selection.\" + pipeline[\"options\"][p])\n args[p] = scorefunc\n continue\n\n args[p] = pipeline[\"options\"][p]\n\n module = eval(\"feature_selection.\" + method)(**args)\n fit = getattr(module, \"fit\")\n mtransform = getattr(module, \"fit_transform\")\n f = fit(X.values, Y.values)\n names = X.columns\n result = {}\n\n if transform is True:\n data = mtransform(X.values, Y.values)\n selected_columns = []\n fcount = 0\n for fs in f.get_support():\n if fs == True:\n selected_columns.append(names[fcount])\n fcount = fcount + 1\n X = pandas.DataFrame(data, columns=selected_columns)\n else:\n selected_columns = names\n\n if method == \"VarianceThreshold\":\n result['variances'] = sorted(zip(map(lambda x: round(x, 4), f.variances_), names), reverse=True)\n else:\n result['scores'] = sorted(zip(map(lambda x: round(x, 4), f.scores_), names), reverse=True)\n result['pvalues'] = sorted(zip(map(lambda x: round(x, 4), f.pvalues_), names), reverse=True)\n\n result[\"features\"] = selected_columns\n return X, Y, result\n except Exception as e:\n raise Exception(\"data_featureselection: \" + str(e))\n\ndef data_getfeatures(X, Y, result, pipeline):\n try:\n method = pipeline[\"options\"]['method']\n transform = pipeline[\"options\"]['transform']\n result = json.loads(result)\n names = result[\"features\"]\n if transform is True:\n X = X[names]\n\n return X, Y, result\n except Exception as e:\n raise Exception(\"data_getfeatures: \" + str(e))\n\ndef data_featureselection_withestimator(estimator, X, Y, pipeline):\n try:\n method = pipeline[\"options\"]['method']\n transform = pipeline[\"options\"]['transform']\n args = {}\n for p in pipeline[\"options\"]:\n if \"method\" in p:\n continue\n if \"transform\" in p:\n continue\n\n args[p] = pipeline[\"options\"][p]\n\n module = eval(\"feature_selection.\" + method)(estimator = estimator, **args)\n fit = getattr(module, \"fit\")\n mtransform = getattr(module, \"fit_transform\")\n f = fit(X, Y)\n names = X.columns\n if transform is True:\n data = mtransform(X, Y)\n X = data\n selected_columns = []\n fcount = 0\n for fs in f.get_support():\n if fs == True:\n selected_columns.append(names[fcount])\n fcount = fcount + 1\n else:\n selected_columns = names\n\n result = {}\n\n result[\"features\"] = selected_columns\n return (X, Y, result)\n except Exception as e:\n raise Exception(\"data_featureselection_withestimator: \" + str(e))\n\ndef model_evaluate(X, Y, pipeline):\n try:\n results = []\n if \"scoring\" in pipeline[\"options\"]:\n if len(pipeline['options']['scoring']) > 0:\n scoring = pipeline['options']['scoring']\n else:\n scoring = \"neg_mean_squared_error\"\n else:\n scoring = \"neg_mean_squared_error\"\n\n kfold = 10\n if \"kfold\" in pipeline['options']:\n kfold = int(pipeline[\"options\"][\"kfold\"])\n\n model = scikitlearn.getSKLearnModel(pipeline['options']['model_name'])\n valresult = cross_validate(model, X, Y, cv=kfold, scoring=scoring, return_train_score=True)\n\n model.fit(X, Y)\n for p in valresult:\n results.append({\"param\": p, \"values\": valresult[p].tolist(), \"min\": valresult[p].min, \"max\": valresult[p].max});\n output = jsonpickle.encode(results, unpicklable=False)\n projectmgr.UpdateExecuteResult(jobid, output)\n picklefile = projectfolder + \"/model.out\"\n with open(picklefile, \"wb\") as f:\n pickle.dump(model, f)\n\n return output\n except Exception as e:\n raise Exception(\"model_evaluate: \" + str(e))\n\ndef model_train(X, Y, pipeline, X_test=None, Y_test=None, more = False):\n try:\n result = None\n if model_type == \"mlp\":\n deepmodel = projectmgr.GetDeepModel(name, \"ml\", pipeline['options']['model_name'])\n if deepmodel is None:\n raise Exception(pipeline['options']['model_name'] + \": Model not found!\")\n\n modeljson = json.loads(deepmodel.modeldata)\n modelObj = mxnetfactory.createModel(modeljson)\n #modelObj.compile(loss=pipeline['options']['loss'], optimizer=pipeline['options']['optimizer'],\n # metrics=pipeline['options']['scoring'])\n epoches = pipeline[\"options\"][\"epoches\"]\n batch_size = pipeline[\"options\"][\"batch_size\"]\n mxnetfactory.init(mxnetfactory, name, jobid)\n result = mxnetfactory.Train(modelObj, X, Y, projectfolder, pipeline[\"options\"], epoches, batch_size, X_test=None, Y_test=None, more=more)\n projectmgr.UpdateExecuteResult(jobid, json.dumps(result))\n picklefile = projectfolder + \"/model.json\"\n model_json = modelObj.to_json()\n with open(picklefile, \"w\") as json_file:\n json_file.write(model_json)\n\n return result\n except Exception as e:\n raise Exception(\"model_train: \" + str(e))\n\ndef model_predict(X, pipeline):\n if model_type == \"mlp\":\n json_file = open(projectfolder + '/model.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n model = model_from_json(loaded_model_json)\n model.load_weights(projectfolder + \"/weights.hdf5\")\n model.compile(loss=pipeline['options']['loss'], optimizer=pipeline['options']['optimizer'],\n metrics=pipeline['options']['scoring'])\n if type(X) is pandas.DataFrame:\n X = X.values\n Y = model.predict(X)\n else:\n picklefile = projectfolder + \"/model.out\"\n with open(picklefile, \"rb\") as f:\n model = pickle.load(f)\n Y = model.predict(X)\n\n return Y\n\ndef return_result(outputname, num = None):\n pickleFile = projectfolder + '/pipeline.out'\n with open(pickleFile, 'rb') as f:\n resultset = pickle.load(f)\n\n result = None\n if num is None:\n outputname = \"output->\" + outputname\n else:\n outputname = \"output->\" + outputname + \"->\" + str(num)\n\n count = 0\n resultDict = {}\n for r in resultset:\n if outputname in r:\n if count > 0:\n resultDict[count - 1] = result\n resultDict[count] = resultset[r]\n else:\n result = resultset[r]\n\n count = count+1\n\n if count > 1:\n return resultDict\n\n return result\n\n", "\"\"\"\nThis file has functions about generating bounding box regression targets\n\"\"\"\n\nimport numpy as np\n\nfrom ..logger import logger\nfrom bbox_transform import bbox_overlaps, bbox_transform\nfrom vis.rcnn.config import config\n\n\ndef compute_bbox_regression_targets(rois, overlaps, labels):\n \"\"\"\n given rois, overlaps, gt labels, compute bounding box regression targets\n :param rois: roidb[i]['boxes'] k * 4\n :param overlaps: roidb[i]['max_overlaps'] k * 1\n :param labels: roidb[i]['max_classes'] k * 1\n :return: targets[i][class, dx, dy, dw, dh] k * 5\n \"\"\"\n # Ensure ROIs are floats\n rois = rois.astype(np.float, copy=False)\n\n # Sanity check\n if len(rois) != len(overlaps):\n logger.warning('bbox regression: len(rois) != len(overlaps)')\n\n # Indices of ground-truth ROIs\n gt_inds = np.where(overlaps == 1)[0]\n if len(gt_inds) == 0:\n logger.warning('bbox regression: len(gt_inds) == 0')\n\n # Indices of examples for which we try to make predictions\n ex_inds = np.where(overlaps >= config.TRAIN.BBOX_REGRESSION_THRESH)[0]\n\n # Get IoU overlap between each ex ROI and gt ROI\n ex_gt_overlaps = bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :])\n\n # Find which gt ROI each ex ROI has max overlap with:\n # this will be the ex ROI's gt target\n gt_assignment = ex_gt_overlaps.argmax(axis=1)\n gt_rois = rois[gt_inds[gt_assignment], :]\n ex_rois = rois[ex_inds, :]\n\n targets = np.zeros((rois.shape[0], 5), dtype=np.float32)\n targets[ex_inds, 0] = labels[ex_inds]\n targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois)\n return targets\n\n\ndef add_bbox_regression_targets(roidb):\n \"\"\"\n given roidb, add ['bbox_targets'] and normalize bounding box regression targets\n :param roidb: roidb to be processed. must have gone through imdb.prepare_roidb\n :return: means, std variances of targets\n \"\"\"\n logger.info('bbox regression: add bounding box regression targets')\n assert len(roidb) > 0\n assert 'max_classes' in roidb[0]\n\n num_images = len(roidb)\n num_classes = roidb[0]['gt_overlaps'].shape[1]\n for im_i in range(num_images):\n rois = roidb[im_i]['boxes']\n max_overlaps = roidb[im_i]['max_overlaps']\n max_classes = roidb[im_i]['max_classes']\n roidb[im_i]['bbox_targets'] = compute_bbox_regression_targets(rois, max_overlaps, max_classes)\n\n if config.TRAIN.BBOX_NORMALIZATION_PRECOMPUTED:\n # use fixed / precomputed means and stds instead of empirical values\n means = np.tile(np.array(config.TRAIN.BBOX_MEANS), (num_classes, 1))\n stds = np.tile(np.array(config.TRAIN.BBOX_STDS), (num_classes, 1))\n else:\n # compute mean, std values\n class_counts = np.zeros((num_classes, 1)) + 1e-14\n sums = np.zeros((num_classes, 4))\n squared_sums = np.zeros((num_classes, 4))\n for im_i in range(num_images):\n targets = roidb[im_i]['bbox_targets']\n for cls in range(1, num_classes):\n cls_indexes = np.where(targets[:, 0] == cls)[0]\n if cls_indexes.size > 0:\n class_counts[cls] += cls_indexes.size\n sums[cls, :] += targets[cls_indexes, 1:].sum(axis=0)\n squared_sums[cls, :] += (targets[cls_indexes, 1:] ** 2).sum(axis=0)\n\n means = sums / class_counts\n # var(x) = E(x^2) - E(x)^2\n stds = np.sqrt(squared_sums / class_counts - means ** 2)\n\n # normalized targets\n for im_i in range(num_images):\n targets = roidb[im_i]['bbox_targets']\n for cls in range(1, num_classes):\n cls_indexes = np.where(targets[:, 0] == cls)[0]\n roidb[im_i]['bbox_targets'][cls_indexes, 1:] -= means[cls, :]\n roidb[im_i]['bbox_targets'][cls_indexes, 1:] /= stds[cls, :]\n\n return means.ravel(), stds.ravel()\n\n\ndef expand_bbox_regression_targets(bbox_targets_data, num_classes):\n \"\"\"\n expand from 5 to 4 * num_classes; only the right class has non-zero bbox regression targets\n :param bbox_targets_data: [k * 5]\n :param num_classes: number of classes\n :return: bbox target processed [k * 4 num_classes]\n bbox_weights ! only foreground boxes have bbox regression computation!\n \"\"\"\n classes = bbox_targets_data[:, 0]\n bbox_targets = np.zeros((classes.size, 4 * num_classes), dtype=np.float32)\n bbox_weights = np.zeros(bbox_targets.shape, dtype=np.float32)\n indexes = np.where(classes > 0)[0]\n for index in indexes:\n cls = classes[index]\n start = int(4 * cls)\n end = start + 4\n bbox_targets[index, start:end] = bbox_targets_data[index, 1:]\n bbox_weights[index, start:end] = config.TRAIN.BBOX_WEIGHTS\n return bbox_targets, bbox_weights\n\n" ]
[ [ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.Imputer", "pandas.DataFrame", "sklearn.model_selection.cross_validate" ], [ "numpy.sqrt", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
likojack/bnv_fusion
[ "76b7354c6f3bf8c7f7e1ff4d958de0e73ec3e614" ]
[ "src/utils/torchvision_utils.py" ]
[ "import torch\nimport torchvision.transforms as T\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport matplotlib as mpl\nimport matplotlib.cm as cm\n\n\ndef visualize_depth(depth, cmap=cv2.COLORMAP_JET):\n \"\"\"\n depth: (H, W)\n \"\"\"\n x = depth.astype(np.uint8)\n x_ = Image.fromarray(cv2.applyColorMap(x, cmap))\n x_ = T.ToTensor()(x_) # (3, H, W)\n return x_\n\n\ndef visualize_prob(prob, cmap=cv2.COLORMAP_BONE):\n \"\"\"\n prob: (H, W) 0~1\n \"\"\"\n x = (255*prob).astype(np.uint8)\n x_ = Image.fromarray(cv2.applyColorMap(x, cmap))\n x_ = T.ToTensor()(x_) # (3, H, W)\n return x_\n\n\ndef depth_visualizer(data, min_depth, max_depth):\n \"\"\"\n Args:\n data (HxW): depth data\n Returns:\n vis_data (HxWx3): depth visualization (RGB)\n \"\"\"\n\n mask = np.logical_and(data > min_depth, data < max_depth)\n inv_depth = 1 / (data + 1e-6)\n vmax = np.percentile(1/(data[mask]+1e-6), 90)\n normalizer = mpl.colors.Normalize(vmin=inv_depth.min(), vmax=vmax)\n mapper = cm.ScalarMappable(norm=normalizer, cmap='magma')\n vis_data = (mapper.to_rgba(inv_depth)[:, :, :3] * 255).astype(np.uint8)\n return vis_data" ]
[ [ "numpy.logical_and", "matplotlib.cm.ScalarMappable", "numpy.percentile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Valerio-Colombo/mbcd
[ "8bb8adce78d303e991d8afdb3fbc045970297f83", "8bb8adce78d303e991d8afdb3fbc045970297f83" ]
[ "mbcd/models/bnn.py", "experiments/mbcd_run.py" ]
[ "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport time\nimport pdb\nimport itertools\nfrom collections import OrderedDict\n\nimport tensorflow as tf\nimport numpy as np\nfrom tqdm import trange\nfrom scipy.io import savemat, loadmat\n\nfrom mbcd.models.utils import get_required_argument, TensorStandardScaler\nfrom mbcd.models.fc import FC\nfrom mbcd.utils.logger import Progress, Silent\nfrom sklearn.preprocessing import PolynomialFeatures\n\nnp.set_printoptions(precision=4)\n\n\nclass BNN:\n \"\"\"Neural network models which model aleatoric uncertainty (and possibly epistemic uncertainty\n with ensembling).\n Code adapted from https://github.com/JannerM/mbpo/blob/master/mbpo/models/bnn.py\n \"\"\"\n\n def __init__(self, params):\n \"\"\"Initializes a class instance.\n\n Arguments:\n params (DotMap): A dotmap of model parameters.\n .name (str): Model name, used for logging/use in variable scopes.\n Warning: Models with the same name will overwrite each other.\n .num_networks (int): (optional) The number of networks in the ensemble. Defaults to 1.\n Ignored if model is being loaded.\n .model_dir (str/None): (optional) Path to directory from which model will be loaded, and\n saved by default. Defaults to None.\n .load_model (bool): (optional) If True, model will be loaded from the model directory,\n assuming that the files are generated by a model of the same name. Defaults to False.\n .sess (tf.Session/None): The session that this model will use.\n If None, creates a session with its own associated graph. Defaults to None.\n \"\"\"\n self.name = get_required_argument(params, 'name', 'Must provide name.')\n self.model_dir = params.get('model_dir', None)\n\n print('[ BNN ] Initializing model: {} | {} networks | {} elites'.format(params['name'], params['num_networks'],\n params['num_elites']))\n if params.get('sess', None) is None:\n # config = tf.ConfigProto(device_count = {'GPU': 0})\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n self._sess = tf.Session(config=config)\n else:\n self._sess = params.get('sess')\n\n # Instance variables\n self.finalized = False\n self.layers, self.max_logvar, self.min_logvar = [], None, None\n self.decays, self.optvars, self.nonoptvars = [], [], []\n self.end_act, self.end_act_name = None, None\n self.scaler = None\n\n # Training objects\n self.train_loss = None\n self.accum_grads = None\n self.zero_ops = None\n self.accum_ops = None\n self.scale_coeff = None\n self.learning_rate = None\n self.optimizer = None\n self.sy_train_in, self.sy_train_targ = None, None\n self.grads, self.graph_vars = None, None\n self.train_op, self.train_op_rescaled, self.mse_loss = None, None, None\n\n # Prediction objects\n self.sy_pred_in2d, self.sy_pred_mean2d_fac, self.sy_pred_var2d_fac = None, None, None\n self.sy_pred_mean2d, self.sy_pred_var2d = None, None\n self.sy_pred_in3d, self.sy_pred_mean3d_fac, self.sy_pred_var3d_fac = None, None, None\n\n if params.get('load_model', False):\n if self.model_dir is None:\n raise ValueError(\"Cannot load model without providing model directory.\")\n self._load_structure()\n self.num_nets, self.model_loaded = self.layers[0].get_ensemble_size(), True\n print(\"Model loaded from %s.\" % self.model_dir)\n self.num_elites = params['num_elites']\n else:\n self.num_nets = params.get('num_networks', 1)\n self.num_elites = params['num_elites'] # params.get('num_elites', 1)\n self.model_loaded = False\n\n if self.num_nets == 1:\n print(\"Created a neural network with variance predictions.\")\n else:\n print(\n \"Created an ensemble of {} neural networks with variance predictions | Elites: {}\".format(self.num_nets,\n self.num_elites))\n\n self._model_inds = [i for i in range(self.num_nets)]\n\n @property\n def is_probabilistic(self):\n return True\n\n @property\n def is_tf_model(self):\n return True\n\n @property\n def sess(self):\n return self._sess\n\n ###################################\n # Network Structure Setup Methods #\n ###################################\n\n def add(self, layer):\n \"\"\"Adds a new layer to the network.\n\n Arguments:\n layer: (layer) The new layer to be added to the network.\n If this is the first layer, the input dimension of the layer must be set.\n\n Returns: None.\n \"\"\"\n if self.finalized:\n raise RuntimeError(\"Cannot modify network structure after finalizing.\")\n if len(self.layers) == 0 and layer.get_input_dim() is None:\n raise ValueError(\"Must set input dimension for the first layer.\")\n if self.model_loaded:\n raise RuntimeError(\"Cannot add layers to a loaded model.\")\n\n layer.set_ensemble_size(self.num_nets)\n if len(self.layers) > 0:\n layer.set_input_dim(self.layers[-1].get_output_dim())\n self.layers.append(layer.copy())\n\n def pop(self):\n \"\"\"Removes and returns the most recently added layer to the network.\n\n Returns: (layer) The removed layer.\n \"\"\"\n if len(self.layers) == 0:\n raise RuntimeError(\"Network is empty.\")\n if self.finalized:\n raise RuntimeError(\"Cannot modify network structure after finalizing.\")\n if self.model_loaded:\n raise RuntimeError(\"Cannot remove layers from a loaded model.\")\n\n return self.layers.pop()\n\n def finalize(self, optimizer, optimizer_args=None, *args, **kwargs):\n \"\"\"Finalizes the network.\n\n Arguments:\n optimizer: (tf.train.Optimizer) An optimizer class from those available at tf.train.Optimizer.\n optimizer_args: (dict) A dictionary of arguments for the __init__ method of the chosen optimizer.\n\n Returns: None\n \"\"\"\n if len(self.layers) == 0:\n raise RuntimeError(\"Cannot finalize an empty network.\")\n if self.finalized:\n raise RuntimeError(\"Can only finalize a network once.\")\n\n optimizer_args = {} if optimizer_args is None else optimizer_args\n\n self.learning_rate = optimizer_args.get(\"learning_rate\")\n self.optimizer = optimizer(**optimizer_args)\n\n # Add variance output.\n self.layers[-1].set_output_dim(2 * self.layers[-1].get_output_dim())\n\n # Remove last activation to isolate variance from activation function.\n self.end_act = self.layers[-1].get_activation()\n self.end_act_name = self.layers[-1].get_activation(as_func=False)\n self.layers[-1].unset_activation()\n\n # Construct all variables.\n with self.sess.as_default():\n with tf.variable_scope(self.name):\n self.scaler = TensorStandardScaler(self.name, self.layers[0].get_input_dim())\n self.max_logvar = tf.Variable(np.ones([1, self.layers[-1].get_output_dim() // 2]) / 2.,\n dtype=tf.float32,\n name=\"max_log_var\")\n self.min_logvar = tf.Variable(-np.ones([1, self.layers[-1].get_output_dim() // 2]) * 10.,\n dtype=tf.float32,\n name=\"min_log_var\")\n for i, layer in enumerate(self.layers):\n with tf.variable_scope(self.name + \"Layer%i\" % i):\n layer.construct_vars()\n self.decays.extend(layer.get_decays())\n self.optvars.extend(layer.get_vars())\n self.optvars.extend([self.max_logvar, self.min_logvar])\n self.nonoptvars.extend(self.scaler.get_vars())\n\n # Set up training\n with tf.variable_scope(self.name):\n self.optimizer = optimizer(**optimizer_args)\n self.sy_train_in = tf.placeholder(dtype=tf.float32,\n shape=[self.num_nets, None, self.layers[0].get_input_dim()],\n name=\"training_inputs\")\n self.sy_train_targ = tf.placeholder(dtype=tf.float32,\n shape=[self.num_nets, None, self.layers[-1].get_output_dim() // 2],\n name=\"training_targets\")\n self.train_loss = tf.reduce_sum(\n self._compile_losses(self.sy_train_in, self.sy_train_targ, inc_var_loss=True))\n self.train_loss += tf.add_n(self.decays)\n self.train_loss += 0.01 * tf.reduce_sum(self.max_logvar) - 0.01 * tf.reduce_sum(self.min_logvar)\n self.mse_loss = self._compile_losses(self.sy_train_in, self.sy_train_targ, inc_var_loss=False)\n\n self.train_op = self.optimizer.minimize(self.train_loss, var_list=self.optvars)\n self.grads, self.graph_vars = zip(*self.optimizer.compute_gradients(self.train_loss, var_list=self.optvars))\n\n self.scale_coeff = tf.placeholder(tf.float32)\n\n # Accumulation ops and variables\n # create a copy of all trainable variables with `0` as initial values\n self.accum_grads = [tf.Variable(tf.zeros_like(t_var.initialized_value()), trainable=False) for t_var in\n self.optvars]\n print(\"OPTVARS: {}\".format(self.optvars))\n print(\"TRAINABLEVARS: {}\".format(tf.trainable_variables()))\n\n # create an op to zero all accumulated vars\n self.zero_ops = [tv.assign(tf.zeros_like(tv)) for tv in self.accum_grads]\n\n # Create ops for accumulating the gradient\n self.accum_ops = [accum_grad.assign_add(grad * self.scale_coeff) for (accum_grad, grad) in\n zip(self.accum_grads, self.grads)]\n\n self.train_op_rescaled = self.optimizer.apply_gradients(zip(self.accum_grads, self.graph_vars))\n\n # Initialize all variables\n self.sess.run(tf.global_variables_initializer())\n # self.sess.run(tf.variables_initializer(self.optvars + self.nonoptvars + self.optimizer.variables()))\n\n # Set up prediction\n with tf.variable_scope(self.name):\n self.sy_pred_in2d = tf.placeholder(dtype=tf.float32,\n shape=[None, self.layers[0].get_input_dim()],\n name=\"2D_training_inputs\")\n self.sy_pred_mean2d_fac, self.sy_pred_var2d_fac = self.create_prediction_tensors(self.sy_pred_in2d,\n factored=True)\n self.sy_pred_mean2d = tf.reduce_mean(self.sy_pred_mean2d_fac, axis=0)\n self.sy_pred_var2d = tf.reduce_mean(self.sy_pred_var2d_fac, axis=0) + tf.reduce_mean(\n tf.square(self.sy_pred_mean2d_fac - self.sy_pred_mean2d), axis=0)\n\n self.sy_pred_in3d = tf.placeholder(dtype=tf.float32,\n shape=[self.num_nets, None, self.layers[0].get_input_dim()],\n name=\"3D_training_inputs\")\n self.sy_pred_mean3d_fac, self.sy_pred_var3d_fac = self.create_prediction_tensors(self.sy_pred_in3d,\n factored=True)\n\n # Load model if needed\n if self.model_loaded:\n with self.sess.as_default():\n params_dict = loadmat(os.path.join(self.model_dir, \"%s.mat\" % self.name))\n all_vars = self.nonoptvars + self.optvars\n for i, var in enumerate(all_vars):\n var.load(params_dict[str(i)])\n self.finalized = True\n\n ##################\n # Custom Methods #\n ##################\n\n def get_weights(self):\n return {idx: [layer.get_model_vars(idx, self.sess) for layer in self.layers] for idx in range(self.num_nets)}\n\n def set_weights(self, weights):\n keys = ['weights', 'biases']\n ops = []\n num_layers = len(self.layers)\n for layer in range(num_layers):\n # net_state = self._state[i]\n params = {key: np.stack([weights[net][layer][key] for net in range(self.num_nets)]) for key in keys}\n ops.extend(self.layers[layer].set_model_vars(params))\n self.sess.run(ops)\n\n def _save_state(self, idx):\n self._state[idx] = [layer.get_model_vars(idx, self.sess) for layer in self.layers]\n\n def _set_state(self):\n keys = ['weights', 'biases']\n # ops = []\n num_layers = len(self.layers)\n for layer in range(num_layers):\n # net_state = self._state[i]\n params = {key: np.stack([self._state[net][layer][key] for net in range(self.num_nets)]) for key in keys}\n self.layers[layer].set_model_vars(params, self.sess)\n # ops.extend()\n # self.sess.run(ops)\n\n def _save_best(self, epoch, holdout_losses):\n updated = False\n for i in range(len(holdout_losses)):\n current = holdout_losses[i]\n _, best = self._snapshots[i]\n improvement = (best - current) / best\n if improvement > 0.01:\n self._snapshots[i] = (epoch, current)\n self._save_state(i)\n updated = True\n improvement = (best - current) / best\n # print('epoch {} | updated {} | improvement: {:.4f} | best: {:.4f} | current: {:.4f}'.format(epoch, i, improvement, best, current))\n\n if updated:\n self._epochs_since_update = 0\n else:\n self._epochs_since_update += 1\n\n if self._epochs_since_update > self._max_epochs_since_update:\n # print('[ BNN ] Breaking at epoch {}: {} epochs since update ({} max)'.format(epoch, self._epochs_since_update, self._max_epochs_since_update))\n return True\n else:\n return False\n\n def _start_train(self):\n self._state = {}\n self._snapshots = {i: (None, 1e10) for i in range(self.num_nets)}\n self._epochs_since_update = 0\n\n def _end_train(self, holdout_losses):\n sorted_inds = np.argsort(holdout_losses)\n self._model_inds = sorted_inds[:self.num_elites].tolist()\n print('Using {} / {} models: {}'.format(self.num_elites, self.num_nets, self._model_inds))\n\n def random_inds(self, batch_size):\n inds = np.random.choice(self._model_inds, size=batch_size)\n return inds\n\n def reset(self):\n print('[ BNN ] Resetting model')\n [layer.reset(self.sess) for layer in self.layers]\n\n def validate(self, inputs, targets):\n inputs = np.tile(inputs[None], [self.num_nets, 1, 1])\n targets = np.tile(targets[None], [self.num_nets, 1, 1])\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: inputs,\n self.sy_train_targ: targets\n }\n )\n mean_elite_loss = np.sort(losses)[:self.num_elites].mean()\n return mean_elite_loss\n\n #################\n # Model Methods #\n #################\n\n # @profile\n def train(self, inputs, targets,\n batch_size=32, max_epochs=None, max_epochs_since_update=5,\n hide_progress=False, holdout_ratio=0.0, max_logging=5000, max_grad_updates=None, timer=None,\n max_t=None):\n \"\"\"Trains/Continues network training\n Arguments:\n inputs (np.ndarray): Network inputs in the training dataset in rows.\n targets (np.ndarray): Network target outputs in the training dataset in rows corresponding\n to the rows in inputs.\n batch_size (int): The minibatch size to be used for training.\n epochs (int): Number of epochs (full network passes that will be done.\n hide_progress (bool): If True, hides the progress bar shown at the beginning of training.\n Returns: None\n \"\"\"\n self._max_epochs_since_update = max_epochs_since_update\n self._start_train()\n break_train = False\n\n def shuffle_rows(arr):\n idxs = np.argsort(np.random.uniform(size=arr.shape), axis=-1)\n return arr[np.arange(arr.shape[0])[:, None], idxs]\n\n with self.sess.as_default():\n self.scaler.fit(inputs)\n\n # Split into training and holdout sets\n num_holdout = min(int(inputs.shape[0] * holdout_ratio), max_logging)\n permutation = np.random.permutation(inputs.shape[0])\n inputs, holdout_inputs = inputs[permutation[num_holdout:]], inputs[permutation[:num_holdout]]\n targets, holdout_targets = targets[permutation[num_holdout:]], targets[permutation[:num_holdout]]\n holdout_inputs = np.tile(holdout_inputs[None], [self.num_nets, 1, 1])\n holdout_targets = np.tile(holdout_targets[None], [self.num_nets, 1, 1])\n\n print('\\n[ BNN ] Training {} | Holdout: {}'.format(inputs.shape, holdout_inputs.shape))\n\n idxs = np.random.randint(inputs.shape[0], size=[self.num_nets, inputs.shape[0]])\n if hide_progress:\n progress = Silent()\n else:\n progress = Progress(max_epochs)\n\n if max_epochs:\n epoch_iter = range(max_epochs)\n else:\n epoch_iter = itertools.count()\n\n # else:\n # epoch_range = trange(epochs, unit=\"epoch(s)\", desc=\"Network training\")\n\n t0 = time.time()\n grad_updates = 0\n for epoch in epoch_iter:\n # print(\"Normal - Epoch: {}\".format(epoch))\n for batch_num in range(int(np.ceil(idxs.shape[-1] / batch_size))):\n batch_idxs = idxs[:, batch_num * batch_size:(batch_num + 1) * batch_size]\n self.sess.run(\n self.train_op,\n feed_dict={self.sy_train_in: inputs[batch_idxs],\n self.sy_train_targ: targets[batch_idxs],\n self.learning_rate: 0.001}\n )\n # print(\"Classic loss: {}\".format(loss))\n grad_updates += 1\n\n idxs = shuffle_rows(idxs)\n if not hide_progress:\n if holdout_ratio < 1e-12:\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: inputs[idxs[:, :max_logging]],\n self.sy_train_targ: targets[idxs[:, :max_logging]]\n }\n )\n named_losses = [['M{}'.format(i), losses[i]] for i in range(len(losses))]\n progress.set_description(named_losses)\n else:\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: inputs[idxs[:, :max_logging]],\n self.sy_train_targ: targets[idxs[:, :max_logging]]\n }\n )\n holdout_losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: holdout_inputs,\n self.sy_train_targ: holdout_targets\n }\n )\n named_losses = [['M{}'.format(i), losses[i]] for i in range(len(losses))]\n named_holdout_losses = [['V{}'.format(i), holdout_losses[i]] for i in\n range(len(holdout_losses))]\n named_losses = named_losses + named_holdout_losses + [['T', time.time() - t0]]\n progress.set_description(named_losses)\n\n break_train = self._save_best(epoch, holdout_losses)\n\n progress.update()\n t = time.time() - t0\n if break_train or (max_grad_updates and grad_updates > max_grad_updates):\n break\n if max_t and t > max_t:\n descr = 'Breaking because of timeout: {}! (max: {})'.format(t, max_t)\n progress.append_description(descr)\n # print('Breaking because of timeout: {}! | (max: {})\\n'.format(t, max_t))\n # time.sleep(5)\n break\n print(\"Trained with normal for {} epochs\".format(epoch + 1))\n\n if holdout_ratio > 0:\n progress.stamp()\n if timer: timer.stamp('bnn_train')\n\n self._set_state()\n if timer: timer.stamp('bnn_set_state')\n\n holdout_losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: holdout_inputs,\n self.sy_train_targ: holdout_targets\n }\n )\n\n if timer: timer.stamp('bnn_holdout')\n\n self._end_train(holdout_losses)\n if timer: timer.stamp('bnn_end')\n\n val_loss = (np.sort(holdout_losses)[:self.num_elites]).mean()\n model_metrics = {'val_loss': val_loss}\n print('[ BNN ] Holdout', np.sort(holdout_losses), model_metrics, '\\n')\n return OrderedDict(model_metrics)\n # return np.sort(holdout_losses)[]\n\n # pdb.set_trace()\n else:\n self._model_inds = [0, 1, 2, 3, 4]\n\n def generate_grad_coeff_poly(self, num_batch=40, poly_grade=4):\n poly = PolynomialFeatures(poly_grade)\n\n scale = 1\n x = np.linspace(0, num_batch * scale, num=num_batch)\n phi = poly.fit_transform(x[:, np.newaxis])\n proto_H = np.matmul(np.linalg.inv(np.matmul(phi.transpose(), phi)), phi.transpose())\n fut_step = np.array([num_batch])[None]\n grad = np.matmul(poly.fit_transform(fut_step), proto_H)\n # grad = np.flip(grad)\n\n return grad\n\n def exp_basis(self, x):\n return np.array([1, np.power(1.1, x)])\n\n def generate_grad_coeff_exp(self, num_batch=40): # low->high\n x = np.linspace(0, num_batch * 1.15, num=num_batch)\n basis_dim = self.exp_basis(1).shape[0]\n\n phi = np.ones([num_batch, basis_dim])\n for idx in range(num_batch):\n phi[idx] = self.exp_basis(x[idx])\n proto_H = np.matmul(np.linalg.inv(np.matmul(phi.transpose(), phi)), phi.transpose())\n fut_step_t = self.exp_basis(num_batch)\n grad = np.matmul(fut_step_t, proto_H)\n # grad = np.flip(grad)\n\n return grad\n\n # @profile\n def train_modified_holdout(self, inputs, targets,\n batch_size=32, max_epochs=None, max_epochs_since_update=5,\n hide_progress=False, holdout_ratio=0.0, max_logging=5000,\n max_grad_updates=None, timer=None, max_t=None, lr=0.001):\n \"\"\"Trains/Continues network training\n\n Arguments:\n inputs (np.ndarray): Network inputs in the training dataset in rows.\n targets (np.ndarray): Network target outputs in the training dataset in rows corresponding\n to the rows in inputs.\n batch_size (int): The minibatch size to be used for training.\n epochs (int): Number of epochs (full network passes that will be done.\n hide_progress (bool): If True, hides the progress bar shown at the beginning of training.\n\n Returns: None\n \"\"\"\n self._max_epochs_since_update = max_epochs_since_update\n self._start_train()\n break_train = False\n\n def shuffle_rows(arr):\n idxs = np.argsort(np.random.uniform(size=arr.shape), axis=-1)\n return arr[np.arange(arr.shape[0])[:, None], idxs]\n\n with self.sess.as_default():\n self.scaler.fit(inputs)\n\n num_holdout = min(int(inputs.shape[0] * holdout_ratio), max_logging)\n\n ############\n # 1) Calculate gradient and sampling coefficients\n total_num_batch = int(np.floor(inputs.shape[0] / batch_size))\n # scale_coeff = self.generate_grad_coeff_exp(num_batch=total_num_batch)\n # scale_coeff = np.full((total_num_batch), 1/total_num_batch)\n scale_coeff = self.generate_grad_coeff_poly(num_batch=total_num_batch, poly_grade=1)\n sampling_coeff = np.repeat(scale_coeff, batch_size)\n for i in range(sampling_coeff.shape[0]):\n if sampling_coeff[i] < 0:\n sampling_coeff[i] = 0\n sampling_coeff = sampling_coeff / np.sum(sampling_coeff) # normalize\n print(\"Sampling coeff sum: {}\".format(np.sum(sampling_coeff)))\n\n # 2) Sample holdout set\n idx_holdout = np.empty([num_holdout], dtype=int)\n idxs_i = np.arange(inputs.shape[0], dtype=int)[-total_num_batch * batch_size:]\n\n for s in range(num_holdout):\n idx_holdout[s] = np.random.choice(a=idxs_i, p=sampling_coeff)\n\n holdout_inputs = inputs[idx_holdout]\n holdout_inputs = np.tile(holdout_inputs[None], [self.num_nets, 1, 1])\n holdout_targets = targets[idx_holdout]\n holdout_targets = np.tile(holdout_targets[None], [self.num_nets, 1, 1])\n\n # 3) Delete holdout data from inputs\n train_inputs = np.delete(inputs, idx_holdout, axis=0)\n train_targets = np.delete(targets, idx_holdout, axis=0)\n\n train_num_batch = int(np.floor(train_inputs.shape[0] / batch_size))\n train_inputs = train_inputs[-train_num_batch * batch_size:]\n train_targets = train_targets[-train_num_batch * batch_size:]\n\n # 4) Divide in batches\n\n train_inputs_b = np.array(np.split(train_inputs, train_num_batch))\n train_targets_b = np.array(np.split(train_targets, train_num_batch))\n\n ############\n\n # permutation = np.random.permutation(inputs.shape[0])\n # inputs, holdout_inputs = inputs[num_holdout:], inputs[:num_holdout]\n # targets, holdout_targets = targets[num_holdout:], targets[:num_holdout]\n # holdout_inputs = np.tile(holdout_inputs[None], [self.num_nets, 1, 1])\n # holdout_targets = np.tile(holdout_targets[None], [self.num_nets, 1, 1])\n\n print('[ BNN ] Training {} | Holdout: {}'.format(train_inputs.shape, holdout_inputs.shape))\n\n # idxs = np.random.randint(inputs.shape[0], size=[self.num_nets, inputs.shape[0]])\n if hide_progress:\n progress = Silent()\n else:\n progress = Progress(max_epochs)\n\n if max_epochs:\n epoch_iter = range(max_epochs)\n else:\n epoch_iter = itertools.count()\n\n # else:\n # epoch_range = trange(epochs, unit=\"epoch(s)\", desc=\"Network training\")\n\n # total_num_batch = int(np.ceil(idxs.shape[-1] / batch_size))\n #\n # # scale_coeff = self.generate_grad_coeff_poly(num_batch=total_num_batch, poly_grade=2)\n # scale_coeff = self.generate_grad_coeff_exp(num_batch=total_num_batch)\n\n t0 = time.time()\n grad_updates = 0\n for epoch in epoch_iter:\n print(\"Modified - Epoch: {}\".format(epoch))\n for batch_num in range(train_num_batch):\n # batch_idxs = np.arange(inputs.shape[0] - batch_size * (batch_num + 1),\n # inputs.shape[0] - batch_size * batch_num)\n # batch_idxs_arr = [batch_idxs for _ in range(self.num_nets)]\n # arrays_stack = np.stack(batch_idxs_arr, axis=0)\n curr_train_inputs = train_inputs_b[train_num_batch - batch_num - 1]\n curr_train_targets = train_targets_b[train_num_batch - batch_num - 1]\n\n curr_idxs = np.arange(batch_size)\n np.random.shuffle(curr_idxs)\n curr_train_inputs = curr_train_inputs[curr_idxs]\n curr_train_targets = curr_train_targets[curr_idxs]\n\n curr_train_inputs = [curr_train_inputs for _ in range(self.num_nets)]\n curr_train_targets = [curr_train_targets for _ in range(self.num_nets)]\n\n _, _loss = self.sess.run(\n (self.accum_ops, self.train_loss),\n feed_dict={self.sy_train_in: curr_train_inputs,\n self.sy_train_targ: curr_train_targets,\n self.scale_coeff: scale_coeff.item(total_num_batch - batch_num - 1)}\n # TODO invert. No more flip!!!! - ?\n )\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: curr_train_inputs,\n self.sy_train_targ: curr_train_targets\n }\n )\n # print(\"Epoch: {} - Batch: {} - Train Loss: {} - MSE loss: {} - Coeff: {}\".format(epoch, batch_num,\n # _loss, losses,\n # scale_coeff.item(\n # total_num_batch - batch_num - 1)))\n\n grad_updates += 1\n\n self.sess.run(self.train_op_rescaled, feed_dict={self.learning_rate: lr}) # apply gradient\n self.sess.run(self.zero_ops) # reset for next epoch\n\n # idxs = shuffle_rows(idxs)\n if not hide_progress:\n if holdout_ratio < 1e-12:\n if train_inputs.shape[0] > max_logging:\n train_inputs_loss = train_inputs[-max_logging:]\n train_targets_loss = train_targets[-max_logging:]\n else:\n train_inputs_loss = train_inputs\n train_targets_loss = train_targets\n\n train_inputs_loss = [train_inputs_loss for _ in range(self.num_nets)]\n train_targets_loss = [train_targets_loss for _ in range(self.num_nets)]\n\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: train_inputs_loss,\n self.sy_train_targ: train_targets_loss\n }\n )\n named_losses = [['M{}'.format(i), losses[i]] for i in range(len(losses))]\n progress.set_description(named_losses)\n else:\n if train_inputs.shape[0] > max_logging:\n train_inputs_loss = train_inputs[-max_logging:]\n train_targets_loss = train_targets[-max_logging:]\n else:\n train_inputs_loss = train_inputs\n train_targets_loss = train_targets\n\n train_inputs_loss = [train_inputs_loss for _ in range(self.num_nets)]\n train_targets_loss = [train_targets_loss for _ in range(self.num_nets)]\n\n losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: train_inputs_loss,\n self.sy_train_targ: train_targets_loss\n }\n )\n holdout_losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: holdout_inputs,\n self.sy_train_targ: holdout_targets\n }\n )\n named_losses = [['M{}'.format(i), losses[i]] for i in range(len(losses))]\n named_holdout_losses = [['V{}'.format(i), holdout_losses[i]] for i in\n range(len(holdout_losses))]\n named_losses = named_losses + named_holdout_losses + [['T', time.time() - t0]]\n progress.set_description(named_losses)\n\n break_train = self._save_best(epoch, holdout_losses)\n\n progress.update()\n t = time.time() - t0\n if break_train or (max_grad_updates and grad_updates > max_grad_updates):\n break\n if max_t and t > max_t:\n descr = 'Breaking because of timeout: {}! (max: {})'.format(t, max_t)\n progress.append_description(descr)\n # print('Breaking because of timeout: {}! | (max: {})\\n'.format(t, max_t))\n # time.sleep(5)\n break\n print(\"Trained with modified for {} epochs\".format(epoch+1))\n\n if holdout_ratio > 0:\n progress.stamp()\n if timer: timer.stamp('bnn_train')\n\n self._set_state()\n if timer: timer.stamp('bnn_set_state')\n\n holdout_losses = self.sess.run(\n self.mse_loss,\n feed_dict={\n self.sy_train_in: holdout_inputs,\n self.sy_train_targ: holdout_targets\n }\n )\n\n if timer: timer.stamp('bnn_holdout')\n\n self._end_train(holdout_losses)\n if timer: timer.stamp('bnn_end')\n\n val_loss = (np.sort(holdout_losses)[:self.num_elites]).mean()\n model_metrics = {'val_loss': val_loss}\n print('[ BNN ] Holdout', np.sort(holdout_losses), model_metrics)\n return OrderedDict(model_metrics)\n # return np.sort(holdout_losses)[]\n\n # pdb.set_trace()\n else:\n self._model_inds = [0, 1, 2, 3, 4]\n\n def predict(self, inputs, factored=False, *args, **kwargs):\n \"\"\"Returns the distribution predicted by the model for each input vector in inputs.\n Behavior is affected by the dimensionality of inputs and factored as follows:\n\n inputs is 2D, factored=True: Each row is treated as an input vector.\n Returns a mean of shape [ensemble_size, batch_size, output_dim] and variance of shape\n [ensemble_size, batch_size, output_dim], where N(mean[i, j, :], diag([i, j, :])) is the\n predicted output distribution by the ith model in the ensemble on input vector j.\n\n inputs is 2D, factored=False: Each row is treated as an input vector.\n Returns a mean of shape [batch_size, output_dim] and variance of shape\n [batch_size, output_dim], where aggregation is performed as described in the paper.\n\n inputs is 3D, factored=True/False: Each row in the last dimension is treated as an input vector.\n Returns a mean of shape [ensemble_size, batch_size, output_dim] and variance of sha\n [ensemble_size, batch_size, output_dim], where N(mean[i, j, :], diag([i, j, :])) is the\n predicted output distribution by the ith model in the ensemble on input vector [i, j].\n\n Arguments:\n inputs (np.ndarray): An array of input vectors in rows. See above for behavior.\n factored (bool): See above for behavior.\n \"\"\"\n if len(inputs.shape) == 2:\n if factored:\n return self.sess.run(\n [self.sy_pred_mean2d_fac, self.sy_pred_var2d_fac],\n feed_dict={self.sy_pred_in2d: inputs}\n )\n else:\n return self.sess.run(\n [self.sy_pred_mean2d, self.sy_pred_var2d],\n feed_dict={self.sy_pred_in2d: inputs}\n )\n else:\n return self.sess.run(\n [self.sy_pred_mean3d_fac, self.sy_pred_var3d_fac],\n feed_dict={self.sy_pred_in3d: inputs}\n )\n\n def create_prediction_tensors(self, inputs, factored=False, *args, **kwargs):\n \"\"\"See predict() above for documentation.\n \"\"\"\n factored_mean, factored_variance = self._compile_outputs(inputs)\n if inputs.shape.ndims == 2 and not factored:\n mean = tf.reduce_mean(factored_mean, axis=0)\n variance = tf.reduce_mean(tf.square(factored_mean - mean), axis=0) + \\\n tf.reduce_mean(factored_variance, axis=0)\n return mean, variance\n return factored_mean, factored_variance\n\n def save_weights(self):\n # Save network parameters (including scalers) in a .mat file\n var_vals = {}\n for i, var_val in enumerate(self.sess.run(self.nonoptvars + self.optvars)):\n var_vals[str(i)] = var_val\n savemat('weights/' + self.name + '.mat', var_vals)\n\n def load_weights(self):\n with self.sess.as_default():\n params_dict = loadmat('weights/' + self.name + '.mat')\n all_vars = self.nonoptvars + self.optvars\n for i, var in enumerate(all_vars):\n var.load(params_dict[str(i)])\n\n def save(self, savedir, timestep):\n \"\"\"Saves all information required to recreate this model in two files in savedir\n (or self.model_dir if savedir is None), one containing the model structuure and the other\n containing all variables in the network.\n\n savedir (str): (Optional) Path to which files will be saved. If not provided, self.model_dir\n (the directory provided at initialization) will be used.\n \"\"\"\n if not self.finalized:\n raise RuntimeError()\n model_dir = self.model_dir if savedir is None else savedir\n\n # Write structure to file\n with open(os.path.join(model_dir, '{}_{}.nns'.format(self.name, timestep)), \"w+\") as f:\n for layer in self.layers[:-1]:\n f.write(\"%s\\n\" % repr(layer))\n last_layer_copy = self.layers[-1].copy()\n last_layer_copy.set_activation(self.end_act_name)\n last_layer_copy.set_output_dim(last_layer_copy.get_output_dim() // 2)\n f.write(\"%s\\n\" % repr(last_layer_copy))\n\n # Save network parameters (including scalers) in a .mat file\n var_vals = {}\n for i, var_val in enumerate(self.sess.run(self.nonoptvars + self.optvars)):\n var_vals[str(i)] = var_val\n savemat(os.path.join(model_dir, '{}_{}.mat'.format(self.name, timestep)), var_vals)\n\n def _load_structure(self):\n \"\"\"Uses the saved structure in self.model_dir with the name of this network to initialize\n the structure of this network.\n \"\"\"\n structure = []\n with open(os.path.join(self.model_dir, \"%s.nns\" % self.name), \"r\") as f:\n for line in f:\n kwargs = {\n key: val for (key, val) in\n [argval.split(\"=\") for argval in line[3:-2].split(\", \")]\n }\n kwargs[\"input_dim\"] = int(kwargs[\"input_dim\"])\n kwargs[\"output_dim\"] = int(kwargs[\"output_dim\"])\n kwargs[\"weight_decay\"] = None if kwargs[\"weight_decay\"] == \"None\" else float(kwargs[\"weight_decay\"])\n kwargs[\"activation\"] = None if kwargs[\"activation\"] == \"None\" else kwargs[\"activation\"][1:-1]\n kwargs[\"ensemble_size\"] = int(kwargs[\"ensemble_size\"])\n structure.append(FC(**kwargs))\n self.layers = structure\n\n #######################\n # Compilation methods #\n #######################\n\n def _compile_outputs(self, inputs, ret_log_var=False):\n \"\"\"Compiles the output of the network at the given inputs.\n\n If inputs is 2D, returns a 3D tensor where output[i] is the output of the ith network in the ensemble.\n If inputs is 3D, returns a 3D tensor where output[i] is the output of the ith network on the ith input matrix.\n\n Arguments:\n inputs: (tf.Tensor) A tensor representing the inputs to the network\n ret_log_var: (bool) If True, returns the log variance instead of the variance.\n\n Returns: (tf.Tensors) The mean and variance/log variance predictions at inputs for each network\n in the ensemble.\n \"\"\"\n dim_output = self.layers[-1].get_output_dim()\n cur_out = self.scaler.transform(inputs)\n for layer in self.layers:\n cur_out = layer.compute_output_tensor(cur_out)\n\n mean = cur_out[:, :, :dim_output // 2]\n if self.end_act is not None:\n mean = self.end_act(mean)\n\n logvar = self.max_logvar - tf.nn.softplus(self.max_logvar - cur_out[:, :, dim_output // 2:])\n logvar = self.min_logvar + tf.nn.softplus(logvar - self.min_logvar)\n\n if ret_log_var:\n return mean, logvar\n else:\n return mean, tf.exp(logvar)\n\n def _compile_losses(self, inputs, targets, inc_var_loss=True):\n \"\"\"Helper method for compiling the loss function.\n\n The loss function is obtained from the log likelihood, assuming that the output\n distribution is Gaussian, with both mean and (diagonal) covariance matrix being determined\n by network outputs.\n\n Arguments:\n inputs: (tf.Tensor) A tensor representing the input batch\n targets: (tf.Tensor) The desired targets for each input vector in inputs.\n inc_var_loss: (bool) If True, includes log variance loss.\n\n Returns: (tf.Tensor) A tensor representing the loss on the input arguments.\n \"\"\"\n mean, log_var = self._compile_outputs(inputs, ret_log_var=True)\n inv_var = tf.exp(-log_var)\n\n if inc_var_loss:\n mse_losses = tf.reduce_mean(tf.reduce_mean(tf.square(mean - targets) * inv_var, axis=-1), axis=-1)\n var_losses = tf.reduce_mean(tf.reduce_mean(log_var, axis=-1), axis=-1)\n total_losses = mse_losses + var_losses\n else:\n total_losses = tf.reduce_mean(tf.reduce_mean(tf.square(mean - targets), axis=-1), axis=-1)\n\n return total_losses", "import os\nimport gym\nimport numpy as np\nimport pandas as pd\nimport random\nimport argparse\n\nimport tensorflow as tf\n\nfrom stable_baselines.common.policies import MlpPolicy\n#from stable_baselines.common.vec_env import DummyVecEnv\n#from stable_baselines.common.vec_env import VecNormalize\n#from stable_baselines.common.policies import register_policy\nfrom stable_baselines.sac.policies import FeedForwardPolicy\n\nfrom mbcd.mbcd import MBCD\nfrom mbcd.envs.non_stationary_wrapper import NonStationaryEnv\n\nfrom mbcd.utils.util import evaluate\nfrom mbcd.sac_mbcd import SAC\n\nfrom experiments.experiments_enum import ExpType\n\n\nclass CustomSACPolicy(FeedForwardPolicy):\n def __init__(self, *args, **kwargs):\n super(CustomSACPolicy, self).__init__(*args, **kwargs, layers=[256, 256], feature_extraction=\"mlp\") # 64,64\n# register_policy('CustomSACPolicy', CustomSACPolicy)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-seed', dest='seed', required=False, type=int, help=\"Seed\\n\", default=0) \nparser.add_argument('-algo', dest='algo', required=True, type=str, help=\"Algo [mbcd, mbpo, sac]\\n\")\nparser.add_argument('-env', dest='env', required=False, type=str, help=\"Env [halfcheetah, pusher]\", default='halfcheetah')\nparser.add_argument('-load', dest='load', required=False, type=bool, help=\"Load pre-trained [True, False]\", default=False)\nparser.add_argument('-gif', dest='gif', required=False, type=bool, help=\"Save gifs [True, False]\", default=False)\nparser.add_argument('-roll', dest='roll', required=False, type=str, help=\"Rollout type [mbcd, m2ac]\\n\", default='mbcd')\nargs = parser.parse_args()\nassert args.algo in ['mbcd', 'mbpo', 'sac']\nassert args.roll in ['mbcd', 'm2ac']\nmbcd = args.algo == 'mbcd'\nmbpo = args.algo != 'sac'\n\nSEED = args.seed\nos.environ['PYTHONHASHSEED'] = str(SEED)\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntf.set_random_seed(SEED)\n\n\ndef main(config):\n sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\n model = SAC(CustomSACPolicy,\n env=config['env'],\n rollout_schedule=config['rollout_schedule'],\n verbose=1,\n batch_size=config['batch_size'],\n gradient_steps=config['gradient_steps'],\n target_entropy='auto',\n ent_coef='auto',\n mbpo=mbpo,\n mbcd=mbcd,\n max_std=config['max_std'],\n num_stds=config['num_stds'],\n n_hidden_units_dynamics=config['n_hidden_units_dynamics'],\n n_layers_dynamics=config['n_layers_dynamics'],\n dynamics_memory_size=config['dynamics_memory_size'],\n cusum_threshold=config['cusum_threshold'],\n run_id=config['run_id'],\n tensorboard_log='./logs/',\n seed=SEED,\n load_pre_trained_model=args.load,\n save_gifs=args.gif,\n rollout_mode=args.roll)\n\n tb_log_name = 'mbcd-test-' + args.roll\n model.learn(total_timesteps=config['total_timesteps'], tb_log_name=tb_log_name)\n if args.algo == 'sac':\n model.save('weights/'+'sacfinalpolicy')\n else:\n model.deepMBCD.save_current()\n model.deepMBCD.save_models()\n\n\nif __name__ == '__main__':\n\n if args.env == 'halfcheetah':\n tasks = ExpType.Normal\n change_freq = tasks.value[\"change_freq\"]\n if isinstance(change_freq, list):\n total_timesteps = sum(tasks.value[\"change_freq\"])\n else:\n total_timesteps = change_freq * len(tasks.value[\"tasks\"])\n\n if args.roll == 'm2ac':\n rollout_schedule = [5000, 20000, 1, 8]\n else:\n rollout_schedule = [5000, 10000, 1, 1]\n config = {\n 'env': NonStationaryEnv(gym.envs.make('HalfCheetah-v2'), tasks=tasks),\n 'rollout_schedule': rollout_schedule,\n 'batch_size': 256,\n 'gradient_steps': 20,\n 'target_entropy': 'auto',\n 'ent_coef': 'auto',\n 'max_std': 0.5,\n 'num_stds': 2.0, \n 'n_hidden_units_dynamics': 200,\n 'n_layers_dynamics': 4,\n 'dynamics_memory_size': 100000,\n 'cusum_threshold': 100,\n 'run_id':'{}-halfcheetah-ns-paper{}'.format(args.algo, str(SEED)),\n 'total_timesteps': total_timesteps\n }\n\n\n main(config)\n\n\n\n \n\n\n" ]
[ [ "numpy.split", "numpy.linspace", "tensorflow.reduce_sum", "sklearn.preprocessing.PolynomialFeatures", "tensorflow.add_n", "numpy.random.randint", "numpy.arange", "numpy.matmul", "scipy.io.loadmat", "tensorflow.ConfigProto", "numpy.ceil", "tensorflow.Session", "tensorflow.square", "tensorflow.trainable_variables", "numpy.repeat", "tensorflow.nn.softplus", "numpy.random.choice", "numpy.power", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.global_variables_initializer", "numpy.delete", "tensorflow.zeros_like", "numpy.floor", "scipy.io.savemat", "numpy.argsort", "numpy.array", "numpy.sum", "tensorflow.reduce_mean", "numpy.set_printoptions", "numpy.tile", "numpy.sort", "numpy.ones", "numpy.random.shuffle", "numpy.random.permutation", "tensorflow.variable_scope", "numpy.random.uniform", "numpy.empty" ], [ "tensorflow.set_random_seed", "tensorflow.ConfigProto", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LucienZuber/AlgoTrader
[ "cc6088a525ed6311c9a6969880c739b91bdebf5c" ]
[ "indicators/support_resistance.py" ]
[ "import pandas as pd\nimport datetime\n\ndef detect_support_resistances(df: pd.DataFrame, initial_state: int = 20, precision: int = 3, expiration_time: datetime.timedelta = datetime.timedelta(days=7)):\n initial_min = df['Close'].iloc[:initial_state].idxmin()\n initial_max = df['Close'].iloc[:initial_state].idxmax()\n\n supports=pd.DataFrame({'Support': df['Close'].loc[initial_min]}, index=[initial_min])\n resistances=pd.DataFrame({'Resistance': df['Close'].loc[initial_max]}, index=[initial_max])\n\n expiration_support = initial_min + expiration_time\n expiration_resistance = initial_max + expiration_time\n\n for (index, close_price) in enumerate(df['Close'].iloc[initial_state:], initial_state):\n index_datetime = df.index[index]\n latest_min_index = df['Close'].iloc[index-precision:index].idxmin()\n latest_min_value = df['Close'].iloc[index-precision:index].min()\n latest_max_index = df['Close'].iloc[index-precision:index].idxmax()\n latest_max_value = df['Close'].iloc[index-precision:index].max()\n if (expiration_support <= index_datetime):\n supports.loc[latest_min_index] = latest_min_value\n expiration_support = latest_min_index + expiration_time\n\n elif (expiration_resistance <= index_datetime):\n resistances.loc[latest_max_index] =latest_max_value\n expiration_resistance = latest_min_index + expiration_time\n\n elif (latest_max_value < supports['Support'].iloc[-1]):\n supports.loc[latest_min_index] = latest_min_value\n expiration_support = latest_min_index + expiration_time\n\n elif (latest_min_value > resistances['Resistance'].iloc[-1]):\n resistances.loc[latest_max_index] = latest_max_value\n expiration_resistance = latest_min_index + expiration_time\n\n supports = supports.reindex(df.index.values)\n resistances = resistances.reindex(df.index.values)\n\n result = supports.join(resistances)\n\n return result" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
JAckleyLSNYC/GitPython
[ "93fa78346e85ec6b8d00c5b362d6b498598a0444", "93fa78346e85ec6b8d00c5b362d6b498598a0444" ]
[ "hyperlinker/app/Historical Backup Scripts/TRCExternalPrep.py", "hyperlinker/app/Historical Backup Scripts/IOIimmQuarterly.py" ]
[ "from flask import request, send_from_directory\r\nfrom app import app, DataWizardTools, HousingToolBox\r\nimport pandas as pd\r\n\r\[email protected](\"/TRCExternalPrep\", methods=['GET', 'POST'])\r\ndef TRCExternalPrep():\r\n #upload file from computer via browser\r\n if request.method == 'POST':\r\n print(request.files['file'])\r\n f = request.files['file']\r\n \r\n #turn the excel file into a dataframe, but skip the top 2 rows if they are blank\r\n test = pd.read_excel(f)\r\n test.fillna('',inplace=True)\r\n if test.iloc[0][0] == '':\r\n df = pd.read_excel(f,skiprows=2)\r\n else:\r\n df = pd.read_excel(f)\r\n \r\n #Remove Rows without Case ID values\r\n df.fillna('',inplace = True)\r\n df['Matter/Case ID#'] = df.apply(lambda x : DataWizardTools.RemoveNoCaseID(x['Matter/Case ID#']),axis=1) \r\n df = df[df['Matter/Case ID#'] != 'No Case ID']\r\n \r\n #Create Hyperlinks\r\n df['Hyperlinked CaseID#'] = df.apply(lambda x : DataWizardTools.Hyperlinker(x['Matter/Case ID#']),axis=1) \r\n\r\n ###This is where all the functions happen:###\r\n \r\n #Just direct mapping for new column names\r\n df['first_name'] = df['Client First Name']\r\n df['last_name'] = df['Client Last Name']\r\n df['SSN'] = df['Social Security #']\r\n df['PA_number'] = df['Gen Pub Assist Case Number']\r\n df['DOB'] = df['Date of Birth']\r\n df['num_adults'] = df['Number of People 18 and Over']\r\n df['num_children'] = df['Number of People under 18']\r\n df['Unit'] = df['Apt#/Suite#']\r\n \r\n df['zip'] = df['Zip Code']\r\n df['waiver_approval_date'] = df['Housing Date Of Waiver Approval']\r\n df['waiver'] = df['Housing TRC HRA Waiver Categories']\r\n df['rent'] = df['Housing Total Monthly Rent']\r\n df['LT_index'] = df['Gen Case Index Number']\r\n df['language'] = df['Language']\r\n df['income'] = df['Total Annual Income ']\r\n df['eligibility_date'] = df['HAL Eligibility Date']\r\n df['DHCI'] = df['Housing Signed DHCI Form']\r\n df['units_in_bldg'] = df['Housing Number Of Units In Building']\r\n df['outcome_date'] = df['Housing Outcome Date']\r\n \r\n #Append the 'LSNYC' prefix to the caseIDs we submit\r\n df['id'] = 'LSNYC' + df['Matter/Case ID#']\r\n \r\n #Turn our funding codes into HRA Program Names\r\n #*for trc (3018 and 3011) everything is AHTP - more complicated for UA etc.\r\n df['program_name'] = 'AHTP'\r\n \r\n #Separate out street number from street name (based on first space)\r\n df['street_number'] = df['Street Address'].str.split(' ').str[0]\r\n df['Street'] = df['Street Address'].str.split(' ',1).str[1]\r\n \r\n #If it is a case in Queens it will have neighborhood - change it to say Queens\r\n df['city'] = df.apply(lambda x: DataWizardTools.QueensConsolidater(x['City']), axis=1)\r\n \r\n #Translation based on HRA Specs \r\n df['proceeding'] = df.apply(lambda x: HousingToolBox.ProceedingType(x['Housing Type Of Case']), axis=1)\r\n\r\n #if it's a multi-tenant/group case? change it from saying Yes/no to say \"no = individual\" or 'yes = Group'\r\n #Also, if it's an eviction case, it's individual, otherwise make it \"needs review\"\r\n \r\n def ProceedingLevel(GroupCase,TypeOfCase,EvictionProceedings):\r\n if GroupCase == \"Yes\":\r\n return \"Group\"\r\n elif GroupCase == \"No\":\r\n return \"Individual\"\r\n elif TypeOfCase in EvictionProceedings:\r\n return \"Individual\"\r\n else:\r\n return \"Needs Review\"\r\n df['proceeding_level'] = df.apply(lambda x: ProceedingLevel(x['Housing Building Case?'], x['proceeding'], HousingToolBox.evictionproceedings), axis=1)\r\n \r\n #For years in apartment, negative 1 or less = 0.5\r\n df['years_in_apt'] = df['Housing Years Living In Apartment'].apply(lambda x: .5 if x <= -1 else x)\r\n \r\n \r\n #Case posture on eligibility date (on trial, no stipulation etc.) - transform them into the HRA initials\r\n df['posture'] = df.apply(lambda x: HousingToolBox.PostureOnEligibility(x['Housing Posture of Case on Eligibility Date']), axis=1)\r\n \r\n \r\n #Level of Service becomes Service type \r\n df['service_type'] = df.apply(lambda x: HousingToolBox.TRCServiceType(x['Housing Level of Service']), axis=1)\r\n \r\n #if below 201, = 'Yes' otherwise 'No'\r\n df['below_200_FPL'] = df['Percentage of Poverty'].apply(lambda x: \"Yes\" if x < 200 else \"No\")\r\n \r\n #Subsidy type - if it's not in the HRA list, it has to be 'none' (other is not valid) - they want a smaller list than we record. (mapping to be confirmed)\r\n \r\n df['subsidy_type'] = df.apply(lambda x: HousingToolBox.SubsidyType(x['Housing Subsidy Type']), axis=1)\r\n \r\n \r\n #Housing Regulation Type: mapping down - we have way more categories, rent regulated, market rate, or other (mapping to be confirmed). can't be blank\r\n\r\n df['housing_type'] = df.apply(lambda x: HousingToolBox.HousingType(x['Housing Form Of Regulation']), axis=1)\r\n\r\n #Referrals need to be one of their specific categories\r\n \r\n df['referral_source'] = df.apply(lambda x: HousingToolBox.ReferralMap(x['Referral Source']), axis = 1)\r\n \r\n #Housing Outcomes needs mapping for HRA\r\n df['outcome'] = df.apply(lambda x: HousingToolBox.Outcome(x['Housing Outcome']), axis=1)\r\n \r\n #Outcome related things that need mapping \r\n df['services_rendered'] = df.apply(lambda x: HousingToolBox.ServicesRendered(x['Housing Services Rendered to Client']), axis=1)\r\n\r\n #Mapped to what HRA wants - some of the options are in LegalServer,\r\n\r\n df['activities'] = df.apply(lambda x: HousingToolBox.Activities(x['Housing Activity Indicators']), axis=1)\r\n \r\n \r\n #Differentiate pre- and post- 3/1/20 eligibility date cases\r\n \r\n df['DateConstruct'] = df.apply(lambda x: DataWizardTools.DateMaker(x['HAL Eligibility Date']), axis=1)\r\n \r\n df['Pre-3/1/20 Elig Date?'] = df.apply(lambda x: HousingToolBox.PreThreeOne(x['DateConstruct']), axis=1)\r\n \r\n \r\n\r\n ###Finalizing Report###\r\n #put columns in correct order\r\n \r\n df = df[['id',\r\n 'program_name',\r\n 'first_name',\r\n 'last_name',\r\n 'SSN',\r\n 'PA_number',\r\n 'DOB',\r\n 'num_adults',\r\n 'num_children',\r\n 'street_number',\r\n 'Street',\r\n 'Unit',\r\n 'city',\r\n 'zip',\r\n 'waiver_approval_date',\r\n 'waiver',\r\n 'rent',\r\n 'proceeding',\r\n 'LT_index',\r\n 'proceeding_level',\r\n 'years_in_apt',\r\n 'language',\r\n 'referral_source',\r\n 'income',\r\n 'eligibility_date',\r\n 'DHCI',\r\n 'posture',\r\n 'service_type',\r\n 'below_200_FPL',\r\n 'units_in_bldg',\r\n 'subsidy_type',\r\n 'housing_type',\r\n 'outcome_date',\r\n 'outcome',\r\n 'services_rendered',\r\n 'activities',\r\n 'HRA Release?',\r\n 'Percentage of Poverty',\r\n 'Primary Advocate',\r\n 'Hyperlinked CaseID#',\r\n 'Pre-3/1/20 Elig Date?'\r\n ]]\r\n \r\n #bounce worksheets back to excel\r\n output_filename = f.filename \r\n writer = pd.ExcelWriter(\"app\\\\sheets\\\\\"+output_filename, engine = 'xlsxwriter')\r\n df.to_excel(writer, sheet_name='Sheet1',index=False)\r\n workbook = writer.book\r\n worksheet = writer.sheets['Sheet1']\r\n \r\n #highlight yellow if needs review\r\n #make columns wider\r\n #give the hyperlink format\r\n link_format = workbook.add_format({'font_color':'blue', 'bold':True, 'underline':True})\r\n problem_format = workbook.add_format({'bg_color':'yellow'})\r\n worksheet.freeze_panes(1,0)\r\n worksheet.set_column('A:BL',20)\r\n worksheet.set_column ('AN:AN',30,link_format)\r\n worksheet.conditional_format('C2:BO100000',{'type': 'text',\r\n 'criteria': 'containing',\r\n 'value': 'Needs',\r\n 'format': problem_format})\r\n \r\n writer.save()\r\n \r\n #send file back to user\r\n return send_from_directory('sheets',output_filename, as_attachment = True, attachment_filename = \"Formatted \" + f.filename)\r\n \r\n#what the user-facing site looks like\r\n return '''\r\n <!doctype html>\r\n <title>TRC Report Prep</title>\r\n <link rel=\"stylesheet\" href=\"/static/css/main.css\"> \r\n <link rel=\"stylesheet\" href=\"/static/css/main.css\"> \r\n <h1>Prep Cases for TRC External Report:</h1>\r\n <form action=\"\" method=post enctype=multipart/form-data>\r\n <p><input type=file name=file><input type=submit value=TRC-ify!>\r\n </form>\r\n <h3>Instructions:</h3>\r\n <ul type=\"disc\">\r\n <li>This tool is meant to be used in conjunction with the LegalServer report called <a href=\"https://lsnyc.legalserver.org/report/dynamic?load=1969\" target=\"_blank\">TRC External Report</a>.</li>\r\n \r\n </ul>\r\n </br>\r\n <a href=\"/\">Home</a>\r\n '''\r\n \r\n", "from flask import render_template, flash, redirect, url_for, request, Flask, jsonify, send_from_directory\r\nfrom app import app, db, ImmigrationToolBox, DataWizardTools\r\nfrom app.models import User, Post\r\nfrom app.forms import PostForm\r\nfrom werkzeug.urls import url_parse\r\nfrom datetime import datetime\r\nimport pandas as pd\r\n\r\n\r\[email protected](\"/IOIimmQuarterly\", methods=['GET', 'POST'])\r\ndef upload_IOIimmQuarterly():\r\n if request.method == 'POST':\r\n print(request.files['file'])\r\n f = request.files['file']\r\n \r\n test = pd.read_excel(f)\r\n \r\n test.fillna('',inplace=True)\r\n \r\n \r\n #Cleaning\r\n if test.iloc[0][0] == '':\r\n df = pd.read_excel(f,skiprows=2)\r\n else:\r\n df = pd.read_excel(f)\r\n \r\n df.fillna('',inplace=True)\r\n #Create Hyperlinks\r\n df['Hyperlinked Case #'] = df.apply(lambda x : DataWizardTools.Hyperlinker(x['Matter/Case ID#']),axis=1)\r\n \r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Bronx Legal Services','BxLS')\r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Brooklyn Legal Services','BkLS')\r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Queens Legal Services','QLS')\r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Manhattan Legal Services','MLS')\r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Staten Island Legal Services','SILS')\r\n df['Assigned Branch/CC'] = df['Assigned Branch/CC'].str.replace('Legal Support Unit','LSU')\r\n \r\n \r\n \r\n #Determining 'level of service' from 3 fields \r\n \r\n df['HRA Level of Service'] = df.apply(lambda x: ImmigrationToolBox.HRA_Level_Service(x['Close Reason'],x['Level of Service']), axis=1)\r\n \r\n \r\n \r\n #HRA Case Coding\r\n #Putting Cases into HRA's Baskets! \r\n df['HRA Case Coding'] = df.apply(lambda x: ImmigrationToolBox.HRA_Case_Coding(x['Legal Problem Code'],x['Special Legal Problem Code'],x['HRA Level of Service'],x['IOI Does Client Have A Criminal History? (IOI 2)']), axis=1)\r\n\r\n #Dummy SLPC for Juvenile Cases\r\n def DummySLPC(LPC,SLPC):\r\n LPC = str(LPC)\r\n SLPC = str(SLPC)\r\n if LPC == \"44 Minor Guardianship / Conservatorship\" or LPC == \"42 Neglected/Abused/Dependent\":\r\n return 'N/A'\r\n else:\r\n return SLPC\r\n \r\n df['Special Legal Problem Code'] = df.apply(lambda x: DummySLPC(x['Legal Problem Code'],x['Special Legal Problem Code']), axis=1)\r\n \r\n df['HRA Service Type'] = df['HRA Case Coding'].apply(lambda x: x[:2] if x != 'Hold For Review' else '')\r\n\r\n df['HRA Proceeding Type'] = df['HRA Case Coding'].apply(lambda x: x[3:] if x != 'Hold For Review' else '')\r\n \r\n #Giving things better names in cleanup sheet\r\n \r\n df['DHCI form?'] = df['Has Declaration of Household Composition and Income (DHCI) Form?']\r\n \r\n df['Consent form?'] = df['IOI HRA Consent Form? (IOI 2)']\r\n \r\n df['Client Name'] = df['Full Person/Group Name (Last First)']\r\n \r\n df['Office'] = df['Assigned Branch/CC']\r\n \r\n df['Country of Origin'] = df['IOI Country Of Origin (IOI 1 and 2)']\r\n \r\n df['Substantial Activity'] = df['IOI Substantial Activity (Choose One)']\r\n \r\n df['Date of Substantial Activity'] = df['Custom IOI Date substantial Activity Performed']\r\n \r\n #Income Waiver\r\n \r\n def Income_Exclude(IncomePct,Waiver,Referral): \r\n IncomePct = int(IncomePct)\r\n Waiver = str(Waiver)\r\n if Referral == 'Action NY':\r\n return ''\r\n elif IncomePct > 200 and Waiver.startswith('2') == False:\r\n return 'Needs Income Waiver'\r\n else:\r\n return ''\r\n\r\n df['Exclude due to Income?'] = df.apply(lambda x: Income_Exclude(x['Percentage of Poverty'],x['IOI HRA WAIVER APPROVAL DATE if over 200% of FPL (IOI 2)'],x['IOI Referral Source (IOI 2)']), axis=1)\r\n \r\n #Eligibility_Date & Rollovers \r\n \r\n def Eligibility_Date(Effective_Date,Date_Opened):\r\n if Effective_Date != '':\r\n return Effective_Date\r\n else:\r\n return Date_Opened\r\n df['Eligibility_Date'] = df.apply(lambda x : Eligibility_Date(x['IOI HRA Effective Date (optional) (IOI 2)'],x['Date Opened']), axis = 1)\r\n \r\n #Manipulable Dates \r\n \r\n df['Open Month'] = df['Eligibility_Date'].apply(lambda x: str(x)[:2])\r\n df['Open Day'] = df['Eligibility_Date'].apply(lambda x: str(x)[3:5])\r\n df['Open Year'] = df['Eligibility_Date'].apply(lambda x: str(x)[6:])\r\n df['Open Construct'] = df['Open Year'] + df['Open Month'] + df['Open Day']\r\n \r\n df['Subs Month'] = df['Date of Substantial Activity'].apply(lambda x: str(x)[:2])\r\n df['Subs Day'] = df['Date of Substantial Activity'].apply(lambda x: str(x)[3:5])\r\n df['Subs Year'] = df['Date of Substantial Activity'].apply(lambda x: str(x)[6:])\r\n df['Subs Construct'] = df['Subs Year'] + df['Subs Month'] + df['Subs Day']\r\n df['Subs Construct'] = df.apply(lambda x : x['Subs Construct'] if x['Subs Construct'] != '' else 0, axis = 1)\r\n \r\n df['Outcome1 Month'] = df['IOI Outcome 2 Date (IOI 2)'].apply(lambda x: str(x)[:2])\r\n df['Outcome1 Day'] = df['IOI Outcome 2 Date (IOI 2)'].apply(lambda x: str(x)[3:5])\r\n df['Outcome1 Year'] = df['IOI Outcome 2 Date (IOI 2)'].apply(lambda x: str(x)[6:])\r\n df['Outcome1 Construct'] = df['Outcome1 Year'] + df['Outcome1 Month'] + df['Outcome1 Day']\r\n\r\n df['Outcome2 Month'] = df['IOI Secondary Outcome Date 2 (IOI 2)'].apply(lambda x: str(x)[:2])\r\n df['Outcome2 Day'] = df['IOI Secondary Outcome Date 2 (IOI 2)'].apply(lambda x: str(x)[3:5])\r\n df['Outcome2 Year'] = df['IOI Secondary Outcome Date 2 (IOI 2)'].apply(lambda x: str(x)[6:])\r\n df['Outcome2 Construct'] = df['Outcome2 Year'] + df['Outcome2 Month'] + df['Outcome2 Day'] \r\n \r\n \r\n #DHCI Form\r\n \r\n def DHCI_Needed(DHCI,Open_Construct,LoS):\r\n if Open_Construct == '':\r\n return ''\r\n elif LoS.startswith('Advice'):\r\n return ''\r\n elif LoS.startswith('Brief'):\r\n return ''\r\n elif int(Open_Construct) < 20180701:\r\n return ''\r\n elif DHCI != 'Yes':\r\n return 'Needs DHCI Form'\r\n else:\r\n return ''\r\n \r\n df['Needs DHCI?'] = df.apply(lambda x: DHCI_Needed(x['Has Declaration of Household Composition and Income (DHCI) Form?'],x['Open Construct'],x['Level of Service']), axis=1)\r\n \r\n \r\n #Needs Substantial Activity to Rollover into FY'20\r\n \r\n def Needs_Rollover(Open_Construct,Substantial_Activity,Substantial_Activity_Date,CaseID,ReportedFY19):\r\n if int(Open_Construct) >= 20190701:\r\n return ''\r\n elif Substantial_Activity != '' and int(Substantial_Activity_Date) >= 20190701 and int(Substantial_Activity_Date) <= 20200630:\r\n return ''\r\n elif CaseID in ReportedFY19:\r\n return 'Needs Substantial Activity in FY20'\r\n else:\r\n return ''\r\n \r\n df['Needs Substantial Activity?'] = df.apply(lambda x: Needs_Rollover(x['Open Construct'],x['Substantial Activity'],x['Subs Construct'],x['Matter/Case ID#'], ImmigrationToolBox.ReportedFY19), axis=1)\r\n\r\n\r\n #Outcomes\r\n \r\n \r\n #if there are two outcomes choose which outcome to report based on which one happened more recently \r\n \r\n def OutcomeToReport (Outcome1,OutcomeDate1,Outcome2,OutcomeDate2,ServiceLevel,CloseDate):\r\n if OutcomeDate1 == '' and OutcomeDate2 == '' and CloseDate != '' and ServiceLevel == 'Advice':\r\n return 'Advice given'\r\n elif OutcomeDate1 == '' and OutcomeDate2 == '' and CloseDate != '' and ServiceLevel == 'Brief Service':\r\n return 'Advice given'\r\n elif CloseDate != '' and ServiceLevel == 'Full Rep or Extensive Service' and Outcome1 == '' and Outcome2 == '':\r\n return '*Needs Outcome*'\r\n elif OutcomeDate1 >= OutcomeDate2:\r\n return Outcome1\r\n elif OutcomeDate2 > OutcomeDate1:\r\n return Outcome2\r\n else:\r\n return 'no actual outcome'\r\n \r\n df['Outcome To Report'] = df.apply(lambda x: OutcomeToReport(x['IOI Outcome 2 (IOI 2)'],x['Outcome1 Construct'],x['IOI Secondary Outcome 2 (IOI 2)'],x['Outcome2 Construct'],x['HRA Level of Service'],x['Date Closed']), axis=1)\r\n \r\n #make it add the outcome date as well (or tell you if you need it!) \r\n\r\n def OutcomeDateToReport (Outcome1,OutcomeDate1,Outcome2,OutcomeDate2,ServiceLevel,CloseDate,ActualOutcomeDate1,ActualOutcomeDate2):\r\n if OutcomeDate1 == '' and OutcomeDate2 == '' and CloseDate != '' and ServiceLevel == 'Advice':\r\n return CloseDate\r\n elif OutcomeDate1 == '' and OutcomeDate2 == '' and CloseDate != '' and ServiceLevel == 'Brief Service':\r\n return CloseDate \r\n elif OutcomeDate1 >= OutcomeDate2:\r\n return ActualOutcomeDate1\r\n elif OutcomeDate2 > OutcomeDate1:\r\n return ActualOutcomeDate2\r\n else:\r\n return '*Needs Outcome Date*'\r\n \r\n \r\n df['Outcome Date To Report'] = df.apply(lambda x: OutcomeDateToReport(x['IOI Outcome 2 (IOI 2)'],x['Outcome1 Construct'],x['IOI Secondary Outcome 2 (IOI 2)'],x['Outcome2 Construct'],x['HRA Level of Service'],x['Date Closed'],x['IOI Outcome 2 Date (IOI 2)'],x['IOI Secondary Outcome Date 2 (IOI 2)']), axis=1)\r\n \r\n\r\n #kind of glitchy - if it has an outcome date but no outcome it doesn't say *Needs Outcome*\r\n \r\n #add LSNYC to start of case numbers \r\n \r\n df['Unique_ID'] = 'LSNYC'+df['Matter/Case ID#']\r\n \r\n #take second letters of first and last names\r\n \r\n df['Last_Initial'] = df['Client Last Name'].str[1]\r\n df['First_Initial'] = df['Client First Name'].str[1]\r\n\r\n #Year of birth\r\n df['Year_of_Birth'] = df['Date of Birth'].str[-4:]\r\n \r\n #Unique Client ID#\r\n df['Unique Client ID#'] = df['First_Initial'] + df['Last_Initial'] + df['Year_of_Birth'] \r\n \r\n #Deliverable Categories\r\n \r\n def Deliverable_Category(HRA_Coded_Case,Income_Cleanup,Age_at_Intake):\r\n if Income_Cleanup == 'Needs Income Waiver':\r\n return 'Needs Cleanup'\r\n elif HRA_Coded_Case == 'T2-RD' and Age_at_Intake <= 21:\r\n return 'Tier 2 (minor removal)'\r\n elif HRA_Coded_Case == 'T2-RD':\r\n return 'Tier 2 (removal)'\r\n elif HRA_Coded_Case.startswith('T2') == True:\r\n return 'Tier 2 (other)'\r\n elif HRA_Coded_Case.startswith('T1')== True:\r\n return 'Tier 1'\r\n elif HRA_Coded_Case.startswith('B') == True:\r\n return 'Brief'\r\n else:\r\n return 'Needs Cleanup'\r\n\r\n df['Deliverable Tally'] = df.apply(lambda x: Deliverable_Category(x['HRA Case Coding'],x['Exclude due to Income?'],x['Age at Intake']), axis=1)\r\n \r\n #make all cases for any client that has a minor removal tally, into also being minor removal cases\r\n \r\n \r\n \r\n \r\n dfs = df.groupby('Unique Client ID#',sort = False)\r\n\r\n tdf = pd.DataFrame()\r\n for x, y in dfs:\r\n for z in y['Deliverable Tally']:\r\n if z == 'Tier 2 (minor removal)':\r\n y['Modified Deliverable Tally'] = 'Tier 2 (minor removal)'\r\n tdf = tdf.append(y)\r\n df = tdf\r\n \r\n \r\n #write function to identify blank 'modified deliverable tallies' and add it back in as the original deliverable tally\r\n df.fillna('',inplace= True)\r\n\r\n def fillBlanks(ModifiedTally,Tally):\r\n if ModifiedTally == '':\r\n return Tally\r\n else:\r\n return ModifiedTally\r\n df['Modified Deliverable Tally'] = df.apply(lambda x: fillBlanks(x['Modified Deliverable Tally'],x['Deliverable Tally']),axis=1)\r\n\r\n \r\n \r\n #***add code to make it so that it deletes any extra 'brief' cases for clients that have mutliple cases\r\n \r\n \r\n \r\n \r\n \r\n #gender\r\n def HRAGender (gender):\r\n if gender == 'Male' or gender == 'Female':\r\n return gender\r\n else:\r\n return 'Other'\r\n df['Gender'] = df.apply(lambda x: HRAGender(x['Gender']), axis=1)\r\n \r\n #county=borough\r\n df['Borough'] = df['County of Residence']\r\n \r\n #household size etc.\r\n df['Household_Size'] = df['Number of People under 18'].astype(int) + df['Number of People 18 and Over'].astype(int)\r\n df['Number_of_Children'] = df['Number of People under 18']\r\n \r\n #Income Eligible?\r\n df['Annual_Income'] = df['Total Annual Income ']\r\n def HRAIncElig (PercentOfPoverty):\r\n if PercentOfPoverty > 200:\r\n return 'NO'\r\n else:\r\n return 'YES'\r\n df['Income_Eligible'] = df.apply(lambda x: HRAIncElig(x['Percentage of Poverty']), axis=1)\r\n \r\n def IncWaiver (eligible,waiverdate):\r\n if eligible == 'NO' and waiverdate != '':\r\n return 'Income'\r\n else:\r\n return ''\r\n df['Waiver_Type'] = df.apply(lambda x: IncWaiver(x['Income_Eligible'],x['IOI HRA WAIVER APPROVAL DATE if over 200% of FPL (IOI 2)']), axis=1)\r\n \r\n def IncWaiverDate (waivertype,date):\r\n if waivertype != '':\r\n return date\r\n else: \r\n return ''\r\n \r\n df['Waiver_Approval_Date'] = df.apply(lambda x: IncWaiverDate(x['Waiver_Type'],x['IOI HRA WAIVER APPROVAL DATE if over 200% of FPL (IOI 2)']), axis = 1)\r\n \r\n #Referrals\r\n def Referral (referral):\r\n if referral == \"Action NY\":\r\n return \"ActionNYC\"\r\n elif referral == \"HRA\":\r\n return \"HRA-DSS\"\r\n elif referral == \"Other\":\r\n return \"Other\"\r\n elif referral == \"\":\r\n return \"None\"\r\n else:\r\n return \"\"\r\n \r\n df['Referral_Source'] = df.apply(lambda x: Referral(x['IOI Referral Source (IOI 2)']), axis = 1)\r\n \r\n #Pro Bono Involvement\r\n def ProBonoCase (branch, pai):\r\n if branch == \"LSU\" or pai == \"Yes\":\r\n return \"YES\"\r\n else:\r\n return \"NO\"\r\n \r\n df['Pro_Bono'] = df.apply(lambda x:ProBonoCase(x['Assigned Branch/CC'], x['PAI Case?']), axis = 1)\r\n \r\n #Prior Enrollment\r\n \r\n def PriorEnrollment (casenumber):\r\n if casenumber in ImmigrationToolBox.ReportedFY19:\r\n return 'FY 19'\r\n \r\n df['Prior_Enrollment_FY'] = df.apply(lambda x:PriorEnrollment(x['Matter/Case ID#']), axis = 1)\r\n \r\n #Other Cleanup\r\n df['Service_Type_Code'] = df['HRA Service Type']\r\n df['Proceeding_Type_Code'] = df['HRA Proceeding Type']\r\n df['Outcome'] = df['Outcome To Report']\r\n df['Outcome_Date'] = df['Outcome Date To Report']\r\n df['Seized_at_Border'] = df['IOI Was client apprehended at border? (IOI 2&3)']\r\n df['Group'] = ''\r\n \r\n \r\n \r\n #REPORTING VERSION Put everything in the right order\r\n df = df[['Unique_ID','Last_Initial','First_Initial','Year_of_Birth','Gender','Country of Origin','Borough','Zip Code','Language','Household_Size','Number_of_Children','Annual_Income','Income_Eligible','Waiver_Type','Waiver_Approval_Date','Eligibility_Date','Referral_Source','Service_Type_Code','Proceeding_Type_Code','Outcome','Outcome_Date','Seized_at_Border','Group','Prior_Enrollment_FY','Pro_Bono','Special Legal Problem Code','HRA Level of Service','HRA Case Coding','Hyperlinked Case #','Office','Primary Advocate','Client Name','Special Legal Problem Code','Level of Service','Needs DHCI?','Exclude due to Income?','Needs Substantial Activity?','Country of Origin','Outcome To Report','HRA Case Coding','IOI Was client apprehended at border? (IOI 2&3)','Deliverable Tally','Modified Deliverable Tally']]\r\n \r\n \r\n \r\n \r\n #Preparing Excel Document\r\n \r\n output_filename = f.filename \r\n writer = pd.ExcelWriter(\"app\\\\sheets\\\\\"+output_filename, engine = 'xlsxwriter')\r\n df.to_excel(writer, sheet_name='Sheet1',index=False)\r\n\r\n workbook = writer.book\r\n worksheet = writer.sheets['Sheet1']\r\n\r\n link_format = workbook.add_format({'font_color':'blue', 'bold':True, 'underline':True})\r\n problem_format = workbook.add_format({'bg_color':'yellow'})\r\n \r\n \r\n \r\n worksheet.set_column('B:B',19)\r\n worksheet.set_column('C:BL',30)\r\n \r\n worksheet.conditional_format('E1:F100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"\"',\r\n 'format': problem_format})\r\n worksheet.conditional_format('F1:F100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"Hold for Review\"',\r\n 'format': problem_format})\r\n worksheet.conditional_format('G1:G100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"Needs DHCI Form\"',\r\n 'format': problem_format}) \r\n worksheet.conditional_format('H1:H100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"Needs Income Waiver\"',\r\n 'format': problem_format})\r\n worksheet.conditional_format('I1:I100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"Needs Substantial Activity in FY20\"',\r\n 'format': problem_format})\r\n worksheet.conditional_format('J1:K100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"\"',\r\n 'format': problem_format})\r\n worksheet.conditional_format('L1:L100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"*Needs Outcome*\"',\r\n 'format': problem_format}) \r\n worksheet.conditional_format('L1:L100000',{'type': 'cell',\r\n 'criteria': '==',\r\n 'value': '\"*Needs Outcome Date*\"',\r\n 'format': problem_format})\r\n \r\n writer.save()\r\n \r\n return send_from_directory('sheets',output_filename, as_attachment = True, attachment_filename = \"Formatted \" + f.filename)\r\n\r\n return '''\r\n <!doctype html>\r\n <title>IOI Immigration Quarterly</title>\r\n <link rel=\"stylesheet\" href=\"/static/css/main.css\">\r\n <h1>Quarterly Formatting for IOI Immigration:</h1>\r\n <form action=\"\" method=post enctype=multipart/form-data>\r\n <p><input type=file name=file><input type=submit value=IOI-ify!>\r\n </form>\r\n <h3>Instructions:</h3>\r\n <ul type=\"disc\">\r\n <li>This tool is meant to be used in conjunction with the LegalServer report called <a href=\"https://lsnyc.legalserver.org/report/dynamic?load=1918\" target=\"_blank\">\"Grants Management IOI 2 (3459) Report\"</a>.</li>\r\n <li>Browse your computer using the field above to find the LegalServer excel document that you want to process for IOI.</li> \r\n <li>Once you have identified this file, click ‘IOI-ify!’ and you should shortly be given a prompt to either open the file directly or save the file to your computer.</li> \r\n <li>When you first open the file, all case numbers will display as ‘0’ until you click “Enable Editing” in excel, this will populate the fields.</li> </ul>\r\n </br>\r\n <a href=\"/\">Home</a>\r\n '''\r\n" ]
[ [ "pandas.read_excel", "pandas.ExcelWriter" ], [ "pandas.read_excel", "pandas.DataFrame", "pandas.ExcelWriter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
zh981008/zh-farm
[ "e8cdb977579eb29417be000331c342427c4daf54" ]
[ "juanzeng.py" ]
[ "import uiautomator2 as u2\nimport time\nfrom utils import *\nfrom cv import *\nfrom Automator import *\nimport matplotlib.pylab as plt\n\n\nplt.ion()\nfig, ax = plt.subplots(1)\nplt.show()\n\na = Automator()\na.start()\n\ndef login_auth(ac,pwd):\n need_auth = a.login(ac=ac,pwd=pwd)\n if need_auth:\n auth_name,auth_id = random_name(), CreatIDnum()\n a.auth(auth_name =auth_name ,auth_id = auth_id)\n\n\n\ndef init_home():\n while True:\n screen_shot_ = a.d.screenshot(format=\"opencv\")\n if a.is_there_img(screen_shot_,'img/liwu.jpg'):\n break\n a.d.click(1,1)\n time.sleep(0.5)#保证回到首页\n time.sleep(0.5)\n while True:\n screen_shot_ = a.d.screenshot(format=\"opencv\")\n if a.is_there_img(screen_shot_,'img/liwu.jpg'):\n break\n a.d.click(1,1)\n time.sleep(0.2)#保证回到首页\n a.d.click(100,505)\n\n\ndef change_acc():#切换账号\n time.sleep(1)\n a.d.click(871, 513)\n time.sleep(1)\n a.d.click(165, 411)\n time.sleep(1)\n a.d.click(591, 369)\n time.sleep(1)\n\n\ndef hanghui():#自动行会捐赠\n while True:\n screen_shot_ = a.d.screenshot(format=\"opencv\")\n if a.is_there_img(screen_shot_,'img/liwu.jpg'):\n break\n a.d.click(100,505)\n a.d.click(1,1)\n time.sleep(1)#首页锁定,保证回到首页\n time.sleep(1)\n a.d.click(693, 436)\n time.sleep(1)\n while True:\n screen_shot_ = a.d.screenshot(format=\"opencv\")\n state_flag = a.get_screen_state(screen_shot_)\n if state_flag == 'hanghui':\n screen_shot = a.d.screenshot(format=\"opencv\")\n a.guochang(screen_shot, ['img/juanzeng.jpg'],suiji=0)\n time.sleep(1)\n screen_shot = a.d.screenshot(format=\"opencv\")\n a.guochang(screen_shot, ['img/max.jpg'],suiji=0)\n time.sleep(1)\n screen_shot = a.d.screenshot(format=\"opencv\")\n a.guochang(screen_shot, ['img/hanghui_ok.jpg'],suiji=0)\n time.sleep(1)\n break\n a.d.click(100, 505)\n time.sleep(1)\n while True:\n screen_shot_ = a.d.screenshot(format=\"opencv\")\n if a.is_there_img(screen_shot_,'img/liwu.jpg'):\n break\n a.d.click(100,505)\n a.d.click(1,1)\n time.sleep(1)#首页锁定,保证回到首页\n\n#%%\n#==============================================================================\n#主程序\naccount_dic = {}\n\nwith open('zhanghao.txt','r') as f:\n for i,line in enumerate(f):\n account,password = line.split('\\t')[0:2]\n account_dic[account]=password.strip()\n\nfor account in account_dic:\n print(account, account_dic[account])\n login_auth(account, account_dic[account])\n\n init_home()#初始化,确保进入首页\n hanghui()#行会捐赠\n change_acc()#退出当前账号,切换下一个" ]
[ [ "matplotlib.pylab.show", "matplotlib.pylab.subplots", "matplotlib.pylab.ion" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tbenthompson/devito
[ "7ced4ba4ceca1680c68412172870b7a3c6e6d09a" ]
[ "tests/test_operator.py" ]
[ "import numpy as np\nimport pytest\nfrom itertools import permutations\n\nfrom conftest import skipif\nfrom devito import (Grid, Eq, Operator, Constant, Function, TimeFunction,\n SparseFunction, SparseTimeFunction, Dimension, error, SpaceDimension,\n NODE, CELL, dimensions, configuration, TensorFunction,\n TensorTimeFunction, VectorFunction, VectorTimeFunction, switchconfig)\nfrom devito import Le, Lt, Ge, Gt # noqa\nfrom devito.exceptions import InvalidOperator\nfrom devito.finite_differences.differentiable import diff2sympy\nfrom devito.ir.equations import ClusterizedEq\nfrom devito.ir.equations.algorithms import lower_exprs\nfrom devito.ir.iet import (Callable, Conditional, Expression, Iteration, TimedList,\n FindNodes, IsPerfectIteration, retrieve_iteration_tree)\nfrom devito.ir.support import Any, Backward, Forward\nfrom devito.passes.iet import DataManager\nfrom devito.symbolics import ListInitializer, indexify, retrieve_indexed\nfrom devito.tools import flatten, powerset, timed_region\nfrom devito.types import Array, Scalar # noqa\n\n\ndef dimify(dimensions):\n assert isinstance(dimensions, str)\n return tuple(SpaceDimension(name=i) for i in dimensions.split())\n\n\ndef symbol(name, dimensions, value=0., shape=(3, 5), mode='function'):\n \"\"\"Short-cut for symbol creation to test \"function\"\n and \"indexed\" API.\"\"\"\n assert(mode in ['function', 'indexed'])\n s = Function(name=name, dimensions=dimensions, shape=shape)\n s.data_with_halo[:] = value\n return s.indexify() if mode == 'indexed' else s\n\n\nclass TestOperatorSetup(object):\n\n def test_platform_compiler_language(self):\n \"\"\"\n Test code generation when ``platform``, ``compiler`` and ``language``\n are explicitly supplied to an Operator, thus bypassing the global values\n stored in ``configuration``.\n \"\"\"\n grid = Grid(shape=(3, 3, 3))\n\n u = TimeFunction(name='u', grid=grid)\n\n # Unrecognised platform name -> exception\n try:\n Operator(Eq(u, u + 1), platform='asga')\n assert False\n except InvalidOperator:\n assert True\n\n # Operator with auto-detected CPU platform (ie, `configuration['platform']`)\n op1 = Operator(Eq(u, u + 1))\n # Operator with preset platform\n op2 = Operator(Eq(u, u + 1), platform='nvidiaX')\n\n # Definitely should be\n assert str(op1) != str(op2)\n\n # `op2` should have OpenMP offloading code\n assert '#pragma omp target' in str(op2)\n\n # `op2` uses a user-supplied `platform`, so the Compiler gets rebuilt\n # to make sure it can JIT for the target platform\n assert op1._compiler is not op2._compiler\n\n # The compiler itself can also be passed explicitly ...\n Operator(Eq(u, u + 1), platform='nvidiaX', compiler='gcc')\n # ... but it will raise an exception if an unknown one\n try:\n Operator(Eq(u, u + 1), platform='nvidiaX', compiler='asf')\n assert False\n except InvalidOperator:\n assert True\n\n # Now with explicit platform *and* language\n op3 = Operator(Eq(u, u + 1), platform='nvidiaX', language='openacc')\n assert '#pragma acc parallel' in str(op3)\n assert op3._compiler is not configuration['compiler']\n assert (op3._compiler.__class__.__name__ ==\n configuration['compiler'].__class__.__name__)\n\n # Unsupported combination of `platform` and `language` should throw an error\n try:\n Operator(Eq(u, u + 1), platform='bdw', language='openacc')\n assert False\n except InvalidOperator:\n assert True\n\n # Check that local config takes precedence over global config\n op4 = switchconfig(language='openmp')(Operator)(Eq(u, u + 1), language='C')\n assert '#pragma omp for' not in str(op4)\n\n def test_opt_options(self):\n grid = Grid(shape=(3, 3, 3))\n\n u = TimeFunction(name='u', grid=grid)\n\n # Unknown pass\n try:\n Operator(Eq(u, u + 1), opt=('aaa'))\n assert False\n except InvalidOperator:\n assert True\n\n # Unknown optimization option\n try:\n Operator(Eq(u, u + 1), opt=('advanced', {'aaa': 1}))\n assert False\n except InvalidOperator:\n assert True\n\n def test_compiler_uniqueness(self):\n grid = Grid(shape=(3, 3, 3))\n\n u = TimeFunction(name='u', grid=grid)\n\n eqns = [Eq(u.forward, u + 1)]\n\n op0 = Operator(eqns)\n op1 = Operator(eqns)\n op2 = Operator(eqns, compiler='gcc')\n\n assert op0._compiler is not op1._compiler\n assert op0._compiler is not op2._compiler\n assert op1._compiler is not op2._compiler\n\n\nclass TestCodeGen(object):\n\n def test_parameters(self):\n \"\"\"Tests code generation for Operator parameters.\"\"\"\n grid = Grid(shape=(3,))\n a_dense = Function(name='a_dense', grid=grid)\n const = Constant(name='constant')\n eqn = Eq(a_dense, a_dense + 2.*const)\n op = Operator(eqn, openmp=False)\n assert len(op.parameters) == 5\n assert op.parameters[0].name == 'a_dense'\n assert op.parameters[0].is_Tensor\n assert op.parameters[1].name == 'constant'\n assert op.parameters[1].is_Scalar\n assert op.parameters[2].name == 'x_M'\n assert op.parameters[2].is_Scalar\n assert op.parameters[3].name == 'x_m'\n assert op.parameters[3].is_Scalar\n assert op.parameters[4].name == 'timers'\n assert op.parameters[4].is_Object\n assert 'a_dense[x + 1] = 2.0F*constant + a_dense[x + 1]' in str(op)\n\n @pytest.mark.parametrize('expr, so, to, expected', [\n ('Eq(u.forward,u+1)', 0, 1, 'Eq(u[t+1,x,y,z],u[t,x,y,z]+1)'),\n ('Eq(u.forward,u+1)', 1, 1, 'Eq(u[t+1,x+1,y+1,z+1],u[t,x+1,y+1,z+1]+1)'),\n ('Eq(u.forward,u+1)', 1, 2, 'Eq(u[t+1,x+1,y+1,z+1],u[t,x+1,y+1,z+1]+1)'),\n ('Eq(u.forward,u+u.backward + m)', 8, 2,\n 'Eq(u[t+1,x+8,y+8,z+8],m[x,y,z]+u[t,x+8,y+8,z+8]+u[t-1,x+8,y+8,z+8])')\n ])\n def test_index_shifting(self, expr, so, to, expected):\n \"\"\"Tests that array accesses get properly shifted based on the halo and\n padding regions extent.\"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions\n t = grid.stepping_dim # noqa\n\n u = TimeFunction(name='u', grid=grid, space_order=so, time_order=to) # noqa\n m = Function(name='m', grid=grid, space_order=0) # noqa\n\n expr = eval(expr)\n\n with timed_region('x'):\n expr = Operator._lower_exprs([expr])[0]\n\n assert str(expr).replace(' ', '') == expected\n\n @pytest.mark.parametrize('expr, so, expected', [\n ('Lt(0.1*(g1 + g2), 0.2*(g1 + g2))', 0,\n '0.1*g1[x,y]+0.1*g2[x,y]<0.2*g1[x,y]+0.2*g2[x,y]'),\n ('Le(0.1*(g1 + g2), 0.2*(g1 + g2))', 1,\n '0.1*g1[x+1,y+1]+0.1*g2[x+1,y+1]<=0.2*g1[x+1,y+1]+0.2*g2[x+1,y+1]'),\n ('Ge(0.1*(g1 + g2), 0.2*(g1 + g2))', 2,\n '0.1*g1[x+2,y+2]+0.1*g2[x+2,y+2]>=0.2*g1[x+2,y+2]+0.2*g2[x+2,y+2]'),\n ('Gt(0.1*(g1 + g2), 0.2*(g1 + g2))', 4,\n '0.1*g1[x+4,y+4]+0.1*g2[x+4,y+4]>0.2*g1[x+4,y+4]+0.2*g2[x+4,y+4]'),\n ])\n def test_relationals_index_shifting(self, expr, so, expected):\n\n grid = Grid(shape=(3, 3))\n g1 = Function(name='g1', grid=grid, space_order=so) # noqa\n g2 = Function(name='g2', grid=grid, space_order=so) # noqa\n expr = eval(expr)\n expr = lower_exprs(expr)\n\n assert str(expr).replace(' ', '') == expected\n\n @pytest.mark.parametrize('expr,exp_uindices,exp_mods', [\n ('Eq(v.forward, u[0, x, y, z] + v + 1)', [(0, 5), (2, 5)], {'v': 5}),\n ('Eq(v.forward, u + v + 1)', [(0, 5), (2, 5), (0, 2)], {'v': 5, 'u': 2}),\n ])\n def test_multiple_steppers(self, expr, exp_uindices, exp_mods):\n \"\"\"Tests generation of multiple, mixed time stepping indices.\"\"\"\n grid = Grid(shape=(3, 3, 3))\n x, y, z = grid.dimensions\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid) # noqa\n v = TimeFunction(name='v', grid=grid, time_order=4) # noqa\n\n op = Operator(eval(expr), opt='noop')\n\n iters = FindNodes(Iteration).visit(op)\n time_iter = [i for i in iters if i.dim.is_Time]\n assert len(time_iter) == 1\n time_iter = time_iter[0]\n\n # Check uindices in Iteration header\n signatures = [(i._offset, i._modulo) for i in time_iter.uindices]\n assert len(signatures) == len(exp_uindices)\n exp_uindices = [(time + i, j) for i, j in exp_uindices]\n assert all(i in signatures for i in exp_uindices)\n\n # Check uindices within each TimeFunction\n exprs = [i.expr for i in FindNodes(Expression).visit(op)]\n assert(i.indices[i.function._time_position].modulo == exp_mods[i.function.name]\n for i in flatten(retrieve_indexed(i) for i in exprs))\n\n def test_lower_stepping_dims_with_mutiple_iterations(self):\n \"\"\"\n Test lowering SteppingDimensions for a time dimension with\n more than one iteration loop with different ModuloDimensions.\n MFE for issue #1486\n \"\"\"\n grid = Grid(shape=(4, 4))\n\n f = Function(name=\"f\", grid=grid, space_order=4)\n g = Function(name=\"g\", grid=grid, space_order=4)\n h = TimeFunction(name=\"h\", grid=grid, space_order=4, time_order=2)\n\n f.data[:] = 0.0\n h.data[:] = 0.0\n\n eqn = [Eq(f, h + 1), Eq(g, f),\n Eq(h.forward, h + g + 1)]\n\n op = Operator(eqn)\n\n for iter in [i for i in FindNodes(Iteration).visit(op) if i.dim.is_Time]:\n exprtimeindices = set([a.indices[a.function._time_position] for\n expr in FindNodes(Expression).visit(iter) for\n a in retrieve_indexed(expr.expr) if\n isinstance(a.function, TimeFunction)])\n # Check if iteration time indices match with expressions time indices\n assert (exprtimeindices == set(iter.uindices))\n # Check if expressions time indices are modulo dimensions\n assert(all([i.is_Modulo for i in exprtimeindices]))\n\n op.apply(time_M=10)\n\n assert np.all(h.data[0, :] == 18)\n assert np.all(h.data[1, :] == 20)\n assert np.all(h.data[2, :] == 22)\n\n @skipif('device')\n def test_timedlist_wraps_time_if_parallel(self):\n \"\"\"\n Test that if the time loop is parallel, then it must be wrapped by a\n Section (and consequently by a TimedList).\n \"\"\"\n grid = Grid(shape=(3, 3, 3))\n\n u = TimeFunction(name='u', grid=grid, save=3)\n\n op = Operator(Eq(u, u + 1))\n\n assert op.body.body[1].body[0].is_Section\n assert isinstance(op.body.body[1].body[0].body[0], TimedList)\n timedlist = op.body.body[1].body[0].body[0]\n if configuration['language'] == 'openmp':\n ompreg = timedlist.body[0]\n assert ompreg.body[0].dim is grid.time_dim\n else:\n timedlist.body[0].dim is grid.time_dim\n\n def test_nested_lowering(self):\n \"\"\"\n Tests that deeply nested (depth > 2) functions over subdomains are lowered.\n \"\"\"\n grid = Grid(shape=(4, 4), dtype=np.int32)\n x, y = grid.dimensions\n x0, y0 = dimensions('x0 y0')\n\n u0 = Function(name=\"u0\", grid=grid)\n u1 = Function(name=\"u1\", shape=grid.shape, dimensions=(x0, y0), dtype=np.int32)\n u2 = Function(name=\"u2\", grid=grid)\n\n u0.data[:2, :2] = 1\n u0.data[2:, 2:] = 2\n u1.data[:, :] = 1\n u2.data[:, :] = 1\n\n eq0 = Eq(u0, u0[u1[x0+1, y0+2], u2[x, u2]], subdomain=grid.interior)\n eq1 = Eq(u0, u0[u1[x0+1, y0+2], u2[x, u2[x, y]]], subdomain=grid.interior)\n\n op0 = Operator(eq0)\n op1 = Operator(eq1)\n op0.apply()\n\n # Check they indeed produced the same code\n assert str(op0.ccode) == str(op1.ccode)\n\n # Also check for numerical correctness\n assert np.all(u0.data[0, 3] == 0) and np.all(u0.data[3, 0] == 0)\n assert np.all(u0.data[:2, :2] == 1) and np.all(u0.data[1:3, 1:3] == 1)\n assert np.all(u0.data[2:3, 3] == 2) and np.all(u0.data[3, 2:3] == 2)\n\n def test_nested_lowering_indexify(self):\n \"\"\"\n Tests that nested function are lowered if only used as index.\n \"\"\"\n grid = Grid(shape=(4, 4), dtype=np.int32)\n x, y = grid.dimensions\n\n u0 = Function(name=\"u0\", grid=grid)\n u1 = Function(name=\"u1\", grid=grid)\n u2 = Function(name=\"u2\", grid=grid)\n\n u0.data[:, :] = 2\n u1.data[:, :] = 1\n u2.data[:, :] = 1\n\n # Function as index only\n eq0 = Eq(u0._subs(x, u1), 2*u0)\n # Function as part of expression as index only\n eq1 = Eq(u0._subs(x, u1._subs(y, u2) + 1), 4*u0)\n\n op0 = Operator(eq0)\n op0.apply()\n op1 = Operator(eq1)\n op1.apply()\n assert np.all(np.all(u0.data[i, :] == 2) for i in [0, 3])\n assert np.all(u0.data[1, :] == 4)\n assert np.all(u0.data[2, :] == 8)\n\n\nclass TestArithmetic(object):\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a, a + b + 5.)', 10.),\n ('Eq(a, b - a)', 1.),\n ('Eq(a, 4 * (b * a))', 24.),\n ('Eq(a, (6. / b) + (8. * a))', 18.),\n ])\n @pytest.mark.parametrize('mode', ['function'])\n def test_flat(self, expr, result, mode):\n \"\"\"Tests basic point-wise arithmetic on two-dimensional data\"\"\"\n i, j = dimify('i j')\n a = symbol(name='a', dimensions=(i, j), value=2., mode=mode)\n b = symbol(name='b', dimensions=(i, j), value=3., mode=mode)\n fa = a.base.function if mode == 'indexed' else a\n fb = b.base.function if mode == 'indexed' else b\n\n eqn = eval(expr)\n Operator(eqn)(a=fa, b=fb)\n assert np.allclose(fa.data, result, rtol=1e-12)\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a, a + b + 5.)', 10.),\n ('Eq(a, b - a)', 1.),\n ('Eq(a, 4 * (b * a))', 24.),\n ('Eq(a, (6. / b) + (8. * a))', 18.),\n ])\n @pytest.mark.parametrize('mode', ['function', 'indexed'])\n def test_deep(self, expr, result, mode):\n \"\"\"Tests basic point-wise arithmetic on multi-dimensional data\"\"\"\n i, j, k, l = dimify('i j k l')\n a = symbol(name='a', dimensions=(i, j, k, l), shape=(3, 5, 7, 6),\n value=2., mode=mode)\n b = symbol(name='b', dimensions=(j, k), shape=(5, 7),\n value=3., mode=mode)\n fa = a.base.function if mode == 'indexed' else a\n fb = b.base.function if mode == 'indexed' else b\n\n eqn = eval(expr)\n Operator(eqn)(a=fa, b=fb)\n assert np.allclose(fa.data, result, rtol=1e-12)\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a[j, l], a[j - 1 , l] + 1.)',\n np.meshgrid(np.arange(2., 8.), np.arange(2., 7.))[1]),\n ('Eq(a[j, l], a[j, l - 1] + 1.)',\n np.meshgrid(np.arange(2., 8.), np.arange(2., 7.))[0]),\n ])\n def test_indexed_increment(self, expr, result):\n \"\"\"Tests point-wise increments with stencil offsets in one dimension\"\"\"\n j, l = dimify('j l')\n a = symbol(name='a', dimensions=(j, l), value=1., shape=(5, 6),\n mode='indexed').base\n fa = a.function\n fa.data[:] = 0.\n\n eqn = eval(expr)\n Operator(eqn)(a=fa)\n assert np.allclose(fa.data, result, rtol=1e-12)\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a[j, l], b[j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[j, l], b[j , l - 1] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[j, l], b[j - 1, l - 1] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[j, l], b[j + 1, l + 1] + 1.)', np.zeros((5, 6)) + 3.),\n ])\n def test_indexed_stencil(self, expr, result):\n \"\"\"Test point-wise arithmetic with stencil offsets across two\n functions in indexed expression format\"\"\"\n j, l = dimify('j l')\n a = symbol(name='a', dimensions=(j, l), value=0., shape=(5, 6),\n mode='indexed').base\n fa = a.function\n b = symbol(name='b', dimensions=(j, l), value=2., shape=(5, 6),\n mode='indexed').base\n fb = b.function\n\n eqn = eval(expr)\n Operator(eqn)(a=fa, b=fb)\n assert np.allclose(fa.data[1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a[1, j, l], a[0, j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[1, j, l], a[0, j , l - 1] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[1, j, l], a[0, j - 1, l - 1] + 1.)', np.zeros((5, 6)) + 3.),\n ('Eq(a[1, j, l], a[0, j + 1, l + 1] + 1.)', np.zeros((5, 6)) + 3.),\n ])\n def test_indexed_buffered(self, expr, result):\n \"\"\"Test point-wise arithmetic with stencil offsets across a single\n functions with buffering dimension in indexed expression format\"\"\"\n i, j, l = dimify('i j l')\n a = symbol(name='a', dimensions=(i, j, l), value=2., shape=(3, 5, 6),\n mode='indexed').base\n fa = a.function\n\n eqn = eval(expr)\n Operator(eqn)(a=fa)\n assert np.allclose(fa.data[1, 1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)\n\n @pytest.mark.parametrize('expr, result', [\n ('Eq(a[1, j, l], a[0, j - 1 , l] + 1.)', np.zeros((5, 6)) + 3.),\n ])\n def test_indexed_open_loops(self, expr, result):\n \"\"\"Test point-wise arithmetic with stencil offsets and open loop\n boundaries in indexed expression format\"\"\"\n i, j, l = dimify('i j l')\n a = Function(name='a', dimensions=(i, j, l), shape=(3, 5, 6))\n fa = a.function\n fa.data[0, :, :] = 2.\n\n eqn = eval(expr)\n Operator(eqn)(a=fa)\n assert np.allclose(fa.data[1, 1:-1, 1:-1], result[1:-1, 1:-1], rtol=1e-12)\n\n def test_indexed_w_indirections(self):\n \"\"\"Test point-wise arithmetic with indirectly indexed Functions.\"\"\"\n grid = Grid(shape=(10, 10))\n x, y = grid.dimensions\n\n p_poke = Dimension('p_src')\n d = Dimension('d')\n\n npoke = 1\n\n u = Function(name='u', grid=grid, space_order=0)\n coordinates = Function(name='coordinates', dimensions=(p_poke, d),\n shape=(npoke, grid.dim), space_order=0, dtype=np.int32)\n coordinates.data[0, 0] = 4\n coordinates.data[0, 1] = 3\n\n poke_eq = Eq(u[coordinates[p_poke, 0], coordinates[p_poke, 1]], 1.0)\n op = Operator(poke_eq)\n op.apply()\n\n ix, iy = np.where(u.data == 1.)\n assert len(ix) == len(iy) == 1\n assert ix[0] == 4 and iy[0] == 3\n assert np.all(u.data[0:3] == 0.) and np.all(u.data[5:] == 0.)\n assert np.all(u.data[:, 0:3] == 0.) and np.all(u.data[:, 5:] == 0.)\n\n def test_constant_time_dense(self):\n \"\"\"Test arithmetic between different data objects, namely Constant\n and Function.\"\"\"\n i, j = dimify('i j')\n const = Constant(name='truc', value=2.)\n a = Function(name='a', shape=(20, 20), dimensions=(i, j))\n a.data[:] = 2.\n eqn = Eq(a, a + 2.*const)\n op = Operator(eqn)\n\n op.apply(a=a, truc=const)\n assert(np.allclose(a.data, 6.))\n\n # Applying a different constant still works\n op.apply(a=a, truc=Constant(name='truc2', value=3.))\n assert(np.allclose(a.data, 12.))\n\n def test_incs_same_lhs(self):\n \"\"\"Test point-wise arithmetic with multiple increments expressed\n as different equations.\"\"\"\n grid = Grid(shape=(10, 10))\n u = Function(name='u', grid=grid, space_order=0)\n op = Operator([Eq(u, u+1.0), Eq(u, u+2.0)])\n u.data[:] = 0.0\n op.apply()\n assert np.all(u.data[:] == 3)\n\n def test_sparsefunction_inject(self):\n \"\"\"\n Test injection of a SparseFunction into a Function\n \"\"\"\n grid = Grid(shape=(11, 11))\n u = Function(name='u', grid=grid, space_order=0)\n\n sf1 = SparseFunction(name='s', grid=grid, npoint=1)\n op = Operator(sf1.inject(u, expr=sf1))\n\n assert sf1.data.shape == (1, )\n sf1.coordinates.data[0, :] = (0.6, 0.6)\n sf1.data[0] = 5.0\n u.data[:] = 0.0\n\n op.apply()\n\n # This should be exactly on a point, all others 0\n assert u.data[6, 6] == pytest.approx(5.0)\n assert np.sum(u.data) == pytest.approx(5.0)\n\n def test_sparsefunction_interp(self):\n \"\"\"\n Test interpolation of a SparseFunction from a Function\n \"\"\"\n grid = Grid(shape=(11, 11))\n u = Function(name='u', grid=grid, space_order=0)\n\n sf1 = SparseFunction(name='s', grid=grid, npoint=1)\n op = Operator(sf1.interpolate(u))\n\n assert sf1.data.shape == (1, )\n sf1.coordinates.data[0, :] = (0.45, 0.45)\n sf1.data[:] = 0.0\n u.data[:] = 0.0\n u.data[4, 4] = 4.0\n\n op.apply()\n\n # Exactly in the middle of 4 points, only 1 nonzero is 4\n assert sf1.data[0] == pytest.approx(1.0)\n\n def test_sparsetimefunction_interp(self):\n \"\"\"\n Test injection of a SparseTimeFunction into a TimeFunction\n \"\"\"\n grid = Grid(shape=(11, 11))\n u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)\n\n sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5)\n op = Operator(sf1.interpolate(u))\n\n assert sf1.data.shape == (5, 1)\n sf1.coordinates.data[0, :] = (0.45, 0.45)\n sf1.data[:] = 0.0\n u.data[:] = 0.0\n u.data[:, 4, 4] = 8*np.arange(5)+4\n\n # Because of time_order=2 this is probably the range we get anyway, but\n # to be sure...\n op.apply(time_m=1, time_M=3)\n\n # Exactly in the middle of 4 points, only 1 nonzero is 4\n assert np.all(sf1.data[:, 0] == pytest.approx([0.0, 3.0, 5.0, 7.0, 0.0]))\n\n def test_sparsetimefunction_inject(self):\n \"\"\"\n Test injection of a SparseTimeFunction from a TimeFunction\n \"\"\"\n grid = Grid(shape=(11, 11))\n u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)\n\n sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5)\n op = Operator(sf1.inject(u, expr=3*sf1))\n\n assert sf1.data.shape == (5, 1)\n sf1.coordinates.data[0, :] = (0.45, 0.45)\n sf1.data[:, 0] = np.arange(5)\n u.data[:] = 0.0\n\n # Because of time_order=2 this is probably the range we get anyway, but\n # to be sure...\n op.apply(time_m=1, time_M=3)\n\n # Exactly in the middle of 4 points, only 1 nonzero is 4\n assert np.all(u.data[1, 4:6, 4:6] == pytest.approx(0.75))\n assert np.all(u.data[2, 4:6, 4:6] == pytest.approx(1.5))\n assert np.all(u.data[3, 4:6, 4:6] == pytest.approx(2.25))\n assert np.sum(u.data[:]) == pytest.approx(4*0.75+4*1.5+4*2.25)\n\n def test_sparsetimefunction_inject_dt(self):\n \"\"\"\n Test injection of the time deivative of a SparseTimeFunction into a TimeFunction\n \"\"\"\n grid = Grid(shape=(11, 11))\n u = TimeFunction(name='u', grid=grid, time_order=2, save=5, space_order=0)\n\n sf1 = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=5, time_order=2)\n\n # This should end up as a central difference operator\n op = Operator(sf1.inject(u, expr=3*sf1.dt))\n\n assert sf1.data.shape == (5, 1)\n sf1.coordinates.data[0, :] = (0.45, 0.45)\n sf1.data[:, 0] = np.arange(5)\n u.data[:] = 0.0\n\n # Because of time_order=2 this is probably the range we get anyway, but\n # to be sure...\n op.apply(time_m=1, time_M=3, dt=1)\n\n # Exactly in the middle of 4 points, only 1 nonzero is 4\n assert np.all(u.data[1:4, 4:6, 4:6] == pytest.approx(0.75))\n assert np.sum(u.data[:]) == pytest.approx(12*0.75)\n\n @pytest.mark.parametrize('func1', [TensorFunction, TensorTimeFunction,\n VectorFunction, VectorTimeFunction])\n def test_tensor(self, func1):\n grid = Grid(tuple([5]*3))\n f1 = func1(name=\"f1\", grid=grid)\n op1 = Operator(Eq(f1, f1.dx))\n op2 = Operator([Eq(f, f.dx) for f in f1.values()])\n assert str(op1.ccode) == str(op2.ccode)\n\n\nclass TestAllocation(object):\n\n @pytest.mark.parametrize('shape', [(20, 20),\n (20, 20, 20),\n (20, 20, 20, 20)])\n def test_first_touch(self, shape):\n dimensions = dimify('i j k l')[:len(shape)]\n grid = Grid(shape=shape, dimensions=dimensions)\n m = Function(name='m', grid=grid, first_touch=True)\n assert(np.allclose(m.data, 0))\n m2 = Function(name='m2', grid=grid, first_touch=False)\n assert(np.allclose(m2.data, 0))\n assert(np.array_equal(m.data, m2.data))\n\n @pytest.mark.parametrize('ndim', [2, 3])\n def test_staggered(self, ndim):\n \"\"\"\n Test the \"deformed\" allocation for staggered functions\n \"\"\"\n grid = Grid(shape=tuple([11]*ndim))\n for stagg in tuple(powerset(grid.dimensions))[1::] + (NODE, CELL):\n f = Function(name='f', grid=grid, staggered=stagg)\n assert f.data.shape == tuple([11]*ndim)\n # Add a non-staggered field to ensure that the auto-derived\n # dimension size arguments are at maximum\n g = Function(name='g', grid=grid)\n # Test insertion into a central point\n index = tuple(5 for _ in f.dimensions)\n set_f = Eq(f[index], 2.)\n set_g = Eq(g[index], 3.)\n\n Operator([set_f, set_g])()\n assert f.data[index] == 2.\n\n @pytest.mark.parametrize('ndim', [2, 3])\n def test_staggered_time(self, ndim):\n \"\"\"\n Test the \"deformed\" allocation for staggered functions\n \"\"\"\n grid = Grid(shape=tuple([11]*ndim))\n for stagg in tuple(powerset(grid.dimensions))[1::] + (NODE,):\n f = TimeFunction(name='f', grid=grid, staggered=stagg)\n assert f.data.shape[1:] == tuple([11]*ndim)\n # Add a non-staggered field to ensure that the auto-derived\n # dimension size arguments are at maximum\n g = TimeFunction(name='g', grid=grid)\n # Test insertion into a central point\n index = tuple([0] + [5 for _ in f.dimensions[1:]])\n set_f = Eq(f[index], 2.)\n set_g = Eq(g[index], 3.)\n\n Operator([set_f, set_g])()\n assert f.data[index] == 2.\n\n\nclass TestApplyArguments(object):\n\n def verify_arguments(self, arguments, expected):\n \"\"\"\n Utility function to verify an argument dictionary against\n expected values.\n \"\"\"\n for name, v in expected.items():\n if isinstance(v, (Function, SparseFunction)):\n condition = v._C_as_ndarray(arguments[name])[v._mask_domain] == v.data\n condition = condition.all()\n else:\n condition = arguments[name] == v\n\n if not condition:\n error('Wrong argument %s: expected %s, got %s' %\n (name, v, arguments[name]))\n assert condition\n\n def verify_parameters(self, parameters, expected):\n \"\"\"\n Utility function to verify a parameter set against expected\n values.\n \"\"\"\n boilerplate = ['timers']\n parameters = [p.name for p in parameters]\n for exp in expected:\n if exp not in parameters + boilerplate:\n error(\"Missing parameter: %s\" % exp)\n assert exp in parameters + boilerplate\n extra = [p for p in parameters if p not in expected and p not in boilerplate]\n if len(extra) > 0:\n error(\"Redundant parameters: %s\" % str(extra))\n assert len(extra) == 0\n\n def test_default_functions(self):\n \"\"\"\n Test the default argument derivation for functions.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n f = TimeFunction(name='f', grid=grid)\n g = Function(name='g', grid=grid)\n op = Operator(Eq(f.forward, g + f), openmp=False)\n\n expected = {\n 'x_m': 0, 'x_M': 4,\n 'y_m': 0, 'y_M': 5,\n 'z_m': 0, 'z_M': 6,\n 'f': f, 'g': g,\n }\n self.verify_arguments(op.arguments(time=4), expected)\n exp_parameters = ['f', 'g', 'x_m', 'x_M', 'y_m', 'y_M', 'z_m', 'z_M',\n 'x0_blk0_size', 'y0_blk0_size', 'time_m', 'time_M']\n self.verify_parameters(op.parameters, exp_parameters)\n\n def test_default_sparse_functions(self):\n \"\"\"\n Test the default argument derivation for composite functions.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n f = TimeFunction(name='f', grid=grid)\n s = SparseTimeFunction(name='s', grid=grid, npoint=3, nt=4)\n s.coordinates.data[:, 0] = np.arange(0., 3.)\n s.coordinates.data[:, 1] = np.arange(1., 4.)\n s.coordinates.data[:, 2] = np.arange(2., 5.)\n op = Operator(s.interpolate(f))\n\n expected = {\n 's': s, 's_coords': s.coordinates,\n # Default dimensions of the sparse data\n 'p_s_size': 3, 'p_s_m': 0, 'p_s_M': 2,\n 'd_size': 3, 'd_m': 0, 'd_M': 2,\n 'time_size': 4, 'time_m': 0, 'time_M': 3,\n }\n self.verify_arguments(op.arguments(), expected)\n\n def test_override_function_size(self):\n \"\"\"\n Test runtime size overrides for Function dimensions.\n\n Note: The current behaviour for size-only arguments seems\n ambiguous (eg. op(x=3, y=4), as it sets `dim_size` as well as\n `dim_end`. Since `dim_size` is used for the cast, we can get\n garbage results if it does not agree with the shape of the\n provided data. This should error out, or potentially we could\n set the corresponding size, while aliasing `dim` to `dim_e`?\n\n The same should be tested for TimeFunction once fixed.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n g = Function(name='g', grid=grid)\n\n op = Operator(Eq(g, 1.))\n args = {'x': 3, 'y': 4, 'z': 5}\n arguments = op.arguments(**args)\n expected = {\n 'x_m': 0, 'x_M': 3,\n 'y_m': 0, 'y_M': 4,\n 'z_m': 0, 'z_M': 5,\n 'g': g\n }\n self.verify_arguments(arguments, expected)\n # Verify execution\n op(**args)\n assert (g.data[4:] == 0.).all()\n assert (g.data[:, 5:] == 0.).all()\n assert (g.data[:, :, 6:] == 0.).all()\n assert (g.data[:4, :5, :6] == 1.).all()\n\n def test_override_function_subrange(self):\n \"\"\"\n Test runtime start/end override for Function dimensions.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n g = Function(name='g', grid=grid)\n\n op = Operator(Eq(g, 1.))\n args = {'x_m': 1, 'x_M': 3, 'y_m': 2, 'y_M': 4, 'z_m': 3, 'z_M': 5}\n arguments = op.arguments(**args)\n expected = {\n 'x_m': 1, 'x_M': 3,\n 'y_m': 2, 'y_M': 4,\n 'z_m': 3, 'z_M': 5,\n 'g': g\n }\n self.verify_arguments(arguments, expected)\n # Verify execution\n op(**args)\n mask = np.ones((5, 6, 7), dtype=np.bool)\n mask[1:4, 2:5, 3:6] = False\n assert (g.data[mask] == 0.).all()\n assert (g.data[1:4, 2:5, 3:6] == 1.).all()\n\n def test_override_timefunction_subrange(self):\n \"\"\"\n Test runtime start/end overrides for TimeFunction dimensions.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n f = TimeFunction(name='f', grid=grid, time_order=0)\n\n # Suppress opts to work around a know bug with GCC and OpenMP:\n # https://github.com/devitocodes/devito/issues/320\n op = Operator(Eq(f, 1.), opt=None)\n # TODO: Currently we require the `time` subrange to be set\n # explicitly. Ideally `t` would directly alias with `time`,\n # but this seems broken currently.\n args = {'x_m': 1, 'x_M': 3, 'y_m': 2, 'y_M': 4,\n 'z_m': 3, 'z_M': 5, 't_m': 1, 't_M': 4}\n arguments = op.arguments(**args)\n expected = {\n 'x_m': 1, 'x_M': 3,\n 'y_m': 2, 'y_M': 4,\n 'z_m': 3, 'z_M': 5,\n 'time_m': 1, 'time_M': 4,\n 'f': f\n }\n self.verify_arguments(arguments, expected)\n # Verify execution\n op(**args)\n mask = np.ones((1, 5, 6, 7), dtype=np.bool)\n mask[:, 1:4, 2:5, 3:6] = False\n assert (f.data[mask] == 0.).all()\n assert (f.data[:, 1:4, 2:5, 3:6] == 1.).all()\n\n def test_override_function_data(self):\n \"\"\"\n Test runtime data overrides for Function symbols.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n a = Function(name='a', grid=grid)\n op = Operator(Eq(a, a + 3))\n\n # Run with default value\n a.data[:] = 1.\n op()\n assert (a.data[:] == 4.).all()\n\n # Override with symbol (different name)\n a1 = Function(name='a1', grid=grid)\n a1.data[:] = 2.\n op(a=a1)\n assert (a1.data[:] == 5.).all()\n\n # Override with symbol (same name as original)\n a2 = Function(name='a', grid=grid)\n a2.data[:] = 3.\n op(a=a2)\n assert (a2.data[:] == 6.).all()\n\n # Override with user-allocated numpy data\n a3 = np.zeros_like(a._data_allocated)\n a3[:] = 4.\n op(a=a3)\n assert (a3[a._mask_domain] == 7.).all()\n\n def test_override_timefunction_data(self):\n \"\"\"\n Test runtime data overrides for TimeFunction symbols.\n \"\"\"\n grid = Grid(shape=(5, 6, 7))\n a = TimeFunction(name='a', grid=grid, save=2)\n # Suppress opts to work around a know bug with GCC and OpenMP:\n # https://github.com/devitocodes/devito/issues/320\n op = Operator(Eq(a, a + 3), opt=None)\n\n # Run with default value\n a.data[:] = 1.\n op(time_m=0, time=1)\n assert (a.data[:] == 4.).all()\n\n # Override with symbol (different name)\n a1 = TimeFunction(name='a1', grid=grid, save=2)\n a1.data[:] = 2.\n op(time_m=0, time=1, a=a1)\n assert (a1.data[:] == 5.).all()\n\n # Override with symbol (same name as original)\n a2 = TimeFunction(name='a', grid=grid, save=2)\n a2.data[:] = 3.\n op(time_m=0, time=1, a=a2)\n assert (a2.data[:] == 6.).all()\n\n # Override with user-allocated numpy data\n a3 = np.zeros_like(a._data_allocated)\n a3[:] = 4.\n op(time_m=0, time=1, a=a3)\n assert (a3[a._mask_domain] == 7.).all()\n\n def test_dimension_size_infer(self, nt=100):\n \"\"\"Test that the dimension sizes are being inferred correctly\"\"\"\n grid = Grid(shape=(3, 5, 7))\n a = Function(name='a', grid=grid)\n b = TimeFunction(name='b', grid=grid, save=nt)\n op = Operator(Eq(b, a))\n\n time = b.indices[0]\n op_arguments = op.arguments()\n assert(op_arguments[time.min_name] == 0)\n assert(op_arguments[time.max_name] == nt-1)\n\n def test_dimension_offset_adjust(self, nt=100):\n \"\"\"Test that the dimension sizes are being inferred correctly\"\"\"\n i, j, k = dimify('i j k')\n shape = (10, 10, 10)\n grid = Grid(shape=shape, dimensions=(i, j, k))\n a = Function(name='a', grid=grid)\n b = TimeFunction(name='b', grid=grid, save=nt)\n time = b.indices[0]\n eqn = Eq(b[time + 1, i, j, k], b[time - 1, i, j, k]\n + b[time, i, j, k] + a[i, j, k])\n op = Operator(eqn)\n op_arguments = op.arguments(time=nt-10)\n assert(op_arguments[time.min_name] == 1)\n assert(op_arguments[time.max_name] == nt - 10)\n\n def test_dimension_size_override(self):\n \"\"\"Test explicit overrides for the leading time dimension\"\"\"\n grid = Grid(shape=(3, 5, 7))\n a = TimeFunction(name='a', grid=grid)\n one = Function(name='one', grid=grid)\n one.data[:] = 1.\n op = Operator(Eq(a.forward, a + one))\n\n # Test dimension override via the buffered dimenions\n a.data[0] = 0.\n op(a=a, t=5)\n assert(np.allclose(a.data[1], 5.))\n\n # Test dimension override via the parent dimenions\n a.data[0] = 0.\n op(a=a, time=4)\n assert(np.allclose(a.data[0], 4.))\n\n def test_override_sparse_data_fix_dim(self):\n \"\"\"\n Ensure the arguments are derived correctly for an input SparseFunction.\n The dimensions are forced to be the same in this case to verify\n the aliasing on the SparseFunction name.\n \"\"\"\n grid = Grid(shape=(10, 10))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid, time_order=2, space_order=2)\n\n original_coords = (1., 1.)\n new_coords = (2., 2.)\n p_dim = Dimension(name='p_src')\n src1 = SparseTimeFunction(name='src1', grid=grid, dimensions=(time, p_dim), nt=10,\n npoint=1, coordinates=original_coords, time_order=2)\n src2 = SparseTimeFunction(name='src2', grid=grid, dimensions=(time, p_dim),\n npoint=1, nt=10, coordinates=new_coords, time_order=2)\n op = Operator(src1.inject(u, src1))\n\n # Move the source from the location where the setup put it so we can test\n # whether the override picks up the original coordinates or the changed ones\n\n args = op.arguments(src1=src2, time=0)\n arg_name = src1.coordinates._arg_names[0]\n assert(np.array_equal(src2.coordinates._C_as_ndarray(args[arg_name]),\n np.asarray((new_coords,))))\n\n def test_override_sparse_data_default_dim(self):\n \"\"\"\n Ensure the arguments are derived correctly for an input SparseFunction.\n The dimensions are the defaults (name dependant 'p_name') in this case to verify\n the aliasing on the SparseFunction coordinates and dimensions.\n \"\"\"\n grid = Grid(shape=(10, 10))\n original_coords = (1., 1.)\n new_coords = (2., 2.)\n u = TimeFunction(name='u', grid=grid, time_order=2, space_order=2)\n src1 = SparseTimeFunction(name='src1', grid=grid, npoint=1, nt=10,\n coordinates=original_coords, time_order=2)\n src2 = SparseTimeFunction(name='src2', grid=grid, npoint=1, nt=10,\n coordinates=new_coords, time_order=2)\n op = Operator(src1.inject(u, src1))\n\n # Move the source from the location where the setup put it so we can test\n # whether the override picks up the original coordinates or the changed ones\n\n args = op.arguments(src1=src2, t=0)\n arg_name = src1.coordinates._arg_names[0]\n assert(np.array_equal(src2.coordinates._C_as_ndarray(args[arg_name]),\n np.asarray((new_coords,))))\n\n def test_argument_derivation_order(self, nt=100):\n \"\"\" Ensure the precedence order of arguments is respected\n Defaults < (overriden by) Tensor Arguments < Dimensions < Scalar Arguments\n \"\"\"\n i, j, k = dimify('i j k')\n shape = (10, 10, 10)\n grid = Grid(shape=shape, dimensions=(i, j, k))\n a = Function(name='a', grid=grid)\n b = TimeFunction(name='b', grid=grid, save=nt)\n time = b.indices[0]\n op = Operator(Eq(b, a))\n\n # Simple case, same as that tested above.\n # Repeated here for clarity of further tests.\n op_arguments = op.arguments()\n assert(op_arguments[time.min_name] == 0)\n assert(op_arguments[time.max_name] == nt-1)\n\n # Providing a tensor argument should infer the dimension size from its shape\n b1 = TimeFunction(name='b1', grid=grid, save=nt+1)\n op_arguments = op.arguments(b=b1)\n assert(op_arguments[time.min_name] == 0)\n assert(op_arguments[time.max_name] == nt)\n\n # Providing a dimension size explicitly should override the automatically inferred\n op_arguments = op.arguments(b=b1, time=nt - 1)\n assert(op_arguments[time.min_name] == 0)\n assert(op_arguments[time.max_name] == nt - 1)\n\n # Providing a scalar argument explicitly should override the automatically\n # inferred\n op_arguments = op.arguments(b=b1, time_M=nt - 2)\n assert(op_arguments[time.min_name] == 0)\n assert(op_arguments[time.max_name] == nt - 2)\n\n def test_derive_constant_value(self):\n \"\"\"Ensure that values for Constant symbols are derived correctly.\"\"\"\n grid = Grid(shape=(5, 6))\n f = Function(name='f', grid=grid)\n a = Constant(name='a', value=3.)\n Operator(Eq(f, a))()\n assert np.allclose(f.data, 3.)\n\n g = Function(name='g', grid=grid)\n b = Constant(name='b')\n op = Operator(Eq(g, b))\n b.data = 4.\n op()\n assert np.allclose(g.data, 4.)\n\n def test_argument_from_index_constant(self):\n nx, ny = 30, 30\n grid = Grid(shape=(nx, ny))\n x, y = grid.dimensions\n\n arbdim = Dimension('arb')\n u = TimeFunction(name='u', grid=grid, save=None, time_order=2, space_order=0)\n snap = Function(name='snap', dimensions=(arbdim, x, y), shape=(5, nx, ny),\n space_order=0)\n\n save_t = Constant(name='save_t', dtype=np.int32)\n save_slot = Constant(name='save_slot', dtype=np.int32)\n\n expr = Eq(snap.subs(arbdim, save_slot), u.subs(grid.stepping_dim, save_t))\n op = Operator(expr)\n u.data[:] = 0.0\n snap.data[:] = 0.0\n u.data[0, 10, 10] = 1.0\n op.apply(save_t=0, save_slot=1)\n assert snap.data[1, 10, 10] == 1.0\n\n def test_argument_no_shifting(self):\n \"\"\"Tests that there's no shifting in the written-to region when\n iteration bounds are prescribed.\"\"\"\n grid = Grid(shape=(11, 11))\n x, y = grid.dimensions\n a = Function(name='a', grid=grid)\n a.data[:] = 1.\n\n # Try with an operator w/o stencil offsets\n op = Operator(Eq(a, a + a))\n op(x_m=3, x_M=7)\n assert (a.data[:3, :] == 1.).all()\n assert (a.data[3:7, :] == 2.).all()\n assert (a.data[8:, :] == 1.).all()\n\n # Try with an operator w/ stencil offsets\n a.data[:] = 1.\n op = Operator(Eq(a, a + (a[x-1, y] + a[x+1, y]) / 2.))\n op(x_m=3, x_M=7)\n assert (a.data[:3, :] == 1.).all()\n assert (a.data[3:7, :] >= 2.).all()\n assert (a.data[8:, :] == 1.).all()\n\n def test_argument_unknown(self):\n \"\"\"Check that Operators deal with unknown runtime arguments.\"\"\"\n grid = Grid(shape=(11, 11))\n a = Function(name='a', grid=grid)\n\n op = Operator(Eq(a, a + a))\n try:\n op.apply(b=3)\n assert False\n except ValueError:\n # `b` means nothing to `op`, so we end up here\n assert True\n\n try:\n configuration['ignore-unknowns'] = True\n op.apply(b=3)\n assert True\n except ValueError:\n # we should not end up here as we're now ignoring unknown arguments\n assert False\n finally:\n configuration['ignore-unknowns'] = configuration._defaults['ignore-unknowns']\n\n @pytest.mark.parametrize('so,to,pad,expected', [\n (0, 1, 0, (2, 4, 4, 4)),\n (2, 1, 0, (2, 8, 8, 8)),\n (4, 1, 0, (2, 12, 12, 12)),\n (4, 3, 0, (4, 12, 12, 12)),\n (4, 1, 3, (2, 15, 15, 15)),\n ((2, 5, 2), 1, 0, (2, 11, 11, 11)),\n ((2, 5, 4), 1, 3, (2, 16, 16, 16)),\n ])\n def test_function_dataobj(self, so, to, pad, expected):\n \"\"\"\n Tests that the C-level structs from DiscreteFunctions are properly\n populated upon application of an Operator.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n\n u = TimeFunction(name='u', grid=grid, space_order=so, time_order=to, padding=pad)\n\n op = Operator(Eq(u, 1), opt='noop')\n\n u_arg = op.arguments(time=0)['u']\n u_arg_shape = tuple(u_arg._obj.size[i] for i in range(u.ndim))\n\n assert u_arg_shape == expected\n\n def test_illegal_override(self):\n grid0 = Grid(shape=(11, 11))\n grid1 = Grid(shape=(13, 13))\n\n a0 = Function(name='a', grid=grid0)\n b0 = Function(name='b', grid=grid0)\n a1 = Function(name='a', grid=grid1)\n\n op = Operator(Eq(a0, a0 + b0 + 1))\n op.apply()\n\n try:\n op.apply(a=a1, b=b0)\n assert False\n except ValueError as e:\n assert 'Override' in e.args[0] # Check it's hitting the right error msg\n except:\n assert False\n\n def test_incomplete_override(self):\n \"\"\"\n Simulate a typical user error when one has to supply replacements for lots\n of Functions (a complex Operator) but at least one is forgotten.\n \"\"\"\n grid0 = Grid(shape=(11, 11))\n grid1 = Grid(shape=(13, 13))\n\n a0 = Function(name='a', grid=grid0)\n a1 = Function(name='a', grid=grid1)\n b = Function(name='b', grid=grid0)\n\n op = Operator(Eq(a0, a0 + b + 1))\n op.apply()\n\n try:\n op.apply(a=a1)\n assert False\n except ValueError as e:\n assert 'Default' in e.args[0] # Check it's hitting the right error msg\n except:\n assert False\n\n @skipif('nompi')\n @pytest.mark.parallel(mode=1)\n def test_new_distributor(self):\n \"\"\"\n Test that `comm` and `nb` are correctly updated when a different distributor\n from that it was originally built with is required by an operator.\n Note that MPI is required to ensure `comm` and `nb` are included in op.objects.\n \"\"\"\n from devito.mpi import MPI\n grid = Grid(shape=(10, 10), comm=MPI.COMM_SELF)\n grid2 = Grid(shape=(10, 10), comm=MPI.COMM_WORLD)\n\n u = TimeFunction(name='u', grid=grid, space_order=2)\n u2 = TimeFunction(name='u2', grid=grid2, space_order=2)\n\n # Create some operator that requires MPI communication\n eqn = Eq(u.forward, u + u.laplace)\n op = Operator(eqn)\n assert op.arguments(u=u, time_M=0)['comm'] is grid.distributor._obj_comm.value\n assert (op.arguments(u=u, time_M=0)['nb'] is\n grid.distributor._obj_neighborhood.value)\n assert op.arguments(u=u2, time_M=0)['comm'] is grid2.distributor._obj_comm.value\n assert (op.arguments(u=u2, time_M=0)['nb'] is\n grid2.distributor._obj_neighborhood.value)\n\n def test_spacing_from_new_grid(self):\n \"\"\"\n MFE for issue #1518.\n \"\"\"\n grid = Grid(shape=(10, 10), extent=(9, 9))\n u = Function(name='u', grid=grid, space_order=1)\n\n # A bogus operator that just assigns the x spacing into the array\n # Note, grid.dimensions[0].spacing here is not a number, it's the symbol h_x\n op = Operator(Eq(u, grid.dimensions[0].spacing))\n\n # Create a new grid with different spacing, and a function defined on it\n grid2 = Grid(shape=(5, 5), extent=(9, 9))\n u2 = Function(name='u', grid=grid2, space_order=1)\n op(u=u2)\n\n # The h_x that was passed to the C code must be the one `grid2`, not `grid`\n assert u2.data[2, 2] == grid2.spacing[0]\n\n\n@skipif('device')\nclass TestDeclarator(object):\n\n def test_heap_1D(self):\n i, j = dimensions('i j')\n\n a = Array(name='a', dimensions=(i,))\n b = Array(name='b', dimensions=(i,))\n f = Function(name='f', shape=(3,), dimensions=(j,))\n\n op = Operator([Eq(a[i], a[i] + b[i] + 5.),\n Eq(f[j], a[j])])\n\n assert op.body.casts[2].is_PointerCast\n assert str(op.body.casts[2]) == ('float (*restrict f) __attribute__ '\n '((aligned (64))) = (float (*)) f_vec->data;')\n\n assert str(op.body.allocs[0]) == 'float *a_vec;'\n assert str(op.body.allocs[1]) == ('posix_memalign((void**)&a_vec, 64, '\n 'sizeof(float[i_size]));')\n assert str(op.body.frees[0]) == 'free(a_vec);'\n\n def test_heap_perfect_2D(self):\n i, j, k = dimensions('i j k')\n\n a = Array(name='a', dimensions=(i,))\n c = Array(name='c', dimensions=(i, j))\n f = Function(name='f', shape=(3, 3), dimensions=(j, k))\n\n op = Operator([Eq(a[i], c[i, j]),\n Eq(c[i, j], c[i, j]*a[i]),\n Eq(f[j, k], a[j] + c[j, k])])\n\n assert op.body.casts[2].is_PointerCast\n assert str(op.body.casts[2]) ==\\\n ('float (*restrict f)[f_vec->size[1]] __attribute__ '\n '((aligned (64))) = (float (*)[f_vec->size[1]]) f_vec->data;')\n\n assert str(op.body.allocs[0]) == 'float *a_vec;'\n assert str(op.body.allocs[1]) == ('posix_memalign((void**)&a_vec, 64, '\n 'sizeof(float[i_size]));')\n assert str(op.body.allocs[2]) == 'float *c_vec;'\n assert str(op.body.allocs[3]) == ('posix_memalign((void**)&c_vec, 64, '\n 'sizeof(float[i_size][j_size]));')\n assert str(op.body.frees[0]) == 'free(a_vec);'\n assert str(op.body.frees[1]) == 'free(c_vec);'\n\n def test_heap_imperfect_2D(self):\n i, j, k = dimensions('i j k')\n\n a = Array(name='a', dimensions=(i,))\n c = Array(name='c', dimensions=(i, j))\n f = Function(name='f', shape=(3, 3), dimensions=(j, k))\n\n op = Operator([Eq(a[i], 0),\n Eq(c[i, j], c[i, j]*a[i]),\n Eq(f[j, k], a[j] + c[j, k])])\n\n assert op.body.casts[2].is_PointerCast\n assert str(op.body.casts[2]) ==\\\n ('float (*restrict f)[f_vec->size[1]] __attribute__ '\n '((aligned (64))) = (float (*)[f_vec->size[1]]) f_vec->data;')\n\n assert str(op.body.allocs[0]) == 'float *a_vec;'\n assert str(op.body.allocs[1]) == ('posix_memalign((void**)&a_vec, 64, '\n 'sizeof(float[i_size]));')\n assert str(op.body.allocs[2]) == 'float *c_vec;'\n assert str(op.body.allocs[3]) == ('posix_memalign((void**)&c_vec, 64, '\n 'sizeof(float[i_size][j_size]));')\n assert str(op.body.frees[0]) == 'free(a_vec);'\n assert str(op.body.frees[1]) == 'free(c_vec);'\n\n def test_stack_scalars(self):\n i, j = dimensions('i j')\n\n a = Array(name='a', dimensions=(i,))\n f = Function(name='f', shape=(3,), dimensions=(j,))\n t0 = Scalar(name='t0')\n t1 = Scalar(name='t1')\n\n op = Operator([Eq(t0, 1.),\n Eq(t1, 2.),\n Eq(a[i], t0*t1*3.),\n Eq(f, a[j])])\n\n assert op.body.casts[1].is_PointerCast\n assert str(op.body.casts[1]) ==\\\n ('float (*restrict f) __attribute__ '\n '((aligned (64))) = (float (*)) f_vec->data;')\n\n assert str(op.body.allocs[0]) == 'float *a_vec;'\n assert str(op.body.allocs[1]) == ('posix_memalign((void**)&a_vec, 64, '\n 'sizeof(float[i_size]));')\n assert str(op.body.frees[0]) == 'free(a_vec);'\n\n assert op.body.body[1].body[0].is_ExpressionBundle\n assert str(op.body.body[1].body[0].body[0]) == 'float t0 = 1.00000000000000F;'\n assert str(op.body.body[1].body[0].body[1]) == 'float t1 = 2.00000000000000F;'\n\n def test_stack_arrays(self):\n i, j, k, s, q = dimensions('i j k s q')\n\n c = Array(name='c', dimensions=(i, j), scope='stack')\n e = Array(name='e', dimensions=(k, s, q, i, j))\n f = Function(name='f', shape=(3, 3), dimensions=(s, q))\n\n op = Operator([Eq(c[i, j], e[k, s, q, i, j]*1.),\n Eq(f, c[s, q])])\n\n assert op.body.casts[0].is_PointerCast\n assert str(op.body.casts[0]) ==\\\n ('float (*restrict c)[j_size] __attribute__ ((aligned (64))) = '\n '(float (*)[j_size]) c_vec;')\n assert op.body.casts[2].is_PointerCast\n assert str(op.body.casts[2]) ==\\\n ('float (*restrict f)[f_vec->size[1]] __attribute__ '\n '((aligned (64))) = (float (*)[f_vec->size[1]]) f_vec->data;')\n\n assert str(op.body.allocs[0]) ==\\\n 'float c_vec[i_size][j_size] __attribute__((aligned(64)));'\n\n def test_conditional_declarations(self):\n x = Dimension(name=\"x\")\n a = Array(name='a', dimensions=(x,), dtype=np.int32, scope='stack')\n init_value = ListInitializer([0, 0])\n list_initialize = Expression(ClusterizedEq(Eq(a[x], init_value)))\n iet = Conditional(x < 3, list_initialize, list_initialize)\n iet = Callable('test', iet, 'void')\n iet = DataManager.place_definitions.__wrapped__(DataManager(None, None), iet)[0]\n for i in iet.body.body[0].children:\n assert len(i) == 1\n assert i[0].is_Expression\n assert i[0].expr.rhs is init_value\n\n\nclass TestLoopScheduling(object):\n\n def test_permutations_without_deps(self):\n \"\"\"\n Test that if none of the Function accesses in the equations use\n offsets, implying that there are no carried dependences, then no\n matter the order in which the equations are provided to an Operator\n the resulting loop nest is the same, and the input ordering of the\n equations is honored.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n\n ti0 = Function(name='ti0', grid=grid)\n ti1 = Function(name='ti1', grid=grid)\n tu = TimeFunction(name='tu', grid=grid)\n tv = TimeFunction(name='tv', grid=grid)\n\n eq1 = Eq(tu, tv*ti0 + ti0)\n eq2 = Eq(ti0, tu + 3.)\n eq3 = Eq(tv, ti0*ti1)\n op1 = Operator([eq1, eq2, eq3], opt='noop')\n op2 = Operator([eq2, eq1, eq3], opt='noop')\n op3 = Operator([eq3, eq2, eq1], opt='noop')\n\n trees = [retrieve_iteration_tree(i) for i in [op1, op2, op3]]\n assert all(len(i) == 1 for i in trees)\n trees = [i[0] for i in trees]\n for tree in trees:\n assert IsPerfectIteration().visit(tree[1])\n exprs = FindNodes(Expression).visit(tree[-1])\n assert len(exprs) == 3\n\n @pytest.mark.parametrize('exprs,fissioned,shared', [\n # 0) Trivial case\n (('Eq(u, 1)', 'Eq(v, u.dxl)'), '(1,x)', [0]),\n # 1) Anti-dependence along x\n (('Eq(u, 1)', 'Eq(v, u.dxr)'), '(1,x)', [0]),\n # 2, 3) As above, but with an additional Dimension-independent dependence\n (('Eq(u, v)', 'Eq(v, u.dxl)'), '(1,x)', [0]),\n (('Eq(u, v)', 'Eq(v, u.dxr)'), '(1,x)', [0]),\n # 4) Slightly more convoluted than above, as the additional dependence is\n # now carried along x\n (('Eq(u, v)', 'Eq(v, u.dxr)'), '(1,x)', [0]),\n # 5) No backward carried dependences, no storage related dependences\n (('Eq(us.forward, vs)', 'Eq(vs, us.dxl)'), '(0,time)', []),\n # 6) No backward carried dependences, no storage related dependences\n (('Eq(us.forward, vs)', 'Eq(vs, us.dxr)'), '(0,time)', []),\n # 7) Three fissionable Eqs\n (('Eq(u, u.dxl + v.dxr)', 'Eq(v, w.dxr)', 'Eq(w, u*w.dxl)'), '(1,x)', [0]),\n # 8) There are carried backward dependences, but not in the Dimension\n # that gets fissioned\n (('Eq(u.forward, u + v.dx)', 'Eq(v.forward, v + u.forward.dx)'), '(1,x)', [0])\n ])\n def test_fission_for_parallelism(self, exprs, fissioned, shared):\n \"\"\"\n Test that expressions are scheduled to separate loops if this can\n turn one sequential loop into two parallel loops (\"loop fission\").\n \"\"\"\n grid = Grid(shape=(3, 3))\n t = grid.stepping_dim # noqa\n time = grid.time_dim # noqa\n x, y = grid.dimensions # noqa\n\n u = TimeFunction(name='u', grid=grid) # noqa\n v = TimeFunction(name='v', grid=grid) # noqa\n w = TimeFunction(name='w', grid=grid) # noqa\n us = TimeFunction(name='u', grid=grid, save=5) # noqa\n vs = TimeFunction(name='v', grid=grid, save=5) # noqa\n\n # List comprehension would need explicit locals/globals mappings to eval\n eqns = []\n for e in exprs:\n eqns.append(eval(e))\n\n # `opt='noop'` is only to avoid loop blocking, hence making the asserts\n # below much simpler to write and understand\n op = Operator(eqns, opt='noop')\n\n # Fission expected\n trees = retrieve_iteration_tree(op)\n assert len(trees) == len(eqns)\n\n exp_depth, exp_dim = eval(fissioned)\n for i in trees:\n # Some outer loops may still be shared\n for j in shared:\n assert i[j] is trees[0][j]\n # Fission happened\n assert i[exp_depth].dim is exp_dim\n\n @pytest.mark.parametrize('exprs', [\n # 0) Storage related dependence\n ('Eq(u.forward, v)', 'Eq(v, u.dxl)'),\n # 1) Backward carried flow-dependence through `v`\n ('Eq(u, v.forward)', 'Eq(v, u)'),\n # 2) Backward carried flow-dependence through `vs`\n ('Eq(us.forward, vs)', 'Eq(vs.forward, us.dxl)'),\n # 3) Classic coupled forward-marching equations\n ('Eq(u.forward, u + u.backward + v)', 'Eq(v.forward, v + v.backward + u)'),\n # 4) Three non-fissionable Eqs\n ('Eq(u, v.dxl)', 'Eq(v, w.dxl)', 'Eq(w, u*w.dxl)')\n ])\n def test_no_fission_as_illegal(self, exprs):\n \"\"\"\n Antithesis of `test_fission_for_parallelism`.\n \"\"\"\n grid = Grid(shape=(3, 3))\n x, y = grid.dimensions\n\n u = TimeFunction(name='u', grid=grid) # noqa\n v = TimeFunction(name='v', grid=grid) # noqa\n w = TimeFunction(name='w', grid=grid) # noqa\n us = TimeFunction(name='u', grid=grid, save=5) # noqa\n vs = TimeFunction(name='v', grid=grid, save=5) # noqa\n\n # List comprehension would need explicit locals/globals mappings to eval\n eqns = []\n for e in exprs:\n eqns.append(eval(e))\n\n op = Operator(eqns)\n\n # No fission expected\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 1\n\n @pytest.mark.parametrize('exprs,directions,expected,visit', [\n # 0) WAR 2->3, 3 fissioned to maximize parallelism\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti3[x,y,z])',\n 'Eq(ti3[x,y,z], ti1[x,y,z+1] + 1.)'),\n '+++++', ['xyz', 'xyz', 'xyz'], 'xyzzz'),\n # 1) WAR 1->2, 2->3\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti0[x,y,z+1])',\n 'Eq(ti3[x,y,z], ti1[x,y,z-2] + 1.)'),\n '+++++', ['xyz', 'xyz', 'xyz'], 'xyzzz'),\n # 2) WAR 1->2, 2->3, RAW 2->3\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti0[x,y,z+1])',\n 'Eq(ti3[x,y,z], ti1[x,y,z-2] + ti1[x,y,z+2])'),\n '+++++', ['xyz', 'xyz', 'xyz'], 'xyzzz'),\n # 3) WAR 1->3\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti3[x,y,z])',\n 'Eq(ti3[x,y,z], ti0[x,y,z+1] + 1.)'),\n '++++', ['xyz', 'xyz'], 'xyzz'),\n # 4) WAR 1->3\n # Like before, but the WAR is along `y`, an inner Dimension\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti3[x,y,z])',\n 'Eq(ti3[x,y,z], ti0[x,y+1,z] + 1.)'),\n '+++++', ['xyz', 'xyz'], 'xyzyz'),\n # 5) WAR 1->2, 2->3; WAW 1->3\n # Similar to the cases above, but the last equation does not iterate over `z`\n (('Eq(ti0[x,y,z], ti0[x,y,z] + ti1[x,y,z])',\n 'Eq(ti1[x,y,z], ti0[x,y,z+2])',\n 'Eq(ti0[x,y,0], ti0[x,y,0] + 1.)'),\n '++++', ['xyz', 'xyz', 'xy'], 'xyzz'),\n # 6) WAR 1->2; WAW 1->3\n # Basically like above, but with the time dimension. This should have no impact\n (('Eq(tu[t,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x,y,z+2])',\n 'Eq(tu[t,x,y,0], tu[t,x,y,0] + 1.)'),\n '+++++', ['txyz', 'txyz', 'txy'], 'txyzz'),\n # 7) WAR 1->2, 2->3\n (('Eq(tu[t,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x,y,z+2])',\n 'Eq(tw[t,x,y,z], tv[t,x,y,z-1] + 1.)'),\n '++++++', ['txyz', 'txyz', 'txyz'], 'txyzzz'),\n # 8) WAR 1->2; WAW 1->3\n (('Eq(tu[t,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x+2,y,z])',\n 'Eq(tu[t,3,y,0], tu[t,3,y,0] + 1.)'),\n '++++++++', ['txyz', 'txyz', 'ty'], 'txyzxyzy'),\n # 9) RAW 1->2, WAR 2->3\n (('Eq(tu[t,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x,y,z-2])',\n 'Eq(tw[t,x,y,z], tv[t,x,y+1,z] + 1.)'),\n '++++++++', ['txyz', 'txyz', 'txyz'], 'txyzyzyz'),\n # 10) WAR 1->2; WAW 1->3\n (('Eq(tu[t-1,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x,y,z+2])',\n 'Eq(tu[t-1,x,y,0], tu[t,x,y,0] + 1.)'),\n '-+++', ['txyz', 'txy'], 'txyz'),\n # 11) WAR 1->2\n (('Eq(tu[t-1,x,y,z], tu[t,x,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t,x,y,z], tu[t,x,y,z+2] + tu[t,x,y,z-2])',\n 'Eq(tw[t,x,y,z], tv[t,x,y,z] + 2)'),\n '-+++', ['txyz'], 'txyz'),\n # 12) Time goes backward so that information flows in time\n (('Eq(tu[t-1,x,y,z], tu[t,x+3,y,z] + tv[t,x,y,z])',\n 'Eq(tv[t-1,x,y,z], tu[t,x,y,z+2])',\n 'Eq(tw[t-1,x,y,z], tu[t,x,y+1,z] + tv[t,x,y-1,z])'),\n '-+++', ['txyz'], 'txyz'),\n # 13) Time goes backward so that information flows in time, but the\n # first and last Eqs are interleaved by a completely independent\n # Eq. This results in three disjoint sets of loops\n (('Eq(tu[t-1,x,y,z], tu[t,x+3,y,z] + tv[t,x,y,z])',\n 'Eq(ti0[x,y,z], ti1[x,y,z+2])',\n 'Eq(tw[t-1,x,y,z], tu[t,x,y+1,z] + tv[t,x,y-1,z])'),\n '-++++++++++', ['txyz', 'xyz', 'txyz'], 'txyzxyztxyz'),\n # 14) Time goes backward so that information flows in time\n (('Eq(ti0[x,y,z], ti1[x,y,z+2])',\n 'Eq(tu[t-1,x,y,z], tu[t,x+3,y,z] + tv[t,x,y,z])',\n 'Eq(tw[t-1,x,y,z], tu[t,x,y+1,z] + ti0[x,y-1,z])'),\n '+++-+++', ['xyz', 'txyz'], 'xyztxyz'),\n # 15) WAR 2->1\n # Here the difference is that we're using SubDimensions\n (('Eq(tv[t,xi,yi,zi], tu[t,xi-1,yi,zi] + tu[t,xi+1,yi,zi])',\n 'Eq(tu[t+1,xi,yi,zi], tu[t,xi,yi,zi] + tv[t,xi-1,yi,zi] + tv[t,xi+1,yi,zi])'),\n '+++++++', ['ti0xi0yi0z', 'ti0xi0yi0z'], 'ti0xi0yi0zi0xi0yi0z'),\n # 16) RAW 3->1; expected=2\n # Time goes backward, but the third equation should get fused with\n # the first one, as the time dependence is loop-carried\n (('Eq(tv[t-1,x,y,z], tv[t,x-1,y,z] + tv[t,x+1,y,z])',\n 'Eq(tv[t-1,z,z,z], tv[t-1,z,z,z] + 1)',\n 'Eq(f[x,y,z], tu[t-1,x,y,z] + tu[t,x,y,z] + tu[t+1,x,y,z] + tv[t,x,y,z])'),\n '-++++', ['txyz', 'tz'], 'txyzz'),\n # 17) WAR 2->3, 2->4; expected=4\n (('Eq(tu[t+1,x,y,z], tu[t,x,y,z] + 1.)',\n 'Eq(tu[t+1,y,y,y], tu[t+1,y,y,y] + tw[t+1,y,y,y])',\n 'Eq(tw[t+1,z,z,z], tw[t+1,z,z,z] + 1.)',\n 'Eq(tv[t+1,x,y,z], tu[t+1,x,y,z] + 1.)'),\n '+++++++++', ['txyz', 'ty', 'tz', 'txyz'], 'txyzyzxyz'),\n # 18) WAR 1->3; expected=3\n # 5 is expected to be moved before 4 but after 3, to be merged with 3\n (('Eq(tu[t+1,x,y,z], tv[t,x,y,z] + 1.)',\n 'Eq(tv[t+1,x,y,z], tu[t,x,y,z] + 1.)',\n 'Eq(tw[t+1,x,y,z], tu[t+1,x+1,y,z] + tu[t+1,x-1,y,z])',\n 'Eq(f[x,x,z], tu[t,x,x,z] + tw[t,x,x,z])',\n 'Eq(ti0[x,y,z], tw[t+1,x,y,z] + 1.)'),\n '++++++++', ['txyz', 'txyz', 'txz'], 'txyzxyzz'),\n # 19) WAR 1->3; expected=3\n # Cannot merge 1 with 3 otherwise we would break an anti-dependence\n (('Eq(tv[t+1,x,y,z], tu[t,x,y,z] + tu[t,x+1,y,z])',\n 'Eq(tu[t+1,xi,yi,zi], tv[t+1,xi,yi,zi] + tv[t+1,xi+1,yi,zi])',\n 'Eq(tw[t+1,x,y,z], tv[t+1,x,y,z] + tv[t+1,x+1,y,z])'),\n '++++++++++', ['txyz', 'ti0xi0yi0z', 'txyz'], 'txyzi0xi0yi0zxyz'),\n ])\n def test_consistency_anti_dependences(self, exprs, directions, expected, visit):\n \"\"\"\n Test that anti dependences end up generating multi loop nests, rather\n than a single loop nest enclosing all of the equations.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions # noqa\n xi, yi, zi = grid.interior.dimensions # noqa\n t = grid.stepping_dim # noqa\n\n ti0 = Array(name='ti0', shape=grid.shape, dimensions=grid.dimensions) # noqa\n ti1 = Array(name='ti1', shape=grid.shape, dimensions=grid.dimensions) # noqa\n ti3 = Array(name='ti3', shape=grid.shape, dimensions=grid.dimensions) # noqa\n f = Function(name='f', grid=grid) # noqa\n tu = TimeFunction(name='tu', grid=grid) # noqa\n tv = TimeFunction(name='tv', grid=grid) # noqa\n tw = TimeFunction(name='tw', grid=grid) # noqa\n\n # List comprehension would need explicit locals/globals mappings to eval\n eqns = []\n for e in exprs:\n eqns.append(eval(e))\n\n # Note: `topofuse` is a subset of `advanced` mode. We use it merely to\n # bypass 'blocking', which would complicate the asserts below\n op = Operator(eqns, opt=('topofuse', {'openmp': False}))\n\n trees = retrieve_iteration_tree(op)\n iters = FindNodes(Iteration).visit(op)\n assert len(trees) == len(expected)\n assert len(iters) == len(directions)\n # mapper just makes it quicker to write out the test parametrization\n mapper = {'time': 't'}\n assert [\"\".join(mapper.get(i.dim.name, i.dim.name) for i in j)\n for j in trees] == expected\n assert \"\".join(mapper.get(i.dim.name, i.dim.name) for i in iters) == visit\n # mapper just makes it quicker to write out the test parametrization\n mapper = {'+': Forward, '-': Backward, '*': Any}\n assert all(i.direction == mapper[j] for i, j in zip(iters, directions))\n\n def test_expressions_imperfect_loops(self):\n \"\"\"\n Test that equations depending only on a subset of all indices\n appearing across all equations are placed within earlier loops\n in the loop nest tree.\n \"\"\"\n grid = Grid(shape=(3, 3, 3))\n x, y, z = grid.dimensions\n\n t0 = Constant(name='t0')\n t1 = Scalar(name='t1')\n e = Function(name='e', shape=(3,), dimensions=(x,), space_order=0)\n f = Function(name='f', shape=(3, 3), dimensions=(x, y), space_order=0)\n g = Function(name='g', grid=grid, space_order=0)\n h = Function(name='h', grid=grid, space_order=0)\n\n eq0 = Eq(t1, e*1.)\n eq1 = Eq(f, t0*3. + t1)\n eq2 = Eq(h, g + 4. + f*5.)\n op = Operator([eq0, eq1, eq2], opt='noop')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 3\n outer, middle, inner = trees\n assert len(outer) == 1 and len(middle) == 2 and len(inner) == 3\n assert outer[0] == middle[0] == inner[0]\n assert middle[1] == inner[1]\n assert outer[-1].nodes[0].exprs[0].expr.rhs == diff2sympy(indexify(eq0.rhs))\n assert middle[-1].nodes[0].exprs[0].expr.rhs == diff2sympy(indexify(eq1.rhs))\n assert inner[-1].nodes[0].exprs[0].expr.rhs == diff2sympy(indexify(eq2.rhs))\n\n def test_equations_emulate_bc(self):\n \"\"\"\n Test that bc-like equations get inserted into the same loop nest\n as the \"main\" equations.\n \"\"\"\n grid = Grid(shape=(3, 3, 3))\n x, y, z = grid.dimensions\n time = grid.time_dim\n t0 = Scalar(name='t0')\n a = Function(name='a', grid=grid)\n b = TimeFunction(name='b', grid=grid, save=6)\n main = Eq(b[time + 1, x, y, z], b[time - 1, x, y, z] + a[x, y, z] + 3.*t0)\n bcs = [Eq(b[time, 0, y, z], 0.),\n Eq(b[time, x, 0, z], 0.),\n Eq(b[time, x, y, 0], 0.)]\n op = Operator([main] + bcs, opt='noop')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 4\n assert all(id(trees[0][0]) == id(i[0]) for i in trees)\n\n def test_different_section_nests(self):\n grid = Grid((3, 3, 3))\n tu = TimeFunction(name='tu', grid=grid, space_order=4)\n t0 = Scalar(name='t0')\n t1 = Scalar(name='t1')\n ti0 = Array(name='ti0', shape=(3, 5, 7), dimensions=grid.dimensions,\n scope='heap').indexify()\n eq1 = Eq(ti0, t0*3.)\n eq2 = Eq(tu, ti0 + t1*3.)\n op = Operator([eq1, eq2], opt='noop')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 2\n assert trees[0][-1].nodes[0].exprs[0].expr.rhs == eq1.rhs\n assert trees[1][-1].nodes[0].exprs[0].expr.rhs == eq2.rhs\n\n @pytest.mark.parametrize('exprs', [\n ['Eq(ti0[x,y,z], ti0[x,y,z] + t0*2.)', 'Eq(ti0[0,0,z], 0.)'],\n ['Eq(ti0[x,y,z], ti0[x,y,z-1] + t0*2.)', 'Eq(ti0[0,0,z], 0.)'],\n ['Eq(ti0[x,y,z], ti0[x,y,z] + t0*2.)', 'Eq(ti0[0,y,0], 0.)'],\n ['Eq(ti0[x,y,z], ti0[x,y,z] + t0*2.)', 'Eq(ti0[0,y,z], 0.)'],\n ])\n def test_directly_indexed_expression(self, exprs):\n \"\"\"\n Test that equations using integer indices are inserted in the right\n loop nest, at the right loop nest depth.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions # noqa\n\n ti0 = Function(name='ti0', grid=grid, space_order=0) # noqa\n t0 = Scalar(name='t0') # noqa\n\n eqs = [eval(exprs[0]), eval(exprs[1])]\n\n op = Operator(eqs, opt='noop')\n\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 2\n assert trees[0][-1].nodes[0].exprs[0].expr.rhs == eqs[0].rhs\n assert trees[1][-1].nodes[0].exprs[0].expr.rhs == eqs[1].rhs\n\n @pytest.mark.parametrize('shape', [(11, 11), (11, 11, 11)])\n def test_equations_mixed_functions(self, shape):\n \"\"\"\n Test that equations using a mixture of Function and TimeFunction objects\n are embedded within the same time loop.\n \"\"\"\n dims0 = Grid(shape).dimensions\n for dims in permutations(dims0):\n grid = Grid(shape=shape, dimensions=dims, dtype=np.float64)\n time = grid.time_dim\n a = TimeFunction(name='a', grid=grid, time_order=2, space_order=2)\n p_aux = Dimension(name='p_aux')\n b = Function(name='b', shape=shape + (10,), dimensions=dims + (p_aux,),\n space_order=2, dtype=np.float64)\n b.data_with_halo[:] = 1.0\n b2 = Function(name='b2', shape=(10,) + shape, dimensions=(p_aux,) + dims,\n space_order=2, dtype=np.float64)\n b2.data_with_halo[:] = 1.0\n eqns = [Eq(a.forward, a.laplace + 1.),\n Eq(b, time*b*a + b)]\n eqns2 = [Eq(a.forward, a.laplace + 1.),\n Eq(b2, time*b2*a + b2)]\n subs = {d.spacing: v for d, v in zip(dims0, [2.5, 1.5, 2.0][:grid.dim])}\n\n op = Operator(eqns, subs=subs, opt='noop')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 2\n assert all(trees[0][i] is trees[1][i] for i in range(3))\n\n op2 = Operator(eqns2, subs=subs, opt='noop')\n trees = retrieve_iteration_tree(op2)\n assert len(trees) == 2\n\n # Verify both operators produce the same result\n op(time=10)\n a.data_with_halo[:] = 0.\n op2(time=10)\n\n for i in range(10):\n assert(np.allclose(b2.data[i, ...].reshape(-1),\n b.data[..., i].reshape(-1),\n rtol=1e-9))\n\n def test_equations_mixed_timedim_stepdim(self):\n \"\"\"\"\n Test that two equations one using a TimeDimension the other a derived\n SteppingDimension end up in the same loop nest.\n \"\"\"\n grid = Grid(shape=(3, 3, 3))\n x, y, z = grid.dimensions\n time = grid.time_dim\n t = grid.stepping_dim\n u1 = TimeFunction(name='u1', grid=grid)\n u2 = TimeFunction(name='u2', grid=grid, save=2)\n eqn_1 = Eq(u1[t+1, x, y, z], u1[t, x, y, z] + 1.)\n eqn_2 = Eq(u2[time+1, x, y, z], u2[time, x, y, z] + 1.)\n op = Operator([eqn_1, eqn_2], opt='topofuse')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 1\n assert len(trees[0][-1].nodes[0].exprs) == 2\n assert trees[0][-1].nodes[0].exprs[0].write == u1\n assert trees[0][-1].nodes[0].exprs[1].write == u2\n\n def test_flow_detection(self):\n \"\"\"\n Test detection of spatial flow directions inside a time loop.\n\n Stencil uses values at new timestep as well as those at previous ones\n This forces an evaluation order onto x.\n Weights are:\n\n x=0 x=1 x=2 x=3\n t=n 2 ---3\n v /\n t=n+1 o--+----4\n\n Flow dependency should traverse x in the negative direction\n\n x=2 x=3 x=4 x=5 x=6\n t=0 0 --- 0 -- 1 -- 0\n v / v / v /\n t=1 44 -+--- 11 -+--- 2--+ -- 0\n \"\"\"\n grid = Grid(shape=(10, 10))\n x, y = grid.dimensions\n u = TimeFunction(name='u', grid=grid, save=2, time_order=1, space_order=0)\n step = Eq(u.forward, 2*u\n + 3*u.subs(x, x+x.spacing)\n + 4*u.forward.subs(x, x+x.spacing))\n op = Operator(step)\n\n u.data[:] = 0.0\n u.data[0, 5, 5] = 1.0\n\n op.apply(time_M=0)\n assert u.data[1, 5, 5] == 2\n assert u.data[1, 4, 5] == 11\n assert u.data[1, 3, 5] == 44\n assert u.data[1, 2, 5] == 4*44\n assert u.data[1, 1, 5] == 4*4*44\n assert u.data[1, 0, 5] == 4*4*4*44\n assert np.all(u.data[1, 6:, :] == 0)\n assert np.all(u.data[1, :, 0:5] == 0)\n assert np.all(u.data[1, :, 6:] == 0)\n\n def test_scheduling_sparse_functions(self):\n \"\"\"Tests loop scheduling in presence of sparse functions.\"\"\"\n grid = Grid((10, 10))\n time = grid.time_dim\n\n u1 = TimeFunction(name=\"u1\", grid=grid, save=10, time_order=2)\n u2 = TimeFunction(name=\"u2\", grid=grid, time_order=2)\n sf1 = SparseTimeFunction(name='sf1', grid=grid, npoint=1, nt=10)\n sf2 = SparseTimeFunction(name='sf2', grid=grid, npoint=1, nt=10)\n\n # Deliberately inject into u1, rather than u1.forward, to create a WAR w/ eqn3\n eqn1 = Eq(u1.forward, u1 + 2.0 - u1.backward)\n eqn2 = sf1.inject(u1, expr=sf1)\n eqn3 = Eq(u2.forward, u2 + 2*u2.backward - u1.dt2)\n eqn4 = sf2.interpolate(u2)\n\n # Note: opts disabled only because with OpenMP otherwise there might be more\n # `trees` than 4\n op = Operator([eqn1] + eqn2 + [eqn3] + eqn4, opt=('noop', {'openmp': False}))\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 4\n # Time loop not shared due to the WAR\n assert trees[0][0].dim is time and trees[0][0] is trees[1][0] # this IS shared\n assert trees[1][0] is not trees[2][0]\n assert trees[2][0].dim is time and trees[2][0] is trees[3][0] # this IS shared\n\n # Now single, shared time loop expected\n eqn2 = sf1.inject(u1.forward, expr=sf1)\n op = Operator([eqn1] + eqn2 + [eqn3] + eqn4, opt=('noop', {'openmp': False}))\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 4\n assert all(trees[0][0] is i[0] for i in trees)\n\n def test_scheduling_with_free_dims(self):\n \"\"\"Tests loop scheduling in presence of free dimensions.\"\"\"\n grid = Grid((4, 4))\n time = grid.time_dim\n x, y = grid.dimensions\n\n u = TimeFunction(name=\"u\", grid=grid)\n f = Function(name=\"f\", grid=grid)\n\n eq0 = Eq(u.forward, u + 1)\n eq1 = Eq(f, time*2)\n\n # Note that `eq1` doesn't impose any constraint on the ordering of\n # the `time` Dimension w.r.t. the `grid` Dimensions, as `time` appears\n # as a free Dimension and not within an array access such as [time, x, y]\n op = Operator([eq0, eq1], opt='topofuse')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 1\n tree = trees[0]\n assert len(tree) == 3\n assert tree[0].dim is time\n assert tree[1].dim is x\n assert tree[2].dim is y\n" ]
[ [ "numpy.allclose", "numpy.array_equal", "numpy.asarray", "numpy.arange", "numpy.ones", "numpy.all", "numpy.zeros_like", "numpy.where", "numpy.sum", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yiman00/ibllib
[ "7fe5dcba1edd40ea05c974fe8b8584001c6c0c15" ]
[ "ibllib/io/spikeglx.py" ]
[ "import json\nimport logging\nfrom pathlib import Path\nimport re\n\nimport numpy as np\n\nimport mtscomp\nfrom brainbox.core import Bunch\nfrom ibllib.ephys import neuropixel as neuropixel\nfrom ibllib.io import hashfile\n\nSAMPLE_SIZE = 2 # int16\nDEFAULT_BATCH_SIZE = 1e6\n_logger = logging.getLogger('ibllib')\n\n\nclass Reader:\n \"\"\"\n Class for SpikeGLX reading purposes\n Some format description was found looking at the Matlab SDK here\n https://github.com/billkarsh/SpikeGLX/blob/master/MATLAB-SDK/DemoReadSGLXData.m\n \"\"\"\n def __init__(self, sglx_file):\n self.file_bin = Path(sglx_file)\n self.nbytes = self.file_bin.stat().st_size\n file_meta_data = Path(sglx_file).with_suffix('.meta')\n if not file_meta_data.exists():\n self.file_meta_data = None\n self.meta = None\n self.channel_conversion_sample2v = 1\n _logger.warning(str(sglx_file) + \" : no metadata file found. Very limited support\")\n return\n # normal case we continue reading and interpreting the metadata file\n self.file_meta_data = file_meta_data\n self.meta = read_meta_data(file_meta_data)\n self.channel_conversion_sample2v = _conversion_sample2v_from_meta(self.meta)\n # if we are not looking at a compressed file, use a memmap, otherwise instantiate mtscomp\n if self.is_mtscomp:\n self._raw = mtscomp.Reader()\n self._raw.open(self.file_bin, self.file_bin.with_suffix('.ch'))\n else:\n if self.nc * self.ns * 2 != self.nbytes:\n ftsec = self.file_bin.stat().st_size / 2 / self.nc / self.fs\n _logger.warning(f\"{sglx_file} : meta data and filesize do not checkout\\n\"\n f\"File size: expected {self.meta['fileSizeBytes']},\"\n f\" actual {self.file_bin.stat().st_size}\\n\"\n f\"File duration: expected {self.meta['fileTimeSecs']},\"\n f\" actual {ftsec}\\n\"\n f\"Will attempt to fudge the meta-data information.\")\n self.meta['fileTimeSecs'] = ftsec\n self._raw = np.memmap(sglx_file, dtype='int16', mode='r', shape=(self.ns, self.nc))\n\n def __getitem__(self, item):\n if isinstance(item, int) or isinstance(item, slice):\n return self.read(nsel=item, sync=False)\n elif len(item) == 2:\n return self.read(nsel=item[0], csel=item[1], sync=False)\n\n @property\n def shape(self):\n return self.ns, self.nc\n\n @property\n def is_mtscomp(self):\n return 'cbin' in self.file_bin.suffix\n\n @property\n def version(self):\n \"\"\":return: \"\"\"\n if not self.meta:\n return None\n return _get_neuropixel_version_from_meta(self.meta)\n\n @property\n def type(self):\n \"\"\":return: ap, lf or nidq. Useful to index dictionaries \"\"\"\n if not self.meta:\n return 0\n return _get_type_from_meta(self.meta)\n\n @property\n def fs(self):\n \"\"\" :return: sampling frequency (Hz) \"\"\"\n if not self.meta:\n return 1\n return _get_fs_from_meta(self.meta)\n\n @property\n def nc(self):\n \"\"\" :return: number of channels \"\"\"\n if not self.meta:\n return\n return _get_nchannels_from_meta(self.meta)\n\n @property\n def ns(self):\n \"\"\" :return: number of samples \"\"\"\n if not self.meta:\n return\n return int(np.round(self.meta.get('fileTimeSecs') * self.fs))\n\n def read(self, nsel=slice(0, 10000), csel=slice(None), sync=True):\n \"\"\"\n Read from slices or indexes\n :param slice_n: slice or sample indices\n :param slice_c: slice or channel indices\n :return: float32 array\n \"\"\"\n darray = np.float32(self._raw[nsel, csel])\n darray *= self.channel_conversion_sample2v[self.type][csel]\n if sync:\n return darray, self.read_sync(nsel)\n else:\n return darray\n\n def read_samples(self, first_sample=0, last_sample=10000, channels=None):\n \"\"\"\n reads all channels from first_sample to last_sample, following numpy slicing convention\n sglx.read_samples(first=0, last=100) would be equivalent to slicing the array D\n D[:,0:100] where the last axis represent time and the first channels.\n\n :param first_sample: first sample to be read, python slice-wise\n :param last_sample: last sample to be read, python slice-wise\n :param channels: slice or numpy array of indices\n :return: numpy array of int16\n \"\"\"\n if channels is None:\n channels = slice(None)\n return self.read(slice(first_sample, last_sample), channels)\n\n def read_sync_digital(self, _slice=slice(0, 10000)):\n \"\"\"\n Reads only the digital sync trace at specified samples using slicing syntax\n >>> sync_samples = sr.read_sync_digital(slice(0,10000))\n \"\"\"\n if not self.meta:\n _logger.warning('Sync trace not labeled in metadata. Assuming last trace')\n return split_sync(self._raw[_slice, _get_sync_trace_indices_from_meta(self.meta)])\n\n def read_sync_analog(self, _slice=slice(0, 10000)):\n \"\"\"\n Reads only the analog sync traces at specified samples using slicing syntax\n >>> sync_samples = sr.read_sync_analog(slice(0,10000))\n \"\"\"\n if not self.meta:\n return\n csel = _get_analog_sync_trace_indices_from_meta(self.meta)\n if not csel:\n return\n else:\n return self.read(nsel=_slice, csel=csel, sync=False)\n\n def read_sync(self, _slice=slice(0, 10000), threshold=1.2):\n \"\"\"\n Reads all sync trace. Convert analog to digital with selected threshold and append to array\n :param _slice: samples slice\n :param threshold: (V) threshold for front detection, defaults to 1.2 V\n :return: int8 array\n \"\"\"\n digital = self.read_sync_digital(_slice)\n analog = self.read_sync_analog(_slice)\n if analog is None:\n return digital\n analog[np.where(analog < threshold)] = 0\n analog[np.where(analog >= threshold)] = 1\n return np.concatenate((digital, np.int8(analog)), axis=1)\n\n def compress_file(self, keep_original=True, **kwargs):\n \"\"\"\n Compresses\n :param keep_original: defaults True. If False, the original uncompressed file is deleted\n and the current spikeglx.Reader object is modified in place\n :param kwargs:\n :return: pathlib.Path of the compressed *.cbin file\n \"\"\"\n file_tmp = self.file_bin.with_suffix('.cbin_tmp')\n assert not self.is_mtscomp\n mtscomp.compress(self.file_bin,\n out=file_tmp,\n outmeta=self.file_bin.with_suffix('.ch'),\n sample_rate=self.fs,\n n_channels=self.nc,\n dtype=np.int16,\n **kwargs)\n file_out = file_tmp.with_suffix('.cbin')\n file_tmp.rename(file_out)\n if not keep_original:\n self.file_bin.unlink()\n self.file_bin = file_out\n return file_out\n\n def decompress_file(self, keep_original=True, **kwargs):\n \"\"\"\n Decompresses a mtscomp file\n :param keep_original: defaults True. If False, the original compressed file (input)\n is deleted and the current spikeglx.Reader object is modified in place\n NB: This is not equivalent to overwrite (which replaces the output file)\n :return: pathlib.Path of the decompressed *.bin file\n \"\"\"\n if 'out' not in kwargs:\n kwargs['out'] = self.file_bin.with_suffix('.bin')\n assert self.is_mtscomp\n mtscomp.decompress(self.file_bin, self.file_bin.with_suffix('.ch'), **kwargs)\n if not keep_original:\n self.file_bin.unlink()\n self.file_bin.with_suffix('.ch').unlink()\n self.file_bin = kwargs['out']\n return kwargs['out']\n\n def verify_hash(self):\n \"\"\"\n Computes SHA-1 hash and returns True if it matches metadata, False otherwise\n :return: boolean\n \"\"\"\n if self.is_mtscomp:\n with open(self.file_bin.with_suffix('.ch')) as fid:\n mtscomp_params = json.load(fid)\n sm = mtscomp_params.get('sha1_compressed', None)\n if sm is None:\n _logger.warning(\"SHA1 hash is not implemented for compressed ephys. To check \"\n \"the spikeglx acquisition hash, uncompress the file first !\")\n return True\n sm = sm.upper()\n else:\n sm = self.meta.fileSHA1\n sc = hashfile.sha1(self.file_bin).upper()\n if sm == sc:\n log_func = _logger.info\n else:\n log_func = _logger.error\n log_func(f\"SHA1 metadata: {sm}\")\n log_func(f\"SHA1 computed: {sc}\")\n return sm == sc\n\n\ndef read(sglx_file, first_sample=0, last_sample=10000):\n \"\"\"\n Function to read from a spikeglx binary file without instantiating the class.\n Gets the meta-data as well.\n\n >>> ibllib.io.spikeglx.read('/path/to/file.bin', first_sample=0, last_sample=1000)\n\n :param sglx_file: full path the the binary file to read\n :param first_sample: first sample to be read, python slice-wise\n :param last_sample: last sample to be read, python slice-wise\n :return: Data array, sync trace, meta-data\n \"\"\"\n sglxr = Reader(sglx_file)\n D, sync = sglxr.read_samples(first_sample=first_sample, last_sample=last_sample)\n return D, sync, sglxr.meta\n\n\ndef read_meta_data(md_file):\n \"\"\"\n Reads the spkike glx metadata file and parse in a dictionary\n Agnostic: does not make any assumption on the keys/content, it just parses key=values\n\n :param md_file: last sample to be read, python slice-wise\n :return: Data array, sync trace, meta-data\n \"\"\"\n with open(md_file) as fid:\n md = fid.read()\n d = {}\n for a in md.splitlines():\n k, v = a.split('=')\n # if all numbers, try to interpret the string\n if v and re.fullmatch('[0-9,.]*', v) and v.count('.') < 2:\n v = [float(val) for val in v.split(',')]\n # scalars should not be nested\n if len(v) == 1:\n v = v[0]\n # tildes in keynames removed\n d[k.replace('~', '')] = v\n d['neuropixelVersion'] = _get_neuropixel_version_from_meta(d)\n d['serial'] = _get_serial_number_from_meta(d)\n return Bunch(d)\n\n\ndef _get_serial_number_from_meta(md):\n \"\"\"\n Get neuropixel serial number from the metadata dictionary\n \"\"\"\n # imProbeSN for 3A, imDatPrb_sn for 3B2, None for nidq 3B2\n serial = md.get('imProbeSN') or md.get('imDatPrb_sn')\n if serial:\n return int(serial)\n\n\ndef _get_neuropixel_version_from_meta(md):\n \"\"\"\n Get neuropixel version tag (3A, 3B1, 3B2) from the metadata dictionary\n \"\"\"\n if 'typeEnabled' in md.keys():\n return '3A'\n elif 'typeImEnabled' in md.keys() and 'typeNiEnabled' in md.keys():\n if 'imDatPrb_port' in md.keys() and 'imDatPrb_slot' in md.keys():\n return '3B2'\n else:\n return '3B1'\n\n\ndef _get_sync_trace_indices_from_meta(md):\n \"\"\"\n Returns a list containing indices of the sync traces in the original array\n \"\"\"\n typ = _get_type_from_meta(md)\n ntr = int(_get_nchannels_from_meta(md))\n if typ == 'nidq':\n nsync = int(md.get('snsMnMaXaDw')[-1])\n elif typ in ['lf', 'ap']:\n nsync = int(md.get('snsApLfSy')[2])\n return list(range(ntr - nsync, ntr))\n\n\ndef _get_analog_sync_trace_indices_from_meta(md):\n \"\"\"\n Returns a list containing indices of the sync traces in the original array\n \"\"\"\n typ = _get_type_from_meta(md)\n if typ != 'nidq':\n return []\n tr = md.get('snsMnMaXaDw')\n nsa = int(tr[-2])\n return list(range(int(sum(tr[0:2])), int(sum(tr[0:2])) + nsa))\n\n\ndef _get_nchannels_from_meta(md):\n typ = _get_type_from_meta(md)\n if typ == 'nidq':\n return int(np.round(np.sum(md.get('snsMnMaXaDw'))))\n elif typ in ['lf', 'ap']:\n return int(np.round(sum(md.get('snsApLfSy'))))\n\n\ndef _get_fs_from_meta(md):\n if md.get('typeThis') == 'imec':\n return md.get('imSampRate')\n else:\n return md.get('niSampRate')\n\n\ndef _get_type_from_meta(md):\n \"\"\"\n Get neuropixel data type (ap, lf or nidq) from metadata\n \"\"\"\n snsApLfSy = md.get('snsApLfSy', [-1, -1, -1])\n if snsApLfSy[0] == 0 and snsApLfSy[1] != 0:\n return 'lf'\n elif snsApLfSy[0] != 0 and snsApLfSy[1] == 0:\n return 'ap'\n elif snsApLfSy == [-1, -1, -1] and md.get('typeThis', None) == 'nidq':\n return 'nidq'\n\n\ndef _map_channels_from_meta(meta_data):\n \"\"\"\n Interpret the meta data string to extract an array of channel positions along the shank\n\n :param meta_data: dictionary output from spikeglx.read_meta_data\n :return: dictionary of arrays 'shank', 'col', 'row', 'flag', one value per active site\n \"\"\"\n if 'snsShankMap' in meta_data.keys():\n chmap = re.findall(r'([0-9]*:[0-9]*:[0-9]*:[0-9]*)', meta_data['snsShankMap'])\n # for digital nidq types, the key exists but does not contain any information\n if not chmap:\n return {'shank': None, 'col': None, 'row': None, 'flag': None}\n # shank#, col#, row#, drawflag\n # (nb: drawflag is one should be drawn and considered spatial average)\n chmap = np.array([np.float32(cm.split(':')) for cm in chmap])\n return {k: chmap[:, v] for (k, v) in {'shank': 0, 'col': 1, 'row': 2, 'flag': 3}.items()}\n\n\ndef _conversion_sample2v_from_meta(meta_data):\n \"\"\"\n Interpret the meta data to extract an array of conversion factors for each channel\n so the output data is in Volts\n Conversion factor is: int2volt / channelGain\n For Lf/Ap interpret the gain string from metadata\n For Nidq, repmat the gains from the trace counts in `snsMnMaXaDw`\n\n :param meta_data: dictionary output from spikeglx.read_meta_data\n :return: numpy array with one gain value per channel\n \"\"\"\n\n def int2volts(md):\n \"\"\" :return: Conversion scalar to Volts. Needs to be combined with channel gains \"\"\"\n if md.get('typeThis', None) == 'imec':\n return md.get('imAiRangeMax') / 512\n else:\n return md.get('niAiRangeMax') / 32768\n\n int2volt = int2volts(meta_data)\n # interprets the gain value from the metadata header:\n if 'imroTbl' in meta_data.keys(): # binary from the probes: ap or lf\n sy_gain = np.ones(int(meta_data['snsApLfSy'][-1]), dtype=np.float32)\n # imroTbl has 384 entries regardless of no of channels saved, so need to index by n_ch\n n_chn = _get_nchannels_from_meta(meta_data) - 1\n # the sync traces are not included in the gain values, so are included for broadcast ops\n gain = re.findall(r'([0-9]* [0-9]* [0-9]* [0-9]* [0-9]*)', meta_data['imroTbl'])[:n_chn]\n out = {'lf': np.hstack((np.array([1 / np.float32(g.split(' ')[-1]) for g in gain]) *\n int2volt, sy_gain)),\n 'ap': np.hstack((np.array([1 / np.float32(g.split(' ')[-2]) for g in gain]) *\n int2volt, sy_gain))}\n elif 'niMNGain' in meta_data.keys(): # binary from nidq\n gain = np.r_[\n np.ones(int(meta_data['snsMnMaXaDw'][0],)) / meta_data['niMNGain'] * int2volt,\n np.ones(int(meta_data['snsMnMaXaDw'][1],)) / meta_data['niMAGain'] * int2volt,\n np.ones(int(meta_data['snsMnMaXaDw'][2], )) * int2volt, # no gain for analog sync\n np.ones(int(np.sum(meta_data['snsMnMaXaDw'][3]),))] # no unit for digital sync\n out = {'nidq': gain}\n return out\n\n\ndef split_sync(sync_tr):\n \"\"\"\n The synchronization channels are stored as single bits, this will split the int16 original\n channel into 16 single bits channels\n\n :param sync_tr: numpy vector: samples of synchronisation trace\n :return: int8 numpy array of 16 channels, 1 column per sync trace\n \"\"\"\n sync_tr = np.int16(np.copy(sync_tr))\n out = np.unpackbits(sync_tr.view(np.uint8)).reshape(sync_tr.size, 16)\n out = np.flip(np.roll(out, 8, axis=1), axis=1)\n return np.int8(out)\n\n\ndef get_neuropixel_version_from_folder(session_path):\n ephys_files = glob_ephys_files(session_path)\n return get_neuropixel_version_from_files(ephys_files)\n\n\ndef get_neuropixel_version_from_files(ephys_files):\n if any([ef.get('nidq') for ef in ephys_files]):\n return '3B'\n else:\n return '3A'\n\n\ndef glob_ephys_files(session_path, suffix='.meta', ext='bin', recursive=True, bin_exists=True):\n \"\"\"\n From an arbitrary folder (usually session folder) gets the ap and lf files and labels\n Associated to the subfolders where they are\n the expected folder tree is:\n ├── 3A\n │ ├── imec0\n │ ├── sync_testing_g0_t0.imec0.ap.bin\n │ │ └── sync_testing_g0_t0.imec0.lf.bin\n │ └── imec1\n │ ├── sync_testing_g0_t0.imec1.ap.bin\n │ └── sync_testing_g0_t0.imec1.lf.bin\n └── 3B\n ├── sync_testing_g0_t0.nidq.bin\n ├── imec0\n │ ├── sync_testing_g0_t0.imec0.ap.bin\n │ └── sync_testing_g0_t0.imec0.lf.bin\n └── imec1\n ├── sync_testing_g0_t0.imec1.ap.bin\n └── sync_testing_g0_t0.imec1.lf.bin\n\n :param bin_exists:\n :param suffix:\n :param ext: file extension to look for, default 'bin' but could also be 'meta' or 'ch'\n :param recursive:\n :param session_path: folder, string or pathlib.Path\n :param glob_pattern: pattern to look recursively for (defaults to '*.ap.*bin)\n :returns: a list of dictionaries with keys 'ap': apfile, 'lf': lffile and 'label'\n \"\"\"\n def get_label(raw_ephys_apfile):\n if raw_ephys_apfile.parts[-2] != 'raw_ephys_data':\n return raw_ephys_apfile.parts[-2]\n else:\n return ''\n\n recurse = '**/' if recursive else ''\n ephys_files = []\n for raw_ephys_file in Path(session_path).glob(f'{recurse}*.ap{suffix}'):\n raw_ephys_apfile = next(raw_ephys_file.parent.glob(raw_ephys_file.stem + f'.*{ext}'), None)\n if not raw_ephys_apfile and bin_exists:\n continue\n elif not raw_ephys_apfile and ext != 'bin':\n continue\n elif not bin_exists and ext == 'bin':\n raw_ephys_apfile = raw_ephys_file.with_suffix('.bin')\n # first get the ap file\n ephys_files.extend([Bunch({'label': None, 'ap': None, 'lf': None, 'path': None})])\n ephys_files[-1].ap = raw_ephys_apfile\n # then get the corresponding lf file if it exists\n lf_file = raw_ephys_apfile.parent / raw_ephys_apfile.name.replace('.ap.', '.lf.')\n ephys_files[-1].lf = next(lf_file.parent.glob(lf_file.stem + f'.*{ext}'), None)\n # finally, the label is the current directory except if it is bare in raw_ephys_data\n ephys_files[-1].label = get_label(raw_ephys_apfile)\n ephys_files[-1].path = raw_ephys_apfile.parent\n # for 3b probes, need also to get the nidq dataset type\n for raw_ephys_file in Path(session_path).rglob(f'{recurse}*.nidq{suffix}'):\n raw_ephys_nidqfile = next(raw_ephys_file.parent.glob(raw_ephys_file.stem + f'.*{ext}'),\n None)\n if not bin_exists and ext == 'bin':\n raw_ephys_nidqfile = raw_ephys_file.with_suffix('.bin')\n ephys_files.extend([Bunch({'label': get_label(raw_ephys_file),\n 'nidq': raw_ephys_nidqfile,\n 'path': raw_ephys_file.parent})])\n return ephys_files\n\n\ndef _mock_spikeglx_file(mock_bin_file, meta_file, ns, nc, sync_depth,\n random=False, int2volts=0.6 / 32768, corrupt=False):\n \"\"\"\n For testing purposes, create a binary file with sync pulses to test reading and extraction\n \"\"\"\n meta_file = Path(meta_file)\n mock_path_bin = Path(mock_bin_file)\n mock_path_meta = mock_path_bin.with_suffix('.meta')\n md = read_meta_data(meta_file)\n assert meta_file != mock_path_meta\n fs = _get_fs_from_meta(md)\n fid_source = open(meta_file)\n fid_target = open(mock_path_meta, 'w+')\n line = fid_source.readline()\n while line:\n line = fid_source.readline()\n if line.startswith('fileSizeBytes'):\n line = f'fileSizeBytes={ns * nc * 2}\\n'\n if line.startswith('fileTimeSecs'):\n if corrupt:\n line = f'fileTimeSecs={ns / fs + 1.8324}\\n'\n else:\n line = f'fileTimeSecs={ns / fs}\\n'\n fid_target.write(line)\n fid_source.close()\n fid_target.close()\n if random:\n D = np.random.randint(-32767, 32767, size=(ns, nc), dtype=np.int16)\n else: # each channel as an int of chn + 1\n D = np.tile(np.int16((np.arange(nc) + 1) / int2volts), (ns, 1))\n D[0:16, :] = 0\n # the last channel is the sync that we fill with\n sync = np.int16(2 ** np.float32(np.arange(-1, sync_depth)))\n D[:, -1] = 0\n D[:sync.size, -1] = sync\n with open(mock_path_bin, 'w+') as fid:\n D.tofile(fid)\n return {'bin_file': mock_path_bin, 'ns': ns, 'nc': nc, 'sync_depth': sync_depth, 'D': D}\n\n\ndef get_hardware_config(config_file):\n \"\"\"\n Reads the neuropixel_wirings.json file containing sync mapping and parameters\n :param config_file: folder or json file\n :return: dictionary or None\n \"\"\"\n config_file = Path(config_file)\n if config_file.is_dir():\n config_file = list(config_file.glob('*.wiring.json'))\n if config_file:\n config_file = config_file[0]\n if not config_file or not config_file.exists():\n return\n with open(config_file) as fid:\n par = json.loads(fid.read())\n return par\n\n\ndef _sync_map_from_hardware_config(hardware_config):\n \"\"\"\n :param hardware_config: dictonary from json read of neuropixel_wirings.json\n :return: dictionary where key names refer to object and values to sync channel index\n \"\"\"\n pin_out = neuropixel.SYNC_PIN_OUT[hardware_config['SYSTEM']]\n sync_map = {hardware_config['SYNC_WIRING_DIGITAL'][pin]: pin_out[pin]\n for pin in hardware_config['SYNC_WIRING_DIGITAL']\n if pin_out[pin] is not None}\n analog = hardware_config.get('SYNC_WIRING_ANALOG')\n if analog:\n sync_map.update({analog[pin]: int(pin[2:]) + 16 for pin in analog})\n return sync_map\n\n\ndef get_sync_map(folder_ephys):\n hc = get_hardware_config(folder_ephys)\n if not hc:\n _logger.warning(f\"No channel map for {str(folder_ephys)}\")\n return None\n else:\n return _sync_map_from_hardware_config(hc)\n" ]
[ [ "numpy.sum", "numpy.arange", "numpy.memmap", "numpy.int8", "numpy.copy", "numpy.float32", "numpy.where", "numpy.roll", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ZiqiuChi/vision
[ "b5ecf5431f7767d8920a69005e7822185ad31f81", "b5ecf5431f7767d8920a69005e7822185ad31f81", "b5ecf5431f7767d8920a69005e7822185ad31f81" ]
[ "flowvision/datasets/semeion.py", "flowvision/transforms/functional_pil.py", "flowvision/datasets/mnist.py" ]
[ "\"\"\"\n\"\"\"\nimport os\nimport os.path\nfrom typing import Any, Callable, Optional, Tuple\n\nimport numpy as np\nfrom PIL import Image\n\nfrom .utils import download_url, check_integrity\nfrom .vision import VisionDataset\n\n\nclass SEMEION(VisionDataset):\n r\"\"\"`SEMEION <http://archive.ics.uci.edu/ml/datasets/semeion+handwritten+digit>`_ Dataset.\n Args:\n root (string): Root directory of dataset where directory\n ``semeion.py`` exists.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n download (bool, optional): If true, downloads the dataset from the internet and\n puts it in root directory. If dataset is already downloaded, it is not\n downloaded again.\n \"\"\"\n url = (\n \"http://archive.ics.uci.edu/ml/machine-learning-databases/semeion/semeion.data\"\n )\n filename = \"semeion.data\"\n md5_checksum = \"cb545d371d2ce14ec121470795a77432\"\n\n def __init__(\n self,\n root: str,\n transform: Optional[Callable] = None,\n target_transform: Optional[Callable] = None,\n download: bool = True,\n ) -> None:\n super(SEMEION, self).__init__(\n root, transform=transform, target_transform=target_transform\n )\n\n if download:\n self.download()\n\n if not self._check_integrity():\n raise RuntimeError(\n \"Dataset not found or corrupted.\"\n + \" You can use download=True to download it\"\n )\n\n fp = os.path.join(self.root, self.filename)\n data = np.loadtxt(fp)\n # convert value to 8 bit unsigned integer\n # color (white #255) the pixels\n self.data = (data[:, :256] * 255).astype(\"uint8\")\n self.data = np.reshape(self.data, (-1, 16, 16))\n self.labels = np.nonzero(data[:, 256:])[1]\n\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n img, target = self.data[index], int(self.labels[index])\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = Image.fromarray(img, mode=\"L\")\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self) -> int:\n return len(self.data)\n\n def _check_integrity(self) -> bool:\n root = self.root\n fpath = os.path.join(root, self.filename)\n if not check_integrity(fpath, self.md5_checksum):\n return False\n return True\n\n def download(self) -> None:\n if self._check_integrity():\n print(\"Files already downloaded and verified\")\n return\n\n root = self.root\n download_url(self.url, root, self.filename, self.md5_checksum)\n", "\"\"\"\n\"\"\"\nimport numbers\nfrom typing import Any, List, Sequence\nimport numpy as np\nfrom PIL import Image, ImageOps, ImageEnhance\n\nimport oneflow as flow\n\ntry:\n import accimage\nexcept ImportError:\n accimage = None\n\n\ndef _is_pil_image(img: Any) -> bool:\n if accimage is not None:\n return isinstance(img, (Image.Image, accimage.Image))\n else:\n return isinstance(img, Image.Image)\n\n\ndef _get_image_size(img: Any) -> List[int]:\n if _is_pil_image(img):\n return img.size\n raise TypeError(\"Unexpected type {}\".format(type(img)))\n\n\ndef _get_image_num_channels(img: Any) -> int:\n if _is_pil_image(img):\n return 1 if img.mode == \"L\" else 3\n\n\ndef hflip(img):\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n return img.transpose(Image.FLIP_LEFT_RIGHT)\n\n\ndef vflip(img):\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n return img.transpose(Image.FLIP_TOP_BOTTOM)\n\n\ndef adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image:\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n enhancer = ImageEnhance.Brightness(img)\n img = enhancer.enhance(brightness_factor)\n return img\n\n\ndef adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image:\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n enhancer = ImageEnhance.Contrast(img)\n img = enhancer.enhance(contrast_factor)\n return img\n\n\ndef adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image:\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n enhancer = ImageEnhance.Color(img)\n img = enhancer.enhance(saturation_factor)\n return img\n\n\ndef adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image:\n if not (-0.5 <= hue_factor <= 0.5):\n raise ValueError(\"hue_factor ({}) is not in [-0.5, 0.5].\".format(hue_factor))\n\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n input_mode = img.mode\n if input_mode in {\"L\", \"1\", \"I\", \"F\"}:\n return img\n\n h, s, v = img.convert(\"HSV\").split()\n\n np_h = np.array(h, dtype=np.uint8)\n # uint8 addition take cares of rotation across boundaries\n with np.errstate(over=\"ignore\"):\n np_h += np.uint8(hue_factor * 255)\n h = Image.fromarray(np_h, \"L\")\n\n img = Image.merge(\"HSV\", (h, s, v)).convert(input_mode)\n return img\n\n\ndef pad(img, padding, fill=0, padding_mode=\"constant\"):\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n if not isinstance(padding, (numbers.Number, tuple, list)):\n raise TypeError(\"Got inappropriate padding arg\")\n if not isinstance(fill, (numbers.Number, str, tuple)):\n raise TypeError(\"Got inappropriate fill arg\")\n if not isinstance(padding_mode, str):\n raise TypeError(\"Got inappropriate padding_mode arg\")\n\n if isinstance(padding, list):\n padding = tuple(padding)\n\n if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]:\n raise ValueError(\n \"Padding must be an int or a 1, 2, or 4 element tuple, not a \"\n + \"{} element tuple\".format(len(padding))\n )\n\n if isinstance(padding, tuple) and len(padding) == 1:\n # Compatibility with `functional_tensor.pad`\n padding = padding[0]\n\n if padding_mode not in [\"constant\", \"edge\", \"reflect\", \"symmetric\"]:\n raise ValueError(\n \"Padding mode should be either constant, edge, reflect or symmetric\"\n )\n\n if padding_mode == \"constant\":\n opts = _parse_fill(fill, img, name=\"fill\")\n if img.mode == \"P\":\n palette = img.getpalette()\n image = ImageOps.expand(img, border=padding, **opts)\n image.putpalette(palette)\n return image\n\n return ImageOps.expand(img, border=padding, **opts)\n else:\n if isinstance(padding, int):\n pad_left = pad_right = pad_top = pad_bottom = padding\n if isinstance(padding, tuple) and len(padding) == 2:\n pad_left = pad_right = padding[0]\n pad_top = pad_bottom = padding[1]\n if isinstance(padding, tuple) and len(padding) == 4:\n pad_left = padding[0]\n pad_top = padding[1]\n pad_right = padding[2]\n pad_bottom = padding[3]\n\n p = [pad_left, pad_top, pad_right, pad_bottom]\n cropping = -np.minimum(p, 0)\n\n if cropping.any():\n crop_left, crop_top, crop_right, crop_bottom = cropping\n img = img.crop(\n (crop_left, crop_top, img.width - crop_right, img.height - crop_bottom)\n )\n\n pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0)\n\n if img.mode == \"P\":\n palette = img.getpalette()\n img = np.asarray(img)\n img = np.pad(\n img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode\n )\n img = Image.fromarray(img)\n img.putpalette(palette)\n return img\n\n img = np.asarray(img)\n # RGB image\n if len(img.shape) == 3:\n img = np.pad(\n img,\n ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)),\n padding_mode,\n )\n # Grayscale image\n if len(img.shape) == 2:\n img = np.pad(\n img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode\n )\n\n return Image.fromarray(img)\n\n\ndef crop(img: Image.Image, top: int, left: int, height: int, width: int) -> Image.Image:\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n return img.crop((left, top, left + width, top + height))\n\n\ndef resize(img, size, interpolation=Image.BILINEAR):\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n if not (\n isinstance(size, int) or (isinstance(size, Sequence) and len(size) in (1, 2))\n ):\n raise TypeError(\"Got inappropriate size arg: {}\".format(size))\n\n if isinstance(size, int) or len(size) == 1:\n if isinstance(size, Sequence):\n size = size[0]\n w, h = img.size\n if (w <= h and w == size) or (h <= w and h == size):\n return img\n if w < h:\n ow = size\n oh = int(size * h / w)\n return img.resize((ow, oh), interpolation)\n else:\n oh = size\n ow = int(size * w / h)\n return img.resize((ow, oh), interpolation)\n else:\n return img.resize(size[::-1], interpolation)\n\n\ndef _parse_fill(fill, img, name=\"fillcolor\"):\n # Process fill color for affine transforms\n num_bands = len(img.getbands())\n if fill is None:\n fill = 0\n if isinstance(fill, (int, float)) and num_bands > 1:\n fill = tuple([fill] * num_bands)\n if isinstance(fill, (list, tuple)):\n if len(fill) != num_bands:\n msg = (\n \"The number of elements in 'fill' does not match the number of \"\n \"bands of the image ({} != {})\"\n )\n raise ValueError(msg.format(len(fill), num_bands))\n\n fill = tuple(fill)\n\n return {name: fill}\n\n\ndef rotate(img, angle, interpolation=0, expand=False, center=None, fill=None):\n if not _is_pil_image(img):\n raise TypeError(\"img should be PIL Image. Got {}\".format(type(img)))\n\n opts = _parse_fill(fill, img)\n return img.rotate(angle, interpolation, expand, center, **opts)\n", "\"\"\"\n\"\"\"\nimport warnings\nfrom PIL import Image\nimport os\nimport os.path\nimport numpy as np\nimport codecs\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom urllib.error import URLError\n\nimport oneflow as flow\nfrom .vision import VisionDataset\nfrom .utils import download_and_extract_archive, check_integrity\nfrom oneflow.framework.tensor import Tensor\n\n\nclass MNIST(VisionDataset):\n r\"\"\" `MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.\n\n Args:\n root (string): Root directory of dataset where ``MNIST/processed/training.pt``\n and ``MNIST/processed/test.pt`` exist.\n train (bool, optional): If True, creates dataset from ``training.pt``,\n otherwise from ``test.pt``.\n download (bool, optional): If true, downloads the dataset from the internet and\n puts it in root directory. If dataset is already downloaded, it is not\n downloaded again.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n \"\"\"\n mirrors = [\n \"http://yann.lecun.com/exdb/mnist/\",\n \"https://ossci-datasets.s3.amazonaws.com/mnist/\",\n ]\n\n resources = [\n (\"train-images-idx3-ubyte.gz\", \"f68b3c2dcbeaaa9fbdd348bbdeb94873\"),\n (\"train-labels-idx1-ubyte.gz\", \"d53e105ee54ea40749a09fcbcd1e9432\"),\n (\"t10k-images-idx3-ubyte.gz\", \"9fb629c4189551a2d022fa330f9573f3\"),\n (\"t10k-labels-idx1-ubyte.gz\", \"ec29112dd5afa0611ce80d1b7f02629c\"),\n ]\n\n training_file = \"training.pt\"\n test_file = \"test.pt\"\n classes = [\n \"0 - zero\",\n \"1 - one\",\n \"2 - two\",\n \"3 - three\",\n \"4 - four\",\n \"5 - five\",\n \"6 - six\",\n \"7 - seven\",\n \"8 - eight\",\n \"9 - nine\",\n ]\n\n @property\n def train_labels(self):\n warnings.warn(\"train_labels has been renamed targets\")\n return self.targets\n\n @property\n def test_labels(self):\n warnings.warn(\"test_labels has been renamed targets\")\n return self.targets\n\n @property\n def train_data(self):\n warnings.warn(\"train_data has been renamed data\")\n return self.data\n\n @property\n def test_data(self):\n warnings.warn(\"test_data has been renamed data\")\n return self.data\n\n def __init__(\n self,\n root: str,\n train: bool = True,\n transform: Optional[Callable] = None,\n target_transform: Optional[Callable] = None,\n download: bool = False,\n source_url: Optional[str] = None,\n ) -> None:\n super(MNIST, self).__init__(\n root, transform=transform, target_transform=target_transform\n )\n self.train = train # training set or test set\n if source_url is not None:\n self.mirrors = [source_url]\n\n if self._check_legacy_exist():\n self.data, self.targets = self._load_legacy_data()\n return\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError(\n \"Dataset not found.\" + \" You can use download=True to download it\"\n )\n\n self.data, self.targets = self._load_data()\n\n def _check_legacy_exist(self):\n processed_folder_exists = os.path.exists(self.processed_folder)\n if not processed_folder_exists:\n return False\n\n return all(\n check_integrity(os.path.join(self.processed_folder, file))\n for file in (self.training_file, self.test_file)\n )\n\n def _load_legacy_data(self):\n # This is for BC only. We no longer cache the data in a custom binary, but simply read from the raw data\n # directly.\n data_file = self.training_file if self.train else self.test_file\n return flow.load(os.path.join(self.processed_folder, data_file))\n\n def _load_data(self):\n image_file = f\"{'train' if self.train else 't10k'}-images-idx3-ubyte\"\n data = read_image_file(os.path.join(self.raw_folder, image_file))\n\n label_file = f\"{'train' if self.train else 't10k'}-labels-idx1-ubyte\"\n targets = read_label_file(os.path.join(self.raw_folder, label_file))\n return data, targets\n\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n img, target = self.data[index], int(self.targets[index].numpy())\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = Image.fromarray(img.numpy(), mode=\"L\")\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self) -> int:\n return self.data.size(0)\n\n @property\n def raw_folder(self) -> str:\n return os.path.join(self.root, self.__class__.__name__, \"raw\")\n\n @property\n def processed_folder(self) -> str:\n return os.path.join(self.root, self.__class__.__name__, \"processed\")\n\n @property\n def class_to_idx(self) -> Dict[str, int]:\n return {_class: i for i, _class in enumerate(self.classes)}\n\n def _check_exists(self) -> bool:\n return all(\n check_integrity(\n os.path.join(\n self.raw_folder, os.path.splitext(os.path.basename(url))[0]\n )\n )\n for url, _ in self.resources\n )\n\n def download(self) -> None:\n \"\"\"Download the MNIST data if it doesn't exist already.\"\"\"\n\n if self._check_exists():\n return\n\n os.makedirs(self.raw_folder, exist_ok=True)\n\n # download files\n for filename, md5 in self.resources:\n for mirror in self.mirrors:\n url = \"{}{}\".format(mirror, filename)\n try:\n print(\"Downloading {}\".format(url))\n download_and_extract_archive(\n url, download_root=self.raw_folder, filename=filename, md5=md5\n )\n except URLError as error:\n print(\"Failed to download (trying next):\\n{}\".format(error))\n continue\n finally:\n print()\n break\n else:\n raise RuntimeError(\"Error downloading {}\".format(filename))\n\n def extra_repr(self) -> str:\n return \"Split: {}\".format(\"Train\" if self.train is True else \"Test\")\n\n\nclass FashionMNIST(MNIST):\n r\"\"\" `Fashion-MNIST <https://github.com/zalandoresearch/fashion-mnist>`_ Dataset.\n\n Args:\n root (string): Root directory of dataset where ``FashionMNIST/processed/training.pt``\n and ``FashionMNIST/processed/test.pt`` exist.\n train (bool, optional): If True, creates dataset from ``training.pt``,\n otherwise from ``test.pt``.\n download (bool, optional): If true, downloads the dataset from the internet and\n puts it in root directory. If dataset is already downloaded, it is not\n downloaded again.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n \"\"\"\n mirrors = [\"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/\"]\n\n resources = [\n (\"train-images-idx3-ubyte.gz\", \"8d4fb7e6c68d591d4c3dfef9ec88bf0d\"),\n (\"train-labels-idx1-ubyte.gz\", \"25c81989df183df01b3e8a0aad5dffbe\"),\n (\"t10k-images-idx3-ubyte.gz\", \"bef4ecab320f06d8554ea6380940ec79\"),\n (\"t10k-labels-idx1-ubyte.gz\", \"bb300cfdad3c16e7a12a480ee83cd310\"),\n ]\n classes = [\n \"T-shirt/top\",\n \"Trouser\",\n \"Pullover\",\n \"Dress\",\n \"Coat\",\n \"Sandal\",\n \"Shirt\",\n \"Sneaker\",\n \"Bag\",\n \"Ankle boot\",\n ]\n\n\nSN3_PASCALVINCENT_TYPEMAP = {\n 8: (flow.uint8, np.uint8, np.uint8),\n 9: (flow.int8, np.int8, np.int8),\n 11: (flow.int32, np.dtype(\">i2\"), \"i2\"),\n 12: (flow.int32, np.dtype(\">i4\"), \"i4\"),\n 13: (flow.float32, np.dtype(\">f4\"), \"f4\"),\n 14: (flow.float64, np.dtype(\">f8\"), \"f8\"),\n}\n\n\ndef get_int(b: bytes) -> int:\n return int(codecs.encode(b, \"hex\"), 16)\n\n\ndef read_sn3_pascalvincent_tensor(path: str, strict: bool = True) -> Tensor:\n \"\"\"Read a SN3 file in \"Pascal Vincent\" format (Lush file 'libidx/idx-io.lsh').\n Argument may be a filename, compressed filename, or file object.\n \"\"\"\n # read\n with open(path, \"rb\") as f:\n data = f.read()\n # parse\n magic = get_int(data[0:4])\n nd = magic % 256\n ty = magic // 256\n assert 1 <= nd <= 3\n assert 8 <= ty <= 14\n m = SN3_PASCALVINCENT_TYPEMAP[ty]\n s = [get_int(data[4 * (i + 1) : 4 * (i + 2)]) for i in range(nd)]\n parsed = np.frombuffer(data, dtype=m[1], offset=(4 * (nd + 1)))\n assert parsed.shape[0] == np.prod(s) or not strict\n return flow.reshape(flow.tensor(parsed.astype(m[2]), dtype=m[0]), shape=s)\n\n\ndef read_label_file(path: str) -> Tensor:\n x = read_sn3_pascalvincent_tensor(path, strict=False)\n assert x.dtype == flow.uint8\n assert x.ndimension() == 1\n x = x.to(dtype=flow.int64)\n return x\n\n\ndef read_image_file(path: str) -> Tensor:\n x = read_sn3_pascalvincent_tensor(path, strict=False)\n assert x.dtype == flow.uint8\n assert x.ndimension() == 3\n return x\n" ]
[ [ "numpy.reshape", "numpy.nonzero", "numpy.loadtxt" ], [ "numpy.maximum", "numpy.minimum", "numpy.pad", "numpy.asarray", "numpy.uint8", "numpy.errstate", "numpy.array" ], [ "numpy.prod", "numpy.frombuffer", "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
akirallL/TurboTransformers
[ "7ca851947b1ae3b08122c45cea0ceac48ee04c3b", "7ca851947b1ae3b08122c45cea0ceac48ee04c3b", "7ca851947b1ae3b08122c45cea0ceac48ee04c3b" ]
[ "turbo_transformers/python/turbo_transformers/layers/modeling_distillbert.py", "turbo_transformers/python/tests/bert_encoder_test.py", "turbo_transformers/python/tests/gpt2_model_test.py" ]
[ "# Copyright (C) 2020 THL A29 Limited, a Tencent company.\n# All rights reserved.\n# Licensed under the BSD 3-Clause License (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n# https://opensource.org/licenses/BSD-3-Clause\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# See the AUTHORS file for names of contributors.\n\ntry:\n # `turbo_transformers_cxxd` is the name on debug mode\n import turbo_transformers.turbo_transformers_cxxd as cxx\nexcept ImportError:\n import turbo_transformers.turbo_transformers_cxx as cxx\nfrom typing import Union, Optional, Sequence\nimport torch\nfrom .return_type import convert_returns_as_type, ReturnType\nfrom .utils import try_convert, convert2tt_tensor, to_param_dict_convert_tt, to_param_dict, create_empty_if_none, AnyTensor\n\nfrom transformers.models.distilbert.modeling_distilbert import DistilBertConfig\nfrom transformers.models.distilbert.modeling_distilbert import MultiHeadSelfAttention as TorchDistilMultiHeadSelfAttention\nfrom transformers.models.distilbert.modeling_distilbert import FFN as TorchDistilFFN\nfrom transformers.models.distilbert.modeling_distilbert import TransformerBlock as TorchDistilTransformerBlock\nfrom transformers.models.distilbert.modeling_distilbert import Transformer as TorchDistilTransformer\nfrom transformers.models.distilbert.modeling_distilbert import Embeddings as TorchDistrilEmbeddings\nfrom transformers.models.distilbert.modeling_distilbert import DistilBertModel as TorchDistilBertModel\n\nfrom torch import nn\nimport numpy as np\n__all__ = [\n 'DistillBertAttention', 'DistrillFFN', 'DistrillTransformerBlock',\n 'DistrillTransformer', 'DistilBertModel'\n]\n\n\nclass DistillBertAttention(cxx.BertAttention):\n def __call__(self,\n input_tensor: AnyTensor,\n attention_mask: Optional[AnyTensor] = None,\n head_mask: Optional[AnyTensor] = None,\n output_attentions: Optional[bool] = False,\n return_type: Optional[ReturnType] = None,\n is_trans_weight: Optional[cxx.Tensor] = False):\n assert (head_mask is None)\n # attention mask is different from BERT\n if attention_mask is not None:\n attention_mask = attention_mask[:, None, None, :]\n attention_mask = (\n 1.0 - attention_mask) * -10000.0 #-float(\"inf\") will cause NAN\n\n input_tensor = try_convert(input_tensor)\n attention_mask = try_convert(create_empty_if_none(attention_mask))\n context_layer = cxx.Tensor.create_empty()\n attn_probs = cxx.Tensor.create_empty()\n super(DistillBertAttention,\n self).__call__(input_tensor, attention_mask, context_layer,\n attn_probs, is_trans_weight)\n outputs = (convert_returns_as_type(context_layer, return_type),\n convert_returns_as_type(attn_probs, ReturnType.TORCH)\n ) if output_attentions else (convert_returns_as_type(\n context_layer, return_type), )\n return outputs\n\n @staticmethod\n def from_torch(attention: TorchDistilMultiHeadSelfAttention,\n layernorm: nn.LayerNorm):\n params = {k: v for k, v in attention.named_parameters()}\n layernorm_params = {k: v for k, v in layernorm.named_parameters()}\n\n with torch.no_grad():\n # merge self.query.weight, self.query.weight and self.query.weight together as qkv.weight\n qkv_weight = torch.clone(\n torch.t(\n torch.cat((params['q_lin.weight'], params['k_lin.weight'],\n params['v_lin.weight']),\n 0).contiguous()).contiguous())\n qkv_bias = torch.cat((params['q_lin.bias'], params['k_lin.bias'],\n params['v_lin.bias']), 0).contiguous()\n\n output_weight = torch.clone(\n torch.t(params['out_lin.weight']).contiguous())\n att = DistillBertAttention(\n convert2tt_tensor(qkv_weight), convert2tt_tensor(qkv_bias),\n convert2tt_tensor(output_weight),\n convert2tt_tensor(params['out_lin.bias']),\n convert2tt_tensor(layernorm_params['weight']),\n convert2tt_tensor(layernorm_params['bias']), attention.n_heads)\n\n return att\n\n\nclass DistrillFFN(cxx.DistrillFFN):\n def __call__(\n self,\n input_tensor: AnyTensor,\n return_type: Optional[ReturnType] = None,\n is_trans_weight: Optional[bool] = True, #Intel 61xx True is faster\n output: Optional[cxx.Tensor] = None):\n input_tensor = try_convert(input_tensor)\n output = create_empty_if_none(output)\n super(DistrillFFN, self).__call__(input_tensor, output,\n is_trans_weight)\n return convert_returns_as_type(output, return_type)\n\n @staticmethod\n def from_torch(ffn: TorchDistilFFN,\n layernorm: nn.LayerNorm,\n is_trans_weight: Optional[bool] = True):\n ffn_params = {k: v for k, v in ffn.named_parameters()}\n layernorm_params = {k: v for k, v in layernorm.named_parameters()}\n\n # Note that torch's weights of linear layer is transposed\n if is_trans_weight:\n w_1 = convert2tt_tensor(ffn_params['lin1.weight'])\n w_2 = convert2tt_tensor(ffn_params['lin2.weight'])\n else:\n w_1 = convert2tt_tensor(\n torch.clone(torch.t(ffn_params['lin1.weight']).contiguous()))\n w_2 = convert2tt_tensor(\n torch.clone(torch.t(ffn_params['lin2.weight']).contiguous()))\n\n with torch.no_grad():\n ffn = DistrillFFN(w_1, convert2tt_tensor(ffn_params['lin1.bias']),\n w_2, convert2tt_tensor(ffn_params['lin2.bias']),\n convert2tt_tensor(layernorm_params['weight']),\n convert2tt_tensor(layernorm_params['bias']))\n return ffn\n\n\nclass DistrillTransformerBlock:\n def __init__(self, attn: DistillBertAttention, ffn: DistrillFFN):\n self.attention = attn\n self.ffn = ffn\n\n def __call__(self,\n hidden_states: AnyTensor,\n attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n output_attentions=False,\n return_type: Optional[ReturnType] = None):\n hidden_states = try_convert(hidden_states)\n\n sa_output = self.attention(hidden_states,\n attention_mask,\n head_mask,\n output_attentions=output_attentions,\n return_type=ReturnType.turbo_transformers)\n if output_attentions:\n sa_output, sa_weights = sa_output\n else:\n sa_output = sa_output[0]\n ffn_output = self.ffn(sa_output)\n output = (ffn_output, )\n if output_attentions:\n output = (sa_weights, ) + output\n return output\n\n @staticmethod\n def from_torch(layer: TorchDistilTransformerBlock):\n return DistrillTransformerBlock(\n DistillBertAttention.from_torch(layer.attention,\n layer.sa_layer_norm),\n DistrillFFN.from_torch(layer.ffn, layer.output_layer_norm))\n\n\nclass DistrillTransformer:\n def __init__(self, blocks: Sequence[DistrillTransformerBlock]):\n self.blocks = blocks\n\n def __call__(self,\n hidden_states: AnyTensor,\n attention_mask: Optional[AnyTensor] = None,\n head_mask: Optional[AnyTensor] = None,\n output_attentions: Optional[bool] = False,\n output_hidden_states: Optional[bool] = False,\n return_type: Optional[ReturnType] = ReturnType.TORCH):\n all_hidden_states = ()\n all_attentions = ()\n hidden_states = try_convert(hidden_states)\n for l in self.blocks:\n layer_outputs = l(hidden_states=hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n return_type=ReturnType.turbo_transformers)\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (\n convert_returns_as_type(hidden_states, ReturnType.TORCH), )\n\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1], )\n\n # outputs = (convert_returns_as_type(hidden_states, return_type), )\n outputs = (hidden_states, )\n # Add last layer\n if output_hidden_states:\n # TODO(jiaruifang)two return value use the same memory space, that is not supported in dlpack.\n # So we do not append the last hidden_state at the buttom of all_hidden_states,\n # User should use outputs[0] if necessary\n # all_hidden_states = all_hidden_states + (convert_returns_as_type(hidden_states, ReturnType.TORCH),)\n pass\n\n if output_hidden_states:\n outputs = outputs + (all_hidden_states, )\n if output_attentions:\n outputs = outputs + (all_attentions, )\n\n return outputs\n\n @staticmethod\n def from_torch(transform: TorchDistilTransformer):\n blocks = [\n DistrillTransformerBlock.from_torch(l) for l in transform.layer\n ]\n return DistrillTransformer(blocks)\n\n\nclass DistilBertModel:\n def __init__(self,\n embeddings_onnxmodel_variant,\n transformer: DistrillTransformer,\n backend=\"turbo\"):\n if backend == \"turbo\":\n self.embeddings = embeddings_onnxmodel_variant\n self.transformer = transformer\n self.backend = \"turbo\"\n elif backend == \"onnxrt\":\n self.onnxmodel = embeddings_onnxmodel_variant\n self.backend = \"onnxrt\"\n\n def __call__(self,\n input_ids: AnyTensor,\n attention_masks: Optional[AnyTensor] = None,\n token_type_ids: Optional[AnyTensor] = None,\n position_ids: Optional[AnyTensor] = None,\n head_mask: Optional[AnyTensor] = None,\n inputs_embeds: Optional[AnyTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_type: Optional[ReturnType] = None):\n if self.backend == \"onnxrt\":\n if attention_masks is None:\n attention_masks = np.ones(input_ids.size(), dtype=np.int64)\n else:\n attention_masks = attention_masks.cpu().numpy()\n data = [input_ids.cpu().numpy(), attention_masks]\n outputs = self.onnxmodel.run(inputs=data)\n for idx, item in enumerate(outputs):\n outputs[idx] = torch.tensor(item, device=input_ids.device)\n return outputs\n elif self.backend == \"turbo\":\n # torch part\n inputs_embeds = self.embeddings(input_ids) # (bs, seq_length, dim)\n inputs_embeds = try_convert(inputs_embeds)\n\n # turbo part\n transformer_outputs = self.transformer(\n hidden_states=inputs_embeds,\n attention_mask=attention_masks,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_type=return_type)\n return transformer_outputs\n\n @staticmethod\n def from_torch(model: TorchDistilBertModel, backend=\"turbo\"):\n \"\"\"\n :param model: a torch distrilBert Model\n backend: turbo or onnxrt\n move model to gpu before call this function.\n \"\"\"\n if backend == \"turbo\":\n transformer = DistrillTransformer.from_torch(model.transformer)\n return DistilBertModel(model.embeddings, transformer, \"turbo\")\n elif backend == \"onnxrt\":\n import onnx\n import onnxruntime.backend\n device = model.device\n if 'cuda' in device.type and torch.cuda.is_available():\n use_gpu = True\n else:\n use_gpu = False\n inputs = {\n 'input_ids':\n torch.randint(32, [2, 32], dtype=torch.long).to(\n device), # list of numerical ids for the tokenised text\n 'attention_mask':\n torch.ones([2, 32],\n dtype=torch.long).to(device), # dummy list of ones\n }\n onnx_model_path = \"/tmp/temp_turbo_onnx.model\"\n with open(onnx_model_path, 'wb') as outf:\n torch.onnx.export(\n model=model,\n args=(inputs['input_ids'], inputs['attention_mask']\n ), # model input (or a tuple for multiple inputs)\n f=outf,\n input_names=['input_ids', 'attention_mask'],\n output_names=['output'],\n dynamic_axes={\n 'input_ids': [0, 1],\n 'attention_mask': [0, 1]\n })\n onnx_model = onnx.load_model(f=onnx_model_path)\n onnx_model = onnxruntime.backend.prepare(\n model=onnx_model,\n device='GPU' if use_gpu else \"CPU\",\n graph_optimization_level=onnxruntime.GraphOptimizationLevel.\n ORT_ENABLE_ALL)\n return DistilBertModel(onnx_model, None, \"onnxrt\")\n", "# Copyright (C) 2020 THL A29 Limited, a Tencent company.\n# All rights reserved.\n# Licensed under the BSD 3-Clause License (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n# https://opensource.org/licenses/BSD-3-Clause\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# See the AUTHORS file for names of contributors.\n\nimport turbo_transformers\n\nimport unittest\nimport sys\nimport torch\nfrom transformers.models.bert.modeling_bert import BertConfig, BertEncoder\nimport os\n\nsys.path.append(os.path.dirname(__file__))\nimport test_helper\n\n\nclass TestBertEncoder(unittest.TestCase):\n def init_data(self, use_cuda) -> None:\n test_device = torch.device('cuda:0') if use_cuda else \\\n torch.device('cpu:0')\n if not use_cuda:\n torch.set_num_threads(1)\n\n torch.set_grad_enabled(False)\n self.cfg = BertConfig()\n\n self.torch_encoder_layer = BertEncoder(self.cfg)\n self.torch_encoder_layer.eval()\n\n if use_cuda:\n self.torch_encoder_layer.to(test_device)\n\n self.batch_size = 1\n self.seq_length = 40\n self.hidden_size = self.cfg.hidden_size\n self.input_tensor = torch.rand(size=(self.batch_size, self.seq_length,\n self.hidden_size),\n dtype=torch.float32,\n device=test_device)\n\n self.attention_mask = torch.ones((self.batch_size, self.seq_length),\n dtype=torch.float32,\n device=test_device)\n self.attention_mask = self.attention_mask[:, None, None, :]\n self.attention_mask = (1.0 - self.attention_mask) * -10000.0\n\n self.turbo_bert_encoder = turbo_transformers.BertEncoder.from_torch(\n self.torch_encoder_layer)\n\n def check_torch_and_turbo(self, use_cuda=True):\n self.init_data(use_cuda=use_cuda)\n self.num_iter = 2\n\n turbo_bert_layer_result = None\n turbo_model = lambda: self.turbo_bert_encoder(self.input_tensor,\n self.attention_mask,\n output_attentions=True,\n output_hidden_states=True\n )\n\n turbo_bert_layer_result, turbo_qps, turbo_time_consume = \\\n test_helper.run_model(turbo_model, use_cuda, self.num_iter)\n\n print(f\"BertEncoder TurboTransform QPS, {turbo_qps}, \",\n f\"Time Cost, {turbo_time_consume}\")\n\n # turbo_bert_layer_result = self.turbo_bert_encoder(\n # self.input_tensor,\n # self.attention_mask,\n # output_attentions = True,\n # output_hidden_states = False)\n\n torch_model = lambda: self.torch_encoder_layer(\n self.input_tensor,\n self.attention_mask, [None] * self.cfg.num_hidden_layers,\n output_attentions=True,\n output_hidden_states=True)\n\n torch_bert_layer_result, torch_qps, torch_time_consume = \\\n test_helper.run_model(torch_model, use_cuda, self.num_iter)\n\n print(f\"BertEncoder Torch QPS, {torch_qps}, \",\n f\"Time Cost, {torch_time_consume}\")\n\n diff = torch.abs(torch_bert_layer_result[0] -\n turbo_bert_layer_result[0])\n self.assertTrue(torch.max(diff) < 1e-2)\n\n # Note we did not print the last hidden_states, because it is the same as output\n # print(len(torch_bert_layer_result[1]), len(turbo_bert_layer_result[1]))\n # for a, b in zip(torch_bert_layer_result[1],\n # turbo_bert_layer_result[1]):\n # diff = torch.abs(a - b)\n # self.assertTrue(torch.max(diff) < 1e-2)\n\n # for a, b in zip(torch_bert_layer_result[2],\n # turbo_bert_layer_result[2]):\n # diff = torch.abs(a - b)\n # self.assertTrue(torch.max(diff) < 1e-2)\n\n def test_encoder(self):\n self.check_torch_and_turbo(use_cuda=False)\n if torch.cuda.is_available() and \\\n turbo_transformers.config.is_compiled_with_cuda():\n self.check_torch_and_turbo(use_cuda=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (C) 2020 THL A29 Limited, a Tencent company.\n# All rights reserved.\n# Licensed under the BSD 3-Clause License (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n# https://opensource.org/licenses/BSD-3-Clause\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# See the AUTHORS file for names of contributors.\n\nimport unittest\nimport torch\nfrom transformers import GPT2Model, GPT2Config\nimport numpy\nimport turbo_transformers\nimport sys\nimport os\n\nsys.path.append(os.path.dirname(__file__))\nimport test_helper\n\n\nclass TestGPT2Model(unittest.TestCase):\n def init_data(self, use_cuda) -> None:\n torch.set_grad_enabled(False)\n torch.set_num_threads(4)\n turbo_transformers.set_num_threads(4)\n self.test_device = torch.device('cuda:0') if use_cuda else \\\n torch.device('cpu:0')\n\n self.cfg = GPT2Config()\n self.torch_model = GPT2Model(self.cfg)\n self.torch_model.eval()\n\n if torch.cuda.is_available():\n self.torch_model.to(self.test_device)\n\n self.turbo_model = turbo_transformers.GPT2Model.from_torch(\n self.torch_model, self.test_device)\n\n def check_torch_and_turbo(self, use_cuda):\n self.init_data(use_cuda)\n num_iter = 1\n device_name = \"GPU\" if use_cuda else \"CPU\"\n input_ids = torch.randint(low=0,\n high=self.cfg.vocab_size - 1,\n size=(1, 10),\n dtype=torch.long,\n device=self.test_device)\n\n torch_model = lambda: self.torch_model(input_ids)\n torch_result, torch_qps, torch_time = \\\n test_helper.run_model(torch_model, use_cuda, num_iter)\n print(f'GPT2Model PyTorch({device_name}) QPS {torch_qps}')\n\n turbo_model = (lambda: self.turbo_model(input_ids))\n\n turbo_result, turbo_qps, turbo_time = \\\n test_helper.run_model(turbo_model, use_cuda, num_iter)\n print(f'GPT2Model TurboTransformer({device_name}) QPS {turbo_qps}')\n\n self.assertTrue(\n numpy.allclose(torch_result[0].cpu(),\n turbo_result[0].cpu(),\n atol=1e-3,\n rtol=1e-3))\n\n def test_gpt2_model(self):\n # TODO(jiaruifang) in order to pass github ci test, which only check cpu\n # onnxrt may be unstable to pass this CI\n if torch.cuda.is_available() and \\\n turbo_transformers.config.is_compiled_with_cuda():\n # self.check_torch_and_turbo(use_cuda=True)\n pass\n else:\n # self.check_torch_and_turbo(use_cuda=False)\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "torch.onnx.export", "torch.randint", "torch.ones", "torch.cat", "torch.tensor", "torch.no_grad", "torch.cuda.is_available", "torch.t" ], [ "torch.abs", "torch.ones", "torch.max", "torch.set_grad_enabled", "torch.set_num_threads", "torch.rand", "torch.cuda.is_available", "torch.device" ], [ "torch.randint", "torch.set_grad_enabled", "torch.set_num_threads", "torch.cuda.is_available", "torch.device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
collassubmission91/CompoSuite-Code
[ "ac544efb68a11ed8a483b0932975c4949f0cec90" ]
[ "compositional-rl-benchmark/composition/spinningup_training/train_compositional_ppo_smallscale.py" ]
[ "from email.policy import default\nimport numpy as np\nimport argparse\nimport composition\nimport os\nimport json\n\nimport torch\n\nfrom spinup.algos.pytorch.ppo.compositional_core import CompositionalMLPActorCritic\nfrom spinup.algos.pytorch.ppo.ppo import ppo\nfrom spinup.utils.run_utils import setup_logger_kwargs\nfrom spinup.utils.mpi_tools import proc_id, num_procs\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data-dir', default='spinningup_training/logs')\n parser.add_argument('--load-dir', default=None)\n\n parser.add_argument('--gridsearch-id', type=int, default=-1)\n parser.add_argument('--task-id', type=int, default=-1)\n\n parser.add_argument('--hid', type=int, default=64)\n parser.add_argument('--l', type=int, default=2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--seed', '-s', type=int, default=4)\n parser.add_argument('--cpu', type=int, default=4)\n parser.add_argument('--steps', type=int, default=16000)\n parser.add_argument('--epochs', type=int, default=625)\n parser.add_argument('--exp-name', type=str, default='ppo')\n parser.add_argument('--clip', type=float, default=0.2)\n parser.add_argument('--pi-lr', type=float, default=1e-4)\n parser.add_argument('--vf-lr', type=float, default=1e-4)\n parser.add_argument('--pi-iters', type=int, default=128)\n parser.add_argument('--vf-iters', type=int, default=128)\n parser.add_argument('--target-kl', type=float, default=0.02)\n parser.add_argument('--ent-coef', type=float, default=0.02)\n parser.add_argument('--log-std-init', type=float, default=0.)\n\n parser.add_argument('--controller', type=str, default=\"joint\")\n parser.add_argument('--robot', type=str, default=\"IIWA\")\n parser.add_argument('--object', type=str, default=\"Hollowbox\")\n parser.add_argument('--obstacle', type=str, default=None)\n parser.add_argument('--task', type=str, default=\"PickPlace\")\n parser.add_argument('--horizon', type=int, default=500)\n\n parser.add_argument('--large-net', action='store_true')\n\n args = parser.parse_args()\n\n args.seed = args.task_id % 3\n np.random.seed(args.seed)\n task_list = np.random.choice(64, num_procs(), replace=False)\n \n axis_indicator = args.task_id // 3\n \n args.task_id = int(task_list[proc_id()])\n \n _robots = [\"IIWA\", \"Jaco\", \"Kinova3\", \"Panda\"]\n _objects = [\"Box\", \"Dumbbell\", \"Plate\", \"Hollowbox\"]\n _objectives = [\"PickPlace\", \"Push\", \"Shelf\", \"Trashcan\"]\n _obstacles = [\"None\", \"GoalWall\", \"ObjectDoor\", \"ObjectWall\"]\n\n if axis_indicator == 0:\n _robots = [\"IIWA\"]\n elif axis_indicator == 1:\n _objects = [\"Hollowbox\"]\n elif axis_indicator == 2:\n _objectives = [\"PickPlace\"]\n else: \n _obstacles = [\"None\"]\n\n idx = np.unravel_index(args.task_id, (len(_robots), len(_objects), len(_objectives), len(_obstacles)))\n args.robot = _robots[idx[0]]\n args.object = _objects[idx[1]]\n args.task = _objectives[idx[2]]\n args.obstacle = _obstacles[idx[3]]\n\n args.exp_name = 'MTL_{}'.format(len(task_list))\n args.data_dir = args.data_dir + \"_64tasks_axis\" + str(axis_indicator) + \"_s\" + str(args.seed)\n return args\n\n\ndef main():\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n torch.set_num_threads(1)\n\n args = parse_args()\n os.makedirs(os.path.join(args.data_dir, args.exp_name), exist_ok=True)\n with open(os.path.join(args.data_dir, args.exp_name, 'args_{}.json'.format(proc_id())), 'w') as f:\n json.dump(args.__dict__, f, indent=2)\n\n logger_kwargs = setup_logger_kwargs(\n args.exp_name, data_dir=args.data_dir)\n\n if args.large_net:\n hidden_sizes = ((64,), (64, 64), (128, 128, 128), (128, 128, 128))\n else:\n hidden_sizes = ((32,), (32, 32), (64, 64, 64), (64, 64, 64))\n\n ac_kwargs = {\n # 'hidden_sizes': [args.hid]*args.l, \n 'log_std_init': args.log_std_init,\n 'hidden_sizes': hidden_sizes, \n 'module_names': ['obstacle_id', 'object_id', 'subtask_id', 'robot_id'],\n 'module_input_names': ['obstacle-state', 'object-state', 'goal-state', 'robot0_proprio-state'],\n 'interface_depths': [-1, 1, 2, 3] , \n 'graph_structure': [[0], [1], [2], [3]],\n }\n\n checkpoint = None\n if args.load_dir is not None:\n checkpoint = torch.load(os.path.join(args.load_dir, 'pyt_save', 'state_dicts.pt'))\n\n ppo(lambda: composition.make(\n args.robot, args.object, args.obstacle, args.task, args.controller, args.horizon, use_task_id_obs=True), actor_critic=CompositionalMLPActorCritic,\n ac_kwargs=ac_kwargs, seed=args.seed, gamma=args.gamma, steps_per_epoch=args.steps, epochs=args.epochs, clip_ratio=args.clip,\n pi_lr=args.pi_lr, vf_lr=args.vf_lr, train_pi_iters=args.pi_iters, train_v_iters=args.vf_iters, target_kl=args.target_kl,\n logger_kwargs=logger_kwargs, max_ep_len=args.horizon, ent_coef=args.ent_coef, log_per_proc=True, checkpoint=checkpoint)\n\n\nif __name__ == '__main__':\n main()\n\n\n'''\n\nobs = 14\nobj = 14\ngoal = 17\nrobot = 32\n\ntask-id = 17\n\n(small)\nobs: 32 (14 + 1) = 480\nobj: 32 (14 + 1) + 32 (64 + 1) = 2560 \ngoal: 64 (17 + 1) + 64 (64 + 1) + 64 (96 + 1) = 11520\nrobot: 64 (32 + 1) + 64 (64 + 1) + 64 (64 + 1) + 1 (128 + 1) = 10561\n = 25121\n\n(large)\nobs: 64 (14 + 1) = 960\nobj: 64 (14 + 1) + 64 (128 + 1) = 9216 \ngoal: 128 (17 + 1) + 128 (128 + 1) + 128 (192 + 1) = 43520\nrobot: 128 (32 + 1) + 128 (128 + 1) + 128 (128 + 1) + 1 (256 + 1) = 37505\n = 91201\n\noriginal: 256 (94 + 1) + 256 (256 + 1) + 1 (256 + 1) = 90369\n'''\n" ]
[ [ "torch.set_num_threads", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
OoSnowfxm/AlphaZero_Othello
[ "3e94ac29dbac413502eb85628a0f8eb6d402d5e9" ]
[ "AlphaGoZero/code/Framework/Mcts.py" ]
[ "'''\n @Author: fxm\n @Date: Dec 27, 2020.\n @Title: Mcts class.\n'''\n\nimport logging\nimport math\nimport numpy as np\n\nEps = 1e-8\nlog = logging.getLogger(__name__)\n\n# 蒙特卡洛树搜索对象\nclass MCTS():\n '''\n 初始化过程\n 参数设置:\n game:游戏对象\n net:网络对象\n args:参数\n N(s,a):记录边的访问次数\n     S(s): 记录该状态的访问次数,有S(s) = sum(N(s,i))\n     Q(s,a) :平均行动价值\n     P(s,a) :选择该条边的先验概率\n Ended(s):存储状态s是否对应了游戏结束\n Valid(s):存储状态s对应的所有的可行动作\n '''\n def __init__(self, game, net, args):\n self.game = game\n self.net = net\n self.args = args\n self.Q = {} \n self.N = {} \n self.S = {} \n self.P = {} \n self.Ended = {} \n self.Valid = {} \n \n '''\n 获得当前棋盘得到的动作的概率向量\n 在temp为0的时候,说明网络深度已经很深,\n 这时候采用将最大概率设为1来计算概率向量\n '''\n def getActionProb(self, canonicalBoard, temp=1):\n for _ in range(self.args.numMCTSSims):\n self.search(canonicalBoard)\n\n # 获得棋盘的字符串解释\n s = self.game.stringRepresentation(canonicalBoard)\n counts = [self.N[(s, a)] if (s, a) in self.N else 0 \\\n for a in range(self.game.getActionSize())]\n\n # 如果temp = 0,我们期望获取准确的动作,也就是测试阶段和深度过深的训练阶段\n if temp == 0:\n idx = np.array(np.argwhere(counts == np.max(counts))).flatten()\n idx = np.random.choice(idx)\n probs = [0] * len(counts)\n probs[idx] = 1\n return probs\n\n # 如果temp不为0,我们期望获取动作的概率向量,也就是深度不深的训练阶段\n counts = [x ** (1. / temp) for x in counts]\n counts_sum = float(sum(counts))\n probs = [x / counts_sum for x in counts]\n return probs\n\n '''\n 蒙特卡洛搜索树过程\n 接收当前玩家看到的棋盘为参数\n 主要作用为更新Q表的值\n '''\n def search(self, canonicalBoard):\n # 获得当前棋盘的字符串解释,注意是玩家所看到的棋盘\n s = self.game.stringRepresentation(canonicalBoard)\n # 如果当前状态不在结束判别列表内,就加入到列表中\n if s not in self.Ended:\n self.Ended[s] = self.game.getGameEnded(canonicalBoard, 1)\n if self.Ended[s] != -2:\n return -self.Ended[s]\n \n # 如果策略列表中没有,就使用深度网络预测的值\n if s not in self.P:\n self.P[s], v = self.net.predict(canonicalBoard)\n valids = self.game.getValid(canonicalBoard, 1)\n self.P[s] = self.P[s] * valids \n sump = np.sum(self.P[s])\n # 将结果修正到0——1之间\n if sump > 0:\n self.P[s] /= sump \n # 如果神经网络预测的结果有问题,那么直接使用valid作为当前状态下的策略\n # 这个时候每一个合法的动作都拥有相同的概率\n else: \n log.error(\"All valid moves were masked, doing a workaround.\")\n self.P[s] = self.P[s] + valids\n self.P[s] /= np.sum(self.P[s])\n\n self.Valid[s] = valids\n self.S[s] = 0\n return -v\n\n # 在当前状态下根据Q表选择最佳的动作\n valids = self.Valid[s]\n best = -float('inf')\n best_action = -1\n\n # 从所有合法动作中选择出UCT值最大的一个作为当前状态的下一个动作\n for a in range(self.game.getActionSize()):\n if valids[a]:\n # 如果Q中已经有这一项\n if (s, a) in self.Q:\n u = self.Q[(s, a)] + self.args.cpuct * self.P[s][a] * \\\n math.sqrt(self.S[s]) / (1 + self.N[(s, a)])\n # 如果没有\n else:\n u = self.args.cpuct * self.P[s][a] * math.sqrt(self.S[s] + Eps) \n # 更新当前的最优动作\n if u > best:\n best = u\n best_action = a\n\n # 获取下一个动作\n a = best_action\n next_state, next_player = self.game.getNextState(canonicalBoard, 1, a)\n next_state = self.game.getCanonicalForm(next_state, next_player)\n\n # 递归实现搜索过程,本质上是一个回溯过程\n v = self.search(next_state)\n\n # 这些是蒙特卡洛树搜索的反向传播过程,也是递归的回溯部分\n # 更新Q,原来的加上新的值\n if (s, a) in self.Q:\n self.Q[(s, a)] = (self.N[(s, a)] * self.Q[(s, a)] + v * 1) / (self.N[(s, a)] + 1)\n self.N[(s, a)] += 1\n else:\n self.Q[(s, a)] = v\n self.N[(s, a)] = 1\n\n self.S[s] += 1\n return -v\n" ]
[ [ "numpy.max", "numpy.sum", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gayatripk1/tvm
[ "8bf6cd5800daaf42935fd69cbd63180c97bef262" ]
[ "tests/python/contrib/test_hexagon/test_benchmark_elemwise_add.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport os.path\nimport sys\nimport pytest\nimport numpy as np\nimport logging\nimport tempfile\n\nimport tvm.testing\nimport tvm.script\nfrom tvm.script import tir as T\nfrom tvm import te\nfrom tvm.contrib.hexagon.build import HexagonLauncherRPC\nfrom . import benchmark_util as bu\n\n_SHOULD_SKIP_BENCHMARKS, _SKIP_BENCHMARKS_REASON = bu.skip_bencharks_flag_and_reason()\n\n# This is a fixed detail of the v68 architecture.\nHVX_VECTOR_BYTES = 128\n\n_HEXAGON_TARGET = tvm.target.hexagon(\"v69\", link_params=True)\n\n_SUPER_TARGET = tvm.target.Target(_HEXAGON_TARGET, host=_HEXAGON_TARGET)\n\n# NOTE on server ports:\n# These tests use different port numbers for the RPC server (7070 + ...).\n# The reason is that an RPC session cannot be gracefully closed without\n# triggering TIME_WAIT state on the server socket. This prevents another\n# server to bind to the same port until the wait time elapses.\n\n_BT = bu.BenchmarksTable()\n\n_CSV_COLUMN_ORDER = [\n # Identifies which TE-compute / TIRScript is used as the basis for the\n # benchmarked primfunc. Only needs to be meaningful to humans.\n \"basic_kernel\",\n # The tensors' element type\n \"dtype\",\n # When applicable, indicates the particular variation of schedules\n # apply by the Python code. Decoding this may require looking at this\n # script's source code.\n \"sched_type\",\n # The memory location of the tensors used during the execution of\n # the primfunc. We currently assume just one location.\n # This will likely need to be generalized as we add more sophisticated\n # primfuncs.\n \"mem_scope\",\n # For primfuncs that treat tensor buffers as collections of 1D vectors,\n # this is the number of vectors in each tensor.\n # This will likely need to be generalized as we add more sophisticated\n # primfuncs.\n \"num_vectors_per_tensor\",\n # Reserved columns defined by the BenchmarksTable class.\n \"row_status\",\n \"timings_min_usecs\",\n \"timings_max_usecs\",\n \"timings_median_usecs\",\n \"timings_mean_usecs\",\n \"timings_stddev_usecs\",\n # For benchmarks that produce files on the host file system, this indicates\n # their location. Useful for post-mortem investigation of benchmark results.\n \"host_files_dir_path\",\n # Miscellaneous comments about the benchmark.\n \"comments\",\n]\n\n_HOST_OUTPUT_DIR = tempfile.mkdtemp()\n\n_PRIMFUNC_NAME = \"elemwise_add\"\n\nprint(\"-\" * 80)\nprint(\"OUTPUT DIRECTORY: {}\".format(_HOST_OUTPUT_DIR))\nprint(\"-\" * 80)\nprint()\n\nfrom typing import Tuple\n\n\ndef _get_irmod_elemwise_add(\n _PRIMFUNC_NAME: str, shape: list, dtype: str, mem_scope: str\n) -> tvm.ir.module.IRModule:\n \"\"\"\n Return an IRModule containing a single primfunc, expressed as NS-TIR.\n\n The primfunc implements elementwise-add. Its signature is (A,B,C), where\n A and B are the input tensors, and C is the output tensor.\n All three tensors have the specfied shape, dtype, and mem_scope.\n\n If the specified primfunc is known to be unsupported, raise an UnsupportedExcetion.\n \"\"\"\n assert len(shape) == 2\n\n # TVMScript can reference simple Python variables, but it doesn't\n # curently support more complex Python expressions...\n (\n dim0_size,\n dim1_size,\n ) = shape\n dtype_str = str(dtype)\n\n if mem_scope == \"global.vtcm\":\n raise bu.UnsupportedException(\"This benchmark kernel does not yet support VTCM buffers.\")\n\n # This check is currently elided by the one above, but it should become relevant as soon\n # as we add VTCM support to this kernel generator.\n #\n # Also: The VTCM budget is a very rough estimate, based only on experience.\n # Assuming that it's even reasonable to use a hard-coded estimate AT ALL, this number\n # may need tweaking.\n estimated_vtcm_budget_bytes = HVX_VECTOR_BYTES * 1024\n\n dtype_bits = tvm._ffi.runtime_ctypes.DataType(dtype).bits\n assert dtype_bits % 8 == 0\n dtype_bytes = dtype_bits // 8\n\n num_vtcm_tensors = 3\n estimated_vtcm_needed_bytes = shape[0] * shape[1] * dtype_bytes * num_vtcm_tensors\n\n if estimated_vtcm_needed_bytes > estimated_vtcm_budget_bytes:\n raise bu.UnsupportedException(\"Expect to exceed VTCM budget.\")\n\n @tvm.script.ir_module\n class BenchmarkModule:\n @T.prim_func\n def main(a: T.handle, b: T.handle, c: T.handle):\n # We exchange data between function by handles, which are similar to pointer.\n T.func_attr({\"global_symbol\": \"main\", \"tir.noalias\": True})\n\n A = T.match_buffer(a, shape, dtype=dtype)\n B = T.match_buffer(b, shape, dtype=dtype)\n C = T.match_buffer(c, shape, dtype=dtype)\n\n for i in range(dim0_size):\n for j in range(dim1_size):\n C[i, j] = A[i, j] + B[i, j]\n\n return BenchmarkModule\n\n\ndef _benchmark_hexagon_elementwise_add_kernel(\n hexagon_launcher: HexagonLauncherRPC, shape: list, dtype: str, mem_scope: str\n):\n \"\"\"\n Generate and benchmark a single elementwise-add kernel for Hexagon.\n\n Produce these outputs:\n - Printed status updates / results to stdout and/or stderr.\n\n - Create a new subdirectory under _HOST_OUTPUT_DIR, and populate it with\n various logs and intermediate files.\n\n - Add to _BT a row describing this benchmark run.\n \"\"\"\n # Represent the benchmark details in a form required by the benchmark table\n # and for other logging...\n keys_dict = {\n \"basic_kernel\": \"ewise-add\",\n \"dtype\": dtype,\n \"shape\": shape,\n \"mem_scope\": mem_scope,\n }\n\n desc = bu.get_benchmark_decription(keys_dict)\n\n # Create the host-side directory for this benchmark run's files / logs...\n host_files_dir_name = bu.get_benchmark_id(keys_dict)\n host_files_dir_path = os.path.join(_HOST_OUTPUT_DIR, host_files_dir_name)\n os.mkdir(host_files_dir_path)\n\n keys_dict[\"host_files_dir_path\"] = host_files_dir_path\n\n log_file_path = os.path.join(host_files_dir_path, \"out.txt\")\n with open(log_file_path, \"w\") as log_file:\n print(f\"CONFIGURATION: {desc}\")\n log_file.write(f\"CONFIGURATION: {desc}\\n\")\n\n try:\n ns_tir_module = _get_irmod_elemwise_add(_PRIMFUNC_NAME, shape, dtype, mem_scope)\n\n # Dump the primfunc NS-TIR (as text) to the log file...\n lowered_mod = tvm.lower(ns_tir_module, _PRIMFUNC_NAME)\n log_file.write(\"LOWERED IR MODULE:\\n\")\n log_file.write(str(lowered_mod))\n log_file.write(\"\\n\")\n\n # Lower the primfunc's IRModule to Hexagon object code...\n A = tvm.te.placeholder(shape, dtype=dtype)\n B = tvm.te.placeholder(shape, dtype=dtype)\n C = tvm.te.placeholder(shape, dtype=dtype)\n\n built_module: tvm.driver.build_module.OperatorModule = tvm.build(\n ns_tir_module,\n [\n A,\n B,\n C,\n ],\n _SUPER_TARGET,\n name=_PRIMFUNC_NAME,\n )\n\n # Create an actual Hexagon-native shared object file, initially stored on the\n # host's file system...\n host_dso_binary_path = os.path.join(host_files_dir_path, \"test_binary.so\")\n built_module.save(host_dso_binary_path)\n print(f\"SAVED BINARY TO HOST PATH: {host_dso_binary_path}\")\n\n # Upload the .so to the Android device's file system (or wherever is appropriate\n # when using the Hexagon simulator)...\n target_dso_binary_filename = \"test_binary.so\"\n target_dso_binary_pathname = hexagon_launcher.upload(\n host_dso_binary_path, target_dso_binary_filename\n )\n\n # Generate our testing / validation data...\n (\n host_numpy_A_data,\n host_numpy_B_data,\n host_numpy_C_data_expected,\n ) = _get_elemwise_add_reference_value_tensors(shape, dtype)\n\n with hexagon_launcher.start_session() as sess:\n # On the target device / simulator, make our Hexagon-native shared object\n # available for use...\n loaded_hexagon_module: tvm.runtime.module.Module = hexagon_launcher.load_module(\n target_dso_binary_pathname, sess\n )\n\n # Create the target-side tensors to hold the primfunc's inputs and outputs...\n A_data = tvm.nd.empty(shape, dtype, sess.device, mem_scope)\n B_data = tvm.nd.empty(shape, dtype, sess.device, mem_scope)\n C_data = tvm.nd.empty(shape, dtype, sess.device, mem_scope)\n\n # Populate the primfunc's input tensors...\n A_data.copyfrom(host_numpy_A_data)\n B_data.copyfrom(host_numpy_B_data)\n\n # Actually benchmark the primfunc...\n timer = loaded_hexagon_module.time_evaluator(\n \"main\", sess.device, number=10, repeat=1\n )\n timing_result = timer(A_data, B_data, C_data)\n\n print(f\"TIMING RESULT: {timing_result}\")\n log_file.write(f\"TIMING RESULT: {timing_result}\\n\")\n\n # Verify that the computation actually happened, and produced the correct result.\n result = C_data.numpy()\n\n if dtype == \"float16\":\n # These are the closest tolerance we currently expect / require for these\n # kernels. They may be changed in the future.\n rel_tolerance = 0.005\n abs_tolerance = 2.0\n elif dtype == \"int8\":\n rel_tolerance = 0\n abs_tolerance = 0\n else:\n raise Exception(f\"Unexpected dtype: {dtype}\")\n\n # TODO: We're assuming that *any* assertion thrown by 'assert_allclose' is because\n # the numerical differences were too large. But ideally this code would\n # differentiate between (a) numerical difference errors, which should simply be\n # recorded as a failed benchmark run, vs. (b) more serious errors that should\n # kill the overall script.\n try:\n tvm.testing.assert_allclose(\n result, host_numpy_C_data_expected, rel_tolerance, abs_tolerance\n )\n except AssertionError as e:\n raise bu.NumericalAccuracyException(str(e))\n\n _BT.record_success(timing_result, **keys_dict)\n\n except bu.NumericalAccuracyException as e:\n print()\n print(f\"FAIL: Numerical accuracy error. See log file.\")\n\n log_file.write(\"\\n\")\n log_file.write(f\"FAIL: {e}\\n\")\n\n _BT.record_fail(**keys_dict, comments=f\"Numerical accuracy error. See log file.\")\n\n except bu.UnsupportedException as e:\n print()\n print(f\"SKIP: {e}\")\n\n log_file.write(\"\\n\")\n log_file.write(f\"SKIP: {e}\\n\")\n\n _BT.record_skip(**keys_dict, comments=f\"Unsupported configuration: {e}\")\n\n\ndef _get_elemwise_add_reference_value_tensors(shape: list, dtype: str):\n \"\"\"\n Return [A:np.array, B:np.array, C:np.array]\n\n `A`, `B`, and `C` are reference data used to exercise and validate\n an elementwise-add kernel: C = A+B.\n\n NOTE: These data are primarily meant for performance testing.\n The values may be helpful in detecting correctness issues, but that's\n a secondary consideration here.\n \"\"\"\n assert len(shape) == 2\n\n A = np.ndarray(shape, dtype=dtype)\n B = np.ndarray(shape, dtype=dtype)\n\n np_dtype = A.dtype\n\n if np_dtype.kind in [\"i\", \"u\"]:\n # We allow overflow for integer types because it tends to be well-behaved\n # and well-understood...\n min_value = np.iinfo(np_dtype).min\n max_value = np.iinfo(np_dtype).max\n\n next_value = min_value\n\n for i in range(shape[0]):\n for j in range(shape[1]):\n A[i, j] = next_value\n B[i, j] = next_value * 2\n next_value += 1\n\n elif np_dtype.kind == \"f\":\n # NOTE: For simplicity, we avoid test data that that require\n # well-defined behavior on floating-point overflow.\n # But it may be reasonable to test that in the future.\n min_value = np.finfo(np_dtype).min\n max_value = np.finfo(np_dtype).max\n\n min_input_value = min_value / 2.0 + 1\n max_input_value = max_value / 2.0 - 2\n delta = (max_input_value - min_input_value) / (shape[0] * shape[1])\n\n next_value = min_input_value\n\n for i in range(shape[0]):\n for j in range(shape[1]):\n A[i, j] = next_value\n B[i, j] = next_value + 1\n next_value += delta\n\n else:\n assert False, f\"Unexpected data type: {np_dtype}\"\n\n C = A + B\n return [\n A,\n B,\n C,\n ]\n\n\[email protected](_SHOULD_SKIP_BENCHMARKS, reason=_SKIP_BENCHMARKS_REASON)\[email protected]_hexagon\ndef test_elemwise_add(hexagon_launcher: HexagonLauncherRPC):\n for dtype in [\n \"int8\",\n \"float16\",\n ]:\n\n for mem_scope in [\n \"global\",\n \"global.vtcm\",\n ]:\n\n # These numbers are fairly arbitrary, but they're meant to stress memory/caches to\n # various extents.\n for num_vectors_per_tensor in [\n 1,\n 16,\n 64,\n 512,\n 2048,\n ]:\n\n dtype_bits = tvm._ffi.runtime_ctypes.DataType(dtype).bits\n assert dtype_bits % 8 == 0\n dtype_bytes = dtype_bits // 8\n\n elem_per_hvx_vector = HVX_VECTOR_BYTES // dtype_bytes\n\n shape = [\n num_vectors_per_tensor,\n elem_per_hvx_vector,\n ]\n\n print()\n _benchmark_hexagon_elementwise_add_kernel(hexagon_launcher, shape, dtype, mem_scope)\n\n print(\"-\" * 80)\n print(f\"OUTPUT DIRECTORY: {_HOST_OUTPUT_DIR}\")\n print(\"-\" * 80)\n print()\n\n tabular_output_filename = os.path.join(_HOST_OUTPUT_DIR, \"benchmark-results.csv\")\n with open(tabular_output_filename, \"w\") as csv_file:\n _BT.print_csv(csv_file, _CSV_COLUMN_ORDER)\n\n print(f\"BENCHMARK RESULTS FILE: {tabular_output_filename}\")\n\n _BT.print_csv(sys.stdout, _CSV_COLUMN_ORDER)\n\n if _BT.has_fail() > 0:\n pytest.fail(\"At least one benchmark configuration failed\", pytrace=False)\n\n\nif __name__ == \"__main__\":\n tvm.testing.main()\n" ]
[ [ "numpy.ndarray", "numpy.iinfo", "numpy.finfo" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hyyh28/tesp
[ "a77d9c228a6891b304e789ba2758a4cbfdb75ec0", "a77d9c228a6891b304e789ba2758a4cbfdb75ec0" ]
[ "ray/rllib/test/test_nested_spaces.py", "ray/rllib/agents/pg/pg_policy_graph.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pickle\n\nfrom gym import spaces\nfrom gym.envs.registration import EnvSpec\nimport gym\nimport tensorflow.contrib.slim as slim\nimport tensorflow as tf\nimport unittest\n\nimport ray\nfrom ray.rllib.agents.pg import PGAgent\nfrom ray.rllib.env.async_vector_env import AsyncVectorEnv\nfrom ray.rllib.env.vector_env import VectorEnv\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.models.model import Model\nfrom ray.rllib.test.test_serving_env import SimpleServing\nfrom ray.tune.registry import register_env\n\nDICT_SPACE = spaces.Dict({\n \"sensors\": spaces.Dict({\n \"position\": spaces.Box(low=-100, high=100, shape=(3, )),\n \"velocity\": spaces.Box(low=-1, high=1, shape=(3, )),\n \"front_cam\": spaces.Tuple(\n (spaces.Box(low=0, high=1, shape=(10, 10, 3)),\n spaces.Box(low=0, high=1, shape=(10, 10, 3)))),\n \"rear_cam\": spaces.Box(low=0, high=1, shape=(10, 10, 3)),\n }),\n \"inner_state\": spaces.Dict({\n \"charge\": spaces.Discrete(100),\n \"job_status\": spaces.Dict({\n \"task\": spaces.Discrete(5),\n \"progress\": spaces.Box(low=0, high=100, shape=()),\n })\n })\n})\n\nDICT_SAMPLES = [DICT_SPACE.sample() for _ in range(10)]\n\nTUPLE_SPACE = spaces.Tuple([\n spaces.Box(low=-100, high=100, shape=(3, )),\n spaces.Tuple((spaces.Box(low=0, high=1, shape=(10, 10, 3)),\n spaces.Box(low=0, high=1, shape=(10, 10, 3)))),\n spaces.Discrete(5),\n])\n\nTUPLE_SAMPLES = [TUPLE_SPACE.sample() for _ in range(10)]\n\n\ndef one_hot(i, n):\n out = [0.0] * n\n out[i] = 1.0\n return out\n\n\nclass NestedDictEnv(gym.Env):\n def __init__(self):\n self.action_space = spaces.Discrete(2)\n self.observation_space = DICT_SPACE\n self._spec = EnvSpec(\"NestedDictEnv-v0\")\n self.steps = 0\n\n def reset(self):\n self.steps = 0\n return DICT_SAMPLES[0]\n\n def step(self, action):\n self.steps += 1\n return DICT_SAMPLES[self.steps], 1, self.steps >= 5, {}\n\n\nclass NestedTupleEnv(gym.Env):\n def __init__(self):\n self.action_space = spaces.Discrete(2)\n self.observation_space = TUPLE_SPACE\n self._spec = EnvSpec(\"NestedTupleEnv-v0\")\n self.steps = 0\n\n def reset(self):\n self.steps = 0\n return TUPLE_SAMPLES[0]\n\n def step(self, action):\n self.steps += 1\n return TUPLE_SAMPLES[self.steps], 1, self.steps >= 5, {}\n\n\nclass InvalidModel(Model):\n def _build_layers_v2(self, input_dict, num_outputs, options):\n return \"not\", \"valid\"\n\n\nclass DictSpyModel(Model):\n capture_index = 0\n\n def _build_layers_v2(self, input_dict, num_outputs, options):\n def spy(pos, front_cam, task):\n # TF runs this function in an isolated context, so we have to use\n # redis to communicate back to our suite\n ray.experimental.internal_kv._internal_kv_put(\n \"d_spy_in_{}\".format(DictSpyModel.capture_index),\n pickle.dumps((pos, front_cam, task)))\n DictSpyModel.capture_index += 1\n return 0\n\n spy_fn = tf.py_func(\n spy, [\n input_dict[\"obs\"][\"sensors\"][\"position\"],\n input_dict[\"obs\"][\"sensors\"][\"front_cam\"][0],\n input_dict[\"obs\"][\"inner_state\"][\"job_status\"][\"task\"]\n ],\n tf.int64,\n stateful=True)\n\n with tf.control_dependencies([spy_fn]):\n output = slim.fully_connected(\n input_dict[\"obs\"][\"sensors\"][\"position\"], num_outputs)\n return output, output\n\n\nclass TupleSpyModel(Model):\n capture_index = 0\n\n def _build_layers_v2(self, input_dict, num_outputs, options):\n def spy(pos, cam, task):\n # TF runs this function in an isolated context, so we have to use\n # redis to communicate back to our suite\n ray.experimental.internal_kv._internal_kv_put(\n \"t_spy_in_{}\".format(TupleSpyModel.capture_index),\n pickle.dumps((pos, cam, task)))\n TupleSpyModel.capture_index += 1\n return 0\n\n spy_fn = tf.py_func(\n spy, [\n input_dict[\"obs\"][0],\n input_dict[\"obs\"][1][0],\n input_dict[\"obs\"][2],\n ],\n tf.int64,\n stateful=True)\n\n with tf.control_dependencies([spy_fn]):\n output = slim.fully_connected(input_dict[\"obs\"][0], num_outputs)\n return output, output\n\n\nclass NestedSpacesTest(unittest.TestCase):\n def testInvalidModel(self):\n ModelCatalog.register_custom_model(\"invalid\", InvalidModel)\n self.assertRaises(ValueError, lambda: PGAgent(\n env=\"CartPole-v0\", config={\n \"model\": {\n \"custom_model\": \"invalid\",\n },\n }))\n\n def doTestNestedDict(self, make_env):\n ModelCatalog.register_custom_model(\"composite\", DictSpyModel)\n register_env(\"nested\", make_env)\n pg = PGAgent(\n env=\"nested\",\n config={\n \"num_workers\": 0,\n \"sample_batch_size\": 5,\n \"model\": {\n \"custom_model\": \"composite\",\n },\n })\n pg.train()\n\n # Check that the model sees the correct reconstructed observations\n for i in range(4):\n seen = pickle.loads(\n ray.experimental.internal_kv._internal_kv_get(\n \"d_spy_in_{}\".format(i)))\n pos_i = DICT_SAMPLES[i][\"sensors\"][\"position\"].tolist()\n cam_i = DICT_SAMPLES[i][\"sensors\"][\"front_cam\"][0].tolist()\n task_i = one_hot(\n DICT_SAMPLES[i][\"inner_state\"][\"job_status\"][\"task\"], 5)\n self.assertEqual(seen[0][0].tolist(), pos_i)\n self.assertEqual(seen[1][0].tolist(), cam_i)\n self.assertEqual(seen[2][0].tolist(), task_i)\n\n def doTestNestedTuple(self, make_env):\n ModelCatalog.register_custom_model(\"composite2\", TupleSpyModel)\n register_env(\"nested2\", make_env)\n pg = PGAgent(\n env=\"nested2\",\n config={\n \"num_workers\": 0,\n \"sample_batch_size\": 5,\n \"model\": {\n \"custom_model\": \"composite2\",\n },\n })\n pg.train()\n\n # Check that the model sees the correct reconstructed observations\n for i in range(4):\n seen = pickle.loads(\n ray.experimental.internal_kv._internal_kv_get(\n \"t_spy_in_{}\".format(i)))\n pos_i = TUPLE_SAMPLES[i][0].tolist()\n cam_i = TUPLE_SAMPLES[i][1][0].tolist()\n task_i = one_hot(TUPLE_SAMPLES[i][2], 5)\n self.assertEqual(seen[0][0].tolist(), pos_i)\n self.assertEqual(seen[1][0].tolist(), cam_i)\n self.assertEqual(seen[2][0].tolist(), task_i)\n\n def testNestedDictGym(self):\n self.doTestNestedDict(lambda _: NestedDictEnv())\n\n def testNestedDictVector(self):\n self.doTestNestedDict(\n lambda _: VectorEnv.wrap(lambda i: NestedDictEnv()))\n\n def testNestedDictServing(self):\n self.doTestNestedDict(lambda _: SimpleServing(NestedDictEnv()))\n\n def testNestedDictAsync(self):\n self.assertRaisesRegexp(\n ValueError, \"Found raw Dict space.*\",\n lambda: self.doTestNestedDict(\n lambda _: AsyncVectorEnv.wrap_async(NestedDictEnv())))\n\n def testNestedTupleGym(self):\n self.doTestNestedTuple(lambda _: NestedTupleEnv())\n\n def testNestedTupleVector(self):\n self.doTestNestedTuple(\n lambda _: VectorEnv.wrap(lambda i: NestedTupleEnv()))\n\n def testNestedTupleServing(self):\n self.doTestNestedTuple(lambda _: SimpleServing(NestedTupleEnv()))\n\n def testNestedTupleAsync(self):\n self.assertRaisesRegexp(\n ValueError, \"Found raw Tuple space.*\",\n lambda: self.doTestNestedTuple(\n lambda _: AsyncVectorEnv.wrap_async(NestedTupleEnv())))\n\n\nif __name__ == \"__main__\":\n ray.init(num_cpus=5)\n unittest.main(verbosity=2)\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport ray\nfrom ray.rllib.models.catalog import ModelCatalog\nfrom ray.rllib.evaluation.postprocessing import compute_advantages\nfrom ray.rllib.evaluation.tf_policy_graph import TFPolicyGraph\n\n\nclass PGLoss(object):\n \"\"\"Simple policy gradient loss.\"\"\"\n\n def __init__(self, action_dist, actions, advantages):\n self.loss = -tf.reduce_mean(action_dist.logp(actions) * advantages)\n\n\nclass PGPolicyGraph(TFPolicyGraph):\n \"\"\"Simple policy gradient example of defining a policy graph.\"\"\"\n\n def __init__(self, obs_space, action_space, config):\n config = dict(ray.rllib.agents.pg.pg.DEFAULT_CONFIG, **config)\n self.config = config\n\n # Setup placeholders\n obs = tf.placeholder(tf.float32, shape=[None] + list(obs_space.shape))\n dist_class, self.logit_dim = ModelCatalog.get_action_dist(\n action_space, self.config[\"model\"])\n prev_actions = ModelCatalog.get_action_placeholder(action_space)\n prev_rewards = tf.placeholder(tf.float32, [None], name=\"prev_reward\")\n\n # Create the model network and action outputs\n self.model = ModelCatalog.get_model({\n \"obs\": obs,\n \"prev_actions\": prev_actions,\n \"prev_rewards\": prev_rewards\n }, obs_space, self.logit_dim, self.config[\"model\"])\n action_dist = dist_class(self.model.outputs) # logit for each action\n\n # Setup policy loss\n actions = ModelCatalog.get_action_placeholder(action_space)\n advantages = tf.placeholder(tf.float32, [None], name=\"adv\")\n loss = PGLoss(action_dist, actions, advantages).loss\n\n # Mapping from sample batch keys to placeholders. These keys will be\n # read from postprocessed sample batches and fed into the specified\n # placeholders during loss computation.\n loss_in = [\n (\"obs\", obs),\n (\"actions\", actions),\n (\"prev_actions\", prev_actions),\n (\"prev_rewards\", prev_rewards),\n (\"advantages\", advantages), # added during postprocessing\n ]\n\n # Initialize TFPolicyGraph\n sess = tf.get_default_session()\n TFPolicyGraph.__init__(\n self,\n obs_space,\n action_space,\n sess,\n obs_input=obs,\n action_sampler=action_dist.sample(),\n loss=loss,\n loss_inputs=loss_in,\n state_inputs=self.model.state_in,\n state_outputs=self.model.state_out,\n prev_action_input=prev_actions,\n prev_reward_input=prev_rewards,\n seq_lens=self.model.seq_lens,\n max_seq_len=config[\"model\"][\"max_seq_len\"])\n sess.run(tf.global_variables_initializer())\n\n def postprocess_trajectory(self,\n sample_batch,\n other_agent_batches=None,\n episode=None):\n # This ads the \"advantages\" column to the sample batch\n return compute_advantages(\n sample_batch, 0.0, self.config[\"gamma\"], use_gae=False)\n\n def get_initial_state(self):\n return self.model.state_init\n" ]
[ [ "tensorflow.contrib.slim.fully_connected", "tensorflow.py_func", "tensorflow.control_dependencies" ], [ "tensorflow.get_default_session", "tensorflow.global_variables_initializer", "tensorflow.placeholder" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]