repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
elizavetaMakarova/AI_mincraft_village_building
|
[
"655bee6dd9757fd08c2c5327d9520abd1e34f864"
] |
[
"mapUtils.py"
] |
[
"\"\"\"\nUtilities for (height)maps\n\"\"\"\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef normalize(array):\n \"\"\"Normalizes the array so that the min value is 0 and the max value is 1\n \"\"\"\n return (array - array.min()) / (array.max() - array.min())\n\ndef visualize(*arrays, title=None, autonormalize=True):\n \"\"\"Uses pyplot and OpenCV to visualize one or multiple numpy arrays\n\n Args:\n title (str, optional): display title. Defaults to None.\n autonormalize (bool, optional): Normalizes the array to be between 0 (black) and 255 (white). Defaults to True.\n \"\"\"\n for array in arrays:\n if autonormalize:\n array = (normalize(array) * 255).astype(np.uint8)\n\n plt.figure()\n if title:\n plt.title(title)\n plt_image = cv2.cvtColor(array, cv2.COLOR_BGR2RGB)\n imgplot = plt.imshow(plt_image)\n plt.show()\n\ndef calcGoodHeightmap(worldSlice): \n \"\"\"Calculates a heightmap that is well suited for building. It ignores any logs and leaves and treats water as ground.\n\n Args:\n worldSlice (WorldSlice): an instance of the WorldSlice class containing the raw heightmaps and block data\n\n Returns:\n any: numpy array containing the calculated heightmap\n \"\"\"\n hm_mbnl = worldSlice.heightmaps[\"MOTION_BLOCKING_NO_LEAVES\"]\n heightmapNoTrees = hm_mbnl[:]\n area = worldSlice.rect\n\n for x in range(area[2]):\n for z in range(area[3]):\n while True:\n y = heightmapNoTrees[x, z]\n block = worldSlice.getBlockAt((area[0] + x, y - 1, area[1] + z))\n if block[-4:] == '_log':\n heightmapNoTrees[x,z] -= 1\n else:\n break\n\n return np.array(np.minimum(hm_mbnl, heightmapNoTrees))\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.minimum",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
frederiknolte/tonic
|
[
"9c4e03ca44c4094f3e232f8dbe8c14ab9217fc17"
] |
[
"tonic/torch/agents/td3.py"
] |
[
"import torch\n\nfrom tonic import logger # noqa\nfrom tonic.torch import agents, models, normalizers, updaters\n\n\ndef default_model(device):\n return models.ActorTwinCriticWithTargets(\n actor=models.Actor(\n device=device,\n encoder=models.ObservationEncoder(),\n torso=models.MLP((256, 256), torch.nn.ReLU),\n head=models.DeterministicPolicyHead()),\n critic=models.Critic(\n device=device,\n encoder=models.ObservationActionEncoder(),\n torso=models.MLP((256, 256), torch.nn.ReLU),\n head=models.ValueHead()),\n observation_normalizer=normalizers.MeanStd())\n\n\nclass TD3(agents.DDPG):\n '''Twin Delayed Deep Deterministic Policy Gradient.\n TD3: https://arxiv.org/pdf/1802.09477.pdf\n '''\n\n def __init__(\n self, model=None, replay=None, exploration=None, actor_updater=None,\n critic_updater=None, delay_steps=2, device=\"cpu\"\n ):\n model = model or default_model(device)\n critic_updater = critic_updater or \\\n updaters.TwinCriticDeterministicQLearning()\n super().__init__(\n model=model, replay=replay, exploration=exploration,\n actor_updater=actor_updater, critic_updater=critic_updater)\n self.delay_steps = delay_steps\n self.model.critic = self.model.critic_1\n\n def _update(self):\n keys = ('observations', 'actions', 'next_observations', 'rewards',\n 'discounts')\n for i, batch in enumerate(self.replay.get(*keys)):\n batch = {k: torch.as_tensor(v).to(self.device) for k, v in batch.items()}\n if (i + 1) % self.delay_steps == 0:\n infos = self._update_actor_critic(**batch)\n else:\n infos = dict(critic=self.critic_updater(**batch))\n for key in infos:\n for k, v in infos[key].items():\n logger.store(key + '/' + k, v.cpu().numpy())\n\n # Update the normalizers.\n if self.model.observation_normalizer:\n self.model.observation_normalizer.update()\n if self.model.return_normalizer:\n self.model.return_normalizer.update()\n"
] |
[
[
"torch.as_tensor"
]
] |
chelsilarious/AutoDiff
|
[
"b4ff703f85288bafd85148edb093d7cd47cbed50"
] |
[
"AutoDiff/ad.py"
] |
[
"import numpy as np\nimport inspect\nimport re\nfrom AutoDiff.forwardNode import ForwardNode\nfrom AutoDiff.reverseNode import ReverseNode\nfrom AutoDiff.utils import *\n\n\ndef init_trace(var, variables):\n '''\n Initialize the trace for ForwardNode objects given all variables in function\n\n Input:\n var - str, name of variable to initialize the trace\n variables - list, names for all variables in function\n\n Output:\n Initilized trace for ForwardNode object var\n\n Examples:\n >>> init_trace(var=\"x1\", variables=[\"x1\", \"x2\", \"x3\"])\n [1.0, 0.0, 0.0]\n '''\n trc = np.zeros(len(variables))\n trc[variables.index(var)] = 1\n return trc\n\n\ndef create_node(var, value, variables):\n '''\n Create a new ForwardNode object ForwardNode objects\n\n Input:\n var - str, name of the new ForwardNode variable\n value - int/float, value of the ForwardNode variable\n variables - list, names for all variables in function\n\n Output:\n A new ForwardNode variable\n\n Examples:\n >>> create_node(var=\"x1\", value=5.0, variables=[\"x1\", \"x2\", \"x3\"])\n ForwardNode Variable: ['x1', 'x2', 'x3'], Value: 5.0, Trace: [1. 0. 0.]\n '''\n return ForwardNode(value, init_trace(var,variables), variables)\n\n\ndef gradientF(y, variables, target=None):\n '''\n Calculate the graident using forward mode methods\n\n Input:\n y - ForwardNode, the functions output we a{re caculating\n variables - list, names for all variables in function\n target - list, name of our target variable(s) to calculate the gradient\n\n Output:\n The derivative / partial derivative / gradient / jacobian of input function and target variable\n\n Examples:\n >>> variables = ['x1']\n >>> x1 = create_node(var='x1', value=2, variables=variables)\n >>> y = 3 * x1 + x1 ** 2 - exp(x1)\n >>> der = gradientF(y, variables, target='x1')\n >>> der\n -0.3890560989306504\n\n '''\n if isinstance(y, ForwardNode):\n if target:\n if target not in variables:\n raise AttributeError(\"This is not a variable used! No gradient available!\")\n # derivative dy/dxi or partial derivatives dely/delxi\n return y.trace[variables.index(target)]\n else:\n # gradient [dely/delx1, ..., dely/delxn]\n return [y.trace[variables.index(var)] for var in variables]\n elif isinstance(y, (np.ndarray, list)) and all([isinstance(yi, ForwardNode) for yi in y]):\n if target:\n if target not in variables:\n raise AttributeError(\"This is not a variable used! No gradient available!\")\n # derivatives [dy1/dxi, ..., dym/dxi]\n return [yi.trace[variables.index(target)] for yi in y]\n else:\n # jacobian [[dely1/delx1, ..., dely1/delxn], ..., [delym/delx1, ..., delym/delxn]]\n jcb = [[yi.trace[variables.index(var)] for yi in y] for var in variables]\n return np.array(jcb).T\n else:\n raise TypeError(\"Invalid Input!\")\n\n\ndef gradientR(functions, var_dict, target=None):\n '''\n Calculate the graident using reverse mode methods\n\n Input:\n functions - str, the functions output we a{re caculating\n var_dict - dictionary, name and value pair of all variables in function\n target - list, name of our target variable(s) to calculate the gradient\n\n Output:\n The derivative / partial derivative / gradient / jacobian of input function and target variable\n\n Examples:\n >>> var_dict = {\"x1\": 2}\n >>> functions = \"3 * x1 + x1 ** 2 - exp(x1)\"\n >>> res = gradientR(functions, var_dict, target=[\"x1\"])\n >>> res\n [[-0.3890560989306504]]\n\n '''\n res = []\n variables = list(var_dict.keys())\n if not target:\n target = variables\n nodes = []\n functions = [functions] if isinstance(functions, str) else functions\n\n for var in variables:\n value = var_dict[var]\n exec(f'{var} = ReverseNode(value=value)')\n exec(f'nodes.append((var, {var}))')\n\n for f in functions:\n grads = []\n for name, node in nodes:\n node.gradient_reset()\n y = eval(f)\n for name, node in nodes:\n if name in target:\n g = node.gradient()\n grads.append(g)\n res.append(grads)\n\n if isinstance(target, str):\n res = [item for sublist in res for item in sublist]\n return np.array(res)\n\n\ndef forward_auto_diff(functions, var_dict, target=None):\n '''\n Perform forward mode automatic differentiation\n\n Input:\n functions - str, the functions output we a{re caculating\n var_dict - dictionary, name and value pair of all variables in function\n target - list, name of our target variable(s) to calculate the gradient\n\n Output:\n The derivative / partial derivative / gradient / jacobian of input function and target variable\n\n Examples:\n >>> functions = [\"x1 + sin(x2) * 5\", \"exp(x1) - log(2 * x2)\"]\n >>> var_dict = {\"x1\": 5, \"x2\": 2}\n >>> target = [\"x1\"]\n >>> res = forward_auto_diff(functions, var_dict, target)\n >>> res\n [[1.0, 148.4131591025766]]\n\n '''\n variables = list(var_dict.keys())\n if not target:\n target = variables\n funcs = []\n res = []\n functions = [functions] if isinstance(functions, str) else functions\n\n for var in variables:\n value = var_dict[var]\n exec(f'{var} = create_node(var=var, value=value, variables=variables)')\n\n for f in functions:\n y = eval(f)\n funcs.append(y)\n\n if isinstance(target, list) and len(variables) == len(target):\n res = gradientF(funcs, variables)\n name = \"Jacobian\" if len(funcs) > 1 else \"Derivative\"\n print(f\"Functions: {functions}\\nVariables: {var_dict}\\n------------------------------\\n{name}:\\n {res}\")\n else:\n name = \"Gradient\" if len(funcs) > 1 else \"Partial derivative\"\n s = \"\"\n for t in target:\n der = gradientF(funcs, variables, target=t)\n res.append(der)\n s += f\"{name} with respect to {t}: {der}\\n\"\n print(f\"Functions: {functions}\\nVariables: {var_dict}\\n------------------------------\\n\" + s)\n\n return res\n\n\ndef reverse_auto_diff(functions, var_dict, target=None):\n '''\n Perform reverse mode automatic differentiation\n\n Input:\n functions - str, the functions output we a{re caculating\n var_dict - dictionary, name and value pair of all variables in function\n target - list, name of our target variable(s) to calculate the gradient\n\n Output:\n The derivative / partial derivative / gradient / jacobian of input function and target variable\n\n Examples:\n >>> functions = [\"x1 + sin(x2) * 5\", \"exp(x1) - log(2 * x2)\"]\n >>> var_dict = {\"x1\": 5, \"x2\": 2}\n >>> target = [\"x1\"]\n >>> res = reverse_auto_diff(functions, var_dict, target)\n >>> res\n [[1.0, 148.4131591025766]]\n\n '''\n\n variables = list(var_dict.keys())\n if not target:\n target = variables\n res = []\n functions = [functions] if isinstance(functions, str) else functions\n\n if isinstance(target, list) and len(variables) == len(target):\n res = gradientR(functions, var_dict, variables)\n name = \"Jacobian\" if len(functions) > 1 else \"Derivative\"\n print(f\"Functions: {functions}\\nVariables: {var_dict}\\n------------------------------\\n{name}:\\n {res}\")\n else:\n name = \"Gradient\" if len(functions) > 1 else \"Partial Derivative\"\n s = \"\"\n for t in target:\n der = gradientR(functions, var_dict, target=t)\n res.append(der)\n s += f\"{name} with respect to {t}: {der}\\n\"\n print(f\"Functions: {functions}\\nVariables: {var_dict}\\n------------------------------\\n\" + s)\n\n return res\n\n\ndef translate(lambda_func):\n '''\n Translate lambda function input to string representation of function\n\n Input:\n lambda_func - function, lambda function(s) that the user want to perform automatic differentiation\n\n Output:\n String representation of function input\n\n Examples:\n >>> functions = lambda x1, x2: x1 + sin(x2)\n >>> translate(lambda_func=functions)\n ['x1 + sin(x2)', 'cos(x1) + 5 / exp(x2)']\n\n >>> functions = lambda x1, x2: [x1 + sin(x2), cos(x1) + 5 / exp(x2)]\n >>> translate(lambda_func=functions)\n ['exp(x1) + log(x2) - 5']\n\n '''\n functions = inspect.getsourcelines(lambda_func)[0][0].strip('\\n').split(\":\")[-1].strip()\n if \"[\" in functions:\n #functions = inspect.getsourcelines(lambda_func)[0][0].strip('\\n').split(\": \")[-1].strip('][').split(\", \")\n functions = re.findall(r'(?<=\\[).*(?=\\])', inspect.getsourcelines(lambda_func)[0][0].strip('\\n').split(\":\")[-1])[0].split(\",\")\n return functions\n\n\ndef auto_diff(functions, var_dict, target=None, mode=\"forward\"):\n '''\n Wrap function for automatic differentiation\n\n Input:\n functions - str, the functions output we are caculating\n var_dict - dictionary, name and value pair of all variables in function\n target - list, name of our target variable(s) to calculate the gradient\n mode - str, either forward or reverse model\n\n Output:\n The derivative / partial derivative / gradient / jacobian of input function and target variable\n\n Examples:\n >>> functions = [\"tanh(x1) + cosh(x2 * 3) - sec(x3)\", \"x1 / x2 * cos(x3)\", \"sin(x1 / 2) + x2 * x3\"]\n >>> var_dict = {\"x1\": np.pi / 2, \"x2\": 1, \"x3\": 0}\n >>> gradient = auto_diff(functions, var_dict, [\"x1\", \"x2\"], mode=\"forward\")\n >>> gradient\n [[0.15883159318006335, 1.0, 0.3535533905932738], [30.053624782229708, -1.5707963267948966, 0.0]]\n\n >>> jacobian = auto_diff(functions, var_dict, [\"x1\", \"x2\", \"x3\"], mode=\"reverse\")\n >>> jacobian\n [[0.15883159318006335, 30.053624782229708, 0.0], [1.0, -1.5707963267948966, 0.0], [0.3535533905932738, 0.0, 1.0]]\n\n '''\n if (not isinstance(functions, (str, list))) and functions.__name__ == \"<lambda>\":\n functions = translate(functions)\n if not (isinstance(functions, str) or all([isinstance(f, str) for f in functions])):\n raise TypeError('Invalid input type: each function should be a string or lambda function')\n if not isinstance(var_dict, dict):\n raise TypeError('Invalid input type: input variables should be dictionary')\n if target:\n if not (isinstance(target, str) or all([t in var_dict.keys() for t in target])):\n raise ValueError('Invalid target value: target must be in the variable dictionary')\n\n if mode == \"forward\":\n return forward_auto_diff(functions, var_dict, target)\n elif mode == \"reverse\":\n return reverse_auto_diff(functions, var_dict, target)\n else:\n raise ValueError(\"Invalid mode: please choose between forward and reverse mode\")\n\n\ndef main():\n functions = lambda x1, x2: [exp(x1) + log(x2) - 5, sin(x1) + cos(x2)]\n var_dict = {\"x1\": 3, \"x2\": 5}\n auto_diff(functions, var_dict, [\"x1\", \"x2\"], \"reverse\")\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] |
[
[
"numpy.array"
]
] |
ocefpaf/argopy
|
[
"80a2bc04768b810a0116660df9298d07924fa5f2"
] |
[
"argopy/stores/argo_index.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom abc import ABC, abstractmethod\nimport hashlib\n\nfrom argopy.errors import DataNotFound\nfrom argopy.options import OPTIONS\nfrom .filesystems import filestore, memorystore\n\n\nclass indexfilter_proto(ABC):\n \"\"\" Class prototype for an Argo index filter\n\n Such classes requires a ``run`` and ``uri`` methods.\n\n\n \"\"\"\n def __init__(self):\n pass\n\n @abstractmethod\n def run(self):\n \"\"\" Take a _io.TextIOWrapper and return filtered data as string (csv likes)\n\n Parameters\n ----------\n index_file: _io.TextIOWrapper\n\n Returns\n -------\n csv rows matching the request, as a in-memory string. Or None.\n \"\"\"\n pass\n\n @abstractmethod\n def uri(self):\n \"\"\" Return a name for one specific filter run \"\"\"\n pass\n\n @property\n def sha(self):\n \"\"\" Unique filter hash string \"\"\"\n return hashlib.sha256(self.uri().encode()).hexdigest()\n\n\nclass indexfilter_wmo(indexfilter_proto):\n \"\"\" Index filter based on WMO and/or CYCLE_NUMER\n\n This is intended to be used by instances of an indexstore\n\n Examples\n --------\n\n # Create filters:\n filt = index_filter_wmo(WMO=13857)\n filt = index_filter_wmo(WMO=13857, CYC=np.arange(1,10))\n filt = index_filter_wmo(WMO=[13857, 13858, 12], CYC=12)\n filt = index_filter_wmo(WMO=[13857, 13858, 12], CYC=[1, 12])\n filt = index_filter_wmo(CYC=250)\n filt = index_filter_wmo()\n\n # Filter name:\n print(filt.uri())\n\n # Direct usage:\n with open(\"/Volumes/Data/ARGO/ar_index_global_prof.txt\", \"r\") as f:\n results = filt.run(f)\n\n # With the indexstore:\n indexstore(cache=1, index_file=\"/Volumes/Data/ARGO/ar_index_global_prof.txt\").open_dataframe(filt)\n\n \"\"\"\n\n def __init__(self, WMO: list = [], CYC=None, **kwargs):\n \"\"\" Create Argo index filter for WMOs/CYCs\n\n Parameters\n ----------\n WMO : list(int)\n The list of WMOs to search\n CYC : int, np.array(int), list(int)\n The cycle numbers to search for each WMO\n \"\"\"\n if isinstance(WMO, int):\n WMO = [WMO] # Make sure we deal with a list\n if isinstance(CYC, int):\n CYC = np.array((CYC,), dtype='int') # Make sure we deal with an array of integers\n if isinstance(CYC, list):\n CYC = np.array(CYC, dtype='int') # Make sure we deal with an array of integers\n self.WMO = sorted(WMO)\n self.CYC = CYC\n\n def uri(self):\n \"\"\" Return a unique name for this filter instance \"\"\"\n if len(self.WMO) > 1:\n listname = [\"WMO%i\" % i for i in sorted(self.WMO)]\n if isinstance(self.CYC, (np.ndarray)):\n [listname.append(\"CYC%0.4d\" % i) for i in sorted(self.CYC)]\n listname = \"_\".join(listname)\n elif len(self.WMO) == 0:\n if isinstance(self.CYC, (np.ndarray)):\n listname = [\"AllWMOs\"]\n [listname.append(\"CYC%0.4d\" % i) for i in sorted(self.CYC)]\n else:\n listname = [\"FULL\"]\n listname = \"_\".join(listname)\n else:\n listname = \"WMO%i\" % self.WMO[0]\n if isinstance(self.CYC, (np.ndarray)):\n listname = [listname]\n [listname.append(\"CYC%0.4d\" % i) for i in sorted(self.CYC)]\n listname = \"_\".join(listname)\n if len(listname) > 256:\n listname = hashlib.sha256(listname.encode()).hexdigest()\n return listname\n\n def run(self, index_file):\n \"\"\" Run search on an Argo index file\n\n Parameters\n ----------\n index_file: _io.TextIOWrapper\n\n Returns\n -------\n csv rows matching the request, as in-memory string. Or None.\n \"\"\"\n\n # Define one-line search functions:\n def search_one_wmo(index, wmo):\n \"\"\" Search for a WMO in the argo index file\n\n Parameters\n ----------\n index_file: _io.TextIOWrapper\n wmo: int\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n index.seek(0)\n results = \"\"\n il_read, il_loaded, il_this = 0, 0, 0\n for line in index:\n il_this = il_loaded\n # if re.search(\"/%i/\" % wmo, line.split(',')[0]):\n if \"/%i/\" % wmo in line: # much faster than re\n # Search for the wmo at the beginning of the file name under: /<dac>/<wmo>/profiles/\n results += line\n il_loaded += 1\n if il_this == il_loaded and il_this > 0:\n break # Since the index is sorted, once we found the float, we can stop reading the index !\n il_read += 1\n if il_loaded > 0:\n return results\n else:\n return None\n\n def define_search_this(cyc):\n if np.all(cyc >= 1000):\n def search_this(this_line):\n # return np.any([re.search(\"%0.4d.nc\" % c, this_line.split(',')[0]) for c in cyc])\n return np.any([\"%0.4d.nc\" % c in this_line for c in cyc])\n else:\n def search_this(this_line):\n # return np.any([re.search(\"%0.3d.nc\" % c, this_line.split(',')[0]) for c in cyc])\n return np.any([\"%0.3d.nc\" % c in this_line for c in cyc])\n return search_this\n\n def search_any_wmo_cyc(index, cyc):\n \"\"\" Search for a WMO in the argo index file\n\n Parameters\n ----------\n index_file: _io.TextIOWrapper\n cyc: array of integers\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n search_this = define_search_this(cyc)\n index.seek(0)\n results = \"\"\n il_read, il_loaded = 0, 0\n for line in index:\n if search_this(line):\n results += line\n il_loaded += 1\n il_read += 1\n if il_loaded > 0:\n return results\n else:\n return None\n\n def search_one_wmo_cyc(index, wmo, cyc):\n \"\"\" Search for a WMO and CYC in the argo index file\n\n Parameters\n ----------\n index: _io.TextIOWrapper\n wmo: int\n cyc: array of integers\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n index.seek(0)\n results = \"\"\n\n # Look for the float:\n il_read, il_loaded, il_this = 0, 0, 0\n for line in index:\n il_this = il_loaded\n # if re.search(\"/%i/\" % wmo, line.split(',')[0]):\n if \"/%i/\" % wmo in line: # much faster than re\n results += line\n il_loaded += 1\n if il_this == il_loaded and il_this > 0:\n break # Since the index is sorted, once we found the float, we can stop reading the index !\n il_read += 1\n\n # Then look for the profile:\n if results:\n search_this = define_search_this(cyc)\n il_loaded, cyc_results = 0, \"\"\n for line in results.split():\n if search_this(line):\n il_loaded += 1\n cyc_results += line + \"\\n\"\n if il_loaded > 0:\n return cyc_results\n else:\n return None\n\n def full_load(index):\n \"\"\" Return the full argo index file (without header)\n\n Parameters\n ----------\n index: _io.TextIOWrapper\n\n Returns\n -------\n csv index, as a string\n \"\"\"\n index.seek(0)\n for line in index:\n if line[0] != '#':\n break\n return index.read()\n\n # Run the filter with the appropriate one-line search\n if len(self.WMO) > 1:\n if isinstance(self.CYC, (np.ndarray)):\n return \"\".join([r for r in [search_one_wmo_cyc(index_file, w, self.CYC) for w in self.WMO] if r])\n else:\n return \"\".join([r for r in [search_one_wmo(index_file, w) for w in self.WMO] if r])\n elif len(self.WMO) == 0: # Search for cycle numbers only\n if isinstance(self.CYC, (np.ndarray)):\n return search_any_wmo_cyc(index_file, self.CYC)\n else:\n # No wmo, No cyc, return the full index:\n return full_load(index_file)\n else:\n if isinstance(self.CYC, (np.ndarray)):\n return search_one_wmo_cyc(index_file, self.WMO[0], self.CYC)\n else:\n return search_one_wmo(index_file, self.WMO[0])\n\n\nclass indexfilter_box(indexfilter_proto):\n \"\"\" Index filter based on LATITUDE, LONGITUDE, DATE\n\n This is intended to be used by instances of an indexstore\n\n Examples\n --------\n\n # Create filters:\n filt = index_filter_box(BOX=[-70, -65, 30., 35.])\n filt = index_filter_box(BOX=[-70, -65, 30., 35., '2012-01-01', '2012-06-30'])\n\n # Filter name:\n print(filt.uri())\n\n # Direct usage:\n with open(\"/Volumes/Data/ARGO/ar_index_global_prof.txt\", \"r\") as f:\n results = filt.run(f)\n\n # With the indexstore:\n indexstore(cache=1, index_file=\"/Volumes/Data/ARGO/ar_index_global_prof.txt\").open_dataframe(filt)\n\n \"\"\"\n\n def __init__(self, BOX: list = [], **kwargs):\n \"\"\" Create Argo index filter for LATITUDE, LONGITUDE, DATE\n\n Parameters\n ----------\n box : list(float, float, float, float, str, str)\n The box domain to load all Argo data for:\n box = [lon_min, lon_max, lat_min, lat_max, datim_min, datim_max]\n \"\"\"\n # is_indexbox(BOX)\n self.BOX = BOX\n\n def _format(self, x, typ):\n \"\"\" string formatting helper \"\"\"\n if typ == 'lon':\n if x < 0:\n x = 360. + x\n return (\"%05d\") % (x * 100.)\n if typ == 'lat':\n return (\"%05d\") % (x * 100.)\n if typ == 'prs':\n return (\"%05d\") % (np.abs(x) * 10.)\n if typ == 'tim':\n return pd.to_datetime(x).strftime('%Y%m%d')\n return str(x)\n\n def uri(self):\n \"\"\" Return a unique name for this filter instance \"\"\"\n BOX = self.BOX\n if len(BOX) == 4:\n boxname = (\"[x=%0.2f/%0.2f; y=%0.2f/%0.2f]\") % (BOX[0], BOX[1], BOX[2], BOX[3])\n else:\n boxname = (\"[x=%0.2f/%0.2f; y=%0.2f/%0.2f; t=%s/%s]\") % (BOX[0], BOX[1], BOX[2], BOX[3], BOX[4], BOX[5])\n if len(boxname) > 256:\n boxname = hashlib.sha256(boxname.encode()).hexdigest()\n return boxname\n\n def search_latlon(self, index):\n \"\"\" Search\n\n Parameters\n ----------\n index: _io.TextIOWrapper\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n index.seek(0)\n results = \"\"\n iv_lat, iv_lon = 2, 3\n il_loaded = 0\n for ii in range(0, 9):\n index.readline()\n for line in index:\n # il_this = il_loaded\n l = line.split(\",\")\n if l[iv_lon] != \"\" and l[iv_lat] != \"\":\n x = float(l[iv_lon])\n y = float(l[iv_lat])\n if x >= self.BOX[0] and x <= self.BOX[1] and y >= self.BOX[2] and y <= self.BOX[3]:\n results += line\n il_loaded += 1\n if il_loaded > 0:\n return results\n else:\n return None\n\n def search_tim(self, index):\n \"\"\" Search\n\n Parameters\n ----------\n index: str csv like\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n results = \"\"\n iv_tim = 1\n il_loaded = 0\n for line in index.split():\n l = line.split(\",\")\n if l[iv_tim] != \"\":\n t = pd.to_datetime(str(l[iv_tim]))\n if t >= pd.to_datetime(self.BOX[4]) and t <= pd.to_datetime(self.BOX[5]):\n results += line + \"\\n\"\n il_loaded += 1\n if il_loaded > 0:\n return results\n else:\n return None\n\n def search_latlontim(self, index):\n \"\"\" Search\n\n Parameters\n ----------\n index: _io.TextIOWrapper\n\n Returns\n -------\n csv chunk matching the request, as a string. Or None\n \"\"\"\n\n # First search in space:\n results = self.search_latlon(index)\n # Then refine in time:\n if results:\n results = self.search_tim(results)\n return results\n\n def run(self, index_file):\n \"\"\" Run search on an Argo index file\n\n Parameters\n ----------\n index_file: _io.TextIOWrapper\n\n Returns\n -------\n csv rows matching the request, as in-memory string. Or None.\n \"\"\"\n\n # Run the filter:\n if len(self.BOX) == 4:\n return self.search_latlon(index_file)\n else:\n return self.search_latlontim(index_file)\n\n\nclass indexstore():\n \"\"\" Use to manage access to a local Argo index and searches \"\"\"\n\n def __init__(self,\n cache: bool = False,\n cachedir: str = \"\",\n index_file: str = \"ar_index_global_prof.txt\",\n **kw):\n \"\"\" Create a file storage system for Argo index file requests\n\n Parameters\n ----------\n cache : bool (False)\n cachedir : str (used value in global OPTIONS)\n index_file: str (\"ar_index_global_prof.txt\")\n \"\"\"\n self.index_file = index_file\n self.cache = cache\n self.cachedir = OPTIONS['cachedir'] if cachedir == '' else cachedir\n self.fs = {}\n self.fs['index'] = filestore(cache, cachedir)\n self.fs['search'] = memorystore(cache, cachedir)\n\n def cachepath(self, uri: str, errors: str = 'raise'):\n \"\"\" Return path to cached file for a given URI \"\"\"\n return self.fs['search'].cachepath(uri, errors)\n\n def clear_cache(self):\n self.fs['index'].clear_cache()\n self.fs['search'].clear_cache()\n\n def in_cache(self, fs, uri):\n \"\"\" Return true if uri is cached \"\"\"\n if not uri.startswith(fs.target_protocol):\n store_path = fs.target_protocol + \"://\" + uri\n else:\n store_path = uri\n fs.load_cache()\n return store_path in fs.cached_files[-1]\n\n def in_memory(self, fs, uri):\n \"\"\" Return True if uri is in the memory store \"\"\"\n return uri in fs.store\n\n def open_index(self):\n return self.fs['index'].open(self.index_file, \"r\")\n\n def res2dataframe(self, results):\n \"\"\" Convert a csv like string into a DataFrame\n\n If one columns has a missing value, the row is skipped\n \"\"\"\n cols_name = ['file', 'date', 'latitude', 'longitude', 'ocean', 'profiler_type', 'institution', 'date_update']\n cols_type = {'file': np.str_, 'date': np.datetime64, 'latitude': np.float32, 'longitude': np.float32,\n 'ocean': np.str_, 'profiler_type': np.str_, 'institution': np.str_, 'date_update': np.datetime64}\n data = [x.split(',') for x in results.split('\\n') if \",,\" not in x]\n return pd.DataFrame(data, columns=cols_name).astype(cols_type)[:-1]\n\n def read_csv(self, search_cls):\n \"\"\" Run a search on an csv Argo index file and return a Pandas DataFrame with results\n\n Parameters\n ----------\n search_cls: Class instance inheriting from index_filter_proto\n\n Returns\n -------\n :class:`pandas.DataFrame`\n\n \"\"\"\n uri = search_cls.uri()\n with self.open_index() as f:\n if self.cache and (self.in_cache(self.fs['search'].fs, uri) or self.in_memory(self.fs['search'].fs, uri)):\n # print('Search already in memory, loading:', uri)\n with self.fs['search'].open(uri, \"r\") as of:\n df = self.res2dataframe(of.read())\n else:\n # print('Running search from scratch ...')\n # Run search:\n results = search_cls.run(f)\n if not results:\n raise DataNotFound(\"No Argo data in the index correspond to your search criteria.\\nSearch URI: %s\" % uri)\n # and save results for caching:\n if self.cache:\n with self.fs['search'].open(uri, \"w\") as of:\n of.write(results) # This happens in memory\n self.fs['search'].fs.save_cache()\n df = self.res2dataframe(results)\n return df\n"
] |
[
[
"pandas.to_datetime",
"numpy.abs",
"pandas.DataFrame",
"numpy.all",
"numpy.any",
"numpy.array"
]
] |
maximekli/solopython
|
[
"529106724120f656a0f2a02b9c5d1a1cbe8de75f"
] |
[
"utils/logger.py"
] |
[
"'''This class will log 1d array in Nd matrix from device and qualisys object'''\nimport numpy as np\nclass Logger():\n def __init__(self, device, qualisys=None, logSize=60e3, ringBuffer=False): \n self.ringBuffer = ringBuffer\n self.logSize=logSize\n self.i=0\n nb_motors = device.nb_motors\n \n #allocate the data:\n self.q_mes = np.zeros([logSize,nb_motors])\n self.v_mes = np.zeros([logSize,nb_motors])\n self.torquesFromCurrentMeasurment = np.zeros([logSize,nb_motors])\n self.baseOrientation = np.zeros([logSize,4])\n self.baseAngularVelocity = np.zeros([logSize,3])\n self.baseLinearAcceleration = np.zeros([logSize,3])\n\n self.mocapPosition = np.zeros([logSize,3])\n self.mocapVelocity = np.zeros([logSize,3])\n self.mocapAngularVelocity = np.zeros([logSize,3])\n self.mocapOrientationMat9 = np.zeros([logSize,3,3])\n self.mocapOrientationQuat = np.zeros([logSize,4])\n\n def sample(self,device,qualisys=None):\n if (self.i>=self.logSize):\n if self.ringBuffer:\n self.i=0\n else:\n return\n #Logging from the device\n self.q_mes[self.i] = device.q_mes\n self.v_mes[self.i] = device.v_mes\n self.baseOrientation[self.i] = device.baseOrientation\n self.baseAngularVelocity[self.i] = device.baseAngularVelocity\n self.baseLinearAcceleration[self.i] = device.baseLinearAcceleration\n self.torquesFromCurrentMeasurment[self.i] = device.torquesFromCurrentMeasurment\n #Logging from qualisys\n if qualisys is not None:\n self.mocapPosition[self.i] = qualisys.getPosition()\n self.mocapVelocity[self.i] = qualisys.getVelocity()\n self.mocapAngularVelocity[self.i] = qualisys.getAngularVelocity()\n self.mocapOrientationMat9[self.i] = qualisys.getOrientationMat9()\n self.mocapOrientationQuat[self.i] = qualisys.getOrientationQuat()\n self.i+=1\n\n def saveAll(self, fileName = \"data.npz\"):\n np.savez(fileName, q_mes=self.q_mes, \n v_mes=self.v_mes,\n torquesFromCurrentMeasurment = self.torquesFromCurrentMeasurment,\n baseOrientation=self.baseOrientation,\n baseAngularVelocity=self.baseAngularVelocity,\n baseLinearAcceleration=self.baseLinearAcceleration,\n mocapPosition=self.mocapPosition,\n mocapVelocity=self.mocapVelocity,\n mocapAngularVelocity=self.mocapAngularVelocity,\n mocapOrientationMat9=self.mocapOrientationMat9,\n mocapOrientationQuat=self.mocapOrientationQuat)\n \n"
] |
[
[
"numpy.savez",
"numpy.zeros"
]
] |
olivaresluque/scrapATP
|
[
"1985d4c73fabd5f08f54b922e73a9306e09c77a5"
] |
[
"ven/Lib/site-packages/pandas/core/indexes/api.py"
] |
[
"from pandas.core.indexes.base import (Index,\n _new_Index,\n _ensure_index,\n _ensure_index_from_sequences,\n _get_na_value,\n InvalidIndexError) # noqa\nfrom pandas.core.indexes.category import CategoricalIndex # noqa\nfrom pandas.core.indexes.multi import MultiIndex # noqa\nfrom pandas.core.indexes.interval import IntervalIndex # noqa\nfrom pandas.core.indexes.numeric import (NumericIndex, Float64Index, # noqa\n Int64Index, UInt64Index)\nfrom pandas.core.indexes.range import RangeIndex # noqa\nfrom pandas.core.indexes.timedeltas import TimedeltaIndex\nfrom pandas.core.indexes.period import PeriodIndex\nfrom pandas.core.indexes.datetimes import DatetimeIndex\n\nimport pandas.core.common as com\nfrom pandas._libs import lib\nfrom pandas._libs.tslib import NaT\n\n# TODO: there are many places that rely on these private methods existing in\n# pandas.core.index\n__all__ = ['Index', 'MultiIndex', 'NumericIndex', 'Float64Index', 'Int64Index',\n 'CategoricalIndex', 'IntervalIndex', 'RangeIndex', 'UInt64Index',\n 'InvalidIndexError', 'TimedeltaIndex',\n 'PeriodIndex', 'DatetimeIndex',\n '_new_Index', 'NaT',\n '_ensure_index', '_ensure_index_from_sequences', '_get_na_value',\n '_get_combined_index',\n '_get_objs_combined_axis', '_union_indexes',\n '_get_consensus_names',\n '_all_indexes_same']\n\n\ndef _get_objs_combined_axis(objs, intersect=False, axis=0):\n # Extract combined index: return intersection or union (depending on the\n # value of \"intersect\") of indexes on given axis, or None if all objects\n # lack indexes (e.g. they are numpy arrays)\n obs_idxes = [obj._get_axis(axis) for obj in objs\n if hasattr(obj, '_get_axis')]\n if obs_idxes:\n return _get_combined_index(obs_idxes, intersect=intersect)\n\n\ndef _get_combined_index(indexes, intersect=False):\n # TODO: handle index names!\n indexes = com._get_distinct_objs(indexes)\n if len(indexes) == 0:\n return Index([])\n if len(indexes) == 1:\n return indexes[0]\n if intersect:\n index = indexes[0]\n for other in indexes[1:]:\n index = index.intersection(other)\n return index\n union = _union_indexes(indexes)\n return _ensure_index(union)\n\n\ndef _union_indexes(indexes):\n if len(indexes) == 0:\n raise AssertionError('Must have at least 1 Index to union')\n if len(indexes) == 1:\n result = indexes[0]\n if isinstance(result, list):\n result = Index(sorted(result))\n return result\n\n indexes, kind = _sanitize_and_check(indexes)\n\n def _unique_indices(inds):\n def conv(i):\n if isinstance(i, Index):\n i = i.tolist()\n return i\n\n return Index(lib.fast_unique_multiple_list([conv(i) for i in inds]))\n\n if kind == 'special':\n result = indexes[0]\n\n if hasattr(result, 'union_many'):\n return result.union_many(indexes[1:])\n else:\n for other in indexes[1:]:\n result = result.union(other)\n return result\n elif kind == 'array':\n index = indexes[0]\n for other in indexes[1:]:\n if not index.equals(other):\n return _unique_indices(indexes)\n\n name = _get_consensus_names(indexes)[0]\n if name != index.name:\n index = index._shallow_copy(name=name)\n return index\n else:\n return _unique_indices(indexes)\n\n\ndef _sanitize_and_check(indexes):\n kinds = list(set([type(index) for index in indexes]))\n\n if list in kinds:\n if len(kinds) > 1:\n indexes = [Index(com._try_sort(x))\n if not isinstance(x, Index) else\n x for x in indexes]\n kinds.remove(list)\n else:\n return indexes, 'list'\n\n if len(kinds) > 1 or Index not in kinds:\n return indexes, 'special'\n else:\n return indexes, 'array'\n\n\ndef _get_consensus_names(indexes):\n\n # find the non-none names, need to tupleify to make\n # the set hashable, then reverse on return\n consensus_names = set([tuple(i.names) for i in indexes\n if com._any_not_none(*i.names)])\n if len(consensus_names) == 1:\n return list(list(consensus_names)[0])\n return [None] * indexes[0].nlevels\n\n\ndef _all_indexes_same(indexes):\n first = indexes[0]\n for index in indexes[1:]:\n if not first.equals(index):\n return False\n return True\n"
] |
[
[
"pandas.core.common._any_not_none",
"pandas.core.common._try_sort",
"pandas.core.indexes.base.Index",
"pandas.core.indexes.base._ensure_index",
"pandas.core.common._get_distinct_objs"
]
] |
shigeokitamura/netkeiba_scraper
|
[
"a280f5e0a372e23ce52075ac55277f1e4d401598"
] |
[
"scraping_csv.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\nimport argparse\nimport time\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\nimport scraper\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--start_year\", type=int, default=1986)\n parser.add_argument(\"--end_year\", type=int, default=2020)\n parser.add_argument(\"--csv_info_path\", type=str, default=\"netkeiba_info.csv\")\n parser.add_argument(\"--csv_data_path\", type=str, default=\"netkeiba_data.csv\")\n return parser.parse_args()\n\ndef get_exist_race_ids(start_year, end_year, csvpath):\n if os.path.isfile(csvpath[\"info\"]):\n df_info = pd.read_csv(csvpath[\"info\"], header=None, usecols=[0, 1])\n df_info = df_info[df_info[1] >= start_year]\n df_info = df_info[df_info[1] <= end_year]\n exist_race_ids = [str(id) for id in df_info[0].tolist()]\n return exist_race_ids\n return []\n\ndef insert_into_csv(race_info, race_data, csvpath):\n race_info.to_csv(csvpath[\"info\"], mode=\"a\", header=False, index=False)\n race_data.to_csv(csvpath[\"data\"], mode=\"a\", header=False, index=False)\n print(\"Inserted race_id %s\" % race_info[\"race_id\"].values[0])\n\ndef scraping(start_year, end_year, csvpath):\n print(\"Start scraping data from %d to %d\" % (start_year, end_year))\n\n exist_race_ids = get_exist_race_ids(start_year, end_year, csvpath)\n race_ids = sorted(list(set(scraper.get_race_ids(start_year, end_year)) - set(exist_race_ids)))\n\n for race_id in tqdm(race_ids):\n time_start = time.time()\n soup = scraper.get_html(race_id)\n if soup is not None:\n df_race_info, df_race_records = scraper.collect_data(soup, race_id)\n insert_into_csv(df_race_info, df_race_records, csvpath)\n elapsed_time = time.time() - time_start\n if elapsed_time < 1:\n time.sleep(1 - elapsed_time)\n\nif __name__ == \"__main__\":\n ARGS = get_args()\n scraping(ARGS.start_year, ARGS.end_year,\n {\"info\": ARGS.csv_info_path, \"data\": ARGS.csv_data_path})\n"
] |
[
[
"pandas.read_csv"
]
] |
Diego-Ibarra/ship-mapper
|
[
"f0959e9ae629c3933bfe4f794f96385a716218dc"
] |
[
"ship_mapper/mapper.py"
] |
[
"import matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import FancyBboxPatch\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\nfrom mpl_toolkits.basemap import Basemap\r\n\r\nimport numpy as np\r\n# Suppress matplotlib warnings\r\nnp.warnings.filterwarnings('ignore')\r\n\r\nimport xarray as xr\r\nimport cmocean\r\nfrom pathlib import Path\r\nimport _pickle as pickle\r\nimport os\r\nimport ship_mapper as sm\r\nimport urllib.request\r\nimport netCDF4\r\n\r\n\r\ndef map_density(info, file_in=None, cmap='Default', sidebar=False,\r\n to_screen=True, save=True,\r\n filename_out='auto',filedir_out='auto'):\r\n '''\r\n Plots a map using a gridded (or merged) file\r\n \r\n Arguments:\r\n info (info): ``info`` object containing metadata\r\n \r\n Keyword Arguments:\r\n file_in (str): Gridded or merged file to map. If ``None`` it looks for \r\n ``merged_grid.nc`` in the `\\merged` directory\r\n \r\n cmap (str): Colormap to use\r\n \r\n sidebar (bool): If ``True``, includes side panel with metadata\r\n \r\n to_screen (bool): If ``True``, a plot is printed to screen\r\n \r\n save (bool): If ``True`` a ``.png`` figure is saved to hardrive\r\n \r\n filename_out (str): Name of produced figure. \r\n If ``auto`` then name is ``info.run_name + '__' + file_in + '.png'``\r\n \r\n filedir_out (str): Directory where figure is saved.\r\n If ``auto`` then output directory is ``info.dirs.pngs``\r\n\r\n Returns:\r\n Basemap object\r\n \r\n '''\r\n \r\n print('map_density ------------------------------------------------------')\r\n \r\n # Load data\r\n if file_in == None:\r\n file_in = os.path.join(str(info.dirs.merged_grid),'merged_grid.nc')\r\n \r\n print(file_in)\r\n \r\n d = xr.open_dataset(file_in)\r\n \r\n # Define boundaries\r\n if info.grid.minlat == None or info.grid.maxlat == None or info.grid.minlon == None or info.grid.maxlon == None: \r\n minlat = d['lat'].values.min()\r\n maxlat = d['lat'].values.max()\r\n minlon = d['lon'].values.min()\r\n maxlon = d['lon'].values.max()\r\n else:\r\n minlat = d.attrs['minlat']\r\n maxlat = d.attrs['maxlat']\r\n minlon = d.attrs['minlon']\r\n maxlon = d.attrs['maxlon']\r\n \r\n basemap_file = info.dirs.basemap\r\n print('Basemap file: ' + basemap_file)\r\n \r\n \r\n # Check for basemap.p and, if doesn;t exist, make it\r\n if not os.path.exists(basemap_file):\r\n m = sm.make_basemap(info,info.dirs.project_path,[minlat,maxlat,minlon,maxlon])\r\n else:\r\n print('Found basemap...')\r\n m = pickle.load(open(basemap_file,'rb'))\r\n\r\n \r\n # Create grid for mapping\r\n lons_grid, lats_grid = np.meshgrid(d['lon'].values,d['lat'].values)\r\n xx,yy = m(lons_grid, lats_grid)\r\n \r\n H = d['ship_density'].values\r\n \r\n # Rotate and flip H... ----------------------------------------------------------------------------\r\n H = np.rot90(H)\r\n H = np.flipud(H)\r\n \r\n # Mask zeros\r\n d.attrs['mask_below'] = info.maps.mask_below\r\n Hmasked = np.ma.masked_where(H<=d.attrs['mask_below'],H)\r\n \r\n # Set vman and vmin\r\n print('Min: ' + str(np.min(Hmasked)))\r\n print('Max: ' + str(np.max(Hmasked)))\r\n print('Mean: ' + str(np.nanmean(Hmasked)))\r\n print('Std: ' + str(Hmasked.std()))\r\n \r\n if info.maps.cbarmax == 'auto':\r\n# vmax = (np.median(Hmasked)) + (4*Hmasked.std())\r\n vmax = (np.max(Hmasked)) - (2*Hmasked.std())\r\n elif info.maps.cbarmax != None:\r\n vmax = info.maps.cbarmax\r\n else:\r\n vmax = None\r\n \r\n if info.maps.cbarmin == 'auto':\r\n# vmin = (np.median(Hmasked)) - (4*Hmasked.std())\r\n alat = (d.attrs['maxlat'] - d.attrs['minlat'])/2\r\n cellsize = sm.degrees_to_meters(d.attrs['bin_size'], alat)\r\n# max_speed = 616.66 # m/min ...roughly 20 knots\r\n max_speed = 316.66 # m/min ...roughly 20 knots\r\n vmin = cellsize / max_speed\r\n elif info.maps.cbarmin != None:\r\n vmin = info.maps.cbarmin\r\n else:\r\n vmin = None\r\n \r\n \r\n \r\n # Log H for better display\r\n Hmasked = np.log10(Hmasked)\r\n if vmin != None:\r\n vmin = np.log10(vmin)\r\n if vmax != None:\r\n vmax = np.log10(vmax)\r\n \r\n\r\n # Make colormap\r\n fig = plt.gcf()\r\n ax = plt.gca()\r\n \r\n if cmap == 'Default':\r\n cmapcolor = load_my_cmap('my_cmap_amber2red')\r\n elif cmap == 'red2black':\r\n cmapcolor = load_my_cmap('my_cmap_red2black')\r\n else:\r\n cmapcolor =plt.get_cmap(cmap)\r\n \r\n\r\n\r\n \r\n cs = m.pcolor(xx,yy,Hmasked, cmap=cmapcolor, zorder=10, vmin=vmin, vmax=vmax)\r\n \r\n #scalebar\r\n sblon = minlon + ((maxlon-minlon)/10)\r\n sblat = minlat + ((maxlat-minlat)/20)\r\n m.drawmapscale(sblon, sblat,\r\n minlon, minlat,\r\n info.maps.scalebar_km, barstyle='fancy',\r\n units='km', fontsize=8,\r\n fontcolor='#808080',\r\n fillcolor1 = '#cccccc',\r\n fillcolor2 = '#a6a6a6',\r\n yoffset = (0.01*(m.ymax-m.ymin)),\r\n labelstyle='simple',zorder=60)\r\n\r\n\r\n if not sidebar:\r\n cbaxes2 = fig.add_axes([0.70, 0.18, 0.2, 0.03],zorder=60)\r\n cbar = plt.colorbar(extend='both', cax = cbaxes2, orientation='horizontal')\r\n \r\n # Change colorbar labels for easier interpreting\r\n label_values = cbar._tick_data_values\r\n log_label_values = np.round(10 ** label_values,decimals=0)\r\n labels = []\r\n for log_label_value in log_label_values:\r\n labels.append(str(int(log_label_value)))\r\n \r\n cbar.ax.set_yticklabels(labels)\r\n cbar.ax.set_xlabel(d.attrs['units'])\r\n \r\n\r\n if sidebar:\r\n \r\n text1, text2, text3, text4 = make_legend_text(info,d.attrs)\r\n \r\n ax2 = plt.subplot2grid((1,24),(0,0),colspan=4)\r\n \r\n # Turn off tick labels\r\n ax2.get_xaxis().set_visible(False)\r\n ax2.get_yaxis().set_visible(False)\r\n ax2.add_patch(FancyBboxPatch((0,0),\r\n width=1, height=1, clip_on=False,\r\n boxstyle=\"square,pad=0\", zorder=3,\r\n facecolor='#e6e6e6', alpha=1.0,\r\n edgecolor='#a6a6a6',\r\n transform=plt.gca().transAxes))\r\n plt.text(0.15, 0.99, text1,\r\n verticalalignment='top',\r\n horizontalalignment='left',\r\n weight='bold',\r\n size=10,\r\n color= '#737373',\r\n transform=plt.gca().transAxes)\r\n \r\n plt.text(0.02, 0.83, text2,\r\n horizontalalignment='left',\r\n verticalalignment='top',\r\n size=9,\r\n color= '#808080',\r\n transform=plt.gca().transAxes)\r\n \r\n plt.text(0.02, 0.145, text3,\r\n horizontalalignment='left',\r\n verticalalignment='top',\r\n size=7,\r\n color= '#808080',\r\n transform=plt.gca().transAxes)\r\n \r\n plt.text(0.02, 0.25, text4,\r\n style='italic',\r\n horizontalalignment='left',\r\n verticalalignment='top',\r\n size=8,\r\n color= '#808080',\r\n transform=plt.gca().transAxes)\r\n \r\n \r\n cbaxes2 = fig.add_axes([0.019, 0.9, 0.15, 0.02],zorder=60)\r\n cbar = plt.colorbar(extend='both', cax = cbaxes2, orientation='horizontal')\r\n cbar.ax.tick_params(labelsize=8, labelcolor='#808080') \r\n \r\n # Change colorbar labels for easier interpreting\r\n label_values = cbar._tick_data_values\r\n# print(\"values\")\r\n# print(label_values)\r\n log_label_values = np.round(10 ** label_values,decimals=0)\r\n# print(log_label_values)\r\n labels = []\r\n for log_label_value in log_label_values:\r\n labels.append(str(int(log_label_value)))\r\n \r\n cbar.ax.set_xticklabels(labels)\r\n cbar.ax.set_xlabel(d.attrs['units'], size=9, color='#808080') \r\n \r\n\r\n \r\n \r\n # TODO: maybe delete this?\r\n# mng = plt.get_current_fig_manager()\r\n# mng.frame.Maximize(True)\r\n#\r\n# fig.tight_layout()\r\n\r\n plt.show()\r\n\r\n \r\n # Save map as png\r\n if save:\r\n if filedir_out == 'auto':\r\n filedir = str(info.dirs.pngs)\r\n else:\r\n filedir = filedir_out\r\n \r\n if filename_out == 'auto':\r\n filename = info.run_name + '__' + sm.get_filename_from_fullpath(file_in) + '.png'\r\n else:\r\n filename = filename_out\r\n \r\n sm.checkDir(filedir)\r\n plt.savefig(os.path.join(filedir,filename), dpi=300)\r\n \r\n \r\n # Close netCDF file\r\n d.close()\r\n \r\n if to_screen == False:\r\n plt.close()\r\n \r\n return\r\n\r\n\r\ndef make_legend_text(info,md):\r\n '''\r\n Makes text for legend in left block of map\r\n \r\n :param info info: ``info`` object containing metadata\r\n \r\n :return: text for legend\r\n '''\r\n import datetime\r\n \r\n alat = (md['maxlat'] - md['minlat'])/2\r\n \r\n text1 = 'VESSEL DENSITY HEATMAP'\r\n# print(info)\r\n # --------------------------------------------------------\r\n text2 = ('Unit description: ' + md['unit_description'] + '\\n\\n' +\r\n 'Data source: ' + md['data_source'] + '\\n\\n' +\r\n 'Data source description:\\n' + md['data_description'] + '\\n\\n' +\r\n 'Time range: \\n' + md['startdate'][0:-3] + ' to ' + md['enddate'][0:-3] + '\\n\\n' +\r\n 'Included speeds: ' + info.sidebar.included_speeds + '\\n' +\r\n 'Included vessels: ' + info.sidebar.included_vessel_types + '\\n\\n' +\r\n 'Grid size: ' + str(md['bin_size']) + ' degrees (~' + str(int(round(sm.degrees_to_meters(md['bin_size'], alat))))+ ' m)\\n' +\r\n 'EPGS code: ' + md['epsg_code'] + '\\n' +\r\n 'Interpolation: ' + md['interpolation'] + '\\n' +\r\n 'Interpolation threshold: ' + str(md['interp_threshold']) + ' knots\\n' +\r\n 'Time bin: ' + str(round(md['time_bin']*1440,1)) + ' minutes\\n' +\r\n 'Mask below: ' + str(md['mask_below']) + ' vessels per grid'\r\n )\r\n \r\n text3 = ('Creation date: ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '\\n' + \r\n 'Creation script: ' + info.run_name + '.py\\n' +\r\n 'Software: ship mapper v0.1\\n\\n' +\r\n 'Created by:\\n' +\r\n 'Oceans and Coastal Management Division\\n' +\r\n 'Ecosystem Management Branch\\n' +\r\n 'Fisheries and Oceans Canada – Maritimes Region\\n' +\r\n 'Bedford Institute of Oceanography\\n' +\r\n 'PO Box 1006, Dartmouth, NS, Canada, B2Y 4A2'\r\n )\r\n \r\n text4 = ('---------------------------------------------------------------\\n' +\r\n 'WARNING: This is a preliminary data product.\\n' +\r\n 'We cannot guarantee the validity, accuracy, \\n' +\r\n 'or quality of this product. Data is provided\\n' +\r\n 'on an \"AS IS\" basis. USE AT YOUR OWN RISK.\\n' +\r\n '---------------------------------------------------------------\\n'\r\n )\r\n \r\n \r\n \r\n return text1, text2, text3, text4\r\n\r\n\r\n\r\ndef map_dots(info, file_in, sidebar=False, save=True):\r\n '''\r\n Creates a map of \"pings\" rather than gridded density\r\n \r\n Arguments:\r\n info (info): ``info`` object containing metadata\r\n\r\n Keyword Arguments:\r\n file_in (str): Gridded or merged file to map. If ``None`` it looks for \r\n ``merged_grid.nc`` in the `\\merged` directory\r\n sidebar (bool): If ``True``, includes side panel with metadata\r\n save (bool): If ``True`` a ``.png`` figure is saved to hardrive\r\n '''\r\n print('Mapping...')\r\n # -----------------------------------------------------------------------------\r\n \r\n d = xr.open_dataset(file_in)\r\n \r\n # Define boundaries\r\n if info.grid.minlat == None or info.grid.maxlat == None or info.grid.minlon == None or info.grid.maxlon == None: \r\n minlat = d['lat'].values.min()\r\n maxlat = d['lat'].values.max()\r\n minlon = d['lon'].values.min()\r\n maxlon = d['lon'].values.max()\r\n else:\r\n minlat = info.grid.minlat\r\n maxlat = info.grid.maxlat\r\n minlon = info.grid.minlon\r\n maxlon = info.grid.maxlon\r\n \r\n \r\n \r\n path_to_basemap = info.dirs.project_path / 'ancillary'\r\n print('-----------------------------------------------------')\r\n print('-----------------------------------------------------')\r\n \r\n if sidebar:\r\n basemap_file = str(path_to_basemap / 'basemap_sidebar.p')\r\n else:\r\n basemap_file = str(path_to_basemap / 'basemap.p')\r\n \r\n if not os.path.exists(basemap_file):\r\n m = sm.make_basemap(info,[minlat,maxlat,minlon,maxlon])\r\n else:\r\n print('Found basemap...')\r\n m = pickle.load(open(basemap_file,'rb'))\r\n\r\n x, y = m(d['longitude'].values,d['latitude'].values)\r\n \r\n cs = m.scatter(x,y,s=0.1,marker='o',color='r', zorder=10)\r\n# \r\n plt.show()\r\n \r\n# # Save map as png\r\n# if save:\r\n# filedir = str(info.dirs.pngs)\r\n# sm.checkDir(filedir)\r\n# filename = info.project_name + '_' + str(info.grid.bin_number) + '.png'\r\n# plt.savefig(os.path.join(filedir,filename), dpi=300)\r\n \r\n return\r\n\r\n\r\n\r\n\r\ndef map_dots_one_ship(info, file_in, Ship_No, save=True):\r\n '''\r\n Creates a map of \"pings\" (i.e. not gridded density) of only one ship\r\n \r\n Arguments:\r\n info (info): ``info`` object containing metadata\r\n\r\n Keyword Arguments:\r\n file_in (str): Gridded or merged file to map. If ``None`` it looks for \r\n ``merged_grid.nc`` in the `\\merged` directory\r\n Ship_No (str): Unique identifier of the ship to plot\r\n save (bool): If ``True`` a ``.png`` figure is saved to hardrive\r\n '''\r\n import pandas as pd\r\n print('Mapping...')\r\n # -----------------------------------------------------------------------------\r\n \r\n d = xr.open_dataset(file_in)\r\n \r\n # Define boundaries\r\n if info.grid.minlat == None or info.grid.maxlat == None or info.grid.minlon == None or info.grid.maxlon == None: \r\n minlat = d['lat'].values.min()\r\n maxlat = d['lat'].values.max()\r\n minlon = d['lon'].values.min()\r\n maxlon = d['lon'].values.max()\r\n else:\r\n minlat = info.grid.minlat\r\n maxlat = info.grid.maxlat\r\n minlon = info.grid.minlon\r\n maxlon = info.grid.maxlon\r\n \r\n \r\n \r\n path_to_basemap = info.dirs.project_path / 'ancillary'\r\n print('-----------------------------------------------------')\r\n print('-----------------------------------------------------')\r\n \r\n# basemap_file = str(path_to_basemap / 'basemap_spots.p')\r\n \r\n m = sm.make_basemap(info.dirs.project_path,[minlat,maxlat,minlon,maxlon])\r\n \r\n# if not os.path.exists(str(path_to_basemap / 'basemap.p')):\r\n# m = sm.make_basemap(info.dirs.project_path,[minlat,maxlat,minlon,maxlon])\r\n# else:\r\n# print('Found basemap...')\r\n# m = pickle.load(open(basemap_file,'rb'))\r\n \r\n indx = ((d['longitude']> minlon) &\r\n (d['longitude']<= maxlon) &\r\n (d['latitude']> minlat) &\r\n (d['latitude']<= maxlat))\r\n \r\n filtered_data = d.sel(Dindex=indx)\r\n\r\n ship_id = info.ship_id\r\n unis = pd.unique(filtered_data[ship_id].values)\r\n ship = unis[Ship_No]\r\n indxship = (filtered_data[ship_id] == ship)\r\n singleship = filtered_data.sel(Dindex=indxship)\r\n print('Ship id:'+ str(ship))\r\n \r\n# print(singleship['longitude'].values)\r\n# print(singleship['latitude'].values)\r\n \r\n \r\n x, y = m(singleship['longitude'].values,singleship['latitude'].values)\r\n# x, y = m(d['longitude'].values,d['latitude'].values)\r\n \r\n cs = m.scatter(x,y,2,marker='o',color='r', zorder=30)\r\n \r\n# fig = plt.figure()\r\n# plt.plot(filtered_data['longitude'].values,filtered_data['latitude'].values,'.')\r\n# \r\n plt.show()\r\n \r\n# # Save map as png\r\n# if save:\r\n# filedir = str(info.dirs.pngs)\r\n# sm.checkDir(filedir)\r\n# filename = info.project_name + '_' + str(info.grid.bin_number) + '.png'\r\n# plt.savefig(os.path.join(filedir,filename), dpi=300)\r\n \r\n return\r\n\r\n\r\n\r\ndef define_path_to_map(info, path_to_basemap='auto'):\r\n '''\r\n Figures out where is the .basemap and .grid files\r\n \r\n Arguments:\r\n info (info): ``info`` object containing metadata\r\n '''\r\n if path_to_basemap == 'auto':\r\n if info.grid.type == 'one-off':\r\n path_to_map = os.path.join(info.dirs.project_path,info.grid.region,'ancillary')\r\n elif info.grid.type == 'generic':\r\n path_to_map = os.path.abspath(os.path.join(info.dirs.project_path,'ancillary'))\r\n else:\r\n path_to_map = path_to_basemap\r\n return path_to_map\r\n\r\n\r\n\r\ndef make_basemap(info,spatial,path_to_basemap='auto', sidebar=False):\r\n '''\r\n Makes a basemap\r\n \r\n Arguments:\r\n info (info): ``info`` object containing metadata\r\n spatial (list): List with corners... this will be deprecated soon\r\n \r\n Keyword arguments:\r\n path_to_basemap (str): Directory where to save the produced basemap. If ``'auto'``\r\n then path is setup by :func:`~ship_mapper.mapper.define_path_to_map`\r\n sidebar (bool): If ``True`` space for a side panel is added to the basemap\r\n \r\n Returns:\r\n A ``.basemap`` and a ``.grid`` files \r\n '''\r\n print('Making basemap...')\r\n # -----------------------------------------------------------------------------\r\n \r\n path_to_map = define_path_to_map(info, path_to_basemap=path_to_basemap)\r\n \r\n sm.checkDir(str(path_to_map))\r\n \r\n\r\n minlat = spatial[0]\r\n maxlat = spatial[1]\r\n minlon = spatial[2]\r\n maxlon = spatial[3]\r\n\r\n # Create map\r\n m = Basemap(projection='mill', llcrnrlat=minlat,urcrnrlat=maxlat,\r\n llcrnrlon=minlon, urcrnrlon=maxlon,resolution=info.maps.resolution)\r\n\r\n\r\n \r\n # TOPO\r\n # Read data from: http://coastwatch.pfeg.noaa.gov/erddap/griddap/usgsCeSrtm30v6.html\r\n # using the netCDF output option\r\n# bathymetry_file = str(path_to_map / 'usgsCeSrtm30v6.nc')\r\n bathymetry_file = os.path.join(path_to_map, 'usgsCeSrtm30v6.nc')\r\n\r\n if not os.path.isfile(bathymetry_file):\r\n isub = 1\r\n base_url='http://coastwatch.pfeg.noaa.gov/erddap/griddap/usgsCeSrtm30v6.nc?'\r\n query='topo[(%f):%d:(%f)][(%f):%d:(%f)]' % (maxlat,isub,minlat,minlon,isub,maxlon)\r\n url = base_url+query\r\n # store data in NetCDF file\r\n urllib.request.urlretrieve(url, bathymetry_file)\r\n # open NetCDF data in \r\n nc = netCDF4.Dataset(bathymetry_file)\r\n ncv = nc.variables\r\n lon = ncv['longitude'][:]\r\n lat = ncv['latitude'][:]\r\n lons, lats = np.meshgrid(lon,lat)\r\n topo = ncv['topo'][:,:]\r\n# \r\n fig = plt.figure(figsize=(19,9))\r\n \r\n# ax = fig.add_axes([0.05,0.05,0.80,1])\r\n# ax = fig.add_axes([0,0,0.80,1])\r\n \r\n\r\n\r\n \r\n# ax = fig.add_axes([0.23,0.035,0.85,0.9])\r\n if sidebar:\r\n ax = plt.subplot2grid((1,24),(0,5),colspan=19)\r\n else:\r\n ax = fig.add_axes([0.05,0.05,0.94,0.94])\r\n \r\n TOPOmasked = np.ma.masked_where(topo>0,topo)\r\n\r\n cs = m.pcolormesh(lons,lats,TOPOmasked,cmap=load_my_cmap('my_cmap_lightblue'),latlon=True,zorder=5)\r\n\r\n# m.drawcoastlines(color='#A27D0C',linewidth=0.5,zorder=25)\r\n# m.fillcontinents(color='#E1E1A0',zorder=23)\r\n m.drawcoastlines(color='#a6a6a6',linewidth=0.5,zorder=25)\r\n m.fillcontinents(color='#e6e6e6',zorder=23)\r\n m.drawmapboundary()\r\n \r\n def setcolor(x, color):\r\n for m in x:\r\n for t in x[m][1]:\r\n t.set_color(color)\r\n\r\n\r\n parallels = np.arange(minlat,maxlat,info.maps.parallels)\r\n # labels = [left,right,top,bottom]\r\n par = m.drawparallels(parallels,labels=[True,False,False,False],dashes=[20,20],color='#00a3cc', linewidth=0.2, zorder=25)\r\n setcolor(par,'#00a3cc') \r\n meridians = np.arange(minlon,maxlon,info.maps.meridians)\r\n mers = m.drawmeridians(meridians,labels=[False,False,False,True],dashes=[20,20],color='#00a3cc', linewidth=0.2, zorder=25)\r\n setcolor(mers,'#00a3cc') \r\n\r\n ax = plt.gca()\r\n# ax.axhline(linewidth=4, color=\"#00a3cc\") \r\n# ax.axvline(linewidth=4, color=\"#00a3cc\") \r\n# \r\n ax.spines['top'].set_color('#00a3cc')\r\n ax.spines['right'].set_color('#00a3cc')\r\n ax.spines['bottom'].set_color('#00a3cc')\r\n ax.spines['left'].set_color('#00a3cc')\r\n \r\n for k, spine in ax.spines.items(): #ax.spines is a dictionary\r\n spine.set_zorder(35) \r\n\r\n# ax.spines['top'].set_visible(False)\r\n# ax.spines['right'].set_visible(False)\r\n# ax.spines['bottom'].set_visible(False)\r\n# ax.spines['left'].set_visible(False)\r\n \r\n# fig.tight_layout(pad=0.25)\r\n fig.tight_layout(rect=[0.01,0.01,.99,.99])\r\n plt.show()\r\n \r\n if sidebar:\r\n basemap_name = 'basemap_sidebar.p'\r\n else:\r\n basemap_name = 'basemap.p'\r\n \r\n info = sm.calculate_gridcell_areas(info)\r\n \r\n # Save basemap\r\n save_basemap(m,info,path_to_basemap=path_to_map)\r\n# picklename = str(path_to_map / basemap_name)\r\n# pickle.dump(m,open(picklename,'wb'),-1)\r\n# print('!!! Pickle just made: ' + picklename)\r\n# \r\n## pngDir = 'C:\\\\Users\\\\IbarraD\\\\Documents\\\\VMS\\\\png\\\\'\r\n## plt.savefig(datadir[0:-5] + 'png\\\\' + filename + '- Grid' + str(BinNo) + ' - Filter' +str(downLim) + '-' + str(upLim) + '.png')\r\n# plt.savefig('test.png')\r\n \r\n return m\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef load_my_cmap(name):\r\n '''\r\n Creates and loads custom colormap\r\n '''\r\n# cdict = {'red': ((0.0, 0.0, 0.0),\r\n# (1.0, 0.7, 0.7)),\r\n# 'green': ((0.0, 0.25, 0.25),\r\n# (1.0, 0.85, 0.85)),\r\n# 'blue': ((0.0, 0.5, 0.5),\r\n# (1.0, 1.0, 1.0))}\r\n# my_cmap = LinearSegmentedColormap('my_colormap',cdict,256)\r\n if name == 'my_cmap_lightblue':\r\n cdict = {'red': ((0.0, 0.0, 0.0), # Dark\r\n (1.0, 0.9, 0.9)), # Light\r\n 'green': ((0.0, 0.9, 0.9),\r\n (1.0, 1.0,1.0)),\r\n 'blue': ((0.0, 0.9, 0.9),\r\n (1.0, 1.0, 1.0))}\r\n my_cmap = LinearSegmentedColormap('my_colormap',cdict,256)\r\n elif name == 'my_cmap_amber2red':\r\n # cdict = {'red': ((0.0, 1.0, 1.0),\r\n # (1.0, 0.5, 0.5)),\r\n # 'green': ((0.0, 1.0, 1.0),\r\n # (1.0, 0.0, 0.0)),\r\n # 'blue': ((0.0, 0.0, 0.0),\r\n # (1.0, 0.0, 0.0))}\r\n # my_cmap_yellow2red = LinearSegmentedColormap('my_colormap',cdict,256)\r\n cdict = {'red': ((0.0, 1.0, 1.0),\r\n (1.0, 0.5, 0.5)),\r\n 'green': ((0.0, 0.85, 0.85),\r\n (1.0, 0.0, 0.0)),\r\n 'blue': ((0.0, 0.3, 0.3),\r\n (1.0, 0.0, 0.0))}\r\n my_cmap = LinearSegmentedColormap('my_colormap',cdict,256)\r\n elif name == 'my_cmap_red2black':\r\n \r\n# c1 = np.array([252,142,110])/256 #RGB/256\r\n c1 = np.array([250,59,59])/256 #RGB/256\r\n c2 = np.array([103,0,13])/256 #RGB/256\r\n \r\n cdict = {'red': ((0.0, c1[0], c1[0]),\r\n (1.0, c2[0], c2[0])),\r\n 'green': ((0.0, c1[1], c1[1]),\r\n (1.0, c2[1], c2[1])),\r\n 'blue': ((0.0, c1[2], c1[2]),\r\n (1.0, c2[2], c2[2]))}\r\n my_cmap = LinearSegmentedColormap('my_colormap',cdict,256)\r\n else:\r\n print('cmap name does not match any of the available cmaps')\r\n\r\n return my_cmap\r\n\r\n\r\ndef save_basemap(m,info,path_to_basemap='auto'):\r\n '''\r\n Saves basemap (and correspoding info.grid) to a pickle file\r\n \r\n Arguments:\r\n m (mpl_toolkits.basemap.Basemap): Basemap object\r\n info (info): ``info`` object containing metadata\r\n \r\n Keyword Arguments:\r\n path_to_basemap (str): If ``'auto'`` it looks in ``grids`` directory\r\n \r\n Returns:\r\n Pickle file\r\n \r\n See also:\r\n :mod:`pickle`\r\n '''\r\n# \r\n# basemap = [grid, m]\r\n# f = open(str(path_to_map / (info.grid.basemap + '.p')),'w')\r\n# pickle.dump(grid, f)\r\n# pickle.dump(m, f)\r\n# f.close()\r\n \r\n# picklename = str(path_to_map / (info.grid.basemap + '.p'))\r\n# pickle.dump(basemap, open(picklename, 'wb'), -1)\r\n# print('!!! Pickle just made: ' + picklename)\r\n \r\n path_to_map = define_path_to_map(info, path_to_basemap=path_to_basemap)\r\n \r\n# basemap_picklename = str(path_to_map / (info.grid.basemap + '.basemap'))\r\n basemap_picklename = os.path.join(path_to_map,info.grid.basemap + '.basemap')\r\n pickle.dump(m, open(basemap_picklename, 'wb'), -1)\r\n \r\n# info_picklename = str(path_to_map / (info.grid.basemap + '.grid'))\r\n info_picklename = os.path.join(path_to_map, info.grid.basemap + '.grid')\r\n pickle.dump(info, open(info_picklename, 'wb'), -1)\r\n \r\n print('!!! Pickles were just made: ' + basemap_picklename)\r\n return\r\n"
] |
[
[
"numpy.flipud",
"matplotlib.pyplot.get_cmap",
"numpy.round",
"numpy.max",
"numpy.nanmean",
"numpy.ma.masked_where",
"matplotlib.pyplot.subplot2grid",
"matplotlib.pyplot.gca",
"numpy.arange",
"matplotlib.colors.LinearSegmentedColormap",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.close",
"numpy.warnings.filterwarnings",
"matplotlib.pyplot.figure",
"numpy.rot90",
"numpy.min",
"numpy.log10",
"pandas.unique",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.use",
"matplotlib.pyplot.colorbar"
]
] |
arvkevi/awesome-streamlit
|
[
"be454e29c35a9a1a760b1737a5176a47f4f9717b"
] |
[
"gallery/self_driving_cars/self_driving_cars.py"
] |
[
"# -*- coding: utf-8 -*-\r\n# Copyright 2018-2019 Streamlit Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n# This demo lets you to explore the Udacity self-driving car image dataset.\r\n# More info: https://github.com/streamlit/demo-self-driving\r\n#\r\n# In order for this to run on in docker/ on linux you might need to run\r\n# `apt-get install -y libsm6 libxext6 libxrender-dev libglib2.0-0`\r\n\r\nimport os\r\nimport urllib\r\n\r\nimport altair as alt\r\nimport cv2\r\nimport numpy as np\r\nimport pandas as pd\r\nimport streamlit as st\r\n\r\n\r\n# Streamlit encourages well-structured code, like starting execution in a main() function.\r\ndef main():\r\n # Render the readme as markdown using st.markdown.\r\n readme_text = st.markdown(\"\"\"\r\n# Streamlit Demo: The Udacity Self-driving Car Image Browser\r\n\r\nThis project demonstrates the [Udacity self-driving-car dataset](https://github.com/udacity/self-driving-car) and [YOLO object detection](https://pjreddie.com/darknet/yolo) into an interactive [Streamlit](https://streamlit.io) app.\r\n\r\nThe complete demo is [implemented in less than 300 lines of Python](https://github.com/streamlit/demo-self-driving/blob/master/app.py) and illustrates all the major building blocks of Streamlit.\r\n\r\n### Questions? Comments?\r\n\r\nPlease ask in the [Streamlit community](https://discuss.streamlit.io).\r\n\r\n\"\"\")\r\n # Download external dependencies.info = st.empty()\r\n if not st.checkbox(\"MAYBE DOWNLOAD 250MB OF DATA TO THE SERVER. THIS MIGHT TAKE A FEW MINUTES!\"):\r\n return\r\n\r\n for filename in EXTERNAL_DEPENDENCIES.keys():\r\n download_file(filename)\r\n\r\n st.sidebar.title(\"Self Driving Cars\")\r\n run_the_app()\r\n\r\n# This file downloader demonstrates Streamlit animation.\r\ndef download_file(file_path):\r\n # Don't download the file twice. (If possible, verify the download using the file length.)\r\n if os.path.exists(file_path):\r\n if \"size\" not in EXTERNAL_DEPENDENCIES[file_path]:\r\n return\r\n elif os.path.getsize(file_path) == EXTERNAL_DEPENDENCIES[file_path][\"size\"]:\r\n return\r\n\r\n # These are handles to two visual elements to animate.\r\n weights_warning, progress_bar = None, None\r\n try:\r\n weights_warning = st.warning(\"Downloading %s...\" % file_path)\r\n progress_bar = st.progress(0)\r\n with open(file_path, \"wb\") as output_file:\r\n with urllib.request.urlopen(EXTERNAL_DEPENDENCIES[file_path][\"url\"]) as response:\r\n length = int(response.info()[\"Content-Length\"])\r\n counter = 0.0\r\n MEGABYTES = 2.0 ** 20.0\r\n while True:\r\n data = response.read(8192)\r\n if not data:\r\n break\r\n counter += len(data)\r\n output_file.write(data)\r\n\r\n # We perform animation by overwriting the elements.\r\n weights_warning.warning(\"Downloading %s... (%6.2f/%6.2f MB)\" %\r\n (file_path, counter / MEGABYTES, length / MEGABYTES))\r\n progress_bar.progress(min(counter / length, 1.0))\r\n\r\n # Finally, we remove these visual elements by calling .empty().\r\n finally:\r\n if weights_warning is not None:\r\n weights_warning.empty()\r\n if progress_bar is not None:\r\n progress_bar.empty()\r\n\r\n# This is the main app app itself, which appears when the user selects \"Run the app\".\r\ndef run_the_app():\r\n # To make Streamlit fast, st.cache allows us to reuse computation across runs.\r\n # In this common pattern, we download data from an endpoint only once.\r\n @st.cache\r\n def load_metadata(url):\r\n return pd.read_csv(url)\r\n\r\n # This function uses some Pandas magic to summarize the metadata Dataframe.\r\n @st.cache\r\n def create_summary(metadata):\r\n one_hot_encoded = pd.get_dummies(metadata[[\"frame\", \"label\"]], columns=[\"label\"])\r\n summary = one_hot_encoded.groupby([\"frame\"]).sum().rename(columns={\r\n \"label_biker\": \"biker\",\r\n \"label_car\": \"car\",\r\n \"label_pedestrian\": \"pedestrian\",\r\n \"label_trafficLight\": \"traffic light\",\r\n \"label_truck\": \"truck\"\r\n })\r\n return summary\r\n\r\n # An amazing property of st.cached functions is that you can pipe them into\r\n # one another to form a computation DAG (directed acyclic graph). Streamlit\r\n # recomputes only whatever subset is required to get the right answer!\r\n metadata = load_metadata(os.path.join(DATA_URL_ROOT, \"labels.csv.gz\"))\r\n summary = create_summary(metadata)\r\n\r\n # Uncomment these lines to peek at these DataFrames.\r\n # st.write('## Metadata', metadata[:1000], '## Summary', summary[:1000])\r\n\r\n # Draw the UI elements to search for objects (pedestrians, cars, etc.)\r\n selected_frame_index, selected_frame = frame_selector_ui(summary)\r\n if selected_frame_index == None:\r\n st.error(\"No frames fit the criteria. Please select different label or number.\")\r\n return\r\n\r\n # Draw the UI element to select parameters for the YOLO object detector.\r\n confidence_threshold, overlap_threshold = object_detector_ui()\r\n\r\n # Load the image from S3.\r\n image_url = os.path.join(DATA_URL_ROOT, selected_frame)\r\n image = load_image(image_url)\r\n\r\n # Add boxes for objects on the image. These are the boxes for the ground image.\r\n boxes = metadata[metadata.frame == selected_frame].drop(columns=[\"frame\"])\r\n draw_image_with_boxes(image, boxes, \"Ground Truth\",\r\n \"**Human-annotated data** (frame `%i`)\" % selected_frame_index)\r\n\r\n # Get the boxes for the objects detected by YOLO by running the YOLO model.\r\n yolo_boxes = yolo_v3(image, overlap_threshold, confidence_threshold)\r\n draw_image_with_boxes(image, yolo_boxes, \"Real-time Computer Vision\",\r\n \"**YOLO v3 Model** (overlap `%3.1f`) (confidence `%3.1f`)\" % (overlap_threshold, confidence_threshold))\r\n\r\n# This sidebar UI is a little search engine to find certain object types.\r\ndef frame_selector_ui(summary):\r\n st.sidebar.markdown(\"# Frame\")\r\n\r\n # The user can pick which type of object to search for.\r\n object_type = st.sidebar.selectbox(\"Search for which objects?\", summary.columns, 2)\r\n\r\n # The user can select a range for how many of the selected objecgt should be present.\r\n min_elts, max_elts = st.sidebar.slider(\"How many %ss (select a range)?\" % object_type, 0, 25, [10, 20])\r\n selected_frames = get_selected_frames(summary, object_type, min_elts, max_elts)\r\n if len(selected_frames) < 1:\r\n return None, None\r\n\r\n # Choose a frame out of the selected frames.\r\n selected_frame_index = st.sidebar.slider(\"Choose a frame (index)\", 0, len(selected_frames) - 1, 0)\r\n\r\n # Draw an altair chart in the sidebar with information on the frame.\r\n objects_per_frame = summary.loc[selected_frames, object_type].reset_index(drop=True).reset_index()\r\n chart = alt.Chart(objects_per_frame, height=120).mark_area().encode(\r\n alt.X(\"index:Q\", scale=alt.Scale(nice=False)),\r\n alt.Y(\"%s:Q\" % object_type))\r\n selected_frame_df = pd.DataFrame({\"selected_frame\": [selected_frame_index]})\r\n vline = alt.Chart(selected_frame_df).mark_rule(color=\"red\").encode(\r\n alt.X(\"selected_frame:Q\", axis=None)\r\n )\r\n st.sidebar.altair_chart(alt.layer(chart, vline))\r\n\r\n selected_frame = selected_frames[selected_frame_index]\r\n return selected_frame_index, selected_frame\r\n\r\n# Select frames based on the selection in the sidebar\r\[email protected]\r\ndef get_selected_frames(summary, label, min_elts, max_elts):\r\n return summary[np.logical_and(summary[label] >= min_elts, summary[label] <= max_elts)].index\r\n\r\n# This sidebar UI lets the user select parameters for the YOLO object detector.\r\ndef object_detector_ui():\r\n st.sidebar.markdown(\"# Model\")\r\n confidence_threshold = st.sidebar.slider(\"Confidence threshold\", 0.0, 1.0, 0.5, 0.01)\r\n overlap_threshold = st.sidebar.slider(\"Overlap threshold\", 0.0, 1.0, 0.3, 0.01)\r\n return confidence_threshold, overlap_threshold\r\n\r\n# Draws an image with boxes overlayed to indicate the presence of cars, pedestrians etc.\r\ndef draw_image_with_boxes(image, boxes, header, description):\r\n # Superpose the semi-transparent object detection boxes. # Colors for the boxes\r\n LABEL_COLORS = {\r\n \"car\": [255, 0, 0],\r\n \"pedestrian\": [0, 255, 0],\r\n \"truck\": [0, 0, 255],\r\n \"trafficLight\": [255, 255, 0],\r\n \"biker\": [255, 0, 255],\r\n }\r\n image_with_boxes = image.astype(np.float64)\r\n for _, (xmin, ymin, xmax, ymax, label) in boxes.iterrows():\r\n image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] += LABEL_COLORS[label]\r\n image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] /= 2\r\n\r\n # Draw the header and image.\r\n st.subheader(header)\r\n st.markdown(description)\r\n st.image(image_with_boxes.astype(np.uint8), use_column_width=True)\r\n\r\n# Download a single file and make its content available as a string.\r\[email protected](show_spinner=False)\r\ndef get_file_content_as_string(path):\r\n url = 'https://raw.githubusercontent.com/streamlit/demo-self-driving/master/' + path\r\n response = urllib.request.urlopen(url)\r\n return response.read().decode(\"utf-8\")\r\n\r\n# This function loads an image from Streamlit public repo on S3. We use st.cache on this\r\n# function as well, so we can reuse the images across runs.\r\[email protected](show_spinner=False)\r\ndef load_image(url):\r\n with urllib.request.urlopen(url) as response:\r\n image = np.asarray(bytearray(response.read()), dtype=\"uint8\")\r\n image = cv2.imdecode(image, cv2.IMREAD_COLOR)\r\n image = image[:, :, [2, 1, 0]] # BGR -> RGB\r\n return image\r\n\r\n# Run the YOLO model to detect objects.\r\ndef yolo_v3(image, confidence_threshold, overlap_threshold):\r\n # Load the network. Because this is cached it will only happen once.\r\n @st.cache(allow_output_mutation=True)\r\n def load_network(config_path, weights_path):\r\n net = cv2.dnn.readNetFromDarknet(config_path, weights_path)\r\n output_layer_names = net.getLayerNames()\r\n output_layer_names = [output_layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\r\n return net, output_layer_names\r\n net, output_layer_names = load_network(\"yolov3.cfg\", \"yolov3.weights\")\r\n\r\n # Run the YOLO neural net.\r\n blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)\r\n net.setInput(blob)\r\n layer_outputs = net.forward(output_layer_names)\r\n\r\n # Supress detections in case of too low confidence or too much overlap.\r\n boxes, confidences, class_IDs = [], [], []\r\n H, W = image.shape[:2]\r\n for output in layer_outputs:\r\n for detection in output:\r\n scores = detection[5:]\r\n classID = np.argmax(scores)\r\n confidence = scores[classID]\r\n if confidence > confidence_threshold:\r\n box = detection[0:4] * np.array([W, H, W, H])\r\n centerX, centerY, width, height = box.astype(\"int\")\r\n x, y = int(centerX - (width / 2)), int(centerY - (height / 2))\r\n boxes.append([x, y, int(width), int(height)])\r\n confidences.append(float(confidence))\r\n class_IDs.append(classID)\r\n indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence_threshold, overlap_threshold)\r\n\r\n # Map from YOLO labels to Udacity labels.\r\n UDACITY_LABELS = {\r\n 0: 'pedestrian',\r\n 1: 'biker',\r\n 2: 'car',\r\n 3: 'biker',\r\n 5: 'truck',\r\n 7: 'truck',\r\n 9: 'trafficLight'\r\n }\r\n xmin, xmax, ymin, ymax, labels = [], [], [], [], []\r\n if len(indices) > 0:\r\n # loop over the indexes we are keeping\r\n for i in indices.flatten():\r\n label = UDACITY_LABELS.get(class_IDs[i], None)\r\n if label is None:\r\n continue\r\n\r\n # extract the bounding box coordinates\r\n x, y, w, h = boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]\r\n\r\n xmin.append(x)\r\n ymin.append(y)\r\n xmax.append(x+w)\r\n ymax.append(y+h)\r\n labels.append(label)\r\n\r\n boxes = pd.DataFrame({\"xmin\": xmin, \"ymin\": ymin, \"xmax\": xmax, \"ymax\": ymax, \"labels\": labels})\r\n return boxes[[\"xmin\", \"ymin\", \"xmax\", \"ymax\", \"labels\"]]\r\n\r\n# Path to the Streamlit public S3 bucket\r\nDATA_URL_ROOT = \"https://streamlit-self-driving.s3-us-west-2.amazonaws.com/\"\r\n\r\n# External files to download.\r\nEXTERNAL_DEPENDENCIES = {\r\n \"yolov3.weights\": {\r\n \"url\": \"https://pjreddie.com/media/files/yolov3.weights\",\r\n \"size\": 248007048\r\n },\r\n \"yolov3.cfg\": {\r\n \"url\": \"https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg\",\r\n \"size\": 8342\r\n }\r\n}\r\n\r\nmain()\r\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame",
"numpy.argmax",
"numpy.array",
"numpy.logical_and",
"pandas.get_dummies"
]
] |
junsikh/pytorch3d
|
[
"a7948adc404d88a8f1247d7b37d3091e791b124a"
] |
[
"pytorch3d/io/experimental_gltf_io.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n\"\"\"\nThis module implements loading meshes from glTF 2 assets stored in a\nGLB container file or a glTF JSON file with embedded binary data.\nIt is experimental.\n\nThe module provides a MeshFormatInterpreter called\nMeshGlbFormat which must be used explicitly.\ne.g.\n\n.. code-block:: python\n\n from pytorch3d.io import IO\n from pytorch3d.io.experimental_gltf_io import MeshGlbFormat\n\n io = IO()\n io.register_meshes_format(MeshGlbFormat())\n io.load_mesh(...)\n\nThis implementation is quite restricted in what it supports.\n\n - It does not try to validate the input against the standard.\n - It loads the default scene only.\n - Only triangulated geometry is supported.\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\n - All material properties are ignored except for either vertex color, baseColorTexture\n or baseColorFactor. If available, one of these (in this order) is exclusively\n used which does not match the semantics of the standard.\n\"\"\"\n\nimport json\nimport struct\nimport warnings\nfrom base64 import b64decode\nfrom collections import deque\nfrom enum import IntEnum\nfrom io import BytesIO\nfrom typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union, cast\n\nimport numpy as np\nimport torch\nfrom iopath.common.file_io import PathManager\nfrom PIL import Image\nfrom pytorch3d.io.utils import PathOrStr, _open_file\nfrom pytorch3d.renderer.mesh import TexturesBase, TexturesUV, TexturesVertex\nfrom pytorch3d.structures import Meshes, join_meshes_as_scene\nfrom pytorch3d.transforms import Transform3d, quaternion_to_matrix\n\nfrom .pluggable_formats import MeshFormatInterpreter, endswith\n\n\n_GLTF_MAGIC = 0x46546C67\n_JSON_CHUNK_TYPE = 0x4E4F534A\n_BINARY_CHUNK_TYPE = 0x004E4942\n_DATA_URI_PREFIX = \"data:application/octet-stream;base64,\"\n\n\nclass _PrimitiveMode(IntEnum):\n POINTS = 0\n LINES = 1\n LINE_LOOP = 2\n LINE_STRIP = 3\n TRIANGLES = 4\n TRIANGLE_STRIP = 5\n TRIANGLE_FAN = 6\n\n\nclass _ComponentType(IntEnum):\n BYTE = 5120\n UNSIGNED_BYTE = 5121\n SHORT = 5122\n UNSIGNED_SHORT = 5123\n UNSIGNED_INT = 5125\n FLOAT = 5126\n\n\n_ITEM_TYPES: Dict[int, Any] = {\n 5120: np.int8,\n 5121: np.uint8,\n 5122: np.int16,\n 5123: np.uint16,\n 5125: np.uint32,\n 5126: np.float32,\n}\n\n\n_ElementShape = Union[Tuple[int], Tuple[int, int]]\n_ELEMENT_SHAPES: Dict[str, _ElementShape] = {\n \"SCALAR\": (1,),\n \"VEC2\": (2,),\n \"VEC3\": (3,),\n \"VEC4\": (4,),\n \"MAT2\": (2, 2),\n \"MAT3\": (3, 3),\n \"MAT4\": (4, 4),\n}\n\n\ndef _read_header(stream: BinaryIO) -> Optional[Tuple[int, int]]:\n header = stream.read(12)\n magic, version, length = struct.unpack(\"<III\", header)\n\n if magic != _GLTF_MAGIC:\n return None\n\n return version, length\n\n\ndef _read_chunks(\n stream: BinaryIO, length: int\n) -> Optional[Tuple[Dict[str, Any], np.ndarray]]:\n \"\"\"\n Get the json header and the binary data from a\n GLB file.\n \"\"\"\n json_data = None\n binary_data = None\n\n while stream.tell() < length:\n chunk_header = stream.read(8)\n chunk_length, chunk_type = struct.unpack(\"<II\", chunk_header)\n chunk_data = stream.read(chunk_length)\n if chunk_type == _JSON_CHUNK_TYPE:\n json_data = json.loads(chunk_data)\n elif chunk_type == _BINARY_CHUNK_TYPE:\n binary_data = chunk_data\n else:\n warnings.warn(\"Unsupported chunk type\")\n return None\n\n if json_data is None:\n raise ValueError(\"Missing json header\")\n\n if binary_data is not None:\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\n\n return json_data, binary_data\n\n\ndef _make_node_transform(node: Dict[str, Any]) -> Transform3d:\n \"\"\"\n Convert a transform from the json data in to a PyTorch3D\n Transform3d format.\n \"\"\"\n array = node.get(\"matrix\")\n if array is not None: # Stored in column-major order\n M = np.array(array, dtype=np.float32).reshape(4, 4, order=\"F\")\n return Transform3d(matrix=torch.from_numpy(M))\n\n out = Transform3d()\n\n # Given some of (scale/rotation/translation), we do them in that order to\n # get points in to the world space.\n # See https://github.com/KhronosGroup/glTF/issues/743 .\n\n array = node.get(\"scale\", None)\n if array is not None:\n scale_vector = torch.FloatTensor(array)\n out = out.scale(scale_vector[None])\n\n # Rotation quaternion (x, y, z, w) where w is the scalar\n array = node.get(\"rotation\", None)\n if array is not None:\n x, y, z, w = array\n # We negate w. This is equivalent to inverting the rotation.\n # This is needed as quaternion_to_matrix makes a matrix which\n # operates on column vectors, whereas Transform3d wants a\n # matrix which operates on row vectors.\n rotation_quaternion = torch.FloatTensor([-w, x, y, z])\n rotation_matrix = quaternion_to_matrix(rotation_quaternion)\n out = out.rotate(R=rotation_matrix)\n\n array = node.get(\"translation\", None)\n if array is not None:\n translation_vector = torch.FloatTensor(array)\n out = out.translate(x=translation_vector[None])\n\n return out\n\n\nclass _GLTFLoader:\n def __init__(self, stream: BinaryIO) -> None:\n self._json_data = None\n # Map from buffer index to (decoded) binary data\n self._binary_data = {}\n\n version_and_length = _read_header(stream)\n if version_and_length is None: # GLTF\n stream.seek(0)\n json_data = json.load(stream)\n else: # GLB\n version, length = version_and_length\n if version != 2:\n warnings.warn(\"Unsupported version\")\n return\n json_and_binary_data = _read_chunks(stream, length)\n if json_and_binary_data is None:\n raise ValueError(\"Data not found\")\n json_data, binary_data = json_and_binary_data\n self._binary_data[0] = binary_data\n\n self._json_data = json_data\n self._accessors = json_data.get(\"accessors\", [])\n self._buffer_views = json_data.get(\"bufferViews\", [])\n self._buffers = json_data.get(\"buffers\", [])\n self._texture_map_images = {}\n\n def _access_image(self, image_index: int) -> np.ndarray:\n \"\"\"\n Get the data for an image from the file. This is only called\n by _get_texture_map_image which caches it.\n \"\"\"\n\n image_json = self._json_data[\"images\"][image_index]\n buffer_view = self._buffer_views[image_json[\"bufferView\"]]\n if \"byteStride\" in buffer_view:\n raise NotImplementedError(\"strided buffer views\")\n\n length = buffer_view[\"byteLength\"]\n offset = buffer_view.get(\"byteOffset\", 0)\n\n binary_data = self.get_binary_data(buffer_view[\"buffer\"])\n\n bytesio = BytesIO(binary_data[offset : offset + length].tobytes())\n # pyre-fixme[16]: `Image.Image` has no attribute `__enter__`.\n with Image.open(bytesio) as f:\n array = np.array(f)\n if array.dtype == np.uint8:\n return array.astype(np.float32) / 255.0\n else:\n return array\n\n def _get_texture_map_image(self, image_index: int) -> torch.Tensor:\n \"\"\"\n Return a texture map image as a torch tensor.\n Calling this function repeatedly with the same arguments returns\n the very same tensor, this allows a memory optimization to happen\n later in TexturesUV.join_scene.\n Any alpha channel is ignored.\n \"\"\"\n im = self._texture_map_images.get(image_index)\n if im is not None:\n return im\n\n im = torch.from_numpy(self._access_image(image_index))[:, :, :3]\n self._texture_map_images[image_index] = im\n return im\n\n def _access_data(self, accessor_index: int) -> np.ndarray:\n \"\"\"\n Get the raw data from an accessor as a numpy array.\n \"\"\"\n accessor = self._accessors[accessor_index]\n\n buffer_view_index = accessor.get(\"bufferView\")\n # Undefined buffer view (all zeros) are not (yet) supported\n if buffer_view_index is None:\n raise NotImplementedError(\"Undefined buffer view\")\n\n accessor_byte_offset = accessor.get(\"byteOffset\", 0)\n component_type = accessor[\"componentType\"]\n element_count = accessor[\"count\"]\n element_type = accessor[\"type\"]\n\n # Sparse accessors are not (yet) supported\n if accessor.get(\"sparse\") is not None:\n raise NotImplementedError(\"Sparse Accessors\")\n\n buffer_view = self._buffer_views[buffer_view_index]\n buffer_index = buffer_view[\"buffer\"]\n buffer_byte_length = buffer_view[\"byteLength\"]\n element_byte_offset = buffer_view.get(\"byteOffset\", 0)\n element_byte_stride = buffer_view.get(\"byteStride\", 0)\n if element_byte_stride != 0 and element_byte_stride < 4:\n raise ValueError(\"Stride is too small.\")\n if element_byte_stride > 252:\n raise ValueError(\"Stride is too big.\")\n\n element_shape = _ELEMENT_SHAPES[element_type]\n item_type = _ITEM_TYPES[component_type]\n item_dtype = np.dtype(item_type)\n item_count = np.prod(element_shape)\n item_size = item_dtype.itemsize\n size = element_count * item_count * item_size\n if size > buffer_byte_length:\n raise ValueError(\"Buffer did not have enough data for the accessor\")\n\n buffer_ = self._buffers[buffer_index]\n binary_data = self.get_binary_data(buffer_index)\n if len(binary_data) < buffer_[\"byteLength\"]:\n raise ValueError(\"Not enough binary data for the buffer\")\n\n if element_byte_stride == 0:\n element_byte_stride = item_size * item_count\n # The same buffer can store interleaved elements\n if element_byte_stride < item_size * item_count:\n raise ValueError(\"Items should not overlap\")\n\n dtype = np.dtype(\n {\n \"names\": [\"element\"],\n \"formats\": [str(element_shape) + item_dtype.str],\n \"offsets\": [0],\n \"itemsize\": element_byte_stride,\n }\n )\n\n byte_offset = accessor_byte_offset + element_byte_offset\n if byte_offset % item_size != 0:\n raise ValueError(\"Misaligned data\")\n byte_length = element_count * element_byte_stride\n buffer_view = binary_data[byte_offset : byte_offset + byte_length].view(dtype)[\n \"element\"\n ]\n\n # Convert matrix data from column-major (OpenGL) to row-major order\n if element_type in (\"MAT2\", \"MAT3\", \"MAT4\"):\n buffer_view = np.transpose(buffer_view, (0, 2, 1))\n\n return buffer_view\n\n def _get_primitive_attribute(\n self, primitive_attributes: Dict[str, Any], key: str, dtype\n ) -> Optional[np.ndarray]:\n accessor_index = primitive_attributes.get(key)\n if accessor_index is None:\n return None\n primitive_attribute = self._access_data(accessor_index)\n if key == \"JOINTS_0\":\n pass\n elif dtype == np.uint8:\n primitive_attribute /= 255.0\n elif dtype == np.uint16:\n primitive_attribute /= 65535.0\n else:\n if dtype != np.float32:\n raise ValueError(\"Unexpected data type\")\n primitive_attribute = primitive_attribute.astype(dtype)\n return primitive_attribute\n\n def get_binary_data(self, buffer_index: int):\n \"\"\"\n Get the binary data from a buffer as a 1D numpy array of bytes.\n This is implemented for explicit uri data buffers or the main GLB data\n segment.\n \"\"\"\n buffer_ = self._buffers[buffer_index]\n binary_data = self._binary_data.get(buffer_index)\n if binary_data is None: # Lazily decode binary data\n uri = buffer_.get(\"uri\")\n if not uri.startswith(_DATA_URI_PREFIX):\n raise NotImplementedError(\"Unexpected URI type\")\n binary_data = b64decode(uri[len(_DATA_URI_PREFIX) :])\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\n self._binary_data[buffer_index] = binary_data\n return binary_data\n\n def get_texture_for_mesh(\n self, primitive: Dict[str, Any], indices: torch.Tensor\n ) -> Optional[TexturesBase]:\n \"\"\"\n Get the texture object representing the given mesh primitive.\n\n Args:\n primitive: the mesh primitive being loaded.\n indices: the face indices of the mesh\n \"\"\"\n attributes = primitive[\"attributes\"]\n vertex_colors = self._get_primitive_attribute(attributes, \"COLOR_0\", np.float32)\n if vertex_colors is not None:\n vertex_colors = np.expand_dims(vertex_colors, axis=0) # ValueError: Expected verts_features to be of shape (N, V, C); got 'torch.Size([184, 4])'\n return TexturesVertex(torch.from_numpy(vertex_colors))\n\n vertex_texcoords_0 = self._get_primitive_attribute(\n attributes, \"TEXCOORD_0\", np.float32\n )\n if vertex_texcoords_0 is not None:\n verts_uvs = torch.from_numpy(vertex_texcoords_0)\n verts_uvs[:, 1] = 1 - verts_uvs[:, -1]\n faces_uvs = indices\n material_index = primitive.get(\"material\", 0)\n material = self._json_data[\"materials\"][material_index]\n material_roughness = material[\"pbrMetallicRoughness\"]\n if \"baseColorTexture\" in material_roughness:\n texture_index = material_roughness[\"baseColorTexture\"][\"index\"]\n texture_json = self._json_data[\"textures\"][texture_index]\n # Todo - include baseColorFactor when also given\n # Todo - look at the sampler\n image_index = texture_json[\"source\"]\n map = self._get_texture_map_image(image_index)\n elif \"baseColorFactor\" in material_roughness:\n # Constant color?\n map = torch.FloatTensor(material_roughness[\"baseColorFactor\"])[\n None, None, :3\n ]\n texture = TexturesUV(\n # pyre-fixme[61]: `map` may not be initialized here.\n maps=[map], # alpha channel ignored\n faces_uvs=[faces_uvs],\n verts_uvs=[verts_uvs],\n )\n return texture\n\n return None\n\n def load(self, include_textures: bool) -> List[Tuple[Optional[str], Meshes]]:\n \"\"\"\n Attempt to load all the meshes making up the default scene from\n the file as a list of possibly-named Meshes objects.\n\n Args:\n include_textures: Whether to try loading textures.\n\n Returns:\n Meshes object containing one mesh.\n \"\"\"\n if self._json_data is None:\n raise ValueError(\"Initialization problem\")\n\n # This loads the default scene from the file.\n # This is usually the only one.\n # It is possible to have multiple scenes, in which case\n # you could choose another here instead of taking the default.\n scene_index = self._json_data.get(\"scene\")\n\n if scene_index is None:\n raise ValueError(\"Default scene is not specified.\")\n\n scene = self._json_data[\"scenes\"][scene_index]\n nodes = self._json_data.get(\"nodes\", [])\n meshes = self._json_data.get(\"meshes\", [])\n root_node_indices = scene[\"nodes\"]\n\n mesh_transform = Transform3d()\n names_meshes_list: List[Tuple[Optional[str], Meshes]] = []\n\n # Keep track and apply the transform of the scene node to mesh vertices\n Q = deque([(Transform3d(), node_index) for node_index in root_node_indices])\n\n while Q:\n parent_transform, current_node_index = Q.popleft()\n\n current_node = nodes[current_node_index]\n\n transform = _make_node_transform(current_node)\n current_transform = transform.compose(parent_transform)\n\n if \"mesh\" in current_node:\n mesh_index = current_node[\"mesh\"]\n mesh = meshes[mesh_index]\n mesh_name = mesh.get(\"name\", None)\n mesh_transform = current_transform\n\n for primitive in mesh[\"primitives\"]:\n attributes = primitive[\"attributes\"]\n accessor_index = attributes[\"POSITION\"]\n positions = torch.from_numpy(\n self._access_data(accessor_index).copy()\n )\n positions = mesh_transform.transform_points(positions)\n\n mode = primitive.get(\"mode\", _PrimitiveMode.TRIANGLES)\n if mode != _PrimitiveMode.TRIANGLES:\n raise NotImplementedError(\"Non triangular meshes\")\n\n if \"indices\" in primitive:\n accessor_index = primitive[\"indices\"]\n indices = self._access_data(accessor_index).astype(np.int64)\n else:\n indices = np.arange(0, len(positions), dtype=np.int64)\n indices = torch.from_numpy(indices.reshape(-1, 3))\n\n texture = None\n if include_textures:\n texture = self.get_texture_for_mesh(primitive, indices)\n\n mesh_obj = Meshes(\n verts=[positions], faces=[indices], textures=texture\n )\n names_meshes_list.append((mesh_name, mesh_obj))\n\n if \"children\" in current_node:\n children_node_indices = current_node[\"children\"]\n Q.extend(\n [\n (current_transform, node_index)\n for node_index in children_node_indices\n ]\n )\n\n return names_meshes_list\n\n\ndef load_meshes(\n path: PathOrStr,\n path_manager: PathManager,\n include_textures: bool = True,\n) -> List[Tuple[Optional[str], Meshes]]:\n \"\"\"\n Loads all the meshes from the default scene in the given GLB file.\n and returns them separately.\n\n Args:\n path: path to read from\n path_manager: PathManager object for interpreting the path\n include_textures: whether to load textures\n\n Returns:\n List of (name, mesh) pairs, where the name is the optional name property\n from the GLB file, or None if it is absent, and the mesh is a Meshes\n object containing one mesh.\n \"\"\"\n with _open_file(path, path_manager, \"rb\") as f:\n loader = _GLTFLoader(cast(BinaryIO, f))\n names_meshes_list = loader.load(include_textures=include_textures)\n return names_meshes_list\n\n\nclass MeshGlbFormat(MeshFormatInterpreter):\n \"\"\"\n Implements loading meshes from glTF 2 assets stored in a\n GLB container file or a glTF JSON file with embedded binary data.\n\n This implementation is quite restricted in what it supports.\n\n - It does not try to validate the input against the standard.\n - It loads the default scene only.\n - Only triangulated geometry is supported.\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\n - All material properties are ignored except for either vertex color, baseColorTexture\n or baseColorFactor. If available, one of these (in this order) is exclusively\n used which does not match the semantics of the standard.\n \"\"\"\n\n def __init__(self) -> None:\n self.known_suffixes = (\".glb\",)\n\n def read(\n self,\n path: PathOrStr,\n include_textures: bool,\n device,\n path_manager: PathManager,\n **kwargs,\n ) -> Optional[Meshes]:\n if not endswith(path, self.known_suffixes):\n return None\n\n names_meshes_list = load_meshes(\n path=path,\n path_manager=path_manager,\n include_textures=include_textures,\n )\n\n meshes_list = [mesh for name, mesh in names_meshes_list]\n mesh = join_meshes_as_scene(meshes_list)\n return mesh.to(device)\n\n def save(\n self,\n data: Meshes,\n path: PathOrStr,\n path_manager: PathManager,\n binary: Optional[bool],\n **kwargs,\n ) -> bool:\n return False\n"
] |
[
[
"numpy.expand_dims",
"torch.from_numpy",
"numpy.dtype",
"numpy.frombuffer",
"torch.FloatTensor",
"numpy.prod",
"numpy.transpose",
"numpy.array"
]
] |
AIDynamicAction/rcognita
|
[
"bac48bd4a53539e4f22094705b180de1d711ac8c"
] |
[
"rcognita/systems.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains a generic interface for systems (environments) as well as concrete systems as realizations of the former\n\nRemarks: \n\n- All vectors are treated as of type [n,]\n- All buffers are treated as of type [L, n] where each row is a vector\n- Buffers are updated from bottom to top\n\n\"\"\"\n\nimport numpy as np\nfrom numpy.random import randn\n\nclass System:\n \"\"\"\n Interface class of dynamical systems a.k.a. environments.\n Concrete systems should be built upon this class.\n To design a concrete system: inherit this class, override:\n | :func:`~systems.system._state_dyn` :\n | right-hand side of system description (required)\n | :func:`~systems.system._disturb_dyn` :\n | right-hand side of disturbance model (if necessary)\n | :func:`~systems.system._ctrl_dyn` :\n | right-hand side of controller dynamical model (if necessary)\n | :func:`~systems.system.out` :\n | system out (if not overridden, output is identical to state)\n \n Attributes\n ----------\n sys_type : : string\n Type of system by description:\n \n | ``diff_eqn`` : differential equation :math:`\\mathcal D state = f(state, action, disturb)`\n | ``discr_fnc`` : difference equation :math:`state^+ = f(state, action, disturb)`\n | ``discr_prob`` : by probability distribution :math:`X^+ \\sim P_X(state^+| state, action, disturb)`\n \n where:\n \n | :math:`state` : state\n | :math:`action` : input\n | :math:`disturb` : disturbance\n \n The time variable ``t`` is commonly used by ODE solvers, and you shouldn't have it explicitly referenced in the definition, unless your system is non-autonomous.\n For the latter case, however, you already have the input and disturbance at your disposal.\n \n Parameters of the system are contained in ``pars`` attribute.\n \n dim_state, dim_input, dim_output, dim_disturb : : integer\n System dimensions \n pars : : list\n List of fixed parameters of the system\n ctrl_bnds : : array of shape ``[dim_input, 2]``\n Box control constraints.\n First element in each row is the lower bound, the second - the upper bound.\n If empty, control is unconstrained (default)\n is_dyn_ctrl : : 0 or 1\n If 1, the controller (a.k.a. agent) is considered as a part of the full state vector\n is_disturb : : 0 or 1\n If 0, no disturbance is fed into the system\n pars_disturb : : list\n Parameters of the disturbance model\n \n Each concrete system must realize ``System`` and define ``name`` attribute. \n \n \"\"\"\n def __init__(self,\n sys_type,\n dim_state,\n dim_input,\n dim_output,\n dim_disturb,\n pars=[],\n ctrl_bnds=[],\n is_dyn_ctrl=0,\n is_disturb=0,\n pars_disturb=[]):\n \n \"\"\"\n Parameters\n ----------\n sys_type : : string\n Type of system by description:\n \n | ``diff_eqn`` : differential equation :math:`\\mathcal D state = f(state, action, disturb)`\n | ``discr_fnc`` : difference equation :math:`state^+ = f(state, action, disturb)`\n | ``discr_prob`` : by probability distribution :math:`X^+ \\sim P_X(state^+| state, action, disturb)`\n \n where:\n \n | :math:`state` : state\n | :math:`action` : input\n | :math:`disturb` : disturbance\n \n The time variable ``t`` is commonly used by ODE solvers, and you shouldn't have it explicitly referenced in the definition, unless your system is non-autonomous.\n For the latter case, however, you already have the input and disturbance at your disposal.\n \n Parameters of the system are contained in ``pars`` attribute.\n \n dim_state, dim_input, dim_output, dim_disturb : : integer\n System dimensions \n pars : : list\n List of fixed parameters of the system\n ctrl_bnds : : array of shape ``[dim_input, 2]``\n Box control constraints.\n First element in each row is the lower bound, the second - the upper bound.\n If empty, control is unconstrained (default)\n is_dyn_ctrl : : 0 or 1\n If 1, the controller (a.k.a. agent) is considered as a part of the full state vector\n is_disturb : : 0 or 1\n If 0, no disturbance is fed into the system\n pars_disturb : : list\n Parameters of the disturbance model \n \"\"\"\n \n self.sys_type = sys_type\n \n self.dim_state = dim_state\n self.dim_input = dim_input\n self.dim_output = dim_output\n self.dim_disturb = dim_disturb \n self.pars = pars\n self.ctrl_bnds = ctrl_bnds\n self.is_dyn_ctrl = is_dyn_ctrl\n self.is_disturb = is_disturb\n self.pars_disturb = pars_disturb\n \n # Track system's state\n self._state = np.zeros(dim_state)\n \n # Current input (a.k.a. action)\n self.action = np.zeros(dim_input)\n \n if is_dyn_ctrl:\n if is_disturb:\n self._dim_full_state = self.dim_state + self.dim_disturb + self.dim_input\n else:\n self._dim_full_state = self.dim_state\n else:\n if is_disturb:\n self._dim_full_state = self.dim_state + self.dim_disturb\n else:\n self._dim_full_state = self.dim_state\n \n def _state_dyn(self, t, state, action, disturb):\n \"\"\"\n Description of the system internal dynamics.\n Depending on the system type, may be either the right-hand side of the respective differential or difference equation, or a probability distribution.\n As a probability disitribution, ``_state_dyn`` should return a number in :math:`[0,1]`\n \n \"\"\"\n pass\n\n def _disturb_dyn(self, t, disturb):\n \"\"\"\n Dynamical disturbance model depending on the system type:\n \n | ``sys_type = \"diff_eqn\"`` : :math:`\\mathcal D disturb = f_q(disturb)` \n | ``sys_type = \"discr_fnc\"`` : :math:`disturb^+ = f_q(disturb)`\n | ``sys_type = \"discr_prob\"`` : :math:`disturb^+ \\sim P_Q(disturb^+|disturb)`\n \n \"\"\" \n pass\n\n def _ctrl_dyn(self, t, action, observation):\n \"\"\"\n Dynamical controller. When ``is_dyn_ctrl=0``, the controller is considered static, which is to say that the control actions are\n computed immediately from the system's output.\n In case of a dynamical controller, the system's state vector effectively gets extended.\n Dynamical controllers have some advantages compared to the static ones.\n \n Depending on the system type, can be:\n \n | ``sys_type = \"diff_eqn\"`` : :math:`\\mathcal D action = f_u(action, observation)` \n | ``sys_type = \"discr_fnc\"`` : :math:`action^+ = f_u(action, observation)` \n | ``sys_type = \"discr_prob\"`` : :math:`action^+ \\sim P_U(action^+|action, observation)` \n \n \"\"\"\n Daction = np.zeros(self.dim_input)\n \n return Daction \n\n def out(self, state, action=[]):\n \"\"\"\n System output.\n This is commonly associated with signals that are measured in the system.\n Normally, output depends only on state ``state`` since no physical processes transmit input to output instantly. \n \n See also\n --------\n :func:`~systems.system._state_dyn`\n \n \"\"\"\n # Trivial case: output identical to state\n observation = state\n return observation\n \n def receive_action(self, action):\n \"\"\"\n Receive exogeneous control action to be fed into the system.\n This action is commonly computed by your controller (agent) using the system output :func:`~systems.system.out`. \n\n Parameters\n ----------\n action : : array of shape ``[dim_input, ]``\n Action\n \n \"\"\"\n self.action = action\n \n def closed_loop_rhs(self, t, state_full):\n \"\"\"\n Right-hand side of the closed-loop system description.\n Combines everything into a single vector that corresponds to the right-hand side of the closed-loop system description for further use by simulators.\n \n Attributes\n ----------\n state_full : : vector\n Current closed-loop system state \n \n \"\"\"\n rhs_full_state = np.zeros(self._dim_full_state)\n \n state = state_full[0:self.dim_state]\n \n if self.is_disturb:\n disturb = state_full[self.dim_state:]\n else:\n disturb = []\n \n if self.is_dyn_ctrl:\n action = state_full[-self.dim_input:]\n observation = self.out(state)\n rhs_full_state[-self.dim_input:] = self._ctrlDyn(t, action, observation)\n else:\n # Fetch the control action stored in the system\n action = self.action\n \n if self.ctrl_bnds.any():\n for k in range(self.dim_input):\n action[k] = np.clip(action[k], self.ctrl_bnds[k, 0], self.ctrl_bnds[k, 1])\n \n rhs_full_state[0:self.dim_state] = self._state_dyn(t, state, action, disturb)\n \n if self.is_disturb:\n rhs_full_state[self.dim_state:] = self._disturb_dyn(t, disturb)\n \n # Track system's state\n self._state = state\n \n return rhs_full_state \n \nclass Sys3WRobot(System):\n \"\"\"\n System class: 3-wheel robot with dynamical actuators.\n \n Description\n -----------\n Three-wheel robot with dynamical pushing force and steering torque (a.k.a. ENDI - extended non-holonomic double integrator) [[1]_]\n \n .. math::\n \\\\begin{array}{ll}\n \t\t\t\\dot x_с & = v \\cos \\\\alpha \\\\newline\n \t\t\t\\dot y_с & = v \\sin \\\\alpha \\\\newline\n \t\t\t\\dot \\\\alpha & = \\\\omega \\\\newline\n \t\t\t\\dot v & = \\\\left( \\\\frac 1 m F + q_1 \\\\right) \\\\newline\n \t\t\t\\dot \\\\omega & = \\\\left( \\\\frac 1 I M + q_2 \\\\right)\n \\\\end{array}\n \n **Variables**\n \n | :math:`x_с` : state-coordinate [m]\n | :math:`y_с` : observation-coordinate [m]\n | :math:`\\\\alpha` : turning angle [rad]\n | :math:`v` : speed [m/s]\n | :math:`\\\\omega` : revolution speed [rad/s]\n | :math:`F` : pushing force [N] \n | :math:`M` : steering torque [Nm]\n | :math:`m` : robot mass [kg]\n | :math:`I` : robot moment of inertia around vertical axis [kg m\\ :sup:`2`]\n | :math:`disturb` : actuator disturbance (see :func:`~RLframe.system.disturbDyn`). Is zero if ``is_disturb = 0``\n \n :math:`state = [x_c, y_c, \\\\alpha, v, \\\\omega]`\n \n :math:`action = [F, M]`\n \n ``pars`` = :math:`[m, I]`\n \n References\n ----------\n .. [1] W. Abbasi, F. urRehman, and I. Shah. “Backstepping based nonlinear adaptive control for the extended\n nonholonomic double integrator”. In: Kybernetika 53.4 (2017), pp. 578–594\n \n \"\"\" \n name = '3wrobot'\n \n def _state_dyn(self, t, state, action, disturb=[]): \n m, I = self.pars[0], self.pars[1]\n\n Dstate = np.zeros(self.dim_state)\n Dstate[0] = state[3] * np.cos( state[2] )\n Dstate[1] = state[3] * np.sin( state[2] )\n Dstate[2] = state[4]\n \n if self.is_disturb and (disturb != []):\n Dstate[3] = 1/m * (action[0] + disturb[0])\n Dstate[4] = 1/I * (action[1] + disturb[1])\n else:\n Dstate[3] = 1/m * action[0]\n Dstate[4] = 1/I * action[1] \n \n return Dstate \n \n def _disturb_dyn(self, t, disturb):\n \"\"\"\n Description\n -----------\n \n We use here a 1st-order stochastic linear system of the type\n \n .. math:: \\mathrm d Q_t = - \\\\frac{1}{\\\\tau_disturb} \\\\left( Q_t \\\\mathrm d t + \\\\sigma_disturb ( \\\\mathrm d B_t + \\\\mu_disturb ) \\\\right) ,\n \n where :math:`B` is the standard Brownian motion, :math:`Q` is the stochastic process whose realization is :math:`disturb`, and\n :math:`\\\\tau_disturb, \\\\sigma_disturb, \\\\mu_disturb` are the time constant, standard deviation and mean, resp.\n \n ``pars_disturb = [sigma_disturb, mu_disturb, tau_disturb]``, with each being an array of shape ``[dim_disturb, ]``\n \n \"\"\" \n Ddisturb = np.zeros(self.dim_disturb)\n \n if self.is_disturb:\n sigma_disturb = self.pars_disturb[0]\n mu_disturb = self.pars_disturb[1]\n tau_disturb = self.pars_disturb[2]\n \n for k in range(0, self.dim_disturb):\n Ddisturb[k] = - tau_disturb[k] * ( disturb[k] + sigma_disturb[k] * (randn() + mu_disturb[k]) )\n \n return Ddisturb \n \n def out(self, state, action=[]):\n observation = np.zeros(self.dim_output)\n # observation = state[:3] + measNoise # <-- Measure only position and orientation\n observation = state # <-- Position, force and torque sensors on\n return observation\n\nclass Sys3WRobotNI(System):\n \"\"\"\n System class: 3-wheel robot with static actuators (the NI - non-holonomic integrator).\n \n \n \"\"\" \n name = '3wrobotNI'\n \n def _state_dyn(self, t, state, action, disturb=[]): \n Dstate = np.zeros(self.dim_state)\n Dstate[0] = action[0] * np.cos( state[2] )\n Dstate[1] = action[0] * np.sin( state[2] )\n Dstate[2] = action[1]\n \n return Dstate \n \n def _disturb_dyn(self, t, disturb):\n \"\"\"\n \n \n \"\"\" \n Ddisturb = np.zeros(self.dim_disturb)\n \n if self.is_disturb:\n sigma_disturb = self.pars_disturb[0]\n mu_disturb = self.pars_disturb[1]\n tau_disturb = self.pars_disturb[2]\n \n for k in range(0, self.dim_disturb):\n Ddisturb[k] = - tau_disturb[k] * ( disturb[k] + sigma_disturb[k] * (randn() + mu_disturb[k]) )\n \n return Ddisturb \n \n def out(self, state, action=[]):\n observation = np.zeros(self.dim_output)\n observation = state\n return observation\n\nclass Sys2Tank(System):\n \"\"\"\n Two-tank system with nonlinearity.\n \n \"\"\"\n name = '2tank'\n \n def _state_dyn(self, t, state, action, disturb=[]): \n tau1, tau2, K1, K2, K3 = self.pars\n\n Dstate = np.zeros(self.dim_state)\n Dstate[0] = 1/(tau1) * ( -state[0] + K1 * action)\n Dstate[1] = 1/(tau2) * ( -state[1] + K2 * state[0] + K3 * state[1]**2)\n \n return Dstate \n \n def _disturb_dyn(self, t, disturb): \n Ddisturb = np.zeros(self.dim_disturb)\n \n return Ddisturb \n \n def out(self, state, action=[]):\n observation = state\n return observation "
] |
[
[
"numpy.clip",
"numpy.cos",
"numpy.sin",
"numpy.random.randn",
"numpy.zeros"
]
] |
jzstark/ossiriand
|
[
"232d12fa7375ce9090f79c2fe3107f0cb8e6a8eb"
] |
[
"image/model_update/FST_CG/tf_to_hdf5.py"
] |
[
"import tensorflow as tf\nimport os\nimport h5py\nimport numpy as np\n\n# The name of each layer\n\nconv2d_n = 'conv2d'\nconv_trans2d_n = 'transpose_conv2d'\nnorm_n = 'normalisation'\nrelu_n = 'activation'\nadd_n = 'add'\n\nlayer_names = [\n conv2d_n, norm_n, relu_n,\n conv2d_n, norm_n, relu_n,\n conv2d_n, norm_n, relu_n,\n conv2d_n, norm_n, relu_n, conv2d_n, norm_n, add_n,\n conv2d_n, norm_n, relu_n, conv2d_n, norm_n, add_n,\n conv2d_n, norm_n, relu_n, conv2d_n, norm_n, add_n,\n conv2d_n, norm_n, relu_n, conv2d_n, norm_n, add_n,\n conv2d_n, norm_n, relu_n, conv2d_n, norm_n, add_n,\n conv_trans2d_n, norm_n, relu_n,\n conv_trans2d_n, norm_n, relu_n,\n conv2d_n, norm_n\n ]\n\nfor i, val in enumerate(layer_names):\n layer_names[i] = val + '_' + str(i+1)\nlayer_names = [ x for x in layer_names if not x.startswith(relu_n)]\n\nlayer_names_rep = []\nfor val in layer_names:\n if val.startswith(norm_n):\n layer_names_rep.extend([val, val])\n else:\n layer_names_rep.append(val)\n\nflag = True\n\nfor i, val in enumerate(layer_names_rep):\n if not val.startswith(norm_n):\n continue\n if flag == True:\n append = '_beta'; flag = False\n else:\n append = '_gamma'; flag = True\n layer_names_rep[i] = val + append\n\nfor l in layer_names_rep:\n if l.startswith(add_n):\n layer_names_rep.remove(l)\n\n\n# Begin transfer\nmodel_name = \"wreck\"\ncheckpoint_file = \"checkpoint/\" + model_name + \".ckpt\"\nreader = tf.train.NewCheckpointReader(checkpoint_file)\n\ndfname = \"fst_style_\" + model_name + \".hdf5\"\ndata_file = h5py.File(dfname, 'w')\n\n# keys = reader.get_variable_to_shape_map().keys()\nfor i in range(len(layer_names_rep)):\n append = '' if i == 0 else '_' + str(i)\n key = 'Variable' + append\n\n data_file.create_dataset(layer_names_rep[i], data=reader.get_tensor(key).tolist())\n print(\"tensor_name: \", key, \" -- \", layer_names_rep[i])\n\ndata_file.close()\n"
] |
[
[
"tensorflow.train.NewCheckpointReader"
]
] |
junjungoal/RLbank
|
[
"e545fa854c203d7669d1d20d5fbe13365ba053ed"
] |
[
"rl/trainers/on_policy_trainer.py"
] |
[
"import os\nfrom time import time\nfrom collections import defaultdict, OrderedDict\nimport gzip\nimport pickle\n\nimport h5py\nimport torch\nimport wandb\nimport numpy as np\nimport moviepy.editor as mpy\nfrom tqdm import tqdm, trange\n\nfrom rl.policies import get_actor_critic_by_name\nfrom rl.trainers.base_trainer import BaseTrainer\nfrom rl.rollout import Rollout\nfrom util.logger import logger\nfrom util.pytorch import get_ckpt_path, count_parameters\nfrom util.info import Info\n\n\nclass OnPolicyTrainer(BaseTrainer):\n def __init__(self, config):\n super().__init__(config)\n\n def train(self):\n config = self._config\n num_batches = config.num_batches\n\n # load checkpoint\n step, update_iter = self._load_ckpt()\n\n logger.info(\"Start training at step=%d\", step)\n pbar = tqdm(initial=step, total=config.max_global_step, desc=config.run_name)\n\n env = self._env\n rollout = Rollout()\n episode = 0\n st_time = time()\n st_step = step\n num_updates = int(config.max_global_step // config.rollout_length // config.num_processes)\n while step < config.max_global_step:\n ob = env.reset()\n done = False\n ep_len = 0\n ep_rew = 0\n reward_infos = [Info() for _ in range(config.num_processes)]\n ep_info = Info()\n train_info = {}\n update_linear_schedule(self._agent._actor_optim,\n update_iter, num_updates,\n self._agent._actor_optim.lr)\n update_linear_schedule(self._agent._critic_optim,\n update_iter, num_updates,\n self._agent._critic_optim.lr)\n for _ in range(config.rollout_length):\n transition = {}\n ac, ac_before_activation, log_prob, vpred = self._agent.act(ob, pred_value=True, return_log_prob=True)\n rollout.add({'ob': ob, 'ac': ac, 'ac_before_activation': ac_before_activation, 'vpred': vpred, 'log_prob': log_prob})\n ob, reward, dones , infos = env.step(ac)\n ep_rew += reward\n pbar.update(1)\n for i, (info, done) in enumerate(zip(infos, dones)):\n reward_infos[i].add(info)\n if done:\n reward_info_dict = reward_infos[i].get_dict(reduction='sum', only_scalar=True)\n ep_info.add(reward_info_dict)\n rollout.add({'done': dones, 'rew': reward, 'ob_next': ob})\n\n ep_len += 1\n step += 1\n\n vpred = self._agent.value(ob)\n rollout.add({'vpred': vpred})\n self._agent.store_episode(rollout.get())\n train_info = self._agent.train()\n\n ep_info = ep_info.get_dict(only_scalar=True)\n\n logger.info(\"Rollout %d: %s\", update_iter,\n {k: v for k, v in ep_info.items()\n if np.isscalar(v)})\n update_iter += 1\n\n if update_iter % config.log_interval == 0:\n logger.info(\"Update networks %d\", update_iter)\n train_info.update({\n 'sec': (time() - st_time) / config.log_interval,\n 'steps_per_sec': (step - st_step) / (time() - st_time),\n 'update_iter': update_iter\n })\n st_time = time()\n st_step = step\n self._log_train(step, train_info, ep_info)\n\n if update_iter % config.evaluate_interval == 0:\n logger.info(\"Evaluate at %d\", update_iter)\n _, info, vids = self._evaluate(step=step, record=config.record)\n self._log_test(step, info, vids)\n\n if update_iter % config.ckpt_interval == 0:\n self._save_ckpt(step, update_iter)\n"
] |
[
[
"numpy.isscalar"
]
] |
ddaskan/trendy
|
[
"f438a98032a96a87144a46ecb8d52c5e84f7169b"
] |
[
"trendypy/utils.py"
] |
[
"'''\nUtility functions for the package.\n'''\nimport numpy as np\n\ndef scale_01(x):\n '''Scales array to 0-1.\n\n Args:\n x (iter): 1d array of float\n\n Returns:\n np.array: scaled 1d array\n\n Example:\n >>> scale_01([1, 2, 3, 5]).tolist()\n [0.0, 0.25, 0.5, 1.0]\n\n '''\n arr_min = min(x)\n x = np.array(x) - float(arr_min)\n arr_max = max(x)\n return x / float(arr_max)\n\ndef abs_distance(x, y):\n '''Returns absolute distance.\n\n Args:\n x (float): input 1\n y (float): input 2\n\n Returns:\n float: \\|x-y\\|\n\n Example:\n >>> abs_distance(5, 7)\n 2.0\n >>> abs_distance(4, 1)\n 3.0\n\n '''\n return float(abs(x - y))\n\ndef euclidean_distance(x, y):\n '''Returns Euclidean distance.\n\n Args:\n x (float or iter): input 1\n y (float or iter): input 2\n\n Returns:\n float: Euclidean distance\n\n References:\n https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html\n\n Examples:\n >>> x, y = 1, 2\n >>> euclidean_distance(x, y)\n 1.0\n >>> x, y = [1, 2], [4, 6]\n >>> euclidean_distance(x, y)\n 5.0\n\n '''\n return np.linalg.norm(np.array(x) - np.array(y))\n\n"
] |
[
[
"numpy.array"
]
] |
MrPluto/ml
|
[
"dbd5ae0ae59a11cc04fb4c38c01ba73b5fe2c895",
"dbd5ae0ae59a11cc04fb4c38c01ba73b5fe2c895"
] |
[
"practices/softmaxRegression.py",
"deep_exercises/part4/convModel/cnn_utils.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\"\"\"A very simple MNIST classifier.\nSee extensive documentation at\nhttps://www.tensorflow.org/get_started/mnist/beginners\n\"\"\"\n# from __future__ import absolute_import\n# from __future__ import division\n# from __future__ import print_function\n#\n# import argparse\n# import sys\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nimport tensorflow as tf\n\nFLAGS = None\n\n\n# def main(_):\n # Import data\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\n# Create the model\nx = tf.placeholder(tf.float32, [None, 784])\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\ny = tf.matmul(x, W) + b\n\n# Define loss and optimizer\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# The raw formulation of cross-entropy,\n#\n# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), # ∑-y`log(y)\n# reduction_indices=[1]))\n#\n# can be numerically unstable.\n#\n# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n# outputs of 'y', and then average across the batch.\n\ncross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n\n# square_sum = tf.reduce_sum(tf.square(y_ * tf.log(tf.nn.softmax(y))))\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n# Train\nfor _ in range(1000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\n# Test trained model\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nprint(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))\n\n\n# def weight_variable(shape):\n# initial = tf.truncated_normal(shape,stddev=0.1)\n# return tf.Variable(initial)\n#\n# def bias_variable(shape):\n# initial = tf.constant(0.1,shape=shape)\n# return tf.Variable(initial)\n#\n# def conv2d(x,W):\n# return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n#\n# def max_pool_2x2(x):\n# return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n#\n# # first convolution layer\n# W_conv1 = weight_variable([5,5,1,32]) #patch 5x5, input 1 and output 32 features\n# b_conv1 = bias_variable([32])\n#\n# x_image = tf.reshape(x,[-1,28,28,1]) #2,3dim corresponding w and h, 4dim means color channels\n#\n# h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)\n# h_pool1 = max_pool_2x2(h_conv1)\n#\n# #second convolution layer\n# W_conv2 = weight_variable([5, 5, 32, 64])\n# b_conv2 = bias_variable([64])\n#\n# h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n# h_pool2 = max_pool_2x2(h_conv2)\n#\n# #densely connected layer\n# W_fc1 = weight_variable([7 * 7 * 64, 1024])\n# b_fc1 = bias_variable([1024])\n#\n# h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n# h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n#\n# # dropout -- reduce overfitting\n# # https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf\n# keep_prob = tf.placeholder(tf.float32)\n# h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n#\n# #readout layer ?\n# W_fc2 = weight_variable([1024, 10])\n# b_fc2 = bias_variable([10])\n#\n# y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n#\n# cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))\n# train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n# correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\n# accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n#\n# with tf.Session() as sess:\n# sess.run(tf.global_variables_initializer())\n# for i in range(20000):\n# batch = mnist.train.next_batch(50)\n# if i % 100 == 0:\n# train_accuracy = accuracy.eval(feed_dict={\n# x: batch[0], y_: batch[1], keep_prob: 1.0})\n# print('step %d, training accuracy %g' % (i, train_accuracy))\n# train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n#\n# print('test accuracy %g' % accuracy.eval(feed_dict={\n# x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))\n",
"import math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\n\ndef load_dataset():\n train_dataset = h5py.File('datasets/train_signs.h5', \"r\")\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:]) # your train set features\n train_set_y_orig = np.array(train_dataset[\"train_set_y\"][:]) # your train set labels\n\n test_dataset = h5py.File('datasets/test_signs.h5', \"r\")\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:]) # your test set features\n test_set_y_orig = np.array(test_dataset[\"test_set_y\"][:]) # your test set labels\n\n classes = np.array(test_dataset[\"list_classes\"][:]) # the list of classes\n\n train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))\n test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))\n\n return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes\n\n\ndef random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):\n \"\"\"\n Creates a list of random minibatches from (X, Y)\n\n Arguments:\n X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)\n Y -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)\n mini_batch_size - size of the mini-batches, integer\n seed -- this is only for the purpose of grading, so that you're \"random minibatches are the same as ours.\n\n Returns:\n mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n \"\"\"\n\n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n\n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation,:,:,:]\n shuffled_Y = Y[permutation,:]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = int(math.floor(m/mini_batch_size)) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(0, num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:]\n mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:,:,:]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n return mini_batches\n\n\ndef convert_to_one_hot(Y, C):\n Y = np.eye(C)[Y.reshape(-1)].T\n return Y\n\n\ndef forward_propagation_for_predict(X, parameters):\n \"\"\"\n Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX\n\n Arguments:\n X -- input dataset placeholder, of shape (input size, number of examples)\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\"\n the shapes are given in initialize_parameters\n\n Returns:\n Z3 -- the output of the last LINEAR unit\n \"\"\"\n\n # Retrieve the parameters from the dictionary \"parameters\"\n W1 = parameters['W1']\n b1 = parameters['b1']\n W2 = parameters['W2']\n b2 = parameters['b2']\n W3 = parameters['W3']\n b3 = parameters['b3']\n # Numpy Equivalents:\n Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1\n A1 = tf.nn.relu(Z1) # A1 = relu(Z1)\n Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b2\n A2 = tf.nn.relu(Z2) # A2 = relu(Z2)\n Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b3\n\n return Z3\n\ndef predict(X, parameters):\n\n W1 = tf.convert_to_tensor(parameters[\"W1\"])\n b1 = tf.convert_to_tensor(parameters[\"b1\"])\n W2 = tf.convert_to_tensor(parameters[\"W2\"])\n b2 = tf.convert_to_tensor(parameters[\"b2\"])\n W3 = tf.convert_to_tensor(parameters[\"W3\"])\n b3 = tf.convert_to_tensor(parameters[\"b3\"])\n\n params = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2,\n \"W3\": W3,\n \"b3\": b3}\n\n x = tf.placeholder(\"float\", [12288, 1])\n\n z3 = forward_propagation_for_predict(x, params)\n p = tf.argmax(z3)\n\n sess = tf.Session()\n prediction = sess.run(p, feed_dict = {x: X})\n\n return prediction\n\n#def predict(X, parameters):\n#\n# W1 = tf.convert_to_tensor(parameters[\"W1\"])\n# b1 = tf.convert_to_tensor(parameters[\"b1\"])\n# W2 = tf.convert_to_tensor(parameters[\"W2\"])\n# b2 = tf.convert_to_tensor(parameters[\"b2\"])\n## W3 = tf.convert_to_tensor(parameters[\"W3\"])\n## b3 = tf.convert_to_tensor(parameters[\"b3\"])\n#\n## params = {\"W1\": W1,\n## \"b1\": b1,\n## \"W2\": W2,\n## \"b2\": b2,\n## \"W3\": W3,\n## \"b3\": b3}\n#\n# params = {\"W1\": W1,\n# \"b1\": b1,\n# \"W2\": W2,\n# \"b2\": b2}\n#\n# x = tf.placeholder(\"float\", [12288, 1])\n#\n# z3 = forward_propagation(x, params)\n# p = tf.argmax(z3)\n#\n# with tf.Session() as sess:\n# prediction = sess.run(p, feed_dict = {x: X})\n#\n# return prediction\n"
] |
[
[
"tensorflow.matmul",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.InteractiveSession",
"tensorflow.zeros",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets"
],
[
"tensorflow.convert_to_tensor",
"tensorflow.nn.relu",
"tensorflow.matmul",
"numpy.random.seed",
"numpy.eye",
"tensorflow.placeholder",
"numpy.random.permutation",
"tensorflow.Session",
"tensorflow.argmax",
"numpy.array"
]
] |
oasys-lnls-kit/OASYS1-LNLS-ShadowOui
|
[
"91d4baeb403289fdbd6e1ec555980415ce87eff3"
] |
[
"orangecontrib/shadow/lnls/widgets/utility/ow_flux_widget.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport time\nimport numpy\n\n\nfrom orangewidget import gui, widget\nfrom orangewidget.settings import Setting\nfrom oasys.widgets import gui as oasysgui\nfrom oasys.util.oasys_util import EmittingStream, TTYGrabber\nfrom oasys.widgets import congruence\nfrom silx.gui.plot.Colormap import Colormap\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QTextCursor\n\nimport orangecanvas.resources as resources\n\nfrom orangecontrib.shadow.lnls.widgets.gui.ow_lnls_shadow_widget import LNLSShadowWidget\n\nfrom orangecontrib.shadow.util.shadow_objects import ShadowBeam\n\nimport Shadow.ShadowTools as st\nfrom orangecontrib.shadow.util.shadow_util import ShadowCongruence\n\n\ntry:\n from scipy.interpolate import interp1d\n from scipy.integrate import simps\n from scipy.special import kv\n from scipy.integrate import quad\n import scipy.constants as codata\nexcept ImportError:\n raise ImportError('FLUX needs module scipy')\n \ntry: \n from oasys_srw.srwlib import SRWLMagFldU, SRWLMagFldH, SRWLPartBeam, SRWLStokes, srwl\n #from oasys_srw.srwlpy import CalcStokesUR\nexcept ImportError:\n raise ImportError('FLUX needs module srwlib and srwlpy')\n \nclass FluxWidget(LNLSShadowWidget):\n name = \"Flux\"\n description = \"Calculate flux and power at any position\"\n icon = \"icons/flux_icon.png\"\n authors = \"Artur C Pinto, Sergio A Lordano Luiz, Bernd C Meyer, Luca Rebuffi\"\n maintainer_email = \"[email protected]\"\n priority = 1\n category = \"Display Data Tools\"\n keywords = [\"data\", \"file\", \"load\", \"read\",\"flux\"]\n\n inputs = [(\"Input Beam\", ShadowBeam, \"set_beam\")]\n\n IMAGE_WIDTH = 380\n IMAGE_HEIGHT = 320\n \n want_main_area=1\n plot_canvas=None\n plot_canvas2=None\n plot_canvas3=None\n plot_canvas4=None \n input_beam=None\n \n retrive_source_parameters = Setting(False)\n\n source_type=Setting(0)\n storage_energy=Setting(3.0)\n current=Setting(0.1)\n mag_field=Setting(3.2)\n k_wiggler=Setting(12.0) \n n_periods=Setting(20)\n w_period=Setting(0.04)\n und_period=Setting(0.021)\n und_length=Setting(2.4)\n k_value=Setting(1.922968)\n c_En=Setting(10000.0)\n und_n=Setting(7)\n use_vert_acc = Setting(0)\n ebeam_vert_sigma = Setting(0.0)\n en_spread=Setting(0.085e-2)\n max_h=Setting(9)\n prec=Setting(1.0) \n \n sigma_x=Setting(19.1e-3)\n sigma_z=Setting(2.0e-3)\n div_x=Setting(13.0e-6)\n div_z=Setting(1.3e-6) \n lim_i_x=Setting(0)\n lim_f_x=Setting(0)\n lim_i_z=Setting(0)\n lim_f_z=Setting(0)\n \n number_of_bins=Setting(101) \n \n inten=Setting(0)\n nrays=Setting(0)\n grays=Setting(0)\n lrays=Setting(0)\n flux_total=Setting(0)\n power_total=Setting(0)\n keep_result=Setting(0)\n showflux=Setting(0)\n showpower=Setting(0)\n output_filename=Setting(\"output.dat\")\n fig_filename=Setting(\"output.png\")\n \n def __init__(self):\n super().__init__()\n \n ############### CONTROL AREA ##################### \n self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH+8)\n \n gui.checkBox(self.general_options_box, self, 'retrive_source_parameters', 'Get Source Parameters', callback=self.get_parameters_from_source)\n \n gui.button(self.controlArea, self, \"Refresh\", callback=self.plot_results, height=35,width=100)\n gui.separator(self.controlArea, 10)\n\n self.tabs_setting = oasysgui.tabWidget(self.controlArea) \n self.tabs_setting.setFixedHeight(550)\n \n\n ### Tabs inside control area ###\n tab_gen = oasysgui.createTabPage(self.tabs_setting, \"Source Settings\")\n tab_config = oasysgui.createTabPage(self.tabs_setting, \"Calculation Settings\" )\n\n ### Source Setting tab (tab_gen) ### \n screen_box = oasysgui.widgetBox(tab_gen, \"Source Description\", addSpace=True, orientation=\"vertical\", height=500)\n\n self.source_combo = gui.comboBox(screen_box, self, \"source_type\", label=\"Source Type\",\n items=[\"Bending Magnet\", \"Wiggler\",\"Linear Undulator\"],callback=self.set_Source, labelWidth=260,orientation=\"horizontal\")\n gui.separator(screen_box)\n\n self.kind_of_source_box_1 = oasysgui.widgetBox(screen_box, \"\", addSpace=False, orientation=\"vertical\", height=400) \n\n\n self.kind_of_source_box_1_1 = oasysgui.widgetBox(self.kind_of_source_box_1, \"\", addSpace=False, orientation=\"vertical\")\n \n self.le_st_energy = oasysgui.lineEdit(self.kind_of_source_box_1_1, self, \"storage_energy\", \"Energy [GeV]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_mag_f = oasysgui.lineEdit(self.kind_of_source_box_1_1, self, \"mag_field\", \"Magnet Field Value [T]\",\n labelWidth=260, callback=self.B_K_wiggler, valueType=float, orientation=\"horizontal\")\n\n ### Exclusive Wiggler parameters ### \n self.kind_of_source_box_1_2 = oasysgui.widgetBox(self.kind_of_source_box_1, \"\", addSpace=False, orientation=\"vertical\", height=100)\n\n self.le_K_w = oasysgui.lineEdit(self.kind_of_source_box_1_2, self, \"k_wiggler\", \"K-value\",\n labelWidth=260, callback=self.K_B_wiggler, valueType=float, orientation=\"horizontal\")\n \n self.le_np = oasysgui.lineEdit(self.kind_of_source_box_1_2, self, \"n_periods\", \"Number of Periods\",\n labelWidth=260, valueType=int, orientation=\"horizontal\")\n \n self.le_wp = oasysgui.lineEdit(self.kind_of_source_box_1_2, self, \"w_period\", \"Wiggler Period [m]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n\n self.kind_of_source_box_1_1b = oasysgui.widgetBox(self.kind_of_source_box_1, \"\", addSpace=False, orientation=\"vertical\")\n \n ### Vertical Acceptance options for Bending Magnet and Wiggler sources ###\n self.check_vert_acc = gui.comboBox(self.kind_of_source_box_1_1b, self, \"use_vert_acc\", label=\"Partial Vertical Acceptance\",\n items=[\"No\", \"Yes\"], callback=self.set_Source, labelWidth=260,orientation=\"horizontal\")\n \n self.kind_of_source_box_1_1c = oasysgui.widgetBox(self.kind_of_source_box_1, \"\", addSpace=False, orientation=\"vertical\")\n \n self.ebeam_divz = oasysgui.lineEdit(self.kind_of_source_box_1_1c, self, \"ebeam_vert_sigma\", \"e-beam Divergence RMS V [rad]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n\n ### Exclusive Linear Undulator parameters ### \n ### Machine Paremeters ###\n self.kind_of_source_box_1_3 = oasysgui.widgetBox(self.kind_of_source_box_1, \"\", addSpace=True, orientation=\"vertical\", height=400)\n\n self.le_st_energy_und = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"storage_energy\", \"Energy [GeV]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_es = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"en_spread\", \"Energy Spread\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_sx = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"sigma_x\", \"Size RMS H [mm]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_sz = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"sigma_z\", \"Size RMS V [mm]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_emx = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"div_x\", \"Divergence RMS H [rad]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_emz = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"div_z\", \"Divergence RMS V [rad]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n\n gui.separator(self.kind_of_source_box_1_3)\n gui.separator(self.kind_of_source_box_1_3)\n \n ### Undulator Paremeters ###\n self.le_up = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"und_period\", \"Undulator Period [m]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_ul = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"und_length\", \"Undulator Length [m]\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n self.le_ce = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"und_n\", \"Harmonic Number (n)\",\n labelWidth=260, valueType=int, orientation=\"horizontal\")\n \n self.le_ce = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"c_En\", \"Target Energy (En) [eV]\",\n labelWidth=260, callback=self.En_K_und, valueType=float, orientation=\"horizontal\")\n \n self.le_kv = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"k_value\", \"K-value\",\n labelWidth=260, callback=self.K_En_und, valueType=float, orientation=\"horizontal\") \n \n self.le_mh = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"max_h\", \"Maximum Harmonic to include\",\n labelWidth=260, valueType=int, orientation=\"horizontal\")\n \n self.le_pr = oasysgui.lineEdit(self.kind_of_source_box_1_3, self, \"prec\", \"Precision (>1)\",\n labelWidth=260, valueType=float, orientation=\"horizontal\")\n \n ### Call set_Source function ###\n self.set_Source()\n \n ### Calculation Settings tab (tab_config) ### \n config_box = oasysgui.widgetBox(tab_config, \"Define Flux Calculation Settings\", addSpace=True, orientation=\"vertical\", height=200)\n \n self.nb = oasysgui.lineEdit(config_box, self, \"number_of_bins\", \"Number of Bins\", \n labelWidth=220, valueType=int, controlWidth=100, orientation=\"horizontal\") \n \n self.mxa = oasysgui.lineEdit(config_box, self, \"lim_i_x\", \"Source Acceptance -X [rad] \", \n labelWidth=220, valueType=float, controlWidth=100, orientation=\"horizontal\") \n \n self.pxa = oasysgui.lineEdit(config_box, self, \"lim_f_x\", \"Source Acceptance +X [rad] \", \n labelWidth=220, valueType=float, controlWidth=100, orientation=\"horizontal\") \n \n self.mxz = oasysgui.lineEdit(config_box, self, \"lim_i_z\", \"Source Acceptance -Z [rad] \", \n labelWidth=220, valueType=float, controlWidth=100, orientation=\"horizontal\")\n \n self.pxz = oasysgui.lineEdit(config_box, self, \"lim_f_z\", \"Source Acceptance +Z [rad] \", \n labelWidth=220, valueType=float, controlWidth=100, orientation=\"horizontal\")\n \n print_box = oasysgui.widgetBox(tab_config, \"Save Data\", addSpace=True, orientation=\"vertical\", height=260)\n\n# self.flux_is_displayed = False\n# self.power_is_displayed = False \n gui.checkBox(print_box, self, \"showflux\", \"Show Flux\", callback=self.showFlux)\n gui.checkBox(print_box, self, \"showpower\", \"Show Power\", callback=self.showPower)\n \n self.select_file_box = oasysgui.widgetBox(print_box, \"\", addSpace=True, orientation=\"horizontal\")\n oasysgui.lineEdit(self.select_file_box, self, \"output_filename\", \"File Name\",\n labelWidth=120, valueType=str, orientation=\"horizontal\")\n gui.button(print_box, self, \"Save Data to txt\", callback=self.down_data, height=35,width=200)\n \n gui.separator(self.select_file_box)\n self.select_file_box2 = oasysgui.widgetBox(print_box, \"\", addSpace=True, orientation=\"horizontal\")\n oasysgui.lineEdit(self.select_file_box2, self, \"fig_filename\", \"Figure Name\",\n labelWidth=120, valueType=str, orientation=\"horizontal\")\n gui.button(print_box, self, \"Save Figure\", callback=self.down_fig, height=35, width=200)\n\n \n \n ############### MAIN AREA #####################\n \n self.tabs_flux = oasysgui.tabWidget(self.mainArea)\n self.tabs_flux.setFixedWidth(2*self.CONTROL_AREA_WIDTH) \n \n\n ### Tabs Inside the main area ###\n plotflux_tab = oasysgui.createTabPage(self.tabs_flux, \"Beamline Spectrum\") \n plotsource_tab = oasysgui.createTabPage(self.tabs_flux, \"Source Spectrum\")\n transm_tab = oasysgui.createTabPage(self.tabs_flux, \"Beamline Transmittance\")\n histo_tab = oasysgui.createTabPage(self.tabs_flux, \"Histogram\")\n vert_acc_tab = oasysgui.createTabPage(self.tabs_flux, \"Source Acceptance\")\n output_tab = oasysgui.createTabPage(self.tabs_flux, \"Ouput\") \n \n \n ### Area for Beamline Flux Plot, inside plotflux_tab ### \n output_box = oasysgui.widgetBox(plotflux_tab, \"\", addSpace=True, orientation=\"horizontal\",\n height=650, width=2.5*self.CONTROL_AREA_WIDTH) \n self.image_box = gui.widgetBox(output_box, \"Element Flux\", addSpace=True, orientation=\"vertical\")\n self.image_box.setFixedHeight(2*self.IMAGE_HEIGHT)\n self.image_box.setFixedWidth(1.75*self.IMAGE_WIDTH)\n self.plot_canvas = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=True)\n self.plot_canvas.setDefaultPlotLines(True)\n self.plot_canvas.setActiveCurveColor(color='blue')\n \n \n ### Area for Source Flux Plot, inside plotflux_tab ###\n self.image_box2 = gui.widgetBox(plotsource_tab, \"Source Flux\", addSpace=True, orientation=\"vertical\")\n self.image_box2.setFixedHeight(2*self.IMAGE_HEIGHT)\n self.image_box2.setFixedWidth(2*self.IMAGE_WIDTH)\n self.plot_canvas2 = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=True)\n self.plot_canvas2.setDefaultPlotLines(True)\n self.plot_canvas2.setActiveCurveColor(color='blue')\n \n ### Area for Transmission Plot, inside plotflux_tab ###\n self.image_box3 = gui.widgetBox(transm_tab, \"Transmission\", addSpace=True, orientation=\"vertical\")\n self.image_box3.setFixedHeight(2*self.IMAGE_HEIGHT)\n self.image_box3.setFixedWidth(2*self.IMAGE_WIDTH)\n self.plot_canvas3 = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=True)\n self.plot_canvas3.setDefaultPlotLines(True)\n self.plot_canvas3.setActiveCurveColor(color='blue')\n \n ### Area for Histograms Plot, inside plotflux_tab ###\n self.image_box4 = gui.widgetBox(histo_tab, \"Histogram\", addSpace=True, orientation=\"vertical\")\n self.image_box4.setFixedHeight(2*self.IMAGE_HEIGHT)\n self.image_box4.setFixedWidth(2*self.IMAGE_WIDTH)\n self.plot_canvas4 = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=True)\n self.plot_canvas4.setDefaultPlotLines(True)\n self.plot_canvas4.setActiveCurveColor(color='blue') \n \n ### Area for Source Acceptance Plot, inside plotflux_tab ###\n acc_box = oasysgui.widgetBox(vert_acc_tab, \"\", addSpace=True, orientation=\"vertical\",\n height=650, width=2.5*self.CONTROL_AREA_WIDTH)\n \n ### Colormap plot - source vertical acceptance ###\n self.image_box5 = gui.widgetBox(acc_box, \"Source Acceptance (Bending Magnet and Wiggler only)\", addSpace=True, orientation=\"horizontal\")\n self.image_box5.setFixedHeight(self.IMAGE_HEIGHT)\n self.image_box5.setFixedWidth(2*self.IMAGE_WIDTH)\n self.plot_canvas5 = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=False)\n self.colormap = Colormap(name='temperature')\n self.plot_canvas5.setDefaultColormap(self.colormap) \n \n ### Curve plot - vertical acceptance ###\n self.image_box6 = gui.widgetBox(acc_box, \"Vertical Acceptance\", addSpace=True, orientation=\"horizontal\")\n self.image_box6.setFixedHeight(self.IMAGE_HEIGHT)\n self.image_box6.setFixedWidth(2*self.IMAGE_WIDTH)\n self.plot_canvas6 = oasysgui.plotWindow(roi=False, control=False, position=True, logScale=False)\n self.plot_canvas6.setDefaultPlotLines(True)\n self.plot_canvas6.setActiveCurveColor(color='blue')\n \n \n #### Area for output info ############\n self.shadow_output = oasysgui.textArea()\n out_box = oasysgui.widgetBox(output_tab, \"System Output\", addSpace=True, orientation=\"horizontal\", height=600)\n out_box.layout().addWidget(self.shadow_output)\n \n \n ################### RAYS INFO ################## \n \n box_info = oasysgui.widgetBox(output_box, \"Info\", addSpace=True, orientation=\"vertical\",\n height=600, width=0.3*self.CONTROL_AREA_WIDTH)\n \n inten_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_i = QtWidgets.QLabel(\"Intensity\")\n self.label_i.setFixedWidth(100)\n inten_info_box.layout().addWidget(self.label_i)\n self.inten_v = gui.lineEdit(inten_info_box, self, \"inten\", \"\", tooltip=\" Intensity \", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.inten_v.setReadOnly(True)\n\n nrays_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_nr = QtWidgets.QLabel(\"Total Rays\")\n self.label_nr.setFixedWidth(100)\n nrays_info_box.layout().addWidget(self.label_nr)\n self.nrays_v = gui.lineEdit(nrays_info_box, self, \"nrays\", \"\", tooltip=\" Total Rays \", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.nrays_v.setReadOnly(True)\n\n grays_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_gr = QtWidgets.QLabel(\"Total Good Rays\")\n self.label_gr.setFixedWidth(100)\n grays_info_box.layout().addWidget(self.label_gr)\n self.grays_v = gui.lineEdit(grays_info_box, self, \"grays\", \"\", tooltip=\" Total Good Rays \", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.grays_v.setReadOnly(True)\n\n lrays_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_lr = QtWidgets.QLabel(\"Total Lost Rays\")\n self.label_lr.setFixedWidth(100)\n lrays_info_box.layout().addWidget(self.label_lr)\n self.lrays_v = gui.lineEdit(lrays_info_box, self, \"lrays\", \"\", tooltip=\" Total Lost Rays \", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.lrays_v.setReadOnly(True) \n \n flux_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_ft = QtWidgets.QLabel(\"Total Flux \\n [ph/s/100mA]\")\n self.label_ft.setFixedWidth(150)\n flux_info_box.layout().addWidget(self.label_ft)\n self.fluxT = gui.lineEdit(flux_info_box, self, \"flux_total\", \"\", tooltip=\" Total Flux\", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.fluxT.setReadOnly(True) \n \n power_info_box = gui.widgetBox(box_info, \"\", addSpace=True, orientation=\"vertical\")\n self.label_pt = QtWidgets.QLabel(\"Total Power \\n [W/100mA]\")\n self.label_pt.setFixedWidth(150)\n power_info_box.layout().addWidget(self.label_pt)\n self.powerT = gui.lineEdit(power_info_box, self, \"power_total\", \"\", tooltip=\" Total Power\", \n\t\t\t\t\t\t\t\tcontrolWidth=100, valueType=str, orientation=\"horizontal\")\n self.powerT.setReadOnly(True) \n \n ### Creates 'Run' function for Flux widget ###\n self.runaction = widget.OWAction(\"Run\", self)\n self.runaction.triggered.connect(self.plot_results)\n self.addAction(self.runaction)\n \n#################################################################################\n#################################################################################\n#################################################################################\n#################################################################################\n \n \n ### Show or hide source \n def set_Source(self):\n self.kind_of_source_box_1.setVisible(self.source_type<=2)\n self.kind_of_source_box_1_1.setVisible(self.source_type<2)\n self.kind_of_source_box_1_2.setVisible(self.source_type==1)\n self.kind_of_source_box_1_3.setVisible(self.source_type==2)\n self.kind_of_source_box_1_1b.setVisible(self.source_type<2)\n self.kind_of_source_box_1_1c.setVisible(self.use_vert_acc==1 and self.source_type<2)\n \n \n ### Calculates Wiggler Magnetic Filed from a given K-Value\n def K_B_wiggler(self):\n self.mag_field = round(self.k_wiggler/(93.364*self.w_period),6) \n \n ### Calculates Wiggler K-Vlaue from Magnetic Filed \n def B_K_wiggler(self): \n self.k_wiggler = round(93.364*self.w_period*self.mag_field, 6)\n \n ### Calculates undulator K-Value from a given Energy \n def En_K_und(self):\n self.k_value = round(numpy.sqrt(2*9.4963425587*self.storage_energy**2/(self.und_period*self.c_En/self.und_n)-2),6) \n \n ### Calculates undulator central Energy from a given K-Value\n def K_En_und(self): \n self.c_En = round(9.4963425587*self.und_n*self.storage_energy**2/((1+self.k_value**2/2.0)*self.und_period),6) \n \n \n ### Colect input beam ###\n def set_beam(self, beam):\n if ShadowCongruence.checkEmptyBeam(beam):\n if ShadowCongruence.checkGoodBeam(beam):\n if self.keep_result == 1 and not self.input_beam is None:\n self.input_beam = ShadowBeam.mergeBeams(self.input_beam, beam)\n \n else:\n self.input_beam = beam\n\n if self.is_automatic_run:\n self.plot_results()\n else:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n \"Data not displayable: No good rays, bad content, bad limits or axes\",\n QtWidgets.QMessageBox.Ok)\n \n\n ### Get Source Info - For Bending Magnet, Geometrical Source and Undulator Gaussian ###\n def get_parameters_from_source(self):\n if(hasattr(self, 'input_beam')):\n try:\n Source = self.input_beam.history[0]._shadow_source_end.src\n \n if not (Source.HDIV1==0 or Source.HDIV2==0 or Source.VDIV1==0 or Source.VDIV2==0):\n self.lim_i_x = Source.HDIV1\n self.lim_f_x = Source.HDIV2\n self.lim_i_z = Source.VDIV1\n self.lim_f_z = Source.VDIV2\n self.mxa.setDisabled(self.retrive_source_parameters)\n self.pxa.setDisabled(self.retrive_source_parameters)\n self.mxz.setDisabled(self.retrive_source_parameters)\n self.pxz.setDisabled(self.retrive_source_parameters)\n \n # Bending Magnet\n if self.source_type == 0:\n self.storage_energy = Source.BENER\n self.le_st_energy.setDisabled(self.retrive_source_parameters)\n self.mag_field = (1e9/codata.c)*self.storage_energy/Source.R_MAGNET\n self.le_mag_f.setDisabled(self.retrive_source_parameters)\n self.ebeam_vert_sigma = Source.EPSI_Z/Source.SIGMAZ\n self.ebeam_divz.setDisabled(self.retrive_source_parameters)\n \n # Wiggler - Beam does not propagate parameters\n elif self.source_type == 1:\n self.storage_energy = Source.BENER\n self.le_st_energy.setDisabled(self.retrive_source_parameters)\n# self.mag_field = \n# self.k_wiggler = \n# self.n_periods =\n# self.w_period =\n self.ebeam_vert_sigma = Source.EPSI_Z/Source.SIGMAZ\n self.ebeam_divz.setDisabled(self.retrive_source_parameters)\n \n #Geometrical Source or Undulator Gaussian\n elif self.source_type == 2:\n self.sigma_x = Source.SIGMAX\n self.le_sx.setDisabled(self.retrive_source_parameters)\n self.sigma_z = Source.SIGMAZ\n self.le_sz.setDisabled(self.retrive_source_parameters)\n self.div_x = Source.SIGDIX\n self.le_emx.setDisabled(self.retrive_source_parameters)\n self.div_z = Source.SIGDIZ\n self.le_emz.setDisabled(self.retrive_source_parameters)\n \n self.c_En = (Source.PH1 + Source.PH2)/2\n self.le_ce.setDisabled(self.retrive_source_parameters)\n self.En_K_und()\n self.le_kv.setDisabled(self.retrive_source_parameters)\n except:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n \"Unable to retrive source data.\",\n QtWidgets.QMessageBox.Ok)\n else:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n \"No input beam! Please run the previous widget.\",\n QtWidgets.QMessageBox.Ok)\n\n ### Call plot functions ###\n def plot_results(self):\n \n if self.retrive_source_parameters:\n self.get_parameters_from_source()\n\n try:\n plotted = False\n\n sys.stdout = EmittingStream(textWritten=self.writeStdOut)\n\n if ShadowCongruence.checkEmptyBeam(self.input_beam):\n self.number_of_bins = congruence.checkStrictlyPositiveNumber(self.number_of_bins, \"Number of Bins\")\n self.getConversion()\n self.plot_xy()\n\n plotted = True\n\n time.sleep(0.5) # prevents a misterious dead lock in the Orange cycle when refreshing the histogram\n\n return plotted\n except Exception as exception:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n str(exception),\n QtWidgets.QMessageBox.Ok)\n return False\n\n\n def plot_xy(self):\n beam_to_plot = self.input_beam._beam \n\n #Intesity Spectrum at Sample\n En = beam_to_plot.getshonecol(11, nolost=1)\n I = beam_to_plot.getshonecol(23, nolost=1)\n self.histoI = numpy.histogram(En, self.number_of_bins, weights=I)[0]\n self.En_coord = numpy.linspace(numpy.min(En), numpy.max(En),self.number_of_bins)\n \n #Collect intensity from Shadow Source\n En0 = beam_to_plot.getshonecol(11, nolost=0)\n I0 = numpy.ones(len(En0))\n \n #Creates source histogram from sample energy range\n I0_new = I0[numpy.logical_and(En0>=numpy.min(En),En0<=numpy.max(En))]\n En0_new = En0[numpy.logical_and(En0>=numpy.min(En),En0<=numpy.max(En))]\n self.histoI0 = numpy.histogram(En0_new, self.number_of_bins , weights=I0_new)[0] \n\n #Collect beam info \n info_beam = beam_to_plot.histo1(1, nolost=1)\n self.inten = (\"{:.2f}\".format(info_beam['intensity']))\n self.nrays = str(int(info_beam['nrays']))\n self.grays = str(int(info_beam['good_rays']))\n self.lrays = str(int(info_beam['nrays']-info_beam['good_rays'])) \n \n self.current = 0.1 #always normalized to 100 mA\n \n ##### Get source acceptance ##### \n if (self.lim_i_x == 0) or (self.lim_i_z == 0):\n \n QtWidgets.QMessageBox.critical(self, \"Error\",\n \"Set Source Acceptance in the Calculation Settings tab!!\",\n QtWidgets.QMessageBox.Ok)\n \n self.checkFields()\n self.hor_accep = (self.lim_f_x + self.lim_i_x)*1e3\n self.ver_accep = (self.lim_f_z + self.lim_i_z)*1e3\n \n sp = ' ' # spacing for identation \n self.print_date_i()\n print( sp + 'Source parameters:')\n \n #Select source type and calculate spectrum\n if self.source_type == 0:\n \n self.source_spec = self.BM_spectrum(E=self.storage_energy,I=self.current,B=self.mag_field,ph_energy=self.En_coord,hor_acc_mrad=self.hor_accep)\n print(sp+sp+'E = {0} GeV'.format(self.storage_energy) + '\\n' + sp+sp+'I = {0} A'.format(self.current) + '\\n' + sp+sp+'B = {0} T'.format(self.mag_field) + '\\n' )\n \n \n if self.source_type == 1:\n\n self.n_periods = self.n_periods\n self.source_spec = self.Wiggler_spectrum(self.storage_energy,self.current,self.mag_field,self.n_periods,self.En_coord,self.hor_accep)\n print(sp+sp+'E = {0} GeV'.format(self.storage_energy) + '\\n' + sp+sp+'I = {0} A'.format(self.current) + '\\n' + sp+sp+'B = {0} T'.format(self.mag_field) + '\\n' + sp+sp+'N periods = {0} '.format(self.n_periods) + '\\n' )\n\n if self.source_type == 2:\n e = 1.60217662e-19; m_e = 9.10938356e-31; pi = 3.141592654; c = 299792458;\n B = 2*pi*m_e*c*self.k_value/(e*self.und_period)\n mag_field=[self.und_period,self.und_length, 0, B, 0, 0, +1, +1]\n electron_beam=[self.sigma_x*1e-3, self.sigma_z*1e-3, self.div_x, self.div_z, self.storage_energy, self.en_spread, self.current]\n sampling_mesh=[10.0, round(-self.lim_i_x*10.0, 8), round(self.lim_f_x*10.0, 8), round(-self.lim_i_z*10.0, 8), round(self.lim_f_z*10.0, 8)] \n precision = [self.max_h, self.prec, self.prec]\n energy_grid=[self.En_coord[0],self.En_coord[-1], self.number_of_bins] \n\n print(sp+sp+\"Parameters passed to SRWLMagFldH():\")\n print(sp+sp+sp+\"_n=1, _h_or_v='v', _B={0}, _ph={1}, _s={2}, _a=1\".format(mag_field[3], mag_field[5], mag_field[7]))\n print(sp+sp+\"Parameters passed to SRWLMagFldH():\")\n print(sp+sp+sp+\"_n=1, _h_or_v='h', _B={0}, _ph={1}, _s={2}, _a=1\".format(mag_field[2], mag_field[4], mag_field[6]))\n print(sp+sp+\"Parameters passed to SRWLMagFldU():\")\n print(sp+sp+sp+\"_arHarm=[SRWLMagFldH_v, SRWLMagFldH_h], _per={0}, _nPer={1}\".format(mag_field[0], int(round(mag_field[1]/mag_field[0]))))\n print(sp+sp+\"Parameters passed to SRWLPartBeam():\")\n print(sp+sp+sp+\"_Iavg={0}, _gamma={1}/0.510998902e-03\".format(electron_beam[6], electron_beam[4]))\n print(sp+sp+sp+\"_arStatMom2=[0=({0})**2, 2=({1})**2, 3=({2})**2,\".format(electron_beam[0], electron_beam[2], electron_beam[1]))\n print(sp+sp+sp+\" 5=({0})**2, 10=({1})**2]\".format(electron_beam[3], electron_beam[5]))\n \n print(sp+sp+\"Precision array passed to CalcStokesUR():\")\n print(sp+sp+sp+\"[0=1, 1={0}, 2={1}, 3={2}, 4=1]\".format(precision[0], precision[1], precision[2]))\n print(sp+sp+\"Energy Grid array: \")\n print(sp+sp+sp, energy_grid)\n print(sp+sp+\"Radiation Sampling array: \")\n print(sp+sp+sp, sampling_mesh, '\\n')\n \n os.write(1, b'########### Running SRW Undulator Spectrum! ############### \\n')\n self.source_spec = self.srw_undulator_spectrum(mag_field, electron_beam, energy_grid, sampling_mesh, precision)\n os.write(1, b'########### Source Spectrum Done! ############### \\n')\n \n \n print(sp+'Source acceptance limits used for source spectrum calculation:')\n print(sp+sp+'-X = '+'{:.3e}'.format(-self.lim_i_x)+' rad')\n print(sp+sp+'+X = '+'{:.3e}'.format(self.lim_f_x)+' rad')\n print(sp+sp+'-Z = '+'{:.3e}'.format(-self.lim_i_z)+' rad')\n print(sp+sp+'+Z = '+'{:.3e}'.format(self.lim_f_z)+' rad' + '\\n')\n \n \n # Calculates Vertical acceptance for Bending Magnet and Wiggler sources\n self.vert_acc = numpy.ones((len(self.En_coord)))\n if(self.source_type<2 and self.use_vert_acc==1):\n \n self.acc_dict = self.BM_vertical_acc(E=self.storage_energy, B=self.mag_field, ph_energy=self.En_coord, \n div_limits=[-self.lim_i_z, self.lim_f_z], e_beam_vert_div=self.ebeam_vert_sigma)\n self.vert_acc = self.acc_dict['acceptance']\n\n \n #Flux Spectrum at Sample\n self.T1 = self.histoI/self.histoI0\n Flux_eV = self.source_spec*(1000.0/self.En_coord)\n Flux_sample = Flux_eV*self.T1*self.vert_acc\n Power_sample = Flux_eV*self.T1*self.vert_acc*self.En_coord*1.60217662e-19\n \n self.Flux = (simps(Flux_sample,x=self.En_coord)*(0.1/self.current)) #Integrate the Flux and normalize to 100 mA\n self.Power = (simps(Power_sample,x=self.En_coord)*(0.1/self.current))\n \n self.flux_total = (\"{:.2e}\".format(self.Flux))\n self.power_total = (\"{:.2e}\".format(self.Power))\n \n print(sp+'### Results ###')\n print(sp+sp+'Total Flux = {:.3e}'.format(self.Flux) + ' ph/s/100 mA')\n print(sp+sp+'Total Power = {:.3e}'.format(self.Power)+' W')\n print('\\n')\n \n #Plot Flux after element\n self.beamline_flux = self.source_spec*self.T1*self.vert_acc\n self.plot_canvas.clear()\n self.plot_canvas.setGraphYLabel(\"Flux [ph/s/100mA/0.1%bW]\")\n self.plot_canvas.setGraphXLabel(\"Energy [eV]\") \n self.plot_canvas.setGraphTitle('Beamline Spectrum')\n self.plot_canvas.addCurve(self.En_coord,self.beamline_flux,color='blue',symbol='.',linewidth=2)\n self.image_box.layout().addWidget(self.plot_canvas)\n# self.showflux = 0\n# self.showpower = 0\n self.showFlux()\n self.showPower()\n# \n #Plot Source Flux \n self.plot_canvas2.clear()\n self.plot_canvas2.setGraphYLabel(\"Flux [ph/s/100mA/0.1%bW]\")\n self.plot_canvas2.setGraphXLabel(\"Energy [eV]\")\n self.plot_canvas2.setGraphTitle('Source Spectrum') \n self.plot_canvas2.addCurve(self.En_coord,self.source_spec*self.vert_acc,color='blue',symbol='.',linewidth=2)\n self.image_box2.layout().addWidget(self.plot_canvas2)\n \n# \n #Plot Transmission \n self.plot_canvas3.clear()\n self.plot_canvas3.setGraphYLabel(\"Transmission\")\n self.plot_canvas3.setGraphXLabel(\"Energy [eV]\") \n self.plot_canvas3.setGraphTitle('Beamline Transmission')\n self.plot_canvas3.addCurve(self.En_coord,self.T1,color='blue',symbol='.',linewidth=2)\n self.image_box3.layout().addWidget(self.plot_canvas3)\n\n#\n #Plot Histogram \n self.plot_canvas4.clear()\n self.plot_canvas4.setGraphYLabel(\"Intensity\")\n self.plot_canvas4.setGraphXLabel(\"Energy [eV]\") \n self.plot_canvas4.setGraphTitle('Intensity Histograms')\n self.plot_canvas4.addCurve(self.En_coord,self.histoI0,legend='Source',color='green') \n self.plot_canvas4.addCurve(self.En_coord,self.histoI,legend='Element',color='red')\n self.image_box4.layout().addWidget(self.plot_canvas4)\n \n #Plot Acceptance\n if(self.source_type<2 and self.use_vert_acc==1):\n self.plot_canvas5.clear() \n self.plot_canvas5.addImage(self.acc_dict[\"PDF\"].transpose(),origin=(numpy.min(self.En_coord),1e3*numpy.min(self.acc_dict[\"Psi\"])),\n scale=((numpy.max(self.En_coord)-numpy.min(self.En_coord))/self.number_of_bins,\n 1e3*(numpy.max(self.acc_dict[\"Psi\"])-numpy.min(self.acc_dict[\"Psi\"]))/len(self.acc_dict[\"PDF\"][0,:])))\n self.plot_canvas5.addCurve(self.En_coord,1e3*self.acc_dict[\"rwhm\"],color='black',linewidth=1.5,legend='right')\n self.plot_canvas5.addCurve(self.En_coord,1e3*self.acc_dict[\"lwhm\"],color='black',linewidth=1.5,legend='left')\n self.plot_canvas5.addCurve([numpy.min(self.En_coord),numpy.max(self.En_coord)],\n [-self.lim_i_z*1e3,-self.lim_i_z*1e3],color='gray',linewidth=1.5,legend='i_z')\n self.plot_canvas5.addCurve([numpy.min(self.En_coord),numpy.max(self.En_coord)],\n [self.lim_f_z*1e3,self.lim_f_z*1e3],color='gray',linewidth=1.5,legend='f_z')\n \n pos = [0.12, 0.2, 0.82, 0.70]\n \n self.plot_canvas5._backend.ax.get_yaxis().get_major_formatter().set_useOffset(True)\n self.plot_canvas5._backend.ax.get_yaxis().get_major_formatter().set_scientific(True)\n self.plot_canvas5._backend.ax.set_position(pos)\n self.plot_canvas5._backend.ax2.set_position(pos)\n \n self.image_box5.layout().addWidget(self.plot_canvas5) \n self.plot_canvas5.setGraphXLabel(\"Energy [keV]\")\n self.plot_canvas5.setGraphYLabel(\"Vert. div. distribution [mrad]\")\n \n self.plot_canvas6.clear() \n self.plot_canvas6.addCurve(self.En_coord,self.acc_dict[\"acceptance\"],color='blue',symbol='.',linewidth=2) \n \n self.plot_canvas6._backend.ax.get_yaxis().get_major_formatter().set_useOffset(True)\n self.plot_canvas6._backend.ax.get_yaxis().get_major_formatter().set_scientific(True)\n self.plot_canvas6._backend.ax.set_position(pos)\n self.plot_canvas6._backend.ax2.set_position(pos)\n \n self.plot_canvas6.setGraphXLabel(\"Energy [keV]\")\n self.plot_canvas6.setGraphYLabel(\"Acceptance Factor\") \n self.image_box6.layout().addWidget(self.plot_canvas6)\n \n self.print_date_f() \n \n \n def writeStdOut(self, text): \n cursor = self.shadow_output.textCursor()\n cursor.movePosition(QTextCursor.End)\n cursor.insertText(text)\n self.shadow_output.setTextCursor(cursor)\n self.shadow_output.ensureCursorVisible()\n\n def retrace_beam(self, new_shadow_beam, dist):\n new_shadow_beam._beam.retrace(dist)\n\n def getConversion(self):\n if self.workspace_units_label == \"cm\":\n self.conv = 1e4\n if self.workspace_units_label == \"mm\":\n self.conv = 1e3\n if self.workspace_units_label == \"m\":\n self.conv = 1e6\n\n def checkFields(self): \n self.lim_i_x = congruence.checkPositiveNumber(self.lim_i_x , \"Source Acceptance -X [rad]\")\n self.lim_f_x = congruence.checkPositiveNumber(self.lim_f_x , \"Source Acceptance +X [rad]\")\n self.lim_i_z = congruence.checkPositiveNumber(self.lim_i_z , \"Source Acceptance -Z [rad]\")\n self.lim_f_z = congruence.checkPositiveNumber(self.lim_f_z , \"Source Acceptance +Z [rad]\")\n \n #########################################################################\n ############ SOURCE SPECTRUM CALCULATION FUNCTIONS ######################\n #########################################################################\n \n def srw_undulator_spectrum(self, mag_field=[], electron_beam=[], energy_grid=[], sampling_mesh=[], precision=[]):\n \"\"\"\n Calls SRW to calculate spectrum for a planar or elliptical undulator\\n\n :mag_field: list containing: [period [m], length [m], Bx [T], By [T], phase Bx = 0, phase By = 0, Symmetry Bx = +1, Symmetry By = -1]\n :electron_beam: list containing: [Sx [m], Sy [m], Sx' [rad], Sy'[rad], Energy [GeV], Energy Spread [dE/E], Current [A]]\n :energy_grid: list containing: [initial energy, final energy, number of energy points]\n :sampling_mesh: list containing: [observation plane distance from source [m], range -X [m], , range+X [m], range -Y [m], range +Y [m]]\n :precision: list containing: [h_max: maximum harmonic number to take into account, longitudinal precision factor, azimuthal precision factor (1 is standard, >1 is more accurate]\n \"\"\" \n \n #***********Undulator\n und = SRWLMagFldU([SRWLMagFldH(1, 'v', mag_field[3], mag_field[5], mag_field[7], 1), \n SRWLMagFldH(1, 'h', mag_field[2], mag_field[4], mag_field[6], 1)], \n mag_field[0], int(round(mag_field[1]/mag_field[0])))\n \n #***********Electron Beam\n eBeam = SRWLPartBeam()\n eBeam.Iavg = electron_beam[6] #average current [A]\n eBeam.partStatMom1.x = 0. #initial transverse positions [m]\n eBeam.partStatMom1.y = 0.\n eBeam.partStatMom1.z = -(mag_field[1]/2 + mag_field[0]*2) #initial longitudinal positions (set in the middle of undulator)\n eBeam.partStatMom1.xp = 0 #initial relative transverse velocities\n eBeam.partStatMom1.yp = 0\n eBeam.partStatMom1.gamma = electron_beam[4]/0.51099890221e-03 #relative energy\n sigEperE = electron_beam[5] #0.00089 #relative RMS energy spread\n sigX = electron_beam[0] #33.33e-06 #horizontal RMS size of e-beam [m]\n sigXp = electron_beam[2] #16.5e-06 #horizontal RMS angular divergence [rad]\n sigY = electron_beam[1] #2.912e-06 #vertical RMS size of e-beam [m]\n sigYp = electron_beam[3] #2.7472e-06 #vertical RMS angular divergence [rad]\n #2nd order stat. moments:\n eBeam.arStatMom2[0] = sigX*sigX #<(x-<x>)^2> \n eBeam.arStatMom2[1] = 0 #<(x-<x>)(x'-<x'>)>\n eBeam.arStatMom2[2] = sigXp*sigXp #<(x'-<x'>)^2> \n eBeam.arStatMom2[3] = sigY*sigY #<(y-<y>)^2>\n eBeam.arStatMom2[4] = 0 #<(y-<y>)(y'-<y'>)>\n eBeam.arStatMom2[5] = sigYp*sigYp #<(y'-<y'>)^2>\n eBeam.arStatMom2[10] = sigEperE*sigEperE #<(E-<E>)^2>/<E>^2\n \n #***********Precision Parameters\n arPrecF = [0]*5 #for spectral flux vs photon energy\n arPrecF[0] = 1 #initial UR harmonic to take into account\n arPrecF[1] = precision[0] #final UR harmonic to take into account\n arPrecF[2] = precision[1] #longitudinal integration precision parameter\n arPrecF[3] = precision[2] #azimuthal integration precision parameter\n arPrecF[4] = 1 #calculate flux (1) or flux per unit surface (2)\n \n #***********UR Stokes Parameters (mesh) for Spectral Flux\n stkF = SRWLStokes() #for spectral flux vs photon energy\n stkF.allocate(energy_grid[2], 1, 1) #numbers of points vs photon energy, horizontal and vertical positions\n stkF.mesh.zStart = sampling_mesh[0] #longitudinal position [m] at which UR has to be calculated\n stkF.mesh.eStart = energy_grid[0] #initial photon energy [eV]\n stkF.mesh.eFin = energy_grid[1] #final photon energy [eV]\n stkF.mesh.xStart = sampling_mesh[1] #initial horizontal position [m]\n stkF.mesh.xFin = sampling_mesh[2] #final horizontal position [m]\n stkF.mesh.yStart = sampling_mesh[3] #initial vertical position [m]\n stkF.mesh.yFin = sampling_mesh[4] #final vertical position [m]\n \n \n #**********************Calculation (SRWLIB function calls)\n #print(' Performing Spectral Flux (Stokes parameters) calculation ... ')\n srwl.CalcStokesUR(stkF, eBeam, und, arPrecF)\n #print('done')\n \n return numpy.array(stkF.arS[0:energy_grid[2]]) \n \n def BM_spectrum(self, E, I, B, ph_energy, hor_acc_mrad=1.0):\n \"\"\"\n Calculates the emitted spectrum of a Bending Magnet (vertically integrated) whithin a horizontal acceptance\\n\n Units: [ph/s/0.1%bw]\\n\n :E: Storage Ring energy [GeV]\n :I: Storage Ring current [A]\n :B: Magnetic Field value [T] \n :ph_energy: Array of Photon Energies [eV]\n :hor_acc_mrad: Horizontal acceptance [mrad]\n \"\"\"\n \n def bessel_f(y):\n return kv(5.0/3.0, y) \n \n e_c = 665*(E**2)*B # eV\n y = ph_energy/e_c\n int_K53 = numpy.zeros((len(y)))\n for i in range(len(y)):\n int_K53[i] = quad(lambda x: kv(5.0/3.0, x), y[i], numpy.inf)[0]\n G1_y = y*int_K53\n BM_Flux = (2.457*1e13)*E*I*G1_y*hor_acc_mrad\n \n return BM_Flux\n \n def Wiggler_spectrum(self, E, I, B, N_periods, ph_energy, hor_acc_mrad=1.0):\n \"\"\"\n Calculates the emitted spectrum of a Wiggler (vertically integrated) whithin a horizontal acceptance\\n\n Units: [ph/s/0.1%bw]\\n\n :E: Storage Ring energy [GeV]\n :I: Storage Ring current [A]\n :B: Magnetic Field value [T] \n :N_periods: Number of Periods\n :ph_energy: Array of Photon Energies [eV]\n :hor_acc_mrad: Horizontal acceptance [mrad]\n \"\"\"\n \n def bessel_f(y):\n return kv(5.0/3.0, y) \n \n e_c = 665*(E**2)*B # eV\n y = ph_energy/e_c\n int_K53 = numpy.zeros((len(y)))\n for i in range(len(y)):\n int_K53[i] = quad(lambda x: kv(5.0/3.0, x), y[i], numpy.inf)[0]\n G1_y = y*int_K53\n W_Flux = (2.457*1e13)*E*I*G1_y*hor_acc_mrad*(2*N_periods)\n \n return W_Flux \n \n def print_date_i(self):\n print('\\n'+'EXECUTION BEGAN AT: ', end='')\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), '\\n')\n \n def print_date_f(self):\n print('\\n'+'EXECUTION FINISHED AT: ', end='')\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), '\\n')\n \n def showFlux(self):\n \n if(self.showflux == 1):\n \n plot_ftext = 'Total Flux' + '\\n ' + self.flux_total + '\\n ' + 'ph/s/100mA' \n eRange = numpy.max(self.En_coord) - numpy.min(self.En_coord)\n fluxRange = numpy.max(self.beamline_flux) - numpy.min(self.beamline_flux) \n self.plot_canvas.remove(legend='fMarker', kind='marker')\n self.plot_canvas.addMarker(x=numpy.min(self.En_coord)+eRange*0.02, y=numpy.min(self.beamline_flux)+fluxRange*0.98, legend='fMarker', text=plot_ftext, color='black', selectable=True, draggable=True, symbol='none')\n \n if(self.showflux == 0):\n self.plot_canvas.remove(legend='fMarker', kind='marker')\n \n def showPower(self):\n\n if(self.showpower == 1): \n \n plot_ptext = 'Total Power' + '\\n ' + self.power_total + '\\n ' + 'W/100mA'\n eRange = numpy.max(self.En_coord) - numpy.min(self.En_coord)\n fluxRange = numpy.max(self.beamline_flux) - numpy.min(self.beamline_flux) \n self.plot_canvas.remove(legend='pMarker', kind='marker')\n self.plot_canvas.addMarker(x=numpy.min(self.En_coord)+eRange*0.02, y=numpy.min(self.beamline_flux)+fluxRange*0.85, legend='pMarker', text=plot_ptext, color='black', selectable=True, draggable=True, symbol='none')\n \n if(self.showpower == 0):\n self.plot_canvas.remove(legend='pMarker', kind='marker')\n\n \n def down_data(self):\n numpy.savetxt(self.output_filename, \n numpy.array([self.En_coord,\n self.histoI0,\n self.histoI,\n self.T1,\n self.source_spec*self.vert_acc,\n self.T1*self.source_spec*self.vert_acc]).T, \n fmt='%.8e',\n header='Total Flux [ph/s/100mA] \\n' + self.flux_total + '\\n' + 'Total Power [W/100mA] \\n' + self.power_total + '\\n' +\n 'Energy [eV] \\\n Source Histogram \\\n Beamline Histogram \\\n Transmission \\\n Source Spectrum [ph/s/100mA/0.1%bW] \\\n Beamline Spectrum [ph/s/100mA/0.1%bW]') \n def down_fig(self):\n \n self.plot_canvas.saveGraph(self.fig_filename, fileFormat='png', dpi=400)\n \n def BM_vertical_acc(self, E=3.0, B=3.2, ph_energy=1915.2, div_limits=[-1.0e-3, 1.0e-3], e_beam_vert_div=0.0, plot=False):\n\n \"\"\"\n Calculates the vertical angular flux probability density function (pdf) for \\\n a Bending Magnet or Wiggler and compares it to divergence limits to calculate \\\n the relative vertcal acceptance.\\n\n Return: Dictionary containing vertical angular distribution, fwhm and acceptance factor (energy-dependent) \\n\n :E: Storage Ring energy [GeV]\n :B: Magnetic Field value [T] \n :ph_energy: Photon Energy - single value or array - [eV]\n :div_limits: Divergence limits array for which acceptance must be calculated [rad]\n :e_beam_vert_div: electron beam vertical divergence sigma [rad]. Not taken into account if equal to None.\n :plot: boolean: True or False if you want the distribution to be shown.\n \"\"\"\n import numpy\n from scipy.special import kv\n from scipy.integrate import simps\n \n def gaussian_pdf(x, x0, sigma): # gaussian probability density function (PDF)\n return (1/(numpy.sqrt(2*numpy.pi*sigma**2)))*numpy.exp(-(x-x0)**2/(2*sigma**2))\n \n def calc_vert_dist(e_relative):\n G = (e_relative/2.0)*(gamma_psi**(1.5)) \n K13_G = kv(1.0/3.0, G)\n K23_G = kv(2.0/3.0, G)\n \n dN_dOmega = (1.33e13)*(E**2)*I*(e_relative**2)*(gamma_psi**2)\n dN_dOmega *= ( (K23_G**2) + (((gamma**2) * (psi**2))/(gamma_psi))*(K13_G**2) ) \n \n return dN_dOmega\n \n if(not(hasattr(ph_energy, \"__len__\"))): # for single energies\n ph_energy = numpy.array([ph_energy])\n \n I = 0.1 # [A] -> result independent\n gamma = E/0.51099890221e-03\n e_c = 665*(E**2)*B # [eV] \n energy_relative = ph_energy/e_c\n \n # calculate graussian approximation to define psi mesh\n int_K53 = quad(lambda x: kv(5.0/3.0, x), energy_relative[0], numpy.inf)[0]\n K23 = kv(2.0/3.0, energy_relative[0]/2)\n vert_angle_sigma = numpy.sqrt(2*numpy.pi/3)/(gamma*energy_relative[0])*int_K53/((K23)**2)\n if(e_beam_vert_div > 0.0):\n vert_angle_sigma = numpy.sqrt(vert_angle_sigma**2 + e_beam_vert_div**2) # calculates gaussian PDF of the e-beam vertical divergence\n \n psi = numpy.linspace(-vert_angle_sigma*2, vert_angle_sigma*2, 1000) # vertical angle array\n gamma_psi = 1 + (gamma**2) * (psi**2) # factor dependent on gamma and psi\n psi_minus = numpy.abs(psi - div_limits[0]).argmin() # first psi limit index\n psi_plus = numpy.abs(psi - div_limits[1]).argmin() # second psi limit index\n \n vert_pdf = numpy.zeros((len(ph_energy), len(psi)))\n vert_acceptance = numpy.zeros((len(ph_energy)))\n lwhm = numpy.zeros((len(ph_energy)))\n rwhm = numpy.zeros((len(ph_energy)))\n fwhm = numpy.zeros((len(ph_energy)))\n \n if(e_beam_vert_div > 0.0):\n e_beam_pdf = gaussian_pdf(psi, 0, e_beam_vert_div) # calculates gaussian PDF of the e-beam vertical divergence\n \n for i in range(len(ph_energy)):\n vert_pdf[i] = calc_vert_dist(energy_relative[i]) \n vert_pdf[i] /= simps(y=vert_pdf[i], x=psi)\n \n if(e_beam_vert_div > 0.0): # convolves radiation and e-beam angular distributions\n \n conv_dist = numpy.convolve(vert_pdf[i], e_beam_pdf, mode='same')\n conv_dist_norm = simps(y=conv_dist, x=psi)\n conv_pdf = conv_dist / conv_dist_norm # convolved PDF\n vert_pdf[i] = conv_pdf\n \n vert_acceptance[i] = simps(vert_pdf[i][psi_minus:psi_plus+1], x=psi[psi_minus:psi_plus+1])\n # calculates FWHM \n peak = numpy.max(vert_pdf[i])\n peak_idx = numpy.abs(vert_pdf[i]-peak).argmin()\n lwhm[i] = psi[numpy.abs(vert_pdf[i][:peak_idx] - peak/2).argmin()]\n rwhm[i] = psi[numpy.abs(vert_pdf[i][peak_idx:] - peak/2).argmin() + peak_idx]\n fwhm[i] = rwhm[i] - lwhm[i]\n \n \n if(plot==True and len(vert_pdf)==1):\n from matplotlib import pyplot as plt\n plt.figure()\n plt.plot(psi*1e3, vert_pdf[0], 'C0.-')\n plt.ylabel('$Flux \\ PDF$')\n plt.xlabel('$\\psi \\ [mrad]$')\n plt.ylim(0, numpy.max(vert_pdf)*1.1)\n plt.fill_between(psi*1e3, vert_pdf[i], where=numpy.logical_and(psi>=psi[psi_minus], psi<=psi[psi_plus]))\n plt.axvline(x=psi[psi_minus]*1e3)\n plt.axvline(x=psi[psi_plus]*1e3)\n plt.plot(lwhm*1e3, peak/2, 'C1+', markersize=12)\n plt.plot(rwhm*1e3, peak/2, 'C1+', markersize=12)\n plt.show()\n \n if(plot==True and len(vert_pdf)>1):\n from matplotlib import pyplot as plt\n plt.figure()\n plt.imshow(vert_pdf.transpose(), extent=[ph_energy[0], ph_energy[-1], psi[0]*1e3, psi[-1]*1e3], aspect='auto')\n plt.xlabel('$Energy \\ [eV]$')\n plt.ylabel('$\\psi \\ [mrad]$')\n plt.plot(ph_energy, lwhm*1e3, '--', color='white', linewidth=1.0, alpha=0.4)\n plt.plot(ph_energy, rwhm*1e3, '--', color='white', linewidth=1.0, alpha=0.4)\n plt.axhline(y=div_limits[0]*1e3, color='gray', alpha=0.5)\n plt.axhline(y=div_limits[1]*1e3, color='gray', alpha=0.5)\n plt.minorticks_on()\n plt.ylim([-vert_angle_sigma*1.75e3, vert_angle_sigma*1.75e3])\n plt.show()\n \n output = {\"Psi\": psi,\n \"PDF\": vert_pdf,\n \"acceptance\": vert_acceptance,\n \"lwhm\": lwhm,\n \"rwhm\": rwhm,\n \"fwhm\": fwhm}\n \n return output\n\n \n \n \n"
] |
[
[
"numpy.sqrt",
"numpy.linspace",
"matplotlib.pyplot.minorticks_on",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.exp",
"numpy.histogram",
"matplotlib.pyplot.figure",
"numpy.min",
"matplotlib.pyplot.ylim",
"scipy.integrate.simps",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.logical_and",
"matplotlib.pyplot.ylabel",
"numpy.convolve",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.axhline",
"numpy.abs",
"matplotlib.pyplot.xlabel",
"scipy.special.kv"
]
] |
uridabomb/AzureChestXRay
|
[
"2e1a6dde1b701f259a6299166a7dd6fecda81164"
] |
[
"AzureChestXRay_AMLWB/Code/src/azure_chestxray_cam.py"
] |
[
"### Copyright (C) Microsoft Corporation. \n\nimport keras.backend as K\nimport sys, os, io\nimport numpy as np\nimport cv2\n\nimport matplotlib\nmatplotlib.use('agg')\n\npaths_to_append = [os.path.join(os.getcwd(), os.path.join(*(['Code', 'src'])))]\ndef add_path_to_sys_path(path_to_append):\n if not (any(path_to_append in paths for paths in sys.path)):\n sys.path.append(path_to_append)\n[add_path_to_sys_path(crt_path) for crt_path in paths_to_append]\n\nimport azure_chestxray_utils\n\n\ndef get_score_and_cam_picture(cv2_input_image, DenseNetImageNet121_model):\n# based on https://github.com/jacobgil/keras-cam/blob/master/cam.py\n width, height, _ = cv2_input_image.shape\n class_weights = DenseNetImageNet121_model.layers[-1].get_weights()[0]\n final_conv_layer = DenseNetImageNet121_model.layers[-3]\n get_output = K.function([DenseNetImageNet121_model.layers[0].input], \n [final_conv_layer.output, \\\n DenseNetImageNet121_model.layers[-1].output])\n [conv_outputs, prediction] = get_output([cv2_input_image[None,:,:,:]])\n conv_outputs = conv_outputs[0, :, :, :]\n prediction = prediction[0,:]\n \n #Create the class activation map.\n predicted_disease = np.argmax(prediction)\n cam = np.zeros(dtype = np.float32, shape = conv_outputs.shape[:2])\n for i, w in enumerate(class_weights[:, predicted_disease]):\n cam += w * conv_outputs[:, :, i]\n \n return prediction, cam, predicted_disease\n\n\ndef process_cam_image(crt_cam_image, xray_image, crt_alpha = .5):\n im_width, im_height, _ = xray_image.shape\n crt_cam_image = cv2.resize(crt_cam_image, (im_width, im_height), \\\n interpolation=cv2.INTER_CUBIC)\n \n# do some gamma enhancement, e is too much\n crt_cam_image = np.power(1.1, crt_cam_image)\n crt_cam_image = azure_chestxray_utils.normalize_nd_array(crt_cam_image)\n # crt_cam_image[np.where(crt_cam_image < 0.5)] = 0 \n crt_cam_image = 255*crt_cam_image\n\n # make cam an rgb image\n empty_image_channel = np.zeros(dtype = np.float32, shape = crt_cam_image.shape[:2])\n crt_cam_image = cv2.merge((crt_cam_image,empty_image_channel,empty_image_channel))\n \n blended_image = cv2.addWeighted(xray_image.astype('uint8'),crt_alpha,\\\n crt_cam_image.astype('uint8'),(1-crt_alpha),0)\n return(blended_image)\n\ndef plot_cam_results(crt_blended_image, crt_cam_image, crt_xray_image, map_caption):\n import matplotlib.pyplot as plt\n\n fig = plt.figure(figsize = (15,7))\n\n ax1 = fig.add_subplot(2, 3, 1)\n ax1.imshow(crt_xray_image, cmap = 'gray', interpolation = 'bicubic')\n ax1.set_title('Orig X Ray')\n plt.axis('off')\n\n ax2 = fig.add_subplot(2,3, 2)\n cam_plot = ax2.imshow(crt_cam_image, cmap=plt.get_cmap('OrRd'), interpolation = 'bicubic')\n plt.colorbar(cam_plot, ax=ax2)\n ax2.set_title('Activation Map')\n plt.axis('off')\n\n ax3 = fig.add_subplot(2,3, 3)\n blended_plot = ax3.imshow(crt_blended_image, interpolation = 'bicubic')\n plt.colorbar(cam_plot, ax=ax3)\n ax3.set_title(map_caption)\n plt.axis('off')\n \n # serialize blended image plot padded in the x/y-direction\n image_as_BytesIO = io.BytesIO()\n x_direction_pad = 1.05;y_direction_pad=1.2\n extent = ax3.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n fig.savefig(image_as_BytesIO, \n bbox_inches=extent.expanded(x_direction_pad, \n y_direction_pad),\n format='png')\n image_as_BytesIO.seek(0)\n return(image_as_BytesIO)\n \n\n \ndef process_xray_image(crt_xray_image, DenseNetImageNet121_model):\n\n# print(crt_xray_image.shape)\n crt_xray_image = azure_chestxray_utils.normalize_nd_array(crt_xray_image)\n crt_xray_image = 255*crt_xray_image\n crt_xray_image=crt_xray_image.astype('uint8')\n\n crt_predictions, crt_cam_image, predicted_disease_index = \\\n get_score_and_cam_picture(crt_xray_image, \n DenseNetImageNet121_model)\n \n prj_consts = azure_chestxray_utils.chestxray_consts()\n likely_disease=prj_consts.DISEASE_list[predicted_disease_index]\n likely_disease_prob = 100*crt_predictions[predicted_disease_index]\n likely_disease_prob_ratio=100*crt_predictions[predicted_disease_index]/sum(crt_predictions)\n print('predictions: ', crt_predictions)\n print('likely disease: ', likely_disease)\n print('likely disease prob: ', likely_disease_prob)\n print('likely disease prob ratio: ', likely_disease_prob_ratio)\n \n crt_blended_image = process_cam_image(crt_cam_image, crt_xray_image)\n plot_cam_results(crt_blended_image, crt_cam_image, crt_xray_image,\n str(likely_disease)+ ' ' +\n \"{0:.1f}\".format(likely_disease_prob)+ '% (weight ' +\n \"{0:.1f}\".format(likely_disease_prob_ratio)+ '%)')\n\ndef process_nih_data(nih_data_files, NIH_data_dir, DenseNetImageNet121_model):\n for crt_image in nih_data_files:\n # print(crt_image)\n prj_consts = azure_chestxray_utils.chestxray_consts()\n\n crt_xray_image = cv2.imread(os.path.join(NIH_data_dir,crt_image))\n crt_xray_image = cv2.resize(crt_xray_image, \n (prj_consts.CHESTXRAY_MODEL_EXPECTED_IMAGE_HEIGHT, \n prj_consts.CHESTXRAY_MODEL_EXPECTED_IMAGE_WIDTH)) \\\n .astype(np.float32)\n\n process_xray_image(crt_xray_image, DenseNetImageNet121_model ) \n \nif __name__==\"__main__\":\n #FIXME\n # add example/test code here\n\n\n\n NIH_annotated_Cardiomegaly = ['00005066_030.png']\n data_dir = ''\n cv2_image = cv2.imread(os.path.join(data_dir,NIH_annotated_Cardiomegaly[0]))\n\n print_image_stats_by_channel(cv2_image)\n cv2_image = normalize_nd_array(cv2_image)\n cv2_image = 255*cv2_image\n cv2_image=cv2_image.astype('uint8')\n print_image_stats_by_channel(cv2_image)\n\n predictions, cam_image, predicted_disease_index = get_score_and_cam_picture(cv2_image, model)\n print(predictions)\n prj_consts = azure_chestxray_utils.chestxray_consts()\n print(prj_consts.DISEASE_list[predicted_disease_index])\n print('likely disease: ', prj_consts.DISEASE_list[predicted_disease_index])\n print('likely disease prob ratio: ', \\\n predictions[predicted_disease_index]/sum(predictions))\n blended_image = process_cam_image(cam_image, cv2_image)\n plot_cam_results(blended_image, cam_image, cv2_image, \\\n prj_consts.DISEASE_list[predicted_disease_index]) "
] |
[
[
"numpy.power",
"matplotlib.use",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.colorbar",
"numpy.argmax",
"matplotlib.pyplot.axis",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
jecker7/BioPlate
|
[
"2339cca2187af522cba9b1bbc8791bdbf8e0a6bd"
] |
[
"tests/test_inserts.py"
] |
[
"import unittest\nimport contextlib\nimport numpy as np\nimport BioPlate.utilitis as bpu\n\nfrom pathlib import Path, PurePath\nfrom BioPlate import BioPlate\nfrom BioPlate.database.plate_db import PlateDB\nfrom BioPlate.database.plate_historic_db import PlateHist\nfrom string import ascii_uppercase\nfrom tabulate import tabulate\n\n\nclass TestPlate(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n \"\"\"\n This function is run one time at the beginning of tests\n :return:\n \"\"\"\n cls.pdb = PlateDB(db_name=\"test_plate.db\")\n cls.pdb.add_plate(\n numWell=96,\n numColumns=12,\n numRows=8,\n surfWell=0.29,\n maxVolWell=200,\n workVolWell=200,\n refURL=\"https://csmedia2.corning.com/LifeSciences/Media/pdf/cc_surface_areas.pdf\",\n )\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"\n This function is run one time at the end of tests\n :return:\n \"\"\"\n with contextlib.suppress(FileNotFoundError):\n Path(\n PurePath(\n Path(__file__).parent.parent,\n \"BioPlate/database/DBFiles\",\n \"test_plate.db\",\n )\n ).unlink()\n Path(\n PurePath(\n Path(__file__).parent.parent,\n \"BioPlate/database/DBFiles\",\n \"test_plate_historic.db\",\n )\n ).unlink()\n Path(\n PurePath(\n Path(__file__).parent.parent,\n \"BioPlate/database/DBFiles\",\n \"plate_historic.db\",\n )\n ).unlink()\n\n def setUp(self):\n \"\"\"\n This function is run every time at the beginning of each test\n :return:\n \"\"\"\n self.Ins = BioPlate({\"id\": 1}, db_name=\"test_plate.db\", inserts=True)\n self.Inserts = BioPlate(4, 3, inserts=True)\n self.Value = {\"A1\": \"Control\", \"C[2,10]\": \"Test1\", \"11[B,G]\": \"Test2\"}\n\n def tearDown(self):\n \"\"\"\n This function is run every time at the end of each test\n :return:\n \"\"\"\n try:\n Path(PurePath(\"test_ins_to_excel.xlsx\")).unlink()\n except FileNotFoundError:\n pass\n \n \n def test_Plate_init(self):\n np.testing.assert_array_equal(\n self.Inserts,\n np.array(\n [\n [\n [\" \", \"1\", \"2\", \"3\", \"4\"],\n [\"A\", \"\", \"\", \"\", \"\"],\n [\"B\", \"\", \"\", \"\", \"\"],\n [\"C\", \"\", \"\", \"\", \"\"],\n ],\n [\n [\" \", \"1\", \"2\", \"3\", \"4\"],\n [\"A\", \"\", \"\", \"\", \"\"],\n [\"B\", \"\", \"\", \"\", \"\"],\n [\"C\", \"\", \"\", \"\", \"\"],\n ],\n ],\n dtype=\"U40\",\n ),\n )\n \n def test_add_values(self):\n np.testing.assert_array_equal(\n self.Inserts.top.set(\"B3\", \"inserts\"), self.Inserts.top\n )\n np.testing.assert_array_equal(\n self.Inserts.bot.set(\"B3\", \"inserts_bot\"), self.Inserts.bot\n )\n self.Inserts[\"top\", \"A2\"] = \"Bob\"\n self.assertEqual(self.Inserts[0, \"A2\"], \"Bob\")\n self.Inserts[\"bot\", \"A2\"] = \"Bibi\"\n self.assertEqual(self.Inserts[1, \"A2\"], \"Bibi\")\n\n def test_add_value_row(self):\n np.testing.assert_array_equal(\n self.Inserts.top.set(\"B[1-3]\", \"inserts\"), self.Inserts.top\n )\n np.testing.assert_array_equal(\n self.Inserts.bot.set(\"A\", \"inserts\"), self.Inserts.bot\n )\n np.testing.assert_array_equal(\n self.Inserts.bot.set(\"B\", \"inserts2\"), self.Inserts.bot\n )\n np.testing.assert_array_equal(\n self.Inserts.bot.set(\"B[1,6]\", 18), self.Inserts.bot) \n \n def test_add_value_column(self):\n np.testing.assert_array_equal(\n self.Inserts.top.set(\"2[A,C]\", \"inserts\"), self.Inserts.top\n )\n np.testing.assert_array_equal(\n self.Inserts.top.set(\"B\", \"inserts2\"), self.Inserts.top\n )\n\n def test_set(self):\n with self.assertRaises(IndexError):\n self.Inserts.top.set(self.Value)\n with self.assertRaises(ValueError):\n self.Inserts.bot.set(\"A[2-4]\", [\"test1\", \"test2\", \"test3\", \"test4\"])\n np.testing.assert_array_equal(\n self.Inserts.top.set(\"A-C[1-3]\", [\"Test1\", \"Test2\", \"Test3\"]),\n self.Inserts.top,\n )\n Ns = BioPlate(12, 8, inserts=True)\n Ns[\"bot\", \"4-7[A-D]\"] = [\"boom1\", \"boom2\", \"boom3\", \"boom4\"]\n np.testing.assert_array_equal(Ns[\"bot\", \"4-7[A-D]\"], np.array([[\"boom1\", \"boom2\", \"boom3\", \"boom4\"],\n [\"boom1\", \"boom2\", \"boom3\", \"boom4\"],\n [\"boom1\", \"boom2\", \"boom3\", \"boom4\"],\n [\"boom1\", \"boom2\", \"boom3\", \"boom4\"]])) \n\n def test_table(self):\n v = {\n \"A[2,8]\": \"VC\",\n \"H[2,8]\": \"MS\",\n \"1-4[B,G]\": [\"MLR\", \"NT\", \"1.1\", \"1.2\"],\n \"E-G[8,10]\": [\"Val1\", \"Val2\", \"Val3\"],\n }\n np.testing.assert_array_equal(self.Ins.top.set(v), self.Ins.top)\n self.assertEqual(self.Ins.top.table(), tabulate(self.Ins.top, headers=\"firstrow\")) \n def test_save(self):\n self.assertEqual(\n self.Inserts.save(\"test save3\", db_hist_name=\"test_plate_historic.db\"),\n \"Inserts test save3 with 12 wells was successfully added to database test_plate_historic.db\",\n )\n phi = PlateHist(db_name=\"test_plate_historic.db\")\n np.testing.assert_array_equal(\n phi.get_one_hplate(1, key=\"id\").plate, self.Inserts\n )\n def test_iteration(self):\n ValIn = {\"A1\": \"Control\", \"C[2,4]\": \"Test1\"}\n self.Inserts.top.set(ValIn)\n self.assertEqual(\n list(self.Inserts.iterate()),\n [\n (\"A1\", \"Control\", \"\"),\n (\"B1\", \"\", \"\"),\n (\"C1\", \"\", \"\"),\n (\"A2\", \"\", \"\"),\n (\"B2\", \"\", \"\"),\n (\"C2\", \"Test1\", \"\"),\n (\"A3\", \"\", \"\"),\n (\"B3\", \"\", \"\"),\n (\"C3\", \"Test1\", \"\"),\n (\"A4\", \"\", \"\"),\n (\"B4\", \"\", \"\"),\n (\"C4\", \"Test1\", \"\"),\n ],\n )\n \n def test_count(self):\n ValIn = {\"A1\": \"Control\", \"C[2,4]\": \"Test1\"}\n self.Inserts.top.set(ValIn)\n self.assertEqual(\n self.Inserts.count(),\n {\"top\": {\"Control\": 1, \"Test1\": 3, \"\": 8}, \"bot\": {\"\": 12}},\n )\n \n def test_get_value(self):\n self.Inserts.top.set(\"C2\", \"Test1\")\n np.testing.assert_array_equal( self.Inserts.top.get(\"C2\"), \"Test1\")\n \n def test_get_values(self):\n self.Inserts.bot.set(\"A[1-3]\", [\"bob1\", \"bob2\", \"bob3\"])\n self.Inserts.bot[\"B[1-3]\"] = [\"bibi1\", \"bibi2\", \"bibi3\"]\n self.assertEqual(\n self.Inserts.bot.get(\"A1\", \"2[A-B]\"), [\"bob1\", [\"bob2\", \"bibi2\"]]\n )\n \n def test_name(self):\n self.assertEqual(self.Inserts.name, \"Inserts\")\n self.assertEqual(self.Ins.name, \"Inserts\")\n \n def test_to_excel(self):\n self.Inserts.to_excel(\"test_ins_to_excel.xlsx\")\n exist_ins = Path(\"test_ins_to_excel.xlsx\").exists()\n self.assertTrue(exist_ins)\n \n def test_merge(self):\n ins = BioPlate(12, 8, inserts=True)\n ins.top.set(\"2-5[A-C]\", [\"test\", \"tes\", \"te\", \"t\"])\n self.assertEqual(ins.top.get(\"A2\"), \"test\")\n ins.top.set(\"2-3[A-C]\", [\"_1\", \"_2\"], merge=True)\n ins.top.set(\"A-C[4-5]\", [\"_3\", \"_4\", \"_5\"], merge=True)\n self.assertEqual(ins.top.get(\"A2\"), \"test_1\")\n self.assertEqual(ins.top.get(\"B3\"), \"tes_2\")\n self.assertEqual(ins.top.get(\"A4\"), \"te_3\")\n self.assertEqual(ins.top.get(\"B5\"), \"t_4\")\n self.assertEqual(ins.top.get(\"C5\"), \"t_5\")\n \n def test_raise_inserts(self):\n with self.assertRaises(ValueError):\n self.Inserts.set(\"A5\", \"martin\")\n \n def test_insert_set_get(self):\n ii = BioPlate(12, 8, inserts=True)\n ii[\"top\", \"A[3-7]\"] = \"Bob\"\n ii[\"bot\", \"B-D[6-9]\"] = [\"t1\", \"t2\", \"t3\"]\n ii[0, \"7-10[F-H]\"] = [\"t4\", \"t5\", \"t6\", \"t7\"]\n self.assertEqual(ii.top.get(\"A4\" ), \"Bob\")\n self.assertEqual(ii.bot.get(\"C7\" ), \"t2\")\n self.assertEqual(ii.top.get(\"G8\" ), \"t5\")\n self.assertEqual(ii[\"top\", \"A5\"], \"Bob\")\n self.assertEqual(ii[\"bot\", \"B6\"], \"t1\")\n self.assertEqual(ii[0, \"H10\"], \"t7\")\n self.assertEqual(ii[1, 3, 8], \"t2\")\n \nif __name__ == \"__main__\":\n unittest.main()"
] |
[
[
"numpy.array"
]
] |
mrek235/robotLearning
|
[
"4da7282f169f5ed2735c6a70084ff1e4decd2cd2"
] |
[
"973lossFor50000ForFirstJoint.py"
] |
[
"from keras.models import Sequential\nfrom keras.layers import Dense,Flatten,LSTM,Conv1D,Conv2D, MaxPool1D\nfrom keras.optimizers import Adam,SGD\nimport numpy as np\nfrom numpy.random import seed\nfrom sklearn.preprocessing import MinMaxScaler\nimport glob\n\nseed(42)\n\nmodel = Sequential()\n\ntimesteps = 30\ndata_dim = 4096\nnum_classes = 6\n\nmodel = Sequential()\n#model.add(Conv2D(64,(3,3), strides = (1,1), activation= 'tanh'))\n#model.add(Conv2D(64,(3,3), strides = (1,1), activation= 'tanh'))\n\n#model.add(Conv1D(8192,1, activation= 'linear', input_shape=(100,100)))\n#model.add(Conv1D(4096,1, activation= 'linear' ))\n\n#model.add(Conv1D(2048,1, activation= 'linear' ))\n#model.add(Conv1D(1024,1, activation= 'linear' ))\n#model.add(Conv1D(800,1, activation= 'linear' ))\n\n#model.add(Conv1D(300,1, activation= 'linear' ))\n\n#model.add(Conv1D(128,1, activation= 'linear'))\n\nmodel.add(Conv1D(64,1, activation= 'linear'))\nmodel.add(Conv1D(16,1, activation= 'linear'))\nmodel.add(Conv1D(8,1, activation= 'linear'))\n\n#model.add(Dense(32000, activation = 'linear'))\n#model.add(Dense(16000, activation= 'tanh'))\n#model.add(Dense(8200, activation = 'tanh'))\n#model.add(Dense(4096, activation = 'linear'))\n#model.add(Dense(2048, activation = 'linear'))\n#model.add(Dense(1024, activation = 'linear'))\n#model.add(Dense(256, activation= 'linear'))\n#model.add(Dense(64, activation = 'linear'))\n#model.add(Dense(4, activation = 'linear')) # return a single vector of dimension 32\nmodel.add(Flatten())\nmodel.add(Dense(1, activation='linear'))\nmodel.compile(loss=\"mean_squared_error\", optimizer=Adam())\n\n#file_list_30_samples = glob.glob(\"P*.npz\")\n#file_list_200_samples = glob.glob(\"R*.npz\")\nfile_list_for_outer_folder = glob.glob(\"/home/pc/Downloads/Robot_Data/A*.npz\") #1.0000052452087402 is black.\nprint(\"File list loaded.\")\n#file_list = glob.glob(\"A*.npz\")\n\ndef file_list_to_positions_list_from_outer_folder(file_list):\n positions_list = []\n for file_name in file_list:\n file_names_without_path = file_name.split('/home/pc/Downloads/Robot_Data/')\n file_names_without_path.remove('')\n file_names_without_npz = file_names_without_path[0].split('.npz')\n file_names_without_npz.remove('')\n for name in file_names_without_npz:\n file_name_without_npz_and_p = name.split('A')\n file_name_without_npz_and_p.remove('')\n floated_sublist = []\n for position in file_name_without_npz_and_p:\n\n floated_sublist.append(float(position))\n positions_list.append(floated_sublist[0:1])\n\n return positions_list\n\ndef file_list_to_positions_list(file_list):\n positions_list = []\n for file_name in file_list:\n file_names_without_npz = file_name.split('.npz')\n file_names_without_npz.remove('')\n for name in file_names_without_npz:\n file_name_without_npz_and_p = name.split('A')\n file_name_without_npz_and_p.remove('')\n floated_sublist = []\n for position in file_name_without_npz_and_p:\n\n floated_sublist.append(float(position))\n positions_list.append(floated_sublist[0:3])\n\n return positions_list\n\n\ndef npz_to_data_arr(file_list):\n data_arr = []\n for file in file_list:\n loaded_file = (np.load(file))['arr_0']\n last_position_data = loaded_file[len(loaded_file)-1]\n last_position_data = last_position_data.reshape(100,100)\n data_arr.append(last_position_data)\n return data_arr\n\nprint(\"Creating data array\")\ndata_arr = np.array(npz_to_data_arr(file_list_for_outer_folder[0:50000]))\nprint(\"Data array created.\")\n\nprint(\"Extracting positions array.\")\npositions_list = np.array(file_list_to_positions_list_from_outer_folder((file_list_for_outer_folder[0:50000])))\nprint(\"Positions array extracted.\")\n\ndef flatten_data(data_arr):\n flattened = []\n for i in range(len(data_arr)):\n new_arr = data_arr[i]\n flattened.append(np.array(data_arr[i]).flatten())\n return flattened\n\n\n\n#flattened_data = np.array(flatten_data(data_arr))\n#data_arr = None\nflattened_data = data_arr\n\nprint(\"Train and test data are prepared.\")\n\nninetieth_percentile = int(len(flattened_data)*0.9)\nX_train = flattened_data[0:ninetieth_percentile]\ny_train = np.array(positions_list[0:ninetieth_percentile])\n\nX_test = flattened_data[ninetieth_percentile:len(flattened_data)]\ny_test = np.array(positions_list[ninetieth_percentile:len(flattened_data)])\n\n\nprint(\"Starting training.\")\nmodel.fit(X_train,y_train, epochs=100)\nX_train = None\ny_train = None\n\nprint(\"Here is a little test of the model:\")\nprint(model.predict(X_test[0:2]))\nprint(y_test[0:2])\n\nprint(\"This is the evaluation of model based on test data\")\nprint(model.evaluate(X_test,y_test))\nmodel.save(\"firstTryWith30thousandImages\")\n#print(X_train.shape)\n#print(y_train.shape)\n"
] |
[
[
"numpy.load",
"numpy.array",
"numpy.random.seed"
]
] |
matt-graham/boltzmann-machine-tools
|
[
"528e61c42fc3de05e00176ebf724aacddbef6824"
] |
[
"bmtools/relaxations/gm_relaxations.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"Gaussian mixture Boltzman machine relaxations.\n\nHelper classes for performing inference with Gaussian mixture Boltzmann machine\nrelaxations [1].\n\nThe original discrete-space Boltzmann machine is assumed to have weight\nparameters `W` and bias parameters `b` and have a signed-binary state\n`s[i] \\in [-1, +1]` with the probability of a binary vector `s` being\n\n p(s) = exp(0.5 * s.dot(W).dot(s) + b.dot(s)) / Z\n\nwhere `Z` is the normalisation constant.\n\nTwo alternative parameterisations for the relaxation distribution on continuous\nvector state `x` are provided.\n\nThe unnormalised density of the `isotropic cosh` form is\n\n p(x) \\propto exp(-0.5 * (x - b).T.dot(V).dot(x - b))) * cosh(x).prod()\n\nwhere `V.dot(W + D) == I` and `D` is a diagonal matrix such that `(W + D)` is\n(semi-)positive definite.\n\nThe unnormalised density of the `istropic covariance` form is\n\n p(x) \\propto exp(-0.5 * x.dot(x)) * cosh(Q.dot(x) + b).prod()\n\nwhere `Q.dot(Q.T) = W + D` with `D` as above.\n\nReferences\n----------\n[1]: Zhang, Y., Ghahramani, Z., Storkey, A. J., & Sutton, C. A.\n Continuous relaxations for discrete Hamiltonian Monte Carlo.\n Advances in Neural Information Processing Systems 2012 (pp. 3194-3202).\n\"\"\"\n\nimport numpy as np\nimport scipy.linalg as la\nimport itertools as it\nimport cvxpy as cvx\nimport bmtools.exact.moments as mom\nimport bmtools.exact.helpers as hlp\n\n\n# Dimension of original binary state space above which to have user have to\n# manually set `force` argument to `True` in functions which involve an\n# exhaustive iteration over the 2**D binary state space.\nFORCE_DIM = 10\n\n\ndef get_min_lambda_max_diagonal(W):\n \"\"\"\n Compute maximum eigenvalue minimising additive diagonal term.\n\n Calculates additive diagonal term D which minimises maximum eigenvalue of\n W + D subject to the constrain W + D is semi-positive definite. This can\n be expressed as a semi-definite programme.\n \"\"\"\n d_vct = cvx.Variable(W.shape[0])\n D_mtx = cvx.diag(d_vct)\n objc = cvx.Minimize(cvx.lambda_max(W + D_mtx))\n cnst = [W + D_mtx >> 0]\n prob = cvx.Problem(objc, cnst)\n prob.solve()\n return np.array(D_mtx.value)\n\n\nclass BaseGMRelaxation(object):\n \"\"\"Abstract Gaussian mixture Boltzmann machine relaxation base class.\"\"\"\n\n def __init__(self, W, b, optimise_eigvals=True, epsilon=0.,\n eigval_thr=1e-6, precomputed_D=None):\n self.W = W\n self.b = b\n self.n_unit = W.shape[0]\n if precomputed_D is not None:\n self.D = precomputed_D\n e, R = la.eigh(W + self.D)\n assert np.all(e > -eigval_thr), 'Provided D does not make W PSD'\n elif optimise_eigvals:\n self.D = (get_min_lambda_max_diagonal(W) +\n np.eye(self.n_unit) * epsilon)\n e, R = la.eigh(W + self.D)\n else:\n e, R = la.eigh(W)\n self.D = np.eye(n_unit) * (epsilon - e.min())\n e += (epsilon - e.min())\n idx_nz = e > eigval_thr\n self.n_dim_r = int(idx_nz.sum())\n self.R_r = R[:, idx_nz]\n self.e_r = e[idx_nz]\n\n def moments_s(self, force=False, num_threads=4):\n if self.n_unit > FORCE_DIM and not force:\n print('Size of state space is large ({0}) '\n 'set force=True to proceed anyway'.format(2**self.n_unit))\n norm_const_s, expc_s, expc_ss = mom.calculate_moments_parallel(\n self.W, self.b, force=force, num_threads=num_threads)\n return norm_const_s, np.array(expc_s), np.array(expc_ss)\n\n def neg_log_dens_x(self, x):\n raise NotImplementedError()\n\n def grad_neg_log_dens_x(self, x):\n raise NotImplementedError()\n\n def sample_x_gvn_s(self, s, n_sample, prng):\n raise NotImplementedError()\n\n def independent_samples(self, n_sample, force=False,\n prng=np.random.RandomState(), num_threads=4,\n return_probs_and_state_counts=True):\n if self.n_unit > FORCE_DIM and not force:\n print('Size of state space is large ({0}) '\n 'set force=True to proceed anyway'.format(2**self.n_unit))\n probs, norm_const = mom.calculate_probs_parallel(\n self.W, self.b, force=force, num_threads=num_threads)\n binary_state_counts = prng.multinomial(n_sample, probs)\n xs = np.empty((n_sample, self.n_dim))\n cum_count = 0\n s = np.empty(self.n_unit, dtype=np.int8)\n for i in np.nonzero(binary_state_counts)[0]:\n hlp.index_to_state(i, s)\n count = binary_state_counts[i]\n xs[cum_count:cum_count+count] = self.sample_x_gvn_s(s, count, prng)\n cum_count += count\n return xs, binary_state_counts, probs, norm_const\n\n\nclass IsotropicCovarianceGMRelaxation(BaseGMRelaxation):\n \"\"\"Isotropic covariance parameterisation of Gaussian mixture relaxation.\n\n The unnormalised density is of the form\n\n p(x) \\propto exp(-0.5 * x.dot(x)) * cosh(Q.dot(x) + b).prod()\n\n where `Q.dot(Q.T) = W + D` with `D` a diagonal matrix such that `(W + D)`\n is (semi-)positive definite.\n \"\"\"\n\n def __init__(self, W, b, optimise_eigvals=True, epsilon=0.,\n eigval_thr=1e-6, precomputed_D=None):\n super(IsotropicCovarianceGMRelaxation, self).__init__(\n W, b, optimise_eigvals, epsilon, eigval_thr, precomputed_D)\n self.n_dim = self.n_dim_r\n self.Q = self.R_r * self.e_r**0.5\n\n def neg_log_dens_x(self, x):\n return (0.5 * (x**2).sum(-1) -\n np.log(np.cosh(x.dot(self.Q.T) + self.b)).sum(-1))\n\n def grad_neg_log_dens_x(self, x):\n return x - np.tanh(x.dot(self.Q.T) + self.b).dot(self.Q)\n\n def sample_x_gvn_s(self, s, n_sample, prng):\n return (self.Q.T.dot(s)[None, :] +\n prng.normal(size=(n_sample, self.n_dim_r)))\n\n def moments_x(self, force=False, num_threads=4):\n norm_const_s, expc_s, expc_ss = self.moments_s(force, num_threads)\n log_norm_const_x = (\n 0.5 * self.n_dim_r * np.log(2 * np.pi) - self.n_unit * np.log(2) +\n 0.5 * self.D.diagonal().sum() + np.log(norm_const_s)\n )\n expc_x = self.Q.T.dot(expc_s)\n covar_x = (\n self.Q.T.dot(expc_ss - np.outer(expc_s, expc_s)).dot(self.Q) +\n np.eye(self.n_dim_r)\n )\n return log_norm_const_x, expc_x, covar_x\n\n\nclass IsotropicCoshGMRelaxation(BaseGMRelaxation):\n \"\"\"Isotropic cosh parameterisation of Gaussian mixture relaxation.\n\n The unnormalised density of the relaxation is of the form\n\n p(x) \\propto exp(-0.5 * (x - b).T.dot(V).dot(x - b))) * cosh(x).prod()\n\n where `V.dot(W + D) == I` and `D` is a diagonal matrix such that `(W + D)`\n is (semi-)positive definite.\n \"\"\"\n\n def __init__(self, W, b, optimise_eigvals=True, epsilon=0.,\n eigval_thr=1e-6, precomputed_D=None):\n super(IsotropicCoshGMRelaxation, self).__init__(\n W, b, optimise_eigvals, epsilon, eigval_thr, precomputed_D)\n self.n_dim = self.n_unit\n self.V_inv = self.W + self.D\n self.V_inv_sqrt = self.R_r * self.e_r**0.5\n self.V = (self.R_r / self.e_r).dot(self.R_r.T)\n self.V_sqrt = self.R_r / self.e_r**0.5\n\n def neg_log_dens_x(self, x):\n x_m_b = x - self.b\n return (0.5 * x_m_b.dot(self.V) * x_m_b - np.log(np.cosh(x))).sum(-1)\n\n def grad_neg_log_dens_x(self, x):\n return (x - self.b).dot(V) - np.tanh(x)\n\n def sample_x_gvn_s(self, s, n_sample, prng):\n n = prng.normal(size=(n_sample, self.n_dim_r))\n return (self.V_inv.dot(s) + self.b)[None, :] + n.dot(self.V_inv_sqrt.T)\n\n def moments_x(self, force=False, num_threads=4):\n norm_const_s, expc_s, expc_ss = self.moments_s(force, num_threads)\n log_norm_const_x = (\n 0.5 * self.n_dim_r * np.log(2 * np.pi) - self.n_unit * np.log(2) +\n 0.5 * self.D.diagonal().sum() + np.log(norm_const_s) +\n 0.5 * self.e_r.sum()\n )\n expc_x = self.b + self.V.dot(expc_s)\n covar_x = (\n self.V.dot(expc_ss - np.outer(expc_s, expc_s)).dot(self.V) +\n self.V\n )\n return log_norm_const_x, expc_x, covar_x\n"
] |
[
[
"numpy.log",
"numpy.cosh",
"numpy.nonzero",
"numpy.random.RandomState",
"numpy.eye",
"numpy.all",
"scipy.linalg.eigh",
"numpy.outer",
"numpy.tanh",
"numpy.array",
"numpy.empty"
]
] |
einbandi/kerneloose
|
[
"2becc7f8df2ae4d79cb5ffef58b8cce440ff6a1e"
] |
[
"kerneloose/kerneloose.py"
] |
[
"import numpy as np\nimport scipy.spatial.distance as dist\nimport pickle\n\n\ndef determine_sigma(x_dist, k_nb, local=True):\n \"\"\" Choose the width of the Gaussian kernels.\n\n Automatically choose the width of the Gaussian kernels based\n on the distance to the k-th nearest neighbor.\n\n Args:\n x_dist: matrix (nparray) of pairwise distances between\n training data points\n k_nb: number of the considered neighbor\n local: optional argument for switching between locally\n different kernels (True) and a single, average\n kernel width (False)\n\n Returns:\n An nparray of kernel widths if local=True, otherwise a\n scalar with the average kernel width\n \"\"\"\n\n n = x_dist.shape[0]\n\n # sort distance matrix column-wise\n dist_sorted = np.sort(x_dist, axis=0)\n\n # disregard entries with distance 0\n ind_nb = np.sum(dist_sorted == 0, axis=0) + k_nb\n # convert to matrix indices\n ind_nb += np.arange(n) * n\n ind_nb = np.unravel_index(ind_nb-1, dist_sorted.shape, order='F')\n\n if local:\n return dist_sorted[ind_nb]\n else:\n return np.mean(dist_sorted[ind_nb])\n\n\ndef kmap_train(x_dist, y, sig, k_nb=10, local=True):\n \"\"\" Train the parameters of the kernel mapping.\n\n Train the parameters of the kernel mapping based on the\n distances and projections of the training data.\n\n Args:\n x_dist: matrix (nparray) of pairwise distances between\n training data points\n y: low-dimensional projections of the training data\n sig: scales the width of the gaussians\n k_nb: number of considered neighbor\n local: locality switch (see 'determine_sigma')\n\n Returns:\n A dictionary with the following entries:\n sigmas: widths of the Gaussians\n coeffs: learned mapping matrix\n \"\"\"\n\n # compute the widths\n sig_nb = determine_sigma(x_dist, k_nb, local=local)\n sig_nb = sig_nb ** 2\n\n # scale the widths\n par = dict()\n par['sigmas'] = sig * sig_nb\n\n # compute the kernel\n ker = np.exp(- (x_dist/par['sigmas']))\n # normalise\n ker = ker / np.sum(ker, axis=1)\n\n # compute inverse\n par['coeffs'] = np.dot(np.linalg.pinv(ker), y)\n\n return par\n\n\ndef kmap_test(x_dist_ose, par):\n \"\"\" Map new data using learned parameters.\n\n Map new data to a low-dimensional space based on the\n parameters learned on the training data.\n\n Args:\n x_dist_ose: matrix (nparray) of pairwise distances between\n test data points and training data points\n par: parameter dictionary of the kernel mapping\n (output of 'kmap_train')\n\n Returns:\n An nparray with low-dimensional projections of the test data\n \"\"\"\n\n # compute kernel\n ker_ose = np.exp(- (x_dist_ose / par['sigmas']))\n ker_ose = ker_ose / np.sum(ker_ose, axis=1, keepdims=True)\n\n # compute projections\n y_ose = np.dot(ker_ose, par['coeffs'])\n y_nan = np.sum(np.isnan(np.sum(y_ose, axis=1)))\n\n if y_nan > 0:\n print('Number of NaN elements is {}'.format(y_nan))\n print('Consider using larger sigma for training.')\n\n return y_ose\n\n\nclass KernelMap:\n \"\"\" Kernel mapping for out-of-sample extension.\n\n Calculate and apply a kernel mapping based on previously\n projected data (e.g. by t-SNE).\n\n Attributes:\n k_nb: number of considered neighbor\n local: a boolean indicating if gaussian width should\n be estimated locally (True) or globally (False)\n sig_scale: scaling factor for gaussians\n metric: function used for computing pairwise distances\n trained: a boolean indicating of kernel mapping has\n already been trained\n params: a dictionary containing the fitted parameters:\n sigmas: widths of the Gaussians\n coeffs: learned mapping matrix\n x_train: data used for fitting\n \"\"\"\n\n def __init__(self, k_nb=1, local=True, sig_scale=1., metric='euclidean'):\n self.k_nb = k_nb\n self.local = local\n self.sig_scale = sig_scale\n self.metric = metric\n self.trained = False\n self.params = {'sigmas': None, 'coeffs': None}\n self.x_train = None\n\n def fit(self, x_train, y_train):\n \"\"\" Calculate the kernel mapping.\"\"\"\n\n self.x_train = x_train\n x_dist = dist.squareform(dist.pdist(x_train, self.metric))\n self.params = kmap_train(x_dist, y_train, self.sig_scale,\n k_nb=self.k_nb, local=self.local)\n self.trained = True\n\n def transform(self, x):\n \"\"\" Apply the calculated kernel mapping.\"\"\"\n\n distances = dist.cdist(x, self.x_train, self.metric)\n return kmap_test(distances, self.params)\n \n def save(self, filename):\n \"\"\" Save the trained mapping for later use.\"\"\"\n \n if self.trained:\n obj = {\n 'k_nb': self.k_nb,\n 'local': self.local,\n 'sig_scale': self.sig_scale,\n 'metric': self.metric,\n 'params': self.params,\n 'x_train': self.x_train\n }\n with open(filename, 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n else: print('Error: cannot save untrained kernel map.')\n \n def load(self, filename):\n \"\"\"Load a trained kernel mapping.\"\"\"\n \n with open(filename, 'rb') as f:\n obj = pickle.load(f)\n\n self.trained = True\n self.k_nb = obj['k_nb']\n self.local = obj['local']\n self.sig_scale = obj['sig_scale']\n self.metric = obj['metric']\n self.params = obj['params']\n self.x_train = obj['x_train']"
] |
[
[
"numpy.dot",
"numpy.arange",
"scipy.spatial.distance.cdist",
"numpy.sort",
"numpy.linalg.pinv",
"scipy.spatial.distance.pdist",
"numpy.mean",
"numpy.exp",
"numpy.unravel_index",
"numpy.sum"
]
] |
vycezhong/segment_mm
|
[
"9b3a183932363668ddb33fc23acca0afc2978ad4"
] |
[
"benchmark.py"
] |
[
"import argparse\nimport time\nimport torch\nimport numpy as np\nfrom tqdm import tqdm \n\nparser = argparse.ArgumentParser()\nparser.add_argument('example', choices=['naive', 'bmm', 'cuda'])\nparser.add_argument('-n', type=int, default=512)\nparser.add_argument('-m', type=int, default=512)\nparser.add_argument('-d', type=int, default=300)\nparser.add_argument('-k', type=int, default=32)\nparser.add_argument('-r', '--runs', type=int, default=1000)\noptions = parser.parse_args()\n\nif options.example == 'naive':\n from python.segment_mm import naive_segment_mm\n segment_mm = naive_segment_mm\nelif options.example == 'bmm':\n from python.segment_mm import bmm_segment_mm\n segment_mm = bmm_segment_mm\nelse:\n from cuda.segment_mm import SegmentMM\n segment_mm = SegmentMM()\n\nN = options.n \nM = options.m \nD = options.d \nK = options.k \n\nmat_A = torch.randn(N, D, requires_grad=True).cuda()\nmat_B = torch.randn(M, D, requires_grad=True).cuda()\n\nsegment_id_a = torch.tensor(np.repeat(list(range(K)), N//K)).cuda()\nsegment_id_b = torch.tensor(np.repeat(list(range(K)), M//K)).cuda()\n\n# force cuda init\nc = segment_mm(mat_A, mat_B, segment_id_a, segment_id_b)\n\nforward_time = 0\nbackward_time = 0\nfor _ in tqdm(range(options.runs)):\n if options.example == 'cuda':\n segment_mm.zero_grad()\n\n start = time.time()\n c = segment_mm(mat_A, mat_B, segment_id_a, segment_id_b)\n elapsed = time.time() - start \n forward_time += elapsed\n\n x = torch.sum(c)\n start = time.time()\n x.backward()\n elapsed = time.time() - start\n backward_time += elapsed\n\nforward_time *= 1000.0\nbackward_time *= 1000.0\n\nprint('forward: %.3f | backward: %.3f' % (\n forward_time/options.runs, backward_time/options.runs\n))"
] |
[
[
"torch.randn",
"torch.sum"
]
] |
dhas/apex
|
[
"ebcd7f084bba96bdb0c3fdf396c3c6b02e745042"
] |
[
"apex/contrib/test/layer_norm/test_fast_layer_norm.py"
] |
[
"import torch\nimport unittest\nimport numpy as np\n\nimport torch.nn.functional as F\n\nfrom apex.contrib.layer_norm import FastLayerNorm\n\nimport fast_layer_norm as fln\n\n\nclass GPUTimer:\n def __init__(self, stream):\n self.start_ = torch.cuda.Event(enable_timing=True)\n self.stop_ = torch.cuda.Event(enable_timing=True)\n self.stream_ = stream\n def start(self):\n self.stream_.record_event(self.start_)\n def stop(self):\n self.stream_.record_event(self.stop_)\n def sync(self):\n self.stream_.synchronize()\n def millis(self):\n return self.start_.elapsed_time(self.stop_)\n\ndef size_in_bytes(t):\n return torch.numel(t) * t.element_size()\ndef abs_err(x, y):\n xf = x.float()\n yf = y.float()\n return ((xf-yf).abs().sum() / yf.abs().sum()).item()\n\n\n\nclass TestFastLayerNorm(unittest.TestCase):\n \n def setUp(self, seed=1234):\n seed = 1234\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n def test_ln_fp32(self):\n self.run_test_layer_norm(torch.float32, atol=1e-5)\n def test_ln_fp16(self):\n self.run_test_layer_norm(torch.float16, atol=1e-2, rtol=1e-3)\n\n def run_test_layer_norm(self, dtype, atol, rtol=1e-5):\n device = torch.device('cuda')\n s = 512\n b = 32\n hidden_size = 1024\n epsilon = 1e-5\n\n x = torch.randn((s,b,hidden_size), dtype=dtype, device=device) \n beta = torch.randn(hidden_size, dtype=dtype, device=device) \n gamma = torch.randn(hidden_size, dtype=dtype, device=device)\n x.requires_grad = True\n beta.requires_grad = True\n gamma.requires_grad = True\n\n x2 = x.clone().detach()\n beta2 = beta.clone().detach()\n gamma2 = gamma.clone().detach()\n x2.requires_grad = True\n beta2.requires_grad = True\n gamma2.requires_grad = True\n \n dummy_label = torch.randn_like(x)\n\n y = F.layer_norm(x, [hidden_size], gamma, beta, epsilon)\n\n diff = y-dummy_label\n l = (diff * diff).sum() / b\n l.backward()\n\n fln = FastLayerNorm(hidden_size).cuda()\n fln.load_state_dict({'bias': beta2, 'weight':gamma2})\n if dtype == torch.float16:\n fln = fln.half()\n\n y2 = fln(x2)\n diff2 = (y2 - dummy_label)\n l2 = (diff2 * diff2).sum() / b\n\n l2.backward()\n\n self.assertTrue(torch.allclose(y2, y, atol=atol, rtol=rtol))\n self.assertTrue(torch.allclose(x2.grad, x.grad, atol=atol,rtol=rtol))\n self.assertTrue(torch.allclose(fln.bias.grad, beta.grad, atol=atol, rtol=rtol))\n self.assertTrue(torch.allclose(fln.weight.grad, gamma.grad, atol=atol, rtol=rtol))\n \n\n\n def test_performance(self):\n print()\n runs = 1000\n device = torch.device('cuda')\n dtype =torch.float16\n s = 512\n b = 32\n hidden_size = 1024\n epsilon = 1e-5\n\n x = torch.randn((s*b,hidden_size), dtype=dtype, device=device) \n beta = torch.randn(hidden_size, dtype=dtype, device=device) \n gamma = torch.randn(hidden_size, dtype=dtype, device=device)\n dy = torch.randn_like(x)\n \n\n stream = torch.cuda.Stream()\n with torch.cuda.stream(stream):\n\n timer = GPUTimer(stream)\n\n #warmup\n for r in range(runs):\n y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5)\n \n \n timer.start()\n for r in range(runs):\n y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5)\n timer.stop()\n timer.sync()\n\n total_bytes_fwd = (size_in_bytes(x) \n + size_in_bytes(y) \n + size_in_bytes(gamma) \n + size_in_bytes(beta) \n + size_in_bytes(mu) \n + size_in_bytes(rsigma)\n )\n\n ms_fwd = timer.millis() / runs\n print('[FWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_fwd, total_bytes_fwd * 1e-6 / ms_fwd ))\n \n\n timer.start()\n for r in range(runs):\n dx, dgamma, dbeta = fln.ln_bwd(dy, x, mu, rsigma, gamma)\n timer.stop()\n timer.sync()\n\n total_bytes_bwd = (size_in_bytes(x) \n + size_in_bytes(dx)\n + size_in_bytes(dy) \n + size_in_bytes(gamma) \n + size_in_bytes(dgamma) \n + size_in_bytes(dbeta) \n + size_in_bytes(mu) \n + size_in_bytes(rsigma)\n )\n\n\n ms_bwd = timer.millis() / runs\n print('[BWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_bwd, total_bytes_bwd * 1e-6 / ms_bwd ))\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"torch.randn_like",
"torch.nn.functional.layer_norm",
"torch.manual_seed",
"torch.randn",
"torch.cuda.Event",
"torch.numel",
"torch.cuda.manual_seed_all",
"torch.cuda.stream",
"torch.device",
"torch.allclose",
"torch.cuda.Stream"
]
] |
rctcwyvrn/rust-ncc
|
[
"1dc03bd6fa1d7314e5aaf6b1509ef7f299f2b4ab"
] |
[
"py_model/environment.py"
] |
[
"import copy\nimport time\n\nimport numba as nb\nimport numpy as np\n\nimport cell\nimport geometry\nimport parameters\n\nimport hardio\nfrom hardio import Writer\nimport chemistry\n\n\"\"\"\nEnvironment of cells.s\n\"\"\"\n\nMODE_EXECUTE = 0\nMODE_OBSERVE = 1\n\n\[email protected](nopython=True)\ndef custom_floor(fp_number, roundoff_distance):\n a = int(fp_number)\n b = a + 1\n\n if abs(fp_number - b) < roundoff_distance:\n return b\n else:\n return a\n\n\n# -----------------------------------------------------------------\n\n\ndef calc_bb_centre(bbox):\n x = bbox[0] + (bbox[1] - bbox[0]) * 0.5\n y = bbox[2] + (bbox[3] - bbox[2]) * 0.5\n\n return np.array([x, y])\n\n\n# -----------------------------------------------------------------\n\n\nclass Environment:\n \"\"\"Implementation of coupled map lattice model of a cell.\n \"\"\"\n\n def __init__(\n self, out_dir, name, log_level, params\n ):\n self.params = params\n\n self.curr_tpoint = 0\n self.t = params[\"t\"]\n self.dt = 1.0\n self.num_tsteps = int(np.ceil(params[\"final_t\"]/self.t))\n self.num_tpoints = self.num_tsteps + 1\n self.timepoints = np.arange(0, self.num_tpoints)\n self.num_int_steps = params[\"num_int_steps\"]\n self.num_cells = params[\"num_cells\"]\n self.snap_period = params[\"snap_period\"]\n\n self.writer = Writer(out_dir, name, log_level, params, self.snap_period)\n self.writer.save_header(params)\n\n self.env_cells = self.make_cells()\n self.cell_indices = np.arange(self.num_cells)\n self.exec_orders = np.zeros(\n (self.num_tpoints, self.num_cells), dtype=np.int64\n )\n\n self.all_geometry_tasks = np.array(\n geometry.create_dist_and_line_segment_intersection_test_args(\n self.num_cells, 16\n ),\n dtype=np.int64,\n )\n self.geometry_tasks_per_cell = np.array(\n [\n geometry.create_dist_and_line_segment_intersection_test_args_relative_to_specific_cell(\n ci, self.num_cells, 16\n )\n for ci in range(self.num_cells)\n ],\n dtype=np.int64,\n )\n\n env_cells_verts = np.array(\n [x.curr_verts for x in self.env_cells]\n )\n cells_bb_array = \\\n geometry.calc_init_cell_bbs(\n self.num_cells, env_cells_verts)\n (\n cells_node_distance_matrix,\n cells_line_segment_intersection_matrix,\n ) = geometry.init_lseg_intersects_and_dist_sq_matrices_old(\n self.num_cells,\n 16,\n cells_bb_array,\n env_cells_verts,\n )\n self.x_cils_per_cell = []\n self.x_coas_per_cell = []\n self.update_coa_cil(env_cells_verts,\n cells_node_distance_matrix,\n cells_line_segment_intersection_matrix)\n for (ci, cell) in enumerate(self.env_cells):\n are_nodes_inside_other_cells = \\\n geometry.check_if_nodes_inside_other_cells(\n cell.cell_ix, 16, self.num_cells,\n env_cells_verts)\n\n close_point_on_other_cells_to_each_node_exists, \\\n close_point_on_other_cells_to_each_node, \\\n close_point_on_other_cells_to_each_node_indices, \\\n close_point_on_other_cells_to_each_node_projection_factors, \\\n close_point_smoothness_factors = \\\n geometry.do_close_points_to_each_node_on_other_cells_exist(\n cell.num_cells, 16, cell.cell_ix,\n env_cells_verts[cell.cell_ix],\n cells_node_distance_matrix[ci],\n cell.close_zero_at,\n cell.close_one_at,\n env_cells_verts, are_nodes_inside_other_cells)\n\n cell.initialize_cell(close_point_smoothness_factors,\n self.x_cils_per_cell[ci],\n self.x_coas_per_cell[ci])\n\n self.mode = MODE_EXECUTE\n self.animation_settings = None\n\n # -----------------------------------------------------------------\n\n def make_cells(self):\n env_cells, init_cell_bbs = self.create_cell_group(self.params)\n return np.array(env_cells)\n\n # -----------------------------------------------------------------\n\n def create_cell_group(\n self, params\n ):\n num_cells = params[\"num_cells\"]\n cell_group_bb = params[\"cell_group_bbox\"]\n cell_r = params[\"cell_r\"]\n\n init_cell_bbs = self.calculate_cell_bbs(\n num_cells,\n cell_r,\n cell_group_bb,\n )\n\n cells_in_group = []\n\n for ci, bbox in enumerate(init_cell_bbs):\n (\n init_verts,\n rest_edge_len,\n rest_area,\n ) = self.create_default_init_cell_verts(\n bbox, cell_r\n )\n\n params.update(\n [\n (\"init_verts\", init_verts),\n (\"rest_edge_len\", rest_edge_len),\n (\"rest_area\", rest_area),\n ]\n )\n\n new_cell = cell.Cell(\n 0,\n ci,\n params,\n self.dt,\n )\n\n cells_in_group.append(new_cell)\n\n return cells_in_group, init_cell_bbs\n\n # -----------------------------------------------------------------\n\n @staticmethod\n def calculate_cell_bbs(\n num_cells,\n cell_r,\n cell_group_bb,\n ):\n\n cell_bbs = np.zeros((num_cells, 4), dtype=np.float64)\n xmin, xmax, ymin, ymax = cell_group_bb\n x_length = xmax - xmin\n y_length = ymax - ymin\n\n cell_diameter = 2 * cell_r\n\n # check if cells can fit in given bounding box\n total_cell_group_area = num_cells * (np.pi * cell_r ** 2)\n cell_group_bb_area = abs(x_length * y_length)\n\n if total_cell_group_area > cell_group_bb_area:\n raise Exception(\n \"Cell group bounding box is not big enough to contain all \"\n \"cells given cell_r constraint.\"\n )\n num_cells_along_x = custom_floor(x_length / cell_diameter, 1e-6)\n num_cells_along_y = custom_floor(y_length / cell_diameter, 1e-6)\n\n cell_x_coords = (\n xmin +\n np.sign(x_length) *\n np.arange(num_cells_along_x) *\n cell_diameter)\n cell_y_coords = (\n ymin +\n np.sign(y_length) *\n np.arange(num_cells_along_y) *\n cell_diameter)\n x_step = np.sign(x_length) * cell_diameter\n y_step = np.sign(y_length) * cell_diameter\n\n xi = 0\n yi = 0\n for ci in range(num_cells):\n cell_bbs[ci] = [\n cell_x_coords[xi],\n cell_x_coords[xi] + x_step,\n cell_y_coords[yi],\n cell_y_coords[yi] + y_step,\n ]\n\n if yi == (num_cells_along_y - 1):\n yi = 0\n xi += 1\n else:\n yi += 1\n\n return cell_bbs\n\n # -----------------------------------------------------------------\n\n @staticmethod\n def create_default_init_cell_verts(\n bbox, cell_r\n ):\n cell_centre = calc_bb_centre(bbox)\n\n cell_node_thetas = np.pi * \\\n np.linspace(0, 2, endpoint=False, num=16)\n cell_verts = np.transpose(\n np.array(\n [\n cell_r * np.cos(cell_node_thetas),\n cell_r * np.sin(cell_node_thetas),\n ]\n )\n )\n\n # rotation_theta = np.random.rand()*2*np.pi\n # cell_verts = np.array([\n # geometry.rotate_2D_vector_CCW_by_theta(rotation_theta, x) for x in\n # cell_verts], dtype=np.float64)\n cell_verts = np.array(\n [[x + cell_centre[0], y + cell_centre[1]] for x, y in\n cell_verts],\n dtype=np.float64,\n )\n\n edge_vectors = geometry.calculate_edge_vectors(cell_verts)\n\n edge_lengths = geometry.calculate_vec_mags(edge_vectors)\n\n rest_edge_len = np.average(edge_lengths)\n\n rest_area = geometry.calculate_polygon_area(cell_verts)\n if rest_area < 0:\n raise Exception(\"Resting area was calculated to be negative.\")\n return cell_verts, rest_edge_len, rest_area\n\n # -----------------------------------------------------------------\n def execute_system_dynamics_in_random_sequence(\n self,\n t,\n cells_node_distance_matrix,\n cells_bb_array,\n cells_line_segment_intersection_matrix,\n env_cells_verts,\n environment_cells,\n ):\n execution_sequence = self.cell_indices\n # np.random.shuffle(execution_sequence)\n\n self.exec_orders[t] = np.copy(execution_sequence)\n\n for ci in execution_sequence:\n current_cell = environment_cells[ci]\n x_cils = self.x_cils_per_cell[ci]\n x_coas = self.x_coas_per_cell[ci]\n\n are_nodes_inside_other_cells = \\\n geometry.check_if_nodes_inside_other_cells(\n current_cell.cell_ix, 16, self.num_cells,\n env_cells_verts)\n\n close_point_on_other_cells_to_each_node_exists, \\\n close_point_on_other_cells_to_each_node, \\\n close_point_on_other_cells_to_each_node_indices, \\\n close_point_on_other_cells_to_each_node_projection_factors, \\\n close_point_smoothness_factors = \\\n geometry.do_close_points_to_each_node_on_other_cells_exist(\n current_cell.num_cells, 16, current_cell.cell_ix,\n env_cells_verts[current_cell.cell_ix],\n cells_node_distance_matrix[ci],\n current_cell.close_zero_at,\n current_cell.close_one_at,\n env_cells_verts, are_nodes_inside_other_cells)\n\n self.writer.begin_cell_save()\n current_cell.execute_step(\n env_cells_verts,\n close_point_smoothness_factors,\n x_cils,\n x_coas,\n self.writer,\n )\n self.writer.finish_cell_save()\n\n this_cell_coords = current_cell.curr_verts\n\n env_cells_verts[ci] = this_cell_coords\n\n cells_bb_array[ci] = \\\n geometry.calculate_polygon_bb(this_cell_coords)\n geometry.update_line_segment_intersection_and_dist_squared_matrices(\n 4,\n self.geometry_tasks_per_cell[ci],\n env_cells_verts,\n cells_bb_array,\n cells_node_distance_matrix,\n cells_line_segment_intersection_matrix,\n sequential=True,\n )\n\n self.update_coa_cil(env_cells_verts, cells_node_distance_matrix,\n cells_line_segment_intersection_matrix)\n\n return (\n cells_node_distance_matrix,\n cells_bb_array,\n cells_line_segment_intersection_matrix,\n env_cells_verts,\n )\n\n # -----------------------------------------------------------------\n\n def update_coa_cil(self, env_cells_verts, cells_node_distance_matrix,\n cells_line_segment_intersection_matrix):\n self.x_cils_per_cell = []\n self.x_coas_per_cell = []\n for ci in range(self.num_cells):\n cell = self.env_cells[ci]\n x_coas = chemistry.calculate_x_coas(\n self.num_cells,\n ci,\n cell.coa_distrib_exp,\n cell.coa_mag,\n cells_node_distance_matrix[ci],\n cells_line_segment_intersection_matrix[ci],\n cell.coa_los_penalty,\n )\n\n are_nodes_inside_other_cells = \\\n geometry.check_if_nodes_inside_other_cells(\n cell.cell_ix, 16, self.num_cells,\n env_cells_verts)\n\n close_point_on_other_cells_to_each_node_exists, \\\n close_point_on_other_cells_to_each_node, \\\n close_point_on_other_cells_to_each_node_indices, \\\n close_point_on_other_cells_to_each_node_projection_factors, \\\n close_point_smoothness_factors = \\\n geometry.do_close_points_to_each_node_on_other_cells_exist(\n cell.num_cells, 16, cell.cell_ix,\n env_cells_verts[cell.cell_ix],\n cells_node_distance_matrix[ci],\n cell.close_zero_at,\n cell.close_one_at,\n env_cells_verts, are_nodes_inside_other_cells)\n x_cils = chemistry.calc_x_cils(cell.cell_ix, cell.num_cells,\n cell.cil_mag,\n close_point_smoothness_factors)\n self.x_coas_per_cell.append(x_coas)\n self.x_cils_per_cell.append(x_cils)\n\n def execute_system_dynamics(\n self,\n ):\n simulation_st = time.time()\n num_cells = self.num_cells\n\n environment_cells = self.env_cells\n all_cell_verts = np.array([x.curr_verts for x in environment_cells])\n\n cell_bbs = \\\n geometry.calc_init_cell_bbs(\n num_cells, all_cell_verts)\n (\n cells_node_distance_matrix,\n cells_line_segment_intersection_matrix,\n ) = geometry.init_lseg_intersects_and_dist_sq_matrices_old(\n num_cells,\n 16,\n cell_bbs,\n all_cell_verts,\n )\n\n cell_group_indices = []\n\n for a_cell in self.env_cells:\n cell_group_indices.append(a_cell.cell_group_ix)\n\n # self.writer.begin_initial_save()\n # for (ci, cell) in enumerate(self.env_cells):\n # x_cils = self.x_cils_per_cell[ci]\n # x_coas = self.x_coas_per_cell[ci]\n # cell.save_with_writer(x_cils, x_coas, self.writer)\n # self.writer.finish_initial_save()\n\n for t in self.timepoints:\n self.writer.begin_tpoint_save(t)\n (\n cells_node_distance_matrix,\n cell_bbs,\n cells_line_segment_intersection_matrix,\n all_cell_verts,\n ) = self.execute_system_dynamics_in_random_sequence(\n t,\n cells_node_distance_matrix,\n cell_bbs,\n cells_line_segment_intersection_matrix,\n all_cell_verts,\n environment_cells,\n )\n self.writer.finish_tpoint_save()\n\n simulation_et = time.time()\n self.writer.finish()\n\n simulation_time = np.round(simulation_et - simulation_st, decimals=2)\n\n print(\n (\"Time taken to complete simulation: {}s\".format(simulation_time))\n )\n\n# -----------------------------------------------------------------\n"
] |
[
[
"numpy.linspace",
"numpy.arange",
"numpy.cos",
"numpy.sin",
"numpy.round",
"numpy.ceil",
"numpy.copy",
"numpy.sign",
"numpy.average",
"numpy.array",
"numpy.zeros"
]
] |
garcia-science/pt_fluids
|
[
"7153d6b0f733e94b07e36299936b93635e392dbe"
] |
[
"visualizacion.py"
] |
[
"from matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom matplotlib.colors import TwoSlopeNorm\nimport numpy as np\nfrom directorios import *\n\n\ndef visualizacion(*args, tipo, guardar, path, file, nombre, **kwargs):\n if 'xlabel' not in kwargs:\n xlabel = ' '\n else:\n xlabel = kwargs['xlabel']\n if 'ylabel' not in kwargs:\n ylabel = ' '\n else:\n ylabel = kwargs['ylabel']\n if 'zlabel' not in kwargs:\n zlabel = ' '\n else:\n zlabel = kwargs['zlabel']\n if 'x_scale' not in kwargs:\n xscale = 'linear'\n else:\n xscale = kwargs['xscale']\n if 'yscale' not in kwargs:\n yscale = 'linear'\n else:\n yscale = kwargs['yscale']\n if 'titulo' not in kwargs:\n titulo = 'Agregar Título'\n else:\n titulo = kwargs['titulo']\n if 'color' not in kwargs:\n color = 'b'\n else:\n color = kwargs['color']\n if 'linestyle' not in kwargs:\n linestyle = '-'\n else:\n linestyle = kwargs['linestyle']\n if 'linewidth' not in kwargs:\n linewidth = 1\n else:\n linewidth = kwargs['linewidth']\n if 'cmap' not in kwargs:\n cmap = 'plasma'\n else:\n cmap = kwargs['cmap']\n if 'vmin' not in kwargs:\n vmin = 'default'\n else:\n vmin = kwargs['vmin']\n if 'vzero' not in kwargs:\n vzero = 'default'\n else:\n vzero = kwargs['vzero']\n if 'vmax' not in kwargs:\n vmax = 'default'\n else:\n vmax = kwargs['vmax']\n if tipo == \"2D\":\n X = args[0]\n Y = args[1]\n plt.plot(X, Y, color=color, linestyle=linestyle, linewidth=linewidth)\n plt.xlabel(xlabel, fontsize=15)\n plt.ylabel(ylabel, fontsize=15)\n plt.xscale(xscale)\n plt.yscale(yscale)\n plt.title(titulo)\n plt.grid(color='silver', linestyle='--', linewidth=0.5)\n if guardar == 'si':\n plt.savefig(path + file + '\\\\' + nombre)\n elif tipo == \"2D_multiple\":\n X = args[0]\n Ys = args[1]\n if len(args) == 2:\n linestyles = ['-'] * len(Ys)\n colors = [(np.random.rand(3,))] * len(Ys)\n elif len(args) == 3:\n colors = [(np.random.rand(3,))] * len(Ys)\n else:\n colors = args[2]\n linestyles = args[3]\n for i in range(len(Ys)):\n plt.plot(X, Ys[i], linestyle=linestyles[i], color=colors[i])\n plt.xlabel(xlabel, fontsize=15)\n plt.ylabel(ylabel, fontsize=15)\n plt.xscale(xscale)\n plt.yscale(yscale)\n plt.title(titulo)\n plt.grid(color='silver', linestyle='--', linewidth=0.5)\n if guardar == 'si':\n plt.savefig(path + file + '\\\\' + nombre)\n elif tipo == \"colormap\":\n X = args[0]\n Y = args[1]\n Z = args[2]\n if vmin == 'default' and np.amax(Z) > 0 > np.amin(Z):\n vmin = np.amin(Z)\n vzero = 0\n vmax = np.amax(Z)\n else:\n vmin = np.amin(Z)\n vmax = np.amax(Z)\n vzero = (vmin + vmax)/2\n ax = plt.gca()\n norm = TwoSlopeNorm(vmin=vmin, vcenter=vzero, vmax=vmax)\n pcm = ax.pcolormesh(X, Y, Z, cmap=cmap, norm=norm, shading='auto')\n cbar = plt.colorbar(pcm, shrink=1)\n cbar.set_label(zlabel, rotation=90, fontsize=15)\n plt.xlabel(xlabel, fontsize=15)\n plt.ylabel(ylabel, fontsize=15)\n plt.title(titulo)\n if guardar == 'si':\n plt.savefig(path + file + '\\\\' + nombre)\n elif tipo == \"3D\":\n X = args[0]\n Y = args[1]\n Z = args[2]\n XX, YY = np.meshgrid(X, Y)\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=cmap, linewidth=0, antialiased=False)\n plt.title(titulo)\n fig.colorbar(surf, shrink=0.5, aspect=5)\n if guardar == 'si':\n plt.savefig(path + file + '\\\\' + nombre)\n elif tipo == \"animacion\":\n campo = args[0]\n x = args[1]\n Nt = args[2]\n fig = plt.figure()\n lines = plt.plot([])\n line = lines[0]\n # other setuo\n plt.xlim(x[0], x[-1])\n plt.ylim(1.1 * np.amax(campo), 1.1 * np.amin(campo))\n plt.xlabel(kwargs['xlabel'], fontsize=15)\n plt.ylabel(kwargs['ylabel'], fontsize=15)\n plt.title(kwargs['titulo'])\n plt.grid(color='silver', linestyle='--', linewidth=0.5)\n def animate(frame):\n y = campo[100 * frame, :]\n line.set_data((x, y))\n anim = FuncAnimation(fig, animate, frames=int(Nt / 100), interval=60)\n if guardar == 'si':\n anim.save(path + file + '\\\\' + nombre + '.gif', fps=100)\n return anim"
] |
[
[
"matplotlib.pyplot.gca",
"numpy.amax",
"matplotlib.pyplot.title",
"numpy.amin",
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"matplotlib.colors.TwoSlopeNorm",
"matplotlib.pyplot.xlim",
"numpy.random.rand",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"numpy.meshgrid",
"matplotlib.pyplot.ylabel"
]
] |
Intelligent-Systems-Laboratory/cvat
|
[
"e2c5d70348001ffd3b0fdce6b4ea06bb95260d68"
] |
[
"cvat/apps/engine/efficientcut.py"
] |
[
"import cv2\nimport os\nimport numpy as np\nimport time\nimport torch\nfrom torch.backends import cudnn\nfrom matplotlib import colors\nfrom cvat.apps.engine.backbone import EfficientDetBackbone\nfrom cvat.apps.engine.efficientdet.utils import BBoxTransform, ClipBoxes\nfrom cvat.apps.engine.efficientdet_utils.utils import preprocess, invert_affine, postprocess, STANDARD_COLORS, standard_to_bgr, get_index_label, plot_one_box\nimport os\n\nimport pathlib\n\nos.environ['DISPLAY'] = ':0'\ndef efficientcut(frame_img,ROI):\n #frame_img is a cv2.read output and ROI is a box defined by (xtl,ytl,xbr,ybr) or cv2.rect\n input_image = np.array(frame_img[ROI[1]:ROI[3], ROI[0]:ROI[2]])\n compound_coef = 0 # set to the model weights coefficient\n force_input_size = None # set None to use default size\n\n # replace this part with your project's anchor config\n anchor_ratios = [(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)]\n anchor_scales = [2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]\n\n threshold = 0.2 # used to determine minimum allowable cofidence coefficient\n iou_threshold = 0.2 # used to determine the IOU threshold\n\n use_cuda = True\n use_float16 = False\n cudnn.fastest = True\n cudnn.benchmark = True\n\n obj_list = ['car', 'suv', 'van', 'truck', 'motorcycle', 'bicycle', 'tricycle', 'jeep', # classes\n 'bus']\n\n color_list = standard_to_bgr(STANDARD_COLORS)\n # tf bilinear interpolation is different from any other's, just make do\n input_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536, 1536]\n input_size = input_sizes[compound_coef] if force_input_size is None else force_input_size\n ori_imgs, framed_imgs, framed_metas = preprocess(input_image, max_size=input_size)\n\n if use_cuda:\n x = torch.stack([torch.from_numpy(fi).cuda() for fi in framed_imgs], 0)\n else:\n x = torch.stack([torch.from_numpy(fi) for fi in framed_imgs], 0)\n\n x = x.to(torch.float32 if not use_float16 else torch.float16).permute(0, 3, 1, 2)\n\n model = EfficientDetBackbone(compound_coef=compound_coef, num_classes=len(obj_list),\n ratios=anchor_ratios, scales=anchor_scales)\n path = os.path.abspath(\"./\")\n model_path = os.path.join(path,'cvat/apps/engine/efficientdet-d0_best.pth')\n # print('path',model_path)\n model.load_state_dict(torch.load(model_path, map_location='cpu')) # add path to weights here\n model.requires_grad_(False)\n model.eval()\n\n if use_cuda:\n model = model.cuda()\n if use_float16:\n model = model.half()\n\n with torch.no_grad():\n features, regression, classification, anchors = model(x)\n\n regressBoxes = BBoxTransform()\n clipBoxes = ClipBoxes()\n\n out = postprocess(x,\n anchors, regression, classification,\n regressBoxes, clipBoxes,\n threshold, iou_threshold)\n\n out = invert_affine(framed_metas, out)\n # get maximum confidence level only\n finalbox_index = np.where(out[0]['scores'] == max(out[0]['scores']))\n final_bbox = out[0]['rois'][finalbox_index]\n final_bbox[0][0] = final_bbox[0][0]+ROI[0]\n final_bbox[0][1] = final_bbox[0][1]+ROI[1]\n final_bbox[0][2] = final_bbox[0][2]+ROI[0]\n final_bbox[0][3] = final_bbox[0][3]+ROI[1]\n return final_bbox[0]\n"
] |
[
[
"numpy.array",
"torch.no_grad",
"torch.from_numpy",
"torch.load"
]
] |
xhosaBoy/HypER-normalised-relations
|
[
"8809e5d3781e2c8bc3e7e724725b5c47ea9694da"
] |
[
"HypER/models.py"
] |
[
"import torch\nfrom torch.nn import functional as F, Parameter\nfrom torch.nn.init import xavier_normal_, xavier_uniform_\n\n\nclass ConvE(torch.nn.Module):\n def __init__(self, d, d1, d2, **kwargs):\n super(ConvE, self).__init__()\n self.in_channels = kwargs[\"in_channels\"]\n self.out_channels = kwargs[\"out_channels\"]\n self.filt_h = kwargs[\"filt_h\"]\n self.filt_w = kwargs[\"filt_w\"]\n\n self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n self.R = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)\n self.inp_drop = torch.nn.Dropout(kwargs[\"input_dropout\"])\n self.hidden_drop = torch.nn.Dropout(kwargs[\"hidden_dropout\"])\n self.feature_map_drop = torch.nn.Dropout2d(kwargs[\"feature_map_dropout\"])\n self.loss = torch.nn.BCELoss()\n\n self.conv1 = torch.nn.Conv2d(self.in_channels, self.out_channels, (self.filt_h, self.filt_w), 1, 0, bias=True)\n self.bn0 = torch.nn.BatchNorm2d(self.in_channels)\n self.bn1 = torch.nn.BatchNorm2d(self.out_channels)\n self.bn2 = torch.nn.BatchNorm1d(d1)\n self.register_parameter('b', Parameter(torch.zeros(len(d.entities))))\n fc_length = (20 - self.filt_h + 1) * (20 - self.filt_w + 1) * self.out_channels\n self.fc = torch.nn.Linear(fc_length, d1)\n\n def init(self):\n xavier_normal_(self.E.weight.data)\n xavier_normal_(self.R.weight.data)\n\n def forward(self, e1_idx, r_idx):\n e1 = self.E(e1_idx).view(-1, 1, 10, 20)\n r = self.R(r_idx).view(-1, 1, 10, 20)\n x = torch.cat([e1, r], 2)\n x = self.bn0(x)\n x= self.inp_drop(x)\n x= self.conv1(x)\n x= self.bn1(x)\n x= F.relu(x)\n x = self.feature_map_drop(x)\n x = x.view(e1.size(0), -1)\n x = self.fc(x)\n x = self.hidden_drop(x)\n x = self.bn2(x)\n x = F.relu(x)\n x = torch.mm(x, self.E.weight.transpose(1,0))\n x += self.b.expand_as(x)\n\n pred = F.sigmoid(x)\n\n return pred\n\n\nclass HypER(torch.nn.Module):\n def __init__(self, d, d1, d2, **kwargs):\n super(HypER, self).__init__()\n\n self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n self.R = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)\n\n self.in_channels = kwargs[\"in_channels\"]\n self.out_channels = kwargs[\"out_channels\"]\n self.filt_h = kwargs[\"filt_h\"]\n self.filt_w = kwargs[\"filt_w\"]\n\n fc_length = (1 - self.filt_h + 1) * (d1 - self.filt_w + 1) * self.out_channels\n self.fc = torch.nn.Linear(fc_length, d1)\n fc1_length = self.in_channels * self.out_channels * self.filt_h * self.filt_w\n self.fc1 = torch.nn.Linear(d2, fc1_length)\n\n self.inp_drop = torch.nn.Dropout(kwargs[\"input_dropout\"])\n self.hidden_drop = torch.nn.Dropout(kwargs[\"hidden_dropout\"])\n self.feature_map_drop = torch.nn.Dropout2d(kwargs[\"feature_map_dropout\"])\n\n self.bn0 = torch.nn.BatchNorm2d(self.in_channels)\n self.bn1 = torch.nn.BatchNorm2d(self.out_channels)\n self.bn2 = torch.nn.BatchNorm1d(d2)\n self.bn3 = torch.nn.BatchNorm1d(d1)\n\n self.register_parameter('b', Parameter(torch.zeros(len(d.entities))))\n\n self.loss = torch.nn.BCELoss()\n\n def init(self):\n xavier_normal_(self.E.weight.data)\n xavier_normal_(self.R.weight.data)\n\n def forward(self, e1_idx, r_idx):\n\n e1 = self.E(e1_idx).view(-1, 1, 1, self.E.weight.size(1))\n\n # Convolutional input regularisation\n x = self.bn0(e1)\n x = self.inp_drop(x)\n\n r = self.R(r_idx)\n\n # Convolutional filter regularisation\n r = self.bn2(r)\n r = self.inp_drop(r)\n\n k = self.fc1(r)\n\n x = x.permute(1, 0, 2, 3)\n\n k = k.view(-1, self.in_channels, self.out_channels, self.filt_h, self.filt_w)\n k = k.view(e1.size(0) * self.in_channels * self.out_channels, 1, self.filt_h, self.filt_w)\n\n x = F.conv2d(x, k, groups=e1.size(0))\n\n x = x.view(e1.size(0), 1, self.out_channels, 1 - self.filt_h + 1, e1.size(3) - self.filt_w + 1)\n x = x.permute(0, 3, 4, 1, 2)\n x = torch.sum(x, dim=3)\n x = x.permute(0, 3, 1, 2).contiguous()\n\n # Feature map regularisation\n x = self.bn1(x)\n x = self.feature_map_drop(x)\n\n x = x.view(e1.size(0), -1)\n\n x = self.fc(x)\n x = F.relu(x)\n\n # Hidden layer regularisation\n x = self.hidden_drop(x)\n\n x = torch.mm(x, self.E.weight.transpose(1,0))\n x += self.b.expand_as(x)\n\n pred = F.sigmoid(x)\n\n return pred\n\n\nclass HypE(torch.nn.Module):\n def __init__(self, d, d1, d2, **kwargs):\n super(HypE, self).__init__()\n self.in_channels = kwargs[\"in_channels\"]\n self.out_channels = kwargs[\"out_channels\"]\n self.filt_h = kwargs[\"filt_h\"]\n self.filt_w = kwargs[\"filt_w\"]\n\n self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n r_dim = self.in_channels * self.out_channels * self.filt_h * self.filt_w\n self.R = torch.nn.Embedding(len(d.relations), r_dim, padding_idx=0)\n self.inp_drop = torch.nn.Dropout(kwargs[\"input_dropout\"])\n self.hidden_drop = torch.nn.Dropout(kwargs[\"hidden_dropout\"])\n self.feature_map_drop = torch.nn.Dropout2d(kwargs[\"feature_map_dropout\"])\n self.loss = torch.nn.BCELoss()\n\n self.bn0 = torch.nn.BatchNorm2d(self.in_channels)\n self.bn1 = torch.nn.BatchNorm2d(self.out_channels)\n self.bn2 = torch.nn.BatchNorm1d(d1)\n self.register_parameter('b', Parameter(torch.zeros(len(d.entities))))\n fc_length = (10 - self.filt_h + 1) * (20 - self.filt_w + 1) * self.out_channels\n self.fc = torch.nn.Linear(fc_length, d1)\n\n def init(self):\n xavier_normal_(self.E.weight.data)\n xavier_normal_(self.R.weight.data)\n\n def forward(self, e1_idx, r_idx):\n e1 = self.E(e1_idx).view(-1, 1, 10, 20)\n r = self.R(r_idx)\n x = self.bn0(e1)\n x = self.inp_drop(x)\n\n k = r.view(-1, self.in_channels, self.out_channels, self.filt_h, self.filt_w)\n k = k.view(e1.size(0) * self.in_channels * self.out_channels, 1, self.filt_h, self.filt_w)\n\n x = x.permute(1, 0, 2, 3)\n\n x = F.conv2d(x, k, groups=e1.size(0))\n x = x.view(e1.size(0), 1, self.out_channels, 10 - self.filt_h + 1, 20 - self.filt_w + 1)\n x = x.permute(0, 3, 4, 1, 2)\n x = torch.sum(x, dim=3)\n x = x.permute(0, 3, 1, 2).contiguous()\n \n x = self.bn1(x)\n x = self.feature_map_drop(x) \n x = x.view(e1.size(0), -1) \n x = self.fc(x)\n x = self.hidden_drop(x)\n x = self.bn2(x)\n x = F.relu(x) \n x = torch.mm(x, self.E.weight.transpose(1, 0))\n x += self.b.expand_as(x)\n\n pred = F.sigmoid(x)\n\n return pred\n\n\nclass DistMult(torch.nn.Module):\n def __init__(self, d, d1, d2, **kwargs):\n super(DistMult, self).__init__()\n self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n self.R = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)\n self.inp_drop = torch.nn.Dropout(kwargs[\"input_dropout\"])\n self.loss = torch.nn.BCELoss()\n self.bn0 = torch.nn.BatchNorm1d(d1)\n\n def init(self):\n xavier_normal_(self.E.weight.data)\n xavier_normal_(self.R.weight.data)\n\n def forward(self, e1_idx, r_idx):\n e1 = self.E(e1_idx)\n r = self.R(r_idx)\n e1 = self.bn0(e1)\n e1 = self.inp_drop(e1)\n\n pred = torch.mm(e1 * r, self.E.weight.transpose(1, 0))\n pred = F.sigmoid(pred)\n\n return pred\n\n\nclass ComplEx(torch.nn.Module):\n def __init__(self, d, d1, d2, **kwargs):\n super(ComplEx, self).__init__()\n self.Er = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n self.Rr = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)\n self.Ei = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)\n self.Ri = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)\n self.inp_drop = torch.nn.Dropout(kwargs[\"input_dropout\"])\n self.loss = torch.nn.BCELoss()\n self.bn0 = torch.nn.BatchNorm1d(d1)\n self.bn1 = torch.nn.BatchNorm1d(d1)\n\n def init(self):\n xavier_normal_(self.Er.weight.data)\n xavier_normal_(self.Rr.weight.data)\n xavier_normal_(self.Ei.weight.data)\n xavier_normal_(self.Ri.weight.data)\n\n def forward(self, e1_idx, r_idx):\n e1r = self.Er(e1_idx)\n rr = self.Rr(r_idx)\n e1i = self.Ei(e1_idx)\n ri = self.Ri(r_idx)\n e1r = self.bn0(e1r)\n e1r = self.inp_drop(e1r)\n e1i = self.bn1(e1i)\n e1i = self.inp_drop(e1i)\n\n pred = torch.mm(e1r * rr, self.Er.weight.transpose(1, 0)) \\\n + torch.mm(e1r * ri, self.Ei.weight.transpose(1, 0)) \\\n + torch.mm(e1i * rr, self.Ei.weight.transpose(1, 0)) \\\n - torch.mm(e1i * ri, self.Er.weight.transpose(1, 0))\n\n pred = F.sigmoid(pred)\n\n return pred\n\n"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.nn.Dropout2d",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.sum",
"torch.nn.BCELoss",
"torch.nn.Linear",
"torch.nn.functional.sigmoid",
"torch.nn.functional.relu",
"torch.nn.BatchNorm2d"
]
] |
rainbean/Container_TensorFlow
|
[
"af3fc40dd281a0971ace3c15fb9e7a636ce19273"
] |
[
"jupyter/startup.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nmpl.rcParams['figure.figsize'] = [20, 10]\nnp.set_printoptions(linewidth=200)\n"
] |
[
[
"numpy.set_printoptions"
]
] |
TauferLab/llnl-hatchet
|
[
"c7d12888d71d2b23058facd3025e7dcfa12cbb39"
] |
[
"hatchet/readers/pyinstrument_reader.py"
] |
[
"# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other\n# Hatchet Project Developers. See the top-level LICENSE file for details.\n#\n# SPDX-License-Identifier: MIT\n\nimport json\n\nimport pandas as pd\n\nimport hatchet.graphframe\nfrom hatchet.node import Node\nfrom hatchet.graph import Graph\nfrom hatchet.frame import Frame\n\n\nclass PyinstrumentReader:\n def __init__(self, filename):\n self.pyinstrument_json_filename = filename\n self.graph_dict = {}\n self.list_roots = []\n self.node_dicts = []\n\n def create_graph(self):\n def parse_node_literal(child_dict, hparent):\n \"\"\"Create node_dict for one node and then call the function\n recursively on all children.\"\"\"\n\n hnode = Node(\n Frame({\"name\": child_dict[\"function\"], \"type\": \"function\"}), hparent\n )\n\n child_node_dict = {\n \"node\": hnode,\n \"name\": child_dict[\"function\"],\n \"file\": child_dict[\"file_path_short\"],\n \"line\": child_dict[\"line_no\"],\n \"time\": child_dict[\"time\"],\n \"time (inc)\": child_dict[\"time\"],\n \"is_application_code\": child_dict[\"is_application_code\"],\n }\n\n hparent.add_child(hnode)\n self.node_dicts.append(child_node_dict)\n\n if \"children\" in child_dict:\n for child in child_dict[\"children\"]:\n # Pyinstrument's time metric actually stores inclusive time.\n # To calculate exclusive time, we subtract the children's time\n # from the parent's time.\n child_node_dict[\"time\"] -= child[\"time\"]\n parse_node_literal(child, hnode)\n\n # start with creating a node_dict for each root\n graph_root = Node(\n Frame(\n {\"name\": self.graph_dict[\"root_frame\"][\"function\"], \"type\": \"function\"}\n ),\n None,\n )\n\n node_dict = {\n \"node\": graph_root,\n \"name\": self.graph_dict[\"root_frame\"][\"function\"],\n \"file\": self.graph_dict[\"root_frame\"][\"file_path_short\"],\n \"line\": self.graph_dict[\"root_frame\"][\"line_no\"],\n \"time\": self.graph_dict[\"root_frame\"][\"time\"],\n \"time (inc)\": self.graph_dict[\"root_frame\"][\"time\"],\n \"is_application_code\": self.graph_dict[\"root_frame\"][\"is_application_code\"],\n }\n\n self.node_dicts.append(node_dict)\n self.list_roots.append(graph_root)\n\n # call recursively on all children of root\n if \"children\" in self.graph_dict[\"root_frame\"]:\n for child in self.graph_dict[\"root_frame\"][\"children\"]:\n # Pyinstrument's time metric actually stores inclusive time.\n # To calculate exclusive time, we subtract the children's time\n # from the parent's time.\n node_dict[\"time\"] -= child[\"time\"]\n parse_node_literal(child, graph_root)\n\n graph = Graph(self.list_roots)\n graph.enumerate_traverse()\n\n return graph\n\n def read(self):\n with open(self.pyinstrument_json_filename) as pyinstrument_json:\n self.graph_dict = json.load(pyinstrument_json)\n\n graph = self.create_graph()\n\n dataframe = pd.DataFrame(data=self.node_dicts)\n dataframe.set_index([\"node\"], inplace=True)\n dataframe.sort_index(inplace=True)\n\n return hatchet.graphframe.GraphFrame(graph, dataframe, [\"time\"], [\"time (inc)\"])\n"
] |
[
[
"pandas.DataFrame"
]
] |
tranmanhdat/tts_vn
|
[
"3a72beb66099f1b5ed6c24c625085b46628997a0"
] |
[
"encoder/preprocess.py"
] |
[
"import os\n\nfrom multiprocess.pool import ThreadPool\nfrom encoder.params_data import *\nfrom encoder.config import librispeech_datasets, anglophone_nationalites\nfrom datetime import datetime\nfrom encoder import audio\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport numpy as np\n\n\nclass DatasetLog:\n \"\"\"\n Registers metadata about the dataset in a text file.\n \"\"\"\n def __init__(self, root, name):\n self.text_file = open(Path(root, \"Log_%s.txt\" % name.replace(\"/\", \"_\")), \"w\")\n self.sample_data = dict()\n \n start_time = str(datetime.now().strftime(\"%A %d %B %Y at %H:%M\"))\n self.write_line(\"Creating dataset %s on %s\" % (name, start_time))\n self.write_line(\"-----\")\n self._log_params()\n \n def _log_params(self):\n from encoder import params_data\n self.write_line(\"Parameter values:\")\n for param_name in (p for p in dir(params_data) if not p.startswith(\"__\")):\n value = getattr(params_data, param_name)\n self.write_line(\"\\t%s: %s\" % (param_name, value))\n self.write_line(\"-----\")\n \n def write_line(self, line):\n self.text_file.write(\"%s\\n\" % line)\n \n def add_sample(self, **kwargs):\n for param_name, value in kwargs.items():\n if not param_name in self.sample_data:\n self.sample_data[param_name] = []\n self.sample_data[param_name].append(value)\n \n def finalize(self):\n self.write_line(\"Statistics:\")\n for param_name, values in self.sample_data.items():\n self.write_line(\"\\t%s:\" % param_name)\n self.write_line(\"\\t\\tmin %.3f, max %.3f\" % (np.min(values), np.max(values)))\n self.write_line(\"\\t\\tmean %.3f, median %.3f\" % (np.mean(values), np.median(values)))\n self.write_line(\"-----\")\n end_time = str(datetime.now().strftime(\"%A %d %B %Y at %H:%M\"))\n self.write_line(\"Finished on %s\" % end_time)\n self.text_file.close()\n \n \ndef _init_preprocess_dataset(dataset_name, datasets_root, out_dir) -> (Path, DatasetLog):\n dataset_root = datasets_root.joinpath(dataset_name)\n if not dataset_root.exists():\n print(\"Couldn\\'t find %s, skipping this dataset.\" % dataset_root)\n return None, None\n return dataset_root, DatasetLog(out_dir, dataset_name)\n\n\ndef _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, extension,\n skip_existing, logger):\n print(\"%s: Preprocessing data for %d lst.\" % (dataset_name, len(speaker_dirs)))\n \n # Function to preprocess utterances for one speaker\n def preprocess_speaker(speaker_dir: Path):\n # Give a name to the speaker that includes its dataset\n speaker_name = \"_\".join(speaker_dir.relative_to(datasets_root).parts)\n speaker_name = str(speaker_dir).split(\"/\")[-1].split(\".\")[0]\n # print(\"speaker_name \" +str(speaker_name))\n # Create an output directory with that name, as well as a txt file containing a \n # reference to each source file.\n speaker_out_dir = out_dir.joinpath(speaker_name)\n # speaker_out_dir = out_dir\n # print(\"speaker_out_dir \" + str(speaker_out_dir))\n speaker_out_dir.mkdir(exist_ok=True)\n sources_fpath = speaker_out_dir.joinpath(\"_sources.txt\")\n # print(\"sources_fpath \" + str(sources_fpath))\n # There's a possibility that the preprocessing was interrupted earlier, check if \n # there already is a sources file.\n if sources_fpath.exists():\n try:\n with sources_fpath.open(\"r\") as sources_file:\n existing_fnames = {line.split(\",\")[0] for line in sources_file}\n except:\n existing_fnames = {}\n else:\n existing_fnames = {}\n \n # Gather all audio files for that speaker recursively\n sources_file = sources_fpath.open(\"a\" if skip_existing else \"w\")\n # for in_fpath in speaker_dir.glob(\"**/*.%s\" % extension):\n with open(speaker_dir, \"r\") as f_read:\n for line in f_read:\n in_fpath = line.split(\"\\t\")[1]\n elements = in_fpath.split(\"/\")\n out_fname = \"/\".join(elements[elements.index(\"speech_data\")+1:])\n # Check if the target output file already exists\n # out_fname = \"_\".join(in_fpath.relative_to(speaker_dir).parts)\n out_fname = out_fname.replace(\".%s\" % extension, \".npy\")\n if skip_existing and out_fname in existing_fnames:\n continue\n\n # Load and preprocess the waveform\n wav = audio.preprocess_wav(in_fpath)\n if len(wav) == 0:\n continue\n\n # Create the mel spectrogram, discard those that are too short\n frames = audio.wav_to_mel_spectrogram(wav)\n if len(frames) < partials_n_frames:\n continue\n\n out_fpath = speaker_out_dir.joinpath(out_fname)\n path_folder = \"/\".join(str(out_fpath).split(\"/\")[:-1])\n os.makedirs(path_folder, exist_ok=True)\n np.save(out_fpath, frames)\n logger.add_sample(duration=len(wav) / sampling_rate)\n sources_file.write(\"%s,%s\\n\" % (out_fname, in_fpath))\n sources_file.close()\n \n # Process the utterances for each speaker\n with ThreadPool(20) as pool:\n list(tqdm(pool.imap(preprocess_speaker, speaker_dirs), dataset_name, len(speaker_dirs),\n unit=\"speakers\"))\n logger.finalize()\n print(\"Done preprocessing %s.\\n\" % dataset_name)\n\n\ndef preprocess_librispeech(datasets_root: Path, out_dir: Path, skip_existing=False):\n dataset_name = \"\"\n # Initialize the preprocessing\n dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir)\n if not dataset_root:\n return\n\n # Preprocess all speakers\n speaker_dirs = list(dataset_root.glob(\"*.lst\"))\n print(speaker_dirs)\n _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, \"wav\",\n skip_existing, logger)"
] |
[
[
"numpy.min",
"numpy.median",
"numpy.save",
"numpy.max",
"numpy.mean"
]
] |
Patte1808/moda
|
[
"312c9594754ae0f6d17cbfafaa2c4c790c58efe5"
] |
[
"moda/models/twitter/twitter_trendiness_detector.py"
] |
[
"import numpy as np\nimport pandas as pd\n\nfrom moda.models.trend_detector import AbstractTrendDetector, MIN_SAMPLES_PER_CATEGORY\nfrom moda.models.twitter.anomaly_detect_ts import anomaly_detect_ts\n\n\nclass TwitterAnomalyTrendinessDetector(AbstractTrendDetector):\n GENERAL_CATEGORY = 'general'\n\n __name__ = 'TwitterAnomalyTrendinessDetector'\n\n def __init__(self, freq, seasonality_freq=7, is_multicategory=False, min_value = None, max_anoms=0.1, direction=\"pos\", alpha=0.05,\n only_last=None,resample = True,\n threshold=None, e_value=False, longterm=False, piecewise_median_period_weeks=2):\n super(TwitterAnomalyTrendinessDetector, self).__init__(freq, is_multicategory,resample)\n self.seasonality_freq = seasonality_freq\n self.min_value = min_value\n self.piecewise_median_period_weeks = piecewise_median_period_weeks\n self.longterm = longterm\n self.e_value = e_value\n self.threshold = threshold\n self.only_last = only_last\n self.alpha = alpha\n self.direction = direction\n self.max_anoms = max_anoms\n self.results = None\n\n def fit_one_category(self, dataset, category=None, verbose=False):\n x = dataset['value']\n\n try:\n model_result = anomaly_detect_ts(x, period=self.seasonality_freq, max_anoms=self.max_anoms,\n direction=self.direction, alpha=self.alpha,\n only_last=self.only_last, threshold=self.threshold, e_value=self.e_value,\n longterm=self.longterm,\n piecewise_median_period_weeks=self.piecewise_median_period_weeks)\n\n anomalies = model_result['anoms'].to_frame('anomalies')\n if 'anomalies' in dataset:\n dataset = dataset.drop(columns=['anomalies'])\n\n if len(anomalies) == 0:\n dataset_with_pred = dataset\n dataset_with_pred['anomalies'] = np.nan\n else:\n dataset_with_pred = pd.merge(dataset, anomalies, how='left', right_index=True, left_index=True)\n\n dataset_with_pred['prediction'] = np.where(np.isnan(dataset_with_pred['anomalies']), 0, 1)\n\n except Exception as e:\n print(e)\n dataset_with_pred = dataset\n dataset_with_pred['prediction'] = 0\n\n\n if self.min_value is not None:\n dataset_with_pred['prediction'] = np.where(dataset_with_pred['value'] < self.min_value,0,dataset_with_pred['prediction'])\n\n self.input_data[category] = dataset_with_pred\n\n return dataset_with_pred\n\n def predict_one_category(self, X, category):\n results = self.input_data.get(category)\n\n if results is None:\n test = X\n else:\n test = pd.concat([results, X], sort=True)\n test = test[~test.index.duplicated(keep='first')]\n\n ## We have to fit the entire datasets again (train+test) as we can't compute anomalies iteratively\n if len(test) > MIN_SAMPLES_PER_CATEGORY:\n test = self.fit_one_category(test, category)\n\n return test\n\n\n def plot_one_category(self, category=None, labels=None):\n import matplotlib.pyplot as plt\n\n if self.input_data is None:\n print(\"Empty datasets\")\n return None\n\n if len(self.input_data) == 0:\n print(\"Empty datasets\")\n return None\n\n if category not in self.input_data.keys():\n print(\"Empty datasets\")\n\n def ts_subplot(plt, series, label):\n plt.plot(series, label=label, linewidth=0.5)\n plt.legend(loc='best')\n plt.xticks(rotation=90)\n\n plt.subplot(411)\n ts_subplot(plt, self.input_data[category]['value'], label='Original')\n plt.subplot(412)\n ts_subplot(plt, self.input_data[category]['prediction'], label='Prediction')\n if (labels is None) and ('label' in self.input_data[category]):\n labels = self.input_data[category]['label']\n\n if labels is not None:\n plt.subplot(413)\n ts_subplot(plt, labels, label='Labels')\n\n diff = labels - self.input_data[category]['prediction']\n plt.subplot(414)\n ts_subplot(plt, diff, label='Difference between labeled and predicted')\n\n if category is None:\n plt.suptitle(\"Twitter anomaly detection results for threshold (std)=\" + str(\n self.threshold) + \", max_anoms=\" + str(self.max_anoms))\n else:\n plt.suptitle(\"Twitter anomaly detection results for category = \" + category + \", threshold (std)=\" + str(\n self.threshold) + \", max_anoms=\" + str(self.max_anoms))\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.concat",
"pandas.merge",
"numpy.isnan",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xticks",
"numpy.where"
]
] |
FrappucinoGithub/school_meal_forecast_xgboost
|
[
"ebb10a8395b9b8158685953b030e664337cf20e0"
] |
[
"tests/calculators/test_strikes.py"
] |
[
"#!/usr/bin/python3\nimport unittest\n\nimport pandas as pd\n\nimport app.calculators as calc\n\n\nclass TestStrikes(unittest.TestCase):\n # pylint: disable=too-many-statements\n def test_add_feature_strikes(self):\n dtf = pd.DataFrame({\n 'index_date': [\"2011-12-15\", \"2017-09-04\"],\n 'date_col': [\"2011-12-15\", \"2017-09-04\"]})\n dtf.set_index('index_date', inplace=True)\n\n train_dtf = calc.add_feature_strikes(dtf.copy(), \"%Y-%m-%d\", \"tests/data\")\n\n self.assertTrue('date_col' in train_dtf)\n self.assertEqual(train_dtf.shape, (2, 2))\n self.assertEqual(train_dtf[train_dtf['greve'] == 0]['date_col'].iloc[0], '2017-09-04')\n self.assertEqual(train_dtf[train_dtf['greve'] == 1]['date_col'].iloc[0], '2011-12-15')\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"pandas.DataFrame"
]
] |
brunoklaus/PS-001-ML5G-GNNetworkingChallenge2021-PARANA
|
[
"c37abbab19f05388b1ac61a3cc287ff36bdd0e19"
] |
[
"datanetAPI.py"
] |
[
"'''\n *\n * Copyright (C) 2020 Universitat Politècnica de Catalunya.\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'''\n\n# -*- coding: utf-8 -*-\n\nimport os, tarfile, numpy, math, networkx, queue, random,traceback\nfrom enum import IntEnum\n\nimport timeit\n\nclass DatanetException(Exception):\n \"\"\"\n Exceptions generated when processing dataset\n \"\"\"\n def __init__(self, msg):\n self.msg = msg\n def __str__(self):\n return self.msg\n\n\nclass TimeDist(IntEnum):\n \"\"\"\n Enumeration of the supported time distributions \n \"\"\"\n EXPONENTIAL_T = 0\n DETERMINISTIC_T = 1\n UNIFORM_T = 2\n NORMAL_T = 3\n ONOFF_T = 4\n PPBP_T = 5\n \n @staticmethod\n def getStrig(timeDist):\n if (timeDist == 0):\n return (\"EXPONENTIAL_T\")\n elif (timeDist == 1):\n return (\"DETERMINISTIC_T\")\n elif (timeDist == 2):\n return (\"UNIFORM_T\")\n elif (timeDist == 3):\n return (\"NORMAL_T\")\n elif (timeDist == 4):\n return (\"ONOFF_T\")\n elif (timeDist == 5):\n return (\"PPBP_T\")\n else:\n return (\"UNKNOWN\")\n\nclass SizeDist(IntEnum):\n \"\"\"\n Enumeration of the supported size distributions \n \"\"\"\n DETERMINISTIC_S = 0\n UNIFORM_S = 1\n BINOMIAL_S = 2\n GENERIC_S = 3\n \n @staticmethod\n def getStrig(sizeDist):\n if (sizeDist == 0):\n return (\"DETERMINISTIC_S\")\n elif (sizeDist == 1):\n return (\"UNIFORM_S\")\n elif (sizeDist == 2):\n return (\"BINOMIAL_S\")\n elif (sizeDist ==3):\n return (\"GENERIC_S\")\n else:\n return (\"UNKNOWN\")\n\nclass Sample:\n \"\"\"\n Class used to contain the results of a single iteration in the dataset\n reading process.\n \n ...\n \n Attributes\n ----------\n global_packets : double\n Overall number of packets transmitteds in network\n global_losses : double\n Overall number of packets lost in network\n global_delay : double\n Overall delay in network\n maxAvgLambda: double\n This variable is used in our simulator to define the overall traffic \n intensity of the network scenario\n performance_matrix : NxN matrix\n Matrix where each cell [i,j] contains aggregated and flow-level\n information about transmission parameters between source i and\n destination j.\n traffic_matrix : NxN matrix\n Matrix where each cell [i,j] contains aggregated and flow-level\n information about size and time distributions between source i and\n destination j.\n routing_matrix : NxN matrix\n Matrix where each cell [i,j] contains the path, if it exists, between\n source i and destination j.\n topology_object : \n Network topology using networkx format.\n port_stats: list-of-dict-of-dict data structure:\n The outer list contain a dict-of-dict for each node. The first dict contain\n the list of adjacents nodes and the last dict contain the parameters of the\n interface port.\n \n \"\"\"\n \n global_packets = None\n global_losses = None\n global_delay = None\n maxAvgLambda = None\n \n performance_matrix = None\n traffic_matrix = None\n routing_matrix = None\n topology_object = None\n port_stats = None\n \n data_set_file = None\n _results_line = None\n _traffic_line = None\n _input_files_line = None\n _status_line = None\n _flowresults_line = None\n _link_usage_line = None\n _routing_file = None\n _graph_file = None\n \n def get_global_packets(self):\n \"\"\"\n Return the number of packets transmitted in the network per time unit of this Sample instance.\n \"\"\"\n \n return self.global_packets\n\n def get_global_losses(self):\n \"\"\"\n Return the number of packets dropped in the network per time unit of this Sample instance.\n \"\"\"\n \n return self.global_losses\n \n def get_global_delay(self):\n \"\"\"\n Return the average per-packet delay over all the packets transmitted in the network in time units \n of this sample instance.\n \"\"\"\n \n return self.global_delay\n \n def get_maxAvgLambda(self):\n \"\"\"\n Returns the maxAvgLamda used in the current iteration. This variable is used in our simulator to define \n the overall traffic intensity of the network scenario.\n \"\"\"\n \n return self.maxAvgLambda\n \n def get_performance_matrix(self):\n \"\"\"\n Returns the performance_matrix of this Sample instance.\n \"\"\"\n \n return self.performance_matrix\n \n def get_srcdst_performance(self, src, dst):\n \"\"\"\n \n\n Parameters\n ----------\n src : int\n Source node.\n dst : int\n Destination node.\n\n Returns\n -------\n Dictionary\n Information stored in the Result matrix for the requested src-dst.\n\n \"\"\"\n return self.performance_matrix[src, dst]\n \n def get_traffic_matrix(self):\n \"\"\"\n Returns the traffic_matrix of this Sample instance.\n \"\"\"\n \n return self.traffic_matrix\n \n def get_srcdst_traffic(self, src, dst):\n \"\"\"\n \n\n Parameters\n ----------\n src : int\n Source node.\n dst : int\n Destination node.\n\n Returns\n -------\n Dictionary\n Information stored in the Traffic matrix for the requested src-dst.\n\n \"\"\"\n \n return self.traffic_matrix[src, dst]\n \n def get_routing_matrix(self):\n \"\"\"\n Returns the routing_matrix of this Sample instance.\n \"\"\"\n \n return self.routing_matrix\n \n def get_srcdst_routing(self, src, dst):\n \"\"\"\n \n\n Parameters\n ----------\n src : int\n Source node.\n dst : int\n Destination node.\n\n Returns\n -------\n Dictionary\n Information stored in the Routing matrix for the requested src-dst.\n\n \"\"\"\n return self.routing_matrix[src, dst]\n \n def get_topology_object(self):\n \"\"\"\n Returns the topology in networkx format of this Sample instance.\n \"\"\"\n \n return self.topology_object\n \n def get_network_size(self):\n \"\"\"\n Returns the number of nodes of the topology.\n \"\"\"\n return self.topology_object.number_of_nodes()\n \n def get_node_properties(self, id):\n \"\"\"\n \n\n Parameters\n ----------\n id : int\n Node identifier.\n\n Returns\n -------\n Dictionary with the parameters of the node\n None if node doesn't exist\n\n \"\"\"\n res = None\n \n if id in self.topology_object.nodes:\n res = self.topology_object.nodes[id] \n \n return res\n \n def get_link_properties(self, src, dst):\n \"\"\"\n \n\n Parameters\n ----------\n src : int\n Source node.\n dst : int\n Destination node.\n\n Returns\n -------\n Dictionary with the parameters of the link\n None if no link exist between src and dst\n\n \"\"\"\n res = None\n \n if dst in self.topology_object[src]:\n res = self.topology_object[src][dst][0] \n \n return res\n \n def get_srcdst_link_bandwidth(self, src, dst):\n \"\"\"\n \n\n Parameters\n ----------\n src : int\n Source node.\n dst : int\n Destination node.\n\n Returns\n -------\n Bandwidth in bits/time unit of the link between nodes src-dst or -1 if not connected\n\n \"\"\"\n if dst in self.topology_object[src]:\n cap = float(self.topology_object[src][dst][0]['bandwidth'])\n else:\n cap = -1\n \n return cap\n \n def get_port_stats(self):\n \"\"\"\n Returns the port_stats object of this Sample instance.\n \"\"\"\n if (self.port_stats == None):\n raise DatanetException(\"ERROR: The processed dataset doesn't have port performance data\")\n \n return self.port_stats\n \n \n def _set_data_set_file_name(self,file):\n \"\"\"\n Sets the data set file from where the sample is extracted.\n \"\"\"\n self.data_set_file = file\n \n def _set_performance_matrix(self, m):\n \"\"\"\n Sets the performance_matrix of this Sample instance.\n \"\"\"\n \n self.performance_matrix = m\n \n def _set_traffic_matrix(self, m):\n \"\"\"\n Sets the traffic_matrix of this Sample instance.\n \"\"\"\n \n self.traffic_matrix = m\n \n def _set_routing_matrix(self, m):\n \"\"\"\n Sets the traffic_matrix of this Sample instance.\n \"\"\"\n \n self.routing_matrix = m\n \n def _set_topology_object(self, G):\n \"\"\"\n Sets the topology_object of this Sample instance.\n \"\"\"\n \n self.topology_object = G\n \n def _set_global_packets(self, x):\n \"\"\"\n Sets the global_packets of this Sample instance.\n \"\"\"\n \n self.global_packets = x\n \n def _set_global_losses(self, x):\n \"\"\"\n Sets the global_losses of this Sample instance.\n \"\"\"\n \n self.global_losses = x\n \n def _set_global_delay(self, x):\n \"\"\"\n Sets the global_delay of this Sample instance.\n \"\"\"\n \n self.global_delay = x\n \n def _get_data_set_file_name(self):\n \"\"\"\n Gets the data set file from where the sample is extracted.\n \"\"\"\n return self.data_set_file\n \n def _get_path_for_srcdst(self, src, dst):\n \"\"\"\n Returns the path between node src and node dst.\n \"\"\"\n \n return self.routing_matrix[src, dst]\n \n def _get_timedis_for_srcdst (self, src, dst):\n \"\"\"\n Returns the time distribution of traffic between node src and node dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['TimeDist']\n \n def _get_eqlambda_for_srcdst (self, src, dst):\n \"\"\"\n Returns the equivalent lambda for the traffic between node src and node\n dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['EqLambda']\n \n def _get_timedistparams_for_srcdst (self, src, dst):\n \"\"\"\n Returns the time distribution parameters for the traffic between node\n src and node dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['TimeDistParams']\n \n def _get_sizedist_for_srcdst (self, src, dst):\n \"\"\"\n Returns the size distribution of traffic between node src and node dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['SizeDist']\n \n def _get_avgpktsize_for_srcdst_flow (self, src, dst):\n \"\"\"\n Returns the average packet size for the traffic between node src and\n node dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['AvgPktSize']\n \n def _get_sizedistparams_for_srcdst (self, src, dst):\n \"\"\"\n Returns the time distribution of traffic between node src and node dst.\n \"\"\"\n \n return self.traffic_matrix[src, dst]['SizeDistParams']\n \n def _get_resultdict_for_srcdst (self, src, dst):\n \"\"\"\n Returns the dictionary with all the information for the communication\n between node src and node dst regarding communication parameters.\n \"\"\"\n \n return self.performance_matrix[src, dst]\n \n def _get_trafficdict_for_srcdst (self, src, dst):\n \"\"\"\n Returns the dictionary with all the information for the communication\n between node src and node dst regarding size and time distribution\n parameters.\n \"\"\"\n \n return self.traffic_matrix[src, dst]\n\nclass DatanetAPI:\n \"\"\"\n Class containing all the functionalities to read the dataset line by line\n by means of an iteratos, and generate a Sample instance with the\n information gathered.\n \"\"\"\n \n def __init__ (self, data_folder, intensity_values = [], topology_sizes = [],\n shuffle=False):\n \"\"\"\n Initialization of the PasringTool instance\n\n Parameters\n ----------\n data_folder : str\n Folder where the dataset is stored.\n intensity_values : array of 1 or 2 integers\n User-defined intensity values used to constrain the reading process\n to the specified range.\n topology_sizes : array of integers\n User-defined topology sizes used to constrain the reading process\n to the specified values.\n shuffle: boolean\n Specify if all files should be shuffled. By default false\n Returns\n -------\n None.\n\n \"\"\"\n \n self.data_folder = data_folder\n self.intensity_values = intensity_values\n self.topology_sizes = topology_sizes\n self.shuffle = shuffle\n \n self._all_tuple_files = []\n self._selected_tuple_files = []\n self._graphs_dic = {}\n self._routings_dic = {}\n for root, dirs, files in os.walk(self.data_folder):\n if (\"graphs\" not in dirs or \"routings\" not in dirs):\n continue\n files.sort()\n # Extend the list of files to process\n self._all_tuple_files.extend([(root, f) for f in files if f.endswith(\"tar.gz\")])\n\n def get_available_files(self):\n \"\"\"\n Get a list of all the dataset files located in the indicated data folder\n \n Returns\n -------\n Array of tuples where each tuple is (root directory, filename)\n \n \"\"\"\n \n return (self._all_tuple_files.copy())\n \n def set_files_to_process(self, tuple_files_lst):\n \"\"\"\n Set the list of files to be processed by the iterator. The files should belong to\n the list of tuples returned by get_available_files. \n \n Parameters\n ----------\n tuple_files_lst: List of tuples\n List of tuples where each tuple is (path to file, filename)\n \"\"\"\n if not type(tuple_files_lst) is list:\n raise DatanetException(\"ERROR: The argument of set_files_to_process should be a list of tuples -> [(root_dir,file),...]\")\n for tuple in tuple_files_lst:\n if not type(tuple) is tuple or len(tuple) != 2:\n raise DatanetException(\"ERROR: The argument of set_files_to_process should be a list of tuples -> [(root_dir,file),...]\")\n if (not tuple in self._all_tuple_files):\n raise DatanetException(\"ERROR: Selected tupla not belong to the list of tuples returned by get_available_files()\")\n \n self._selected_tuple_files = tuple_files_lst.copy()\n\n def _create_routing_matrix(self, routing_file, net_size):\n \"\"\"\n\n Parameters\n ----------\n\n routing_file : str\n File where the information about routing is located.\n netSize : int\n Number of nodes of the topology\n\n Returns\n -------\n MatrixPath : NxN Matrix\n Matrix where each cell [i,j] contains the path to go from node\n i to node j.\n\n \"\"\"\n \n MatrixPath = numpy.empty((net_size, net_size), dtype=object)\n with open (routing_file) as fd:\n for line in fd:\n nodes = line.split(\";\")\n nodes = list(map(int, nodes))\n MatrixPath[nodes[0],nodes[-1]] = nodes\n \n return (MatrixPath)\n\n def _generate_graphs_dic(self, path):\n \"\"\"\n Return a dictionary with networkx objects generated from the GML\n files found in path\n \n Parameters\n ----------\n path : str\n Direcotory where the graphs files are located.\n \n Returns\n -------\n Returns a dictionary where keys are the names of GML files found in path \n and the values are the networkx object generated from the GML files.\n \n \"\"\"\n \n graphs_dic = {}\n for topology_file in os.listdir(path):\n G = networkx.read_gml(path+\"/\"+topology_file, destringizer=int)\n graphs_dic[topology_file] = G\n \n return graphs_dic\n \n def _graph_links_update(self,G,file):\n \"\"\"\n Updates the graph with the link information of the file\n \n Parameters\n ----------\n G : graph\n Graph object to be updated\n file: str\n file name that contains the information of the links to be modified: src;dst;bw (bps)\n \n Returns\n -------\n None\n \n \"\"\"\n \n try:\n fd = open(file,\"r\")\n except:\n print (\"ERROR: %s not exists\" % (file))\n exit(-1)\n \n for line in fd:\n aux = line.split(\";\")\n G[int(aux[0])][int(aux[1])][0][\"bandwidth\"] = int(aux[2])\n\n def __iter__(self):\n \"\"\"\n \n\n Yields\n ------\n s : Sample\n Sample instance containing information about the last line read\n from the dataset.\n\n \"\"\"\n \n g = None\n \n if (len(self._selected_tuple_files) > 0):\n tuple_files = self._selected_tuple_files\n else:\n tuple_files = self._all_tuple_files\n\n if self.shuffle:\n random.Random(1234).shuffle(tuple_files)\n ctr = 0\n for root, file in tuple_files:\n try:\n it = 0 \n tar = tarfile.open(os.path.join(root, file), 'r:gz')\n dir_info = tar.next()\n results_file = tar.extractfile(dir_info.name+\"/simulationResults.txt\")\n traffic_file = tar.extractfile(dir_info.name+\"/traffic.txt\")\n status_file = tar.extractfile(dir_info.name+\"/stability.txt\")\n input_files = tar.extractfile(dir_info.name+\"/input_files.txt\")\n if (dir_info.name+\"/flowSimulationResults.txt\" in tar.getnames()):\n flowresults_file = tar.extractfile(dir_info.name+\"/flowSimulationResults.txt\")\n else:\n flowresults_file = None\n if (dir_info.name+\"/linkUsage.txt\" in tar.getnames()):\n link_usage_file = tar.extractfile(dir_info.name+\"/linkUsage.txt\")\n else:\n link_usage_file = None\n while(True):\n s = Sample()\n s._set_data_set_file_name(os.path.join(root, file))\n \n s._results_line = results_file.readline().decode()[:-2]\n s._traffic_line = traffic_file.readline().decode()[:-1]\n if (flowresults_file):\n s._flowresults_line = flowresults_file.readline().decode()[:-2]\n s._status_line = status_file.readline().decode()[:-1]\n s._input_files_line = input_files.readline().decode()[:-1]\n if (link_usage_file):\n s._link_usage_line = link_usage_file.readline().decode()[:-1]\n if (len(s._results_line) == 0) or (len(s._traffic_line) == 0):\n break\n if (not \";OK;\" in s._status_line):\n print (\"Removed iteration: \"+s._status_line)\n continue;\n \n # Filter traffic intensity\n if (len(self.intensity_values) != 0):\n ptr = s._traffic_line.find('|')\n specific_intensity = float(s._traffic_line[0:ptr])\n if(specific_intensity < self.intensity_values[0]) or (specific_intensity > self.intensity_values[1]):\n continue\n \n used_files = s._input_files_line.split(';')\n s._graph_file = os.path.join(root,\"graphs\",used_files[1])\n s._routing_file = os.path.join(root,\"routings\",used_files[2])\n if (s._graph_file in self._graphs_dic):\n g = self._graphs_dic[s._graph_file]\n else:\n g = networkx.read_gml(s._graph_file, destringizer=int)\n self._graphs_dic[s._graph_file] = g\n \n # Filter topology size\n if (len(self.topology_sizes) != 0 and not len(g) in self.topology_sizes):\n continue\n \n if (len(used_files) == 4):\n self._graph_links_update(g,os.path.join(root,\"links_bw\",used_files[3]))\n \n # XXX We considerer that all graphs using the same routing file have the same topology\n if (s._routing_file in self._routings_dic):\n routing_matrix = self._routings_dic[s._routing_file]\n else:\n routing_matrix = self._create_routing_matrix(s._routing_file,len(g))\n self._routings_dic[s._routing_file] = routing_matrix\n \n s._set_routing_matrix(routing_matrix)\n s._set_topology_object(g)\n self._process_flow_results(s)\n if (s._link_usage_line):\n self._process_link_usage(s)\n it +=1\n yield s\n except (GeneratorExit,SystemExit) as e:\n raise\n except:\n #traceback.print_exc()\n print (\"Error in the file: %s iteration: %d\" % (file,it))\n \n ctr += 1\n #print(\"Progress check: %d/%d\" % (ctr,len(tuple_files)))\n \n def _process_flow_results(self, s):\n \"\"\"\n \n\n Parameters\n ----------\n s : Sample\n Instance of Sample associated with the current iteration.\n\n Returns\n -------\n None.\n\n \"\"\"\n \n q_flows = queue.Queue()\n first_params = s._results_line.split('|')[0].split(',')\n first_params = list(map(float, first_params))\n s._set_global_packets(first_params[0])\n s._set_global_losses(first_params[1])\n s._set_global_delay(first_params[2])\n r = s._results_line[s._results_line.find('|')+1:].split(';')\n if (s._flowresults_line):\n f = s._flowresults_line.split(';')\n else:\n f = r\n \n ptr = s._traffic_line.find('|')\n t = s._traffic_line[ptr+1:].split(';')\n s.maxAvgLambda = float(s._traffic_line[:ptr])\n sim_time = float(s._status_line.split(';')[0])\n \n m_result = []\n m_traffic = []\n for i in range(0,len(r), int(math.sqrt(len(r)))):\n new_result_row = []\n new_traffic_row = []\n for j in range(i, i+int(math.sqrt(len(r)))):\n dict_result_srcdst = {}\n aux_agg_ = r[j].split(',')\n aux_agg = list(map(float, aux_agg_))\n dict_result_agg = {'PktsDrop':aux_agg[2], \"AvgDelay\":aux_agg[3], \"AvgLnDelay\":aux_agg[4], \"p10\":aux_agg[5], \"p20\":aux_agg[6], \"p50\":aux_agg[7], \"p80\":aux_agg[8], \"p90\":aux_agg[9], \"Jitter\":aux_agg[10]}\n \n lst_result_flows = []\n aux_result_flows = f[j].split(':')\n for flow in aux_result_flows:\n dict_result_tmp = {}\n tmp_result_flow = flow.split(',')\n tmp_result_flow = list(map(float, tmp_result_flow))\n q_flows.put([tmp_result_flow[0], tmp_result_flow[1]])\n dict_result_tmp = {'PktsDrop':tmp_result_flow[2], \"AvgDelay\":tmp_result_flow[3], \"AvgLnDelay\":tmp_result_flow[4], \"p10\":tmp_result_flow[5], \"p20\":tmp_result_flow[6], \"p50\":tmp_result_flow[7], \"p80\":tmp_result_flow[8], \"p90\":tmp_result_flow[9], \"Jitter\":tmp_result_flow[10]}\n lst_result_flows.append(dict_result_tmp)\n \n dict_traffic_srcdst = {}\n # From kbps to bps\n dict_traffic_agg = {'AvgBw':aux_agg[0]*1000,\n 'PktsGen':aux_agg[1],\n 'TotalPktsGen':aux_agg[1]*sim_time}\n lst_traffic_flows = []\n aux_traffic_flows = t[j].split(':')\n for flow in aux_traffic_flows:\n dict_traffic = {}\n q_values_for_flow = q_flows.get()\n tmp_traffic_flow = flow.split(',')\n tmp_traffic_flow = list(map(float, tmp_traffic_flow))\n offset = self._timedistparams(tmp_traffic_flow,dict_traffic)\n if offset != -1:\n self._sizedistparams(tmp_traffic_flow, offset, dict_traffic)\n # From kbps to bps\n dict_traffic['AvgBw'] = q_values_for_flow[0]*1000\n dict_traffic['PktsGen'] = q_values_for_flow[1]\n dict_traffic['TotalPktsGen'] = sim_time * dict_traffic['PktsGen']\n dict_traffic['ToS'] = tmp_traffic_flow[-1]\n if (len(dict_traffic.keys())!=0):\n lst_traffic_flows.append (dict_traffic)\n \n dict_result_srcdst['AggInfo'] = dict_result_agg\n dict_result_srcdst['Flows'] = lst_result_flows\n dict_traffic_srcdst['AggInfo'] = dict_traffic_agg\n dict_traffic_srcdst['Flows'] = lst_traffic_flows\n new_result_row.append(dict_result_srcdst)\n new_traffic_row.append(dict_traffic_srcdst)\n \n m_result.append(new_result_row)\n m_traffic.append(new_traffic_row)\n m_result = numpy.asmatrix(m_result)\n m_traffic = numpy.asmatrix(m_traffic)\n s._set_performance_matrix(m_result)\n s._set_traffic_matrix(m_traffic)\n\n def _timedistparams(self, data, dict_traffic):\n \"\"\"\n \n\n Parameters\n ----------\n data : List\n List of all the flow traffic parameters to be processed.\n dict_traffic: dictionary\n Dictionary to fill with the time distribution information\n extracted from data\n\n Returns\n -------\n offset : int\n Number of elements read from the list of parameters data\n\n \"\"\"\n \n if data[0] == 0: \n dict_traffic['TimeDist'] = TimeDist.EXPONENTIAL_T\n params = {}\n params['EqLambda'] = data[1]\n params['AvgPktsLambda'] = data[2]\n params['ExpMaxFactor'] = data[3]\n dict_traffic['TimeDistParams'] = params\n return 4\n elif data[0] == 1:\n dict_traffic['TimeDist'] = TimeDist.DETERMINISTIC_T\n params = {}\n params['EqLambda'] = data[1]\n params['AvgPktsLambda'] = data[2]\n dict_traffic['TimeDistParams'] = params\n return 3\n elif data[0] == 2:\n dict_traffic['TimeDist'] = TimeDist.UNIFORM_T\n params = {}\n params['EqLambda'] = data[1]\n params['MinPktLambda'] = data[2]\n params['MaxPktLambda'] = data[3]\n dict_traffic['TimeDistParams'] = params\n return 4\n elif data[0] == 3:\n dict_traffic['TimeDist'] = TimeDist.NORMAL_T\n params = {}\n params['EqLambda'] = data[1]\n params['AvgPktsLambda'] = data[2]\n params['StdDev'] = data[3]\n dict_traffic['TimeDistParams'] = params\n return 4\n elif data[0] == 4:\n dict_traffic['TimeDist'] = TimeDist.ONOFF_T\n params = {}\n params['EqLambda'] = data[1]\n params['PktsLambdaOn'] = data[2]\n params['AvgTOff'] = data[3]\n params['AvgTOn'] = data[4]\n params['ExpMaxFactor'] = data[5]\n dict_traffic['TimeDistParams'] = params\n return 6\n elif data[0] == 5:\n dict_traffic['TimeDist'] = TimeDist.PPBP_T\n params = {}\n params['EqLambda'] = data[1]\n params['BurstGenLambda'] = data[2]\n params['Bitrate'] = data[3]\n params['ParetoMinSize'] = data[4]\n params['ParetoMaxSize'] = data[5]\n params['ParetoAlfa'] = data[6]\n params['ExpMaxFactor'] = data[7]\n dict_traffic['TimeDistParams'] = params\n return 8\n else: return -1\n \n def _sizedistparams(self, data, starting_point, dict_traffic):\n \"\"\"\n \n\n Parameters\n ----------\n data : List\n List of all the flow traffic parameters to be processed.\n starting_point : int\n Point of the overall traffic file line where the extraction of\n data regarding the size distribution should start.\n dict_traffic : dictionary\n Dictionary to fill with the size distribution information\n extracted from data\n\n Returns\n -------\n ret : int\n 0 if it finish successfully and -1 otherwise\n\n \"\"\"\n \n if data[starting_point] == 0:\n dict_traffic['SizeDist'] = SizeDist.DETERMINISTIC_S\n params = {}\n params['AvgPktSize'] = data[starting_point+1]\n dict_traffic['SizeDistParams'] = params\n elif data[starting_point] == 1:\n dict_traffic['SizeDist'] = SizeDist.UNIFORM_S\n params = {}\n params['AvgPktSize'] = data[starting_point+1]\n params['MinSize'] = data[starting_point+2]\n params['MaxSize'] = data[starting_point+3]\n dict_traffic['SizeDistParams'] = params\n elif data[starting_point] == 2:\n dict_traffic['SizeDist'] = SizeDist.BINOMIAL_S\n params = {}\n params['AvgPktSize'] = data[starting_point+1]\n params['PktSize1'] = data[starting_point+2]\n params['PktSize2'] = data[starting_point+3]\n dict_traffic['SizeDistParams'] = params\n elif data[starting_point] == 3:\n dict_traffic['SizeDist'] = SizeDist.GENERIC_S\n params = {}\n params['AvgPktSize'] = data[starting_point+1]\n params['NumCandidates'] = data[starting_point+2]\n for i in range(0, int(data[starting_point+2]) * 2, 2):\n params[\"Size_%d\"%(i/2)] = data[starting_point+3+i]\n params[\"Prob_%d\"%(i/2)] = data[starting_point+4+i]\n dict_traffic['SizeDistParams'] = params\n else:\n return -1\n return 0\n\n def _process_link_usage(self,s):\n \"\"\"\n\n Parameters\n ----------\n s : Sample\n Instance of Sample associated with the current iteration.\n\n Returns\n -------\n None.\n\n \"\"\"\n # port_state is an array of the nodes containing a dictionary with the adjacent nodes. \n # Each adjacent node contains a dictionary with performance metrics\n port_stat = []\n l = s._link_usage_line.split(\";\")\n netSize = s.get_network_size()\n for i in range(netSize):\n port_stat.append({})\n for j in range(netSize):\n params = l[i*netSize+j].split(\",\")\n if (params[0] == \"-1\"):\n continue\n link_stat = {}\n link_stat[\"utilization\"] = float(params[0])\n link_stat[\"losses\"] = float(params[1])\n link_stat[\"avgPacketSize\"] = float(params[2])\n num_qos_queues = int((len(params)-3)/5)\n qos_queue_stat_lst = []\n for q in range(num_qos_queues):\n qos_queue_stat = {\"utilization\":float(params[3+q*5]),\n \"losses\":float(params[3+q*5+1]),\n \"avgPortOccupancy\":float(params[3+q*5+2]),\n \"maxQueueOccupancy\":float(params[3+q*5+3]),\n \"avgPacketSize\":float(params[3+q*5+4])}\n qos_queue_stat_lst.append(qos_queue_stat)\n link_stat[\"qosQueuesStats\"] = qos_queue_stat_lst;\n port_stat[i][j] = link_stat\n# \n s.port_stats = port_stat\n\n"
] |
[
[
"numpy.asmatrix",
"numpy.empty"
]
] |
lyn1874/anomaly_detection_under_varying_visibility
|
[
"3d3cbd8344fa8cd6af7f54f7c3f9a3e9ef0994f7"
] |
[
"memae-anomaly-detection/Testing.py"
] |
[
"import torch \nfrom torch import nn\nimport summary\nimport os\nimport sys\nimport numpy as np\nimport time\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nimport utils\nfrom models import AutoEncoderCov3D, AutoEncoderCov3DMem\nimport data.utils as data_utils\nimport argparse\nfrom tqdm import tqdm\nimport aug_data as aug_data\nimport utils.eval as eval_utils\n\nparser = argparse.ArgumentParser(description=\"Memorizing_Normality\")\nparser.add_argument('--dataset', type=str, default=\"UCSDped2\")\nparser.add_argument('--dataset_augment_type', type=str, default=\"training\", help='the augmented version or not augmented version')\nparser.add_argument('--dataset_augment_test_type', type=str, default='original_testing', help='the augmented version')\nparser.add_argument(\"--version\", type=int, default=1)\nparser.add_argument(\"--ckpt_step\", type=int, default=59)\nparser.add_argument(\"--data_path\", type=str, default='/project/bo/anomaly_data/')\nparser.add_argument(\"--EntropyLossWeight\", type=float, default=0)\nparser.add_argument(\"--lr\", type=float, default=1e-4)\nargs = parser.parse_args()\n\ndevice = \"cuda\"\n\nheight, width = 256, 256\nch = 1\nnum_frame = 16\nbatch_size=1\nModelName = \"MemAE\"\nmodel_dir = '/project/bo/exp_data/memory_normal/%s/%slr_%.5f_entropyloss_%.5f_version_%d/' % (args.dataset, \n args.dataset_augment_type,\n args.lr,\n args.EntropyLossWeight,\n args.version)\n\n\norig_stdout = sys.stdout\nif args.dataset_augment_test_type == \"frames/testing/\":\n first = \"original_1.00\"\nelse:\n first = args.dataset_augment_test_type\nf = open(os.path.join(model_dir, 'output_%s_%d.txt' % (first, args.ckpt_step)),'w')\nsys.stdout= f\n\n\nckpt_dir = model_dir + \"model-00%d.pt\" % args.ckpt_step\n\nif \"venue\" in args.dataset:\n args.dataset = \"Avenue\"\n \ngt_file = \"/project/bo/anomaly_data/%s/gt.npy\" % args.dataset\n\nif args.dataset_augment_test_type == \"frames/testing/\":\n save_path = model_dir + \"recons_error_original_1.0.npy\"\nelse:\n save_path = model_dir + \"recons_error_%s.npy\" % args.dataset_augment_test_type\n \nif os.path.isfile(save_path):\n recons_error = np.load(save_path)\n eval_utils.eval_video2(gt_file, recons_error, args.dataset)\n exit()\n \n \nif args.dataset_augment_test_type != \"frames/testing/\" and \"venue\" in args.dataset:\n rain_type = str(args.dataset_augment_test_type.strip().split('_')[0])\n brightness = int(args.dataset_augment_test_type.strip().split('_')[-1])/10\n data_dir = args.data_path + \"Avenue/frames/%s_testing/bright_%.2f/\" % (rain_type, brightness)\n if not os.path.exists(data_dir):\n aug_data.save_avenue_rain_or_bright(args.data_path, rain_type, True, \"testing\", bright_space=brightness)\nelse:\n data_dir = args.data_path + '/%s/%s/' % (args.dataset, args.dataset_augment_test_type)\n\nframe_trans = transforms.Compose([\n transforms.Resize([height, width]),\n transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor(),\n transforms.Normalize([0.5], [0.5]),\n ])\nunorm_trans = utils.UnNormalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\nprint(\"------Data folder\", data_dir)\nprint(\"------Model folder\", model_dir)\nprint(\"------Restored ckpt\", ckpt_dir)\n\ndata_loader = data_utils.DataLoader(data_dir, frame_trans, time_step=num_frame-1, num_pred=1)\n\n# batch_size = [v for v in range(50)[1:] if len(data_loader) % v == 0][-1]\n\nvideo_data_loader = DataLoader(data_loader, batch_size=batch_size, shuffle=False)\n\nchnum_in_ = 1\nmem_dim_in = 2000\nsparse_shrink_thres = 0.0025\n\nmodel = AutoEncoderCov3DMem(chnum_in_, mem_dim_in, shrink_thres=sparse_shrink_thres)\nmodel_para = torch.load(ckpt_dir)\nmodel.load_state_dict(model_para)\nmodel.requires_grad_(False)\nmodel.to(device)\nmodel.eval()\n\nimg_crop_size = 0\nrecon_error_list = [None] * len(video_data_loader)\n# recon_error_list = []\ntime_init = time.time()\nprogress_bar = tqdm(video_data_loader)\nfor batch_idx, frames in enumerate(progress_bar):\n progress_bar.update()\n frames = frames.reshape([batch_size, num_frame, ch, height, width])\n frames = frames.permute(0, 2, 1, 3, 4)\n frames = frames.to(device)\n if (ModelName == 'AE'):\n recon_frames = model(frames)\n ###### calculate reconstruction error (MSE)\n recon_np = utils.vframes2imgs(unorm_trans(recon_frames.data), step=1, batch_idx=0)\n input_np = utils.vframes2imgs(unorm_trans(frames.data), step=1, batch_idx=0)\n r = utils.crop_image(recon_np, img_crop_size) - utils.crop_image(input_np, img_crop_size)\n # recon_error = np.mean(sum(r**2)**0.5)\n recon_error = np.mean(r ** 2) # **0.5\n elif (ModelName == 'MemAE'):\n recon_res = model(frames)\n recon_frames = recon_res['output']\n recon_np = utils.vframes2imgs(unorm_trans(recon_frames.data), step=1, batch_idx=0)\n input_np = utils.vframes2imgs(unorm_trans(frames.data), step=1, batch_idx=0)\n r = utils.crop_image(recon_np, img_crop_size) - utils.crop_image(input_np, img_crop_size)\n sp_error_map = sum(r ** 2)**0.5\n recon_error = np.mean(sp_error_map.flatten())\n else:\n recon_error = -1\n print('Wrong ModelName.')\n# recon_error_list.append(recon_error)\n recon_error_list[batch_idx] = recon_error\n# recon_error_list = [v for j in recon_error_list for v in j]\nprint(\"The length of the reconstruction error is \", len(recon_error_list))\nprint(\"The length of the testing images is\", len(data_loader))\nprint(\"............start to checking the anomaly detection auc score...................\")\nprint(\"............use ckpt dir at step %d\" % args.ckpt_step)\neval_utils.eval_video2(gt_file, recon_error_list, args.dataset)\ntime_use = time.time() - time_init\nprint(\"FPS-------------\", len(video_data_loader) / (time_use))\nsys.stdout = orig_stdout\nf.close()\n\nif args.dataset_augment_test_type == \"frames/testing/\":\n save_path = model_dir + \"recons_error_original_1.0\"\nelse:\n save_path = model_dir + \"recons_error_%s\" % args.dataset_augment_test_type\nnp.save(save_path, recon_error_list)\n\n\n\n\n"
] |
[
[
"torch.load",
"torch.utils.data.DataLoader",
"numpy.save",
"numpy.mean",
"numpy.load"
]
] |
mihirkestur/neowise
|
[
"2bce24812fb276f07bdbced605c28e0f865dd6eb"
] |
[
"neowise/neowise/optimizers.py"
] |
[
"import numpy as np\n\n\nclass OptimizerHelpers:\n \"\"\"\n Optimizer Helpers\n Used to initiate the instance variables of nw.optimizers\n\n Arguments:\n alpha: Learning rate of the network (float)\n layers_arr: List containing the objects of nw.layers (List)\n V_dict: Dictionary containing the moving averages of the gradient of weights of all the layers (nd-array)\n S_dict: Dictionary containing the moving averages of the squared gradient of weights of all the layers (nd-array)\n t: Number of iterations elapsed (int)\n \"\"\"\n def __init__(self, alpha, layers_arr, V_dict, S_dict, t):\n self.alpha, self.layers_arr, self.V_dict, self.S_dict, self.t = alpha, layers_arr, V_dict, S_dict, t\n\n\nclass GradientDescent(OptimizerHelpers):\n \"\"\"\n Gradient Descent\n\n Arguments:\n alpha: Learning rate of the network (float)\n layers_arr: List containing the objects of nw.layers (List)\n V_dict: Dictionary containing the moving averages of the gradient of weights of all the layers (nd-array)\n S_dict: Dictionary containing the moving averages of the squared gradient of weights of all the layers (nd-array)\n t: Number of iterations elapsed (int)\n \"\"\"\n def __init__(self, alpha, layers_arr, V_dict, S_dict, t):\n OptimizerHelpers.__init__(self, alpha, layers_arr, V_dict, S_dict, t)\n\n def __call__(self):\n for layers in self.layers_arr:\n layers.weights -= (self.alpha * layers.dW)\n layers.bias -= (self.alpha * layers.db)\n\n\nclass Momentum(OptimizerHelpers):\n \"\"\"\n Gradient Descent with Momentum\n\n Arguments:\n alpha: Learning rate of the network (float)\n layers_arr: List containing the objects of nw.layers (List)\n V_dict: Dictionary containing the moving averages of the gradient of weights of all the layers (nd-array)\n S_dict: Dictionary containing the moving averages of the squared gradient of weights of all the layers (nd-array)\n t: Number of iterations elapsed (int)\n \"\"\"\n def __init__(self, alpha, layers_arr, V_dict, S_dict, t):\n OptimizerHelpers.__init__(self, alpha, layers_arr, V_dict, S_dict, t)\n\n def __call__(self):\n beta1 = 0.9\n for h in range(1, len(self.layers_arr) + 1):\n self.V_dict[\"Vdw\" + str(h)] = (beta1 * self.V_dict[\"Vdw\" + str(h)]) + (\n (1 - beta1) * self.layers_arr[h - 1].dW)\n self.V_dict[\"Vdb\" + str(h)] = (beta1 * self.V_dict[\"Vdb\" + str(h)]) + (\n (1 - beta1) * self.layers_arr[h - 1].db)\n for g in range(1, len(self.layers_arr) + 1):\n self.layers_arr[g - 1].weights -= (self.alpha * self.V_dict[\"Vdw\" + str(g)])\n self.layers_arr[g - 1].bias -= (self.alpha * self.V_dict[\"Vdb\" + str(g)])\n\n\nclass RMSProp(OptimizerHelpers):\n \"\"\"\n Root Mean Square Propagation\n\n Arguments:\n alpha: Learning rate of the network (float)\n layers_arr: List containing the objects of nw.layers (List)\n V_dict: Dictionary containing the moving averages of the gradient of weights of all the layers (nd-array)\n S_dict: Dictionary containing the moving averages of the squared gradient of weights of all the layers (nd-array)\n t: Number of iterations elapsed (int)\n \"\"\"\n def __init__(self, alpha, layers_arr, V_dict, S_dict, t):\n OptimizerHelpers.__init__(self, alpha, layers_arr, V_dict, S_dict, t)\n\n def __call__(self):\n beta2 = 0.999\n epsilon = 1e-8\n for h in range(1, len(self.layers_arr) + 1):\n self.S_dict[\"Sdw\" + str(h)] = (beta2 * self.S_dict[\"Sdw\" + str(h)]) + (\n (1 - beta2) * np.square(self.layers_arr[h - 1].dW))\n self.S_dict[\"Sdb\" + str(h)] = (beta2 * self.S_dict[\"Sdb\" + str(h)]) + (\n (1 - beta2) * np.square(self.layers_arr[h - 1].db))\n for g in range(1, len(self.layers_arr) + 1):\n self.layers_arr[g - 1].weights -= (\n (self.alpha * self.layers_arr[g - 1].dW) / (np.sqrt(self.S_dict[\"Sdw\" + str(g)]) + epsilon))\n self.layers_arr[g - 1].bias -= (\n (self.alpha * self.layers_arr[g - 1].db) / (np.sqrt(self.S_dict[\"Sdb\" + str(g)]) + epsilon))\n\n\nclass Adam(OptimizerHelpers):\n \"\"\"\n Adam\n\n Arguments:\n alpha: Learning rate of the network (float)\n layers_arr: List containing the objects of nw.layers (List)\n V_dict: Dictionary containing the moving averages of the gradient of weights of all the layers (nd-array)\n S_dict: Dictionary containing the moving averages of the squared gradient of weights of all the layers (nd-array)\n t: Number of iterations elapsed (int)\n \"\"\"\n def __init__(self, alpha, layers_arr, V_dict, S_dict, t):\n OptimizerHelpers.__init__(self, alpha, layers_arr, V_dict, S_dict, t)\n\n def __call__(self):\n beta1 = 0.9\n beta2 = 0.999\n epsilon = 1e-8\n S_dict_corr = {}\n V_dict_corr = {}\n for h in range(1, len(self.layers_arr) + 1):\n self.V_dict[\"Vdw\" + str(h)] = (beta1 * self.V_dict[\"Vdw\" + str(h)]) + (\n (1 - beta1) * self.layers_arr[h - 1].dW)\n self.V_dict[\"Vdb\" + str(h)] = (beta1 * self.V_dict[\"Vdb\" + str(h)]) + (\n (1 - beta1) * self.layers_arr[h - 1].db)\n self.S_dict[\"Sdw\" + str(h)] = (beta2 * self.S_dict[\"Sdw\" + str(h)]) + (\n (1 - beta2) * np.square(self.layers_arr[h - 1].dW))\n self.S_dict[\"Sdb\" + str(h)] = (beta2 * self.S_dict[\"Sdb\" + str(h)]) + (\n (1 - beta2) * np.square(self.layers_arr[h - 1].db))\n for n in range(1, len(self.layers_arr) + 1):\n S_dict_corr[\"Sdw\" + str(n)] = self.S_dict[\"Sdw\" + str(n)] / (1 - np.power(beta2, self.t))\n S_dict_corr[\"Sdb\" + str(n)] = self.S_dict[\"Sdb\" + str(n)] / (1 - np.power(beta2, self.t))\n V_dict_corr[\"Vdw\" + str(n)] = self.V_dict[\"Vdw\" + str(n)] / (1 - np.power(beta1, self.t))\n V_dict_corr[\"Vdb\" + str(n)] = self.V_dict[\"Vdb\" + str(n)] / (1 - np.power(beta1, self.t))\n for g in range(1, len(self.layers_arr) + 1):\n self.layers_arr[g - 1].weights -= (\n (self.alpha * V_dict_corr[\"Vdw\" + str(g)]) / (np.sqrt(S_dict_corr[\"Sdw\" + str(g)]) + epsilon))\n self.layers_arr[g - 1].bias -= (\n (self.alpha * V_dict_corr[\"Vdb\" + str(g)]) / (np.sqrt(S_dict_corr[\"Sdb\" + str(g)]) + epsilon))\n"
] |
[
[
"numpy.square",
"numpy.power"
]
] |
engineerscodes/PyVisionHUB
|
[
"512ff1fde5dd9849e555bc7848a11cee65ee9068"
] |
[
"Matplotlib/Histogram.py"
] |
[
"import matplotlib.pyplot as plt\r\n\r\ndata = [18,55,21,25,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]\r\n\r\n# ids = [x for x in range(len(ages))]\r\n\r\nbins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]\r\n\r\nplt.hist(data, bins, histtype='bar' , rwidth=0.8 )\r\n\r\nplt.xlabel(\"X-axis\")\r\nplt.ylabel(\"Y-axis\")\r\nplt.title(\"Graph Below\")\r\n\r\nplt.show()"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
] |
tatHi/cwr
|
[
"1a2b15066ee46a5597f2702b55f7ae482ad754c2"
] |
[
"wordReplacer.py"
] |
[
"from scipy.stats import poisson\nimport numpy as np\nimport random\n\nclass WordReplacer:\n def __init__(self, word2id, usePoisson=False, useCache=False, cacheCoef=5.0, ignoreFirst=0):\n '''\n word2id: a dictionary of word to idx like {a:1, b:2, ...}\n usePoisson: use poisson weighting consiering word length if true\n useCache: use cache for fast sampling of length if true\n cacheCoef: sample vocabSize*cacheCoed words for cache\n ignoreFirst: ignore first N tokens of vocabulary.\n Used for special tokens basically allocated small idxs.\n '''\n\n self.usePoisson = usePoisson\n self.useCache = useCache\n self.cacheCoef = cacheCoef\n self.vocabSize = len(word2id)\n self.idList = list(range(self.vocabSize))\n self.ignoreFirst = ignoreFirst\n \n if self.usePoisson:\n self.__build(word2id)\n\n def __build(self, word2id):\n lengths = [len(w) for w, i in sorted(word2id.items(), key=lambda x:x[1])]\n self.id2length = {i:l for i, l in enumerate(lengths)}\n maxLength = max(lengths)\n\n # poissonTable (maxLength x maxLength)\n poissonTable = [[poisson.pmf(mu=mu+1, k=k+1) for k in range(maxLength)] \n for mu in range(maxLength)]\n \n print('>>> BUILD SAMPLING TABLE')\n # table for sampling (maxLength x vocabSize)\n self.samplingTable = [[poissonTable[mu][l-1] for l in lengths]\n for mu in range(maxLength)]\n self.samplingTable = np.array(self.samplingTable)\n self.samplingTable = self.samplingTable / self.samplingTable.sum(axis=1, keepdims=True)\n\n print('>>> BUILD CAHCE TABLE')\n if self.useCache:\n # CACHE of sampled words\n self.cacheTable = [random.choices(self.idList[self.ignoreFirst:],\n k=int(self.vocabSize*self.cacheCoef),\n weights=self.samplingTable[mu][self.ignoreFirst:]) \n for mu in range(maxLength)]\n\n def sampleWord(self, wordId, wordLength=-1):\n if self.usePoisson:\n if wordLength<0:\n wordLength = self.id2length[wordId]\n if self.useCache:\n return random.choice(self.cacheTable[wordLength-1])\n else:\n return random.choices(self.idList[self.ignoreFirst:],\n k=1,\n weights=self.samplingTable[wordLength-1])[0]\n else:\n return random.randint(self.ignoreFirst, self.vocabSize-1)\n\n def perturb(self, idss, rate, ignoreIdx=None):\n # idss is a batch of ids like [[1,2,3], [3,4,5,6]]\n if rate==0.0:\n return idss\n\n idss = [[self.sampleWord(i)\n if i!=ignoreIdx and random.random()<rate else i\n for i in ids] for ids in idss]\n\n return idss\n\nif __name__=='__main__':\n word2id = {'a'*(i+1):i for i in range(5)}\n word2id['bbb'] = len(word2id)\n wrp = WordReplacer(word2id, True, True)\n print(wrp.sampleWord(2))\n"
] |
[
[
"numpy.array",
"scipy.stats.poisson.pmf"
]
] |
xpmemeda/mgeconvert
|
[
"d30e28dffaa9c42cbbefd7a8c41c688f9d2a8acd"
] |
[
"mgeconvert/cambricon_converter/cambricon_converter.py"
] |
[
"# -*- coding: utf-8 -*-\n# MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.\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 ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nfrom typing import List\n\nimport numpy as np\n\nfrom ..mge_context import (\n ConcatOpr,\n ConvBiasForwardOpr,\n ConvolutionBackwardDataOpr,\n ConvolutionForwardOpr,\n MatrixMulOpr,\n TopologyNetwork,\n TransformerRule,\n optimize_for_conversion,\n)\nfrom ..mge_context.mge_utils import get_dtype_name, get_logger\nfrom .cambricon_op import MGE2CN\nfrom .lib import cnq\nfrom .lib import operators as cnop\nfrom .lib.model import Model\nfrom .lib.tensor import DATA_TYPE, TENSOR_TYPE, Tensor\n\nlogger = get_logger(__name__)\n\n\nmap_dtype = {\n \"float16\": DATA_TYPE.FLOAT16,\n \"float32\": DATA_TYPE.FLOAT32,\n}\n\n\nclass CambriconConverter:\n transformer_options: List[TransformerRule] = []\n\n def __init__(\n self,\n net,\n transformer_options=None,\n batch_size=4,\n core_number=1,\n data_type=\"float32\",\n use_nhwc=False,\n ):\n if use_nhwc:\n Tensor.NCHW2NHWC = True\n Tensor._default_dtype = map_dtype[data_type]\n self.batch_size = batch_size\n self.core_number = core_number\n self.data_type = map_dtype[data_type]\n self.mge_net = net\n if transformer_options is not None:\n self.transformer_options = transformer_options\n optimize_for_conversion(self.mge_net, self.transformer_options)\n self.var_map = {}\n self.cn_inputs = []\n self.cn_outputs = []\n self.cn_oprs = []\n self.fusion = None\n\n self.check_model()\n\n def check_model(self):\n logger.info(\"check model...\")\n unsupported_oprs = set()\n quantization_error_oprs = set()\n for opr in self.mge_net.all_oprs:\n if not isinstance(opr, tuple(MGE2CN.keys())):\n unsupported_oprs.add(type(opr))\n if isinstance(\n opr,\n (\n ConvBiasForwardOpr,\n ConvolutionBackwardDataOpr,\n ConvolutionForwardOpr,\n MatrixMulOpr,\n ),\n ):\n if (\n get_dtype_name(opr.inp_vars[0]) != \"QuantizedS8\"\n or get_dtype_name(opr.inp_vars[1]) != \"QuantizedS8\"\n or (\n len(opr.inp_vars) > 2\n and get_dtype_name(opr.inp_vars[2]) != \"QuantizedS32\"\n )\n or get_dtype_name(opr.out_vars[0]) != \"QuantizedS32\"\n ):\n quantization_error_oprs.add(type(opr))\n\n if unsupported_oprs:\n logger.error(\"Operators %s are not supported yet.\", unsupported_oprs)\n if quantization_error_oprs:\n logger.error(\n \"Operators %s should be quantized, \"\n \"check the function test_linear in test/test_cambricon for inspiration\",\n quantization_error_oprs,\n )\n assert not unsupported_oprs and not quantization_error_oprs\n\n def get_cn_tensor(self, var):\n if var not in self.var_map:\n raise KeyError(\"can not find var {}\".format(var.__dict__))\n return self.var_map[var]\n\n def set_cn_tensor(self, opr, var):\n ttype = TENSOR_TYPE.CONST\n dtype = self.data_type\n shp = var.shape\n data = var.np_data\n\n if var.qbit == \"QuantizedS8\":\n ttype = TENSOR_TYPE.FILTER\n dtype = DATA_TYPE.INT8\n if var.qbit == \"QuantizedS32\":\n data = data.astype(np.float32) * var.scale\n\n if len(shp) == 1: # conv bias\n shp = (1, shp[0], 1, 1)\n data = data.reshape(shp)\n if len(shp) == 5: # group conv's filter\n shp = (shp[0] * shp[1], shp[2], shp[3], shp[4])\n data = data.reshape(shp)\n # if var.qbit is None and shp[0] != 1:\n if isinstance(opr, ConcatOpr):\n shp = (self.batch_size,) + shp[1:]\n data = np.broadcast_to(data[:1], shp)\n return Tensor(\n shape=shp,\n ttype=ttype,\n dtype=dtype,\n data=data,\n scale=var.scale,\n name=opr.name,\n )\n\n def get_cn_inputs_and_outputs(self, opr):\n cn_inps = []\n for var in opr.inp_vars:\n if var not in self.var_map:\n self.var_map[var] = self.set_cn_tensor(opr, var)\n cn_inps.append(self.var_map[var])\n cn_oups = []\n for var in opr.out_vars:\n shp = (self.batch_size,) + var.shape[1:]\n self.var_map[var] = Tensor(shape=shp, name=var.name, scale=var.scale)\n cn_oups.append(self.var_map[var])\n return cn_inps, cn_oups\n\n def add_oprs(self, *cnoprs):\n self.cn_oprs.extend(cnoprs)\n\n def convert(self, end_op=None):\n for opr in self.mge_net.all_oprs:\n # Prune operators which calculate parameters.\n pruning = True\n for var in opr.out_vars:\n pruning = False if var.np_data is None else pruning\n if pruning:\n continue\n MGE2CN[type(opr)](opr, self)\n if opr.name == end_op:\n end_op = opr\n break\n assert not isinstance(end_op, str), (\n 'This operator does not exist: \"%s\"' % end_op\n )\n self.cn_inputs = self.cn_oprs[0].inputs[0]\n if end_op is None:\n self.cn_outputs = self.cn_oprs[-1].outputs[0]\n else:\n self.cn_outputs = self.var_map[end_op.out_vars[0]]\n\n def fuse(self):\n self.fusion = cnop.Fusion(\"fusion\", self.cn_inputs, self.cn_outputs)\n for cnopr in self.cn_oprs:\n self.fusion.fuse_op(cnopr)\n self.fusion.set_fusion_io()\n self.fusion.set_core_num(self.core_number)\n self.fusion.compile()\n\n def forward(self, feed_input: \"np.ndarray\"):\n self.cn_inputs.cpudata = feed_input\n self.cn_inputs.h2d()\n self.fusion.forward(cnq)\n return self.cn_outputs.cpudata\n\n def dump(self, fname):\n model = Model(self.fusion.name)\n model.add_fusionop(self.fusion)\n model.dump(fname)\n\n\ndef convert_to_cambricon(\n mge_fpath, filename, batch_size, core_number, data_type, use_nhwc\n):\n \"\"\"\n Convert megengine model to cambricon model.\n\n :param mge_fpath: the file path of megengine model.\n :type mge_fpath: str\n :param filename: cambricon model file name.\n :type filename: str\n :param batch_size: batch_size of the output cambricon model.\n :type batch_size: int\n :param core_number: core_number of the output cambricon model.\n :type core_number: int\n :param data_type: data_type of the output cambricon model, which should be\n \"float32\" or \"float16\".\n :type data_type: str\n :param use_nhwc: whether to use nhwc layout.\n :type use_nhwc: bool\n \"\"\"\n assert isinstance(mge_fpath, str), \"mge_fpath must be string\"\n net = TopologyNetwork(mge_fpath)\n logger.info(\"init converter...\")\n converter = CambriconConverter(\n net,\n batch_size=batch_size,\n core_number=core_number,\n data_type=data_type,\n use_nhwc=use_nhwc,\n )\n logger.info(\"convert operators to cambricon...\")\n converter.convert()\n logger.info(\"%d operators converted...\", len(converter.cn_oprs))\n converter.fuse()\n logger.info(\"fusing...\")\n converter.dump(filename)\n logger.info(\"ok, dump model to %s\", filename)\n"
] |
[
[
"numpy.broadcast_to"
]
] |
Joseph-tsai415/Msc-All-Terrain-Robot
|
[
"40973b8d1b088d37efc372f6313ee58d18792c02"
] |
[
"src/Guidance_system/guidance_sys/gen_marker/gen_marker.py"
] |
[
"import cv2 as cv\nimport numpy as np\n\n# Load the predefined dictionary\n\ndictionary = cv.aruco.Dictionary_get(cv.aruco.DICT_4X4_50)\n# Generate the marker\n\nmarkerImage = np.zeros((400, 400), dtype=np.uint8)\nfor i in range(50):\n markerImage = cv.aruco.drawMarker(dictionary, i, 400, markerImage, 1);\n cv.imwrite(\"marker4X4_%i.png\"%+(i+1), markerImage);\n\n"
] |
[
[
"numpy.zeros"
]
] |
bayesquant/VDSH
|
[
"19dc616c8b91fee5d47854163bb1dc71bbefd553"
] |
[
"datasets.py"
] |
[
"import os\nfrom os.path import join\nimport numpy as np\nimport torch\n#from scipy.sparse import csr_matrix\nimport pandas as pd\nimport pickle\nfrom torch.utils.data import Dataset\n\n##########################################################################################################################\n\nclass SingleLabelTextDataset(Dataset):\n \"\"\"datasets wrapper for ng20, agnews, dbpedia, yahooanswer\"\"\"\n\n def __init__(self, data_dir, download=False, subset='train', bow_format='tf'):\n \"\"\"\n Args:\n data_dir (string): Directory for loading and saving train, test, and cv dataframes.\n download (boolean): Download newsgroups20 dataset from sklearn if necessary.\n subset (string): Specify subset of the datasets. The choices are: train, test, cv.\n bow_format (string): A weight scheme of a bag-of-words document. The choices are:\n tf (term frequency), tfidf (term freq with inverse document frequency), bm25.\n \"\"\"\n self.data_dir = data_dir\n self.subset = subset\n self.bow_format = bow_format\n self.df = self.load_df('{}.{}.df.pkl'.format(subset, bow_format))\n\n def load_df(self, df_file):\n df_file = os.path.join(self.data_dir, df_file)\n return pd.read_pickle(df_file)\n \n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n doc_bow = self.df.iloc[idx].bow\n doc_bow = torch.from_numpy(doc_bow.toarray().squeeze().astype(np.float32))\n label = self.df.iloc[idx].label\n return (doc_bow, label)\n \n def num_classes(self):\n return len(set(self.df.label))\n \n def num_features(self):\n return self.df.bow.iloc[0].shape[1]\n \n##########################################################################################################################\n\nclass MultiLabelTextDataset(SingleLabelTextDataset):\n \"\"\"datasets wrapper for reuters, rcv1, tmc\"\"\"\n def __init__(self, data_dir, download=False, subset='train', bow_format='tf'):\n super(MultiLabelTextDataset, self).__init__(data_dir, download, subset, bow_format)\n \n def __getitem__(self, idx):\n doc_bow = self.df.iloc[idx].bow\n doc_bow = torch.from_numpy(doc_bow.toarray().squeeze().astype(np.float32))\n label_bow = self.df.iloc[idx].label\n label_bow = torch.from_numpy(label_bow.toarray().squeeze().astype(np.float32))\n return (doc_bow, label_bow)\n \n def num_classes(self):\n return self.df.iloc[0].label.shape[1]"
] |
[
[
"pandas.read_pickle"
]
] |
bonskotti/desdeo-mcdm
|
[
"33a94e9ac701712ef9669641da4a36d99084d50f"
] |
[
"desdeo_mcdm/interactive/NautilusNavigator.py"
] |
[
"from typing import Callable, Dict, List, Optional, Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom desdeo_mcdm.interactive.InteractiveMethod import InteractiveMethod\nfrom desdeo_tools.interaction.request import BaseRequest, SimplePlotRequest\nfrom desdeo_tools.scalarization.ASF import PointMethodASF\nfrom desdeo_tools.scalarization.Scalarizer import DiscreteScalarizer\nfrom desdeo_tools.solver.ScalarSolver import DiscreteMinimizer\n\n\nclass NautilusNavigatorRequest(BaseRequest):\n \"\"\"Request to handle interactions with NAUTILUS Navigator. See the\n NautilusNavigator class for further details.\n \"\"\"\n\n def __init__(\n self,\n ideal: np.ndarray,\n nadir: np.ndarray,\n reachable_lb: np.ndarray,\n reachable_ub: np.ndarray,\n reachable_idx: List[int],\n step_number: int,\n steps_remaining: int,\n distance: float,\n allowed_speeds: [int],\n current_speed: int,\n navigation_point: np.ndarray,\n ):\n msg = (\n # TODO: Be more specific...\n \"Please supply aspirations levels for each objective between \"\n \"the upper and lower bounds as `reference_point`. Specify a \"\n \"speed between 1-5 as `speed`. If going to a previous step is \"\n \"desired, please set `go_to_previous` to True, otherwise it should \"\n \"be False. \"\n \"Lastly, if stopping is desired, `stop` should be True, \"\n \"otherweise it should be set to False.\"\n )\n content = {\n \"message\": msg,\n \"ideal\": ideal,\n \"nadir\": nadir,\n \"reachable_lb\": reachable_lb,\n \"reachable_ub\": reachable_ub,\n \"reachable_idx\": reachable_idx,\n \"step_number\": step_number,\n \"steps_remaining\": steps_remaining,\n \"distance\": distance,\n \"allowed_speeds\": allowed_speeds,\n \"current_speed\": current_speed,\n \"navigation_point\": navigation_point,\n }\n\n super().__init__(\n \"reference_point_preference\", \"required\", content=content\n )\n\n @classmethod\n def init_with_method(cls, method):\n return cls(\n method._ideal,\n method._nadir,\n method._reachable_lb,\n method._reachable_ub,\n method._reachable_idx,\n method._step_number,\n method._steps_remaining,\n method._distance,\n method._allowed_speeds,\n method._current_speed,\n method._navigation_point,\n )\n\n def validator(self, response: Dict) -> None:\n if \"reference_point\" not in response:\n raise NautilusNavigatorException(\"'reference_point' entry missing.\")\n\n if \"speed\" not in response:\n raise NautilusNavigatorException(\"'speed' entry missing.\")\n\n if \"go_to_previous\" not in response:\n raise NautilusNavigatorException(\"'go_to_previous' entry missing.\")\n\n if \"stop\" not in response:\n raise NautilusNavigatorException(\"'stop' entry missing.\")\n\n ref_point = response[\"reference_point\"]\n try:\n if np.any(ref_point < self._content[\"ideal\"]) or np.any(\n ref_point > self._content[\"nadir\"]\n ):\n raise NautilusNavigatorException(\n f\"The given reference point {ref_point} \"\n \"must be between the ranges imposed by the ideal and nadir points.\"\n )\n except Exception as e:\n raise NautilusNavigatorException(\n f\"An exception rose when validating the given reference point {ref_point}.\\n\"\n f\"Previous exception: {type(e)}: {str(e)}.\"\n )\n\n speed = response[\"speed\"]\n try:\n if int(speed) not in self._content[\"allowed_speeds\"]:\n raise NautilusNavigatorException(f\"Invalid speed: {speed}.\")\n except Exception as e:\n raise NautilusNavigatorException(\n f\"An exception rose when validating the given speed {speed}.\\n\"\n f\"Previous exception: {type(e)}: {str(e)}.\"\n )\n\n if not type(response[\"go_to_previous\"]) == bool:\n raise (\n f\"Non boolean value {response['go_to_previous']} \"\n f\"found for 'go_to_previous' when validating the response.\"\n )\n\n if not type(response[\"stop\"]) == bool:\n raise (\n f\"Non boolean value {response['stop']} \"\n f\"found for 'go_to_previous' when validating the response.\"\n )\n\n @BaseRequest.response.setter\n def response(self, response: Dict):\n self.validator(response)\n self._response = response\n\n\nclass NautilusNavigatorException(Exception):\n \"\"\"Raised when an exception related to NAUTILUS Navigator is encountered.\n \"\"\"\n\n pass\n\n\nclass NautilusNavigator(InteractiveMethod):\n \"\"\"Implementations of the NAUTILUS Navigator algorithm.\n\n \"\"\"\n\n def __init__(\n self,\n pareto_front: np.ndarray,\n ideal: np.ndarray,\n nadir: np.ndarray,\n objective_names: Optional[List[str]] = None,\n minimize: Optional[List[int]] = None,\n ):\n \"\"\"\n\n Args:\n pareto_front (np.ndarray): A two dimensional numpy array\n representing a Pareto front with objective vectors on each of its\n rows.\n ideal (np.ndarray): The ideal objective vector of the problem\n being represented by the Pareto front.\n nadir (np.ndarray): The nadir objective vector of the problem\n being represented by the Pareto front.\n objective_names (Optional[List[str]], optional): Names of the\n objectives. List must match the number of columns in\n pareto_front. Defaults to 'f1', 'f2', 'f3', ...\n minimize (Optional[List[int]], optional): Multipliers for each\n objective. '-1' indicates maximization and '1' minimization.\n Defaults to all objective values being minimized.\n\n Raises:\n NautilusNavigatorException: One or more dimension mismatches are\n encountered among the supplies arguments.\n \"\"\"\n if not pareto_front.ndim == 2:\n raise NautilusNavigatorException(\n \"The supplied Pareto front should be a two dimensional array. Found \"\n f\" number of dimensions {pareto_front.ndim}.\"\n )\n\n if not ideal.shape[0] == pareto_front.shape[1]:\n raise NautilusNavigatorException(\n \"The Pareto front must consist of objective vectors with the \"\n \"same number of objectives as defined in the ideal and nadir \"\n \"points.\"\n )\n\n if not ideal.shape == nadir.shape:\n raise NautilusNavigatorException(\n \"The dimensions of the ideal and nadir point do not match.\"\n )\n\n if objective_names:\n if not len(objective_names) == ideal.shape[0]:\n raise NautilusNavigatorException(\n \"The supplied objective names must have a leangth equal to \"\n \"the numbr of objectives.\"\n )\n self._objective_names = objective_names\n else:\n self._objective_names = [f\"f{i+1}\" for i in range(ideal.shape[0])]\n\n if minimize:\n if not len(objective_names) == ideal.shape[0]:\n raise NautilusNavigatorException(\n \"The minimize list must have \"\n \"as many elements as there are objectives.\"\n )\n self._minimize = minimize\n else:\n self._minimize = [1 for _ in range(ideal.shape[0])]\n\n self._ideal = ideal\n self._nadir = nadir\n\n # in objective space!\n self._pareto_front = pareto_front\n\n # bounds of the rechable region\n self._reachable_ub = self._nadir\n self._reachable_lb = self._ideal\n\n # currently reachable solution as a list of indices of the Pareto front\n self._reachable_idx = list(range(0, self._pareto_front.shape[0]))\n\n # current iteration step number\n self._step_number = 1\n\n # iterations left\n self._steps_remaining = 100\n\n # L2 distance to the supplied Pareto front\n self._distance = 0\n\n self._allowed_speeds = [1, 2, 3, 4, 5]\n self._current_speed = None\n\n self._reference_point = None\n self._navigation_point = self._nadir\n self._projection_index = None\n\n def start(self) -> NautilusNavigatorRequest:\n \"\"\"Returns the first Request object to begin iterating.\n\n Returns:\n NautilusNavigatorRequest: The Request.\n \"\"\"\n return NautilusNavigatorRequest.init_with_method(self)\n\n def iterate(\n self, request: NautilusNavigatorRequest\n ) -> NautilusNavigatorRequest:\n \"\"\"Perform the next logical step based on the response in the\n Request.\n \"\"\"\n reqs = self.handle_request(request)\n return reqs\n\n def handle_request(\n self, request: NautilusNavigatorRequest\n ) -> NautilusNavigatorRequest:\n \"\"\"Handle the Request and its contents.\n\n Args:\n request (NautilusNavigatorRequest): A Request with a defined response.\n\n Returns:\n NautilusNavigatorRequest: Some of the contents of the response are invalid.\n \"\"\"\n preference_point = request.response[\"reference_point\"]\n speed = request.response[\"speed\"]\n go_to_previous = request.response[\"go_to_previous\"]\n stop = request.response[\"stop\"]\n\n if go_to_previous:\n step_number = request.content[\"step_number\"]\n nav_point = request.content[\"navigation_point\"]\n lower_bounds = request.content[\"reachable_lb\"]\n upper_bounds = request.content[\"reachable_ub\"]\n reachable_idx = request.content[\"reachable_idx\"]\n distance = request.content[\"distance\"]\n steps_remaining = request.content[\"steps_remaining\"]\n\n return self.update(\n preference_point,\n speed,\n go_to_previous,\n stop,\n step_number,\n nav_point,\n lower_bounds,\n upper_bounds,\n reachable_idx,\n distance,\n steps_remaining,\n )\n\n else:\n return self.update(preference_point, speed, go_to_previous, stop,)\n\n def update(\n self,\n ref_point: np.ndarray,\n speed: int,\n go_to_previous: bool,\n stop: bool,\n step_number: Optional[int] = None,\n nav_point: Optional[np.ndarray] = None,\n lower_bounds: Optional[np.ndarray] = None,\n upper_bounds: Optional[np.ndarray] = None,\n reachable_idx: Optional[List[int]] = None,\n distance: Optional[float] = None,\n steps_remaining: Optional[int] = None,\n ) -> Optional[NautilusNavigatorRequest]:\n \"\"\"Update the inernal state of self.\n\n Args:\n ref_point (np.ndarray): A reference point given by a decision maker.\n speed (int): An integer value between 1-5 indicating the navigation speed.\n go_to_previous (bool): If True, the parameters indicate the state\n of a previous state, and the request is handled accordingly.\n stop (bool): If the navigation should stop. If True, self.update return None.\n step_number (Optional[int], optional): Current step number, or\n previous step number if go_to_previous is True. Defaults to None.\n nav_point (Optional[np.ndarray], optional): The current\n navigation point. Relevant if go_to_previous is True. Defaults to\n None.\n lower_bounds (Optional[np.ndarray], optional): Lower bounds of\n the reachable objective vector valus. Relevant if go_to_previous\n is True. Defaults to None.\n upper_bounds (Optional[np.ndarray], optional): Upper bounds of\n the reachable objective vector valus. Relevant if go_to_previous\n is True. Defaults to None.\n reachable_idx (Optional[List[int]], optional): Indices of the\n reachable Pareto optimal solutions. Relevant if go_to_previous is\n True. Defaults to None.\n distance (Optional[float], optional): Distance to the Pareto\n optimal front. Relevant if go_to_previous is True. Defaults to\n None.\n steps_remaining (Optional[int], optional): Remaining steps in the\n navigation. Relevant if go_to_previous is True. Defaults to None.\n\n Returns:\n NautilusNavigatorRequest: Some of the given parameters are erraneous.\n \"\"\"\n # go to a previous state\n if go_to_previous:\n self._step_number = step_number\n self._navigation_point = nav_point\n self._reachable_lb = lower_bounds\n self._reachable_ub = upper_bounds\n self._reachable_idx = reachable_idx\n self._distance = distance\n self._steps_remaining = steps_remaining\n return NautilusNavigatorRequest.init_with_method(self)\n\n # compute a new navigation point closer to the Pareto front and the\n # bounds of the reachable Pareto optimal region.\n elif self._step_number == 1 or not np.allclose(\n ref_point, self._reference_point\n ):\n if self._step_number == 1:\n self._current_speed = speed\n\n proj_i = self.solve_nautilus_asf_problem(\n self._pareto_front,\n self._reachable_idx,\n ref_point,\n self._ideal,\n self._nadir,\n )\n\n self._reference_point = ref_point\n self._projection_index = proj_i\n\n elif stop:\n # new reference point given, also update speed\n self._reference_point = ref_point\n self._current_speed = speed\n\n new_nav = self.calculate_navigation_point(\n self._pareto_front[self._projection_index],\n self._navigation_point,\n self._steps_remaining,\n )\n\n self._navigation_point = new_nav\n\n new_lb, new_ub = self.calculate_bounds(\n self._pareto_front[self._reachable_idx], self._navigation_point,\n )\n\n self._reachable_lb = new_lb\n self._reachable_ub = new_ub\n\n new_dist = self.calculate_distance(\n self._navigation_point,\n self._pareto_front[self._projection_index],\n self._nadir,\n )\n\n self._distance = new_dist\n\n new_reachable = self.calculate_reachable_point_indices(\n self._pareto_front, self._reachable_lb, self._reachable_ub,\n )\n\n self._reachable_idx = new_reachable\n\n # If stop, do not update steps\n if self._steps_remaining == 1:\n # stop\n return NautilusNavigatorRequest.init_with_method(self)\n\n self._step_number += 1\n self._steps_remaining -= 1\n\n return NautilusNavigatorRequest.init_with_method(self)\n\n def calculate_reachable_point_indices(\n self,\n pareto_front: np.ndarray,\n lower_bounds: np.ndarray,\n upper_bounds: np.ndarray,\n ) -> List[int]:\n \"\"\"Calculate the indices of the reachable Pareto optimal solutions\n based on lower and upper bounds.\n\n Returns:\n List[int]: List of the indices of the reachable solutions.\n \"\"\"\n low_idx = np.all(pareto_front >= lower_bounds, axis=1)\n up_idx = np.all(pareto_front <= upper_bounds, axis=1)\n\n reachable_idx = np.argwhere(low_idx & up_idx).squeeze()\n\n return reachable_idx\n\n def solve_nautilus_asf_problem(\n self,\n pareto_f: np.ndarray,\n subset_indices: [int],\n ref_point: np.ndarray,\n ideal: np.ndarray,\n nadir: np.ndarray,\n ) -> int:\n \"\"\"Forms and solves the achievement scalarizing function to find the\n closesto point on the Pareto optimal front to the given reference\n point.\n\n Args:\n pareto_f (np.ndarray): The whole Pareto optimal front.\n subset_indices ([type]): Indices of the currently reachable solutions.\n ref_point (np.ndarray): The reference point indicating a decision\n maker's preference.\n ideal (np.ndarray): Ideal point.\n nadir (np.ndarray): Nadir point.\n\n Returns:\n int: Index of the closest point according the minimized value of the ASF.\n \"\"\"\n asf = PointMethodASF(nadir, ideal)\n scalarizer = DiscreteScalarizer(asf, {\"reference_point\": ref_point})\n solver = DiscreteMinimizer(scalarizer)\n\n tmp = np.copy(pareto_f)\n mask = np.zeros(tmp.shape[0], dtype=bool)\n mask[subset_indices] = True\n tmp[~mask] = np.nan\n\n res = solver.minimize(tmp)\n\n return res\n\n def calculate_navigation_point(\n self,\n projection: np.ndarray,\n nav_point: np.ndarray,\n steps_remaining: int,\n ) -> np.ndarray:\n \"\"\"Calculate a new navigation point based on the projection of the\n preference point to the Pareto optimal front.\n\n Args:\n projection (np.ndarray): The point on the Pareto optimal front\n closest to the preference point given by a decision maker.\n nav_point (np.ndarray): The previous navigation point.\n steps_remaining (int): How many steps are remaining in the navigation.\n\n Returns:\n np.ndarray: The new navigation point.\n \"\"\"\n new_nav_point = (\n (steps_remaining - 1) / steps_remaining\n ) * nav_point + (1 / steps_remaining) * projection\n return new_nav_point\n\n def calculate_bounds(\n self, pareto_front: np.ndarray, nav_point: np.ndarray,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Calculate the new bounds of the reachable points on the Pareto\n optimal front from a navigation point.\n\n Args:\n pareto_front (np.ndarray): The Pareto optimal front.\n nav_point (np.ndarray): The current navigation point.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: The lower and upper bounds.\n \"\"\"\n _pareto_front = np.atleast_2d(pareto_front)\n new_lower_bounds = np.zeros(_pareto_front.shape[1])\n new_upper_bounds = np.zeros(_pareto_front.shape[1])\n\n # TODO: vectorize this loop\n for r in range(_pareto_front.shape[1]):\n mask = np.zeros(_pareto_front.shape[1], dtype=bool)\n mask[r] = True\n\n subject_to = _pareto_front[:, ~mask].reshape(\n (_pareto_front.shape[0], _pareto_front.shape[1] - 1)\n )\n\n con_mask = np.all(subject_to <= nav_point[~mask], axis=1)\n\n min_val = np.min(_pareto_front[con_mask, mask])\n max_val = np.max(_pareto_front[con_mask, mask])\n\n new_lower_bounds[r] = min_val\n new_upper_bounds[r] = max_val\n\n return new_lower_bounds, new_upper_bounds\n\n def calculate_distance(\n self, nav_point: np.ndarray, projection: np.ndarray, nadir: np.ndarray\n ) -> float:\n \"\"\"Calculate the distance to the Pareto optimal front from a\n navigation point. The distance is calculated to the supplied\n projection which is assumed to lay on the front.\n\n Args:\n nav_point (np.ndarray): The navigation point.\n projection (np.ndarray): The point of the Pareto optimal front the distance is calculated to.\n nadir (np.ndarray): The nadir point of the Pareto optimal set.\n\n Returns:\n float: The distance.\n \"\"\"\n nom = np.linalg.norm(nav_point - nadir)\n denom = np.linalg.norm(projection - nadir)\n dist = (nom / denom) * 100\n\n return dist\n\n\nif __name__ == \"__main__\":\n # front = np.array([[1, 2, 3], [2, 3, 4], [2, 2, 3], [3, 2, 1]], dtype=float)\n # ideal = np.zeros(3)\n # nadir = np.ones(3) * 5\n f1 = np.linspace(1, 100, 50)\n f2 = f1[::-1] ** 2\n\n front = np.stack((f1, f2)).T\n ideal = np.min(front, axis=0)\n nadir = np.max(front, axis=0)\n\n method = NautilusNavigator((front), ideal, nadir)\n\n req = method.start()\n print(req.content[\"reachable_lb\"])\n print(req.content[\"navigation_point\"])\n print(req.content[\"reachable_ub\"])\n\n response = {\n \"reference_point\": np.array([50, 6000]),\n \"speed\": 5,\n \"go_to_previous\": False,\n \"stop\": False,\n }\n req.response = response\n req = method.iterate(req)\n req.response = response\n\n req1 = req\n\n import time\n\n while req.content[\"steps_remaining\"] > 1:\n time.sleep(1 / req.content[\"current_speed\"])\n req = method.iterate(req)\n req.response = response\n print(req.content[\"steps_remaining\"])\n print(req.content[\"reachable_lb\"])\n print(req.content[\"navigation_point\"])\n print(req.content[\"reachable_ub\"])\n\n req1.response[\"go_to_previous\"] = True\n req = method.iterate(req1)\n req.response = response\n req.response[\"go_to_previous\"] = False\n\n while req.content[\"steps_remaining\"] > 1:\n time.sleep(1 / req.content[\"current_speed\"])\n req = method.iterate(req)\n req.response = response\n print(req.content[\"steps_remaining\"])\n print(req.content[\"reachable_lb\"])\n print(req.content[\"navigation_point\"])\n print(req.content[\"reachable_ub\"])\n print(req)\n"
] |
[
[
"numpy.allclose",
"numpy.linspace",
"numpy.min",
"numpy.linalg.norm",
"numpy.stack",
"numpy.argwhere",
"numpy.all",
"numpy.max",
"numpy.copy",
"numpy.atleast_2d",
"numpy.any",
"numpy.array",
"numpy.zeros"
]
] |
Calvin-Ruiz/entitylib2
|
[
"8a8d6142628a91c24dd7c9d3e7c3c52eda20ca30"
] |
[
"entitylib2.py"
] |
[
"from random import randint\r\nfrom time import time, sleep\r\ntry:\r\n import pygame\r\nexcept:\r\n import os\r\n print(\"ImportError : Pygame wasn't installed !\")\r\n print(\"Should I install pygame right now ?\")\r\n if input().upper() in [\"OUI\", \"O\", \"Y\", \"YES\", \"INSTALL\", \"INSTALLER\", \"TRUE\", \"1\", \"CMD\", \"PIP\", \"OK\"]:\r\n print(\"Python folder detected in '\"+os.__file__[0:-10]+\"'\")\r\n file = open(\"supprime_moi.bat\", \"w\")\r\n file.write(\"cd /d \"+os.__file__[0:-10]+\"\"\"\r\npython -m pip install --upgrade pip\r\npython -m pip install pygame\"\"\")\r\n file.close()\r\n os.startfile(\"supprime_moi.bat\")\r\n input(\"Press <Entry> after complete installation of pygame\")\r\n import pygame\r\n\r\ntry:\r\n import numpy\r\n from os import listdir\r\nexcept:\r\n import os\r\n print(\"ImportError : Numpy wasn't installed !\\nFunctions 'save' and 'load' need numpy.\")\r\n print(\"Should I install pygame right now ?\")\r\n if input().upper() in [\"OUI\", \"O\", \"Y\", \"YES\", \"INSTALL\", \"INSTALLER\", \"TRUE\", \"1\", \"CMD\", \"PIP\", \"OK\"]:\r\n print(\"Python folder detected in '\"+os.__file__[0:-10]+\"'\")\r\n file = open(\"supprime_moi.bat\", \"w\")\r\n file.write(\"cd /d \"+os.__file__[0:-10]+\"\"\"\r\npython -m pip install --upgrade pip\r\npython -m pip install numpy\"\"\")\r\n file.close()\r\n os.startfile(\"supprime_moi.bat\")\r\n input(\"Press <Entry> after complete installation of numpy\")\r\n import numpy\r\n\r\npygame.init()\r\nprint(\"Hello from entitylib2 too https://github.com/Calvin-Ruiz/entitylib2\")\r\n\r\ndef save(filename):\r\n print(\"NotImplementedError : save hasn't been implemented yet.\");return None\r\n global Player, Obstacle, Fired, Entity, IA, IA_D\r\n numpy.save(\"saves/\"+filename, (Player.__dict__, Obstacle.entities, Fired.entities, Entity.entities, IA.entities, IA_D.entities))\r\n\r\ndef load(filename):\r\n \"return True if save doesn't exist\"\r\n print(\"NotImplementedError : save hasn't been implemented yet.\");return None\r\n global core, Player, Obstacle, Fired, Entity, IA, IA_D\r\n if filename in listdir(\"saves\"):\r\n N = numpy.load(\"saves/\"+filename).tolist()\r\n Player.__dict__, Obstacle.entities, Fired.entities, Entity.entities, IA.entities, IA_D.entities = N\r\n return False\r\n else:return True\r\n\r\nclass BaseEntity:\r\n def __repr__(self):\r\n text = \"--------- \"+self.name+\" ----------\\nlive : \"+str(self.live)+\"\\n--- effects ---\\n\"\r\n for a in self.effect:text+=str(a)\r\n return text+\"---------------------\"+\"-\"*len(self.name)\r\n img_format=(1, \"png\")\r\n live=20\r\n atk_freq=20\r\n atk_delay=0\r\n Size=None\r\n def chunking(self):\r\n global core\r\n \"Test if entity exit chunk\"\r\n if self.pos[0] + self.Size[0] < 0:\r\n # sortie à gauche\r\n if self.chunk[0] > core.border[0]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[0]-=1\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n self.pos[0]+=256\r\n else:\r\n self.pos[0]=-self.Size[0]\r\n elif self.pos[0] + self.Size[0] > 256:\r\n # sortie à droite\r\n if self.chunk[0] < core.border[1]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[0]+=1\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n self.pos[0]-=256\r\n else:\r\n self.pos[0]=256-self.Size[0]\r\n if self.pos[1] + self.Size[1] < 0:\r\n # sortie en haut\r\n if self.chunk[1] > core.border[2]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[1]-=1\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n self.pos[1]+=256\r\n else:\r\n self.pos[1]=-self.Size[1]\r\n elif self.pos[1] + self.Size[1] > 256:\r\n # sortie en bas\r\n if self.chunk[1] < core.border[3]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[1]+=1\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n self.pos[1]-=256\r\n else:\r\n self.pos[1]=256-self.Size[1]\r\n def apply(self, effect, delay, level):\r\n for a in self.effect:\r\n if a.name == effect.name:\r\n if a.level >= level:\r\n a.delay=delay\r\n a.level=level\r\n return None\r\n self.effect.append(effect(delay, level))\r\n self.effect[-1].init_effect(self)\r\n def apply_all(self, liste):\r\n # deprecated\r\n l=list()\r\n for a in self.effect:\r\n l.append(a.name)\r\n for a in liste:\r\n self.effect.append(a[0](a[1], a[2]))\r\n self.effect[-1].init_effect(self)\r\n def apply_all(self, liste):\r\n for e in liste:\r\n self.apply(e[0], e[1], e[2])\r\n\r\ndef write(text):\r\n global letters\r\n # créer une image\r\n b = text.split(\"\\n\")\r\n s = pygame.Surface((len(max(b))*8, len(b)*12), pygame.SRCALPHA, 32).convert_alpha()\r\n x=0\r\n y=0\r\n for a in text:\r\n if a == \"\\n\":\r\n x = 0\r\n y += 12\r\n elif a == \" \":\r\n x+=8\r\n elif a == \"\t\":\r\n x = x//64*64+64\r\n else:\r\n s.blit(letters[a], (x, y))\r\n x+=8\r\n return s\r\n\r\ndef to_str(number, force_size=True, symbol = {0:\"\", 1:\"k\", 2:\"M\", 3:\"G\", 4:\"T\"}):\r\n exposant = 0\r\n lenght = 5\r\n while number >= 10000:\r\n number = number//1000\r\n exposant += 1\r\n lenght = 4\r\n number = str(number)\r\n if len(number) > lenght:\r\n number = number[0:lenght]\r\n elif force_size:\r\n number=\" \"*(lenght-len(number))+number\r\n # longueur de 40 pixels max !\r\n return number+symbol[exposant]\r\n\r\ndef fullscreen():\r\n global core\r\n if core.fmode:\r\n pygame.display.set_mode(core.size)\r\n else:pygame.display.set_mode(core.size, pygame.FULLSCREEN)\r\n core.fmode = not core.fmode\r\n\r\ndef screenshoot():\r\n global core\r\n t=int(time())\r\n date = str(t%60) + \"s\"\r\n t//=60\r\n date = str(t%60) + \"m\" + date\r\n t//=60\r\n t+=2\r\n date = str(t%24) + \"h\" + date\r\n t//=24\r\n date = str(t) + \" on \" + date\r\n pygame.image.save(core.fen, \"screenshoots/screenshoot of day \" + date +\".bmp\")\r\n print(\"screenshoot saved as 'screenshoot of day \"+date+\"'\")\r\n\r\nclass core:\r\n __doc__ = \"Content all variables used on this library. Use with caution !\"\r\n __init__ = None\r\n area={\"entity\":[], \"obs\":[], \"static\":[]}\r\n model = list()\r\n while len(model) < 64:\r\n model.append([])\r\n model = str(tuple(model))\r\n a=0\r\n while a < 64:\r\n area[\"entity\"].append(eval(model))\r\n a+=1\r\n area[\"entity\"] = tuple(area[\"entity\"])\r\n a=0\r\n while a < 64:\r\n area[\"obs\"].append(eval(model))\r\n a+=1\r\n area[\"obs\"] = tuple(area[\"obs\"])\r\n a=0\r\n while a < 64:\r\n area[\"static\"].append(eval(model))\r\n a+=1\r\n area[\"static\"] = tuple(area[\"static\"])\r\n score=0\r\n border = None\r\n fmode = False\r\n size = None # fen size\r\n fen = None\r\n S = None # chunk size\r\n tic=0 # reset when tic == 360\r\n timer=0 # nombre de 0,3 minutes écoulées depuis le début de la partie (si aucun lags)\r\n timexe = time()\r\n lags = -1\r\n images = []\r\n jauges = []\r\n def refresh():pass\r\n try:\r\n img = pygame.image.load(\"textures/background.bmp\")\r\n except:\r\n img = pygame.image.load(\"textures/default.bmp\")\r\n Bsize=img.get_size()\r\n Bnum=None\r\n\r\nletters=dict()\r\nimgeff = dict()\r\n\r\ndef init(MobTypes, fen_size=(1536, 1024)):\r\n \"MobTypes : tuple of all created class\\nInitializing all class in tuple\"\r\n global core, Fired, Player, letters, imgeff\r\n print(\"Initialisation...\")\r\n core.S=(fen_size[0]//256+1, fen_size[1]//256+1)\r\n core.size = ((core.S[0]-1)*256, (core.S[1]-1)*256)\r\n core.fen = pygame.display.set_mode(core.size)\r\n core.Bnum = (core.size[0]//core.Bsize[0]+2, core.size[1]//core.Bsize[1]+2)\r\n core.border = (core.S[0]-2, 65-core.S[0], core.S[1]-2, 65-core.S[1])\r\n files = listdir(\"textures\")\r\n for a in MobTypes + (Player,):\r\n if max(a.size) > 128:print(\"Warning : maximal size is 128 and \"+str(max(a.size))+\" > 128\")\r\n a.name = a.__name__\r\n if a.sound != None:a.sounded=True;a.sound=pygame.mixer.Sound(\"sounds/\"+a.sound)\r\n if type(a.img_format) is str:\r\n if a.name + \".\" + a.img_format in files:\r\n a.img = pygame.transform.scale(pygame.image.load(\"textures/\" + a.name + \".\"+a.img_format), a.size)\r\n else:\r\n a.img = pygame.transform.scale(pygame.image.load(\"textures/default.bmp\"), a.size)\r\n continue\r\n a.Size = (a.size[0]//2, a.size[1]//2)\r\n try:\r\n imgs = pygame.image.load(\"textures/\" + a.name + \".\"+a.img_format[-1])\r\n except:\r\n imgs = pygame.image.load(\"textures/default.bmp\")\r\n a.img = list()\r\n b=0\r\n size = imgs.get_size()\r\n if len(a.img_format) == 3:\r\n size = (size[0]//a.img_format[0], size[1]//a.img_format[1])\r\n while b < a.img_format[1]:\r\n c=0\r\n a.img.append(list())\r\n while c < a.img_format[0]:\r\n c+=1\r\n img=pygame.Surface(size, pygame.SRCALPHA, 32).convert_alpha()\r\n img.blit(imgs, ((c - a.img_format[0])*size[0], (1+b - a.img_format[1])*size[1]))\r\n a.img[b].append(pygame.transform.scale(img, a.size))\r\n b+=1\r\n elif a.__class__ is Fired:\r\n c=0\r\n while c < a.img_format[0]:\r\n img=pygame.Surface(size, pygame.SRCALPHA, 32).convert_alpha()\r\n img.blit(imgs, (-size[0]*c, 0))\r\n a.img.append(pygame.transform.scale(img, a.size))\r\n c+=1\r\n else:\r\n size = (size[0]//a.img_format[0], size[1])\r\n while b < 4:\r\n c=0\r\n a.img.append(list())\r\n while c < a.img_format[0]:\r\n img=pygame.Surface(size, pygame.SRCALPHA, 32).convert_alpha()\r\n img.blit(imgs, (-size[0]*c, 0))\r\n a.img[b].append(pygame.transform.scale(pygame.transform.rotate(img, (4-b)*90), a.size))\r\n c+=1\r\n b+=1\r\n for image in listdir(\"textures/letter\"):\r\n letters.__setitem__(image[0:-4], pygame.image.load(\"textures/letter/\"+image))\r\n for image in listdir(\"textures/letters\"):\r\n letters.__setitem__(image[0:-4], pygame.image.load(\"textures/letters/\"+image))\r\n for image in listdir(\"textures/effect\"):\r\n imgeff.__setitem__(image[0:-4], pygame.image.load(\"textures/effect/\"+image))\r\n print(\"Librairie et entités initialisées\")\r\n\r\ndef NoWeapon(a, b):pass\r\n\r\nclass player(BaseEntity):\r\n __doc__=\"\"\"Contiend tout ce qui est en rapport avec le joueur.\r\nUtiliser Player.effect.append(effect) pour ajouter un effet au joueur\r\nUtiliser MyEffect = effect(*args) pour créer un nouvel effet.\"\"\"\r\n __name__=\"Player\"\r\n def __init__(self):\r\n global Player\r\n self.effect=list()\r\n self.atk_delay = 0\r\n pos = [48, 48]\r\n move = [0, 0]\r\n chunk = [31,31]\r\n size = (32, 32)\r\n live = 20\r\n dir = 0\r\n img = None\r\n atk_delay = 0\r\n atk_freq = 10\r\n weapon = NoWeapon\r\n frame = 0\r\n speed = 3\r\n react = None\r\n sound = None\r\n sounded=False\r\n def chunking(self):\r\n global core\r\n \"Test if entity exit chunk\"\r\n if self.pos[0] + self.Size[0] < 0:\r\n # sortie à gauche\r\n if self.chunk[0] > core.border[0]:\r\n self.chunk[0]-=1\r\n self.pos[0]+=256\r\n else:\r\n self.pos[0]=-self.Size[0]\r\n elif self.pos[0] + self.Size[0] > 256:\r\n # sortie à droite\r\n if self.chunk[0] < core.border[1]:\r\n self.chunk[0]+=1\r\n self.pos[0]-=256\r\n else:\r\n self.pos[0]=256-self.Size[0]\r\n if self.pos[1] + self.Size[1] < 0:\r\n # sortie en haut\r\n if self.chunk[1] > core.border[2]:\r\n self.chunk[1]-=1\r\n self.pos[1]+=256\r\n else:\r\n self.pos[1]=-self.Size[1]\r\n elif self.pos[1] + self.Size[1] > 256:\r\n # sortie en bas\r\n if self.chunk[1] < core.border[3]:\r\n self.chunk[1]+=1\r\n self.pos[1]-=256\r\n else:\r\n self.pos[1]=256-self.Size[0]\r\n def collide(self):\r\n global core, IA, IA_D, Static, Obstacle, Entity\r\n cond = False\r\n x, y = self.pos\r\n a=0\r\n x+=256\r\n y+=256\r\n while a < 9:\r\n if a%3:\r\n x-=256\r\n elif a//3:\r\n x+=512\r\n y-=256\r\n for e in core.area[\"entity\"][self.chunk[0]+a%3-1][self.chunk[1]+a//3-1]:\r\n if e.pos[0] + e.size[0] > x and x + self.size[0] > e.pos[0] and e.pos[1] + e.size[1] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n coll=True\r\n if x + self.size[0] + e.move[0]*e.speed <= e.pos[0] + self.move[0]*self.speed + 0.4*(e.speed+self.speed):\r\n # droite\r\n if self.move[0]==1:x -= self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==-1:e.pos[0] += e.speed * (1 - 0.3 * abs(e.move[1]))\r\n elif x + e.move[0]*e.speed + 0.4*(e.speed+self.speed) >= e.pos[0] + e.size[0] + self.move[0]*self.speed:\r\n # gauche\r\n if self.move[0]==-1:x += self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==1:e.pos[0] -= e.speed * (1 - 0.3 * abs(e.move[1]))\r\n if y + self.size[1] + e.move[1]*e.speed <= e.pos[1] + self.move[1]*self.speed + 0.4*(e.speed+self.speed):\r\n # bas\r\n if self.move[1]==1:y -= self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==-1:e.pos[1] += e.speed * (1 - 0.3 * abs(e.move[0]))\r\n elif y + e.move[1]*e.speed + 0.4*(e.speed+self.speed) >= e.pos[1] + e.size[1] + self.move[1]*self.speed:\r\n # haut\r\n if self.move[1]==-1:y += self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==1:e.pos[1] -= e.speed * (1 - 0.3 * abs(e.move[0]))\r\n if e.atk_delay == 0:\r\n e.atk_delay = e.atk_freq\r\n self.live+=-e.dmg\r\n if self.sounded:self.sound.play()\r\n a+=1\r\n a=0\r\n x+=512\r\n y+=512\r\n while a < 4:\r\n if a%2:\r\n x-=256\r\n elif a//2:\r\n x+=256\r\n y-=256\r\n for e in core.area[\"obs\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[2] > x and x + self.size[0] > e.pos[0] and e.pos[3] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n coll=True\r\n if self.move[0] == 1 and x + self.size[0] <= e.pos[0] + self.speed:\r\n # droite\r\n x = e.pos[0] - self.size[0]\r\n elif self.move[0] == -1 and e.pos[2] <= x + self.speed:\r\n # gauche\r\n x = e.pos[0] + e.size[0]\r\n elif self.move[1] == 1 and y + self.size[1] <= e.pos[1] + self.speed:\r\n # bas\r\n y = e.pos[1] - self.size[1]\r\n elif self.move[1] == -1 and e.pos[3] <= y + self.speed:\r\n # haut\r\n y = e.pos[1] + e.size[1]\r\n for e in core.area[\"static\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e[2][0] > x and x + self.size[0] > e[1][0] and e[2][1] > y and y + self.size[1] > e[1][1]:\r\n # collision\r\n coll=True\r\n if self.move[0] == 1 and x + self.size[0] <= e[1][0] + self.speed:\r\n # droite\r\n x = e[1][0] - self.size[0]\r\n elif self.move[0] == -1 and e[2][0] <= x + self.speed:\r\n # gauche\r\n x = e[2][0]\r\n elif self.move[1] == 1 and y + self.size[1] <= e[1][1] + self.speed:\r\n # bas\r\n y = e[1][1] - self.size[1]\r\n elif self.move[1] == -1 and e[2][1] <= y + self.speed:\r\n # haut\r\n y = e[2][1]\r\n a+=1\r\n if self.atk_delay > 0:\r\n self.atk_delay+=-1\r\n self.pos[0]=x\r\n self.pos[1]=y\r\n\r\nclass Static:\r\n __doc__ = \"\"\"Utiliser 'nom = Static(*args)' pour créer un mur.\r\nUtiliser nom.append(pos, chunk) pour ajouter une mur.\r\nRenvoie un type d'objet indestructible et immobile.\r\nTout objet Static ne pourra jamais être traversé, il sera toujours 'solide'.\r\nimg_format : format de l'image ('png' par défaut)\r\nsize : tuple de la hauteur et de la largeur de l'entité désiré\"\"\"\r\n def __init__(self, name, size, img_format=\"png\"):\r\n global Static\r\n self.img = pygame.transform.scale(pygame.image.load(\"textures/\"+name + \".\"+img_format), size)\r\n self.size = size\r\n def append(self, pos, chunk):\r\n \"pos : position du mur dans le chunk de 0 à 255 (exemple : (314,159))\\nchunk : chunk contenant le mur de -29 à 29 (exemple : (1,-2))\"\r\n global core\r\n self.pos = pos + (pos[0]+self.size[0], pos[1]+self.size[1])\r\n a = (pos[0]+self.size[0]//2-128)//256\r\n b = (pos[1]+self.size[1]//2-128)//256\r\n chunk = list(chunk)\r\n pos = list(pos)\r\n chunk[0] += a+31\r\n chunk[1] += b+31\r\n pos[0] += -a*256\r\n pos[1] += -b*256\r\n core.area[\"static\"][chunk[0]][chunk[1]].append((self.img, pos, (pos[0]+self.size[0], pos[1]+self.size[1])))\r\n\r\nclass Obstacle:\r\n __doc__ = \"\"\"Utiliser 'class <nom>(Obstacle):' pour créer un obstacle (similaire à mur).\r\nAttributs de ce type de classe :\r\nlive : points de vie de l'obstacle\r\nimg_format : format de l'image ('png' par défaut)\r\nsize : tuple de la hauteur et de la largeur de l'entité désiré\r\nCe type d'objet est statique mais destructible.\"\"\"\r\n entities = []\r\n def __init__(self, pos, chunk):\r\n global core\r\n self.pos = pos + (pos[0]+self.size[0], pos[1]+self.size[1])\r\n self.chunk = (chunk[0]+31, chunk[1]+31)\r\n self.entities.append(self)\r\n core.area[\"obs\"][self.chunk[0]][self.chunk[1]].append(self)\r\n \r\n img_format=\"png\"\r\n img=None\r\n sounded = False\r\n sound = None\r\n def clean():\r\n global Obstacle,core\r\n a=0;b=len(Obstacle.entities)\r\n while a < b:\r\n if Obstacle.entities[a].live <= 0:\r\n core.area[\"obs\"][Obstacle.entities[a].chunk[0]][Obstacle.entities[a].chunk[1]].remove(Obstacle.entities[a])\r\n del Obstacle.entities[a]\r\n b+=-1\r\n else:a+=1\r\n\r\ndef Rien(self):pass\r\n\r\nclass Fired:\r\n __doc__ = \"\"\"Utiliser 'class <nom>(Fired):' pour créer un projectile.\r\nEntités mobiles (exemple : flèche)\r\nAttributs de ce type de classe :\r\nspeed : vitesse de déplacement (0 par défaut)\r\npcoll : activer la collision avec le joueur (True par défaut)\r\necoll : activer la collision avec les entités (True par défaut)\r\naction : action supplémentaire quand contact avec le joueur (renvoie le projectile comme argument)\r\ndmg : dégâts infligés à l'objet/entité touché (0 par défaut)\r\ndelay : durée de vie du projectile (en tic) (-1 par défaut)\r\nimg_format : format du \"tableau d'image\" ((1, 'png') par défaut)\r\neffects : effets appliqués à l'entité touché.\r\neffects = ((effet1, temps, niveau), etc...)\r\nPeut être sous la forme (nbr_frames, nbr_directions, format)\r\nOu avec une rotation automatique si sous la forme (nbr_frames, format)\r\nCe type d'entité se détruit au contact en infligeant des dégats\"\"\"\r\n entities = []\r\n actives = []\r\n speed = 0\r\n pcoll = True\r\n ecoll = True\r\n action = Rien\r\n sounded = False\r\n sound = None\r\n frame = 0\r\n dmg = 0\r\n delay = -1\r\n effects = tuple()\r\n img_format = (1, \"png\")\r\n img=None\r\n def __init__(self, pos, chunk, move):\r\n \"\"\"pos : position du projectile (exemple : (367, -23) )\r\nmove : mouvement du projectile en x et en y.\r\n1 : mouvement positif, 0 : immobile et -1 : mouvement négatif\r\n(exemple : (-1, 1) )\"\"\"\r\n global Player\r\n self.frame = randint(1-self.img_format[0], 0)\r\n self.pos = list(pos)\r\n self.chunk = list(chunk)\r\n if move == [0,0]:move=list({0:(1, 0), 1:(0, 1), 2:(-1, 0), 3:(0, -1)}[Player.dir])\r\n self.move = move\r\n img=list()\r\n for a in self.img[0]:\r\n img.append(pygame.transform.rotate(a, {(1, 0) : 0,(1, 1) : 45,(0, 1) : 90,(-1, 1) : 135,(-1, 0) : 180,(-1, -1): 225,(0, -1) : 270,(1, -1) : 315}[tuple(move)]))\r\n self.img=img\r\n self.entities.append(self)\r\n self.actives.append(self.react)\r\n\r\n def clean():\r\n global Fired\r\n a=0;b=len(Fired.entities)\r\n while a < b:\r\n if Fired.entities[a].delay == 0:\r\n if Fired.entities[a].sounded:Fired.entities[a].sound.play()\r\n del Fired.entities[a]\r\n del Fired.actives[a]\r\n b+=-1\r\n else:a+=1\r\n def react(self):\r\n global core\r\n \"Test if entity exit chunk\"\r\n if self.pos[0] + self.Size[0] < 0:\r\n # sortie à gauche\r\n if self.chunk[0] > 1:\r\n self.chunk[0]-=1\r\n self.pos[0]+=256\r\n else:\r\n self.pos[0]=0\r\n elif self.pos[0] + self.Size[0] > 256:\r\n # sortie à droite\r\n if self.chunk[0] < 62:\r\n self.chunk[0]+=1\r\n self.pos[0]-=256\r\n else:\r\n self.pos[0]=256-self.size[0]\r\n if self.pos[1] + self.Size[1] < 0:\r\n # sortie en haut\r\n if self.chunk[1] > 1:\r\n self.chunk[1]-=1\r\n self.pos[1]+=256\r\n else:\r\n self.pos[1]=0\r\n elif self.pos[1] + self.Size[1] > 256:\r\n # sortie en bas\r\n if self.chunk[1] < 62:\r\n self.chunk[1]+=1\r\n self.pos[1]-=256\r\n else:\r\n self.pos[1]=256-self.size[1]\r\n if self.delay>0:self.delay += -1\r\n x = self.pos[0] + self.move[0] * (self.speed * (1 - 0.3 * abs(self.move[1])))\r\n y = self.pos[1] + self.move[1] * (self.speed * (1 - 0.3 * abs(self.move[0])))\r\n if self.pcoll and Player.pos[0] + Player.size[0] > x and x + self.size[0] > Player.pos[0] and Player.pos[1] + Player.size[1] > y and y + self.size[1] > Player.pos[1]:\r\n # collision\r\n self.action()\r\n self.delay = 0\r\n Player.live += -self.dmg\r\n e.apply_all(self.effects)\r\n if Player.sounded:Player.sound.play()\r\n x+=256\r\n y+=256\r\n for a in range(0,4):\r\n if a%2:\r\n x+=-256\r\n elif a//2:\r\n x+=256\r\n y-=256\r\n if self.ecoll:\r\n for e in core.area[\"entity\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[0] + e.size[0] > x and x + self.size[0] > e.pos[0] and e.pos[1] + e.size[1] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n self.delay = 0\r\n e.live -= self.dmg\r\n e.apply_all(self.effects)\r\n if e.sounded:e.sound.play()\r\n for e in core.area[\"obs\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[2] > x and x + self.size[0] > e.pos[0] and e.pos[3] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n self.delay = 0\r\n e.live -= self.dmg\r\n if e.sounded:e.sound.play()\r\n for e in core.area[\"static\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e[2][0] > x and x + self.size[0] > e[1][0] and e[2][1] > y and y + self.size[1] > e[1][1]:\r\n # collision\r\n self.delay = 0\r\n self.pos[0]=x\r\n self.pos[1]=y\r\n\r\ndef Suivre(self):\r\n global core\r\n a = self.pos[0] - Player.pos[0] + 256*(self.chunk[0] - Player.chunk[0])\r\n b = self.pos[1] - Player.pos[1] + 256*(self.chunk[1] - Player.chunk[1])\r\n c = abs(a) > abs(b)\r\n if a < 0:\r\n if c:\r\n self.move[0] = 1\r\n self.dir=0\r\n else:\r\n if a == 0:pass\r\n elif abs(a) > self.speed:self.move[0] = 1\r\n else:\r\n self.move[0] = 0\r\n self.pos[0] = Player.pos[0]\r\n if self.chunk[0] != Player.chunk[0]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[0]=Player.chunk[0]\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n else:\r\n if c:\r\n self.move[0] = -1\r\n self.dir=2\r\n else:\r\n if a == 0:pass\r\n elif abs(a) > self.speed:self.move[0] = -1\r\n else:\r\n self.move[0] = 0\r\n self.pos[0] = Player.pos[0]\r\n if self.chunk[0] != Player.chunk[0]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[0]=Player.chunk[0]\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n if b < 0:\r\n if c:\r\n if b == 0:pass\r\n elif abs(b) > self.speed:self.move[1] = 1\r\n else:\r\n self.move[1] = 0\r\n self.pos[1] = Player.pos[1]\r\n if self.chunk[1] != Player.chunk[1]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[1]=Player.chunk[1]\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n else:\r\n self.move[1] = 1\r\n self.dir=1\r\n else:\r\n if c:\r\n if b == 0:pass\r\n elif abs(b) > self.speed:self.move[1] = -1\r\n else:\r\n self.move[1] = 0\r\n self.pos[1] = Player.pos[1]\r\n if self.chunk[1] != Player.chunk[1]:\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].remove(self)\r\n self.chunk[1]=Player.chunk[1]\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n else:\r\n self.move[1] = -1\r\n self.dir=3\r\n\r\nclass Entity(BaseEntity):\r\n __doc__ = \"\"\"Utiliser 'class <nom>(Fired):' pour créer une entité.\r\nEntités simples (trajectoire aléatoire) sauf si joueur à proximité\r\nAttributs de ce type de classe :\r\nlive : vie de l'entité (100 par défaut)\r\nimg_format : format du \"tableau d'image\" ((1, 'png') par défaut)\r\nPeut être sous la forme (nbr_frames, nbr_directions, format)\r\nOu avec une rotation automatique si sous la forme (nbr_frames, format)\r\ndmg : dégats infligés à la cible (5 par défaut)\r\natk_freq : temps (en tic) entre 2 attaques de l'IA (20 par défaut)\r\nspeed : vitesse de déplacement de l'entité\r\nrange : distance de vue de l'entité\r\nxp : nombre de points gagnés lorsque l'entité est tuée\"\"\"\r\n dmg=2\r\n xp=0\r\n dir=0\r\n speed = 2\r\n img=None\r\n range = 500\r\n entities = []\r\n actives = []\r\n sounded = False\r\n sound = None\r\n def __init__(self, pos, chunk):\r\n global core\r\n self.effect = list()\r\n self.frame = randint(1-self.img_format[0], 0)\r\n self.pos = list(pos)\r\n self.chunk = [chunk[0]+31, chunk[1]+31]\r\n self.move = [0, 0] # mouvement\r\n self.dir = 0 # direction\r\n self.atk_delay = 0\r\n self.entities.append(self)\r\n self.actives.append(self.react)\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n def clean():\r\n global Entity, core\r\n a=0;b=len(Entity.entities)\r\n while a < b:\r\n if Entity.entities[a].live <= 0:\r\n E = Entity.entities[a]\r\n core.score+=E.xp\r\n core.area[\"entity\"][E.chunk[0]][E.chunk[1]].remove(E)\r\n del Entity.entities[a]\r\n del Entity.actives[a]\r\n b+=-1\r\n else:a+=1\r\n suivre = Suivre\r\n def react(self):\r\n if abs(self.chunk[0] - Player.chunk[0]) + abs(self.chunk[1] - Player.chunk[1]) < self.range:self.suivre()\r\n self.pos[0] += self.move[0] * self.speed * (1-abs(self.move[1]) * 0.3)\r\n self.pos[1] += self.move[1] * self.speed * (1-abs(self.move[0]) * 0.3)\r\n self.chunking()\r\n self.collide()\r\n def collide(self):\r\n global Player, IA, IA_D, Static, Obstacle, Entity\r\n cond = False\r\n x, y = self.pos[0:2]\r\n a=0\r\n x+=256\r\n y+=256\r\n while True:\r\n if a%2:\r\n x-=256\r\n elif a//2:\r\n x+=256\r\n y-=256\r\n for e in core.area[\"entity\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[0] + e.size[0] > x and x + self.size[0] > e.pos[0] and e.pos[1] + e.size[1] > y and y + self.size[1] > e.pos[1]:\r\n if e is self:continue\r\n # collision\r\n coll=True\r\n unsolved=True\r\n if x + self.size[0] + e.move[0]*e.speed <= e.pos[0] + self.move[0]*self.speed + 0.3*(e.speed+self.speed):\r\n # droite\r\n if self.move[0]==1:x -= self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==-1:e.pos[0] += e.speed * (1 - 0.3 * abs(e.move[1]))\r\n unsolved=False\r\n elif x + e.move[0]*e.speed + 0.3*(e.speed+self.speed) >= e.pos[0] + e.size[0] + self.move[0]*self.speed:\r\n # gauche\r\n if self.move[0]==-1:x += self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==1:e.pos[0] -= e.speed * (1 - 0.3 * abs(e.move[1]))\r\n unsolved=False\r\n if y + self.size[1] + e.move[1]*e.speed <= e.pos[1] + self.move[1]*self.speed + 0.3*(e.speed+self.speed):\r\n # bas\r\n if self.move[1]==1:y -= self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==-1:e.pos[1] += e.speed * (1 - 0.3 * abs(e.move[0]))\r\n unsolved=False\r\n elif y + e.move[1]*e.speed + 0.3*(e.speed+self.speed) >= e.pos[1] + e.size[1] + self.move[1]*self.speed:\r\n # haut\r\n if self.move[1]==-1:y += self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==1:e.pos[1] -= e.speed * (1 - 0.3 * abs(e.move[0]))\r\n unsolved=False\r\n if unsolved:\r\n # méthode anti-superposition !\r\n if self.move[0]==1:x -= self.speed * (2 - 0.6 * abs(self.move[1]))\r\n elif self.move[0]==-1:x += self.speed * (2 - 0.6 * abs(self.move[1]))\r\n if self.move[1]==1:y -= self.speed * (2 - 0.6 * abs(self.move[0]))\r\n elif self.move[1]==-1:y += self.speed * (2 - 0.6 * abs(self.move[0]))\r\n if a == 4:break\r\n for e in core.area[\"obs\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[2] > x and x + self.size[0] > e.pos[0] and e.pos[3] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n coll=True\r\n if x + self.size[0] <= e.pos[0] + self.speed:\r\n # droite\r\n x = e.pos[0] - self.size[0]\r\n elif e.pos[2] <= x + self.speed:\r\n # gauche\r\n x = e.pos[2]\r\n elif y + self.size[1] <= e.pos[1] + self.speed:\r\n # bas\r\n y = e.pos[1] - self.size[1]\r\n elif e.pos[3] <= y + self.speed:\r\n # haut\r\n y = e.pos[3]\r\n for e in core.area[\"static\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e[2][0] > x and x + self.size[0] > e[1][0] and e[2][1] > y and y + self.size[1] > e[1][1]:\r\n # collision\r\n coll=True\r\n if x + self.size[0] <= e[1][0] + self.speed:\r\n # droite\r\n x = e[1][0] - self.size[0]\r\n elif e[2][0] <= x + self.speed:\r\n # gauche\r\n x = e[2][0]\r\n elif y + self.size[1] <= e[1][1] + self.speed:\r\n # bas\r\n y = e[1][1] - self.size[1]\r\n elif e[2][1] <= y + self.speed:\r\n # haut\r\n y = e[2][1]\r\n a+=1\r\n if self.atk_delay > 0:\r\n self.atk_delay+=-1\r\n if cond:\r\n self.move[0] = randint(-1, 1)\r\n self.move[1] = randint(-1, 1)\r\n self.pos[0]=x-256\r\n self.pos[1]=y+256\r\n\r\nclass IA(BaseEntity):\r\n __doc__ = \"\"\"Utiliser 'class <nom>(IA):' pour créer une IA.\r\nEntités intelligentes ! (exemple : monstre)\r\nAttributs de ce type de classe :\r\nlive : vie de l'entité (100 par défaut)\r\nimg_format : format du \"tableau d'image\" ((1, 'png') par défaut)\r\nPeut être sous la forme (nbr_frames, nbr_directions, format)\r\nOu avec une rotation automatique si sous la forme (nbr_frames, format)\r\ndmg : dégats infligés à la cible (5 par défaut)\r\natk_freq : temps (en tic) entre 2 attaques de l'IA (20 par défaut)\r\ndelay : temps de vie (en tic) de l'IA (-1 par défaut)\r\nspeed : vitesse de déplacement de l'IA\r\nxp : nombre de points gagnés lorsque l'IA est tuée\"\"\"\r\n dmg=2\r\n delay = 0\r\n xp=0\r\n dir=0\r\n speed = 2\r\n indirect=0\r\n img=None\r\n sounded = False\r\n sound = None\r\n entities = []\r\n actives = []\r\n def clean():\r\n global IA, core\r\n a=0;b=len(IA.entities)\r\n while a < b:\r\n if IA.entities[a].delay == 0 or IA.entities[a].live <= 0:\r\n I = IA.entities[a]\r\n if I.delay != 0:core.score+=I.xp\r\n core.area[\"entity\"][I.chunk[0]][I.chunk[1]].remove(I)\r\n del IA.entities[a]\r\n del IA.actives[a]\r\n b+=-1\r\n else:\r\n a+=1\r\n def __init__(self, pos, chunk):\r\n global core\r\n self.effect = list()\r\n self.frame = randint(1-self.img_format[0], 0)\r\n self.pos = list(pos)\r\n self.chunk = [chunk[0]+31, chunk[1]+31]\r\n self.move = [0,0] # mouvement\r\n self.dir = 0 # direction\r\n self.DIR = 0 # direction initiale\r\n self.atk_delay = 0\r\n self.indirect = 0\r\n self.entities.append(self)\r\n self.actives.append(self.react)\r\n core.area[\"entity\"][self.chunk[0]][self.chunk[1]].append(self)\r\n suivre = Suivre\r\n def react(self):\r\n global Player\r\n if not self.indirect:self.suivre()\r\n self.pos[0] += self.move[0] * self.speed * (1-abs(self.move[1]) * 0.3)\r\n self.pos[1] += self.move[1] * self.speed * (1-abs(self.move[0]) * 0.3)\r\n self.chunking()\r\n self.collide()\r\n def collide(self):\r\n global Player, IA, IA_D, Static, Obstacle, Entity\r\n self.delay+=-1\r\n cond = True\r\n x, y = self.pos[0:2]\r\n a=0\r\n x+=256\r\n y+=256\r\n while True:\r\n if a%2:\r\n x-=256\r\n elif a//2:\r\n x+=256\r\n y-=256\r\n for e in core.area[\"entity\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[0] + e.size[0] > x and x + self.size[0] > e.pos[0] and e.pos[1] + e.size[1] > y and y + self.size[1] > e.pos[1]:\r\n if e is self:continue\r\n # collision\r\n coll=True\r\n unsolved = True\r\n if x + self.size[0] + e.move[0]*e.speed <= e.pos[0] + self.move[0]*self.speed + 0.3*(e.speed+self.speed):\r\n # droite\r\n if self.move[0]==1:x -= self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==-1:e.pos[0] += e.speed * (1 - 0.3 * abs(e.move[1]))\r\n unsolved = False\r\n elif x + e.move[0]*e.speed + 0.3*(e.speed+self.speed) >= e.pos[0] + e.size[0] + self.move[0]*self.speed:\r\n # gauche\r\n if self.move[0]==-1:x += self.speed * (1 - 0.3 * abs(self.move[1]))\r\n if e.move[0]==1:e.pos[0] -= e.speed * (1 - 0.3 * abs(e.move[1]))\r\n unsolved = False\r\n if y + self.size[1] + e.move[1]*e.speed <= e.pos[1] + self.move[1]*self.speed + 0.3*(e.speed+self.speed):\r\n # bas\r\n if self.move[1]==1:y -= self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==-1:e.pos[1] += e.speed * (1 - 0.3 * abs(e.move[0]))\r\n unsolved = False\r\n elif y + e.move[1]*e.speed + 0.3*(e.speed+self.speed) >= e.pos[1] + e.size[1] + self.move[1]*self.speed:\r\n # haut\r\n if self.move[1]==-1:y += self.speed * (1 - 0.3 * abs(self.move[0]))\r\n if e.move[1]==1:e.pos[1] -= e.speed * (1 - 0.3 * abs(e.move[0]))\r\n unsolved = False\r\n if unsolved:\r\n # méthode anti-superposition !\r\n if self.move[0]==1:x -= self.speed * (2 - 0.6 * abs(self.move[1]))\r\n elif self.move[0]==-1:x += self.speed * (2 - 0.6 * abs(self.move[1]))\r\n if self.move[1]==1:y -= self.speed * (2 - 0.6 * abs(self.move[0]))\r\n elif self.move[1]==-1:y += self.speed * (2 - 0.6 * abs(self.move[0]))\r\n if a == 4:break\r\n for e in core.area[\"obs\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e.pos[2] > x and x + self.size[0] > e.pos[0] and e.pos[3] > y and y + self.size[1] > e.pos[1]:\r\n # collision\r\n if x + self.size[0] <= e.pos[0] + self.speed:\r\n # droite\r\n x = e.pos[0] - self.size[0]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 1:cond = False\r\n elif self.dir == 0:\r\n self.dir = 1\r\n self.move[1] = 1\r\n cond = False\r\n elif self.dir == 0:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 1\r\n self.move[1] = 1\r\n self.indirect = 1\r\n self.DIR = 0\r\n cond = False\r\n elif e.pos[2] <= x + self.speed:\r\n # gauche\r\n x = e.pos[2]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 3:cond = False\r\n elif self.dir == 2:\r\n self.dir = 3\r\n self.move[1] = -1\r\n cond = False\r\n elif self.dir == 2:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 3\r\n self.move[1] = -1\r\n self.indirect = 1\r\n self.DIR = 2\r\n cond = False\r\n elif y + self.size[1] <= e.pos[1] + self.speed:\r\n # bas\r\n y = e.pos[1] - self.size[1]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 2:cond = False\r\n elif self.dir == 1:\r\n self.dir = 2\r\n self.move[0] = -1\r\n cond = False\r\n elif self.dir == 1:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 2\r\n self.move[0] = -1\r\n self.indirect = 1\r\n self.DIR = 1\r\n cond = False\r\n elif e.pos[3] <= y + self.speed:\r\n # haut\r\n y = e.pos[3]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 0:cond = False\r\n elif self.dir == 3:\r\n self.dir = 0\r\n self.move[0] = 1\r\n cond = False\r\n elif self.dir == 3:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 0\r\n self.move[0] = 1\r\n self.indirect = 1\r\n self.DIR = 3\r\n cond = False\r\n for e in core.area[\"static\"][self.chunk[0]+a%2-1][self.chunk[1]+a//2-1]:\r\n if e[2][0] > x and x + self.size[0] > e[1][0] and e[2][1] > y and y + self.size[1] > e[1][1]:\r\n # collision\r\n if x + self.size[0] <= e[1][0] + self.speed:\r\n # droite\r\n x = e[1][0] - self.size[0]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 1:cond = False\r\n elif self.dir == 0:\r\n self.dir = 1\r\n self.move[1] = 1\r\n cond = False\r\n elif self.dir == 0:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 1\r\n self.move[1] = 1\r\n self.indirect = 1\r\n self.DIR = 0\r\n cond = False\r\n elif e[2][0] <= x + self.speed:\r\n # gauche\r\n x = e[2][0]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 3:cond = False\r\n elif self.dir == 2:\r\n self.dir = 3\r\n self.move[1] = -1\r\n cond = False\r\n elif self.dir == 2:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 3\r\n self.move[1] = -1\r\n self.indirect = 1\r\n self.DIR = 2\r\n cond = False\r\n elif y + self.size[1] <= e[1][1] + self.speed:\r\n # bas\r\n y = e[1][1] - self.size[1]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 2:cond = False\r\n elif self.dir == 1:\r\n self.dir = 2\r\n self.move[0] = -1\r\n cond = False\r\n elif self.dir == 1:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 2\r\n self.move[0] = -1\r\n self.indirect = 1\r\n self.DIR = 1\r\n cond = False\r\n elif e[2][1] <= y + self.speed:\r\n # haut\r\n y = e[2][1]\r\n if self.indirect == 1:\r\n # On est déja en train de contourner un obstacle\r\n if self.dir == 0:cond = False\r\n elif self.dir == 3:\r\n self.dir = 0\r\n self.move[0] = 1\r\n cond = False\r\n elif self.dir == 3:\r\n # On se cogne juste contre un mur dans sa direction\r\n self.dir = 0\r\n self.move[0] = 1\r\n self.indirect = 1\r\n self.DIR = 3\r\n cond = False\r\n a+=1\r\n if self.indirect == 1 and cond:\r\n self.dir = (self.dir - 1)%4\r\n self.move[self.dir%2] = -self.move[self.dir%2]\r\n if self.dir == self.DIR:\r\n self.indirect = 0\r\n if self.atk_delay > 0:\r\n self.atk_delay+=-1\r\n rem = list()\r\n for a in self.effect:\r\n a.delay+=-1\r\n if a.delay == 0:\r\n a.end_effect(self)\r\n rem.append(a)\r\n else:\r\n a.active_effect(self)\r\n for a in rem:\r\n self.effect.remove(a)\r\n self.pos[0]=x-256\r\n self.pos[1]=y+256\r\n\r\nclass IA_D(IA):\r\n __doc__ = \"\"\"Utiliser 'class <nom>(IA_D):' pour créer une IA lançant des projectiles sur le joueur.\r\nEntités intelligentes ! (exemple : archer)\r\nAttributs de ce type de classe :\r\nTous les attributs de IA\r\nweapon : projectile lancé par l'IA\"\"\"\r\n entities = []\r\n actives = []\r\n def __init__(self, pos=None):raise NotImplementedError(\"IA_D hasn't been implemented yet.\")\r\n def clean():\r\n global IA_D, core\r\n a=0;b=len(IA_D.entities)\r\n while a < b:\r\n if IA_D.entities[a].delay == 0 or IA_D.entities[a].live <= 0:\r\n if IA.entities[a].delay != 0:core.score+=IA.entities[a].xp\r\n del IA_D.entities[a]\r\n del IA_D.actives[a]\r\n b+=-1\r\n else:\r\n IA_D.entities[a].delay += -1\r\n a+=1\r\n\r\ndef tir():\r\n global Player\r\n if Player.atk_delay == 0:\r\n Player.atk_delay = Player.atk_freq\r\n M = [Player.pos[0], Player.pos[1]]\r\n d = Player.dir%4\r\n M[0]+=(Player.size[0]-Player.weapon.size[0])//2 * (Player.move[0]+1)\r\n M[1]+=(Player.size[1]-Player.weapon.size[1])//2 * (Player.move[1]+1)\r\n if Player.move == (0, 0):\r\n if Player.dir%2:\r\n if Player.dir:m=(0,-1)\r\n else:m=(0,1)\r\n else:\r\n if Player.dir==1:m=(1,0)\r\n else:m=(-1,0)\r\n else:Player.weapon(M, Player.chunk.copy(), Player.move.copy())\r\n\r\ndef UpdateEntities():\r\n global Static, Obstacle, Fired, IA, IA_D, Player, Entity, core, imgeff, player\r\n Obstacle.clean()\r\n Fired.clean()\r\n Entity.clean()\r\n IA.clean()\r\n IA_D.clean()\r\n # ----- SCREEN ----- #\r\n x = (core.size[0] - Player.size[0])//2 - Player.pos[0] - 512\r\n y = (core.size[1] - Player.size[1])//2 - Player.pos[1] - 512\r\n X = x%core.Bsize[0]-core.Bsize[0]\r\n Y = y%core.Bsize[1]-core.Bsize[1]\r\n a=0\r\n while a < core.Bnum[0]:\r\n b=0\r\n while b < core.Bnum[1]:\r\n core.fen.blit(core.img, (X+core.Bsize[0]*a, Y+core.Bsize[1]*b))\r\n b+=1\r\n a+=1\r\n frame=core.tic//6\r\n # Add Fired to screen\r\n chunk0 = (Player.chunk[0]-1, Player.chunk[1]-1)\r\n c = -1\r\n while c < core.S[1]:\r\n b = -1\r\n while b < core.S[0]:\r\n pos = (chunk0[0]+b, chunk0[1]+c)\r\n for a in core.area[\"entity\"][pos[0]][pos[1]]:\r\n core.fen.blit(a.img[a.dir][(frame+a.frame)%a.img_format[0]], (x+a.pos[0], y+a.pos[1]))\r\n for a in core.area[\"obs\"][pos[0]][pos[1]]:\r\n core.fen.blit(a.img, (x+a.pos[0], y+a.pos[1]))\r\n for a in core.area[\"static\"][pos[0]][pos[1]]:\r\n core.fen.blit(a[0], (x+a[1][0], y+a[1][1]))\r\n x += 256\r\n b += 1\r\n x -= 256*(core.S[0]+1)\r\n y += 256\r\n c += 1\r\n y -= 256*(core.S[1]-1)\r\n x += 512\r\n core.fen.blit(Player.img[Player.dir][Player.frame],\r\n ((core.size[0] - Player.size[0])//2, (core.size[1] - Player.size[1])//2))\r\n for a in Fired.entities:\r\n core.fen.blit(a.img[frame%a.img_format[0]+a.frame], (x+a.pos[0]+256*(a.chunk[0] - Player.chunk[0]), y+a.pos[1]+256*(a.chunk[1] - Player.chunk[1])))\r\n for a in core.images:\r\n core.fen.blit(a[0], (a[1], a[2]))\r\n b=0\r\n rem = list()\r\n for a in Player.effect:\r\n a.delay+=-1\r\n if a.delay > 1200:core.fen.blit(imgeff[\"contour green\"], (b, 0))\r\n elif a.delay > 200:core.fen.blit(imgeff[\"contour orange\"], (b, 0))\r\n elif a.delay == 0:\r\n a.end_effect(Player)\r\n rem.append(a)\r\n else:\r\n core.fen.blit(imgeff[\"contour red\"], (b, 0))\r\n a.active_effect(Player)\r\n core.fen.blit(imgeff[a.name], (b+8, 8))\r\n b+=64\r\n for a in rem:\r\n Player.effect.remove(a)\r\n core.fen.fill(b'\\x00\\x00\\x00', (0, core.size[1]-16, player.live, core.size[1]))\r\n core.fen.fill(b'\\xff\\x00\\x00', (0, core.size[1]-16, Player.live*10, core.size[1]))\r\n core.refresh()\r\n pygame.display.flip()\r\n # ------------------ #\r\n Player.pos[0] += Player.move[0] * (Player.speed * (1 - 0.3 * abs(Player.move[1])))\r\n Player.pos[1] += Player.move[1] * (Player.speed * (1 - 0.3 * abs(Player.move[0])))\r\n core.timexe += 0.05\r\n T = core.timexe - time()\r\n if T > 0:sleep(T)\r\n core.tic+=1\r\n if core.tic == 360:\r\n core.tic = 0\r\n core.timer+=1\r\n elif T < -1:\r\n core.timexe=time()\r\n\r\ndef Refresh():\r\n \"Move entities, refresh screen and test collisions\"\r\n global Static, Obstacle, Fired, IA, IA_D, Player, Entity\r\n UpdateEntities()\r\n for a in Fired.entities:\r\n a.react()\r\n for a in Entity.entities:\r\n a.react()\r\n for a in IA.entities:\r\n a.react()\r\n for a in IA_D.entities:\r\n a.react()\r\n Player.chunking()\r\n Player.collide()\r\n\r\nclass effect:\r\n def __repr__(self):\r\n if self.level > 12:return self.name + \" ##\\n duration : \" + str(self.delay//20)+\"s\\n\"\r\n if self.level < 0:return self.name + \" ##\\n duration : \" + str(self.delay//20)+\"s\\n\"\r\n return self.name + (\"\",\" I\",\" II\",\" III\",\" IV\",\" V\",\" VI\",\" VII\",\" VIII\",\" IX\",\" X\",\" XI\",\" XII\")[self.level] + \"\\n duration : \" + str(self.delay//20)+\"s\\n\"\r\n def __init__(self, delay, level):\r\n self.level=level\r\n self.delay=delay\r\n\r\nPlayer = player()\r\n"
] |
[
[
"numpy.load",
"numpy.save"
]
] |
schmidtand/water-anomaly-detection
|
[
"65a8d09f7fa4d1899c89c1a69ba3a468de4d7cd5"
] |
[
"src/classifier.py"
] |
[
"\"\"\"\ncontains classes of the supported models\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport datetime\nimport logging\nimport sklearn.ensemble\nimport sklearn.svm\n\n\n\n\nclass AdvancedThresholdClassifier:\n def __init__(self, y_name, *args, lower_threshold=0, upper_threshold=400, neighborhood=9, moving_average_window_length=9, moving_average_quantile=0.7):#neighborhood_threshold_criterion=lambda x: np.quantile(x, 0.7), **kwargs):\n self.y_name = y_name\n self.lower_threshold=lower_threshold\n self.upper_threshold=upper_threshold\n self.neighborhood=int(neighborhood)\n self.moving_average_window_length= int(moving_average_window_length)\n self.moving_average_quantile=moving_average_quantile\n \n def fit(self, *args, **kwargs):\n pass\n\n def predict(self, X):\n pred = pd.Series(0, index=X.index)\n pred.loc[X[self.y_name] >= self.upper_threshold] = 1\n \n moving_average = X[self.y_name].rolling(window=self.moving_average_window_length, center=True).quantile(self.moving_average_quantile)\n\n #neighborhood = 10\n for iter in range(self.neighborhood):\n current_sum = pred.sum()\n direct_neighbors_of_pred = ((np.convolve(pred, [1,0,0], mode=\"same\") | np.convolve(pred, [0,1], mode=\"same\")) & (1-pred)) == 1\n pred.loc[(X[self.y_name] > moving_average) & direct_neighbors_of_pred] = 1\n if current_sum == pred.sum():\n break\n \n pred.loc[X[self.y_name] <= self.lower_threshold] = 1\n\n return pred\n\n max_iter = 30\n for idx in pred.loc[(pred == 1) & (X[self.y_name] > 0)].index:\n for _ in range(max_iter):\n idx_iloc = X.index.get_loc(np.where(pred.index == idx)[0][0])\n neighbors = X.iloc[idx_iloc-self.neighborhood:idx_iloc+self.neighborhood]\n neighbors_avg = self.neighborhood_threshold_criterion(X.iloc[[*list(range(idx_iloc-self.neighborhood, idx_iloc)), *list(range(idx_iloc+1, idx_iloc+self.neighborhood))]][self.y_name])\n pred[neighbors.loc[neighbors[self.y_name] > neighbors_avg].index] = 1\n\n return pred\n\n\n\n\nclass AdvancedAutocorrelationClassifier:\n def __init__(self, y_name, slope, prev, next):\n self.y_name = y_name\n \n self.min_prev_pos = int(prev)\n self.max_prev_pos = int(next)\n self.min_prev_neg = int(prev)\n self.max_prev_neg = int(next)\n self.min_next_pos = int(prev)\n self.max_next_pos = int(next)\n self.min_next_neg = int(prev)\n self.max_next_neg = int(next)\n\n self.slope_threshold = slope\n self.lower_threshold = 0\n\n self.moving_average_window_length = 15\n self.moving_average_quantile = 0.25\n self.neighborhood = 5\n \n def fit(self, *args, **kwargs):\n pass\n\n def predict(self, X):\n def slope(x, prev, next):\n diff = (x if next==0 else np.hstack((x[next:], x[-next:]))) - (x if prev==0 else np.hstack((x[:prev], x[:-prev])))\n\n return diff / (1 if next+prev == 0 else (next+prev))\n\n pred = pd.Series(0, index=X.index)\n\n for i in range(self.min_prev_pos, self.max_prev_pos+1):\n for j in range(self.min_next_pos, self.max_next_pos+1):\n pred.loc[slope(X[self.y_name].values, prev=i, next=j) > self.slope_threshold] = 1\n \n for i in range(self.min_prev_neg, self.max_prev_neg+1):\n for j in range(self.min_next_neg, self.max_next_neg+1):\n pred.loc[-slope(X[self.y_name].values, prev=i, next=j) > self.slope_threshold] = 1\n\n\n moving_average = X[self.y_name].rolling(window=self.moving_average_window_length, center=True).quantile(self.moving_average_quantile)\n\n #neighborhood = 10\n for iter in range(self.neighborhood):\n current_sum = pred.sum()\n direct_neighbors_of_pred = ((np.convolve(pred, [1,0,0], mode=\"same\") | np.convolve(pred, [0,1], mode=\"same\")) & (1-pred)) == 1\n pred.loc[(X[self.y_name] > moving_average) & direct_neighbors_of_pred] = 1\n if current_sum == pred.sum():\n break\n \n pred.loc[X[self.y_name] <= self.lower_threshold] = 1\n\n return pred\n\n #pred.loc[slope(X[self.y_name].values, prev=self.lag, next=0) > self.slope_threshold] = 1\n #pred.loc[-slope(X[self.y_name].values, prev=0, next=self.lag) > self.slope_threshold] = 1\n\n pred.loc[X[self.y_name] <= self.lower_threshold] = 1\n\n return pred\n\n\n\n\nclass MyRandomForest(sklearn.ensemble.RandomForestClassifier):\n def __init__(self, y_name, vars, convolve_window_prev, convolve_window_next, *args, **kwargs):\n super().__init__(*args, n_estimators=100, **{k: None if k == \"max_depth\" and np.isnan(v) else v for k,v in kwargs.items()})\n self.vars = vars\n self.convolve_window_prev = convolve_window_prev\n self.convolve_window_next = convolve_window_next\n \n def fit(self, X, Y):\n X = X[self.vars]\n X = _fill_nan(X)\n X = _convolve(X, self.convolve_window_prev, self.convolve_window_next)\n\n super().fit(X, Y)\n\n def predict(self, X):\n X = X[self.vars]\n X = _fill_nan(X)\n X = _convolve(X, self.convolve_window_prev, self.convolve_window_next)\n return super().predict(X)\n\n\n\n\nclass MySVC(sklearn.svm.SVC):\n def __init__(self, y_name, vars, convolve_window_prev, convolve_window_next, c):\n super().__init__(C=c, max_iter=100)\n self.c = c\n self.y_name = y_name\n self.vars = vars\n self.convolve_window_prev = convolve_window_prev\n self.convolve_window_next = convolve_window_next\n \n def fit(self, X, Y):\n X = X[self.vars]\n X = _fill_nan(X)\n X = _convolve(X, self.convolve_window_prev, self.convolve_window_next, diffs=True)\n\n super().fit(X, Y)\n\n def predict(self, X):\n X = X[self.vars]\n X = _fill_nan(X)\n X = _convolve(X, self.convolve_window_prev, self.convolve_window_next, diffs=True)\n return super().predict(X)\n\n\n\n\ndef _fill_nan(X):\n \"\"\"\n fill nan values with accumulation of prev/next value\n \"\"\"\n X = X.copy()\n for v in X.columns:\n X[v] = X[v].values[\n np.maximum.accumulate(\n np.where(\n ~np.isnan(X[v].values),\n np.arange(np.isnan(X[v].values).shape[0]),\n np.where(~np.isnan(X[v]))[0][0] if len(np.where(~np.isnan(X[v]))[0]) > 0 else 0\n )\n )\n ]\n X = X.fillna(0)\n return X\n\ndef _convolve(X, n_prev, n_next, diffs=False):\n \"\"\"\n add prev n_prev/next n_next values as columns\n \"\"\"\n X = X.copy()\n for v in X.columns:\n for i in range(-n_prev,n_next+1):\n v2 = v + \"_\" + ((\"n\" + str(-i)) if i < 0 else str(i)) \n w = [\n *([1] if i < 0 else []), \n *[0 for _ in range(min(2*(-i if i < 0 else i),len(X)-1))], \n *([1] if i >= 0 else [])\n ]\n x = np.convolve(\n X[v],\n w,\n mode=\"same\"\n )\n x[i:]\n X[v2] = x\n \n if diffs:\n cols = X.columns.copy()\n for i,c1 in enumerate(cols[:-1]):\n for c2 in cols[i+1:]:\n #X[c1+\"_\"+c2+\"_ac\"] = X.apply(lambda x: (x[c1]/x[c2]) if x[c2] > 0 else 0, axis=1)\n with np.errstate(divide='ignore'):\n X[c1+\"_\"+c2+\"_ac\"] = X[c1] / X[c2]\n X.loc[X[c2] == 0, c1+\"_\"+c2+\"_ac\"] = 0\n return X\n\n"
] |
[
[
"numpy.convolve",
"numpy.hstack",
"pandas.Series",
"numpy.isnan",
"numpy.errstate",
"numpy.where"
]
] |
epochml/paintWebcam
|
[
"93ea24603869f3cae2a0ab4f591ba4cbc8f9c533"
] |
[
"webcamDraw.py"
] |
[
"import numpy as np\nimport cv2\nfrom collections import deque\n\n\nDblueLower = np.array([100, 60, 60])\nDblueUpper = np.array([140, 255, 255])\n\n\nkernel = np.ones((5, 5), np.uint8)\n\n\nbpoints = [deque(maxlen=512)]\ngpoints = [deque(maxlen=512)]\nrpoints = [deque(maxlen=512)]\nypoints = [deque(maxlen=512)]\n\nbindex = 0\ngindex = 0\nrindex = 0\nyindex = 0\n\ncolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255)]\ncolorIndex = 0\n\npaintWindow = np.zeros((471, 636, 3)) + 255\npaintWindow = cv2.rectangle(paintWindow, (40, 1), (140, 65), (0, 0, 0), 2)\npaintWindow = cv2.rectangle(paintWindow, (160, 1), (255, 65), colors[0], -1)\npaintWindow = cv2.rectangle(paintWindow, (275, 1), (370, 65), colors[1], -1)\npaintWindow = cv2.rectangle(paintWindow, (390, 1), (485, 65), colors[2], -1)\npaintWindow = cv2.rectangle(paintWindow, (505, 1), (600, 65), colors[3], -1)\ncv2.putText(paintWindow, \"Clear Screen\", (49, 33),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2, cv2.LINE_AA)\ncv2.putText(paintWindow, \"Move here for Blue\", (185, 33),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\ncv2.putText(paintWindow, \"Move here for Green\", (298, 33),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\ncv2.putText(paintWindow, \"Move here for Red\", (420, 33),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\ncv2.putText(paintWindow, \"Move here for Yellow\", (520, 33),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (150, 150, 150), 2, cv2.LINE_AA)\n\n# cv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE)\n\n# RUNNNNER UPPP!\ncamera = cv2.VideoCapture(0)\n\n\nwhile True:\n\n (grabbed, frame) = camera.read()\n frame = cv2.flip(frame, 1)\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # frame = cv2.rectangle(frame, (40,1), (140,65), (122,122,122), -1)\n # frame = cv2.rectangle(frame, (160,1), (255,65), colors[0], -1)\n # frame = cv2.rectangle(frame, (275,1), (370,65), colors[1], -1)\n # frame = cv2.rectangle(frame, (390,1), (485,65), colors[2], -1)\n # frame = cv2.rectangle(frame, (505,1), (600,65), colors[3], -1)\n # cv2.putText(frame, \"CLEAR ALL\", (49, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n # cv2.putText(frame, \"BLUE\", (185, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n # cv2.putText(frame, \"GREEN\", (298, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n # cv2.putText(frame, \"RED\", (420, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n # cv2.putText(frame, \"YELLOW\", (520, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (150,150,150), 2, cv2.LINE_AA)\n\n if not grabbed:\n break\n\n blueMask = cv2.inRange(hsv, DblueLower, DblueUpper)\n blueMask = cv2.erode(blueMask, kernel, iterations=2)\n blueMask = cv2.morphologyEx(blueMask, cv2.MORPH_OPEN, kernel)\n blueMask = cv2.dilate(blueMask, kernel, iterations=1)\n\n (cnts, _) = cv2.findContours(blueMask.copy(),\n cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n center = None\n\n if len(cnts) > 0:\n\n cnt = sorted(cnts, key=cv2.contourArea, reverse=True)[0]\n\n ((x, y), radius) = cv2.minEnclosingCircle(cnt)\n\n cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)\n\n M = cv2.moments(cnt)\n center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))\n\n if center[1] <= 65:\n if 40 <= center[0] <= 140: # Clear All\n bpoints = [deque(maxlen=512)]\n gpoints = [deque(maxlen=512)]\n rpoints = [deque(maxlen=512)]\n ypoints = [deque(maxlen=512)]\n\n bindex = 0\n gindex = 0\n rindex = 0\n yindex = 0\n\n paintWindow[67:, :, :] = 255\n elif 160 <= center[0] <= 255:\n colorIndex = 0 # Blue\n elif 275 <= center[0] <= 370:\n colorIndex = 1 # Green\n elif 390 <= center[0] <= 485:\n colorIndex = 2 # Red\n elif 505 <= center[0] <= 600:\n colorIndex = 3 # Yellow\n else:\n if colorIndex == 0:\n bpoints[bindex].appendleft(center)\n elif colorIndex == 1:\n gpoints[gindex].appendleft(center)\n elif colorIndex == 2:\n rpoints[rindex].appendleft(center)\n elif colorIndex == 3:\n ypoints[yindex].appendleft(center)\n\n else:\n bpoints.append(deque(maxlen=500))\n bindex += 1\n gpoints.append(deque(maxlen=500))\n gindex += 1\n rpoints.append(deque(maxlen=500))\n rindex += 1\n ypoints.append(deque(maxlen=500))\n yindex += 1\n\n points = [bpoints, gpoints, rpoints, ypoints]\n for i in range(len(points)):\n for j in range(len(points[i])):\n for k in range(1, len(points[i][j])):\n if points[i][j][k - 1] is None or points[i][j][k] is None:\n continue\n cv2.line(frame, points[i][j][k - 1],\n points[i][j][k], colors[i], 2)\n cv2.line(paintWindow, points[i][j]\n [k - 1], points[i][j][k], colors[i], 2)\n\n # cv2.imshow(\"Drawing\", frame)\n cv2.imshow(\"Paint App\", paintWindow)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n\ncamera.release()\ncv2.destroyAllWindows()\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.ones"
]
] |
pinakinathc/task_image_enhancement
|
[
"a8b628f10c02dcf047382ef0774817cb6c47780a"
] |
[
"unet.py"
] |
[
"import numpy as np \nimport os\nimport tensorflow as tf\nimport numpy as np\n# from keras.models import *\nfrom tensorflow.keras.layers import *\n\n\ndef unet(inputs, input_size=(256, 256)):\n # inputs = Input(input_size)\n input_rs = tf.image.resize_nearest_neighbor(inputs, input_size)\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n drop4 = Dropout(0.5)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = Dropout(0.5)(conv5)\n\n up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n merge6 = concatenate([drop4,up6], axis = 3)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n\n up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n merge7 = concatenate([conv3,up7], axis = 3)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n\n up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n merge8 = concatenate([conv2,up8], axis = 3)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n\n up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n merge9 = concatenate([conv1,up9], axis = 3)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv9 = Conv2D(3, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = Conv2D(3, 1, activation = 'sigmoid')(conv9)\n p_output = tf.image.resize_nearest_neighbor(conv10, (tf.shape(inputs)[1], tf.shape(inputs)[2]))\n return p_output\n\n# unet()\n"
] |
[
[
"tensorflow.image.resize_nearest_neighbor",
"tensorflow.shape"
]
] |
suhangpro/deeprl
|
[
"9dcd1905b016a823fe92bf92dc00d3e56d732925"
] |
[
"main.py"
] |
[
"#######################################################################\n# Copyright (C) 2017 Shangtong Zhang([email protected]) #\n# Permission given to modify the code as long as you keep this #\n# declaration at the top #\n#######################################################################\n\nimport logging\nfrom agent import *\nfrom component import *\nfrom utils import *\nfrom model import *\n\n## cart pole\n\ndef dqn_cart_pole():\n game = 'CartPole-v0'\n config = Config()\n config.task_fn = lambda: ClassicalControl(game, max_steps=200)\n config.evaluation_env = config.task_fn()\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, 0.001)\n config.network_fn = lambda state_dim, action_dim: VanillaNet(action_dim, FCBody(state_dim))\n # config.network_fn = lambda state_dim, action_dim: DuelingNet(action_dim, FCBody(state_dim))\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=10000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=10000, batch_size=10)\n config.discount = 0.99\n config.target_network_update_freq = 200\n config.exploration_steps = 1000\n config.logger = Logger('./log', logger)\n config.double_q = True\n # config.double_q = False\n run_episodes(DQNAgent(config))\n\ndef a2c_cart_pole():\n config = Config()\n name = 'CartPole-v0'\n # name = 'MountainCar-v0'\n task_fn = lambda log_dir: ClassicalControl(name, max_steps=200, log_dir=log_dir)\n config.evaluation_env = task_fn(None)\n config.num_workers = 5\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers,\n log_dir=get_default_log_dir(a2c_cart_pole.__name__))\n config.optimizer_fn = lambda params: torch.optim.Adam(params, 0.001)\n config.network_fn = lambda state_dim, action_dim: ActorCriticNet(action_dim, FCBody(state_dim))\n config.policy_fn = SamplePolicy\n config.discount = 0.99\n config.logger = Logger('./log', logger)\n config.gae_tau = 1.0\n config.entropy_weight = 0.01\n config.rollout_length = 5\n run_iterations(A2CAgent(config))\n\ndef categorical_dqn_cart_pole():\n game = 'CartPole-v0'\n config = Config()\n config.task_fn = lambda: ClassicalControl(game, max_steps=200)\n config.evaluation_env = config.task_fn()\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, 0.001)\n config.network_fn = lambda state_dim, action_dim: \\\n CategoricalNet(action_dim, config.categorical_n_atoms, FCBody(state_dim))\n config.policy_fn = lambda: GreedyPolicy(epsilon=0.1, final_step=10000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=10000, batch_size=10)\n config.discount = 0.99\n config.target_network_update_freq = 200\n config.exploration_steps = 100\n config.logger = Logger('./log', logger, skip=True)\n config.categorical_v_max = 100\n config.categorical_v_min = -100\n config.categorical_n_atoms = 50\n run_episodes(CategoricalDQNAgent(config))\n\ndef quantile_regression_dqn_cart_pole():\n config = Config()\n config.task_fn = lambda: ClassicalControl('CartPole-v0', max_steps=200)\n config.evaluation_env = config.task_fn()\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, 0.001)\n config.network_fn = lambda state_dim, action_dim: \\\n QuantileNet(action_dim, config.num_quantiles, FCBody(state_dim))\n config.policy_fn = lambda: GreedyPolicy(epsilon=0.1, final_step=10000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=10000, batch_size=10)\n config.discount = 0.99\n config.target_network_update_freq = 200\n config.exploration_steps = 100\n config.logger = Logger('./log', logger, skip=True)\n config.num_quantiles = 20\n run_episodes(QuantileRegressionDQNAgent(config))\n\ndef n_step_dqn_cart_pole():\n config = Config()\n task_fn = lambda log_dir: ClassicalControl('CartPole-v0', max_steps=200, log_dir=log_dir)\n config.evaluation_env = task_fn(None)\n config.num_workers = 5\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers)\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, 0.001)\n config.network_fn = lambda state_dim, action_dim: VanillaNet(action_dim, FCBody(state_dim))\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=10000, min_epsilon=0.1)\n config.discount = 0.99\n config.target_network_update_freq = 200\n config.rollout_length = 5\n config.logger = Logger('./log', logger)\n run_iterations(NStepDQNAgent(config))\n\ndef ppo_cart_pole():\n config = Config()\n task_fn = lambda log_dir: ClassicalControl('CartPole-v0', max_steps=200, log_dir=log_dir)\n config.num_workers = 5\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers)\n optimizer_fn = lambda params: torch.optim.RMSprop(params, 0.001)\n network_fn = lambda state_dim, action_dim: ActorCriticNet(action_dim, FCBody(state_dim))\n config.network_fn = lambda state_dim, action_dim: \\\n CategoricalActorCriticWrapper(state_dim, action_dim, network_fn, optimizer_fn)\n config.discount = 0.99\n config.logger = Logger('./log', logger)\n config.use_gae = True\n config.gae_tau = 0.95\n config.entropy_weight = 0.01\n config.gradient_clip = 0.5\n config.rollout_length = 128\n config.optimization_epochs = 10\n config.num_mini_batches = 4\n config.ppo_ratio_clip = 0.2\n config.iteration_log_interval = 1\n run_iterations(PPOAgent(config))\n\n## Atari games\n\ndef dqn_pixel_atari(name):\n config = Config()\n config.history_length = 4\n config.task_fn = lambda: PixelAtari(name, frame_skip=4, history_length=config.history_length,\n log_dir=get_default_log_dir(dqn_pixel_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=0.00025, alpha=0.95, eps=0.01)\n config.network_fn = lambda state_dim, action_dim: VanillaNet(action_dim, NatureConvBody(), gpu=0)\n # config.network_fn = lambda state_dim, action_dim: DuelingNet(action_dim, NatureConvBody(), gpu=0)\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=1000000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=100000, batch_size=32)\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.target_network_update_freq = 10000\n config.exploration_steps= 50000\n config.logger = Logger('./log', logger)\n # config.double_q = True\n config.double_q = False\n run_episodes(DQNAgent(config))\n\ndef a2c_pixel_atari(name):\n config = Config()\n config.history_length = 4\n config.num_workers = 16\n task_fn = lambda log_dir: PixelAtari(name, frame_skip=4, history_length=config.history_length, log_dir=log_dir)\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=get_default_log_dir(a2c_pixel_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=0.0007)\n config.network_fn = lambda state_dim, action_dim: \\\n ActorCriticNet(action_dim, NatureConvBody(), gpu=0)\n config.policy_fn = SamplePolicy\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.use_gae = False\n config.gae_tau = 0.97\n config.entropy_weight = 0.01\n config.rollout_length = 5\n config.gradient_clip = 0.5\n config.logger = Logger('./log', logger, skip=True)\n run_iterations(A2CAgent(config))\n\ndef a2c_lstm_pixel_atari(name):\n config = MultiGPUConfig()\n config.history_length = 4\n config.num_workers = 16\n task_fn = lambda log_dir, worker_id: PixelAtari(name, frame_skip=4, history_length=config.history_length,\n log_dir=log_dir, worker_id=worker_id)\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers,\n log_dir=get_default_log_dir(a2c_lstm_pixel_atari.__name__),\n worker_ids=range(config.num_workers))\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=0.0007)\n config.network_fn = lambda state_dim, action_dim: \\\n ActorCriticLSTM(action_dim, NatureConvBody(), use_internal_state=False, gpu=config.gpus[0])\n config.policy_fn = SamplePolicy\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.use_gae = False\n config.gae_tau = 0.97\n config.entropy_weight = 0.01\n config.rollout_length = 5\n config.gradient_clip = 0.5\n config.logger = Logger('./log', logger, skip=True)\n run_iterations(A2C(config))\n\ndef categorical_dqn_pixel_atari(name):\n config = Config()\n config.history_length = 4\n config.task_fn = lambda: PixelAtari(name, frame_skip=4, history_length=config.history_length,\n log_dir=get_default_log_dir(categorical_dqn_pixel_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.Adam(params, lr=0.00025, eps=0.01 / 32)\n config.network_fn = lambda state_dim, action_dim: \\\n CategoricalNet(action_dim, config.categorical_n_atoms, NatureConvBody(), gpu=0)\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=1000000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=100000, batch_size=32)\n config.discount = 0.99\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.target_network_update_freq = 10000\n config.exploration_steps= 50000\n config.logger = Logger('./log', logger)\n config.double_q = False\n config.categorical_v_max = 10\n config.categorical_v_min = -10\n config.categorical_n_atoms = 51\n run_episodes(CategoricalDQNAgent(config))\n\ndef quantile_regression_dqn_pixel_atari(name):\n config = Config()\n config.history_length = 4\n config.task_fn = lambda: PixelAtari(name, frame_skip=4, history_length=config.history_length,\n log_dir=get_default_log_dir(quantile_regression_dqn_pixel_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.Adam(params, lr=0.00005, eps=0.01 / 32)\n config.network_fn = lambda state_dim, action_dim: \\\n QuantileNet(action_dim, config.num_quantiles, NatureConvBody(), gpu=0)\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=1000000, min_epsilon=0.01)\n config.replay_fn = lambda: Replay(memory_size=100000, batch_size=32)\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.target_network_update_freq = 10000\n config.exploration_steps= 50000\n config.logger = Logger('./log', logger)\n config.double_q = False\n config.num_quantiles = 200\n run_episodes(QuantileRegressionDQNAgent(config))\n\ndef n_step_dqn_pixel_atari(name):\n config = Config()\n config.history_length = 4\n task_fn = lambda log_dir: PixelAtari(name, frame_skip=4, history_length=config.history_length, log_dir=log_dir)\n config.num_workers = 16\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers,\n log_dir=get_default_log_dir(n_step_dqn_pixel_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=1e-4, alpha=0.99, eps=1e-5)\n config.network_fn = lambda state_dim, action_dim: VanillaNet(action_dim, NatureConvBody(), gpu=0)\n config.policy_fn = lambda: GreedyPolicy(epsilon=1.0, final_step=1000000, min_epsilon=0.05)\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.target_network_update_freq = 10000\n config.rollout_length = 5\n config.gradient_clip = 5\n config.logger = Logger('./log', logger)\n run_iterations(NStepDQNAgent(config))\n\ndef ppo_pixel_atari(name):\n config = Config()\n config.history_length = 4\n task_fn = lambda log_dir: PixelAtari(name, frame_skip=4, history_length=config.history_length, log_dir=log_dir)\n config.num_workers = 16\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers,\n log_dir=get_default_log_dir(ppo_pixel_atari.__name__))\n optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=0.00025)\n network_fn = lambda state_dim, action_dim: ActorCriticNet(action_dim, NatureConvBody(), gpu=0)\n config.network_fn = lambda state_dim, action_dim: \\\n CategoricalActorCriticWrapper(state_dim, action_dim, network_fn, optimizer_fn)\n config.state_normalizer = ImageNormalizer()\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.logger = Logger('./log', logger)\n config.use_gae = True\n config.gae_tau = 0.95\n config.entropy_weight = 0.01\n config.gradient_clip = 0.5\n config.rollout_length = 128\n config.optimization_epochs = 4\n config.num_mini_batches = 4\n config.ppo_ratio_clip = 0.1\n config.iteration_log_interval = 1\n run_iterations(PPOAgent(config))\n\ndef dqn_ram_atari(name):\n config = Config()\n config.task_fn = lambda: RamAtari(name, no_op=30, frame_skip=4,\n log_dir=get_default_log_dir(dqn_ram_atari.__name__))\n config.optimizer_fn = lambda params: torch.optim.RMSprop(params, lr=0.00025, alpha=0.95, eps=0.01)\n config.network_fn = lambda state_dim, action_dim: VanillaNet(action_dim, FCBody(state_dim), gpu=0)\n config.policy_fn = lambda: GreedyPolicy(epsilon=0.1, final_step=1000000, min_epsilon=0.1)\n config.replay_fn = lambda: Replay(memory_size=100000, batch_size=32)\n config.state_normalizer = RescaleNormalizer(1.0 / 128)\n config.reward_normalizer = SignNormalizer()\n config.discount = 0.99\n config.target_network_update_freq = 10000\n config.max_episode_length = 0\n config.exploration_steps= 100\n config.logger = Logger('./log', logger)\n config.double_q = True\n # config.double_q = False\n run_episodes(DQNAgent(config))\n\n## continuous control\n\ndef ppo_continuous():\n config = Config()\n config.num_workers = 1\n # task_fn = lambda log_dir: Pendulum(log_dir=log_dir)\n # task_fn = lambda log_dir: Roboschool('RoboschoolInvertedPendulum-v1', log_dir=log_dir)\n task_fn = lambda log_dir: Roboschool('RoboschoolAnt-v1', log_dir=log_dir)\n # task_fn = lambda log_dir: Roboschool('RoboschoolReacher-v1', log_dir=log_dir)\n # task_fn = lambda log_dir: Roboschool('RoboschoolHopper-v1', log_dir=log_dir)\n # task_fn = lambda log_dir: DMControl('cartpole', 'balance', log_dir=log_dir)\n # task_fn = lambda log_dir: DMControl('hopper', 'hop', log_dir=log_dir)\n config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=get_default_log_dir(ppo_continuous.__name__))\n actor_network_fn = lambda state_dim, action_dim: GaussianActorNet(\n action_dim, FCBody(state_dim))\n critic_network_fn = lambda state_dim: GaussianCriticNet(FCBody(state_dim))\n actor_optimizer_fn = lambda params: torch.optim.Adam(params, 3e-4, eps=1e-5)\n critic_optimizer_fn = lambda params: torch.optim.Adam(params, 3e-4, eps=1e-5)\n config.network_fn = lambda state_dim, action_dim: \\\n GaussianActorCriticWrapper(state_dim, action_dim, actor_network_fn,\n critic_network_fn, actor_optimizer_fn,\n critic_optimizer_fn)\n # config.state_normalizer = RunningStatsNormalizer()\n config.discount = 0.99\n config.use_gae = True\n config.gae_tau = 0.95\n config.gradient_clip = 0.5\n config.rollout_length = 2048\n config.optimization_epochs = 10\n config.num_mini_batches = 32\n config.ppo_ratio_clip = 0.2\n config.iteration_log_interval = 1\n config.logger = Logger('./log', logger)\n run_iterations(PPOAgent(config))\n\ndef ddpg_continuous():\n config = Config()\n log_dir = get_default_log_dir(ddpg_continuous.__name__)\n # config.task_fn = lambda: Pendulum(log_dir=log_dir)\n # config.task_fn = lambda: Roboschool('RoboschoolInvertedPendulum-v1', log_dir=log_dir)\n # config.task_fn = lambda: Roboschool('RoboschoolReacher-v1', log_dir=log_dir)\n config.task_fn = lambda: Roboschool('RoboschoolHopper-v1')\n # config.task_fn = lambda: Roboschool('RoboschoolAnt-v1', log_dir=log_dir)\n # config.task_fn = lambda: Roboschool('RoboschoolWalker2d-v1', log_dir=log_dir)\n # config.task_fn = lambda: DMControl('cartpole', 'balance', log_dir=log_dir)\n # config.task_fn = lambda: DMControl('finger', 'spin', log_dir=log_dir)\n config.evaluation_env = Roboschool('RoboschoolHopper-v1', log_dir=log_dir)\n config.actor_network_fn = lambda state_dim, action_dim: DeterministicActorNet(\n action_dim, FCBody(state_dim, (300, 200)))\n config.critic_network_fn = lambda state_dim, action_dim: DeterministicCriticNet(\n TwoLayerFCBodyWithAction(state_dim, action_dim, [400, 300]))\n config.actor_optimizer_fn = lambda params: torch.optim.Adam(params, lr=1e-4)\n config.critic_optimizer_fn = lambda params: torch.optim.Adam(params, lr=1e-3, weight_decay=0.01)\n config.replay_fn = lambda: Replay(memory_size=1000000, batch_size=64)\n config.discount = 0.99\n config.state_normalizer = RunningStatsNormalizer()\n config.random_process_fn = lambda action_dim: GaussianProcess(action_dim, LinearSchedule(0.3, 0, 1e6))\n config.min_memory_size = 64\n config.target_network_mix = 1e-3\n config.logger = Logger('./log', logger)\n run_episodes(DDPGAgent(config))\n\ndef plot():\n import matplotlib.pyplot as plt\n plotter = Plotter()\n names = plotter.load_log_dirs('')\n data = plotter.load_results(names)\n\n for i, name in enumerate(names):\n x, y = data[i]\n plt.plot(x, y, color=Plotter.COLORS[i], label=name)\n plt.legend()\n plt.xlabel('timesteps')\n plt.ylabel('episode return')\n plt.show()\n\ndef action_conditional_video_prediction():\n game = 'PongNoFrameskip-v4'\n prefix = '.'\n\n # Train an agent to generate the dataset\n # a2c_pixel_atari(game)\n\n # Generate a dataset with the trained model\n # a2c_model_file = './data/A2CAgent-vanilla-model-%s.bin' % (game)\n # generate_dataset(game, a2c_model_file, prefix)\n\n # Train the action conditional video prediction model\n acvp_train(game, prefix)\n\n\nif __name__ == '__main__':\n mkdir('data/video')\n mkdir('dataset')\n mkdir('log')\n set_one_thread()\n # logger.setLevel(logging.DEBUG)\n logger.setLevel(logging.INFO)\n\n # dqn_cart_pole()\n # a2c_cart_pole()\n # categorical_dqn_cart_pole()\n # quantile_regression_dqn_cart_pole()\n # n_step_dqn_cart_pole()\n # ppo_cart_pole()\n\n # dqn_pixel_atari('BreakoutNoFrameskip-v4')\n a2c_pixel_atari('BreakoutNoFrameskip-v4')\n # a2c_lstm_pixel_atari('BreakoutNoFrameskip-v4')\n # categorical_dqn_pixel_atari('BreakoutNoFrameskip-v4')\n # quantile_regression_dqn_pixel_atari('BreakoutNoFrameskip-v4')\n # n_step_dqn_pixel_atari('BreakoutNoFrameskip-v4')\n # ppo_pixel_atari('BreakoutNoFrameskip-v4')\n # dqn_ram_atari('Breakout-ramNoFrameskip-v4')\n\n # ddpg_continuous()\n # ppo_continuous()\n\n # action_conditional_video_prediction()\n\n # plot()\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
urikz/language
|
[
"503aca178c98fed4c606cf83e58ae0f84012a4d9",
"503aca178c98fed4c606cf83e58ae0f84012a4d9"
] |
[
"language/canine/tydiqa/tf_io.py",
"language/mentionmemory/modules/mention_losses_test.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\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\"\"\"Performs IO somewhat specific to TensorFlow.\n\nThis includes reading/writing `tf.Example`s to/from TF record files and opening\nfiles via `tf.gfile`.\n\"\"\"\n\nimport collections\nimport gzip\nimport json\nfrom typing import Iterator, List, Sequence, Text\n\nfrom absl import logging\nfrom language.canine.tydiqa import data\nfrom language.canine.tydiqa import preproc\nfrom language.canine.tydiqa import tydi_tokenization_interface as tok_interface\nimport tensorflow.compat.v1 as tf\n\n\ndef read_entries(input_jsonl_pattern: Text,\n tokenizer: tok_interface.TokenizerWithOffsets,\n max_passages: int, max_position: int, fail_on_invalid: bool):\n \"\"\"Reads TyDi QA examples from JSONL files.\n\n Args:\n input_jsonl_pattern: Glob of the gzipped JSONL files to read.\n tokenizer: Used to create special marker symbols to insert into the text.\n max_passages: see FLAGS.max_passages.\n max_position: see FLAGS.max_position.\n fail_on_invalid: Immediately stop if an error is found?\n\n Yields:\n tuple:\n input_file: str\n line_no: int\n tydi_entry: \"TyDiEntry\"s, dicts as returned by `create_entry_from_json`,\n one per line of the input JSONL files.\n debug_info: Dict containing debugging data.\n \"\"\"\n matches = tf.gfile.Glob(input_jsonl_pattern)\n if not matches:\n raise ValueError(f\"No files matched: {input_jsonl_pattern}\")\n for input_path in matches:\n with gzip.GzipFile(fileobj=tf.gfile.Open(input_path, \"rb\")) as input_file: # pytype: disable=wrong-arg-types\n for line_no, line in enumerate(input_file, 1):\n json_elem = json.loads(line, object_pairs_hook=collections.OrderedDict)\n entry = preproc.create_entry_from_json(\n json_elem,\n tokenizer,\n max_passages=max_passages,\n max_position=max_position,\n fail_on_invalid=fail_on_invalid)\n\n if not entry:\n tf.logging.info(\"Invalid Example %d\", json_elem[\"example_id\"])\n if fail_on_invalid:\n raise ValueError(\"Invalid example at {}:{}\".format(\n input_path, line_no))\n\n # Return a `debug_info` dict that methods throughout the codebase\n # append to with debugging information.\n debug_info = {\"json\": json_elem}\n yield input_path, line_no, entry, debug_info\n\n\ndef input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n # This needs to be kept in sync with `FeatureWriter`.\n name_to_features = {\n \"unique_ids\": tf.FixedLenFeature([], tf.int64),\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n }\n\n if is_training:\n name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)\n name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)\n name_to_features[\"answer_types\"] = tf.FixedLenFeature([], tf.int64)\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\nclass FeatureWriter(object):\n \"\"\"Writes InputFeatures to TF example file.\"\"\"\n\n def __init__(self, filename: Text, is_training: bool):\n self.filename = filename\n self.is_training = is_training\n self.num_features = 0\n self._writer = tf.python_io.TFRecordWriter(filename)\n\n def process_feature(self, feature: preproc.InputFeatures) -> None:\n \"\"\"Writes InputFeatures to the TFRecordWriter as a tf.train.Example.\"\"\"\n self.num_features += 1\n\n def create_int_feature(values: Sequence[int]) -> tf.train.Feature:\n return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n\n # This needs to be kept in sync with `input_fn_builder`.\n features = collections.OrderedDict()\n features[\"unique_ids\"] = create_int_feature([feature.unique_id])\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"language_id\"] = create_int_feature([feature.language_id])\n\n if self.is_training:\n features[\"start_positions\"] = create_int_feature([feature.start_position])\n features[\"end_positions\"] = create_int_feature([feature.end_position])\n features[\"answer_types\"] = create_int_feature([feature.answer_type])\n else:\n features[\"wp_start_offset\"] = create_int_feature(feature.wp_start_offset)\n features[\"wp_end_offset\"] = create_int_feature(feature.wp_end_offset)\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n self._writer.write(tf_example.SerializeToString())\n\n def close(self):\n self._writer.close()\n\n\nclass CreateTFExampleFn(object):\n \"\"\"Functor for creating TyDi `tf.Example`s to be written to a TFRecord file.\"\"\"\n\n def __init__(self, is_training, max_question_length, max_seq_length,\n doc_stride, include_unknowns,\n tokenizer: tok_interface.TokenizerWithOffsets):\n self.is_training = is_training\n self.tokenizer = tokenizer\n self.max_question_length = max_question_length\n self.max_seq_length = max_seq_length\n self.doc_stride = doc_stride\n self.include_unknowns = include_unknowns\n\n def process(self,\n entry,\n errors,\n debug_info=None) -> Iterator[tf.train.Example]:\n \"\"\"Converts TyDi entries into serialized tf examples.\n\n Args:\n entry: \"TyDi entries\", dicts as returned by `create_entry_from_json`.\n errors: A list that this function appends to if errors are created. A\n non-empty list indicates problems.\n debug_info: A dict of information that may be useful during debugging.\n These elements should be used for logging and debugging only. For\n example, we log how the text was tokenized into WordPieces.\n\n Yields:\n `tf.train.Example` with the features needed for training or inference\n (depending on how `is_training` was set in the constructor).\n \"\"\"\n if not debug_info:\n debug_info = {}\n tydi_example = data.to_tydi_example(entry, self.is_training)\n debug_info[\"tydi_example\"] = tydi_example\n input_features = preproc.convert_single_example(\n tydi_example,\n tokenizer=self.tokenizer,\n is_training=self.is_training,\n max_question_length=self.max_question_length,\n max_seq_length=self.max_seq_length,\n doc_stride=self.doc_stride,\n include_unknowns=self.include_unknowns,\n errors=errors,\n debug_info=debug_info,\n ) # type: List[preproc.InputFeatures]\n for input_feature in input_features:\n input_feature.example_index = int(entry[\"id\"])\n input_feature.unique_id = (\n input_feature.example_index + input_feature.doc_span_index)\n\n def create_int_feature(values):\n return tf.train.Feature(\n int64_list=tf.train.Int64List(value=list(values)))\n\n features = collections.OrderedDict()\n features[\"unique_ids\"] = create_int_feature([input_feature.unique_id])\n features[\"example_index\"] = create_int_feature(\n [input_feature.example_index])\n features[\"input_ids\"] = create_int_feature(input_feature.input_ids)\n features[\"input_mask\"] = create_int_feature(input_feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(input_feature.segment_ids)\n features[\"language_id\"] = create_int_feature([input_feature.language_id])\n\n if self.is_training:\n features[\"start_positions\"] = create_int_feature(\n [input_feature.start_position])\n features[\"end_positions\"] = create_int_feature(\n [input_feature.end_position])\n features[\"answer_types\"] = create_int_feature(\n [input_feature.answer_type])\n else:\n features[\"wp_start_offset\"] = create_int_feature(\n input_feature.wp_start_offset)\n features[\"wp_end_offset\"] = create_int_feature(\n input_feature.wp_end_offset)\n\n yield tf.train.Example(features=tf.train.Features(feature=features))\n\n\ndef gopen(path):\n \"\"\"Opens a file object given a (possibly gzipped) `path`.\"\"\"\n logging.info(\"*** Loading from: %s ***\", path)\n if \".gz\" in path:\n return gzip.GzipFile(fileobj=tf.gfile.Open(path, \"rb\")) # pytype: disable=wrong-arg-types\n else:\n return tf.gfile.Open(path, \"r\")\n",
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\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\"\"\"Tests for losses for mention encodings.\"\"\"\n\nimport functools\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\nimport jax.numpy as jnp\nimport language.mentionmemory.modules.mention_losses as mention_losses\nfrom language.mentionmemory.utils import mention_utils\nfrom language.mentionmemory.utils import test_utils\nimport numpy as np\nimport scipy.spatial\n\n\nclass MentionLossesTest(test_utils.TestCase):\n \"\"\"Mention encoding losses tests.\"\"\"\n\n entity_vocab_size = 100\n hidden_size = 3\n\n n_mentions = 37\n n_devices = 3\n batch_size = 5\n\n metrics_prefix = 'test_'\n\n def _gen_array(self, gen_fn):\n array = [gen_fn() for _ in range(len(self.devices))]\n array_sharded = jax.device_put_sharded(array, self.devices)\n array_stacked = np.stack(array)\n array_stacked = array_stacked.reshape([-1] + list(array_stacked.shape[2:]))\n return array_stacked, array_sharded\n\n def setUp(self):\n super().setUp()\n test_utils.force_multi_devices(self.n_devices)\n self.devices = jax.local_devices()\n # pylint: disable=g-long-lambda\n (self.mention_encodings_stacked,\n self.mention_encodings_sharded) = self._gen_array(\n lambda: 10.0 * np.random.random((self.n_mentions, self.hidden_size)))\n (self.mention_target_ids_stacked, self.mention_target_ids_sharded\n ) = self._gen_array(lambda: np.random.randint(\n self.entity_vocab_size, size=(self.n_mentions)))\n (self.mention_batch_positions_stacked,\n self.mention_batch_positions_sharded) = self._gen_array(\n lambda: np.random.randint(self.batch_size, size=(self.n_mentions)))\n (self.mention_target_is_masked_stacked,\n self.mention_target_is_masked_sharded\n ) = self._gen_array(lambda: np.random.randint(2, size=(self.n_mentions)))\n\n def test_build_coref_positive_negative_mask(self):\n all_mention_target_ids = jax.device_put_replicated(\n self.mention_target_ids_stacked, self.devices)\n\n get_batch_positions = functools.partial(\n mention_utils.get_globally_consistent_batch_positions,\n batch_size=self.batch_size)\n get_batch_positions = jax.pmap(get_batch_positions, axis_name='batch')\n\n (local_mention_batch_positions,\n global_mention_batch_positions) = get_batch_positions(\n self.mention_batch_positions_sharded)\n\n (positive_mask, negative_mask) = jax.pmap(\n mention_losses.build_coref_positive_negative_mask,\n axis_name='batch')(local_mention_batch_positions,\n global_mention_batch_positions,\n self.mention_target_ids_sharded,\n all_mention_target_ids)\n\n n_all_mentions = self.n_mentions * self.n_devices\n self.assertSequenceEqual(positive_mask.shape, negative_mask.shape)\n self.assertSequenceEqual(positive_mask.shape,\n (self.n_devices, self.n_mentions, n_all_mentions))\n positive_mask = positive_mask.reshape(-1, n_all_mentions)\n negative_mask = negative_mask.reshape(-1, n_all_mentions)\n\n for i in range(n_all_mentions):\n for j in range(n_all_mentions):\n is_same_device = i // self.n_mentions == j // self.n_mentions\n is_same_passage = (\n self.mention_batch_positions_stacked[i] ==\n self.mention_batch_positions_stacked[j])\n is_same_passage = is_same_passage and is_same_device\n\n if (self.mention_target_ids_stacked[i] == 0 or\n self.mention_target_ids_stacked[j] == 0 or is_same_passage):\n self.assertEqual(positive_mask[i, j], 0)\n self.assertEqual(negative_mask[i, j], 0)\n continue\n\n self.assertEqual(\n positive_mask[i, j], self.mention_target_ids_stacked[i] ==\n self.mention_target_ids_stacked[j])\n self.assertEqual(\n negative_mask[i, j], self.mention_target_ids_stacked[i] !=\n self.mention_target_ids_stacked[j])\n\n @parameterized.parameters(('dot',), ('cos'), ('dot_sqrt'))\n def test_coref_resolution_loss_multiple_devices(self, mode):\n \"\"\"Testing coreference resolution loss.\"\"\"\n\n def compute_loss(mention_encodings, mention_batch_positions,\n mention_target_is_masked, mention_ids):\n return mention_losses.coreference_resolution_loss(\n mention_encodings, mention_batch_positions, mention_ids,\n self.batch_size, mode, mention_target_is_masked, self.metrics_prefix)\n\n loss_sharded, metrics_sharded = jax.pmap(\n compute_loss, axis_name='batch')(self.mention_encodings_sharded,\n self.mention_batch_positions_sharded,\n self.mention_target_is_masked_sharded,\n self.mention_target_ids_sharded)\n\n num_total_mentions, hidden_dim = self.mention_encodings_stacked.shape\n scores = np.zeros((num_total_mentions, num_total_mentions))\n total_avg_scores, total_unnorm_avg_scores = [], []\n for i in range(num_total_mentions):\n current_avg_scores = []\n current_unnorm_avg_scores = []\n for j in range(num_total_mentions):\n if mode == 'dot':\n scores[i, j] = np.dot(self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j])\n elif mode == 'dot_sqrt':\n scores[i, j] = np.dot(\n self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j]) / np.sqrt(hidden_dim)\n elif mode == 'cos':\n scores[i, j] = 1 - scipy.spatial.distance.cosine(\n self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j])\n else:\n raise ValueError('Unknown coreference resolution mode: ' + mode)\n if self.mention_target_ids_stacked[j] != 0:\n current_avg_scores.append(scores[i, j])\n current_unnorm_avg_scores.append(\n np.dot(self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j]))\n # pylint: disable=g-explicit-length-test\n if len(current_avg_scores) > 0:\n current_avg_scores = np.array(current_avg_scores)\n total_avg_scores.append(current_avg_scores.mean())\n current_unnorm_avg_scores = np.array(current_unnorm_avg_scores)\n total_unnorm_avg_scores.append(current_unnorm_avg_scores.mean())\n else:\n total_avg_scores.append(0)\n total_unnorm_avg_scores.append(0)\n self.assertLen(total_avg_scores, len(self.mention_target_ids_stacked))\n\n expected_loss, expected_acc, expected_denom = 0, 0, 0\n expected_denom_masked, expected_denom_non_masked = 0, 0\n expected_acc_masked, expected_acc_non_masked = 0, 0\n expected_n_positives, expected_n_negatives = 0, 0\n expected_avg_scores, expected_unnorm_avg_scores = 0, 0\n expected_avg_norms = 0\n for i in range(len(self.mention_target_ids_stacked)):\n if self.mention_target_ids_stacked[i] == 0:\n continue\n positive_scores, negative_scores = [], []\n for j in range(len(self.mention_target_ids_stacked)):\n if self.mention_target_ids_stacked[j] == 0:\n continue\n is_same_device = i // self.n_mentions == j // self.n_mentions\n is_same_passage = (\n self.mention_batch_positions_stacked[i] ==\n self.mention_batch_positions_stacked[j])\n is_same_passage = is_same_passage and is_same_device\n if is_same_passage:\n continue\n if (self.mention_target_ids_stacked[i] ==\n self.mention_target_ids_stacked[j]):\n positive_scores.append(scores[i, j])\n else:\n negative_scores.append(scores[i, j])\n n_pos = len(positive_scores)\n n_neg = len(negative_scores)\n max_negative_scores = max(negative_scores)\n if n_pos == 0 or n_neg == 0:\n continue\n current_loss, current_acc = 0, 0\n for pos_index in range(n_pos):\n current_scores = np.array([positive_scores[pos_index]] +\n negative_scores)\n current_scores = jax.nn.log_softmax(current_scores)\n current_loss += -current_scores[0]\n current_acc += int(positive_scores[pos_index] > max_negative_scores)\n\n expected_loss += current_loss / n_pos\n expected_acc += current_acc / n_pos\n expected_denom += 1\n if self.mention_target_is_masked_stacked[i] > 0:\n expected_denom_masked += 1\n expected_acc_masked += current_acc / n_pos\n else:\n expected_denom_non_masked += 1\n expected_acc_non_masked += current_acc / n_pos\n\n expected_n_positives += n_pos\n expected_n_negatives += n_neg\n expected_avg_scores += total_avg_scores[i]\n expected_unnorm_avg_scores += total_unnorm_avg_scores[i]\n expected_avg_norms += np.linalg.norm(self.mention_encodings_stacked[i])\n\n metrics_sharded = jax.tree_map(jnp.sum, metrics_sharded)\n metrics_sharded_masked = metrics_sharded[self.metrics_prefix +\n 'coref_resolution_masked']\n metrics_sharded_non_masked = metrics_sharded[self.metrics_prefix +\n 'coref_resolution_non_masked']\n metrics_sharded = metrics_sharded[self.metrics_prefix + 'coref_resolution']\n loss_sharded = jnp.sum(loss_sharded)\n\n self.assertAlmostEqual(loss_sharded, expected_loss, places=2)\n self.assertAlmostEqual(metrics_sharded['loss'], expected_loss, places=2)\n self.assertAlmostEqual(metrics_sharded['acc'], expected_acc, places=3)\n self.assertEqual(metrics_sharded['denominator'], expected_denom)\n self.assertEqual(metrics_sharded['n_positive'], expected_n_positives)\n self.assertEqual(metrics_sharded['n_negative'], expected_n_negatives)\n self.assertAlmostEqual(\n metrics_sharded['avg_score'], expected_avg_scores, places=2)\n self.assertAlmostEqual(\n metrics_sharded['avg_unnorm_score'],\n expected_unnorm_avg_scores,\n places=2)\n self.assertAlmostEqual(\n metrics_sharded['avg_norm'], expected_avg_norms, places=2)\n\n self.assertAlmostEqual(\n metrics_sharded_masked['acc'], expected_acc_masked, places=3)\n self.assertEqual(metrics_sharded_masked['denominator'],\n expected_denom_masked)\n self.assertAlmostEqual(\n metrics_sharded_non_masked['acc'], expected_acc_non_masked, places=3)\n self.assertEqual(metrics_sharded_non_masked['denominator'],\n expected_denom_non_masked)\n\n def test_coref_resolution_loss_multiple_vs_single_devices(self):\n \"\"\"Comparing coreference resolution loss on multiple vs single devices.\"\"\"\n\n def compute_loss(mention_encodings, mention_batch_positions, mention_ids,\n mention_target_is_masked):\n return mention_losses.coreference_resolution_loss(\n mention_encodings, mention_batch_positions, mention_ids,\n self.batch_size, 'dot', mention_target_is_masked, self.metrics_prefix)\n\n loss_sharded, metrics_sharded = jax.pmap(\n compute_loss, axis_name='batch')(self.mention_encodings_sharded,\n self.mention_batch_positions_sharded,\n self.mention_target_ids_sharded,\n self.mention_target_is_masked_sharded)\n\n mention_batch_positions_stacked = (\n self.mention_batch_positions_stacked.reshape(self.n_devices, -1))\n mention_batch_positions_stacked = mention_batch_positions_stacked.copy()\n mention_batch_positions_stacked += (\n np.expand_dims(np.arange(self.n_devices), 1) * self.batch_size)\n mention_batch_positions_stacked = mention_batch_positions_stacked.reshape(\n -1)\n loss_stacked, metrics_stacked = compute_loss(\n self.mention_encodings_stacked, mention_batch_positions_stacked,\n self.mention_target_ids_stacked, self.mention_target_is_masked_stacked)\n\n loss_sharded = jnp.sum(loss_sharded)\n metrics_sharded = jax.tree_map(jnp.sum, metrics_sharded)\n\n self.assertAlmostEqual(loss_sharded, loss_stacked, places=2)\n for metric_group_name in metrics_stacked:\n for metric_name in metrics_stacked[metric_group_name]:\n self.assertAlmostEqual(\n metrics_sharded[metric_group_name][metric_name],\n metrics_stacked[metric_group_name][metric_name],\n places=2)\n\n @parameterized.parameters(('dot',), ('cos'), ('dot_sqrt'))\n def test_mtb_loss_multiple_devices(self, mode):\n \"\"\"Testing MTB loss.\"\"\"\n\n def compute_loss(mention_encodings, mention_batch_positions, mention_ids,\n mention_target_is_masked):\n return mention_losses.mtb_loss(mention_encodings, mention_batch_positions,\n mention_ids, self.batch_size, mode,\n mention_target_is_masked,\n self.metrics_prefix)\n\n loss_sharded, metrics_sharded = jax.pmap(\n compute_loss, axis_name='batch')(self.mention_encodings_sharded,\n self.mention_batch_positions_sharded,\n self.mention_target_ids_sharded,\n self.mention_target_is_masked_sharded)\n\n batches = []\n for i in range(self.n_devices):\n batches.append([])\n for j in range(self.batch_size):\n batches[i].append(set())\n for j in range(self.n_mentions):\n if self.mention_target_ids_sharded[i, j] > 0:\n batches[i][self.mention_batch_positions_sharded[i, j]].add(\n self.mention_target_ids_sharded[i, j].item())\n\n num_total_mentions, hidden_dim = self.mention_encodings_stacked.shape\n\n # Compute the scores between mentions.\n scores = np.zeros((num_total_mentions, num_total_mentions))\n total_avg_scores, total_unnorm_avg_scores = [], []\n for i in range(num_total_mentions):\n current_avg_scores = []\n current_unnorm_avg_scores = []\n for j in range(num_total_mentions):\n if mode == 'dot':\n scores[i, j] = np.dot(self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j])\n elif mode == 'dot_sqrt':\n scores[i, j] = np.dot(\n self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j]) / np.sqrt(hidden_dim)\n elif mode == 'cos':\n scores[i, j] = 1 - scipy.spatial.distance.cosine(\n self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j])\n else:\n raise ValueError('Unknown coreference resolution mode: ' + mode)\n if self.mention_target_ids_stacked[j] != 0:\n current_avg_scores.append(scores[i, j])\n current_unnorm_avg_scores.append(\n np.dot(self.mention_encodings_stacked[i],\n self.mention_encodings_stacked[j]))\n # pylint: disable=g-explicit-length-test\n if len(current_avg_scores) > 0:\n current_avg_scores = np.array(current_avg_scores)\n total_avg_scores.append(current_avg_scores.mean())\n current_unnorm_avg_scores = np.array(current_unnorm_avg_scores)\n total_unnorm_avg_scores.append(current_unnorm_avg_scores.mean())\n else:\n total_avg_scores.append(0)\n total_unnorm_avg_scores.append(0)\n self.assertLen(total_avg_scores, len(self.mention_target_ids_stacked))\n\n # Compute the loss and metrics.\n expected_loss, expected_acc, expected_denom = 0, 0, 0\n expected_n_positives, expected_n_negatives = 0, 0\n expected_n_hard_negatives = 0\n expected_avg_scores, expected_unnorm_avg_scores = 0, 0\n expected_denom_masked, expected_denom_non_masked = 0, 0\n expected_acc_masked, expected_acc_non_masked = 0, 0\n expected_avg_norms = 0\n for i in range(len(self.mention_target_ids_stacked)):\n if self.mention_target_ids_stacked[i] == 0:\n continue\n device_i = i // self.n_mentions\n unique_entities_i = (\n batches[device_i][self.mention_batch_positions_sharded[\n device_i, i % self.n_mentions]])\n\n positive_scores, hard_negative_scores, negative_scores = [], [], []\n for j in range(len(self.mention_target_ids_stacked)):\n if self.mention_target_ids_stacked[j] == 0:\n continue\n device_j = j // self.n_mentions\n is_same_device = device_i == device_j\n is_same_passage = (\n self.mention_batch_positions_stacked[i] ==\n self.mention_batch_positions_stacked[j])\n is_same_passage = is_same_passage and is_same_device\n if is_same_passage:\n continue\n if (self.mention_target_ids_stacked[i] ==\n self.mention_target_ids_stacked[j]):\n unique_entities_j = (\n batches[device_j][self.mention_batch_positions_sharded[\n device_j, j % self.n_mentions]])\n num_common_entities = len(\n unique_entities_i.intersection(unique_entities_j))\n if num_common_entities >= 2:\n positive_scores.append(scores[i, j])\n else:\n hard_negative_scores.append(scores[i, j])\n else:\n negative_scores.append(scores[i, j])\n negative_scores = negative_scores + hard_negative_scores\n n_pos = len(positive_scores)\n n_neg = len(negative_scores)\n n_hard_neg = len(hard_negative_scores)\n max_negative_scores = max(negative_scores)\n if n_pos == 0 or n_hard_neg == 0:\n continue\n current_loss, current_acc = 0, 0\n for pos_index in range(n_pos):\n current_scores = np.array([positive_scores[pos_index]] +\n negative_scores)\n current_scores = jax.nn.log_softmax(current_scores)\n current_loss += -current_scores[0]\n current_acc += int(positive_scores[pos_index] > max_negative_scores)\n\n expected_loss += current_loss / n_pos\n expected_acc += current_acc / n_pos\n expected_denom += 1\n if self.mention_target_is_masked_stacked[i] > 0:\n expected_denom_masked += 1\n expected_acc_masked += current_acc / n_pos\n else:\n expected_denom_non_masked += 1\n expected_acc_non_masked += current_acc / n_pos\n expected_n_positives += n_pos\n expected_n_negatives += n_neg\n expected_n_hard_negatives += n_hard_neg\n expected_avg_scores += total_avg_scores[i]\n expected_unnorm_avg_scores += total_unnorm_avg_scores[i]\n expected_avg_norms += np.linalg.norm(self.mention_encodings_stacked[i])\n\n metrics_sharded = jax.tree_map(jnp.sum, metrics_sharded)\n metrics_sharded_masked = metrics_sharded[self.metrics_prefix + 'mtb_masked']\n metrics_sharded_non_masked = metrics_sharded[self.metrics_prefix +\n 'mtb_non_masked']\n metrics_sharded = metrics_sharded[self.metrics_prefix + 'mtb']\n\n loss_sharded = jnp.sum(loss_sharded)\n self.assertAlmostEqual(loss_sharded, expected_loss, places=2)\n self.assertAlmostEqual(metrics_sharded['loss'], expected_loss, places=2)\n self.assertAlmostEqual(metrics_sharded['acc'], expected_acc, places=3)\n self.assertEqual(metrics_sharded['denominator'], expected_denom)\n self.assertEqual(metrics_sharded['n_positive'], expected_n_positives)\n self.assertEqual(metrics_sharded['n_negative'], expected_n_negatives)\n self.assertEqual(metrics_sharded['n_hard_negative'],\n expected_n_hard_negatives)\n self.assertAlmostEqual(\n metrics_sharded['avg_score'], expected_avg_scores, places=2)\n self.assertAlmostEqual(\n metrics_sharded['avg_unnorm_score'],\n expected_unnorm_avg_scores,\n places=2)\n self.assertAlmostEqual(\n metrics_sharded['avg_norm'], expected_avg_norms, places=2)\n self.assertAlmostEqual(\n metrics_sharded_masked['acc'], expected_acc_masked, places=3)\n self.assertEqual(metrics_sharded_masked['denominator'],\n expected_denom_masked)\n self.assertAlmostEqual(\n metrics_sharded_non_masked['acc'], expected_acc_non_masked, places=3)\n self.assertEqual(metrics_sharded_non_masked['denominator'],\n expected_denom_non_masked)\n\n def test_mtb_loss_multiple_vs_single_devices(self):\n \"\"\"Comparing MTB loss on multiple vs single devices.\"\"\"\n\n def loss_fn_multi_device(mention_encodings, mention_batch_positions,\n mention_ids, mention_target_is_masked):\n return mention_losses.mtb_loss(mention_encodings, mention_batch_positions,\n mention_ids, self.batch_size, 'dot',\n mention_target_is_masked,\n self.metrics_prefix)\n\n loss_sharded, metrics_sharded = jax.pmap(\n loss_fn_multi_device,\n axis_name='batch')(self.mention_encodings_sharded,\n self.mention_batch_positions_sharded,\n self.mention_target_ids_sharded,\n self.mention_target_is_masked_sharded)\n\n mention_batch_positions_stacked = (\n self.mention_batch_positions_stacked.reshape(self.n_devices, -1))\n mention_batch_positions_stacked = mention_batch_positions_stacked.copy()\n mention_batch_positions_stacked += (\n np.expand_dims(np.arange(self.n_devices), 1) * self.batch_size)\n mention_batch_positions_stacked = mention_batch_positions_stacked.reshape(\n -1)\n loss_stacked, metrics_stacked = mention_losses.mtb_loss(\n self.mention_encodings_stacked, mention_batch_positions_stacked,\n self.mention_target_ids_stacked, self.batch_size * self.n_devices,\n 'dot', self.mention_target_is_masked_stacked, self.metrics_prefix)\n\n loss_sharded = jnp.sum(loss_sharded)\n metrics_sharded = jax.tree_map(jnp.sum, metrics_sharded)\n\n self.assertAlmostEqual(loss_sharded, loss_stacked, places=2)\n for metric_group_name in metrics_stacked:\n for metric_name in metrics_stacked[metric_group_name]:\n self.assertAlmostEqual(\n metrics_sharded[metric_group_name][metric_name],\n metrics_stacked[metric_group_name][metric_name],\n places=2)\n\n @parameterized.parameters(('dot',), ('cos'), ('dot_sqrt'))\n def test_entity_linking_loss(self, mode):\n n_mentions = 5\n n_entities = 10\n hidden_size = 3\n mention_encodings = np.random.random((n_mentions, hidden_size))\n entity_embeddings = np.random.random((n_entities, hidden_size))\n mention_target_ids = np.random.randint(n_entities, size=(n_mentions))\n mention_target_weights = np.random.randint(2, size=(n_mentions))\n\n (actual_loss, actual_metrics,\n (actual_acc_per_mention,\n actual_weight_per_mention)) = mention_losses.entity_linking_loss(\n mention_encodings, entity_embeddings, mention_target_ids,\n mention_target_weights, mode)\n\n # Simple consistency checks\n self.assertArrayEqual(mention_target_weights, actual_weight_per_mention)\n self.assertEqual(actual_metrics['loss'], actual_loss)\n self.assertAlmostEqual(\n actual_metrics['acc'], actual_acc_per_mention.sum(), places=6)\n self.assertAlmostEqual(\n actual_metrics['denominator'], mention_target_weights.sum(), places=8)\n\n scores = np.matmul(mention_encodings, np.transpose(entity_embeddings))\n if mode == 'dot_sqrt':\n scores /= np.sqrt(hidden_size)\n if mode == 'cos':\n scores /= np.expand_dims(np.linalg.norm(mention_encodings, axis=-1), 1)\n scores /= np.expand_dims(np.linalg.norm(entity_embeddings, axis=-1), 0)\n\n log_probs = np.log(scipy.special.softmax(scores, axis=-1))\n expected_loss = 0\n expected_acc_per_mention = []\n expected_cos_sim_per_mention = []\n for i in range(n_mentions):\n if mention_target_weights[i] == 1:\n expected_loss += -log_probs[i, mention_target_ids[i]]\n is_correct = int(np.argmax(log_probs[i]) == mention_target_ids[i])\n expected_acc_per_mention.append(is_correct)\n expected_cos_sim_per_mention.append(1 - scipy.spatial.distance.cosine(\n mention_encodings[i], entity_embeddings[mention_target_ids[i]]))\n else:\n expected_acc_per_mention.append(0)\n expected_cos_sim_per_mention.append(0)\n expected_acc_per_mention = np.array(expected_acc_per_mention)\n expected_cos_sim_per_mention = np.array(expected_cos_sim_per_mention)\n self.assertAlmostEqual(actual_loss, expected_loss, places=4)\n self.assertAlmostEqual(\n actual_metrics['denominator'], mention_target_weights.sum(), places=8)\n self.assertArrayAlmostEqual(\n actual_acc_per_mention, expected_acc_per_mention, places=8)\n self.assertAlmostEqual(\n actual_metrics['cos_sim'], expected_cos_sim_per_mention.sum(), places=2)\n\n @parameterized.parameters([\n {\n 'batch_size': 1,\n },\n {\n 'batch_size': 11,\n },\n {\n 'batch_size': 11,\n 'entity_vocab_size': 1000000,\n },\n {\n 'batch_size': 2,\n 'n_target_mentions': 19,\n },\n {\n 'batch_size': 2,\n 'n_target_mentions': 19,\n 'entity_vocab_size': 2,\n },\n {\n 'batch_size': 2,\n 'k_top': 1,\n },\n {\n 'batch_size': 2,\n 'n_mentions_per_memory_passage': 21,\n },\n {\n 'batch_size': 10,\n 'n_mentions_per_memory_passage': 41,\n },\n {\n 'batch_size': 10,\n 'n_mentions': 100,\n },\n {\n 'batch_size': 2,\n 'n_mentions': 1,\n },\n {\n 'batch_size': 11,\n 'p_memory_mask': 0,\n },\n {\n 'batch_size': 11,\n 'p_memory_mask': 1,\n },\n ])\n def test_same_entity_set_retrieval_loss(self,\n batch_size,\n n_target_mentions=11,\n n_mentions=21,\n entity_vocab_size=10,\n k_top=10,\n n_mentions_per_memory_passage=4,\n p_memory_mask=0.5):\n np.random.seed(0)\n mention_target_batch_positions = np.random.randint(\n batch_size, size=(n_target_mentions))\n mention_target_ids = np.random.randint(\n entity_vocab_size, size=(n_target_mentions))\n mention_target_weights = np.random.randint(2, size=(n_target_mentions))\n mention_batch_positions = np.random.randint(batch_size, size=(n_mentions))\n mention_mask = np.random.randint(2, size=(n_mentions))\n memory_mask = np.random.random((n_mentions, k_top)) < p_memory_mask\n memory_mask = memory_mask.astype(np.int32)\n\n # `memory_text_entities` are assumed to contain unique IDs in the last dim.\n memory_text_entities = np.zeros(\n (n_mentions, k_top, n_mentions_per_memory_passage), np.int32)\n for m_index in range(n_mentions):\n for r_index in range(k_top):\n current_text_entities = np.random.choice(\n entity_vocab_size,\n size=(min(n_mentions_per_memory_passage, entity_vocab_size)),\n replace=False)\n memory_text_entities[\n m_index,\n r_index, :len(current_text_entities)] = current_text_entities\n memory_attention_weights = np.random.random((n_mentions, k_top))\n memory_attention_weights /= memory_attention_weights.sum(\n axis=-1, keepdims=True)\n\n actual_entity_overlap = mention_losses.get_batch_and_retrievals_entity_overlap(\n mention_target_batch_positions=mention_target_batch_positions,\n mention_target_ids=mention_target_ids,\n mention_target_weights=mention_target_weights,\n memory_text_entities=memory_text_entities.reshape(\n [n_mentions * k_top, -1]),\n batch_size=batch_size,\n )\n actual_entity_overlap = actual_entity_overlap.reshape(\n [batch_size, n_mentions, k_top])\n\n expected_entity_overlap = np.zeros((batch_size, n_mentions, k_top))\n for batch_index in range(batch_size):\n sample_ids = mention_target_ids[mention_target_batch_positions ==\n batch_index]\n sample_weights = mention_target_weights[mention_target_batch_positions ==\n batch_index]\n sample_ids = sample_ids[sample_weights > 0]\n sample_ids = set([x for x in sample_ids if x != 0])\n for m_index in range(n_mentions):\n for r_index in range(k_top):\n common_ids = set(\n memory_text_entities[m_index, r_index]).intersection(sample_ids)\n expected_entity_overlap[batch_index, m_index,\n r_index] = len(common_ids)\n\n self.assertArrayEqual(expected_entity_overlap, actual_entity_overlap)\n\n for same_entity_set_target_threshold in [1, 2, 3]:\n (actual_loss, actual_avg_probs,\n actual_denom) = mention_losses.same_entity_set_retrieval_loss(\n mention_target_batch_positions=mention_target_batch_positions,\n mention_target_ids=mention_target_ids,\n mention_target_weights=mention_target_weights,\n mention_batch_positions=mention_batch_positions,\n mention_mask=mention_mask,\n memory_text_entities=memory_text_entities,\n memory_attention_weights=memory_attention_weights,\n memory_mask=memory_mask,\n batch_size=batch_size,\n same_entity_set_target_threshold=same_entity_set_target_threshold,\n )\n\n expected_loss, expected_avg_probs, expected_denom = 0, 0, 0\n for batch_index in range(batch_size):\n for m_index in range(n_mentions):\n if mention_batch_positions[m_index] != batch_index:\n continue\n if mention_mask[m_index] == 0:\n continue\n\n correct_prob, n_positive, n_negative = 0, 0, 0\n for r_index in range(k_top):\n if memory_mask[m_index, r_index] == 0:\n continue\n if (expected_entity_overlap[batch_index, m_index, r_index] >=\n same_entity_set_target_threshold):\n correct_prob += memory_attention_weights[m_index, r_index]\n n_positive += 1\n else:\n n_negative += 1\n\n if n_positive > 0 and n_negative > 0:\n expected_loss -= np.log(correct_prob + 1e-5)\n expected_avg_probs += correct_prob\n expected_denom += 1\n\n self.assertEqual(actual_denom, expected_denom)\n self.assertAlmostEqual(actual_loss, expected_loss, places=4)\n self.assertAlmostEqual(actual_avg_probs, expected_avg_probs, places=4)\n\n\nif __name__ == '__main__':\n absltest.main()\n"
] |
[
[
"tensorflow.compat.v1.data.TFRecordDataset",
"tensorflow.compat.v1.to_int32",
"tensorflow.compat.v1.gfile.Open",
"tensorflow.compat.v1.FixedLenFeature",
"tensorflow.compat.v1.gfile.Glob",
"tensorflow.compat.v1.logging.info",
"tensorflow.compat.v1.parse_single_example",
"tensorflow.compat.v1.python_io.TFRecordWriter",
"tensorflow.compat.v1.train.Features"
],
[
"numpy.dot",
"numpy.log",
"numpy.random.random",
"numpy.sqrt",
"numpy.random.seed",
"numpy.arange",
"numpy.linalg.norm",
"numpy.stack",
"numpy.argmax",
"numpy.transpose",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
boryana-ilieva/soepy_dev
|
[
"98655bb1d7012c5554201a8dcfb728eeeaadf5bf"
] |
[
"development/tests/property/property_auxiliary.py"
] |
[
"\"\"\"This module contains some auxiliary functions for the property testing.\"\"\"\nfrom datetime import datetime\nimport importlib\nimport argparse\nimport shutil\nimport string\nimport glob\nimport os\n\nimport numpy as np\n\nfrom soepy.python.soepy_config import PACKAGE_DIR\n\n\ndef collect_tests():\n \"\"\"This function collects all available tests.\"\"\"\n\n current_wd = os.getcwd()\n os.chdir(PACKAGE_DIR + \"/test\")\n test_modules = glob.glob(\"test_*.py\")\n os.chdir(current_wd)\n test_dict = dict()\n for module in sorted(test_modules):\n test_dict[module] = []\n mod = importlib.import_module(\"soepy.test.\" + module.replace(\".py\", \"\"))\n for candidate in sorted(dir(mod)):\n if \"test\" in candidate and \"py\" not in candidate:\n test_dict[module] += [candidate]\n return test_dict\n\n\ndef run_property_test(module, test, dirname=None):\n \"\"\"This function runs a single replication test.\"\"\"\n mod = importlib.import_module(\"soepy.test.\" + module.replace(\".py\", \"\"))\n test_fun = getattr(mod, test)\n\n # We do not switch directories if we are investigating a failed test case.\n if dirname is not None:\n if os.path.exists(dirname):\n shutil.rmtree(dirname)\n\n os.mkdir(dirname)\n os.chdir(dirname)\n\n test_fun()\n\n\ndef print_rslt_ext(start, timeout, rslt, err_msg):\n \"\"\"This function print out the current state of the property tests.\"\"\"\n\n start_time = start.strftime(\"%Y-%m-%d %H:%M:%S\")\n end_time = (start + timeout).strftime(\"%Y-%m-%d %H:%M:%S\")\n current_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n with open(\"property.soepy.info\", \"w\") as outfile:\n\n # Write out some header information.\n outfile.write(\"\\n\\n\")\n str_ = \"\\t{0[0]:<15}{0[1]:<20}\\n\\n\"\n outfile.write(str_.format([\"START\", start_time]))\n outfile.write(str_.format([\"FINISH\", end_time]))\n outfile.write(str_.format([\"UPDATE\", current_time]))\n\n modules = sorted(rslt.keys())\n\n for module in modules:\n\n outfile.write(\"\\n \" + module.replace(\".py\", \"\") + \"\\n\\n\")\n\n string = \"{:>18}{:>15}{:>15}\\n\\n\"\n outfile.write(string.format(\"Test\", \"Success\", \"Failure\"))\n\n for test in sorted(rslt[module].keys()):\n\n stat = rslt[module][test]\n\n string = \"{:>18}{:>15}{:>15}\\n\"\n outfile.write(string.format(*[test] + stat))\n\n outfile.write(\"\\n\")\n outfile.write(\"\\n\" + \"-\" * 79 + \"\\n\\n\")\n\n for err in err_msg:\n\n module, test, seed, msg = err\n\n string = \"MODULE {:<25} TEST {:<15} SEED {:<15}\\n\\n\"\n outfile.write(string.format(*[module, test, seed]))\n outfile.write(msg)\n outfile.write(\"\\n\" + \"-\" * 79 + \"\\n\\n\")\n\n\ndef finish(rslt):\n \"\"\"This function simply finalizes the logging.\"\"\"\n # We want to record the overall performance.\n num_tests_total, num_success = 0, 0\n for module in sorted(rslt.keys()):\n for test in sorted(rslt[module].keys()):\n num_tests_total += np.sum(rslt[module][test])\n num_success += rslt[module][test][0]\n\n with open(\"property.soepy.info\", \"a\") as outfile:\n string = \"{:>18}{:>15}\\n\"\n outfile.write(string.format(*[\"Success\", num_tests_total]))\n outfile.write(string.format(*[\"Total\", num_success]))\n\n outfile.write(\"\\n TERMINATED\")\n\n\ndef distribute_command_line_arguments(args):\n \"\"\"This function distributes the command line arguments.\"\"\"\n rslt = dict()\n try:\n rslt[\"num_tests\"] = args.num_tests\n except AttributeError:\n pass\n\n try:\n rslt[\"request\"] = args.request\n except AttributeError:\n pass\n\n try:\n rslt[\"hours\"] = args.hours\n except AttributeError:\n pass\n\n try:\n rslt[\"seed\"] = args.seed\n except AttributeError:\n pass\n\n try:\n rslt[\"is_update\"] = args.is_update\n except AttributeError:\n pass\n\n rslt[\"is_check\"] = rslt[\"request\"] in [\"check\", \"investigate\"]\n\n return rslt\n\n\ndef process_command_line_arguments(which):\n \"\"\"This function processes the command line arguments for the test battery.\"\"\"\n is_request, is_hours, is_seed, is_test, is_update = (\n False,\n False,\n False,\n False,\n False,\n )\n\n if which == \"replication\":\n msg = \"Test replication of package\"\n is_request, is_hours, is_seed = True, True, True\n elif which == \"regression\":\n msg = \"Test package for regressions\"\n is_request, is_test, is_update = True, True, True\n elif which == \"property\":\n msg = \"Property testing of package\"\n is_request, is_seed, is_hours = True, True, True\n else:\n raise NotImplementedError\n\n parser = argparse.ArgumentParser(msg)\n\n if is_request:\n if which == \"regression\":\n parser.add_argument(\n \"--request\",\n action=\"store\",\n dest=\"request\",\n help=\"task to perform\",\n required=True,\n choices=[\"check\", \"create\"],\n )\n else:\n parser.add_argument(\n \"--request\",\n action=\"store\",\n dest=\"request\",\n help=\"task to perform\",\n required=True,\n choices=[\"run\", \"investigate\"],\n )\n\n if is_hours:\n parser.add_argument(\n \"--hours\", action=\"store\", dest=\"hours\", type=float, help=\"hours\"\n )\n\n if is_seed:\n parser.add_argument(\n \"--seed\", action=\"store\", dest=\"seed\", type=int, help=\"seed\"\n )\n\n if is_test:\n parser.add_argument(\n \"--tests\",\n action=\"store\",\n dest=\"num_tests\",\n required=True,\n type=int,\n help=\"number of tests\",\n )\n\n if is_update:\n parser.add_argument(\n \"--update\",\n action=\"store_true\",\n dest=\"is_update\",\n required=False,\n help=\"update regression vault\",\n )\n\n return parser.parse_args()\n\n\ndef get_random_string(size=6):\n \"\"\"This function samples a random string of varying size.\"\"\"\n chars = list(string.ascii_lowercase)\n str_ = \"\".join(np.random.choice(chars) for _ in range(size))\n return str_\n"
] |
[
[
"numpy.sum",
"numpy.random.choice"
]
] |
liangdaojun/MSIN
|
[
"36acc8e3b746a7245a2d13e9c0cada1ccda06a91"
] |
[
"utils.py"
] |
[
"'''Some helper functions for PyTorch, including:\n - get_mean_and_std: calculate the mean and std value of dataset.\n - msr_init: net parameter initialization.\n - progress_bar: progress bar mimic xlua.progress.\n'''\nimport os\nimport sys\nimport time\n\nimport torch.nn as nn\nimport torch.nn.init as init\n\nimport numpy as np\nimport torch\n\ndef mixup_data(x1,x2,x3,y1,y2,y3):\n\n '''Compute the mixup data. Return mixed inputs, pairs of targets, and lambda'''\n y1,y2,y3=y1.numpy(),y2.numpy(),y3.numpy()\n \n mixed=torch.cat((x1,x2,x3),1)\n \n y_a, y_b, y_c = torch.Tensor(y1).type(torch.LongTensor), torch.Tensor(y2).type(torch.LongTensor), torch.Tensor(y3).type(torch.LongTensor)\n return mixed, y_a, y_b,y_c\n\n\ndef mixup_data_test(x):\n x = x.numpy()\n #mixed_x = torch.Tensor(lam * x + (1 - lam) * x[index,:])\n mixed_x=torch.Tensor(np.concatenate((0.5 * x, 0.5 * x),1))\n return mixed_x\n\ndef mixup_criterion(y_a, y_b,y_c,y_d, lam):\n return lambda criterion, pred,pred2,pred3,prec4: criterion(pred, y_a) + criterion(pred2, y_b) + criterion(pred3, y_c)+ criterion(prec4, y_d)\n\ndef get_mean_and_std(dataset):\n '''Compute the mean and std value of dataset.'''\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)\n mean = torch.zeros(3)\n std = torch.zeros(3)\n print('==> Computing mean and std..')\n for inputs, targets in dataloader:\n for i in range(3):\n mean[i] += inputs[:,i,:,:].mean()\n std[i] += inputs[:,i,:,:].std()\n mean.div_(len(dataset))\n std.div_(len(dataset))\n return mean, std\n\ndef init_params(net):\n '''Init layer parameters.'''\n for m in net.modules():\n if isinstance(m, nn.Conv2d):\n init.kaiming_normal(m.weight, mode='fan_out')\n if m.bias:\n init.constant(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n init.constant(m.weight, 1)\n init.constant(m.bias, 0)\n elif isinstance(m, nn.Linear):\n init.normal(m.weight, std=1e-3)\n if m.bias:\n init.constant(m.bias, 0)\n\n\n_, term_width = os.popen('stty size', 'r').read().split()\nterm_width = int(term_width)\n\nTOTAL_BAR_LENGTH = 65.\nlast_time = time.time()\nbegin_time = last_time\n\ndef progress_bar(current, total, msg=None):\n global last_time, begin_time\n if current == 0:\n begin_time = time.time() # Reset for new bar.\n\n cur_len = int(TOTAL_BAR_LENGTH*current/total)\n rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1\n\n sys.stdout.write(' [')\n for i in range(cur_len):\n sys.stdout.write('=')\n sys.stdout.write('>')\n for i in range(rest_len):\n sys.stdout.write('.')\n sys.stdout.write(']')\n\n cur_time = time.time()\n step_time = cur_time - last_time\n last_time = cur_time\n tot_time = cur_time - begin_time\n\n L = []\n L.append(' Step: %s' % format_time(step_time))\n L.append(' | Tot: %s' % format_time(tot_time))\n if msg:\n L.append(' | ' + msg)\n\n msg = ''.join(L)\n sys.stdout.write(msg)\n for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3):\n sys.stdout.write(' ')\n\n # Go back to the center of the bar.\n for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2):\n sys.stdout.write('\\b')\n sys.stdout.write(' %d/%d ' % (current+1, total))\n\n if current < total-1:\n sys.stdout.write('\\r')\n else:\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\ndef format_time(seconds):\n days = int(seconds / 3600/24)\n seconds = seconds - days*3600*24\n hours = int(seconds / 3600)\n seconds = seconds - hours*3600\n minutes = int(seconds / 60)\n seconds = seconds - minutes*60\n secondsf = int(seconds)\n seconds = seconds - secondsf\n millis = int(seconds*1000)\n\n f = ''\n i = 1\n if days > 0:\n f += str(days) + 'D'\n i += 1\n if hours > 0 and i <= 2:\n f += str(hours) + 'h'\n i += 1\n if minutes > 0 and i <= 2:\n f += str(minutes) + 'm'\n i += 1\n if secondsf > 0 and i <= 2:\n f += str(secondsf) + 's'\n i += 1\n if millis > 0 and i <= 2:\n f += str(millis) + 'ms'\n i += 1\n if f == '':\n f = '0ms'\n return f\n"
] |
[
[
"torch.nn.init.kaiming_normal",
"torch.Tensor",
"torch.zeros",
"torch.cat",
"torch.utils.data.DataLoader",
"numpy.concatenate",
"torch.nn.init.constant",
"torch.nn.init.normal"
]
] |
dolaver/calsagos
|
[
"9c4f77c9952ede6ffc4cb9dd915bb1cb2ca80b1c"
] |
[
"calsagos/redshift_boundaries.py"
] |
[
"# Filename: redshift_boundaries.py\r\n# Here we found a serie of scripts develop to estimate the\r\n# central redshift and velocity dispersion of the cluster\r\n# and to establish the limits in the redshift distribution\r\nimport numpy as np\r\n\r\n# Section dedicated to importing the modules from SubFind\r\nfrom . import cluster_kinematics\r\n\r\n# define speed of light in km/s\r\nc = 299792.458\r\n\r\n#####################################################################################################################################################################################\r\n#####################################################################################################################################################################################\r\n\r\n# FUNCTION THAT ESTIMATES THE UPPER AND LOWER BOUNNDS OF THE REDSHIFT DISTRIBUTION OF CLUSTER MEMBERS (3 x velocity dispersion)\r\n# (Pierluigi Cerulo 27/03/2016)\r\n\r\ndef calc_redshift_boundaries(redshift, escape_velocity, starting_redshift):\r\n\r\n \"\"\" redshift_boundaries = calsagos.redshift_boundaries.calc_redshift_boundaries(redshift, escape_velocity, starting_redshift)\r\n\r\n Function that estimates the central redshift, the\r\n velocity dispersion and the upper and lower bounds \r\n of the redshift distribution.\r\n \r\n The limits of the redshift distribution are estimated\r\n using a 3sigma clipping implementation \r\n\r\n This function was develop by P. Cerulo (27/03/2016)\r\n\r\n :param redshift: redshift of the cluster members\r\n :param escape_velocity: escape velocity of the cluster \r\n in km s-1 units\r\n :param starting_redshift: preliminary estimation of \r\n the redshift of the cluster\r\n\r\n\t:type redshift: array\r\n\t:type escape_velocity: int, float\r\n\t:type starting_redshift: int, float\r\n\r\n\t:returns: the redshift of the cluster and the upper\r\n and lower bound of the redshift distribution\r\n\t:rtype: numpy array\r\n\r\n .. note::\r\n\r\n calc_redshift_boundaries(redshift, escape_velocity, starting_redshift)[0] corresponds to the \r\n redshift of the cluster\r\n calc_redshift_boundaries(redshift, escape_velocity, starting_redshift)[1] corresponds to the\r\n velocity dispersion of the cluster\r\n calc_redshift_boundaries(redshift, escape_velocity, starting_redshift)[2] corresponds to the\r\n lower limit of the redshift\r\n calc_redshift_boundaries(redshift, escape_velocity, starting_redshift)[3] corresponds to the\r\n upper limit of the redshift\r\n\r\n\t\"\"\"\r\n\r\n #-- estimate the redshift and cluster velocity dispersion\r\n sigma_estimate = cluster_kinematics.calc_cluster_velocity_dispersion(redshift, escape_velocity, starting_redshift)\r\n\r\n new_cluster_redshift = sigma_estimate[0]\r\n sigma = sigma_estimate[1]\r\n\r\n #-- deriving upper and lower bounds of redshift distribution of cluster members\r\n redshift_upper_bound = new_cluster_redshift + 3*(sigma/c)\r\n redshift_lower_bound = new_cluster_redshift - 3*(sigma/c)\r\n\r\n #-- returning output quantity\r\n return np.array([new_cluster_redshift, sigma, redshift_lower_bound, redshift_upper_bound])\r\n\r\n#####################################################################################################################################################################################\r\n#####################################################################################################################################################################################\r\n\r\n\r\n\r\n\r\n\r\n"
] |
[
[
"numpy.array"
]
] |
FabulousFatTiger/ml-mipt
|
[
"770f84acee786a2d4c1bd7f13f8f3f7b1124464e"
] |
[
"homeworks_basic/assignment0_01_kNN/k_nearest_neighbor.py"
] |
[
"import numpy as np\n\"\"\"\nCredits: the original code belongs to Stanford CS231n course assignment1. Source link: http://cs231n.github.io/assignments2019/assignment1/\n\"\"\"\n\nclass KNearestNeighbor:\n \"\"\" a kNN classifier with L2 distance \"\"\"\n\n def __init__(self):\n pass\n\n def fit(self, X, y):\n \"\"\"\n Train the classifier. For k-nearest neighbors this is just\n memorizing the training data.\n\n Inputs:\n - X: A numpy array of shape (num_train, D) containing the training data\n consisting of num_train samples each of dimension D.\n - y: A numpy array of shape (N,) containing the training labels, where\n y[i] is the label for X[i].\n \"\"\"\n self.X_train = X\n self.y_train = y\n\n def predict(self, X, k=1, num_loops=0):\n \"\"\"\n Predict labels for test data using this classifier.\n\n Inputs:\n - X: A numpy array of shape (num_test, D) containing test data consisting\n of num_test samples each of dimension D.\n - k: The number of nearest neighbors that vote for the predicted labels.\n - num_loops: Determines which implementation to use to compute distances\n between training points and testing points.\n\n Returns:\n - y: A numpy array of shape (num_test,) containing predicted labels for the\n test data, where y[i] is the predicted label for the test point X[i].\n \"\"\"\n if num_loops == 0:\n dists = self.compute_distances_no_loops(X)\n elif num_loops == 1:\n dists = self.compute_distances_one_loop(X)\n elif num_loops == 2:\n dists = self.compute_distances_two_loops(X)\n else:\n raise ValueError('Invalid value %d for num_loops' % num_loops)\n\n return self.predict_labels(dists, k=k)\n\n def compute_distances_two_loops(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using a nested loop over both the training data and the\n test data.\n\n Inputs:\n - X: A numpy array of shape (num_test, D) containing test data.\n\n Returns:\n - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n is the Euclidean distance between the ith test point and the jth training\n point.\n \"\"\"\n num_test = X.shape[0]\n num_train = self.X_train.shape[0]\n dists = np.zeros((num_test, num_train))\n for i in range(num_test):\n for j in range(num_train):\n #####################################################################\n # TODO: #\n # Compute the l2 distance between the ith test point and the jth #\n # training point, and store the result in dists[i, j]. You should #\n # not use a loop over dimension, nor use np.linalg.norm(). #\n #####################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n dists[i, j] = np.sqrt(np.sum((X[i, :] - self.X_train[j, :])**2))\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n return dists\n\n def compute_distances_one_loop(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using a single loop over the test data.\n\n Input / Output: Same as compute_distances_two_loops\n \"\"\"\n num_test = X.shape[0]\n num_train = self.X_train.shape[0]\n dists = np.zeros((num_test, num_train))\n for i in range(num_test):\n #######################################################################\n # TODO: #\n # Compute the l2 distance between the ith test point and all training #\n # points, and store the result in dists[i, :]. #\n # Do not use np.linalg.norm(). #\n #######################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n dists[i, :] = np.sqrt(np.sum((self.X_train - X[i, :])**2, axis=1))\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n return dists\n\n def compute_distances_no_loops(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using no explicit loops.\n\n Input / Output: Same as compute_distances_two_loops\n \"\"\"\n num_test = X.shape[0]\n num_train = self.X_train.shape[0]\n dists = np.zeros((num_test, num_train))\n #########################################################################\n # TODO: #\n # Compute the l2 distance between all test points and all training #\n # points without using any explicit loops, and store the result in #\n # dists. #\n # #\n # You should implement this function using only basic array operations; #\n # in particular you should not use functions from scipy, #\n # nor use np.linalg.norm(). #\n # #\n # HINT: Try to formulate the l2 distance using matrix multiplication #\n # and two broadcast sums. #\n #########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n dists = np.sqrt((-2 * np.dot(X, self.X_train.T)) + np.sum(X**2, axis=1, keepdims=True) + np.sum(self.X_train**2, axis=1))\n\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n return dists\n\n def predict_labels(self, dists, k=1):\n \"\"\"\n Given a matrix of distances between test points and training points,\n predict a label for each test point.\n\n Inputs:\n - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n gives the distance betwen the ith test point and the jth training point.\n\n Returns:\n - y: A numpy array of shape (num_test,) containing predicted labels for the\n test data, where y[i] is the predicted label for the test point X[i].\n \"\"\"\n num_test = dists.shape[0]\n y_pred = np.zeros(num_test)\n for i in range(num_test):\n # A list of length k storing the labels of the k nearest neighbors to\n # the ith test point.\n #########################################################################\n # TODO: #\n # Use the distance matrix to find the k nearest neighbors of the ith #\n # testing point, and use self.y_train to find the labels of these #\n # neighbors. Store these labels in closest_y. #\n # Hint: Look up the function numpy.argsort. #\n #########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n k_nearest_idxs = np.argsort(dists[i, :])[:k]\n closest_y = self.y_train[k_nearest_idxs]\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n #########################################################################\n # TODO: #\n # Now that you have found the labels of the k nearest neighbors, you #\n # need to find the most common label in the list closest_y of labels. #\n # Store this label in y_pred[i]. Break ties by choosing the smaller #\n # label. #\n #########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n y_pred[i] = np.argmax(np.bincount(closest_y))\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n return y_pred\n"
] |
[
[
"numpy.dot",
"numpy.bincount",
"numpy.argsort",
"numpy.zeros",
"numpy.sum"
]
] |
yfe3/Intelligent-Systems
|
[
"14c22e144e1a7f8625b2ff3f63e9c0545f946f69"
] |
[
"Random walk experiment with Funtion Approximation/state_aggregation_agent.py"
] |
[
"#!/usr/bin/env python\n\n\"\"\"\n Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian\n Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent\n for use on A3 of Reinforcement learning course University of Alberta Fall 2017\n\n\"\"\"\n\nfrom utils import rand_in_range, rand_un\nimport numpy as np\nimport pickle\nimport random\n\nalpha = 0.1\n\nw = 0\n\n\noldS = 0\n\nnewS = 0\n\n\ndef agent_init():\n \"\"\"\n Hint: Initialize the variables that need to be reset before each run begins\n Returns: nothing\n \"\"\"\n\n # initialize the policy array in a smart way\n\n\n global w, oldS, newS\n\n w = np.zeros(11) # 1-10 = 0 ,0 not used\n\n\n\ndef agent_start(current_position):\n \"\"\"\n Hint: Initialize the variavbles that you want to reset before starting a new episode\n Arguments: state: numpy array\n Returns: action: integer\n \"\"\"\n # pick the first action, don't forget about exploring starts\n\n global w, oldS, newS\n\n # print(\"agent_stat\")\n # print(current_position)\n temp_ve = random.randint(0, 1) # choose left or right, 0 = right, 1 = left\n\n temp_action = random.randint(1, 100) # 1 100 random walk\n\n if temp_ve == 0: # change sign\n temp_ve = -1\n\n action = current_position + temp_ve * temp_action # get index in v\n\n #print(action)\n\n oldS = current_position\n\n return action\n\n\ndef agent_step(reward, position): # returns NumPy array, reward: floating point, this_observation: NumPy array\n \"\"\"\n Arguments: reward: floting point, state: integer\n Returns: action: integer\n \"\"\"\n # select an action, based on Q\n global w, newS, oldS\n\n # time_steps_counter+=1 # increment time step\n\n temp_ve = random.randint(0, 1) # choose left or right, 0 = right, 1 = left\n\n temp_action = random.randint(1, 100) # 1 100 random walk\n\n if temp_ve == 0: # change sign\n temp_ve = -1\n\n action = position + temp_ve * temp_action # get index in v\n\n newS = position\n\n # do update\n\n temp_w = np.zeros(11)\n\n temp_w[oldS//100] = 1\n\n w = w + alpha * (reward + 1 * w[newS//100] - w[oldS//100]) * temp_w # gamma = 1 for this problem\n\n oldS = newS\n\n #print(action)\n\n return action\n\n\ndef agent_end(reward):\n \"\"\"\n Arguments: reward: floating point\n Returns: Nothing\n \"\"\"\n # do learning and update pi\n\n global w, newS, oldS\n\n # do update\n\n temp_w = np.zeros(11)\n\n temp_w[oldS // 100] = 1\n\n w = w + alpha * (reward - w[oldS // 100]) * temp_w # tabular\n\n\ndef agent_cleanup():\n \"\"\"\n This function is not used\n \"\"\"\n # clean up\n return\n\n\ndef agent_message(in_message): # returns string, in_message: string\n global w\n\n # print(np.max(Q, axis=1)) #debug\n\n\n \"\"\"\n Arguments: in_message: string\n returns: The value function as a string.\n This function is complete. You do not need to add code here.\n \"\"\"\n # should not need to modify this function. Modify at your own risk\n if (in_message == 'ValueFunction'):\n\n # print(time_steps_result)\n return w # return result\n\n\n else:\n return \"I don't know what to return!!\"\n\n\n"
] |
[
[
"numpy.zeros"
]
] |
dgriffiths3/finding-your-center
|
[
"6eea1ed5d1bbd9064828133111e96f3395a3afcc"
] |
[
"scene_network/inference.py"
] |
[
"import os\nimport sys\nimport glob\nimport colorsys\n\nsys.path.insert(0, './')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport numpy as np\nimport pyvista as pv\nimport tensorflow as tf\n\nfrom scene_network.model import ObjDetectorModel\nfrom utils import helpers, tf_utils, losses\n\n\ndef plot_scene(scene, scene_pts, scene_ext, gt_pts, gt_ext):\n\n\tpts = scene[:, 0:3]\n\tcols = scene[:, 3:6]\n\n\tcols = cols[pts[:, 2] < np.max(pts[:, 2])-1.5]\n\tpts = pts[pts[:, 2] < np.max(pts[:, 2])-1.5]\n\n\tplot = pv.Plotter()\n\tplot.set_background('white')\n\t\n\tplot.add_points(pts, scalars=cols, rgb=True, opacity=1, render_points_as_spheres=True, point_size=10)\n\t\n\tif scene_pts.shape[0] > 0:\n\t\n\t\text_hwd = scene_ext[:, :3]\n\t\text_theta = scene_ext[:, 3:5]\n\t\n\t\tboxes_min = scene_pts - (ext_hwd / 2)\n\t\tboxes_max = scene_pts + (ext_hwd / 2)\n\t\tboxes = np.hstack((boxes_min, boxes_max))\n\t\n\t\tbox_pts = helpers.rotate_boxes(boxes, scene_pts, ext_theta)\n\t\n\t\tclasses = np.linspace(0, 1, box_pts.shape[0]+1)\n\t\trgb_classes = np.array([colorsys.hsv_to_rgb(c, 0.8, 0.8) for c in classes])\n\t\n\t\tfor i, box in enumerate(box_pts):\n\t\t\tlines = helpers.make_lines(box)\n\t\t\t[plot.add_mesh(l, color=rgb_classes[i], line_width=4) for l in lines]\n\t\n\tplot.view_xy()\n\tplot.show()\n\n\ndef parse_room():\n\n\tmodel = ObjDetectorModel(1, config['n_pred'])\n\tmodel(tf.zeros((1, config['n_pts'], 3), tf.float32))\n\tmodel.load_weights(config['weights'])\n\n\tif config['dataset'] == 's3d':\n\t\troom = 'Area_' + str(config['area']) + '_' + config['room'] + '.npy'\n\t\tscene = np.load(os.path.join(config['dataset_dir'], 'processed', room))\n\n\tscene_extent = [\n\t\tnp.min(scene[:, 0]), np.min(scene[:, 1]), np.min(scene[:, 2]),\n\t\tnp.max(scene[:, 0]), np.max(scene[:, 1]), np.max(scene[:, 2])\n\t]\n\n\tobject_paths = glob.glob(\n\t\tos.path.join(\n\t\t\tconfig['dataset_dir'],\n\t\t\t'Area_'+str(config['area']),\n\t\t\tconfig['room'],\n\t\t\t'Annotations',\n\t\t\t'*chair*.npy'\n\t\t)\n\t)\n\n\tobjects = np.array([np.load(o_f)[:, :3] for o_f in object_paths])\n\tgt_pts = np.array([np.mean(o, axis=0) for o in objects])\n\tgt_theta, gt_ext = helpers.get_oabb(objects)\n\tgt_ext = np.hstack((gt_ext, gt_theta))\n\n\tx_stride_len = config['box_size'][0]\n\ty_stride_len = config['box_size'][1]\n\n\tnum_xstrides = int(np.ceil((scene_extent[3] - scene_extent[0])/x_stride_len))\n\tnum_ystrides = int(np.ceil((scene_extent[4] - scene_extent[1])/y_stride_len))\n\n\tscene_pts = []\n\tscene_ext = []\n\n\tfor x_stride in range(num_xstrides):\n\n\t\tfor y_stride in range(num_ystrides):\n\n\t\t\tbbox = [\n\t\t\t\tscene_extent[0] + (x_stride*x_stride_len),\n\t\t\t\tscene_extent[1] + (y_stride*y_stride_len),\n\t\t\t\t-1e10,\n\t\t\t\tscene_extent[0] + ((x_stride*x_stride_len) + x_stride_len),\n\t\t\t\tscene_extent[1] + ((y_stride*y_stride_len) + y_stride_len),\n\t\t\t\t1e10\n\t\t\t]\n\n\t\t\tscene_crop = helpers.crop_bbox(scene, bbox)\n\t\t\t_, scene_crop = helpers.get_fixed_pts(scene_crop, config['n_pts'])\n\n\t\t\tpts = scene_crop[:, 0:3]\n\t\t\tcols = scene_crop[:, 3:6] / 256.\n\n\t\t\tpts_mean = np.mean(pts, axis=0)\n\t\t\tpts -= pts_mean\n\n\t\t\txyz, score, ext, _ = model(tf.expand_dims(pts, 0))\n\t\t\txyz, score, ext = tf_utils.objectness_mask(xyz, score[:, :, 1], ext, config['score_thresh'])\n\n\t\t\tlabels = gt_pts[\n\t\t\t\t(gt_pts[:, 0] >= bbox[0]) & (gt_pts[:, 0] <= bbox[3]) &\n\t\t\t\t(gt_pts[:, 1] >= bbox[1]) & (gt_pts[:, 1] <= bbox[4]) &\n\t\t\t\t(gt_pts[:, 2] >= bbox[2]) & (gt_pts[:, 2] <= bbox[5])\n\t\t\t]\n\n\t\t\tlabels = tf.expand_dims(labels - pts_mean, 0)\n\n\t\t\tif xyz.shape[1] > 1 and config['nms'] == True:\n\t\t\t\tboxes = helpers.make_boxes(xyz, ext)\n\t\t\t\tnms_inds = tf_utils.nms(xyz, boxes, score, 15, 0, config['score_thresh'])\n\n\t\t\t\txyz = tf.gather(xyz, nms_inds, batch_dims=1)\n\t\t\t\tscore = tf.gather(score, nms_inds, batch_dims=1)\n\t\t\t\tboxes = tf.gather(boxes, nms_inds, batch_dims=1)\n\t\t\t\text = tf.gather(ext, nms_inds, batch_dims=1)\n\n\t\t\tif xyz.shape[1] > 0:\n\t\t\t\tfor i, pred in enumerate(xyz[0]):\n\t\t\t\t\tscene_pts.append((pred.numpy()+pts_mean).tolist())\n\t\t\t\t\tscene_ext.append(ext[0, i].numpy().tolist())\n\n\tscene_pts = np.array(scene_pts)\n\tscene_ext = np.array(scene_ext)\n\n\tplot_scene(scene, scene_pts, scene_ext, gt_pts, gt_ext)\n\n\nif __name__ == '__main__':\n\n\tconfig = {\n\t\t'dataset' : 's3d',\n\t\t'dataset_dir' : './data/Stanford3dDataset',\n\t\t'area' : 5,\n\t\t'room' : 'office_1',\n\t\t'weights' : './logs/scenenet_1/models/weights.ckpt',\n\t\t'nms' : False,\n\t\t'score_thresh' : 0.9,\n\t\t'box_size' : (3, 3),\n\t\t'n_pts' : 32768,\n\t\t'n_pred' : 15\n\t}\n\n\tparse_room()\n"
] |
[
[
"numpy.hstack",
"numpy.linspace",
"numpy.min",
"tensorflow.zeros",
"tensorflow.expand_dims",
"numpy.max",
"numpy.ceil",
"tensorflow.gather",
"numpy.mean",
"numpy.load",
"numpy.array"
]
] |
passerby233/keratitis_imb
|
[
"a7fb12f39b2084b82e19da6dfe0097a6003a9ea2"
] |
[
"supervise_cross_ddp.py"
] |
[
"import os\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"4\"\n\nimport numpy as np\nimport random, torch, json\nfrom sklearn import metrics\nfrom functools import reduce\n\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom torch.cuda.amp import autocast, GradScaler\n\nfrom dataset import KeratitisLabeled\nfrom args import get_args\nfrom utils import get_model, get_optimizer, move_to_device, get_utils_cross, merge_report\nfrom supervise import seed_torch\n\nimport torch.distributed as dist\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\nimport logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s-%(levelname)s: %(message)s')\n\ndef train(model, dataloader, optimizer, use_amp, scaler):\n model.train()\n device = next(model.parameters()).device\n for step, data in enumerate(dataloader):\n image, target = move_to_device(data, device)\n optimizer.zero_grad()\n if use_amp:\n with autocast():\n pred = model(image)\n loss = F.cross_entropy(pred, target)\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n else:\n pred = model(image) # B x C\n loss = F.cross_entropy(pred, target)\n loss.backward()\n optimizer.step()\n\ndef test(model, dataloader):\n model.eval()\n device = next(model.parameters()).device\n logit_list, target_list = [], []\n with torch.no_grad():\n for step, data in enumerate(dataloader):\n image, target = data\n image = image.to(device)\n pred = model.module(image).cpu()\n logit_list.extend(pred.argmax(-1).tolist())\n target_list.extend(target.tolist())\n prob = F.softmax(pred, 1, dtype=torch.float32).cpu().detach().numpy()\n if step == 0:\n y_score = prob\n else:\n y_score = np.concatenate((y_score, prob), axis=0)\n\n report = metrics.classification_report(y_true=target_list, y_pred=logit_list, digits=3,\n target_names=dataloader.dataset.classes, \n zero_division=0, output_dict=False)\n report_dict = metrics.classification_report(y_true=target_list, y_pred=logit_list, digits=3,\n target_names=dataloader.dataset.classes, \n zero_division=0, output_dict=True)\n auc = metrics.roc_auc_score(y_true=target_list, y_score=y_score, multi_class='ovo')\n acc, f1_score = report_dict['accuracy'], report_dict['macro avg']['f1-score']\n report_dict['auc'] = auc\n return acc, f1_score, auc, report, report_dict\n\ndef main():\n seed_torch()\n\n # Get basic utils\n args = get_args()\n torch.distributed.init_process_group(backend='nccl', rank=args.local_rank, world_size=args.num_gpus)\n torch.cuda.set_device(args.local_rank)\n device = torch.device('cuda', args.local_rank)\n \n report_list = []\n for k in range(5):\n args.k = k\n if args.local_rank == 0:\n exp_dir, save_dir, writer = get_utils_cross(args)\n save_path = os.path.join(save_dir, f\"{args.model}.pth\")\n report_path = os.path.join(save_dir, 'report_dict.json')\n # Get dataloader for k_th fold\n dataset, loader = {}, {}\n for mode in ['train', 'test']:\n dataset[mode] = KeratitisLabeled(mode=mode, k=k)\n if mode == 'train':\n data_sampler = DistributedSampler(dataset[mode])\n loader[mode] = DataLoader(dataset[mode], batch_size=args.batch_size//args.num_gpus,\n num_workers=8, sampler=data_sampler, pin_memory=True)\n else:\n loader[mode] = DataLoader(dataset[mode], batch_size=args.batch_size, num_workers=8, pin_memory=True)\n\n if args.local_rank == 0:\n print(f\"Length of Train, Test dataset : {len(dataset['train']), len(dataset['test'])}\")\n\n # Load model\n model = get_model(args.model, len(dataset['test'].classes)).to(device)\n if args.ckpt:\n state_dict = model.state_dict()\n state_dict.update(torch.load(args.ckpt)) # only update the shared backbone part from byol\n model.load_state_dict(state_dict)\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n dist_model = DDP(model, device_ids=[args.local_rank], output_device=args.local_rank)\n\n # Get optimizer, scheduler, scaler\n optimizer = get_optimizer(model.parameters(), args)\n scheduler = MultiStepLR(optimizer, args.milestones, args.lr_decay)\n if args.use_amp:\n scaler = GradScaler()\n if args.local_rank == 0:\n logging.info(\"AMP activated\")\n \n # Train and Test Iteration\n max_acc = 0\n best_report, best_report_dict = None, None\n if args.local_rank == 0:\n logging.info(f'Start training, k={k}')\n for epoch in range(args.epochs):\n data_sampler.set_epoch(epoch)\n for i, mode in enumerate(['train', 'test']):\n if mode == 'train':\n dist.barrier()\n train(dist_model, loader['train'], optimizer, args.use_amp, scaler)\n scheduler.step()\n else:\n if args.local_rank == 0:\n acc, f1_score, auc, report, report_dict = test(dist_model, loader[mode])\n logging.info(f'{mode.capitalize():5} Acc:{acc:.3f}, {mode.capitalize():5} F1: {f1_score:.3f}, {mode.capitalize():5} AUC: {auc:.3f}') \n\n # Save model\n if acc > max_acc:\n max_acc, best_report, best_report_dict = acc, report, report_dict\n logging.info(f'Saving model, {args.model} got new max_acc: {max_acc}')\n torch.save(model.state_dict(), save_path)\n print(report)\n\n # log to tensorboard \n for num, metric_name, metric_value in zip(range(3), ('acc', 'f1_score', 'auc'), (acc, f1_score, auc)):\n writer.add_scalar(f'{i}_{mode}/{num}_{metric_name}', metric_value, epoch)\n \n if args.local_rank == 0:\n print('best_report:\\n' + best_report)\n with open(report_path ,'w') as f:\n json.dump(best_report_dict, f)\n report_list.append(best_report_dict)\n if args.local_rank == 0:\n avg_report_path = os.path.join(exp_dir, 'avg_report_dict.json')\n with open(avg_report_path ,'w') as f:\n json.dump(merge_report(report_list), f)\n\nif __name__ == '__main__':\n import warnings\n # to suppress annoying warnings from PIL\n warnings.filterwarnings(\"ignore\", \"(Possibly )?corrupt EXIF data\", UserWarning)\n\n main()"
] |
[
[
"torch.optim.lr_scheduler.MultiStepLR",
"sklearn.metrics.roc_auc_score",
"torch.nn.functional.softmax",
"torch.distributed.init_process_group",
"torch.cuda.set_device",
"torch.utils.data.distributed.DistributedSampler",
"torch.load",
"torch.nn.functional.cross_entropy",
"torch.utils.data.DataLoader",
"torch.distributed.barrier",
"torch.nn.SyncBatchNorm.convert_sync_batchnorm",
"torch.cuda.amp.autocast",
"numpy.concatenate",
"torch.cuda.amp.GradScaler",
"torch.no_grad",
"torch.device",
"sklearn.metrics.classification_report",
"torch.nn.parallel.DistributedDataParallel"
]
] |
WestCityInstitute/InvDN
|
[
"3846cf3548ccf6690e58be3aafe1f6d98c56b90d"
] |
[
"Crop_DIV2K.py"
] |
[
"import os\nimport cv2\nimport glob\nimport numpy as np\n\ncropSize = 256\nnum = 100\n\n# Crop SIDD\n# GT = glob.glob(os.path.join('/home/yang/Documents/Yang_Liu/Research_Projects/Data/SIDD/SIDD_Medium_Srgb/GT', '*.PNG'))\n# Noisy = glob.glob(os.path.join('/home/yang/Documents/Yang_Liu/Research_Projects/Data/SIDD/SIDD_Medium_Srgb/Noisy', '*.PNG'))\nGT = glob.glob(os.path.join('/home/zhenyue/Data/SIDD/SIDD_Medium_Srgb/GT', '*.PNG'))\nNoisy = glob.glob(os.path.join('/home/zhenyue/Data/SIDD/SIDD_Medium_Srgb/Noisy', '*.PNG'))\n\nGT.sort()\nNoisy.sort()\n\n# out_dir = '/home/yang/Documents/Yang_Liu/Research_Projects/Data/SIDD/SIDD_Medium_Srgb_Patches'\nout_dir = '/home/zhenyue/Data/SIDD/SIDD_Medium_Srgb_Patches'\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\nif not os.path.exists(os.path.join(out_dir, 'GT')):\n os.mkdir(os.path.join(out_dir, 'GT'))\nif not os.path.exists(os.path.join(out_dir, 'Noisy')):\n os.mkdir(os.path.join(out_dir, 'Noisy'))\n\nfor i in range(len(GT)):\n image = cv2.imread(GT[i])\n noisy_image = cv2.imread(Noisy[i])\n endw, endh = image.shape[0], image.shape[1]\n assert (endw >= cropSize) and (endh >= cropSize)\n for k in range(num):\n x = np.random.randint(0, endw - cropSize)\n y = np.random.randint(0, endh - cropSize)\n crop = image[x:(cropSize + x), y:(cropSize + y), :]\n noisy_crop = noisy_image[x:(cropSize + x), y:(cropSize + y), :]\n cv2.imwrite(os.path.join(out_dir, 'GT', '%d_%d.PNG'%(i, k)), crop)\n cv2.imwrite(os.path.join(out_dir, 'Noisy', '%d_%d.PNG' % (i, k)), noisy_crop)"
] |
[
[
"numpy.random.randint"
]
] |
spejamchr/unties
|
[
"5fd4a6ddf95310f008c89eeaa17598513022aba1"
] |
[
"unties/tests/test_unties.py"
] |
[
"from unittest import TestCase\nimport math\nimport numpy as np\nfrom scipy.optimize import fsolve\n\nimport unties as _\nimport unties.utilities.errors as ue\n\n\ndef _deep_map(func, *args):\n \"\"\"Like map, but recursively enters iterables\n\n Ex:\n\n >>> _deep_map(lambda a, b: a + b,\n (1, 2, (3, (4,), 5)),\n (10, 20, (30, (40,), 50)))\n [11, 22, [33, [44], 55]]\n\n \"\"\"\n try:\n return [_deep_map(func, *z) for z in zip(*args)]\n except TypeError:\n return func(*args)\n\n\nclass TestUnties(TestCase):\n\n def assert_display_with_units_of(self, units_group, units):\n self.assertEqual(units_group.full_name, units.full_name)\n\n # Test Addition\n def test_add_commutative_law(self):\n self.assertEqual(1 * _.m + 5 * _.m, 5 * _.m + 1 * _.m)\n\n def test_can_add_scalar_units_group_and_number(self):\n scalar = _.m / _.m\n self.assertEqual(scalar + 1, 2)\n\n def test_can_add_number_and_scalar_units_group(self):\n scalar = _.m / _.m\n self.assertEqual(1 + scalar, 2)\n\n # Test Subtraction #\n ####################\n def test_sub_commutative_law(self):\n self.assertEqual(3 * _.m - 1 * _.m, -(1 * _.m - 3 * _.m))\n\n def test_can_subtract_scalar_units_group_and_number(self):\n scalar = _.m / _.m\n self.assertEqual(scalar - 1, 0)\n\n def test_can_subtract_number_and_scalar_units_group(self):\n scalar = _.m / _.m\n self.assertEqual(1 - scalar, 0)\n\n # Test multiplication #\n #######################\n def test_m_times_m_equals_m_squared(self):\n self.assertEqual(_.m * _.m, _.m**2)\n\n def test_mult_commutative_law(self):\n self.assertEqual(_.m * 2, 2 * _.m)\n\n def test_np_mult_unit(self):\n try:\n np.array([5 * _.m, 2 * _.ft, 3 * _.inch]) * _.cm\n except:\n self.fail(\"np array * unit raised an error unexpectedly!\")\n\n def test_unit_mult_np(self):\n try:\n _.cm * np.array([5 * _.m, 2 * _.ft, 3 * _.inch])\n except:\n self.fail(\"unit * np array raised an error unexpectedly!\")\n\n def test_np_mult_is_commutative(self):\n linspace = np.linspace(1, 2)\n a = linspace * _.ft\n b = _.ft * linspace\n self.assertTrue(np.all(a == b))\n\n def test_mult_by_zero_to_get_zero(self):\n try:\n _.K * (0 / _.K)\n except:\n self.fail(\"_.K * (0 / _.K) raised an error unexpectedly!\")\n\n def test_mult_by_zero_to_get_zero_2(self):\n try:\n (0 / _.K) * _.K\n except:\n self.fail(\"(0 / _.K) * _.K raised an error unexpectedly!\")\n\n # Test Division #\n #################\n def test_division_by_one_equals_self(self):\n self.assertEqual(_.inch, _.inch / 1)\n\n def test_division_by_self_equals_1(self):\n self.assertEqual(_.inch / _.inch, 1)\n\n def test_div_commutative_law(self):\n self.assertEqual(_.m / _.inch, 1 / (_.inch / _.m))\n\n def test_mi_per_hr_div_by_mi_leaves_per_hr(self):\n self.assertEqual((_.mi / _.hr) / _.mi, 1 / _.hr)\n\n def test_np_div_unit(self):\n try:\n np.array([5 * _.m, 2 * _.ft, 3 * _.inch]) / _.cm\n except:\n self.fail(\"np array / unit raised an error unexpectedly!\")\n\n def test_unit_div_np(self):\n try:\n _.cm / np.array([5 * _.m, 2 * _.ft, 3 * _.inch])\n except:\n self.fail(\"unit / np array raised an error unexpectedly!\")\n\n # Test Absolute Value #\n #######################\n def test_absolute_value_leaves_positive_positive(self):\n self.assertEqual(abs(_.m), _.m)\n\n def test_absolute_value_makes_negatives_positive(self):\n self.assertEqual(abs(-_.m), _.m)\n\n # Test comparators #\n ####################\n def test_one_meter_is_larger_than_one_foot(self):\n self.assertTrue(_.m > _.ft)\n\n def test_kph_is_less_than_mph(self):\n self.assertTrue(_.kph < _.mph)\n\n def test_ltet(self):\n self.assertTrue(_.kmol <= _.kmol)\n self.assertTrue(_.mol <= _.kmol)\n\n def test_gtet(self):\n self.assertTrue(_.kPa >= _.kPa)\n self.assertTrue(_.kPa >= _.Pa)\n\n def test_math_log_2_units_is_log_2(self):\n self.assertEqual(math.log(2), math.log(2 * _.atm / _.atm))\n\n def test_np_log_2_units_is_log_2(self):\n self.assertEqual(np.log(2), np.log(2 * _.atm / _.atm))\n\n def test_math_exp_2_units_is_exp_2(self):\n self.assertEqual(math.log(2), math.log(2 * _.atm / _.atm))\n\n def test_np_exp_2_units_is_exp_2(self):\n self.assertEqual(np.exp(2), np.exp(2 * _.atm / _.atm))\n\n def test_np_log10_2_units_is_log10_2(self):\n self.assertEqual(np.log10(100), np.log10(100 * _.atm/_.atm))\n\n def test_np_cos_2_units_is_cos_2(self):\n self.assertEqual(np.cos(2), np.cos(2 * _.atm/_.atm))\n\n def test_np_sin_2_units_is_sin_2(self):\n self.assertEqual(np.sin(2), np.sin(2 * _.atm/_.atm))\n\n def test_inch_is_not_equal_to_ft(self):\n self.assertNotEqual(_.inch, _.ft)\n\n def test_inch_is_not_equal_to_s(self):\n self.assertNotEqual(_.inch, _.s)\n\n def test_inch_is_not_equal_to_4(self):\n self.assertNotEqual(_.inch, 4)\n\n # Test Smart Conversion #\n #########################\n def test_ft_times_yd_is_yd_squared(self):\n self.assert_display_with_units_of(_.ft * _.yd, _.yd**2.0)\n\n def test_ft_divided_by_yd_is_unitless_one_third(self):\n self.assertEqual(_.ft / _.yd, 1 / 3)\n\n def test_ft_times_acre_is_acre_to_the_one_and_a_half(self):\n self.assert_display_with_units_of(_.ft * _.acre, _.acre**1.5)\n\n def test_acre_times_ft_is_ft_cubed(self):\n self.assert_display_with_units_of(_.acre * _.ft, _.ft**3.0)\n\n def test_ft_times_gal_is_gal_to_the_four_thirds(self):\n self.assert_display_with_units_of(_.ft * _.gal, _.gal**(4 / 3))\n\n def test_gal_times_ft_is_ft_to_the_fourth(self):\n self.assert_display_with_units_of(_.gal * _.ft, _.ft**4.0)\n\n def test_acre_divided_by_ft_is_ft(self):\n self.assert_display_with_units_of(_.acre / _.ft, _.ft)\n\n def test_ft_divided_by_acre_is_inverse_ft(self):\n self.assert_display_with_units_of(_.ft / _.acre, 1 / _.ft)\n\n def test_gal_divided_by_ft_is_ft_squared(self):\n self.assert_display_with_units_of(_.gal / _.ft, _.ft**2.0)\n\n def test_cm_divided_by_gal_is_inverse_cm_squared(self):\n self.assert_display_with_units_of(_.cm / _.gal, 1 / _.cm**2.0)\n\n # Test Conversion #\n ###################\n def test_inch_equals_25_point_4_mm(self):\n self.assertEqual(_.inch, 25.4 * _.mm)\n\n def test_ft_equals_12_inches(self):\n self.assertEqual(_.ft, 12 * _.inch)\n\n def test_conversion_does_not_affect_value_kph_to_mph(self):\n self.assertEqual(_.kph(_.mph), _.kph)\n\n def test_conversion_does_not_affect_value_J_to_hp(self):\n self.assertEqual(_.J(_.hp), _.J)\n\n def test_conversion_does_not_affect_value_m_s_to_cm(self):\n self.assertEqual(12 / _.s * _.m(_.cm), 12 / _.s * _.m)\n\n def test_conversion_does_not_affect_value_kPa_to_hp(self):\n self.assertEqual(12 * _.kPa(_.hp), 12 * _.kPa)\n\n def test_conversion_does_not_affect_value_yr_to_hr(self):\n self.assertEqual(_.yr(_.hr), _.yr)\n\n def test_conversion_does_not_affect_value_custom_unit_to_m(self):\n b = _.UnitsGroup('b')\n self.assertEqual(12 * b(_.m), 12 * b)\n\n def test_converting_scalar_does_nothing(self):\n scalar = _.m / _.m\n self.assertEqual(scalar, scalar(_.inch))\n\n def test_specific_conversion(self):\n self.assertEqual(str((_.m / _.s)(_.km / _.minute)),\n '0.06 * km / minute')\n self.assertEqual(str((3 * _.m / _.m)(_.A)), '3.0')\n self.assertEqual(str((3 * _.ft / _.ft)(_.mmHg)), '3.0000000000000004')\n self.assertEqual(str((3 * _.ft / _.s)(_.cm)),\n '91.44000000000001 * cm / s')\n\n def test_strange_conversions_hz_to_yr(self):\n self.assertEqual(_.Hz(_.hr), _.Hz)\n\n def test_strange_conversions_kg_to_hr(self):\n self.assertEqual(_.kg(_.hr), _.kg)\n\n def test_strange_conversions_acre_to_cm(self):\n self.assertEqual(_.acre(_.cm), _.acre)\n\n def test_strange_conversions_gpm_to_square_inch(self):\n self.assertEqual((_.gal/_.mi)(_.inch**2), _.gal/_.mi)\n\n def test_strange_conversions_gpm_to_inch(self):\n self.assertEqual((_.gal/_.mi)(_.inch), _.gal/_.mi)\n\n def test_strange_conversions_inch_fur_to_ft_square_bad_parentheses(self):\n self.assertEqual(_.inch*_.fur(_.ft**2), _.inch*_.fur)\n\n def test_can_convert_to_units_of_other_measurement(self):\n a = 2 * _.ft\n b = 3 * _.m\n self.assertEqual(str(a(b)), '0.6096 * m')\n self.assertEqual(a, 2 * _.ft)\n self.assertEqual(b, 3 * _.m)\n\n # Test magnitude #\n #######################\n def test_magnitude(self):\n self.assertEqual((2 * _.yr).magnitude, 2)\n self.assertEqual((12 * _.ltyr).magnitude, 12)\n self.assertEqual((62 * _.F).magnitude, 62)\n\n # Test string conversions #\n ###########################\n def test_to_string(self):\n self.assertEqual(str(1 * _.m), '1.0 * m')\n self.assertEqual(str(_.m * _.s * _.kg), '1.0 * kg * m * s')\n self.assertEqual(str(_.m**-1), '1.0 / m')\n self.assertEqual(str(1 / (_.s * _.kg * _.m)), '1.0 / (kg * m * s)')\n self.assertEqual(str(_.m / _.s), '1.0 * m / s')\n self.assertEqual(str(_.m * _.A * _.K / (_.mol * _.s * _.kg)),\n '1.0 * A * K * m / (kg * mol * s)')\n self.assertEqual(str(_.m**-1 * _.kg**-2 / _.A**-1),\n '1.0 * A / (kg**2.0 * m)')\n\n def test_description_and_quantity_work(self):\n for unit in [_.m, _.ft, _.ltyr, _.lb, _.mmol, _.mas, _.yr, _.latm,\n _.Btu, _.dyn, _.tonf]:\n self.assertTrue(unit.description, 'no description: ' + str(unit))\n self.assertTrue(unit.quantity, 'no quantity: ' + str(unit))\n\n def test_single_unit_to_string(self):\n self.assertEqual(str(_.m), '1.0 * m # Meter [length]')\n self.assertEqual(str(_.nmi), '1.0 * nmi # Nautical Mile [length]')\n self.assertEqual(str(_.galUK),\n '1.0 * galUK # British gallon [volume]')\n self.assertEqual(str(_.yr), '1.0 * yr # Year [time]')\n\n def test_constant_to_string(self):\n self.assertIn('# Gas constant [', str(_.Rc))\n self.assertIn('# Speed of light [', str(_.c))\n self.assertIn('# Acceleration of gravity [', str(_.g))\n self.assertIn('# Gravitational constant', str(_.Gc))\n self.assertIn('# Planck\\'s constant [', str(_.h))\n self.assertIn('# Electron rest mass [', str(_.Me))\n self.assertIn('# Neutron rest mass [', str(_.Mn))\n self.assertIn('# Proton rest mass [', str(_.Mp))\n self.assertIn('# Avogadro constant', str(_.Na))\n self.assertIn('# Electron charge [', str(_.q))\n self.assertIn('# Coulomb\\'s constant', str(_.Cc))\n self.assertIn('# Reduced Planck\\'s constant [', str(_.hbar))\n self.assertIn('# Vacuum permeability [', str(_.u0))\n self.assertIn('# Vacuum permittivity [', str(_.e0))\n self.assertIn('# Boltzmann\\'s constant [', str(_.kb))\n self.assertIn('# Stefan-Boltzmann constant', str(_.sbc))\n self.assertIn('# Bohr magneton [', str(_.ub))\n self.assertIn('# Bohr radius [', str(_.Rb))\n self.assertIn('# Rydberg Constant [', str(_.Rdb))\n self.assertIn('# Magnetic flux quantum [', str(_.mfq))\n\n def test_quantity_applies_to_new_unit(self):\n hd = (4 * _.inch).rename('hd', 'hand')\n self.assertEqual(hd.quantity, _.inch.quantity)\n\n # Test custom units #\n #####################\n def test_custom_unit_equals_itself(self):\n self.assertEqual(_.UnitsGroup('b'), _.UnitsGroup('b'))\n\n def test_different_custom_units_are_not_equal(self):\n self.assertNotEqual(_.UnitsGroup('b'), _.UnitsGroup('bb'))\n\n # Test Copy #\n #############\n def copy_does_not_change_unit(self):\n a = _.m\n b = a.copy()\n self.assertEqual(a, b)\n\n # Test Join #\n #############\n def join_does_not_change_unit(self):\n a = _.m.copy()\n b = _.m.copy()\n a.join(_.ft / _.mol)\n self.assertEqual(a, b)\n\n # Test fsolve #\n ###############\n def test_solve_np_array_with_other_order(self):\n def other(x):\n return x + 2.0 * _.mm\n\n def solve(x):\n return [x.value for x in _.ft * x - _.m + other(_.ft * x)]\n try:\n fsolve(solve, 3)\n except:\n self.fail(\"fsolve with units failed unexpectedly!\")\n\n def test_solve_np_array_with_mixed_order_should_work(self):\n def other(x):\n return x + 2.0 * _.mm\n\n def solve(x):\n return [x.value for x in _.ft * x - _.m + other(x * _.ft)]\n try:\n fsolve(solve, 3)\n except:\n self.fail(\"fsolve with units failed unexpectedly!\")\n\n def test_my_fsolve(self):\n def other(x):\n return x + 2.0 * _.mm\n\n def solve(x):\n return x - _.m + other(x)\n try:\n _.units_fsolve(solve, 3 * _.ft)\n except:\n self.fail(\"fsolve with units failed unexpectedly!\")\n\n # Test unitless helper #\n #######################\n def test_unitless(self):\n def spring_force(x, k):\n return x * k\n\n with_units = spring_force(3 * _.mm, 2 * _.N/_.m)(_.lbf)\n unitless_spring_force = _.unitless(_.lbf,\n (_.mm, _.N/_.m))(spring_force)\n without_units = unitless_spring_force(3, 2)\n\n self.assertEqual(without_units, with_units.magnitude)\n\n def test_unitless_can_handle_strange_args_and_returns(self):\n def func(x, array):\n a = x * array[1]\n b = array[0] + array[1]\n c = (a * b).standardized()\n return ((b, c), a)\n\n with_units = func(3 * _.s, [2 * _.N/_.m, 3 * _.lbf/_.ft])\n unitless_func = _.unitless(((_.N/_.m, _.kg**2/_.s**3), _.lbf*_.s/_.ft),\n (_.s, (_.N/_.m, _.lbf/_.ft)))(func)\n without_units = unitless_func(3, (2, 3))\n\n self.assertEqual(without_units, _deep_map(lambda u: u.magnitude,\n with_units))\n\n def test_unitless_can_handle_numpy_arrays(self):\n def spring_force(x):\n k = 2 * _.N/_.m\n return x * k\n\n unitless_func = _.unitless(_.N, _.ft)(spring_force)\n try:\n unitless_func(np.linspace(1, 2, 4))\n except:\n self.fail(\"unitless with np array failed unexpectedly!\")\n\n # Test unitified helper #\n ##########################\n def test_with_units_helper(self):\n def emc_without_units(mass):\n return mass * 2.99792458**2 * 10\n\n without_units = emc_without_units(3)\n emc_with_units = _.unitified(_.MJ, _.ug)(emc_without_units)\n with_units = emc_with_units(3 * _.ug)\n\n self.assertEqual(round(without_units, 12),\n round(with_units.magnitude, 12))\n\n def test_with_units_requires_compatible_units(self):\n def emc_without_units(m):\n return m * 2.99792458**2 * 10\n\n emc_with_units = _.unitified(_.MJ, _.ug)(emc_without_units)\n self.assertRaises(ue.IncompatibleUnitsError, emc_with_units, 8 * _.s)\n\n def test_unitified_can_handle_numpy_arrays(self):\n def some_function(x):\n return 311 / x**2\n\n unitified_func = _.unitified(_.Pa, _.ft)(some_function)\n try:\n unitified_func(np.linspace(1, 2, 4) * _.ft)\n except:\n self.fail(\"unitified with np array failed unexpectedly!\")\n\n def test_unitified_can_handle_strange_args_and_returns(self):\n def func(length, time_and_energy):\n time, energy = time_and_energy\n speed = length / time\n power = energy / time\n energy_density = energy / length**3\n return [[power, energy_density], speed]\n\n without_units = func(2, (4, 3))\n func_with_units = _.unitified(((_.W, _.J/_.m**3), _.m/_.s),\n (_.m, (_.s, _.J)))(func)\n with_units = func_with_units(2 * _.m, (4 * _.s, 3 * _.J))\n self.assertEqual(without_units, _deep_map(lambda u: u.magnitude,\n with_units))\n\n # Test inplace methods #\n ########################\n def test_inplace_mul(self):\n a = _.cm.copy()\n a._inplace_mul(2)\n self.assertEqual(str(a), '2.0 * cm')\n a._inplace_mul(_.m)\n self.assertEqual(str(a), '0.02 * m**2.0')\n\n def test_inplace_join(self):\n a = _.cm.copy()\n a._inplace_join(_.s)\n self.assertEqual(str(a), '1.0 * cm * s')\n\n def test_inplace_standardized(self):\n a = _.Btu.copy()\n a._inplace_standardized()\n self.assertEqual(str(a), '1055.05585262 * kg * m**2.0 / s**2.0')\n\n def test_inplace_normalized(self):\n a = 212 * _.Btu\n a._inplace_normalized()\n self.assertEqual(str(a), '1.0 * Btu')\n\n def test_inplace_units_of(self):\n a = 212 * _.Btu\n a._inplace_units_of(_.kJ)\n self.assertEqual(str(a), '223.67184075543997 * kJ')\n"
] |
[
[
"numpy.log",
"scipy.optimize.fsolve",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"numpy.all",
"numpy.log10",
"numpy.array",
"numpy.exp"
]
] |
a7b23/CS236G-project
|
[
"8bde7d54ca3d22e13703fe72dfb998b38d9cd8b4"
] |
[
"BigBiGAN-TensorFlow2.0/data_all.py"
] |
[
"import tensorflow as tf\n\nimport tensorflow_datasets as tfds\nfrom data_util import preprocess_image\n\nNUM_CALLS = tf.data.experimental.AUTOTUNE\nNUM_PREFETCH = tf.data.experimental.AUTOTUNE\n\nmnist = tf.keras.datasets.mnist\n(mnist_images, mnist_labels), _ = mnist.load_data()\n\n\ndef map_fn(image, label):\n # Sample one mnist image.\n i = tf.random.uniform([], maxval=len(mnist_images), dtype=tf.int32)\n digit = tf.squeeze(tf.slice(mnist_images, [i, 0, 0], [1, 28, 28]))\n digit_label = tf.squeeze(tf.slice(mnist_labels, [i], [1]))\n digit = tf.image.grayscale_to_rgb(tf.expand_dims(digit, -1))\n digit = tf.image.convert_image_dtype(digit, dtype=tf.float32)\n digit = tf.image.resize(digit, [8, 8])\n image = tf.image.resize(image, [32, 32]) / 255.\n\n size_big, size_small = 32, 8\n images = []\n for pad_x, pad_y in [(2, 2), (2, 22), (12, 12), (22, 2), (22, 22)]:\n x_max, y_max = size_big - size_small, size_big - size_small\n d = tf.pad(digit,\n [[pad_x, x_max - pad_x],\n [pad_y, y_max - pad_y],\n [0, 0]])\n images.append(d)\n images.append(image)\n\n image = tf.reduce_max(tf.stack(images, 0), 0)\n return image, (label, digit_label)\n\n\ndef scale(image, label):\n image = tf.cast(image, tf.float32)\n image = image / 255.0\n image = tf.image.resize(image, [32, 32])\n image_aug = preprocess_image(image, 32, 32, is_training=True)\n image = tf.concat([image, image_aug], axis=-1)\n \n return image, label\n\n\ndef get_dataset(config):\n if config.dataset != 'cifar_mnist':\n datasets, ds_info = tfds.load(name=config.dataset, with_info=True, as_supervised=True, data_dir=config.dataset_path)\n else:\n datasets, ds_info = tfds.load(name='cifar10', with_info=True, as_supervised=True,\n data_dir=config.dataset_path)\n for k in list(datasets.keys()):\n datasets[k] = datasets[k].map(map_fn)\n train_data, test_data = datasets['train'], datasets['test']\n return train_data, test_data\n\n\ndef get_train_pipeline(dataset, config):\n if config.dataset != 'cifar_mnist':\n dataset = dataset.map(scale, num_parallel_calls=NUM_CALLS)\n if (config.cache_dataset):\n dataset = dataset.cache()\n dataset = dataset.shuffle(config.data_buffer_size).batch(config.train_batch_size, drop_remainder=True).prefetch(\n NUM_PREFETCH)\n return dataset\n"
] |
[
[
"tensorflow.concat",
"tensorflow.slice",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.image.resize",
"tensorflow.image.convert_image_dtype",
"tensorflow.pad"
]
] |
mriedem/qiskit-ibm
|
[
"be7056e9f59098cb3097d9bdcf6e9f2bbc006455"
] |
[
"test/ibm/experiment/test_experiment_server_integration.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Experiment integration test with server.\"\"\"\n\nimport os\nimport uuid\nfrom unittest import mock, SkipTest, skipIf\nfrom datetime import datetime, timedelta\nfrom typing import Optional, Dict, Any\nimport re\nfrom dateutil import tz\nimport numpy as np\n\nfrom qiskit_ibm.experiment.constants import ExperimentShareLevel\nfrom qiskit_ibm.exceptions import IBMNotAuthorizedError\nfrom qiskit_ibm.experiment import ResultQuality, IBMExperimentEntryNotFound\n\nfrom ...ibm_test_case import IBMTestCase\nfrom ...decorators import requires_provider, requires_device\nfrom .utils import ExperimentEncoder, ExperimentDecoder\n\n\n@skipIf(not os.environ.get('QISKIT_IBM_USE_STAGING_CREDENTIALS', ''), \"Only runs on staging\")\nclass TestExperimentServerIntegration(IBMTestCase):\n \"\"\"Test experiment modules.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Initial class level setup.\"\"\"\n # pylint: disable=arguments-differ\n super().setUpClass()\n cls.provider = cls._setup_provider() # pylint: disable=no-value-for-parameter\n cls.backend = cls._setup_backend() # pylint: disable=no-value-for-parameter\n try:\n cls.device_components = cls.provider.experiment.device_components(cls.backend.name())\n except Exception:\n raise SkipTest(\"Not authorized to use experiment service.\")\n\n @classmethod\n @requires_provider\n def _setup_provider(cls, provider):\n \"\"\"Get the provider for the class.\"\"\"\n return provider\n\n @classmethod\n @requires_device\n def _setup_backend(cls, backend):\n \"\"\"Get a backend for the class.\"\"\"\n return backend\n\n def setUp(self) -> None:\n \"\"\"Test level setup.\"\"\"\n super().setUp()\n self.experiments_to_delete = []\n\n def tearDown(self):\n \"\"\"Test level tear down.\"\"\"\n for expr_uuid in self.experiments_to_delete:\n try:\n with mock.patch('builtins.input', lambda _: 'y'):\n self.provider.experiment.delete_experiment(expr_uuid)\n except Exception as err: # pylint: disable=broad-except\n self.log.info(\"Unable to delete experiment %s: %s\", expr_uuid, err)\n super().tearDown()\n\n def test_unauthorized(self):\n \"\"\"Test unauthorized access.\"\"\"\n saved_experiment = self.provider._experiment\n try:\n self.provider._experiment = None\n with self.assertRaises(IBMNotAuthorizedError) as context_manager:\n self.provider.experiment.experiments()\n self.assertIn(\"experiment service\", str(context_manager.exception))\n finally:\n self.provider._experiment = saved_experiment\n\n def test_experiments(self):\n \"\"\"Test retrieving experiments.\"\"\"\n exp_id = self._create_experiment()\n experiments = self.provider.experiment.experiments()\n self.assertTrue(experiments, \"No experiments found.\")\n\n found = False\n for exp in experiments:\n self.assertTrue(exp[\"experiment_id\"], \"{} does not have an ID!\".format(exp))\n for dt_attr in ['start_datetime', 'creation_datetime',\n 'end_datetime', 'updated_datetime']:\n if getattr(exp, dt_attr, None):\n self.assertTrue(getattr(exp, dt_attr).tzinfo)\n if exp[\"experiment_id\"] == exp_id:\n found = True\n self.assertTrue(found, f\"Experiment {exp_id} not found!\")\n\n def test_experiments_with_backend(self):\n \"\"\"Test retrieving all experiments for a specific backend.\"\"\"\n exp_id = self._create_experiment()\n backend_experiments = self.provider.experiment.experiments(\n backend_name=self.backend.name())\n\n found = False\n for exp in backend_experiments:\n self.assertEqual(self.backend.name(), exp[\"backend\"].name())\n if exp[\"experiment_id\"] == exp_id:\n found = True\n self.assertTrue(found, \"Experiment {} not found when filter by backend name {}.\".format(\n exp_id, self.backend.name()))\n\n def test_experiments_with_type(self):\n \"\"\"Test retrieving all experiments for a specific type.\"\"\"\n exp_type = 'qiskit_test'\n exp_id = self._create_experiment(experiment_type=exp_type)\n backend_experiments = self.provider.experiment.experiments(\n experiment_type=exp_type)\n\n found = False\n for exp in backend_experiments:\n self.assertEqual(exp_type, exp[\"experiment_type\"])\n if exp[\"experiment_id\"] == exp_id:\n found = True\n self.assertTrue(found, \"Experiment {} not found when filter by type {}.\".format(\n exp_id, exp_type))\n\n def test_experiments_with_parent_id(self):\n \"\"\"Test retrieving all experiments for a specific parent id.\"\"\"\n parent_id = self._create_experiment()\n child_id = self._create_experiment(parent_id=parent_id)\n experiments = self.provider.experiment.experiments(\n parent_id=parent_id)\n\n found = False\n for exp in experiments:\n self.assertEqual(parent_id, exp[\"parent_id\"])\n if exp[\"experiment_id\"] == child_id:\n found = True\n self.assertTrue(found, \"Experiment {} not found when filter by type {}.\".format(\n child_id, parent_id))\n\n def test_experiments_with_type_operator(self):\n \"\"\"Test retrieving all experiments for a specific type with operator.\"\"\"\n exp_type = 'qiskit_test'\n exp_id = self._create_experiment(experiment_type=exp_type)\n\n experiments = self.provider.experiment.experiments(\n experiment_type=\"foo\", experiment_type_operator=\"like\")\n self.assertNotIn(exp_id, [exp[\"experiment_id\"] for exp in experiments])\n\n subtests = [\"qiskit\", \"test\"]\n for filter_type in subtests:\n with self.subTest(filter_type=filter_type):\n experiments = self.provider.experiment.experiments(\n experiment_type=exp_type, experiment_type_operator=\"like\")\n found = False\n for exp in experiments:\n self.assertTrue(re.match(f\".*{filter_type}.*\", exp[\"experiment_type\"]))\n if exp[\"experiment_id\"] == exp_id:\n found = True\n self.assertTrue(found, f\"Experiment {exp_id} not found \"\n f\"when filter by type {filter_type}\")\n\n def test_experiments_with_bad_type_operator(self):\n \"\"\"Test retrieving all experiments with a bad type operator.\"\"\"\n with self.assertRaises(ValueError):\n self.provider.experiment.experiments(\n experiment_type=\"foo\", experiment_type_operator=\"bad\")\n\n def test_experiments_with_start_time(self):\n \"\"\"Test retrieving an experiment by its start_time.\"\"\"\n ref_start_dt = datetime.now() - timedelta(days=1)\n ref_start_dt = ref_start_dt.replace(tzinfo=tz.tzlocal())\n exp_id = self._create_experiment(start_datetime=ref_start_dt)\n\n before_start = ref_start_dt - timedelta(hours=1)\n after_start = ref_start_dt + timedelta(hours=1)\n sub_tests = [(before_start, None, True, \"before start, None\"),\n (None, after_start, True, \"None, after start\"),\n (before_start, after_start, True, \"before, after start\"),\n (after_start, None, False, \"after start, None\"),\n (None, before_start, False, \"None, before start\"),\n (before_start, before_start, False, \"before, before start\")\n ]\n\n for start_dt, end_dt, expected, title in sub_tests:\n with self.subTest(title=title):\n backend_experiments = self.provider.experiment.experiments(\n start_datetime_after=start_dt, start_datetime_before=end_dt,\n experiment_type='qiskit_test')\n found = False\n for exp in backend_experiments:\n if start_dt:\n self.assertGreaterEqual(exp[\"start_datetime\"], start_dt)\n if end_dt:\n self.assertLessEqual(exp[\"start_datetime\"], end_dt)\n if exp[\"experiment_id\"] == exp_id:\n found = True\n self.assertEqual(found, expected,\n \"Experiment {} (not)found unexpectedly when filter using\"\n \"start_dt={}, end_dt={}. Found={}\".format(\n exp_id, start_dt, end_dt, found))\n\n def test_experiments_with_tags(self):\n \"\"\"Test filtering experiments using tags.\"\"\"\n ref_tags = [\"qiskit_test\", \"foo\"]\n exp_id = self._create_experiment(tags=ref_tags)\n\n phantom_tag = uuid.uuid4().hex\n sub_tests = [\n (ref_tags, 'AND', True),\n (ref_tags, 'OR', True),\n (ref_tags[:1], \"OR\", True),\n (ref_tags + [phantom_tag], \"AND\", False),\n (ref_tags + [phantom_tag], \"OR\", True),\n ([phantom_tag], \"OR\", False)\n ]\n for tags, operator, found in sub_tests:\n with self.subTest(tags=tags, operator=operator):\n experiments = self.provider.experiment.experiments(\n tags=tags, tags_operator=operator)\n ref_expr_found = False\n for expr in experiments:\n msg = \"Tags {} not fond in experiment tags {}\".format(tags, expr[\"tags\"])\n if operator == 'AND':\n self.assertTrue(all(f_tag in expr[\"tags\"] for f_tag in tags), msg)\n else:\n self.assertTrue(any(f_tag in expr[\"tags\"] for f_tag in tags), msg)\n if expr[\"experiment_id\"] == exp_id:\n ref_expr_found = True\n self.assertTrue(ref_expr_found == found,\n \"Experiment tags {} unexpectedly (not)found. Found={}\".format(\n ref_tags, found))\n\n def test_experiments_with_hgp(self):\n \"\"\"Test retrieving all experiments for a specific h/g/p.\"\"\"\n exp_id = self._create_experiment()\n credentials = self.provider.credentials\n hgp = [credentials.hub, credentials.group, credentials.project]\n sub_tests = [\n {'hub': hgp[0]},\n {'hub': hgp[0], 'group': hgp[1]},\n {'hub': hgp[0], 'group': hgp[1], 'project': hgp[2]}\n ]\n\n for hgp_kwargs in sub_tests:\n with self.subTest(kwargs=hgp_kwargs.keys()):\n hgp_experiments = self.provider.experiment.experiments(**hgp_kwargs)\n ref_expr_found = False\n for expr in hgp_experiments:\n for hgp_key, hgp_val in hgp_kwargs.items():\n self.assertEqual(expr[hgp_key], hgp_val)\n if expr[\"experiment_id\"] == exp_id:\n ref_expr_found = True\n self.assertTrue(ref_expr_found)\n\n def test_experiments_with_hgp_error(self):\n \"\"\"Test retrieving experiments with bad h/g/p specification.\"\"\"\n sub_tests = [\n ({'project': 'test_project'}, ['hub', 'group']),\n ({'project': 'test_project', 'group': 'test_group'}, ['hub']),\n ({'project': 'test_project', 'hub': 'test_hub'}, ['group']),\n ({'group': 'test_group'}, ['hub'])\n ]\n\n for hgp_kwargs, missing_keys in sub_tests:\n with self.subTest(kwargs=hgp_kwargs.keys()):\n with self.assertRaises(ValueError) as ex_cm:\n self.provider.experiment.experiments(**hgp_kwargs)\n for key in missing_keys:\n self.assertIn(key, str(ex_cm.exception))\n\n def test_experiments_with_exclude_public(self):\n \"\"\"Tests retrieving experiments with exclude_public filter.\"\"\"\n # Make sure that we have at least one public experiment and one non-public\n # experiment.\n public_exp_id = self._create_experiment(share_level=ExperimentShareLevel.PUBLIC)\n private_exp_id = self._create_experiment(share_level=ExperimentShareLevel.PRIVATE)\n\n experiments = self.provider.experiment.experiments(exclude_public=True)\n # The public experiment we just created should not be in the set.\n non_public_experiment_uuids = []\n for experiment in experiments:\n self.assertNotEqual(\n experiment[\"share_level\"], ExperimentShareLevel.PUBLIC.value,\n 'Public experiment should not be returned with exclude_public filter: %s' %\n experiment)\n non_public_experiment_uuids.append(experiment[\"experiment_id\"])\n self.assertIn(\n private_exp_id, non_public_experiment_uuids,\n 'Non-public experiment not returned with exclude_public filter: %s' %\n private_exp_id)\n self.assertNotIn(\n public_exp_id, non_public_experiment_uuids,\n 'Public experiment returned with exclude_public filter: %s' %\n public_exp_id)\n\n def test_experiments_with_public_only(self):\n \"\"\"Tests retrieving experiments with public_only filter.\"\"\"\n # Make sure that we have at least one public experiment and one non-public\n # experiment.\n public_exp_id = self._create_experiment(share_level=ExperimentShareLevel.PUBLIC)\n private_exp_id = self._create_experiment(share_level=ExperimentShareLevel.PRIVATE)\n\n experiments = self.provider.experiment.experiments(public_only=True)\n public_experiment_uuids = []\n for experiment in experiments:\n self.assertEqual(\n experiment[\"share_level\"], ExperimentShareLevel.PUBLIC.value,\n 'Only public experiments should be returned with public_only filter: %s' %\n experiment)\n public_experiment_uuids.append(experiment[\"experiment_id\"])\n self.assertIn(\n public_exp_id, public_experiment_uuids,\n 'Public experiment not returned with public_only filter: %s' %\n public_exp_id)\n self.assertNotIn(\n private_exp_id, public_experiment_uuids,\n 'Non-public experiment returned with public_only filter: %s' %\n private_exp_id)\n\n def test_experiments_with_public_filters_error(self):\n \"\"\"Tests that exclude_public and public_only cannot both be True.\"\"\"\n with self.assertRaisesRegex(\n ValueError,\n 'exclude_public and public_only cannot both be True'):\n self.provider.experiment.experiments(exclude_public=True, public_only=True)\n\n def test_experiments_with_exclude_mine(self):\n \"\"\"Tests retrieving experiments with exclude_mine filter.\"\"\"\n # Note that we cannot specify the owner when creating the experiment, the value comes\n # from the user profile via the token so we would have to use different test accounts\n # to explicitly create separately-owned experiments. We should be able to assume that\n # there is at least one experiment owned by another user in the integration test\n # environment though.\n exp_id = self._create_experiment()\n exp_owner = self.provider.experiment.experiment(exp_id)[\"owner\"]\n\n not_my_experiments = self.provider.experiment.experiments(exclude_mine=True)\n # The experiment we just created should not be in the set.\n not_mine_experiment_uuids = []\n for experiment in not_my_experiments:\n self.assertNotEqual(\n experiment[\"owner\"], exp_owner, # pylint: disable=no-member\n 'My experiment should not be returned with exclude_mine filter: %s' %\n experiment[\"experiment_id\"])\n not_mine_experiment_uuids.append(experiment[\"experiment_id\"])\n self.assertNotIn(\n exp_id, not_mine_experiment_uuids,\n 'My experiment returned with exclude_mine filter: %s' %\n exp_id)\n\n def test_experiments_with_mine_only(self):\n \"\"\"Tests retrieving experiments with mine_only filter.\"\"\"\n # Note that we cannot specify the owner when creating the experiment, the value comes\n # from the user profile via the token so we would have to use different test accounts\n # to explicitly create separately-owned epxeriments. We should be able to assume that\n # there is at least one experiment owned by another user in the integration test\n # environment though.\n exp_id = self._create_experiment()\n exp_owner = self.provider.experiment.experiment(exp_id)[\"owner\"]\n my_experiments = self.provider.experiment.experiments(mine_only=True)\n my_experiment_uuids = []\n for experiment in my_experiments:\n self.assertEqual(\n experiment[\"owner\"], exp_owner, # pylint: disable=no-member\n 'Only my experiments should be returned with mine_only filter: %s' %\n experiment[\"experiment_id\"])\n my_experiment_uuids.append(experiment[\"experiment_id\"])\n self.assertIn(\n exp_id, my_experiment_uuids,\n 'My experiment not returned with mine_only filter: %s' %\n exp_id)\n\n def test_experiments_with_owner_filters_error(self):\n \"\"\"Tests that exclude_mine and mine_only cannot both be True.\"\"\"\n with self.assertRaisesRegex(\n ValueError,\n 'exclude_mine and mine_only cannot both be True'):\n self.provider.experiment.experiments(exclude_mine=True, mine_only=True)\n\n def test_experiments_with_limit(self):\n \"\"\"Test retrieving experiments with limit.\"\"\"\n self._create_experiment()\n experiments = self.provider.experiment.experiments(limit=1)\n self.assertEqual(1, len(experiments))\n\n def test_experiments_with_no_limit(self):\n \"\"\"Test retrieving experiments with no limit.\"\"\"\n tags = [str(uuid.uuid4())]\n exp_id = self._create_experiment(tags=tags)\n experiments = self.provider.experiment.experiments(limit=None, tags=tags)\n self.assertEqual(1, len(experiments))\n self.assertEqual(exp_id, experiments[0][\"experiment_id\"])\n\n def test_experiments_with_sort_by(self):\n \"\"\"Test retrieving experiments with sort_by.\"\"\"\n tags = [str(uuid.uuid4())]\n exp1 = self._create_experiment(tags=tags,\n experiment_type=\"qiskit_test1\",\n start_datetime=datetime.now()-timedelta(hours=1))\n exp2 = self._create_experiment(tags=tags,\n experiment_type=\"qiskit_test2\",\n start_datetime=datetime.now())\n exp3 = self._create_experiment(tags=tags,\n experiment_type=\"qiskit_test1\",\n start_datetime=datetime.now()-timedelta(hours=2))\n\n subtests = [\n ([\"experiment_type:asc\"], [exp1, exp3, exp2]),\n ([\"experiment_type:desc\"], [exp2, exp1, exp3]),\n ([\"start_datetime:asc\"], [exp3, exp1, exp2]),\n ([\"start_datetime:desc\"], [exp2, exp1, exp3]),\n ([\"experiment_type:asc\", \"start_datetime:asc\"], [exp3, exp1, exp2]),\n ([\"experiment_type:asc\", \"start_datetime:desc\"], [exp1, exp3, exp2]),\n ([\"experiment_type:desc\", \"start_datetime:asc\"], [exp2, exp3, exp1]),\n ([\"experiment_type:desc\", \"start_datetime:desc\"], [exp2, exp1, exp3]),\n ]\n\n for sort_by, expected in subtests:\n with self.subTest(sort_by=sort_by):\n experiments = self.provider.experiment.experiments(tags=tags, sort_by=sort_by)\n self.assertEqual(expected, [exp[\"experiment_id\"] for exp in experiments])\n\n def test_experiments_with_bad_sort_by(self):\n \"\"\"Test retrieving experiments with bad sort_by.\"\"\"\n subtests = [\"experiment_id:asc\", \"experiment_type\", \"experiment_type:foo\", \"foo:bar\"]\n\n for sort_by in subtests:\n with self.subTest(sort_by=sort_by):\n with self.assertRaises(ValueError):\n self.provider.experiment.experiments(sort_by=sort_by)\n\n def test_experiments_with_device_components(self):\n \"\"\"Test filtering experiments with device components.\"\"\"\n expr_id = self._create_experiment()\n self._create_analysis_result(exp_id=expr_id,\n device_components=self.device_components)\n experiments = self.provider.experiment.experiments(\n device_components=self.device_components)\n self.assertIn(expr_id, [expr[\"experiment_id\"] for expr in experiments],\n f\"Experiment {expr_id} not found when filtering with \"\n f\"device components {self.device_components}\")\n\n def test_experiments_with_device_components_operator(self):\n \"\"\"Test filtering experiments with device components operator.\"\"\"\n backend_name, device_components = self._find_backend_device_components(3)\n if not backend_name:\n self.skipTest(\"Need at least 3 device components.\")\n\n expr_id = self._create_experiment(backend_name=backend_name)\n self._create_analysis_result(exp_id=expr_id,\n device_components=device_components)\n experiments = self.provider.experiment.experiments(\n device_components=device_components[:2],\n device_components_operator=\"contains\")\n\n self.assertIn(expr_id, [expr[\"experiment_id\"] for expr in experiments],\n f\"Experiment {expr_id} not found when filtering with \"\n f\"device components {device_components[:2]}\")\n\n def test_experiments_with_bad_components_operator(self):\n \"\"\"Test filtering experiments with bad device components operator.\"\"\"\n with self.assertRaises(ValueError):\n self.provider.experiment.experiments(\n device_components=[\"Q1\"],\n device_components_operator=\"foo\")\n\n def test_retrieve_experiment(self):\n \"\"\"Test retrieving an experiment by its ID.\"\"\"\n exp_id = self._create_experiment()\n rexp = self.provider.experiment.experiment(exp_id)\n self.assertEqual(exp_id, rexp[\"experiment_id\"])\n for attr in ['hub', 'group', 'project', 'owner', 'share_level']:\n self.assertIsNotNone(rexp[attr], \"{} does not have a {}\".format(rexp, attr))\n\n def test_upload_experiment(self):\n \"\"\"Test uploading an experiment.\"\"\"\n exp_id = str(uuid.uuid4())\n new_exp_id = self.provider.experiment.create_experiment(\n experiment_type=\"qiskit_test\",\n backend_name=self.backend.name(),\n metadata={\"foo\": \"bar\"},\n experiment_id=exp_id,\n job_ids=[\"job1\", \"job2\"],\n tags=[\"qiskit_test\"],\n notes=\"some notes\",\n share_level=ExperimentShareLevel.PROJECT,\n start_datetime=datetime.now()\n )\n self.experiments_to_delete.append(new_exp_id)\n self.assertEqual(exp_id, new_exp_id)\n new_exp = self.provider.experiment.experiment(new_exp_id)\n\n credentials = self.provider.credentials\n self.assertEqual(credentials.hub, new_exp[\"hub\"]) # pylint: disable=no-member\n self.assertEqual(credentials.group, new_exp[\"group\"]) # pylint: disable=no-member\n self.assertEqual(credentials.project, new_exp[\"project\"]) # pylint: disable=no-member\n self.assertEqual(\"qiskit_test\", new_exp[\"experiment_type\"])\n self.assertEqual(self.backend.name(), new_exp[\"backend\"].name())\n self.assertEqual({\"foo\": \"bar\"}, new_exp[\"metadata\"])\n self.assertEqual([\"job1\", \"job2\"], new_exp[\"job_ids\"])\n self.assertEqual([\"qiskit_test\"], new_exp[\"tags\"])\n self.assertEqual(\"some notes\", new_exp[\"notes\"])\n self.assertEqual(ExperimentShareLevel.PROJECT.value, new_exp[\"share_level\"])\n self.assertTrue(new_exp[\"creation_datetime\"])\n self.assertIsNotNone(new_exp[\"owner\"], 'Owner should be set') # pylint: disable=no-member\n\n for dt_attr in ['start_datetime', 'creation_datetime', 'end_datetime', 'updated_datetime']:\n if dt_attr in new_exp:\n self.assertTrue(new_exp[dt_attr].tzinfo)\n\n def test_update_experiment(self):\n \"\"\"Test updating an experiment.\"\"\"\n new_exp_id = self._create_experiment()\n\n self.provider.experiment.update_experiment(\n experiment_id=new_exp_id,\n metadata={\"foo\": \"bar\"},\n job_ids=[\"job1\", \"job2\"],\n tags=[\"qiskit_test\"],\n notes=\"some notes\",\n share_level=ExperimentShareLevel.PROJECT,\n end_datetime=datetime.now()\n )\n\n rexp = self.provider.experiment.experiment(new_exp_id)\n self.assertEqual({\"foo\": \"bar\"}, rexp[\"metadata\"])\n self.assertEqual([\"job1\", \"job2\"], rexp[\"job_ids\"])\n self.assertEqual([\"qiskit_test\"], rexp[\"tags\"])\n self.assertEqual(\"some notes\", rexp[\"notes\"])\n self.assertEqual(ExperimentShareLevel.PROJECT.value, rexp[\"share_level\"])\n self.assertTrue(rexp[\"end_datetime\"])\n\n def test_delete_experiment(self):\n \"\"\"Test deleting an experiment.\"\"\"\n new_exp_id = self._create_experiment(notes='delete me')\n\n with mock.patch('builtins.input', lambda _: 'y'):\n self.provider.experiment.delete_experiment(new_exp_id)\n\n with self.assertRaises(IBMExperimentEntryNotFound) as ex_cm:\n self.provider.experiment.experiment(new_exp_id)\n self.assertIn(\"Not Found for url\", ex_cm.exception.message)\n\n def test_upload_analysis_result(self):\n \"\"\"Test uploading an analysis result.\"\"\"\n exp_id = self._create_experiment()\n fit = dict(value=41.456, variance=4.051)\n result_id = str(uuid.uuid4())\n chisq = 1.3253\n aresult_id = self.provider.experiment.create_analysis_result(\n experiment_id=exp_id,\n result_type=\"qiskit_test\",\n result_data=fit,\n device_components=self.device_components,\n tags=[\"qiskit_test\"],\n quality=ResultQuality.GOOD,\n verified=True,\n result_id=result_id,\n chisq=chisq\n )\n\n rresult = self.provider.experiment.analysis_result(aresult_id)\n self.assertEqual(exp_id, rresult[\"experiment_id\"])\n self.assertEqual(\"qiskit_test\", rresult[\"result_type\"])\n self.assertEqual(fit, rresult[\"result_data\"])\n self.assertEqual(self.device_components,\n [str(comp) for comp in rresult[\"device_components\"]])\n self.assertEqual([\"qiskit_test\"], rresult[\"tags\"])\n self.assertEqual(ResultQuality.GOOD, rresult[\"quality\"])\n self.assertTrue(rresult[\"verified\"])\n self.assertEqual(result_id, rresult[\"result_id\"])\n self.assertEqual(chisq, rresult[\"chisq\"])\n\n def test_update_analysis_result(self):\n \"\"\"Test updating an analysis result.\"\"\"\n result_id = self._create_analysis_result()\n fit = dict(value=41.456, variance=4.051)\n chisq = 1.3253\n\n self.provider.experiment.update_analysis_result(\n result_id=result_id,\n result_data=fit,\n tags=[\"qiskit_test\"],\n quality=ResultQuality.GOOD,\n verified=True,\n chisq=chisq\n )\n\n rresult = self.provider.experiment.analysis_result(result_id)\n self.assertEqual(result_id, rresult[\"result_id\"])\n self.assertEqual(fit, rresult[\"result_data\"])\n self.assertEqual([\"qiskit_test\"], rresult[\"tags\"])\n self.assertEqual(ResultQuality.GOOD, rresult[\"quality\"])\n self.assertTrue(rresult[\"verified\"])\n self.assertEqual(chisq, rresult[\"chisq\"])\n\n def test_analysis_results(self):\n \"\"\"Test retrieving all analysis results.\"\"\"\n result_id = self._create_analysis_result()\n results = self.provider.experiment.analysis_results()\n found = False\n for res in results:\n self.assertIsInstance(res[\"verified\"], bool)\n self.assertIsInstance(res[\"result_data\"], dict)\n self.assertTrue(res[\"result_id\"], \"{} does not have an uuid!\".format(res))\n for dt_attr in ['creation_datetime', 'updated_datetime']:\n if dt_attr in res:\n self.assertTrue(res[dt_attr].tzinfo)\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found)\n\n def test_analysis_results_device_components(self):\n \"\"\"Test filtering analysis results with device components.\"\"\"\n result_id = self._create_analysis_result(device_components=self.device_components)\n results = self.provider.experiment.analysis_results(\n device_components=self.device_components)\n\n found = False\n for res in results:\n self.assertEqual(self.device_components,\n [str(comp) for comp in res[\"device_components\"]])\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found, f\"Result {result_id} not found when filtering by \"\n f\"device components {self.device_components}\")\n\n def test_analysis_results_device_components_operator(self):\n \"\"\"Test filtering analysis results with device components operator.\"\"\"\n backend_name, device_components = self._find_backend_device_components(3)\n if not backend_name:\n self.skipTest(\"Need at least 3 device components.\")\n\n expr_id = self._create_experiment(backend_name=backend_name)\n result_id = self._create_analysis_result(exp_id=expr_id,\n device_components=device_components)\n results = self.provider.experiment.analysis_results(\n device_components=device_components[:2], device_components_operator=\"contains\")\n\n found = False\n for res in results:\n self.assertTrue(set(device_components[:2]) <=\n {str(comp) for comp in res[\"device_components\"]})\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found, f\"Result {result_id} not found when filtering by \"\n f\"device components {device_components[:2]}\")\n\n def test_analysis_results_experiment_id(self):\n \"\"\"Test filtering analysis results with experiment id.\"\"\"\n expr_id = self._create_experiment()\n result_id1 = self._create_analysis_result(exp_id=expr_id)\n result_id2 = self._create_analysis_result(exp_id=expr_id)\n\n results = self.provider.experiment.analysis_results(experiment_id=expr_id)\n self.assertEqual(2, len(results))\n self.assertEqual({result_id1, result_id2}, {res[\"result_id\"] for res in results})\n\n def test_analysis_results_type(self):\n \"\"\"Test filtering analysis results with type.\"\"\"\n result_type = \"qiskit_test\"\n result_id = self._create_analysis_result(result_type=result_type)\n results = self.provider.experiment.analysis_results(result_type=result_type)\n found = False\n for res in results:\n self.assertEqual(result_type, res[\"result_type\"])\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found, f\"Result {result_id} not returned when filtering by \"\n f\"type {result_type}\")\n\n def test_analysis_results_type_operator(self):\n \"\"\"Test filtering analysis results with type operator.\"\"\"\n result_type = \"qiskit_test_1234\"\n result_id = self._create_analysis_result(result_type=result_type)\n\n results = self.provider.experiment.analysis_results(\n result_type=\"foo\", result_type_operator=\"like\")\n self.assertNotIn(result_id, [res[\"result_id\"] for res in results])\n\n subtests = [\"qiskit_test\", \"test_1234\"]\n for filter_type in subtests:\n with self.subTest(filter_type=filter_type):\n results = self.provider.experiment.analysis_results(\n result_type=filter_type,\n result_type_operator=\"like\")\n\n found = False\n for res in results:\n self.assertIn(filter_type, res[\"result_type\"])\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found, f\"Result {result_id} not returned when filtering by \"\n f\"type substring {filter_type}\")\n\n def test_analysis_results_bad_type_operator(self):\n \"\"\"Test retrieving all experiments with a bad type operator.\"\"\"\n with self.assertRaises(ValueError):\n self.provider.experiment.analysis_results(\n result_type=\"foo\", result_type_operator=\"bad\")\n\n def test_analysis_results_quality(self):\n \"\"\"Test filtering analysis results with quality.\"\"\"\n expr_id = self._create_experiment()\n result_id1 = self._create_analysis_result(exp_id=expr_id, quality=ResultQuality.GOOD)\n result_id2 = self._create_analysis_result(exp_id=expr_id, quality=ResultQuality.BAD)\n result_id3 = self._create_analysis_result(exp_id=expr_id, quality=ResultQuality.UNKNOWN)\n\n subtests = [(ResultQuality.GOOD, {result_id1}),\n (ResultQuality.BAD.value, {result_id2}),\n (\"unknown\", {result_id3}),\n ([ResultQuality.UNKNOWN], {result_id3}),\n ([ResultQuality.GOOD, ResultQuality.UNKNOWN], {result_id1, result_id3}),\n ([\"Good\", \"Bad\"], {result_id1, result_id2}),\n ([ResultQuality.UNKNOWN, ResultQuality.BAD], {result_id3, result_id2}),\n ([ResultQuality.GOOD, ResultQuality.BAD, ResultQuality.UNKNOWN],\n {result_id1, result_id2, result_id3})\n ]\n\n for quality, expected in subtests:\n with self.subTest(quality=quality):\n results = self.provider.experiment.analysis_results(quality=quality)\n if not isinstance(quality, list):\n quality = [quality]\n qual_set = []\n for qual in quality:\n if isinstance(qual, str):\n qual = ResultQuality(qual.upper())\n qual_set.append(qual)\n res_ids = set()\n for res in results:\n self.assertIn(res[\"quality\"], qual_set)\n res_ids.add(res[\"result_id\"])\n self.assertTrue(expected <= res_ids,\n f\"Result {expected} not returned \"\n f\"when filter with quality {quality}\")\n\n def test_analysis_results_backend_name(self):\n \"\"\"Test filtering analysis results with backend name.\"\"\"\n result_id = self._create_analysis_result()\n results = self.provider.experiment.analysis_results(backend_name=self.backend.name())\n self.assertIn(result_id, [res[\"result_id\"] for res in results])\n\n def test_analysis_results_verified(self):\n \"\"\"Test filtering analysis results with verified.\"\"\"\n result_id = self._create_analysis_result(verified=True)\n results = self.provider.experiment.analysis_results(verified=True)\n found = False\n for res in results:\n self.assertTrue(res[\"verified\"])\n if res[\"result_id\"] == result_id:\n found = True\n self.assertTrue(found, f\"Result {result_id} not found when \"\n f\"filtering with verified=True\")\n\n def test_analysis_results_with_tags(self):\n \"\"\"Test filtering analysis results using tags.\"\"\"\n ref_tags = [\"qiskit_test\", \"foo\"]\n result_id = self._create_analysis_result(tags=ref_tags)\n\n phantom_tag = uuid.uuid4().hex\n sub_tests = [\n (ref_tags, 'AND', True),\n (ref_tags, 'OR', True),\n (ref_tags[:1], \"OR\", True),\n (ref_tags + [phantom_tag], \"AND\", False),\n (ref_tags + [phantom_tag], \"OR\", True),\n ([phantom_tag], \"OR\", False)\n ]\n for tags, operator, found in sub_tests:\n with self.subTest(tags=tags, operator=operator):\n results = self.provider.experiment.analysis_results(\n tags=tags, tags_operator=operator)\n res_found = False\n for res in results:\n msg = \"Tags {} not fond in result tags {}\".format(tags, res[\"tags\"])\n if operator == 'AND':\n self.assertTrue(all(f_tag in res[\"tags\"] for f_tag in tags), msg)\n else:\n self.assertTrue(any(f_tag in res[\"tags\"] for f_tag in tags), msg)\n if res[\"result_id\"] == result_id:\n res_found = True\n self.assertTrue(res_found == found,\n \"Result tags {} unexpectedly (not)found. Found={}\".format(\n ref_tags, found))\n\n def test_analysis_results_with_limit(self):\n \"\"\"Test retrieving analysis results with limit.\"\"\"\n self._create_analysis_result()\n results = self.provider.experiment.analysis_results(limit=1)\n self.assertEqual(1, len(results))\n\n def test_analysis_results_with_no_limit(self):\n \"\"\"Test retrieving analysis results with no limit.\"\"\"\n tags = [str(uuid.uuid4())]\n result_id = self._create_analysis_result(tags=tags)\n results = self.provider.experiment.analysis_results(limit=None, tags=tags)\n self.assertEqual(1, len(results))\n self.assertEqual(result_id, results[0][\"result_id\"])\n\n def test_analysis_results_with_sort_by(self):\n \"\"\"Test retrieving analysis results with sort_by.\"\"\"\n tags = [str(uuid.uuid4())]\n backend, components = self._find_backend_device_components(3)\n backend_name = backend or self.backend.name()\n device_components = components or self.device_components\n if len(device_components) < 3:\n device_components = [None]*3 # Skip testing device components.\n device_components.sort()\n expr_id = self._create_experiment(backend_name=backend_name)\n\n res1 = self._create_analysis_result(exp_id=expr_id, tags=tags,\n result_type=\"qiskit_test1\",\n device_components=device_components[2])\n res2 = self._create_analysis_result(exp_id=expr_id, tags=tags,\n result_type=\"qiskit_test2\",\n device_components=device_components[0])\n res3 = self._create_analysis_result(exp_id=expr_id, tags=tags,\n result_type=\"qiskit_test1\",\n device_components=device_components[1])\n\n subtests = [\n ([\"result_type:asc\"], [res3, res1, res2]),\n ([\"result_type:desc\"], [res2, res3, res1]),\n ([\"creation_datetime:asc\"], [res1, res2, res3]),\n ([\"creation_datetime:desc\"], [res3, res2, res1]),\n ([\"result_type:asc\", \"creation_datetime:asc\"], [res1, res3, res2]),\n ([\"result_type:asc\", \"creation_datetime:desc\"], [res3, res1, res2]),\n ([\"result_type:desc\", \"creation_datetime:asc\"], [res2, res1, res3]),\n ([\"result_type:desc\", \"creation_datetime:desc\"], [res2, res3, res1]),\n ]\n if device_components[0]:\n subtests += [\n ([\"device_components:asc\"], [res2, res3, res1]),\n ([\"device_components:desc\"], [res1, res3, res2]),\n ([\"result_type:asc\", \"device_components:desc\"], [res1, res3, res2])\n ]\n\n for sort_by, expected in subtests:\n with self.subTest(sort_by=sort_by):\n results = self.provider.experiment.analysis_results(tags=tags, sort_by=sort_by)\n self.assertEqual(expected, [res[\"result_id\"] for res in results])\n\n def test_analysis_results_with_bad_sort_by(self):\n \"\"\"Test retrieving analysis results with bad sort_by.\"\"\"\n subtests = [\"result_id:asc\", \"result_type\", \"result_type:foo\", \"foo:bar\"]\n\n for sort_by in subtests:\n with self.subTest(sort_by=sort_by):\n with self.assertRaises(ValueError):\n self.provider.experiment.analysis_results(sort_by=sort_by)\n\n def test_delete_analysis_result(self):\n \"\"\"Test deleting an analysis result.\"\"\"\n result_id = self._create_analysis_result()\n with mock.patch('builtins.input', lambda _: 'y'):\n self.provider.experiment.delete_analysis_result(result_id)\n\n with self.assertRaises(IBMExperimentEntryNotFound):\n self.provider.experiment.analysis_result(result_id)\n\n def test_backend_components(self):\n \"\"\"Test retrieving all device components.\"\"\"\n device_components = self.provider.experiment.device_components()\n self.assertTrue(device_components)\n\n def test_backend_components_backend_name(self):\n \"\"\"Test retrieving device components for a specific backend.\"\"\"\n device_components = self.provider.experiment.device_components()\n backend = list(device_components.keys())[0]\n backend_components = self.provider.experiment.device_components(backend)\n self.assertEqual(device_components[backend], backend_components)\n\n def test_retrieve_backends(self):\n \"\"\"Test retrieving all backends.\"\"\"\n backends = self.provider.experiment.backends()\n self.assertIn(self.backend.name(), [b['name'] for b in backends])\n\n def test_create_figure(self):\n \"\"\"Test creating a figure.\"\"\"\n hello_bytes = str.encode(\"hello world\")\n file_name = \"hello_world.svg\"\n figure_name = \"hello.svg\"\n with open(file_name, 'wb') as file:\n file.write(hello_bytes)\n self.addCleanup(os.remove, file_name)\n\n subtests = [\n (hello_bytes, None),\n (hello_bytes, figure_name),\n (file_name, None),\n (file_name, file_name)\n ]\n\n for figure, figure_name in subtests:\n title = f\"figure_name={figure_name}\" if figure_name else f\"figure={figure}\"\n with self.subTest(title=title):\n expr_id = self._create_experiment()\n name, _ = self.provider.experiment.create_figure(\n experiment_id=expr_id,\n figure=figure,\n figure_name=figure_name\n )\n if figure_name:\n self.assertEqual(figure_name, name)\n elif isinstance(figure, str):\n self.assertEqual(figure, name)\n expr = self.provider.experiment.experiment(expr_id)\n self.assertIn(name, expr[\"figure_names\"])\n\n def test_figure(self):\n \"\"\"Test getting a figure.\"\"\"\n hello_bytes = str.encode(\"hello world\")\n figure_name = \"hello.svg\"\n expr_id = self._create_experiment()\n self.provider.experiment.create_figure(\n experiment_id=expr_id,\n figure=hello_bytes,\n figure_name=figure_name\n )\n file_name = \"hello_world.svg\"\n self.addCleanup(os.remove, file_name)\n\n subtests = [\n (figure_name, None),\n (figure_name, file_name)\n ]\n\n for figure_name, file_name in subtests:\n with self.subTest(file_name=file_name):\n fig = self.provider.experiment.figure(expr_id, figure_name, file_name)\n if file_name:\n with open(file_name, 'rb') as file:\n self.assertEqual(hello_bytes, file.read())\n else:\n self.assertEqual(hello_bytes, fig)\n\n def test_update_figure(self):\n \"\"\"Test uploading and updating plot data.\"\"\"\n figure_name = \"hello.svg\"\n expr_id = self._create_experiment()\n self.provider.experiment.create_figure(\n experiment_id=expr_id,\n figure=str.encode(\"hello world\"),\n figure_name=figure_name\n )\n friend_bytes = str.encode(\"hello friend!\")\n name, _ = self.provider.experiment.update_figure(\n experiment_id=expr_id,\n figure=friend_bytes,\n figure_name=figure_name\n )\n self.assertEqual(name, figure_name)\n rplot = self.provider.experiment.figure(expr_id, figure_name)\n self.assertEqual(rplot, friend_bytes, \"Retrieved plot not equal updated plot.\")\n\n def test_delete_figure(self):\n \"\"\"Test deleting a figure.\"\"\"\n figure_name = \"hello.svg\"\n expr_id = self._create_experiment()\n self.provider.experiment.create_figure(\n experiment_id=expr_id,\n figure=str.encode(\"hello world\"),\n figure_name=figure_name\n )\n with mock.patch('builtins.input', lambda _: 'y'):\n self.provider.experiment.delete_figure(expr_id, figure_name)\n self.assertRaises(IBMExperimentEntryNotFound,\n self.provider.experiment.figure, expr_id, figure_name)\n\n def test_experiment_coders(self):\n \"\"\"Test custom encoder and decoder for an experiment.\"\"\"\n metadata = {\"complex\": 2 + 3j, \"numpy\": np.zeros(2)}\n expr_id = self._create_experiment(metadata=metadata, json_encoder=ExperimentEncoder)\n rexp = self.provider.experiment.experiment(expr_id, json_decoder=ExperimentDecoder)\n rmetadata = rexp[\"metadata\"]\n self.assertEqual(metadata[\"complex\"], rmetadata[\"complex\"])\n self.assertTrue((metadata[\"numpy\"] == rmetadata[\"numpy\"]).all())\n\n new_metadata = {\"complex\": 4 + 5j, \"numpy\": np.ones(3)}\n self.provider.experiment.update_experiment(\n expr_id, metadata=new_metadata, json_encoder=ExperimentEncoder)\n rexp = self.provider.experiment.experiment(expr_id, json_decoder=ExperimentDecoder)\n rmetadata = rexp[\"metadata\"]\n self.assertEqual(new_metadata[\"complex\"], rmetadata[\"complex\"])\n self.assertTrue((new_metadata[\"numpy\"] == rmetadata[\"numpy\"]).all())\n\n def test_analysis_result_coders(self):\n \"\"\"Test custom encoder and decoder for an analysis result.\"\"\"\n data = {\"complex\": 2 + 3j, \"numpy\": np.zeros(2)}\n result_id = self._create_analysis_result(\n result_data=data, json_encoder=ExperimentEncoder)\n rresult = self.provider.experiment.analysis_result(\n result_id, json_decoder=ExperimentDecoder)\n rdata = rresult[\"result_data\"]\n self.assertEqual(data[\"complex\"], rdata[\"complex\"])\n self.assertTrue((data[\"numpy\"] == rdata[\"numpy\"]).all())\n\n new_data = {\"complex\": 4 + 5j, \"numpy\": np.ones(3)}\n self.provider.experiment.update_analysis_result(\n result_id, result_data=new_data, json_encoder=ExperimentEncoder)\n rresult = self.provider.experiment.analysis_result(\n result_id, json_decoder=ExperimentDecoder)\n rdata = rresult[\"result_data\"]\n self.assertEqual(new_data[\"complex\"], rdata[\"complex\"])\n self.assertTrue((new_data[\"numpy\"] == rdata[\"numpy\"]).all())\n\n def _create_experiment(\n self,\n experiment_type: Optional[str] = None,\n backend_name: Optional[str] = None,\n **kwargs\n ) -> str:\n \"\"\"Create a new experiment.\"\"\"\n experiment_type = experiment_type or 'qiskit_test'\n backend_name = backend_name or self.backend.name()\n exp_id = self.provider.experiment.create_experiment(\n experiment_type=experiment_type,\n backend_name=backend_name,\n **kwargs\n )\n self.experiments_to_delete.append(exp_id)\n return exp_id\n\n def _create_analysis_result(\n self,\n exp_id: Optional[str] = None,\n result_type: Optional[str] = None,\n result_data: Optional[Dict] = None,\n **kwargs: Any):\n \"\"\"Create a simple analysis result.\"\"\"\n experiment_id = exp_id or self._create_experiment()\n result_type = result_type or \"qiskit_test\"\n result_data = result_data or {}\n aresult_id = self.provider.experiment.create_analysis_result(\n experiment_id=experiment_id,\n result_data=result_data,\n result_type=result_type,\n **kwargs\n )\n return aresult_id\n\n def _find_backend_device_components(self, min_components):\n \"\"\"Find a backend with the minimum number of device components.\"\"\"\n backend_name = self.backend.name()\n device_components = self.device_components\n if len(device_components) < min_components:\n all_components = self.provider.experiment.device_components()\n for key, val in all_components.items():\n if len(val) >= min_components:\n backend_name = key\n device_components = val\n break\n if len(device_components) < min_components:\n return None, None\n\n return backend_name, device_components\n"
] |
[
[
"numpy.zeros",
"numpy.ones"
]
] |
zanellia/ctree
|
[
"d53d29d972ac06b60d8fc4fb81f5553d2ffbfda0"
] |
[
"examples/OclDoubler.py"
] |
[
"\"\"\"\nParses the python AST below, transforms it to C, JITs it, and runs it.\n\"\"\"\n\nimport logging\n\nlogging.basicConfig(level=20)\n\nimport numpy as np\nimport ctypes as ct\nimport pycl as cl\n\nimport ctree.np\nfrom ctree.c.nodes import *\nfrom ctree.cpp.nodes import *\nfrom ctree.ocl.nodes import *\nfrom ctree.ocl.types import *\nfrom ctree.ocl.macros import *\nfrom ctree.templates.nodes import StringTemplate\nfrom ctree.transformations import *\nfrom ctree.frontend import get_ast\nfrom ctree.jit import LazySpecializedFunction\nfrom ctree.jit import ConcreteSpecializedFunction\n\nfrom ctree import browser_show_ast\n\n# ---------------------------------------------------------------------------\n# Specializer code\n\nclass OpFunction(ConcreteSpecializedFunction):\n def __init__(self):\n self.context = cl.clCreateContextFromType()\n self.queue = cl.clCreateCommandQueue(self.context)\n\n def finalize(self, kernel, tree, entry_name, entry_type):\n self.kernel = kernel\n self._c_function = self._compile(entry_name, tree, entry_type)\n return self\n\n def __call__(self, A):\n buf, evt = cl.buffer_from_ndarray(self.queue, A, blocking=False)\n self._c_function(self.queue, self.kernel, buf)\n B, evt = cl.buffer_to_ndarray(self.queue, buf, like=A)\n return B\n\n\nclass OpTranslator(LazySpecializedFunction):\n def args_to_subconfig(self, args):\n \"\"\"\n Analyze arguments and return a 'subconfig', a hashable object\n that classifies them. Arguments with identical subconfigs\n might be processed by the same generated code.\n \"\"\"\n A = args[0]\n return np.ctypeslib.ndpointer(A.dtype, A.ndim, A.shape)\n\n def transform(self, py_ast, program_config):\n \"\"\"\n Convert the Python AST to a C AST according to the directions\n given in program_config.\n \"\"\"\n A = program_config[0]\n len_A = np.prod(A._shape_)\n inner_type = A._dtype_.type()\n # browser_show_ast(py_ast,'tmp.png')\n apply_one = PyBasicConversions().visit(py_ast.body[0])\n apply_one.name = 'apply'\n apply_one.return_type = inner_type\n apply_one.params[0].type = inner_type\n\n apply_kernel = FunctionDecl(None, \"apply_kernel\",\n params=[SymbolRef(\"A\", A()).set_global()],\n defn=[\n Assign(SymbolRef(\"i\", ct.c_int()), get_global_id(0)),\n If(Lt(SymbolRef(\"i\"), Constant(len_A)), [\n Assign(ArrayRef(SymbolRef(\"A\"), SymbolRef(\"i\")),\n FunctionCall(SymbolRef(apply_one.name),\n [ArrayRef(SymbolRef(\"A\"), SymbolRef(\"i\"))])),\n ], []),\n ]\n ).set_kernel()\n\n kernel = OclFile(\"kernel\", [apply_one, apply_kernel])\n\n control = StringTemplate(r\"\"\"\n #ifdef __APPLE__\n #include <OpenCL/opencl.h>\n #else\n #include <CL/cl.h>\n #endif\n void apply_all(cl_command_queue queue, cl_kernel kernel, cl_mem buf) {\n size_t global = $n;\n size_t local = 32;\n clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf);\n clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, &local, 0, NULL, NULL);\n\n }\n \"\"\", {'n': Constant(len_A + 32 - (len_A % 32))})\n cfile = CFile(\"generated\", [control], config_target='opencl')\n return kernel, cfile\n\n def finalize(self, transform_result, program_config):\n kernel, cfile = transform_result\n proj = Project([kernel, cfile])\n fn = OpFunction()\n\n program = cl.clCreateProgramWithSource(fn.context, kernel.codegen()).build()\n apply_kernel_ptr = program['apply_kernel']\n\n entry_type = ct.CFUNCTYPE(None, cl.cl_command_queue, cl.cl_kernel, cl.cl_mem)\n return fn.finalize(apply_kernel_ptr, proj, \"apply_all\", entry_type)\n\n def interpret(self, A):\n return np.vectorize(self.apply)(A)\n\n\n# ---------------------------------------------------------------------------\n# user code\n\n\ndef double(x):\n return x * 2\n\n\ndef square(x):\n return x * x\n\n\ndef main():\n doubler = OpTranslator.from_function(double, 'Doubler')\n squarer = OpTranslator.from_function(square, 'Squarer')\n\n data = np.arange(123, dtype=np.float32)\n\n # squaring floats\n actual = squarer(data)\n expected = np.vectorize(square)(data)\n np.testing.assert_array_equal(actual, expected)\n print(\"Squarer works.\")\n\n # doubling floats\n actual = doubler(data)\n expected = np.vectorize(double)(data)\n np.testing.assert_array_equal(actual, expected)\n print(\"Doubler works.\")\n\nif __name__ == '__main__':\n # Testing conventional (non-lambda) kernel function implementation\n main()\n"
] |
[
[
"numpy.arange",
"numpy.testing.assert_array_equal",
"numpy.vectorize",
"numpy.prod",
"numpy.ctypeslib.ndpointer"
]
] |
alexandroskoliousis/benchmarks
|
[
"6a6b95b97e53244ac8c01577801cfbf0926b718c"
] |
[
"scripts/tf_cnn_benchmarks/preprocessing.py"
] |
[
"# Copyright 2017 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\n\"\"\"Image pre-processing utilities.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nimport cnn_util\nfrom tensorflow.contrib.data.python.ops import threadpool\nfrom tensorflow.contrib.image.python.ops import distort_image_ops\nfrom tensorflow.python.data.ops import multi_device_iterator_ops\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.layers import utils\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.platform import gfile\nimport mlperf\n\n\ndef parse_example_proto(example_serialized):\n \"\"\"Parses an Example proto containing a training example of an image.\n\n The output of the build_image_data.py image preprocessing script is a dataset\n containing serialized Example protocol buffers. Each Example proto contains\n the following fields:\n\n image/height: 462\n image/width: 581\n image/colorspace: 'RGB'\n image/channels: 3\n image/class/label: 615\n image/class/synset: 'n03623198'\n image/class/text: 'knee pad'\n image/object/bbox/xmin: 0.1\n image/object/bbox/xmax: 0.9\n image/object/bbox/ymin: 0.2\n image/object/bbox/ymax: 0.6\n image/object/bbox/label: 615\n image/format: 'JPEG'\n image/filename: 'ILSVRC2012_val_00041207.JPEG'\n image/encoded: <JPEG encoded string>\n\n Args:\n example_serialized: scalar Tensor tf.string containing a serialized\n Example protocol buffer.\n\n Returns:\n image_buffer: Tensor tf.string containing the contents of a JPEG file.\n label: Tensor tf.int32 containing the label.\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged as\n [ymin, xmin, ymax, xmax].\n text: Tensor tf.string containing the human-readable label.\n \"\"\"\n # Dense features in Example proto.\n feature_map = {\n 'image/encoded': tf.FixedLenFeature([], dtype=tf.string,\n default_value=''),\n 'image/class/label': tf.FixedLenFeature([1], dtype=tf.int64,\n default_value=-1),\n 'image/class/text': tf.FixedLenFeature([], dtype=tf.string,\n default_value=''),\n }\n sparse_float32 = tf.VarLenFeature(dtype=tf.float32)\n # Sparse features in Example proto.\n feature_map.update(\n {k: sparse_float32 for k in ['image/object/bbox/xmin',\n 'image/object/bbox/ymin',\n 'image/object/bbox/xmax',\n 'image/object/bbox/ymax']})\n\n features = tf.parse_single_example(example_serialized, feature_map)\n label = tf.cast(features['image/class/label'], dtype=tf.int32)\n\n xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0)\n ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0)\n xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0)\n ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0)\n\n # Note that we impose an ordering of (y, x) just to make life difficult.\n bbox = tf.concat([ymin, xmin, ymax, xmax], 0)\n\n # Force the variable number of bounding boxes into the shape\n # [1, num_boxes, coords].\n bbox = tf.expand_dims(bbox, 0)\n bbox = tf.transpose(bbox, [0, 2, 1])\n\n return features['image/encoded'], label, bbox, features['image/class/text']\n\n\n_RESIZE_METHOD_MAP = {\n 'nearest': tf.image.ResizeMethod.NEAREST_NEIGHBOR,\n 'bilinear': tf.image.ResizeMethod.BILINEAR,\n 'bicubic': tf.image.ResizeMethod.BICUBIC,\n 'area': tf.image.ResizeMethod.AREA\n}\n\n\ndef get_image_resize_method(resize_method, batch_position=0):\n \"\"\"Get tensorflow resize method.\n\n If resize_method is 'round_robin', return different methods based on batch\n position in a round-robin fashion. NOTE: If the batch size is not a multiple\n of the number of methods, then the distribution of methods will not be\n uniform.\n\n Args:\n resize_method: (string) nearest, bilinear, bicubic, area, or round_robin.\n batch_position: position of the image in a batch. NOTE: this argument can\n be an integer or a tensor\n Returns:\n one of resize type defined in tf.image.ResizeMethod.\n \"\"\"\n\n if resize_method != 'round_robin':\n return _RESIZE_METHOD_MAP[resize_method]\n\n # return a resize method based on batch position in a round-robin fashion.\n resize_methods = list(_RESIZE_METHOD_MAP.values())\n def lookup(index):\n return resize_methods[index]\n\n def resize_method_0():\n return utils.smart_cond(batch_position % len(resize_methods) == 0,\n lambda: lookup(0), resize_method_1)\n\n def resize_method_1():\n return utils.smart_cond(batch_position % len(resize_methods) == 1,\n lambda: lookup(1), resize_method_2)\n\n def resize_method_2():\n return utils.smart_cond(batch_position % len(resize_methods) == 2,\n lambda: lookup(2), lambda: lookup(3))\n\n # NOTE(jsimsa): Unfortunately, we cannot use a single recursive function here\n # because TF would not be able to construct a finite graph.\n\n return resize_method_0()\n\n\ndef decode_jpeg(image_buffer, scope=None): # , dtype=tf.float32):\n \"\"\"Decode a JPEG string into one 3-D float image Tensor.\n\n Args:\n image_buffer: scalar string Tensor.\n scope: Optional scope for op_scope.\n Returns:\n 3-D float Tensor with values ranging from [0, 1).\n \"\"\"\n # with tf.op_scope([image_buffer], scope, 'decode_jpeg'):\n # with tf.name_scope(scope, 'decode_jpeg', [image_buffer]):\n with tf.name_scope(scope or 'decode_jpeg'):\n # Decode the string as an RGB JPEG.\n # Note that the resulting image contains an unknown height and width\n # that is set dynamically by decode_jpeg. In other words, the height\n # and width of image is unknown at compile-time.\n image = tf.image.decode_jpeg(image_buffer, channels=3,\n fancy_upscaling=False,\n dct_method='INTEGER_FAST')\n\n # image = tf.Print(image, [tf.shape(image)], 'Image shape: ')\n\n return image\n\n\n_R_MEAN = 123.68\n_G_MEAN = 116.78\n_B_MEAN = 103.94\n_CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN]\n\n\ndef normalized_image(images):\n # Rescale from [0, 255] to [0, 2]\n images = tf.multiply(images, 1. / 127.5)\n # Rescale to [-1, 1]\n mlperf.logger.log(key=mlperf.tags.INPUT_MEAN_SUBTRACTION, value=[1.0] * 3)\n return tf.subtract(images, 1.0)\n\n\ndef eval_image(image,\n height,\n width,\n batch_position,\n resize_method,\n summary_verbosity=0):\n \"\"\"Get the image for model evaluation.\n\n We preprocess the image simiarly to Slim, see\n https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/vgg_preprocessing.py\n Validation images do not have bounding boxes, so to crop the image, we first\n resize the image such that the aspect ratio is maintained and the resized\n height and width are both at least 1.145 times `height` and `width`\n respectively. Then, we do a central crop to size (`height`, `width`).\n\n Args:\n image: 3-D float Tensor representing the image.\n height: The height of the image that will be returned.\n width: The width of the image that will be returned.\n batch_position: position of the image in a batch, which affects how images\n are distorted and resized. NOTE: this argument can be an integer or a\n tensor\n resize_method: one of the strings 'round_robin', 'nearest', 'bilinear',\n 'bicubic', or 'area'.\n summary_verbosity: Verbosity level for summary ops. Pass 0 to disable both\n summaries and checkpoints.\n Returns:\n An image of size (output_height, output_width, 3) that is resized and\n cropped as described above.\n \"\"\"\n # TODO(reedwm): Currently we resize then crop. Investigate if it's faster to\n # crop then resize.\n with tf.name_scope('eval_image'):\n if summary_verbosity >= 3:\n tf.summary.image(\n 'original_image', tf.expand_dims(image, 0))\n\n shape = tf.shape(image)\n image_height = shape[0]\n image_width = shape[1]\n image_height_float = tf.cast(image_height, tf.float32)\n image_width_float = tf.cast(image_width, tf.float32)\n\n # This value is chosen so that in resnet, images are cropped to a size of\n # 256 x 256, which matches what other implementations do. The final image\n # size for resnet is 224 x 224, and floor(224 * 1.145) = 256.\n scale_factor = 1.145\n\n # Compute resize_height and resize_width to be the minimum values such that\n # 1. The aspect ratio is maintained (i.e. resize_height / resize_width is\n # image_height / image_width), and\n # 2. resize_height >= height * `scale_factor`, and\n # 3. resize_width >= width * `scale_factor`\n max_ratio = tf.maximum(height / image_height_float,\n width / image_width_float)\n resize_height = tf.cast(image_height_float * max_ratio * scale_factor,\n tf.int32)\n resize_width = tf.cast(image_width_float * max_ratio * scale_factor,\n tf.int32)\n mlperf.logger.log_input_resize_aspect_preserving(height, width,\n scale_factor)\n\n # Resize the image to shape (`resize_height`, `resize_width`)\n image_resize_method = get_image_resize_method(resize_method, batch_position)\n distorted_image = tf.image.resize_images(image,\n [resize_height, resize_width],\n image_resize_method,\n align_corners=False)\n\n # Do a central crop of the image to size (height, width).\n # MLPerf requires us to log (height, width) with two different keys.\n mlperf.logger.log(key=mlperf.tags.INPUT_CENTRAL_CROP, value=[height, width])\n mlperf.logger.log(key=mlperf.tags.INPUT_RESIZE, value=[height, width])\n total_crop_height = (resize_height - height)\n crop_top = total_crop_height // 2\n total_crop_width = (resize_width - width)\n crop_left = total_crop_width // 2\n distorted_image = tf.slice(distorted_image, [crop_top, crop_left, 0],\n [height, width, 3])\n\n distorted_image.set_shape([height, width, 3])\n if summary_verbosity >= 3:\n tf.summary.image(\n 'cropped_resized_image', tf.expand_dims(distorted_image, 0))\n image = distorted_image\n return image\n\n\ndef train_image(image_buffer,\n height,\n width,\n bbox,\n batch_position,\n resize_method,\n distortions,\n scope=None,\n summary_verbosity=0,\n distort_color_in_yiq=False,\n fuse_decode_and_crop=False):\n \"\"\"Distort one image for training a network.\n\n Distorting images provides a useful technique for augmenting the data\n set during training in order to make the network invariant to aspects\n of the image that do not effect the label.\n\n Args:\n image_buffer: scalar string Tensor representing the raw JPEG image buffer.\n height: integer\n width: integer\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax].\n batch_position: position of the image in a batch, which affects how images\n are distorted and resized. NOTE: this argument can be an integer or a\n tensor\n resize_method: round_robin, nearest, bilinear, bicubic, or area.\n distortions: If true, apply full distortions for image colors.\n scope: Optional scope for op_scope.\n summary_verbosity: Verbosity level for summary ops. Pass 0 to disable both\n summaries and checkpoints.\n distort_color_in_yiq: distort color of input images in YIQ space.\n fuse_decode_and_crop: fuse the decode/crop operation.\n Returns:\n 3-D float Tensor of distorted image used for training.\n \"\"\"\n # with tf.op_scope([image, height, width, bbox], scope, 'distort_image'):\n # with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]):\n with tf.name_scope(scope or 'distort_image'):\n # A large fraction of image datasets contain a human-annotated bounding box\n # delineating the region of the image containing the object of interest. We\n # choose to create a new bounding box for the object which is a randomly\n # distorted version of the human-annotated bounding box that obeys an\n # allowed range of aspect ratios, sizes and overlap with the human-annotated\n # bounding box. If no box is supplied, then we assume the bounding box is\n # the entire image.\n min_object_covered = 0.1\n aspect_ratio_range = [0.75, 1.33]\n area_range = [0.05, 1.0]\n max_attempts = 100\n mlperf.logger.log(key=mlperf.tags.INPUT_DISTORTED_CROP_MIN_OBJ_COV,\n value=min_object_covered)\n mlperf.logger.log(key=mlperf.tags.INPUT_DISTORTED_CROP_RATIO_RANGE,\n value=aspect_ratio_range)\n mlperf.logger.log(key=mlperf.tags.INPUT_DISTORTED_CROP_AREA_RANGE,\n value=area_range)\n mlperf.logger.log(key=mlperf.tags.INPUT_DISTORTED_CROP_MAX_ATTEMPTS,\n value=max_attempts)\n\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(\n tf.image.extract_jpeg_shape(image_buffer),\n bounding_boxes=bbox,\n min_object_covered=min_object_covered,\n aspect_ratio_range=aspect_ratio_range,\n area_range=area_range,\n max_attempts=max_attempts,\n use_image_if_no_bounding_boxes=True)\n bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box\n if summary_verbosity >= 3:\n image = tf.image.decode_jpeg(image_buffer, channels=3,\n dct_method='INTEGER_FAST')\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n image_with_distorted_box = tf.image.draw_bounding_boxes(\n tf.expand_dims(image, 0), distort_bbox)\n tf.summary.image(\n 'images_with_distorted_bounding_box',\n image_with_distorted_box)\n\n # Crop the image to the specified bounding box.\n if fuse_decode_and_crop:\n offset_y, offset_x, _ = tf.unstack(bbox_begin)\n target_height, target_width, _ = tf.unstack(bbox_size)\n crop_window = tf.stack([offset_y, offset_x, target_height, target_width])\n image = tf.image.decode_and_crop_jpeg(\n image_buffer, crop_window, channels=3)\n else:\n image = tf.image.decode_jpeg(image_buffer, channels=3,\n dct_method='INTEGER_FAST')\n image = tf.slice(image, bbox_begin, bbox_size)\n\n mlperf.logger.log(key=mlperf.tags.INPUT_RANDOM_FLIP)\n distorted_image = tf.image.random_flip_left_right(image)\n\n # This resizing operation may distort the images because the aspect\n # ratio is not respected.\n mlperf.logger.log(key=mlperf.tags.INPUT_RESIZE, value=[height, width])\n image_resize_method = get_image_resize_method(resize_method, batch_position)\n distorted_image = tf.image.resize_images(\n distorted_image, [height, width],\n image_resize_method,\n align_corners=False)\n # Restore the shape since the dynamic slice based upon the bbox_size loses\n # the third dimension.\n distorted_image.set_shape([height, width, 3])\n if summary_verbosity >= 3:\n tf.summary.image('cropped_resized_maybe_flipped_image',\n tf.expand_dims(distorted_image, 0))\n\n if distortions:\n distorted_image = tf.cast(distorted_image, dtype=tf.float32)\n # Images values are expected to be in [0,1] for color distortion.\n distorted_image /= 255.\n # Randomly distort the colors.\n distorted_image = distort_color(distorted_image, batch_position,\n distort_color_in_yiq=distort_color_in_yiq)\n\n # Note: This ensures the scaling matches the output of eval_image\n distorted_image *= 255\n\n if summary_verbosity >= 3:\n tf.summary.image(\n 'final_distorted_image',\n tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n\ndef distort_color(image, batch_position=0, distort_color_in_yiq=False,\n scope=None):\n \"\"\"Distort the color of the image.\n\n Each color distortion is non-commutative and thus ordering of the color ops\n matters. Ideally we would randomly permute the ordering of the color ops.\n Rather then adding that level of complication, we select a distinct ordering\n of color ops based on the position of the image in a batch.\n\n Args:\n image: float32 Tensor containing single image. Tensor values should be in\n range [0, 1].\n batch_position: the position of the image in a batch. NOTE: this argument\n can be an integer or a tensor\n distort_color_in_yiq: distort color of input images in YIQ space.\n scope: Optional scope for op_scope.\n Returns:\n color-distorted image\n \"\"\"\n with tf.name_scope(scope or 'distort_color'):\n\n def distort_fn_0(image=image):\n \"\"\"Variant 0 of distort function.\"\"\"\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n if distort_color_in_yiq:\n image = distort_image_ops.random_hsv_in_yiq(\n image, lower_saturation=0.5, upper_saturation=1.5,\n max_delta_hue=0.2 * math.pi)\n else:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n return image\n\n def distort_fn_1(image=image):\n \"\"\"Variant 1 of distort function.\"\"\"\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n if distort_color_in_yiq:\n image = distort_image_ops.random_hsv_in_yiq(\n image, lower_saturation=0.5, upper_saturation=1.5,\n max_delta_hue=0.2 * math.pi)\n else:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n return image\n\n image = utils.smart_cond(batch_position % 2 == 0, distort_fn_0,\n distort_fn_1)\n # The random_* ops do not necessarily clamp.\n image = tf.clip_by_value(image, 0.0, 1.0)\n return image\n\n\nclass InputPreprocessor(object):\n \"\"\"Base class for all model preprocessors.\"\"\"\n\n def __init__(self, batch_size, output_shapes):\n self.batch_size = batch_size\n self.output_shapes = output_shapes\n\n def supports_datasets(self):\n \"\"\"Whether this preprocessor supports dataset.\"\"\"\n return False\n\n def minibatch(self, dataset, subset, params, shift_ratio=-1):\n \"\"\"Returns tensors representing a minibatch of all the input.\"\"\"\n raise NotImplementedError('Must be implemented by subclass.')\n\n # The methods added below are only supported/used if supports_datasets()\n # returns True.\n # TODO(laigd): refactor benchmark_cnn.py and put the logic of\n # _build_input_processing() into InputPreprocessor.\n\n def parse_and_preprocess(self, value, batch_position):\n \"\"\"Function to parse and preprocess an Example proto in input pipeline.\"\"\"\n raise NotImplementedError('Must be implemented by subclass.')\n\n # TODO(laigd): figure out how to remove these parameters, since the\n # preprocessor itself has self.batch_size, self.num_splits, etc defined.\n def build_multi_device_iterator(self, batch_size, num_splits, cpu_device,\n params, gpu_devices, dataset, doing_eval):\n \"\"\"Creates a MultiDeviceIterator.\"\"\"\n assert self.supports_datasets()\n assert num_splits == len(gpu_devices)\n with tf.name_scope('batch_processing'):\n if doing_eval:\n subset = 'validation'\n else:\n subset = 'train'\n batch_size_per_split = batch_size // num_splits\n ds = self.create_dataset(\n batch_size,\n num_splits,\n batch_size_per_split,\n dataset,\n subset,\n train=(not doing_eval),\n datasets_repeat_cached_sample=params.datasets_repeat_cached_sample,\n num_threads=params.datasets_num_private_threads,\n datasets_use_caching=params.datasets_use_caching,\n datasets_parallel_interleave_cycle_length=(\n params.datasets_parallel_interleave_cycle_length),\n datasets_sloppy_parallel_interleave=(\n params.datasets_sloppy_parallel_interleave),\n datasets_parallel_interleave_prefetch=(\n params.datasets_parallel_interleave_prefetch))\n multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(\n ds,\n gpu_devices,\n source_device=cpu_device,\n max_buffer_size=params.multi_device_iterator_max_buffer_size)\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS,\n multi_device_iterator.initializer)\n return multi_device_iterator\n\n def create_dataset(self,\n batch_size,\n num_splits,\n batch_size_per_split,\n dataset,\n subset,\n train,\n datasets_repeat_cached_sample,\n num_threads=None,\n datasets_use_caching=False,\n datasets_parallel_interleave_cycle_length=None,\n datasets_sloppy_parallel_interleave=False,\n datasets_parallel_interleave_prefetch=None):\n \"\"\"Creates a dataset for the benchmark.\"\"\"\n raise NotImplementedError('Must be implemented by subclass.')\n\n def create_iterator(self, ds):\n ds_iterator = ds.make_initializable_iterator()\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS,\n ds_iterator.initializer)\n return ds_iterator\n\n def minibatch_fn(self, batch_size, model_input_shapes, num_splits,\n dataset, subset, train, datasets_repeat_cached_sample,\n num_threads, datasets_use_caching,\n datasets_parallel_interleave_cycle_length,\n datasets_sloppy_parallel_interleave,\n datasets_parallel_interleave_prefetch):\n \"\"\"Returns a function and list of args for the fn to create a minibatch.\"\"\"\n assert self.supports_datasets()\n batch_size_per_split = batch_size // num_splits\n assert batch_size_per_split == model_input_shapes[0][0]\n with tf.name_scope('batch_processing'):\n ds = self.create_dataset(batch_size, num_splits, batch_size_per_split,\n dataset, subset, train,\n datasets_repeat_cached_sample, num_threads,\n datasets_use_caching,\n datasets_parallel_interleave_cycle_length,\n datasets_sloppy_parallel_interleave,\n datasets_parallel_interleave_prefetch)\n ds_iterator = self.create_iterator(ds)\n\n ds_iterator_string_handle = ds_iterator.string_handle()\n\n @function.Defun(tf.string)\n def _fn(h):\n remote_iterator = tf.data.Iterator.from_string_handle(\n h, ds_iterator.output_types, ds_iterator.output_shapes)\n input_list = remote_iterator.get_next()\n reshaped_input_list = [\n tf.reshape(input_list[i], shape=model_input_shapes[i])\n for i in range(len(input_list))\n ]\n return reshaped_input_list\n\n return _fn, [ds_iterator_string_handle]\n\n\nclass BaseImagePreprocessor(InputPreprocessor):\n \"\"\"Base class for all image model preprocessors.\"\"\"\n\n def __init__(self,\n batch_size,\n output_shapes,\n num_splits,\n dtype,\n train,\n distortions,\n resize_method,\n shift_ratio=-1,\n summary_verbosity=0,\n distort_color_in_yiq=True,\n fuse_decode_and_crop=True,\n match_mlperf=False):\n super(BaseImagePreprocessor, self).__init__(batch_size, output_shapes)\n image_shape = output_shapes[0]\n # image_shape is in form (batch_size, height, width, depth)\n self.height = image_shape[1]\n self.width = image_shape[2]\n self.depth = image_shape[3]\n self.num_splits = num_splits\n self.dtype = dtype\n self.train = train\n self.resize_method = resize_method\n self.shift_ratio = shift_ratio\n self.distortions = distortions\n self.distort_color_in_yiq = distort_color_in_yiq\n self.fuse_decode_and_crop = fuse_decode_and_crop\n if self.batch_size % self.num_splits != 0:\n raise ValueError(\n ('batch_size must be a multiple of num_splits: '\n 'batch_size %d, num_splits: %d') %\n (self.batch_size, self.num_splits))\n self.batch_size_per_split = self.batch_size // self.num_splits\n self.summary_verbosity = summary_verbosity\n self.match_mlperf = match_mlperf\n\n def parse_and_preprocess(self, value, batch_position):\n assert self.supports_datasets()\n image_buffer, label_index, bbox, _ = parse_example_proto(value)\n if self.match_mlperf:\n bbox = tf.zeros((1, 0, 4), dtype=bbox.dtype)\n mlperf.logger.log(key=mlperf.tags.INPUT_CROP_USES_BBOXES, value=False)\n else:\n mlperf.logger.log(key=mlperf.tags.INPUT_CROP_USES_BBOXES, value=True)\n image = self.preprocess(image_buffer, bbox, batch_position)\n return (image, label_index)\n\n def preprocess(self, image_buffer, bbox, batch_position):\n raise NotImplementedError('Must be implemented by subclass.')\n\n def create_dataset(self,\n batch_size,\n num_splits,\n batch_size_per_split,\n dataset,\n subset,\n train,\n datasets_repeat_cached_sample,\n num_threads=None,\n datasets_use_caching=False,\n datasets_parallel_interleave_cycle_length=None,\n datasets_sloppy_parallel_interleave=False,\n datasets_parallel_interleave_prefetch=None):\n \"\"\"Creates a dataset for the benchmark.\"\"\"\n assert self.supports_datasets()\n glob_pattern = dataset.tf_record_pattern(subset)\n file_names = gfile.Glob(glob_pattern)\n if not file_names:\n raise ValueError('Found no files in --data_dir matching: {}'\n .format(glob_pattern))\n ds = tf.data.TFRecordDataset.list_files(file_names, shuffle=train)\n ds = ds.apply(\n tf.data.experimental.parallel_interleave(\n tf.data.TFRecordDataset,\n cycle_length=datasets_parallel_interleave_cycle_length or 10,\n sloppy=datasets_sloppy_parallel_interleave,\n prefetch_input_elements=datasets_parallel_interleave_prefetch))\n if datasets_repeat_cached_sample:\n # Repeat a single sample element indefinitely to emulate memory-speed IO.\n ds = ds.take(1).cache().repeat()\n counter = tf.data.Dataset.range(batch_size)\n counter = counter.repeat()\n ds = tf.data.Dataset.zip((ds, counter))\n ds = ds.prefetch(buffer_size=batch_size)\n if datasets_use_caching:\n ds = ds.cache()\n if train:\n buffer_size = 10000\n mlperf.logger.log(key=mlperf.tags.INPUT_SHARD, value=buffer_size)\n ds = ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=buffer_size))\n else:\n ds = ds.repeat()\n ds = ds.apply(\n tf.data.experimental.map_and_batch(\n map_func=self.parse_and_preprocess,\n batch_size=batch_size_per_split,\n num_parallel_batches=num_splits))\n ds = ds.prefetch(buffer_size=num_splits)\n if num_threads:\n ds = threadpool.override_threadpool(\n ds,\n threadpool.PrivateThreadPool(\n num_threads, display_name='input_pipeline_thread_pool'))\n return ds\n\n\nclass RecordInputImagePreprocessor(BaseImagePreprocessor):\n \"\"\"Preprocessor for images with RecordInput format.\"\"\"\n\n def preprocess(self, image_buffer, bbox, batch_position):\n \"\"\"Preprocessing image_buffer as a function of its batch position.\"\"\"\n if self.train:\n image = train_image(image_buffer, self.height, self.width, bbox,\n batch_position, self.resize_method, self.distortions,\n None, summary_verbosity=self.summary_verbosity,\n distort_color_in_yiq=self.distort_color_in_yiq,\n fuse_decode_and_crop=self.fuse_decode_and_crop)\n else:\n image = tf.image.decode_jpeg(\n image_buffer, channels=3, dct_method='INTEGER_FAST')\n image = eval_image(image, self.height, self.width, batch_position,\n self.resize_method,\n summary_verbosity=self.summary_verbosity)\n # Note: image is now float32 [height,width,3] with range [0, 255]\n\n # image = tf.cast(image, tf.uint8) # HACK TESTING\n\n if self.match_mlperf:\n mlperf.logger.log(key=mlperf.tags.INPUT_MEAN_SUBTRACTION,\n value=_CHANNEL_MEANS)\n normalized = image - _CHANNEL_MEANS\n else:\n normalized = normalized_image(image)\n return tf.cast(normalized, self.dtype)\n\n def minibatch(self,\n dataset,\n subset,\n params,\n shift_ratio=-1):\n if shift_ratio < 0:\n shift_ratio = self.shift_ratio\n with tf.name_scope('batch_processing'):\n # Build final results per split.\n images = [[] for _ in range(self.num_splits)]\n labels = [[] for _ in range(self.num_splits)]\n if params.use_datasets:\n print(\"DBG> Use datasets\")\n ds = self.create_dataset(\n self.batch_size, self.num_splits, self.batch_size_per_split,\n dataset, subset, self.train,\n datasets_repeat_cached_sample=params.datasets_repeat_cached_sample,\n num_threads=params.datasets_num_private_threads,\n datasets_use_caching=params.datasets_use_caching,\n datasets_parallel_interleave_cycle_length=(\n params.datasets_parallel_interleave_cycle_length),\n datasets_sloppy_parallel_interleave=(\n params.datasets_sloppy_parallel_interleave),\n datasets_parallel_interleave_prefetch=(\n params.datasets_parallel_interleave_prefetch))\n ds_iterator = self.create_iterator(ds)\n for d in xrange(self.num_splits):\n images[d], labels[d] = ds_iterator.get_next()\n\n # TODO(laigd): consider removing the --use_datasets option, it should\n # always use datasets.\n else:\n print(\"DBG> Don't use datasets\")\n record_input = data_flow_ops.RecordInput(\n file_pattern=dataset.tf_record_pattern(subset),\n seed=301,\n parallelism=64,\n buffer_size=10000,\n batch_size=self.batch_size,\n shift_ratio=shift_ratio,\n name='record_input')\n records = record_input.get_yield_op()\n records = tf.split(records, self.batch_size, 0)\n records = [tf.reshape(record, []) for record in records]\n for idx in xrange(self.batch_size):\n value = records[idx]\n (image, label) = self.parse_and_preprocess(value, idx)\n split_index = idx % self.num_splits\n labels[split_index].append(label)\n images[split_index].append(image)\n\n for split_index in xrange(self.num_splits):\n if not params.use_datasets:\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.concat(labels[split_index], 0)\n images[split_index] = tf.reshape(\n images[split_index],\n shape=[self.batch_size_per_split, self.height, self.width,\n self.depth])\n labels[split_index] = tf.reshape(labels[split_index],\n [self.batch_size_per_split])\n return images, labels\n\n def supports_datasets(self):\n return True\n\n\nclass ImagenetPreprocessor(RecordInputImagePreprocessor):\n\n def preprocess(self, image_buffer, bbox, batch_position):\n # pylint: disable=g-import-not-at-top\n try:\n from official.resnet.imagenet_preprocessing import preprocess_image\n except ImportError:\n tf.logging.fatal('Please include tensorflow/models to the PYTHONPATH.')\n raise\n if self.train:\n image = preprocess_image(\n image_buffer, bbox, self.height, self.width, self.depth,\n is_training=True)\n else:\n image = preprocess_image(\n image_buffer, bbox, self.height, self.width, self.depth,\n is_training=False)\n return tf.cast(image, self.dtype)\n\n\nclass Cifar10ImagePreprocessor(BaseImagePreprocessor):\n \"\"\"Preprocessor for Cifar10 input images.\"\"\"\n\n def _distort_image(self, image):\n \"\"\"Distort one image for training a network.\n\n Adopted the standard data augmentation scheme that is widely used for\n this dataset: the images are first zero-padded with 4 pixels on each side,\n then randomly cropped to again produce distorted images; half of the images\n are then horizontally mirrored.\n\n Args:\n image: input image.\n Returns:\n distorted image.\n \"\"\"\n image = tf.image.resize_image_with_crop_or_pad(\n image, self.height + 8, self.width + 8)\n distorted_image = tf.random_crop(image,\n [self.height, self.width, self.depth])\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n if self.summary_verbosity >= 3:\n tf.summary.image('distorted_image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def _eval_image(self, image):\n \"\"\"Get the image for model evaluation.\"\"\"\n distorted_image = tf.image.resize_image_with_crop_or_pad(\n image, self.width, self.height)\n if self.summary_verbosity >= 3:\n tf.summary.image('cropped.image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def preprocess(self, raw_image):\n \"\"\"Preprocessing raw image.\"\"\"\n if self.summary_verbosity >= 3:\n tf.summary.image('raw.image', tf.expand_dims(raw_image, 0))\n if self.train and self.distortions:\n image = self._distort_image(raw_image)\n else:\n image = self._eval_image(raw_image)\n normalized = normalized_image(image)\n return tf.cast(normalized, self.dtype)\n\n def minibatch(self,\n dataset,\n subset,\n params,\n shift_ratio=-1):\n # TODO(jsimsa): Implement datasets code path\n del shift_ratio, params\n with tf.name_scope('batch_processing'):\n all_images, all_labels = dataset.read_data_files(subset)\n all_images = tf.constant(all_images)\n all_labels = tf.constant(all_labels)\n input_image, input_label = tf.train.slice_input_producer(\n [all_images, all_labels])\n input_image = tf.cast(input_image, self.dtype)\n input_label = tf.cast(input_label, tf.int32)\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(dataset.num_examples_per_epoch(subset) *\n min_fraction_of_examples_in_queue)\n raw_images, raw_labels = tf.train.shuffle_batch(\n [input_image, input_label], batch_size=self.batch_size,\n capacity=min_queue_examples + 3 * self.batch_size,\n min_after_dequeue=min_queue_examples)\n\n images = [[] for i in range(self.num_splits)]\n labels = [[] for i in range(self.num_splits)]\n\n # Create a list of size batch_size, each containing one image of the\n # batch. Without the unstack call, raw_images[i] would still access the\n # same image via a strided_slice op, but would be slower.\n raw_images = tf.unstack(raw_images, axis=0)\n raw_labels = tf.unstack(raw_labels, axis=0)\n for i in xrange(self.batch_size):\n split_index = i % self.num_splits\n # The raw image read from data has the format [depth, height, width]\n # reshape to the format returned by minibatch.\n raw_image = tf.reshape(raw_images[i],\n [dataset.depth, dataset.height, dataset.width])\n raw_image = tf.transpose(raw_image, [1, 2, 0])\n image = self.preprocess(raw_image)\n images[split_index].append(image)\n\n labels[split_index].append(raw_labels[i])\n\n for split_index in xrange(self.num_splits):\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.parallel_stack(labels[split_index])\n return images, labels\n\n\nclass Cifar100ImagePreprocessor(BaseImagePreprocessor):\n \"\"\"Preprocessor for Cifar100 input images.\"\"\"\n\n def _distort_image(self, image):\n \"\"\"Distort one image for training a network.\n\n Adopted the standard data augmentation scheme that is widely used for\n this dataset: the images are first zero-padded with 4 pixels on each side,\n then randomly cropped to again produce distorted images; half of the images\n are then horizontally mirrored.\n\n Args:\n image: input image.\n Returns:\n distorted image.\n \"\"\"\n image = tf.image.resize_image_with_crop_or_pad(\n image, self.height + 8, self.width + 8)\n distorted_image = tf.random_crop(image,\n [self.height, self.width, self.depth])\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n if self.summary_verbosity >= 3:\n tf.summary.image('distorted_image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def _eval_image(self, image):\n \"\"\"Get the image for model evaluation.\"\"\"\n distorted_image = tf.image.resize_image_with_crop_or_pad(\n image, self.width, self.height)\n if self.summary_verbosity >= 3:\n tf.summary.image('cropped.image', tf.expand_dims(distorted_image, 0))\n return distorted_image\n\n def preprocess(self, raw_image):\n \"\"\"Preprocessing raw image.\"\"\"\n if self.summary_verbosity >= 3:\n tf.summary.image('raw.image', tf.expand_dims(raw_image, 0))\n if self.train and self.distortions:\n image = self._distort_image(raw_image)\n else:\n image = self._eval_image(raw_image)\n normalized = normalized_image(image)\n return tf.cast(normalized, self.dtype)\n\n def minibatch(self,\n dataset,\n subset,\n params,\n shift_ratio=-1):\n # TODO(jsimsa): Implement datasets code path\n del shift_ratio, params\n with tf.name_scope('batch_processing'):\n all_images, all_labels = dataset.read_data_files(subset)\n all_images = tf.constant(all_images)\n all_labels = tf.constant(all_labels)\n input_image, input_label = tf.train.slice_input_producer(\n [all_images, all_labels])\n input_image = tf.cast(input_image, self.dtype)\n input_label = tf.cast(input_label, tf.int32)\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(dataset.num_examples_per_epoch(subset) *\n min_fraction_of_examples_in_queue)\n raw_images, raw_labels = tf.train.shuffle_batch(\n [input_image, input_label], batch_size=self.batch_size,\n capacity=min_queue_examples + 3 * self.batch_size,\n min_after_dequeue=min_queue_examples)\n\n images = [[] for i in range(self.num_splits)]\n labels = [[] for i in range(self.num_splits)]\n\n # Create a list of size batch_size, each containing one image of the\n # batch. Without the unstack call, raw_images[i] would still access the\n # same image via a strided_slice op, but would be slower.\n raw_images = tf.unstack(raw_images, axis=0)\n raw_labels = tf.unstack(raw_labels, axis=0)\n for i in xrange(self.batch_size):\n split_index = i % self.num_splits\n # The raw image read from data has the format [depth, height, width]\n # reshape to the format returned by minibatch.\n raw_image = tf.reshape(raw_images[i],\n [dataset.depth, dataset.height, dataset.width])\n raw_image = tf.transpose(raw_image, [1, 2, 0])\n image = self.preprocess(raw_image)\n images[split_index].append(image)\n\n labels[split_index].append(raw_labels[i])\n\n for split_index in xrange(self.num_splits):\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.parallel_stack(labels[split_index])\n return images, labels\n\n\nclass COCOPreprocessor(BaseImagePreprocessor):\n \"\"\"Preprocessor for COCO dataset input images, boxes, and labels.\"\"\"\n\n def minibatch(self,\n dataset,\n subset,\n params,\n shift_ratio=-1):\n del shift_ratio # Not used when using datasets instead of data_flow_ops\n with tf.name_scope('batch_processing'):\n ds = self.create_dataset(\n self.batch_size, self.num_splits, self.batch_size_per_split,\n dataset, subset, self.train, params.datasets_repeat_cached_sample)\n ds_iterator = self.create_iterator(ds)\n\n # Training data: 4 tuple\n # Validation data: 5 tuple\n # See get_input_shapes in models/ssd_model.py for details.\n input_len = 4 if subset == 'train' else 5\n input_lists = [[None for _ in range(self.num_splits)]\n for _ in range(input_len)]\n for d in xrange(self.num_splits):\n input_list = ds_iterator.get_next()\n for i in range(input_len):\n input_lists[i][d] = input_list[i]\n return input_lists\n\n def preprocess(self, data):\n try:\n import ssd_dataloader # pylint: disable=g-import-not-at-top\n import ssd_constants # pylint: disable=g-import-not-at-top\n from object_detection.core import preprocessor # pylint: disable=g-import-not-at-top\n except ImportError:\n raise ImportError('To use the COCO dataset, you must clone the '\n 'repo https://github.com/tensorflow/models and add '\n 'tensorflow/models and tensorflow/models/research to '\n 'the PYTHONPATH, and compile the protobufs by '\n 'following https://github.com/tensorflow/models/blob/'\n 'master/research/object_detection/g3doc/installation.md'\n '#protobuf-compilation')\n image_buffer = data['image_buffer']\n boxes = data['groundtruth_boxes']\n classes = tf.reshape(data['groundtruth_classes'], [-1, 1])\n source_id = tf.string_to_number(data['source_id'])\n raw_shape = data['raw_shape']\n\n ssd_encoder = ssd_dataloader.Encoder()\n\n # Only 80 of the 90 COCO classes are used.\n class_map = tf.convert_to_tensor(ssd_constants.CLASS_MAP)\n classes = tf.gather(class_map, classes)\n classes = tf.cast(classes, dtype=tf.float32)\n\n if self.train:\n image, boxes, classes = ssd_dataloader.ssd_decode_and_crop(\n image_buffer, boxes, classes, raw_shape)\n # ssd_crop resizes and returns image of dtype float32 and does not change\n # its range (i.e., value in between 0--255). Divide by 255. converts it\n # to [0, 1] range. Not doing this before cropping to avoid dtype cast\n # (which incurs additional memory copy).\n image /= 255.\n\n image, boxes = preprocessor.random_horizontal_flip(\n image=image, boxes=boxes)\n # Random horizontal flip probability is 50%\n # See https://github.com/tensorflow/models/blob/master/research/object_detection/core/preprocessor.py # pylint: disable=line-too-long\n mlperf.logger.log(key=mlperf.tags.RANDOM_FLIP_PROBABILITY, value=0.5)\n\n image = tf.cast(image, self.dtype)\n\n encoded_returns = ssd_encoder.encode_labels(boxes, classes)\n encoded_classes, encoded_boxes, num_matched_boxes = encoded_returns\n\n # Shape of image: [width, height, channel]\n # Shape of encoded_boxes: [NUM_SSD_BOXES, 4]\n # Shape of encoded_classes: [NUM_SSD_BOXES, 1]\n # Shape of num_matched_boxes: [1]\n return (image, encoded_boxes, encoded_classes, num_matched_boxes)\n\n else:\n image = tf.image.decode_jpeg(image_buffer)\n image = tf.image.resize_images(\n image, size=(ssd_constants.IMAGE_SIZE, ssd_constants.IMAGE_SIZE))\n # resize_image returns image of dtype float32 and does not change its\n # range. Divide by 255 to convert image to [0, 1] range.\n image /= 255.\n\n image = ssd_dataloader.normalize_image(image)\n image = tf.cast(image, self.dtype)\n\n def trim_and_pad(inp_tensor):\n \"\"\"Limit the number of boxes, and pad if necessary.\"\"\"\n inp_tensor = inp_tensor[:ssd_constants.MAX_NUM_EVAL_BOXES]\n num_pad = ssd_constants.MAX_NUM_EVAL_BOXES - tf.shape(inp_tensor)[0]\n inp_tensor = tf.pad(inp_tensor, [[0, num_pad], [0, 0]])\n return tf.reshape(inp_tensor, [ssd_constants.MAX_NUM_EVAL_BOXES,\n inp_tensor.get_shape()[1]])\n\n boxes, classes = trim_and_pad(boxes), trim_and_pad(classes)\n\n # Shape of boxes: [MAX_NUM_EVAL_BOXES, 4]\n # Shape of classes: [MAX_NUM_EVAL_BOXES, 1]\n # Shape of source_id: [] (scalar tensor)\n # Shape of raw_shape: [3]\n return (image, boxes, classes, source_id, raw_shape)\n\n def create_dataset(self,\n batch_size,\n num_splits,\n batch_size_per_split,\n dataset,\n subset,\n train,\n datasets_repeat_cached_sample,\n num_threads=None,\n datasets_use_caching=False,\n datasets_parallel_interleave_cycle_length=None,\n datasets_sloppy_parallel_interleave=False,\n datasets_parallel_interleave_prefetch=None):\n \"\"\"Creates a dataset for the benchmark.\"\"\"\n try:\n import ssd_dataloader # pylint: disable=g-import-not-at-top\n except ImportError:\n raise ImportError('To use the COCO dataset, you must clone the '\n 'repo https://github.com/tensorflow/models and add '\n 'tensorflow/models and tensorflow/models/research to '\n 'the PYTHONPATH, and compile the protobufs by '\n 'following https://github.com/tensorflow/models/blob/'\n 'master/research/object_detection/g3doc/installation.md'\n '#protobuf-compilation')\n assert self.supports_datasets()\n\n glob_pattern = dataset.tf_record_pattern(subset)\n ds = tf.data.TFRecordDataset.list_files(glob_pattern, shuffle=train)\n # TODO(haoyuzhang): Enable map+filter fusion after cl/218399112 in release\n # options = tf.data.Options()\n # options.experimental_optimization = tf.data.experimental.OptimizationOptions() # pylint: disable=line-too-long\n # options.experimental_optimization.map_and_filter_fusion = True\n # ds = ds.with_options(options)\n\n ds = ds.apply(\n tf.data.experimental.parallel_interleave(\n tf.data.TFRecordDataset,\n cycle_length=datasets_parallel_interleave_cycle_length or 10,\n sloppy=datasets_sloppy_parallel_interleave))\n mlperf.logger.log(key=mlperf.tags.INPUT_ORDER)\n if datasets_repeat_cached_sample:\n # Repeat a single sample element indefinitely to emulate memory-speed IO.\n ds = ds.take(1).cache().repeat()\n ds = ds.prefetch(buffer_size=batch_size)\n if datasets_use_caching:\n ds = ds.cache()\n if train:\n ds = ds.apply(tf.data.experimental.shuffle_and_repeat(buffer_size=10000))\n mlperf.logger.log(key=mlperf.tags.INPUT_SHARD, value=10000)\n mlperf.logger.log(key=mlperf.tags.INPUT_ORDER)\n else:\n ds = ds.repeat()\n\n ds = ds.map(ssd_dataloader.ssd_parse_example_proto, num_parallel_calls=64)\n ds = ds.filter(\n lambda data: tf.greater(tf.shape(data['groundtruth_boxes'])[0], 0))\n ds = ds.apply(\n tf.data.experimental.map_and_batch(\n map_func=self.preprocess,\n batch_size=batch_size_per_split,\n num_parallel_batches=num_splits,\n drop_remainder=train))\n ds = ds.prefetch(buffer_size=num_splits)\n if num_threads:\n ds = threadpool.override_threadpool(\n ds,\n threadpool.PrivateThreadPool(\n num_threads, display_name='input_pipeline_thread_pool'))\n return ds\n\n def supports_datasets(self):\n return True\n\n\nclass TestImagePreprocessor(BaseImagePreprocessor):\n \"\"\"Preprocessor used for testing.\n\n set_fake_data() sets which images and labels will be output by minibatch(),\n and must be called before minibatch(). This allows tests to easily specify\n a set of images to use for training, without having to create any files.\n\n Queue runners must be started for this preprocessor to work.\n \"\"\"\n\n def __init__(self,\n batch_size,\n output_shapes,\n num_splits,\n dtype,\n train=None,\n distortions=None,\n resize_method=None,\n shift_ratio=0,\n summary_verbosity=0,\n distort_color_in_yiq=False,\n fuse_decode_and_crop=False,\n match_mlperf=False):\n super(TestImagePreprocessor, self).__init__(\n batch_size, output_shapes, num_splits, dtype, train, distortions,\n resize_method, shift_ratio, summary_verbosity=summary_verbosity,\n distort_color_in_yiq=distort_color_in_yiq,\n fuse_decode_and_crop=fuse_decode_and_crop, match_mlperf=match_mlperf)\n self.expected_subset = None\n\n def set_fake_data(self, fake_images, fake_labels):\n assert len(fake_images.shape) == 4\n assert len(fake_labels.shape) == 1\n num_images = fake_images.shape[0]\n assert num_images == fake_labels.shape[0]\n assert num_images % self.batch_size == 0\n self.fake_images = fake_images\n self.fake_labels = fake_labels\n\n def minibatch(self,\n dataset,\n subset,\n params,\n shift_ratio=0):\n \"\"\"Get test image batches.\"\"\"\n del dataset, params\n if (not hasattr(self, 'fake_images') or\n not hasattr(self, 'fake_labels')):\n raise ValueError('Must call set_fake_data() before calling minibatch '\n 'on TestImagePreprocessor')\n if self.expected_subset is not None:\n assert subset == self.expected_subset\n\n shift_ratio = shift_ratio or self.shift_ratio\n fake_images = cnn_util.roll_numpy_batches(self.fake_images, self.batch_size,\n shift_ratio)\n fake_labels = cnn_util.roll_numpy_batches(self.fake_labels, self.batch_size,\n shift_ratio)\n\n with tf.name_scope('batch_processing'):\n image_slice, label_slice = tf.train.slice_input_producer(\n [fake_images, fake_labels],\n shuffle=False,\n name='image_slice')\n raw_images, raw_labels = tf.train.batch(\n [image_slice, label_slice], batch_size=self.batch_size,\n name='image_batch')\n images = [[] for _ in range(self.num_splits)]\n labels = [[] for _ in range(self.num_splits)]\n for i in xrange(self.batch_size):\n split_index = i % self.num_splits\n raw_image = tf.cast(raw_images[i], self.dtype)\n images[split_index].append(raw_image)\n labels[split_index].append(raw_labels[i])\n for split_index in xrange(self.num_splits):\n images[split_index] = tf.parallel_stack(images[split_index])\n labels[split_index] = tf.parallel_stack(labels[split_index])\n\n normalized = [normalized_image(part) for part in images]\n return [[tf.cast(part, self.dtype) for part in normalized], labels]\n\n\nclass LibrispeechPreprocessor(InputPreprocessor):\n \"\"\"Preprocessor for librispeech class for all image model preprocessors.\"\"\"\n\n def __init__(self, batch_size, output_shapes, num_splits, dtype, train,\n **kwargs):\n del kwargs\n super(LibrispeechPreprocessor, self).__init__(batch_size, output_shapes)\n self.num_splits = num_splits\n self.dtype = dtype\n self.is_train = train\n if self.batch_size % self.num_splits != 0:\n raise ValueError(('batch_size must be a multiple of num_splits: '\n 'batch_size %d, num_splits: %d') % (self.batch_size,\n self.num_splits))\n self.batch_size_per_split = self.batch_size // self.num_splits\n\n def create_dataset(self,\n batch_size,\n num_splits,\n batch_size_per_split,\n dataset,\n subset,\n train,\n datasets_repeat_cached_sample,\n num_threads=None,\n datasets_use_caching=False,\n datasets_parallel_interleave_cycle_length=None,\n datasets_sloppy_parallel_interleave=False,\n datasets_parallel_interleave_prefetch=None):\n \"\"\"Creates a dataset for the benchmark.\"\"\"\n # TODO(laigd): currently the only difference between this and the one in\n # BaseImagePreprocessor is, this uses map() and padded_batch() while the\n # latter uses tf.data.experimental.map_and_batch(). Try to merge them.\n assert self.supports_datasets()\n glob_pattern = dataset.tf_record_pattern(subset)\n file_names = gfile.Glob(glob_pattern)\n if not file_names:\n raise ValueError('Found no files in --data_dir matching: {}'\n .format(glob_pattern))\n ds = tf.data.TFRecordDataset.list_files(file_names, shuffle=train)\n ds = ds.apply(\n tf.data.experimental.parallel_interleave(\n tf.data.TFRecordDataset,\n cycle_length=datasets_parallel_interleave_cycle_length or 10,\n sloppy=datasets_sloppy_parallel_interleave,\n prefetch_input_elements=datasets_parallel_interleave_prefetch))\n if datasets_repeat_cached_sample:\n # Repeat a single sample element indefinitely to emulate memory-speed IO.\n ds = ds.take(1).cache().repeat()\n counter = tf.data.Dataset.range(batch_size)\n counter = counter.repeat()\n ds = tf.data.Dataset.zip((ds, counter))\n ds = ds.prefetch(buffer_size=batch_size)\n if datasets_use_caching:\n ds = ds.cache()\n if train:\n ds = ds.apply(tf.data.experimental.shuffle_and_repeat(buffer_size=10000))\n else:\n ds = ds.repeat()\n ds = ds.map(map_func=self.parse_and_preprocess,\n num_parallel_calls=batch_size_per_split*num_splits)\n ds = ds.padded_batch(\n batch_size=batch_size_per_split,\n padded_shapes=tuple([\n tf.TensorShape(output_shape[1:])\n for output_shape in self.output_shapes\n ]),\n drop_remainder=True)\n ds = ds.prefetch(buffer_size=num_splits)\n if num_threads:\n ds = threadpool.override_threadpool(\n ds,\n threadpool.PrivateThreadPool(\n num_threads, display_name='input_pipeline_thread_pool'))\n return ds\n\n def minibatch(self, dataset, subset, params, shift_ratio=-1):\n assert params.use_datasets\n # TODO(laigd): unify this with CNNModel's minibatch()\n # TODO(laigd): in distributed mode we use shift_ratio so different workers\n # won't work on same inputs, so we should respect that.\n del shift_ratio\n with tf.name_scope('batch_processing'):\n ds = self.create_dataset(\n self.batch_size,\n self.num_splits,\n self.batch_size_per_split,\n dataset,\n subset,\n self.is_train,\n datasets_repeat_cached_sample=params.datasets_repeat_cached_sample,\n num_threads=params.datasets_num_private_threads,\n datasets_use_caching=params.datasets_use_caching,\n datasets_parallel_interleave_cycle_length=(\n params.datasets_parallel_interleave_cycle_length),\n datasets_sloppy_parallel_interleave=(\n params.datasets_sloppy_parallel_interleave),\n datasets_parallel_interleave_prefetch=(\n params.datasets_parallel_interleave_prefetch))\n ds_iterator = self.create_iterator(ds)\n\n # The four lists are: input spectrogram feature, labels, input lengths,\n # label lengths\n input_lists = [[None for _ in range(self.num_splits)] for _ in range(4)]\n for d in xrange(self.num_splits):\n input_list = ds_iterator.get_next()\n for i in range(4):\n input_lists[i][d] = input_list[i]\n\n assert self.output_shapes == [\n input_lists[i][0].shape.as_list() for i in range(4)\n ]\n return tuple(input_lists)\n\n def supports_datasets(self):\n return True\n\n def parse_and_preprocess(self, value, batch_position):\n \"\"\"Parse an TFRecord.\"\"\"\n del batch_position\n assert self.supports_datasets()\n context_features = {\n 'labels': tf.VarLenFeature(dtype=tf.int64),\n 'input_length': tf.FixedLenFeature([], dtype=tf.int64),\n 'label_length': tf.FixedLenFeature([], dtype=tf.int64),\n }\n sequence_features = {\n 'features': tf.FixedLenSequenceFeature([161], dtype=tf.float32)\n }\n context_parsed, sequence_parsed = tf.parse_single_sequence_example(\n serialized=value,\n context_features=context_features,\n sequence_features=sequence_features,\n )\n\n return [\n # Input\n tf.expand_dims(sequence_parsed['features'], axis=2),\n # Label\n tf.cast(\n tf.reshape(\n tf.sparse_tensor_to_dense(context_parsed['labels']), [-1]),\n dtype=tf.int32),\n # Input length\n tf.cast(\n tf.reshape(context_parsed['input_length'], [1]),\n dtype=tf.int32),\n # Label length\n tf.cast(\n tf.reshape(context_parsed['label_length'], [1]),\n dtype=tf.int32),\n ]\n"
] |
[
[
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"tensorflow.FixedLenFeature",
"tensorflow.image.random_contrast",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.image.random_saturation",
"tensorflow.image.decode_and_crop_jpeg",
"tensorflow.data.experimental.map_and_batch",
"tensorflow.pad",
"tensorflow.string_to_number",
"tensorflow.train.batch",
"tensorflow.contrib.data.python.ops.threadpool.PrivateThreadPool",
"tensorflow.image.random_hue",
"tensorflow.image.random_flip_left_right",
"tensorflow.data.Iterator.from_string_handle",
"tensorflow.data.experimental.parallel_interleave",
"tensorflow.summary.image",
"tensorflow.python.framework.function.Defun",
"tensorflow.subtract",
"tensorflow.data.Dataset.zip",
"tensorflow.gather",
"tensorflow.contrib.image.python.ops.distort_image_ops.random_hsv_in_yiq",
"tensorflow.name_scope",
"tensorflow.parse_single_example",
"tensorflow.parse_single_sequence_example",
"tensorflow.train.shuffle_batch",
"tensorflow.logging.fatal",
"tensorflow.image.decode_jpeg",
"tensorflow.TensorShape",
"tensorflow.image.random_brightness",
"tensorflow.unstack",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.sparse_tensor_to_dense",
"tensorflow.image.extract_jpeg_shape",
"tensorflow.FixedLenSequenceFeature",
"tensorflow.python.layers.utils.smart_cond",
"tensorflow.python.data.ops.multi_device_iterator_ops.MultiDeviceIterator",
"tensorflow.data.Dataset.range",
"tensorflow.VarLenFeature",
"tensorflow.split",
"tensorflow.add_to_collection",
"tensorflow.parallel_stack",
"tensorflow.clip_by_value",
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.multiply",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.slice",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.python.platform.gfile.Glob",
"tensorflow.expand_dims",
"tensorflow.random_crop",
"tensorflow.data.TFRecordDataset.list_files",
"tensorflow.image.convert_image_dtype",
"tensorflow.train.slice_input_producer",
"tensorflow.data.experimental.shuffle_and_repeat"
]
] |
ChrisDemahy/word-rnn-tensorflow
|
[
"7dbd7f4c9e84c1d374391d422dfa11f6ffe5ae7e"
] |
[
"utils.py"
] |
[
"# -*- coding: utf-8 -*-\r\nimport os\r\nimport codecs\r\nimport collections\r\nfrom six.moves import cPickle\r\nimport numpy as np\r\nimport re\r\nimport itertools\r\n\r\nclass TextLoader():\r\n def __init__(self, data_dir, batch_size, seq_length, encoding=None):\r\n self.data_dir = data_dir\r\n self.batch_size = batch_size\r\n self.seq_length = seq_length\r\n\r\n input_file = os.path.join(data_dir, \"input.txt\")\r\n vocab_file = os.path.join(data_dir, \"vocab.pkl\")\r\n tensor_file = os.path.join(data_dir, \"data.npy\")\r\n\r\n # Let's not read voca and data from file. We many change them.\r\n if True or not (os.path.exists(vocab_file) and os.path.exists(tensor_file)):\r\n print(\"reading text file\")\r\n self.preprocess(input_file, vocab_file, tensor_file, encoding)\r\n else:\r\n print(\"loading preprocessed files\")\r\n self.load_preprocessed(vocab_file, tensor_file)\r\n self.create_batches()\r\n self.reset_batch_pointer()\r\n\r\n def clean_str(self, string):\r\n \"\"\"\r\n Tokenization/string cleaning for all datasets except for SST.\r\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data\r\n \"\"\"\r\n string = re.sub(r\"[^가-힣A-Za-z0-9(),!?\\'\\`]\", \" \", string)\r\n string = re.sub(r\"\\'s\", \" \\'s\", string)\r\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\r\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\r\n string = re.sub(r\"\\'re\", \" \\'re\", string)\r\n string = re.sub(r\"\\'d\", \" \\'d\", string)\r\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\r\n string = re.sub(r\",\", \" , \", string)\r\n string = re.sub(r\"!\", \" ! \", string)\r\n string = re.sub(r\"\\(\", \" \\( \", string)\r\n string = re.sub(r\"\\)\", \" \\) \", string)\r\n string = re.sub(r\"\\?\", \" \\? \", string)\r\n string = re.sub(r\"\\s{2,}\", \" \", string)\r\n return string.strip().lower()\r\n\r\n def build_vocab(self, sentences):\r\n \"\"\"\r\n Builds a vocabulary mapping from word to index based on the sentences.\r\n Returns vocabulary mapping and inverse vocabulary mapping.\r\n \"\"\"\r\n # Build vocabulary\r\n word_counts = collections.Counter(sentences)\r\n # Mapping from index to word\r\n vocabulary_inv = [x[0] for x in word_counts.most_common()]\r\n vocabulary_inv = list(sorted(vocabulary_inv))\r\n # Mapping from word to index\r\n vocabulary = {x: i for i, x in enumerate(vocabulary_inv)}\r\n return [vocabulary, vocabulary_inv]\r\n\r\n def preprocess(self, input_file, vocab_file, tensor_file, encoding):\r\n with codecs.open(input_file, \"r\", encoding=encoding) as f:\r\n data = f.read()\r\n\r\n # Optional text cleaning or make them lower case, etc.\r\n #data = self.clean_str(data)\r\n x_text = data.split()\r\n\r\n self.vocab, self.words = self.build_vocab(x_text)\r\n self.vocab_size = len(self.words)\r\n\r\n with open(vocab_file, 'wb') as f:\r\n cPickle.dump(self.words, f)\r\n\r\n #The same operation like this [self.vocab[word] for word in x_text]\r\n # index of words as our basic data\r\n self.tensor = np.array(list(map(self.vocab.get, x_text)))\r\n # Save the data to data.npy\r\n np.save(tensor_file, self.tensor)\r\n\r\n def load_preprocessed(self, vocab_file, tensor_file):\r\n with open(vocab_file, 'rb') as f:\r\n self.words = cPickle.load(f)\r\n self.vocab_size = len(self.words)\r\n self.vocab = dict(zip(self.words, range(len(self.words))))\r\n self.tensor = np.load(tensor_file)\r\n self.num_batches = int(self.tensor.size / (self.batch_size *\r\n self.seq_length))\r\n\r\n def create_batches(self):\r\n self.num_batches = int(self.tensor.size / (self.batch_size *\r\n self.seq_length))\r\n if self.num_batches==0:\r\n assert False, \"Not enough data. Make seq_length and batch_size small.\"\r\n\r\n self.tensor = self.tensor[:self.num_batches * self.batch_size * self.seq_length]\r\n xdata = self.tensor\r\n ydata = np.copy(self.tensor)\r\n\r\n ydata[:-1] = xdata[1:]\r\n ydata[-1] = xdata[0]\r\n self.x_batches = np.split(xdata.reshape(self.batch_size, -1), self.num_batches, 1)\r\n self.y_batches = np.split(ydata.reshape(self.batch_size, -1), self.num_batches, 1)\r\n\r\n def next_batch(self):\r\n x, y = self.x_batches[self.pointer], self.y_batches[self.pointer]\r\n self.pointer += 1\r\n return x, y\r\n\r\n def reset_batch_pointer(self):\r\n self.pointer = 0\r\n"
] |
[
[
"numpy.load",
"numpy.copy",
"numpy.save"
]
] |
icyda17/MNT
|
[
"f88a0a199e79d6d4201ec724478c710380e71ea3"
] |
[
"model/model.py"
] |
[
"import math\nimport torch\nimport random\nfrom torch import nn\nfrom torch import optim\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.utils import clip_grad_norm_\nimport numpy as np\nimport time\n# from reporter import Reporter\nimport os\nfrom tqdm import tqdm\nfrom queue import PriorityQueue\nimport operator\n\n\nSOS_token = 2\nEOS_token = 3\nMAX_LENGTH = 100\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_size, embed_size, hidden_size,\n n_layers, dropout):\n super(Encoder, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.embed_size = embed_size\n self.embed = nn.Embedding(input_size, embed_size)\n self.gru = nn.GRU(embed_size, hidden_size, n_layers,\n dropout=dropout, bidirectional=True)\n\n def forward(self, src, hidden=None):\n # src: TxB -> embed: TxBxEmbed size (input_size)\n embedded = self.embed(src)\n # out: TxBx(hidden_size*n_layers) , hidden: (2*n_layers)xBxhidden_size\n outputs, hidden = self.gru(embedded, hidden)\n # sum bidirectional outputs\n outputs = (outputs[:, :, :self.hidden_size] +\n outputs[:, :, self.hidden_size:])\n return outputs, hidden\n\n\nclass Attention(nn.Module):\n def __init__(self, hidden_size):\n super(Attention, self).__init__()\n self.hidden_size = hidden_size\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.rand(hidden_size))\n stdv = 1. / math.sqrt(self.v.size(0))\n self.v.data.uniform_(-stdv, stdv)\n\n def forward(self, hidden, encoder_outputs):\n timestep = encoder_outputs.size(0)\n h = hidden.repeat(timestep, 1, 1).transpose(0, 1)\n encoder_outputs = encoder_outputs.transpose(0, 1) # [B*T*H]\n attn_energies = self.score(h, encoder_outputs)\n return F.softmax(attn_energies, dim=1).unsqueeze(1)\n\n def score(self, hidden, encoder_outputs):\n # [B*T*2H]->[B*T*H]\n energy = F.relu(self.attn(torch.cat([hidden, encoder_outputs], 2)))\n energy = energy.transpose(1, 2) # [B*H*T]\n v = self.v.repeat(encoder_outputs.size(0), 1).unsqueeze(1) # [B*1*H]\n energy = torch.bmm(v, energy) # [B*1*T]\n return energy.squeeze(1) # [B*T]\n\n\nclass Decoder(nn.Module):\n def __init__(self, embed_size, hidden_size, output_size,\n n_layers, dropout):\n super(Decoder, self).__init__()\n self.embed_size = embed_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n\n self.embed = nn.Embedding(output_size, embed_size)\n self.dropout = nn.Dropout(dropout, inplace=True)\n self.attention = Attention(hidden_size)\n self.gru = nn.GRU(hidden_size + embed_size, hidden_size,\n n_layers)\n self.out = nn.Linear(hidden_size * 2, output_size)\n\n def forward(self, input, last_hidden, encoder_outputs):\n # Get the embedding of the current input word (last output word)\n embedded = self.embed(input).unsqueeze(0) # (1,B,H)\n embedded = self.dropout(embedded)\n # Calculate attention weights and apply to encoder outputs\n attn_weights = self.attention(\n last_hidden[-1], encoder_outputs) # (B,1,N)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # (B,1,N)\n context = context.transpose(0, 1) # (1,B,N)\n # Combine embedded input word and attended context, run through RNN\n rnn_input = torch.cat([embedded, context], 2)\n output, hidden = self.gru(rnn_input, last_hidden)\n output = output.squeeze(0) # (1,B,N) -> (B,N)\n context = context.squeeze(0)\n output = self.out(torch.cat([output, context], 1))\n output = F.log_softmax(output, dim=1)\n return output, hidden, attn_weights\n\n\nclass Seq2Seq(nn.Module):\n def __init__(self, encoder, decoder, device, teacher_forcing_ratio):\n super(Seq2Seq, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.device = device\n self.teacher_forcing_ratio = teacher_forcing_ratio\n\n def forward(self, src, trg):\n try:\n max_len = trg.size(0)\n\n except:\n max_len = trg\n self.teacher_forcing_ratio = 1\n\n batch_size = src.size(1)\n vocab_size = self.decoder.output_size\n outputs = Variable(torch.zeros(max_len, batch_size, vocab_size)).to(\n self.device) # T*B*V\n\n encoder_output, hidden = self.encoder(src) # T*B*H, 2*n_layersxBxH\n hidden = hidden[:self.decoder.n_layers] # n_decoder_layersxBxH\n try:\n output = Variable(trg.data[0, :]) # sos # B\n except:\n output = Variable(torch.tensor(np.array([2]))).to(\n self.device) # vi_vocab.stoi['<sos>']\n\n for t in range(1, max_len):\n output, hidden, attn_weights = self.decoder(\n output, hidden, encoder_output) # output: BxV, hidden: 1xBxH, encoder: TxBxH\n outputs[t] = output\n if self.teacher_forcing_ratio == 1:\n is_teacher = False\n else:\n is_teacher = random.random() < self.teacher_forcing_ratio\n top1 = output.data.max(1)[1]\n output = Variable(\n trg.data[t] if is_teacher else top1).to(self.device)\n return outputs\n\n def decode(self, src, trg, beam_size, method='beam-search'):\n # [27, 32]=> =>[27, 32, 512],[4, 32, 512]\n encoder_output, hidden = self.encoder(src)\n hidden = hidden[:self.decoder.n_layers] # [4, 32, 512][1, 32, 512]\n if method == 'beam-search':\n return self.beam_decode(trg, hidden, beam_size, encoder_output)\n else:\n return self.greedy_decode(trg, hidden, encoder_output)\n\n def greedy_decode(self, trg, decoder_hidden, encoder_outputs, ):\n '''\n :param target_tensor: target indexes tensor of shape [B, T] where B is the batch size and T is the maximum length of the output sentence\n :param decoder_hidden: input tensor of shape [1, B, H] for start of the decoding\n :param encoder_outputs: if you are using attention mechanism you can pass encoder outputs, [T, B, H] where T is the maximum length of input sentence\n :return: decoded_batch\n '''\n seq_len, batch_size = trg.size()\n decoded_batch = torch.zeros((batch_size, seq_len))\n # decoder_input = torch.LongTensor([[EN.vocab.stoi['<sos>']] for _ in range(batch_size)]).cuda()\n decoder_input = Variable(trg.data[0, :]).to(self.device) # sos\n print(decoder_input.shape)\n for t in range(seq_len):\n decoder_output, decoder_hidden, _ = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n\n topv, topi = decoder_output.data.topk(\n 1) # [32, 10004] get candidates\n topi = topi.view(-1)\n decoded_batch[:, t] = topi\n\n decoder_input = topi.detach().view(-1)\n\n return decoded_batch\n\n # @timeit\n def beam_decode(self, target_tensor, decoder_hiddens, beam_size, encoder_outputs=None):\n '''\n :param target_tensor: target indexes tensor of shape [B, T] where B is the batch size and T is the maximum length of the output sentence\n :param decoder_hiddens: input tensor of shape [1, B, H] for start of the decoding\n :param encoder_outputs: if you are using attention mechanism you can pass encoder outputs, [T, B, H] where T is the maximum length of input sentence\n :return: decoded_batch\n '''\n if isinstance(target_tensor, int):\n batch_size = decoder_hiddens.size(1)\n else:\n target_tensor = target_tensor.permute(1, 0)\n batch_size = target_tensor.size(0)\n beam_size = beam_size\n topk = 1 # how many sentence do you want to generate\n decoded_batch = []\n\n # decoding goes sentence by sentence\n for idx in range(batch_size): # batch_size\n if isinstance(decoder_hiddens, tuple): # LSTM case\n decoder_hidden = (\n decoder_hiddens[0][:, idx, :].unsqueeze(0), decoder_hiddens[1][:, idx, :].unsqueeze(0))\n else:\n decoder_hidden = decoder_hiddens[:, idx, :].unsqueeze(\n 0) # [1, B, H]=>[1,H]=>[1,1,H]\n encoder_output = encoder_outputs[:, idx, :].unsqueeze(\n 1) # [T,B,H]=>[T,H]=>[T,1,H]\n\n # Start with the start of the sentence token\n decoder_input = torch.LongTensor([SOS_token]).to(self.device)\n\n # Number of sentence to generate\n endnodes = []\n number_required = min((topk + 1), topk - len(endnodes))\n\n # starting node - hidden vector, previous node, word id, logp, length\n node = BeamSearchNode(decoder_hidden, None, decoder_input, 0, 1)\n nodes = PriorityQueue()\n\n # start the queue\n nodes.put((-node.eval(), node))\n qsize = 1\n\n # start beam search\n while True:\n # give up when decoding takes too long\n if qsize > 2000:\n break\n\n # fetch the best node\n score, n = nodes.get()\n # print('--best node seqs len {} '.format(n.leng))\n decoder_input = n.wordid\n decoder_hidden = n.h\n\n if n.wordid.item() == EOS_token and n.prevNode != None:\n endnodes.append((score, n))\n # if we reached maximum # of sentences required\n if len(endnodes) >= number_required:\n break\n else:\n continue\n\n # decode for one step using decoder\n decoder_output, decoder_hidden, _ = self.decoder(\n decoder_input, decoder_hidden, encoder_output)\n\n # PUT HERE REAL BEAM SEARCH OF TOP\n log_prob, indexes = torch.topk(decoder_output, beam_size)\n nextnodes = []\n\n for new_k in range(beam_size):\n decoded_t = indexes[0][new_k].view(-1)\n log_p = log_prob[0][new_k].item()\n\n node = BeamSearchNode(\n decoder_hidden, n, decoded_t, n.logp + log_p, n.leng + 1)\n score = -node.eval()\n nextnodes.append((score, node))\n\n # put them into queue\n for i in range(len(nextnodes)):\n score, nn = nextnodes[i]\n nodes.put((score, nn))\n # increase qsize\n qsize += len(nextnodes) - 1\n\n # choose nbest paths, back trace them\n if len(endnodes) == 0:\n endnodes = [nodes.get() for _ in range(topk)]\n\n utterances = []\n for score, n in sorted(endnodes, key=operator.itemgetter(0)):\n utterance = []\n utterance.append(n.wordid)\n # back trace\n while n.prevNode != None:\n n = n.prevNode\n utterance.append(n.wordid)\n\n utterance = utterance[::-1]\n utterances.append(utterance)\n\n decoded_batch.append(utterances)\n\n return decoded_batch\n\n\nclass BeamSearchNode(object):\n def __init__(self, hiddenstate, previousNode, wordId, logProb, length):\n '''\n :param hiddenstate:\n :param previousNode:\n :param wordId:\n :param logProb:\n :param length:\n '''\n self.h = hiddenstate\n self.prevNode = previousNode\n self.wordid = wordId\n self.logp = logProb\n self.leng = length\n\n def eval(self, alpha=1.0):\n reward = 0\n # Add here a function for shaping a reward\n\n return self.logp / float(self.leng - 1 + 1e-6) + alpha * reward\n\n def __lt__(self, other):\n return self.leng < other.leng\n\n def __gt__(self, other):\n return self.leng > other.leng\n\n\nclass MNTModel():\n def __init__(self, src_size, trg_size, trg_vocab, embed_size, hidden_size, n_layers_encoder, n_layers_decoder, dropout_encoder, dropout_decoder, device, teacher_forcing_ratio, learning_rate, grad_clip, patience, min_delta):\n print(\"[!] Instantiating models...\")\n self.trg_size = trg_size\n self.trg_vocab = trg_vocab\n self.encoder = Encoder(src_size, embed_size, hidden_size,\n n_layers=n_layers_encoder, dropout=dropout_encoder)\n self.decoder = Decoder(embed_size, hidden_size, self.trg_size,\n n_layers=n_layers_decoder, dropout=dropout_decoder)\n self.seq2seq = Seq2Seq(self.encoder, self.decoder, device,\n teacher_forcing_ratio).to(device)\n self.optimizer = optim.Adam(\n self.seq2seq.parameters(), lr=learning_rate)\n print(self.seq2seq)\n self.best_val_loss = None\n self.grad_clip = grad_clip\n self.early_stopping = EarlyStopping(patience, min_delta)\n self.device = device\n\n def train_epoch(self, n_epochs, train_iter, val_iter, save_model_path):\n # reporter = Reporter(\"logs\", \"mnt_envi\")\n for e in range(1, n_epochs+1):\n start_time = time.time()\n train_loss = self.train(e, train_iter)\n end_time = time.time()\n val_loss = self.evaluate(val_iter)\n self.early_stopping(val_loss)\n if self.early_stopping.early_stop:\n break\n print((f\"Epoch: {e}, Train loss: {train_loss:.3f}, Val loss: {val_loss:.3f}, \"\n f\"Epoch time = {(end_time - start_time):.3f}s\"))\n # reporter.log_metric(\"val_loss\", float(val_loss), e)\n\n # Save the model if the validation loss is the best we've seen so far.\n if not self.best_val_loss or val_loss < self.best_val_loss:\n print(\"[!] saving model...\")\n if not os.path.isdir(\"save\"):\n os.makedirs(\"save\")\n torch.save({'model_state_dict': self.seq2seq.state_dict(),\n 'epoch': e,\n 'loss': '%5.3f' % val_loss},\n save_model_path)\n self.best_val_loss = val_loss\n\n def train(self, e, train_iter):\n self.seq2seq.train()\n total_loss = 0\n pad = self.trg_vocab.stoi['<pad>']\n with tqdm(train_iter, unit=\"batch\") as tepoch:\n for src, trg in tepoch:\n tepoch.set_description(f\"Epoch {e}\")\n\n src, trg = src.to(self.device), trg.to(self.device) # TxB\n self.optimizer.zero_grad()\n output = self.seq2seq(src, trg)\n loss = F.nll_loss(output[1:].view(-1, self.trg_size),\n trg[1:].contiguous().view(-1),\n ignore_index=pad)\n loss.backward()\n clip_grad_norm_(self.seq2seq.parameters(), self.grad_clip)\n self.optimizer.step()\n\n tepoch.set_postfix(loss=loss.item())\n\n total_loss += loss.item()\n return total_loss/len(train_iter)\n\n def evaluate(self, val_iter):\n with torch.no_grad():\n self.seq2seq.eval()\n pad = self.trg_vocab.stoi['<pad>']\n total_loss = 0\n for idx, (src, trg) in enumerate(val_iter):\n src = src.data.to(self.device)\n trg = trg.data.to(self.device)\n output = self.seq2seq(src, trg)\n loss = F.nll_loss(output[1:].view(-1, self.trg_size),\n trg[1:].contiguous().view(-1),\n ignore_index=pad)\n total_loss += loss.data.item()\n return total_loss / len(val_iter)\n\n def eval(self):\n self.seq2seq.eval()\n\n def lazyload(self, path, device):\n self.seq2seq.load_state_dict(torch.load(\n path, map_location=device)['model_state_dict'])\n\n\nclass EarlyStopping():\n \"\"\"\n Early stopping to stop the training when the loss does not improve after\n certain epochs.\n \"\"\"\n\n def __init__(self, patience, min_delta):\n \"\"\"\n :param patience: how many epochs to wait before stopping when loss is\n not improving\n :param min_delta: minimum difference between new loss and old loss for\n new loss to be considered as an improvement\n \"\"\"\n self.patience = patience\n self.min_delta = min_delta\n self.counter = 0\n self.best_loss = None\n self.early_stop = False\n\n def __call__(self, val_loss):\n if self.best_loss == None:\n self.best_loss = val_loss\n elif self.best_loss - val_loss > self.min_delta:\n self.best_loss = val_loss\n self.counter = 0\n elif self.best_loss - val_loss < self.min_delta:\n self.counter += 1\n print(\n f\"INFO: Early stopping counter {self.counter} of {self.patience}\")\n if self.counter >= self.patience:\n print('INFO: Early stopping')\n self.early_stop = True\n"
] |
[
[
"torch.nn.Dropout",
"torch.nn.functional.softmax",
"torch.LongTensor",
"torch.nn.functional.log_softmax",
"torch.cat",
"torch.zeros",
"torch.load",
"torch.nn.GRU",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.no_grad",
"torch.bmm",
"torch.rand",
"torch.topk",
"numpy.array",
"torch.autograd.Variable"
]
] |
jasonkaye/libdlr
|
[
"7dcccc9713615e1ec17d4d0d069b19a5eecbc60d"
] |
[
"pydlr/test/test_semi_circ.py"
] |
[
"\"\"\" Evaluation of integral between a semi-circular \nspectral function and the imaginary time kernel, giving \nthe imaginary time Green's function analytically.\n\nThe analytical result is compared with the DLR representation\non a dense tau mesh.\n\nThe result is also compared to the iterative solution of\nthe corresponding Bethe lattice self-consistency \\Sigma = G / 4\n\nAuthor: Hugo U.R. Strand (2021) \"\"\"\n\n\nimport unittest\n\nimport numpy as np\nfrom scipy.integrate import quad\n\nfrom pydlr import dlr, kernel\n\n\ndef eval_semi_circ_G_tau(t):\n I = lambda x: -2 / np.pi * kernel(np.array([t]), np.array([x]))[0,0] \n g, res = quad(I, -1, 1, weight='alg', wvar=(0.5, 0.5))\n return g\n\neval_semi_circ_G_tau = np.vectorize(eval_semi_circ_G_tau)\n\n\nclass TestSemiCircular(unittest.TestCase):\n\n\n def test_semi_cirular_G_tau(self, verbose=False):\n\n # -- Dense mesh analytic evaluation\n\n beta = 1.\n tau_i = np.linspace(0, 1, num=200)\n G_i = eval_semi_circ_G_tau(tau_i)\n\n # -- Evaluation on DLR-tau points\n # -- and reinterpolation on dense grid from DLR coefficients\n\n d = dlr(lamb=10.)\n tau_l = d.get_tau(beta)\n shape = (len(tau_l), 1, 1)\n G_l = eval_semi_circ_G_tau(tau_l).reshape(shape)\n G_x = d.dlr_from_tau(G_l)\n G_i_ref = d.eval_dlr_tau(G_x, tau_i, 1.)[:, 0, 0]\n\n G_l = np.squeeze(G_l)\n\n print(f'diff = {np.max(np.abs(G_i - G_i_ref))}')\n self.assertTrue(np.allclose(G_i, G_i_ref))\n\n # -- Iterative determination using the Dyson equation\n\n max_iter = 20\n G_q = np.zeros(len(tau_l), dtype=complex)\n\n for iter in range(max_iter):\n G_q = d.dyson_matsubara(np.array([[0.]]), 0.25 * G_q.reshape(shape), 1.)[:, 0, 0]\n G_x_ref = d.dlr_from_matsubara(G_q, beta)\n G_l_ref = d.tau_from_dlr(G_x_ref).real\n G_i_ref2 = d.eval_dlr_tau(G_x_ref, tau_i, 1.)\n\n diff = np.max(np.abs(G_i - G_i_ref2))\n print(f'diff = {diff}')\n\n if diff < 5e-14: break\n\n self.assertTrue(np.allclose(G_l, G_l_ref))\n self.assertTrue(np.allclose(G_i, G_i_ref2))\n\n if verbose:\n\n import matplotlib.pyplot as plt\n\n plt.figure(figsize=(6, 6))\n\n subp = [2, 1, 1]\n\n plt.subplot(*subp); subp[-1] += 1\n plt.title('Semi-circular spectral function')\n plt.plot(tau_i, G_i, '-', label='analytic')\n plt.plot(tau_l, G_l, '.', label='tau DLR points')\n plt.plot(tau_l, G_l_ref, 'x', label='tau DLR points (iterative)')\n plt.xlabel(r'$\\tau$')\n plt.ylabel(r'$G(\\tau)$')\n plt.legend(loc='best') \n\n plt.subplot(*subp); subp[-1] += 1\n plt.semilogy(tau_i, np.abs(G_i - G_i_ref), '.-', label='analytic')\n plt.semilogy(tau_i, np.abs(G_i - G_i_ref2), '.-', label='iterative')\n plt.xlabel(r'$\\tau$')\n plt.ylabel(r'$|G(\\tau) - G_{DLR}(\\tau)|$')\n plt.legend(loc='best') \n\n plt.tight_layout()\n plt.savefig('figure_test_semi_circ.pdf')\n\n plt.show()\n\n\nif __name__ == '__main__':\n unittest.main()\n \n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.tight_layout",
"numpy.allclose",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.abs",
"numpy.squeeze",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"numpy.vectorize",
"matplotlib.pyplot.subplot",
"scipy.integrate.quad",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
ElnuraMusaoglu/SingleObjectTracking
|
[
"282a6312be23f6c4bce3b38c19045a1d1a3bce3b"
] |
[
"hierarchical_conv_features_tracking/hcf_old.py"
] |
[
"import cv2\nimport numpy as np\nfrom numpy.fft import fft2, ifft2, fftshift\nfrom numpy import conj, real\nimport argparse\nimport cv2\nimport os\nfrom os.path import join, realpath, dirname\nfrom keras.applications.vgg19 import VGG19\nfrom keras.models import Model\nfrom matplotlib import pyplot\nfrom numpy import expand_dims\nfrom os.path import realpath, dirname, join\nimport cv2\nimport scipy\nfrom utils.utils import gaussian2d_rolled_labels, cos_window\nimport scipy.io\n\nstyle_layers = ['block5_conv4',\n 'block4_conv4',\n 'block3_conv4']\n\n\n\n\ndef create_model2():\n import tensorflow as tf\n \"\"\" Creates a vgg model that returns a list of intermediate output values.\"\"\"\n # Load our model. Load pretrained VGG, trained on imagenet data\n vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')\n vgg.trainable = False\n indLayers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21] # VGG19 3., 4., 5. cnn layers [20, 15, 10]\n\n #outputs = [vgg.get_layer(name).output for name in style_layers]\n outputs = [vgg.layers[i].output for i in indLayers]\n\n model = tf.keras.Model([vgg.input], outputs)\n return model\n\ndef create_model1():\n mat = scipy.io.loadmat('D:/PROJECTS/MOT_CNN_DATAASSOCIATION/imagenet-vgg-verydeep-19.mat')\n model = VGG19(mat)\n nweights = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.02, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1,\n 0] # Weights for combining correlation filter responses [1, 0.5, 0.02]\n indLayers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21] # VGG19 3., 4., 5. cnn layers [20, 15, 10]\n\n outputs = [model.layers[i].output for i in indLayers]\n\n return Model(inputs=model.inputs, outputs=outputs)\n\nclass HCFTracker():\n def __init__(self):\n self.model = create_model2()\n self.indLayers = [20, 15, 10] # The CNN layers Conv5-4, Conv4-4, and Conv3-4 in VGG Net\n self.nweights = [1, 0.5, 0.02] # Weights for combining correlation filter responses\n\n self.padding = {\"generic\": 1.8, \"large\": 1, \"height\": 0.4} # generic, large, height\n self.sigma = 0.6\n self.lambdar = 0.0001 # Regularization parameter Eqn 3\n self.output_sigma_factor = 0.1 # Spatial bandwidth (proportional to the target size)\n self.interp_factor = 0.01 # Model learning rate (see Eqn 6a, 6b)\n self.cell_size = 4 # Spatial cell size\n self.numLayers = len(self.indLayers)\n self.model_xf = []\n self.model_x = []\n self.model_alphaf = []\n\n def init(self, image, roi):\n # Get image size and search window size\n x1, y1, w, h = roi\n self.crop_size = (w, h)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.target_sz = [h, w] # 125 122\n im_sz = image.shape\n self.window_sz = self.get_search_window(self.target_sz, im_sz, self.padding)\n # Compute the sigma for the Gaussian function label\n output_sigma = np.sqrt(self.target_sz[0] * self.target_sz[1]) * self.output_sigma_factor / self.cell_size # 3.08\n # create regression labels, gaussian shaped, with a bandwidth\n self.l1_patch_num = np.floor(self.window_sz / self.cell_size) # 62 61\n # Pre-compute the Fourier Transform of the Gaussian function label\n self.yf = fft2(gaussian2d_rolled_labels([self.l1_patch_num[1], self.l1_patch_num[0]], output_sigma)) # 62 61 complex double\n # Pre-compute and cache the cosine window (for avoiding boundary discontinuity)\n self.cos_window = cos_window([self.yf.shape[1], self.yf.shape[0]]) # 62 61 double\n _nweights = np.zeros([1, 1, 3]) # ELNURA\n _nweights[0, 0, 0] = self.nweights[0]\n _nweights[0, 0, 1] = self.nweights[1]\n _nweights[0, 0, 2] = self.nweights[2] # ELNURA\n self.nweights = _nweights # 1x1x3 ELNURA Düzenle\n # Note: variables ending with 'f' are in the Fourier domain.\n self.model_xf = [] # numLayers\n self.model_x = []\n self.model_alphaf = [] # numLayers\n self.current_scale_factor = 1\n\n self.pos = [roi[1] + np.floor(self.target_sz[0] / 2), roi[0] + np.floor(self.target_sz[1] / 2)] # 130, 178\n\n # Extracting hierarchical convolutional features\n feat = self.extract_feature(image, self.pos, self.window_sz, self.cos_window, self.indLayers)\n self.update_model(feat, self.yf, self.interp_factor, self.lambdar, 0)\n target_sz_t = self.target_sz * self.current_scale_factor\n box = [self.pos[1] - target_sz_t[1] / 2,\n self.pos[0] - target_sz_t[0] / 2,\n target_sz_t[1],\n target_sz_t[0]] # 117, 67.5, 122, 125\n\n return box[0], box[1], box[2], box[3]\n\n def update(self, image, vis=False):\n if vis is True:\n self.score = self.yf\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # Extracting hierarchical convolutional features\n feat = self.extract_feature(image, self.pos, self.window_sz, self.cos_window, self.indLayers)\n # Predict position\n pos = self.predict_position(feat, self.pos, self.indLayers, self.nweights, self.cell_size,\n self.l1_patch_num)\n\n # Extracting hierarchical convolutional features\n feat = self.extract_feature(image, pos, self.window_sz, self.cos_window, self.indLayers)\n self.update_model(feat, self.yf, self.interp_factor, self.lambdar, 1)\n target_sz_t = self.target_sz * self.current_scale_factor\n self.pos = pos\n box = [pos[1] - target_sz_t[1] / 2,\n pos[0] - target_sz_t[0] / 2,\n target_sz_t[1],\n target_sz_t[0]] # 117, 67.5, 122, 125\n\n return box[0], box[1], box[2], box[3]\n\n def extract_feature(self, im, pos, window_sz, cos_window, indLayers):\n # Get the search window from previous detection\n patch = self.get_subwindow(im, pos, window_sz)\n #patch = self._preprocessing(patch, cos_window) # ELNURA\n features = self.get_features(patch, cos_window, indLayers)\n\n return features\n\n def gaussian_peak(self, w, h):\n output_sigma = 0.125\n sigma = np.sqrt(w * h) / self.padding * output_sigma\n syh, sxh = h // 2, w // 2\n y, x = np.mgrid[-syh:-syh + h, -sxh:-sxh + w]\n x = x + (1 - w % 2) / 2.\n y = y + (1 - h % 2) / 2.\n g = 1. / (2. * np.pi * sigma ** 2) * np.exp(-((x ** 2 + y ** 2) / (2. * sigma ** 2)))\n return g\n\n def get_search_window(self, target_sz, im_sz, padding):\n if target_sz[0] / target_sz[1] > 2:\n # For objects with large height, we restrict the search window with padding.height\n # Element-wise multiplication\n window_sz = np.floor(target_sz * [1 + padding[\"height\"], 1 + padding[\"generic\"]]) # ELNURA\n elif (target_sz[0] * target_sz[1]) / (im_sz[0] * im_sz[1]) > 0.05:\n # 125 * 122 / 360 * 640\n # For objects with large height and width and accounting for at least 10 percent of the whole image,\n # we only search 2x height and width\n window_sz = np.floor(np.multiply(target_sz, (1 + padding[\"large\"])))\n else:\n # otherwise, we use the padding configuration\n window_sz = np.floor(np.multiply(target_sz, (1 + padding[\"generic\"])))\n\n return window_sz\n\n def get_subwindow(self, im, pos, sz):\n _p1 = np.array(range(1, int(sz[0] + 1))).reshape([1, int(sz[0])])\n #_p1 = _p1.reshape([_p1.shape[1], _p1.shape[0]])\n _p2 = np.array(range(1, int(sz[1] + 1))).reshape([1, int(sz[1])])\n #_p2 = _p2.reshape([_p2.shape[1], _p2.shape[0]])\n ys = np.floor(pos[0]) + _p1 - np.floor(sz[0]/2) # 1 250\n xs = np.floor(pos[1]) + _p2 - np.floor(sz[1]/2) # 1, 244\n #sub = cv2.getRectSubPix(im, sz, pos)\n # sub_image = im[y:y + h, x:x + w, :]\n # Check for out-of-bounds coordinates, and set them to the values at the borders\n xs = self.clamp(xs, 1, np.size(im, 1))\n ys = self.clamp(ys, 1, np.size(im, 0))\n # extract image\n out = im[int(ys[0][0]) - 1:int(ys[0][np.size(ys, 1)-1]),\n int(xs[0][0]) - 1: int(xs[0][np.size(xs, 1)-1]), :]\n\n return out\n\n def clamp(self, x, lb, ub):\n # Clamp the value using lowerBound and upperBound\n lb = np.full((x.shape[0], x.shape[1]), lb)\n ub = np.full((x.shape[0], x.shape[1]), ub)\n y = np.maximum(x, lb)\n y = np.minimum(y, ub)\n\n return y\n\n def get_features(self, im, cos_window, layers):\n sz_window = np.array([cos_window.shape[0], cos_window.shape[1]]).reshape([1, int(2)])\n\n # Preprocessing\n img = im.astype('float64') # note: [0, 255] range\n img = cv2.resize(img, (224, 224))\n\n average = np.zeros((224, 224, 3)).astype('float64')\n average[:, :, 0] = 123.6800 # RGB 123, BGR 103\n average[:, :, 1] = 116.7790\n average[:, :, 2] = 103.9390\n\n img = np.subtract(img, average)\n img = img.round(4)\n\n img = expand_dims(img, axis=0)\n #img = preprocess_input(img)\n\n feature_maps = self.model.predict(img)\n features = []\n\n for fi in self.indLayers:\n f_map = feature_maps[fi][0][:][:][:]\n feature_map_n = cv2.resize(f_map, (cos_window.shape[1], cos_window.shape[0]), interpolation=cv2.INTER_LINEAR)\n feature_map_c = feature_map_n * cos_window[:, :, None]\n features.append(feature_map_c)\n\n return features\n\n def update_model(self, feat, yf, interp_factor, lambdar, frame):\n numLayers = len(feat)\n self.model_x = feat\n xf = []\n alphaf = []\n # Model update\n for i in range(numLayers):\n xf.append(fft2(feat[i]))\n kf = np.sum(conj(xf[i]) * xf[i], 2) / np.size(xf[i])\n alphaf.append(yf / (kf + lambdar)) # Fast training\n # Model initialization or update\n if frame == 0: # First frame, train with a single image\n self.model_alphaf = alphaf\n self.model_xf = xf\n else:\n for i in range(numLayers):\n self.model_alphaf[i] = (1 - interp_factor) * self.model_alphaf[i] + interp_factor * alphaf[i]\n self.model_xf[i] = (1 - interp_factor) * self.model_xf[i] + interp_factor * xf[i]\n\n def predict_position(self, feat, pos, indLayers, nweights, cell_size, l1_patch_num):\n # Compute correlation filter responses at each layer\n res_layer = np.zeros([int(l1_patch_num[0]), int(l1_patch_num[1]), len(indLayers)])\n\n for i in range(len(indLayers)):\n zf = fft2(feat[i])\n zf_c = zf * conj(self.model_xf[i])\n kzf = (np.sum(zf_c, axis=2)) / (np.size(zf)) # 62 61\n # kzf=sum(zf .* conj(model_xf{ii}), 3) / numel(zf)\n # ifft2(np.sum(conj(fft2(x1)) * fft2(x2), axis=0))\n # real(ifft2(alphaf * fft2(k)))\n temp = real(fftshift(ifft2(self.model_alphaf[i] * kzf))) # equation for fast detection 62 61, nweights -> 1 1 3\n # temp= real(fftshift(ifft2(model_alphaf{ii} .* kzf))); %equation for fast detection\n res_layer[:, :, i] = temp / np.max(temp)\n\n # Combine responses from multiple layers (see Eqn. 5)\n # response = sum(bsxfun(@times, res_layer, nweights), 3)\n response = np.sum(res_layer * nweights, axis=2)\n\n # Find target location\n # if the target doesn't move, the peak will appear at the top-left corner, not at the center.\n # The responses wrap around cyclically.\n\n # Find indices and values of nonzero elements curr = np.unravel_index(np.argmax(gi, axis=None), gi.shape)\n delta = np.unravel_index(np.argmax(response, axis=None), response.shape)\n vert_delta, horiz_delta = delta[0], delta[1]\n vert_delta = vert_delta - np.floor(np.size(zf, 0) / 2)\n horiz_delta = horiz_delta - np.floor(np.size(zf, 1) / 2)\n\n # Map the position to the image space\n pos = np.array(pos)\n pos = pos.reshape((pos.shape[0], 1))\n move_pos = np.array([vert_delta, horiz_delta]).reshape((pos.shape[0], 1))\n pos = pos + self.cell_size * move_pos# 122 174\n\n return pos\n\n def _preprocessing(self, img, cos_window, eps=1e-5):\n img = np.log(img+1)\n img = (img-np.mean(img))/(np.std(img)+eps)\n return cos_window*img\n\ndef get_img_list(img_dir):\n frame_list = []\n for frame in sorted(os.listdir(img_dir)):\n if os.path.splitext(frame)[1] == '.jpg':\n frame_list.append(os.path.join(img_dir, frame))\n return frame_list\n\n'''\nif __name__ == '__main__':\n tracker = HCFTracker()\n roi = (275,\t137, 23, 26) # surfer (275,\t137, 23, 26) (117, 68, 122, 125)\n img_dir = 'D:/PROJECTS/DATASET/OTB50/Surfer/img/'\n frame_list = get_img_list(img_dir)\n frame_list.sort()\n current_frame = cv2.imread(frame_list[0])\n tracker.init(current_frame, roi)\n\n for idx in range(len(frame_list)):\n frame = cv2.imread(frame_list[idx])\n bbox = tracker.update(frame)\n x, y, w, h = bbox\n x, y, w, h = int(x), int(y), int(w), int(h)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 1)\n cv2.imwrite('D:/PROJECTS/DATASET/OTB50/Surfer/img/RESULT/HCF/' + str(idx) + '.jpg', frame)\n cv2.imshow('tracking_single', frame)\n c = cv2.waitKey(1) & 0xFF\n\n if c == 27 or c == ord('q'):\n break\n\n cv2.destroyAllWindows()\n'''\n\n"
] |
[
[
"numpy.expand_dims",
"numpy.minimum",
"numpy.sqrt",
"numpy.max",
"numpy.mean",
"numpy.exp",
"scipy.io.loadmat",
"numpy.subtract",
"numpy.full",
"numpy.size",
"numpy.argmax",
"numpy.std",
"numpy.zeros",
"numpy.fft.fft2",
"numpy.log",
"numpy.multiply",
"tensorflow.keras.Model",
"numpy.floor",
"numpy.array",
"numpy.sum",
"numpy.maximum",
"numpy.conj",
"numpy.fft.ifft2",
"tensorflow.keras.applications.VGG19"
]
] |
daniilpastukhov/serendipity_experiments
|
[
"5ff544937d1796dbb20e11137f364972935be967"
] |
[
"models/mf.py"
] |
[
"# ref: Stanislav Kuznetsov\nimport pandas as pd\n\nimport numpy as np\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.neighbors import NearestNeighbors\nfrom scipy.sparse import csr_matrix\nfrom tqdm import tqdm\n\nfrom utils.helpers import get_movies_by_ids\nfrom utils.metrics import unexpectedness, relevance\n\n\nclass MatrixFactorization:\n def __init__(self, name, train_data, item_ratings):\n self.name = name\n self.train_data = train_data\n self.users_amount = len(train_data)\n self.train_data_sparse = csr_matrix(self.train_data.values)\n self.item_ratings = item_ratings\n self.beta = 1.0\n\n self.SVD = None\n self.matrix = None\n self.model_knn = None\n\n def fit(self, params):\n try:\n n_components = params['n_components']\n random_state = params['random_state']\n\n self.SVD = TruncatedSVD(n_components=n_components, random_state=random_state)\n self.matrix = self.SVD.fit_transform(self.train_data)\n\n self.model_knn = NearestNeighbors(metric='cosine', algorithm='auto', n_neighbors=20, n_jobs=-1)\n self.model_knn.fit(self.matrix)\n\n except Exception as e:\n print(self.name + ' fit ' + str(e))\n\n def predict(self, user_profile, n, just_scores=False):\n user_rated_items = user_profile[user_profile != 0].index\n\n user_matrix = self.SVD.transform(user_profile.values.reshape(1, -1))\n distances, indices = self.model_knn.kneighbors(user_matrix)\n\n my_neighbors = indices[0]\n my_neighbors_distance = distances[0]\n\n neighbours_profiles = self.train_data.iloc[my_neighbors]\n average_ratings = np.mean(neighbours_profiles[neighbours_profiles != 0], axis=1)\n\n popular_items = []\n popular_items_score = []\n\n for i in range(len(neighbours_profiles)):\n row = neighbours_profiles.iloc[i]\n user_average_rating = average_ratings.iloc[i]\n best_items = row[row > user_average_rating]\n popular_items.append(best_items.index)\n score = (best_items.values - user_average_rating) * (1 - my_neighbors_distance[i])\n popular_items_score.append(score)\n\n scores = pd.Series(np.zeros(user_profile.shape[0]), index=user_profile.index)\n for i in range(len(popular_items)):\n scores.loc[popular_items[i]] += popular_items_score[i]\n\n final_score = scores / (self.item_ratings.sort_values(by='movieId')['sum_rating'].values ** self.beta)\n final_score = final_score.loc[~final_score.index.isin(user_rated_items)]\n final_score.dropna(inplace=True)\n final_score = final_score[final_score != 0]\n if just_scores:\n return final_score\n argsort = np.argsort(final_score.values)[::-1][:n]\n recommendations = final_score[argsort].index.astype(np.int)\n\n return recommendations\n\n def evaluate(self,\n data,\n model_params,\n control_items,\n user_embeddings,\n primitive_recommendations,\n movies,\n n):\n hit = 0 # used for recall calculation\n total_recommendations = 0\n recommendations = []\n all_recommendations = [] # used for coverage calculation\n rel = []\n unexp = []\n nov = []\n\n for user_id, user_profile in tqdm(data.iterrows(), total=len(data)):\n prediction = self.predict(user_profile, n)\n if prediction is None or prediction.ndim == 0:\n continue\n\n if control_items[user_id] in prediction: # if prediction contains control item increase hit counter\n hit += 1\n\n recommendations.append(prediction)\n all_recommendations.extend(list(prediction))\n total_recommendations += 1\n\n recommended_items_embeddings = get_movies_by_ids(movies, prediction)\n\n if len(user_profile) == 0: # check if user profile is empty\n continue\n\n primitive_recs = np.array(\n [v for k, v in primitive_recommendations[user_id].items() if k not in json.dumps(model_params)]\n ).ravel()\n\n rel.append(relevance(recommended_items_embeddings, user_embeddings[user_id]))\n unexp.append(unexpectedness(prediction, primitive_recs))\n\n if total_recommendations > 0:\n recall = hit / total_recommendations\n else:\n recall = 0\n\n recommendations = np.array(recommendations)\n # calculate novelty of each item\n movies_nov = pd.Series(np.zeros(len(data.columns)), index=data.columns, dtype=np.float32)\n for movie_id in data.columns:\n recommended_fraction = (recommendations == int(movie_id)).sum()\n not_interacted_fraction = (data[movie_id] == 0).sum() + 1e-10\n movies_nov[movies_nov.index == movie_id] = 1 - (recommended_fraction / not_interacted_fraction)\n\n movies_nov = (movies_nov - movies_nov.min()) / (movies_nov.max() - movies_nov.min()) # min-max scaling\n\n for recommendation in recommendations:\n nov.append(movies_nov[movies_nov.index.astype(int).isin(recommendation)].mean())\n\n coverage = np.unique(all_recommendations).shape[0] / self.train_data.shape[1]\n return recall, coverage, nov, unexp, rel\n\n"
] |
[
[
"sklearn.decomposition.TruncatedSVD",
"numpy.unique",
"scipy.sparse.csr_matrix",
"numpy.mean",
"sklearn.neighbors.NearestNeighbors",
"numpy.argsort",
"numpy.array",
"numpy.zeros"
]
] |
francesconazzaro/pangeo-forge
|
[
"5c80733a1002c3b5f281e373746c9bc580453204"
] |
[
"pangeo_forge/recipes/xarray_zarr.py"
] |
[
"\"\"\"\nA Pangeo Forge Recipe\n\"\"\"\n\nimport json\nimport logging\nimport os\nimport tempfile\nimport warnings\nfrom contextlib import ExitStack, contextmanager\nfrom dataclasses import dataclass, field\nfrom itertools import product\nfrom typing import Callable, Dict, List, Optional, Sequence, Tuple\n\nimport dask\nimport fsspec\nimport numpy as np\nimport xarray as xr\nimport zarr\n\nfrom ..patterns import FilePattern\nfrom ..storage import AbstractTarget, UninitializedTarget, UninitializedTargetError\nfrom ..utils import (\n chunk_bounds_and_conflicts,\n chunked_iterable,\n fix_scalar_attr_encoding,\n lock_for_conflicts,\n)\nfrom .base import BaseRecipe\n\n# use this filename to store global recipe metadata in the metadata_cache\n# it will be written once (by prepare_target) and read many times (by store_chunk)\n_GLOBAL_METADATA_KEY = \"pangeo-forge-recipe-metadata.json\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef _encode_key(key) -> str:\n return \"-\".join([str(k) for k in key])\n\n\ndef _input_metadata_fname(input_key):\n return \"input-meta-\" + _encode_key(input_key) + \".json\"\n\n\ndef _chunk_metadata_fname(chunk_key) -> str:\n return \"chunk-meta-\" + _encode_key(chunk_key) + \".json\"\n\n\ndef _copy_btw_filesystems(input_opener, output_opener, BLOCK_SIZE=10_000_000):\n with input_opener as source:\n with output_opener as target:\n while True:\n data = source.read(BLOCK_SIZE)\n if not data:\n break\n target.write(data)\n\n\n@contextmanager\ndef _maybe_open_or_copy_to_local(opener, copy_to_local, orig_name):\n _, suffix = os.path.splitext(orig_name)\n if copy_to_local:\n ntf = tempfile.NamedTemporaryFile(suffix=suffix)\n tmp_name = ntf.name\n logger.info(f\"Copying {orig_name} to local file {tmp_name}\")\n target_opener = open(tmp_name, mode=\"wb\")\n _copy_btw_filesystems(opener, target_opener)\n yield tmp_name\n ntf.close() # cleans up the temporary file\n else:\n with opener as fp:\n with fp as fp2:\n yield fp2\n\n\n@contextmanager\ndef _fsspec_safe_open(fname, **kwargs):\n # workaround for inconsistent behavior of fsspec.open\n # https://github.com/intake/filesystem_spec/issues/579\n with fsspec.open(fname, **kwargs) as fp:\n with fp as fp2:\n yield fp2\n\n\ndef _get_url_size(fname):\n with fsspec.open(fname, mode=\"rb\") as of:\n size = of.size\n return size\n\n\n# Notes about dataclasses:\n# - https://www.python.org/dev/peps/pep-0557/#inheritance\n# - https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses\n# The main awkward thing here is that, because we are using multiple inheritance\n# with dataclasses, _ALL_ fields must have default values. This makes it impossible\n# to have \"required\" keyword arguments--everything needs some default.\n# That's whay we end up with `UninitializedTarget` and `_variable_sequence_pattern_default_factory`\n\n\nChunkKey = Tuple[int]\nInputKey = Tuple[int]\n\n\n@dataclass\nclass XarrayZarrRecipe(BaseRecipe):\n \"\"\"This class represents a dataset composed of many individual NetCDF files.\n This class uses Xarray to read and write data and writes its output to Zarr.\n The organization of the source files is described by the ``file_pattern``.\n Currently this recipe supports at most one ``MergeDim`` and one ``ConcatDim``\n in the File Pattern.\n\n :param file_pattern: An object which describes the organization of the input files.\n :param inputs_per_chunk: The number of inputs to use in each chunk along the concat dim.\n Must be an integer >= 1.\n :param target_chunks: Desired chunk structure for the targret dataset.\n :param target: A location in which to put the dataset. Can also be assigned at run time.\n :param input_cache: A location in which to cache temporary data.\n :param metadata_cache: A location in which to cache metadata for inputs and chunks.\n Required if ``nitems_per_file=None`` on concat dim in file pattern.\n :param cache_inputs: If ``True``, inputs are copied to ``input_cache`` before\n opening. If ``False``, try to open inputs directly from their source location.\n :param copy_input_to_local_file: Whether to copy the inputs to a temporary\n local file. In this case, a path (rather than file object) is passed to\n ``xr.open_dataset``. This is required for engines that can't open\n file-like objects (e.g. pynio).\n :param consolidate_zarr: Whether to consolidate the resulting Zarr dataset.\n :param xarray_open_kwargs: Extra options for opening the inputs with Xarray.\n :param xarray_concat_kwargs: Extra options to pass to Xarray when concatenating\n the inputs to form a chunk.\n :param delete_input_encoding: Whether to remove Xarray encoding from variables\n in the input dataset\n :param fsspec_open_kwargs: Extra options for opening the inputs with fsspec.\n :param process_input: Function to call on each opened input, with signature\n `(ds: xr.Dataset, filename: str) -> ds: xr.Dataset`.\n :param process_chunk: Function to call on each concatenated chunk, with signature\n `(ds: xr.Dataset) -> ds: xr.Dataset`.\n \"\"\"\n\n file_pattern: FilePattern\n inputs_per_chunk: Optional[int] = 1\n target_chunks: Dict[str, int] = field(default_factory=dict)\n target: AbstractTarget = field(default_factory=UninitializedTarget)\n input_cache: AbstractTarget = field(default_factory=UninitializedTarget)\n metadata_cache: AbstractTarget = field(default_factory=UninitializedTarget)\n cache_inputs: bool = True\n copy_input_to_local_file: bool = False\n consolidate_zarr: bool = True\n xarray_open_kwargs: dict = field(default_factory=dict)\n xarray_concat_kwargs: dict = field(default_factory=dict)\n delete_input_encoding: bool = True\n fsspec_open_kwargs: dict = field(default_factory=dict)\n process_input: Optional[Callable[[xr.Dataset, str], xr.Dataset]] = None\n process_chunk: Optional[Callable[[xr.Dataset], xr.Dataset]] = None\n\n # internal attributes not meant to be seen or accessed by user\n _concat_dim: Optional[str] = None\n \"\"\"The concatenation dimension name.\"\"\"\n\n _concat_dim_chunks: Optional[int] = None\n \"\"\"The desired chunking along the sequence dimension.\"\"\"\n\n # In general there may be a many-to-many relationship between input keys and chunk keys\n _inputs_chunks: Dict[InputKey, Tuple[ChunkKey]] = field(\n default_factory=dict, repr=False, init=False\n )\n \"\"\"Mapping of input keys to chunk keys.\"\"\"\n\n _chunks_inputs: Dict[ChunkKey, Tuple[InputKey]] = field(\n default_factory=dict, repr=False, init=False\n )\n \"\"\"Mapping of chunk keys to input keys.\"\"\"\n\n _init_chunks: List[ChunkKey] = field(default_factory=list, repr=False, init=False)\n \"\"\"List of chunks needed to initialize the recipe.\"\"\"\n\n def __post_init__(self):\n self._validate_file_pattern()\n # from here on we know there is at most one merge dim and one concat dim\n self._concat_dim = self.file_pattern.concat_dims[0]\n self._cache_metadata = any(\n [v is None for v in self.file_pattern.concat_sequence_lens.values()]\n )\n self._nitems_per_input = self.file_pattern.nitems_per_input[self._concat_dim]\n\n # now for the fancy bit: we have to define the mappings _inputs_chunks and _chunks_inputs\n # this is where refactoring would need to happen to support more complex file patterns\n # (e.g. multiple concat dims)\n # for now we assume 1:many chunk_keys:input_keys\n # theoretically this could handle more than one merge dimension\n\n # list of iterators that iterates over merge dims normally\n # but concat dims in chunks\n dimension_iterators = [\n range(v)\n if k != self._concat_dim\n else enumerate(chunked_iterable(range(v), self.inputs_per_chunk))\n for k, v in self.file_pattern.dims.items()\n ]\n for k in product(*dimension_iterators):\n # typical k would look like (0, (0, (0, 1)))\n chunk_key = tuple([v[0] if hasattr(v, \"__len__\") else v for v in k])\n all_as_tuples = tuple([v[1] if hasattr(v, \"__len__\") else (v,) for v in k])\n input_keys = tuple(v for v in product(*all_as_tuples))\n self._chunks_inputs[chunk_key] = input_keys\n for input_key in input_keys:\n self._inputs_chunks[input_key] = (chunk_key,)\n\n # init chunks are all elements from merge dim and first element from concat dim\n merge_dimension_iterators = [\n range(v) if k != self._concat_dim else (range(1))\n for k, v in self.file_pattern.dims.items()\n ]\n self._init_chunks = list(product(*merge_dimension_iterators))\n\n self._validate_input_and_chunk_keys()\n self._set_target_chunks()\n\n def _validate_file_pattern(self):\n if len(self.file_pattern.merge_dims) > 1:\n raise NotImplementedError(\"This Recipe class can't handle more than one merge dim.\")\n if len(self.file_pattern.concat_dims) > 1:\n raise NotImplementedError(\"This Recipe class can't handle more than one concat dim.\")\n\n def _validate_input_and_chunk_keys(self):\n all_input_keys = set(self._inputs_chunks.keys())\n all_chunk_keys = set(self._chunks_inputs.keys())\n if not all_input_keys == set(self.file_pattern):\n raise ValueError(\"_inputs_chunks and file_pattern don't have the same keys\")\n if not all_input_keys == set([c for val in self._chunks_inputs.values() for c in val]):\n raise ValueError(\"_inputs_chunks and _chunks_inputs don't use the same input keys.\")\n if not all_chunk_keys == set([c for val in self._inputs_chunks.values() for c in val]):\n raise ValueError(\"_inputs_chunks and _chunks_inputs don't use the same chunk keys.\")\n\n def _set_target_chunks(self):\n target_concat_dim_chunks = self.target_chunks.get(self._concat_dim)\n if (self._nitems_per_input is None) and (target_concat_dim_chunks is None):\n raise ValueError(\n \"Unable to determine target chunks. Please specify either \"\n \"`target_chunks` or `nitems_per_input`\"\n )\n elif target_concat_dim_chunks:\n self._concat_dim_chunks = target_concat_dim_chunks\n else:\n self._concat_dim_chunks = self._nitems_per_input * self.inputs_per_chunk\n\n @property\n def prepare_target(self) -> Callable:\n def _prepare_target():\n\n try:\n ds = self.open_target()\n logger.info(\"Found an existing dataset in target\")\n logger.debug(f\"{ds}\")\n\n if self.target_chunks:\n # TODO: check that target_chunks id compatibile with the\n # existing chunks\n pass\n\n except (FileNotFoundError, IOError, zarr.errors.GroupNotFoundError):\n logger.info(\"Creating a new dataset in target\")\n\n # need to rewrite this as an append loop\n for chunk_key in self._init_chunks:\n with self.open_chunk(chunk_key) as ds:\n # ds is already chunked\n\n # https://github.com/pydata/xarray/blob/5287c7b2546fc8848f539bb5ee66bb8d91d8496f/xarray/core/variable.py#L1069\n for v in ds.variables:\n if self.target_chunks:\n this_var = ds[v]\n chunks = {\n this_var.get_axis_num(dim): chunk\n for dim, chunk in self.target_chunks.items()\n if dim in this_var.dims\n }\n\n chunks = tuple(\n chunks.get(n, s) for n, s in enumerate(this_var.shape)\n )\n encoding_chunks = chunks\n else:\n encoding_chunks = ds[v].shape\n logger.debug(\n f\"Setting variable {v} encoding chunks to {encoding_chunks}\"\n )\n ds[v].encoding[\"chunks\"] = encoding_chunks\n\n # load all variables that don't have the sequence dim in them\n # these are usually coordinates.\n # Variables that are loaded will be written even with compute=False\n # TODO: make this behavior customizable\n for v in ds.variables:\n if self._concat_dim not in ds[v].dims:\n ds[v].load()\n\n target_mapper = self.target.get_mapper()\n logger.info(f\"Storing dataset in {self.target.root_path}\")\n logger.debug(f\"{ds}\")\n with warnings.catch_warnings():\n warnings.simplefilter(\n \"ignore\"\n ) # suppress the warning that comes with safe_chunks\n ds.to_zarr(target_mapper, mode=\"a\", compute=False, safe_chunks=False)\n\n # Regardless of whether there is an existing dataset or we are creating a new one,\n # we need to expand the concat_dim to hold the entire expected size of the data\n input_sequence_lens = self.calculate_sequence_lens()\n n_sequence = sum(input_sequence_lens)\n logger.info(f\"Expanding target concat dim '{self._concat_dim}' to size {n_sequence}\")\n self.expand_target_dim(self._concat_dim, n_sequence)\n\n if self._cache_metadata:\n # if nitems_per_input is not constant, we need to cache this info\n recipe_meta = {\"input_sequence_lens\": input_sequence_lens}\n meta_mapper = self.metadata_cache.get_mapper()\n # we are saving a dictionary with one key (input_sequence_lens)\n logger.info(\"Caching global metadata\")\n meta_mapper[_GLOBAL_METADATA_KEY] = json.dumps(recipe_meta).encode(\"utf-8\")\n\n return _prepare_target\n\n @property\n def cache_input(self) -> Callable:\n def cache_func(input_key: InputKey) -> None:\n logger.info(f\"Caching input {input_key}\")\n fname = self.file_pattern[input_key]\n\n # check and see if the file already exists in the cache\n if self.input_cache.exists(fname):\n cached_size = self.input_cache.size(fname)\n remote_size = _get_url_size(fname)\n if cached_size == remote_size:\n logger.info(f\"Input {input_key} file {fname} is already cached\")\n return\n\n input_opener = _fsspec_safe_open(fname, mode=\"rb\", **self.fsspec_open_kwargs)\n target_opener = self.input_cache.open(fname, mode=\"wb\")\n _copy_btw_filesystems(input_opener, target_opener)\n # TODO: make it so we can cache metadata WITHOUT copying the file\n if self._cache_metadata:\n self.cache_input_metadata(input_key)\n\n return cache_func\n\n @property\n def store_chunk(self) -> Callable:\n def _store_chunk(chunk_key: ChunkKey):\n with self.open_chunk(chunk_key) as ds_chunk:\n # writing a region means that all the variables MUST have concat_dim\n to_drop = [\n v for v in ds_chunk.variables if self._concat_dim not in ds_chunk[v].dims\n ]\n ds_chunk = ds_chunk.drop_vars(to_drop)\n\n target_mapper = self.target.get_mapper()\n write_region, conflicts = self.region_and_conflicts_for_chunk(chunk_key)\n\n zgroup = zarr.open_group(target_mapper)\n for vname, var_coded in ds_chunk.variables.items():\n zarr_array = zgroup[vname]\n # get encoding for variable from zarr attributes\n # could this backfire some way?\n var_coded.encoding.update(zarr_array.attrs)\n # just delete all attributes from the var;\n # they are not used anyway, and there can be conflicts\n # related to xarray.coding.variables.safe_setitem\n var_coded.attrs = {}\n with dask.config.set(\n scheduler=\"single-threaded\"\n ): # make sure we don't use a scheduler\n var = xr.backends.zarr.encode_zarr_variable(var_coded)\n data = np.asarray(\n var.data\n ) # TODO: can we buffer large data rather than loading it all?\n zarr_region = tuple(write_region.get(dim, slice(None)) for dim in var.dims)\n lock_keys = [f\"{vname}-{c}\" for c in conflicts]\n logger.debug(f\"Acquiring locks {lock_keys}\")\n with lock_for_conflicts(lock_keys):\n logger.info(\n f\"Storing variable {vname} chunk {chunk_key} \"\n f\"to Zarr region {zarr_region}\"\n )\n zarr_array[zarr_region] = data\n\n return _store_chunk\n\n @property\n def finalize_target(self) -> Callable:\n def _finalize_target():\n if self.consolidate_zarr:\n logger.info(\"Consolidating Zarr metadata\")\n target_mapper = self.target.get_mapper()\n zarr.consolidate_metadata(target_mapper)\n\n return _finalize_target\n\n @contextmanager\n def input_opener(self, fname: str):\n try:\n logger.info(f\"Opening '{fname}' from cache\")\n opener = self.input_cache.open(fname, mode=\"rb\")\n with _maybe_open_or_copy_to_local(opener, self.copy_input_to_local_file, fname) as fp:\n yield fp\n except (IOError, FileNotFoundError, UninitializedTargetError) as err:\n if self.cache_inputs:\n raise Exception(\n f\"You are trying to open input {fname}, but the file is \"\n \"not cached yet. First call `cache_input` or set \"\n \"`cache_inputs=False`.\"\n ) from err\n logger.info(f\"No cache found. Opening input `{fname}` directly.\")\n opener = _fsspec_safe_open(fname, mode=\"rb\", **self.fsspec_open_kwargs)\n with _maybe_open_or_copy_to_local(opener, self.copy_input_to_local_file, fname) as fp:\n yield fp\n\n @contextmanager\n def open_input(self, input_key: InputKey):\n fname = self.file_pattern[input_key]\n logger.info(f\"Opening input with Xarray {input_key}: '{fname}'\")\n with self.input_opener(fname) as f:\n ds = xr.open_dataset(f, **self.xarray_open_kwargs)\n # Explicitly load into memory;\n # if we don't do this, we get a ValueError: seek of closed file.\n # But there will be some cases where we really don't want to load.\n # how to keep around the open file object?\n # ds = ds.load()\n\n ds = fix_scalar_attr_encoding(ds)\n\n if self.delete_input_encoding:\n for var in ds.variables:\n ds[var].encoding = {}\n\n if self.process_input is not None:\n ds = self.process_input(ds, str(fname))\n\n logger.debug(f\"{ds}\")\n yield ds\n\n def cache_input_metadata(self, input_key: InputKey):\n logger.info(f\"Caching metadata for input '{input_key}'\")\n with self.open_input(input_key) as ds:\n metadata = ds.to_dict(data=False)\n mapper = self.metadata_cache.get_mapper()\n mapper[_input_metadata_fname(input_key)] = json.dumps(metadata).encode(\"utf-8\")\n\n @contextmanager\n def open_chunk(self, chunk_key: ChunkKey):\n logger.info(f\"Opening inputs for chunk {chunk_key}\")\n inputs = self._chunks_inputs[chunk_key]\n\n # need to open an unknown number of contexts at the same time\n with ExitStack() as stack:\n dsets = [stack.enter_context(self.open_input(i)) for i in inputs]\n # explicitly chunking prevents eager evaluation during concat\n dsets = [ds.chunk() for ds in dsets]\n logger.info(f\"Combining inputs for chunk '{chunk_key}'\")\n if len(dsets) > 1:\n # During concat, attributes and encoding are taken from the first dataset\n # https://github.com/pydata/xarray/issues/1614\n ds = xr.concat(dsets, self._concat_dim, **self.xarray_concat_kwargs)\n elif len(dsets) == 1:\n ds = dsets[0]\n else: # pragma: no cover\n assert False, \"Should never happen\"\n\n if self.process_chunk is not None:\n ds = self.process_chunk(ds)\n\n logger.debug(f\"{ds}\")\n\n # TODO: maybe do some chunking here?\n yield ds\n\n def open_target(self):\n target_mapper = self.target.get_mapper()\n return xr.open_zarr(target_mapper)\n\n def expand_target_dim(self, dim, dimsize):\n target_mapper = self.target.get_mapper()\n zgroup = zarr.open_group(target_mapper)\n ds = self.open_target()\n sequence_axes = {v: ds[v].get_axis_num(dim) for v in ds.variables if dim in ds[v].dims}\n\n for v, axis in sequence_axes.items():\n arr = zgroup[v]\n shape = list(arr.shape)\n shape[axis] = dimsize\n logger.debug(f\"resizing array {v} to shape {shape}\")\n arr.resize(shape)\n\n # now explicity write the sequence coordinate to avoid missing data\n # when reopening\n if dim in zgroup:\n zgroup[dim][:] = 0\n\n def iter_inputs(self):\n for input in self._inputs_chunks:\n yield input\n\n def region_and_conflicts_for_chunk(self, chunk_key: ChunkKey):\n # return a dict suitable to pass to xr.to_zarr(region=...)\n # specifies where in the overall array to put this chunk's data\n # also return the conflicts with other chunks\n\n input_keys = self._chunks_inputs[chunk_key]\n\n if self._nitems_per_input:\n input_sequence_lens = (self._nitems_per_input,) * self.file_pattern.dims[\n self._concat_dim # type: ignore\n ]\n else:\n input_sequence_lens = json.loads(\n self.metadata_cache.get_mapper()[_GLOBAL_METADATA_KEY]\n )[\"input_sequence_lens\"]\n\n chunk_bounds, all_chunk_conflicts = chunk_bounds_and_conflicts(\n input_sequence_lens, self._concat_dim_chunks # type: ignore\n )\n input_positions = [self.input_position(input_key) for input_key in input_keys]\n start = chunk_bounds[min(input_positions)]\n stop = chunk_bounds[max(input_positions) + 1]\n\n this_chunk_conflicts = set()\n for k in input_keys:\n # for multi-variable recipes, the confilcts will usually be the same\n # for each variable. using a set avoids duplicate locks\n for input_conflict in all_chunk_conflicts[self.input_position(k)]:\n this_chunk_conflicts.add(input_conflict)\n region_slice = slice(start, stop)\n return {self._concat_dim: region_slice}, this_chunk_conflicts\n\n def iter_chunks(self):\n for k in self._chunks_inputs:\n yield k\n\n def get_input_meta(self, *input_keys: Sequence[InputKey]) -> Dict:\n meta_mapper = self.metadata_cache.get_mapper()\n # getitems should be async; much faster than serial calls\n all_meta_raw = meta_mapper.getitems([_input_metadata_fname(k) for k in input_keys])\n return {k: json.loads(raw_bytes) for k, raw_bytes in all_meta_raw.items()}\n\n def input_position(self, input_key):\n # returns the index position of an input key wrt the concat_dim\n concat_dim_axis = list(self.file_pattern.dims).index(self._concat_dim)\n return input_key[concat_dim_axis]\n\n def calculate_sequence_lens(self):\n if self._nitems_per_input:\n return list((self._nitems_per_input,) * self.file_pattern.dims[self._concat_dim])\n\n # read per-input metadata; this is distinct from global metadata\n # get the sequence length of every file\n # this line could become problematic for large (> 10_000) lists of files\n input_meta = self.get_input_meta(*self._inputs_chunks)\n # use a numpy array to allow reshaping\n all_lens = np.array([m[\"dims\"][self._concat_dim] for m in input_meta.values()])\n all_lens.shape = list(self.file_pattern.dims.values())\n # check that all lens are the same along the concat dim\n concat_dim_axis = list(self.file_pattern.dims).index(self._concat_dim)\n selector = [slice(0, 1)] * len(self.file_pattern.dims)\n selector[concat_dim_axis] = slice(None) # this should broadcast correctly agains all_lens\n sequence_lens = all_lens[tuple(selector)]\n if not (all_lens == sequence_lens).all():\n raise ValueError(f\"Inconsistent sequence lengths found: f{all_lens}\")\n return sequence_lens.squeeze().tolist()\n\n def inputs_for_chunk(self, chunk_key: ChunkKey) -> Tuple[InputKey]:\n \"\"\"Convenience function for users to introspect recipe.\"\"\"\n return self._chunks_inputs[chunk_key]\n"
] |
[
[
"numpy.asarray"
]
] |
fakotakis/Natural-Language_Processing
|
[
"6efd454c50b58fa62dbeae90128f43902bf882d0"
] |
[
"plotting_results.py"
] |
[
"import matplotlib.pyplot as plt\n\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\n\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\n\nplt.legend()\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
thantuongaotrang/AlphaToe
|
[
"1220f4f883dbbd7ac1d84092bdaf04ca18a4dbc2"
] |
[
"value_network.py"
] |
[
"\"\"\"\nAfter using reinforcement learning to train a network, e.g. policy_gradient.py, to play a game well. We then want to\nlearn to estimate weather that network would win, lose or draw from a given position.\n\nAlpha Go used a database of real positions to get it's predictions from, we don't have that for tic-tac-toe so instead\nwe generate some random game positions and train off of the results we get playing from those.\n\"\"\"\nimport os\nimport random\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom common.network_helpers import create_network, load_network, save_network, \\\n get_deterministic_network_move\nfrom games.tic_tac_toe import TicTacToeGameSpec\n\nHIDDEN_NODES_VALUE = (100, 100, 100)\nHIDDEN_NODES_REINFORCEMENT = (100, 100, 100)\nBATCH_SIZE = 100 # every how many games to do a parameter update?\nLEARN_RATE = 1e-4\nREINFORCEMENT_NETWORK_PATH = 'current_network.p'\nVALUE_NETWORK_PATH = 'value_netowrk.p'\nTRAIN_SAMPLES = 10000\nTEST_SAMPLES = 10000\n\n# to play a different game change this to another spec, e.g TicTacToeXGameSpec or ConnectXGameSpec\ngame_spec = TicTacToeGameSpec()\n\nNUMBER_RANDOM_RANGE = (1, game_spec.board_squares() * 0.8)\n\n\n# it would be good to have real board positions, but failing that just generate random ones\ndef generate_random_board_position():\n while True:\n board_state = game_spec.new_board()\n number_moves = random.randint(*NUMBER_RANDOM_RANGE)\n side = 1\n for _ in range(number_moves):\n board_state = game_spec.apply_move(board_state, random.choice(list(game_spec.available_moves(board_state))),\n side)\n if game_spec.has_winner(board_state) != 0:\n # start again if we hit an already winning position\n continue\n\n side = -side\n return board_state\n\n\nreinforcement_input_layer, reinforcement_output_layer, reinforcement_variables = create_network(\n game_spec.board_squares(),\n HIDDEN_NODES_REINFORCEMENT,\n game_spec.outputs())\n\nvalue_input_layer, value_output_layer, value_variables = create_network(game_spec.board_squares(), HIDDEN_NODES_VALUE,\n output_nodes=1, output_softmax=False)\n\ntarget_placeholder = tf.placeholder(\"float\", (None, 1))\nerror = tf.reduce_sum(tf.square(target_placeholder - value_output_layer))\n\ntrain_step = tf.train.RMSPropOptimizer(LEARN_RATE).minimize(error)\n\nwith tf.Session() as session:\n session.run(tf.global_variables_initializer())\n\n load_network(session, reinforcement_variables, REINFORCEMENT_NETWORK_PATH)\n\n if os.path.isfile(VALUE_NETWORK_PATH):\n print(\"loading previous version of value network\")\n load_network(session, value_variables, VALUE_NETWORK_PATH)\n\n\n def make_move(board_state, side):\n move = get_deterministic_network_move(session, reinforcement_input_layer, reinforcement_output_layer,\n board_state, side)\n\n return game_spec.flat_move_to_tuple(np.argmax(move))\n\n\n board_states_training = {}\n board_states_test = []\n episode_number = 0\n\n while len(board_states_training) < TRAIN_SAMPLES + TEST_SAMPLES:\n board_state = generate_random_board_position()\n board_state_flat = tuple(np.ravel(board_state))\n\n # only accept the board_state if not already in the dict\n if board_state_flat not in board_states_training:\n result = game_spec.play_game(make_move, make_move, board_state=board_state)\n board_states_training[board_state_flat] = float(result)\n\n # take a random selection from training into a test set\n for _ in range(TEST_SAMPLES):\n sample = random.choice(board_states_training.keys())\n board_states_test.append((sample, board_states_training[sample]))\n del board_states_training[sample]\n\n board_states_training = list(board_states_training.iteritems())\n\n test_error = session.run(error, feed_dict={value_input_layer: [x[0] for x in board_states_test],\n target_placeholder: [[x[1]] for x in board_states_test]})\n\n while True:\n np.random.shuffle(board_states_training)\n train_error = 0\n\n for start_index in range(0, len(board_states_training) - BATCH_SIZE + 1, BATCH_SIZE):\n mini_batch = board_states_training[start_index:start_index + BATCH_SIZE]\n\n batch_error, _ = session.run([error, train_step],\n feed_dict={value_input_layer: [x[0] for x in mini_batch],\n target_placeholder: [[x[1]] for x in mini_batch]})\n train_error += batch_error\n\n new_test_error = session.run(error, feed_dict={value_input_layer: [x[0] for x in board_states_test],\n target_placeholder: [[x[1]] for x in board_states_test]})\n\n print(\"episode: %s train_error: %s test_error: %s\" % (episode_number, train_error, test_error))\n\n if new_test_error > test_error:\n print(\"train error went up, stopping training\")\n break\n\n test_error = new_test_error\n episode_number += 1\n\n save_network(session, value_variables, VALUE_NETWORK_PATH)\n"
] |
[
[
"tensorflow.train.RMSPropOptimizer",
"tensorflow.placeholder",
"numpy.random.shuffle",
"tensorflow.global_variables_initializer",
"numpy.argmax",
"tensorflow.Session",
"tensorflow.square",
"numpy.ravel"
]
] |
mofanv/privacy
|
[
"452031ecb1761712188155e4b36d6d01abf162aa"
] |
[
"tensorflow_privacy/privacy/membership_inference_attack/utils.py"
] |
[
"# Copyright 2020, The TensorFlow Authors.\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# Lint as: python3\n\"\"\"Utility functions for membership inference attacks.\"\"\"\n\nfrom typing import Text, Dict, Union, List, Any, Tuple\n\nimport numpy as np\nfrom sklearn import metrics\n\nArrayDict = Dict[Text, np.ndarray]\nDataset = Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]\n\n# ------------------------------------------------------------------------------\n# Utilities for managing result dictionaries\n# ------------------------------------------------------------------------------\n\n\ndef to_numpy(in_dict: Dict[Text, Any]) -> ArrayDict:\n \"\"\"Convert values of dict to numpy arrays.\n\n Warning: This may fail if the values cannot be converted to numpy arrays.\n\n Args:\n in_dict: A dictionary mapping Text keys to values where the values must be\n something that can be converted to a numpy array.\n\n Returns:\n a dictionary with the same keys as input with all values converted to numpy\n arrays\n \"\"\"\n return {k: np.array(v) for k, v in in_dict.items()}\n\n\ndef ensure_1d(in_dict: Dict[Text, Union[int, float, np.ndarray]]) -> ArrayDict:\n \"\"\"Ensure all values of a dictionary are at least 1D numpy arrays.\n\n Args:\n in_dict: The input dictionary mapping Text keys to numpy arrays or numbers.\n\n Returns:\n dictionary with same keys as in_dict and values converted to numpy arrays\n with at least one dimension (i.e., pack scalars into arrays)\n \"\"\"\n return {k: np.atleast_1d(v) for k, v in in_dict.items()}\n\n\ndef prepend_to_keys(in_dict: Dict[Text, Any], prefix: Text) -> Dict[Text, Any]:\n \"\"\"Prepend a prefix to all keys of a dictionary.\n\n Args:\n in_dict: The input dictionary mapping Text keys to numpy arrays.\n prefix: Text which to prepend to each key in in_dict\n\n Returns:\n dictionary with same values as in_dict and all keys having prefix prepended\n to them\n \"\"\"\n return {prefix + k: v for k, v in in_dict.items()}\n\n\n# ------------------------------------------------------------------------------\n# Subsampling and data selection functionality\n# ------------------------------------------------------------------------------\n\n\ndef select_indices(in_dict: ArrayDict, indices: np.ndarray) -> ArrayDict:\n \"\"\"Subsample all values in the dictionary by the provided indices.\n\n Args:\n in_dict: The input dictionary mapping Text keys to numpy array values.\n indices: A numpy which can be used to index other arrays, specifying the\n indices to subsample from in_dict values.\n\n Returns:\n dictionary with same keys as in_dict and subsampled values\n \"\"\"\n return {k: v[indices] for k, v in in_dict.items()}\n\n\ndef merge_dictionaries(res: List[ArrayDict]) -> ArrayDict:\n \"\"\"Convert iterable of dicts to dict of iterables.\"\"\"\n output = {k: np.empty(0) for k in res[0]}\n for k in output:\n output[k] = np.concatenate([r[k] for r in res if k in r], axis=0)\n return output\n\n\ndef get_features(features: ArrayDict,\n feature_name: Text,\n top_k: int,\n add_loss: bool = False) -> np.ndarray:\n \"\"\"Combine the specified features into one array.\n\n Args:\n features: A dictionary containing all possible features.\n feature_name: Which feature to use (logits or prob).\n top_k: The number of the top features (of feature_name) to select.\n add_loss: Whether to also add the loss as a feature.\n\n Returns:\n combined numpy array with the selected features (n_examples, n_features)\n \"\"\"\n if top_k < 1:\n raise ValueError('Must select at least one feature.')\n feats = np.sort(features[feature_name], axis=-1)[:, :top_k]\n if add_loss:\n feats = np.concatenate((feats, features['loss'][:, np.newaxis]), axis=-1)\n return feats\n\n\ndef subsample_to_balance(features: ArrayDict, random_state: int) -> ArrayDict:\n \"\"\"Subsample if necessary to balance labels.\"\"\"\n train_idx = features['is_train'] == 1\n test_idx = np.logical_not(train_idx)\n n0 = np.sum(test_idx)\n n1 = np.sum(train_idx)\n\n if n0 < 20 or n1 < 20:\n raise RuntimeError('Need at least 20 examples from training and test set.')\n\n np.random.seed(random_state)\n\n if n0 > n1:\n use_idx = np.random.choice(np.where(test_idx)[0], n1, replace=False)\n use_idx = np.concatenate((use_idx, np.where(train_idx)[0]))\n features = {k: v[use_idx] for k, v in features.items()}\n elif n0 < n1:\n use_idx = np.random.choice(np.where(train_idx)[0], n0, replace=False)\n use_idx = np.concatenate((use_idx, np.where(test_idx)[0]))\n features = {k: v[use_idx] for k, v in features.items()}\n\n return features\n\n\ndef get_train_test_split(features: ArrayDict, add_loss: bool,\n test_size: float) -> Dataset:\n \"\"\"Get training and test data split.\"\"\"\n y = features['is_train']\n n_total = len(y)\n n_test = int(test_size * n_total)\n perm = np.random.permutation(len(y))\n test_idx = perm[:n_test]\n train_idx = perm[n_test:]\n y_train = y[train_idx]\n y_test = y[test_idx]\n\n # We are using 10 top logits as a good default value if there are more than 10\n # classes. Typically, there is no significant amount of weight in more than\n # 10 logits.\n n_logits = min(features['logits'].shape[1], 10)\n x = get_features(features, 'logits', n_logits, add_loss)\n\n x_train, x_test = x[train_idx], x[test_idx]\n return (x_train, y_train), (x_test, y_test)\n\n\n# ------------------------------------------------------------------------------\n# Computation of the attack metrics\n# ------------------------------------------------------------------------------\n\n\ndef compute_performance_metrics(true_labels: np.ndarray,\n predictions: np.ndarray,\n threshold: float = None) -> ArrayDict:\n \"\"\"Compute relevant classification performance metrics.\n\n The outout metrics are\n 1.arrays of thresholds and corresponding true and false positives (fpr, tpr).\n 2.auc area under fpr-tpr curve.\n 3.advantage max difference between tpr and fpr.\n 4.precision/recall/accuracy/f1_score if threshold arg is given.\n\n Args:\n true_labels: True labels.\n predictions: Predicted probabilities/scores.\n threshold: The threshold to use on `predictions` binary classification.\n\n Returns:\n A dictionary with relevant metrics which are fully described by their key.\n \"\"\"\n results = {}\n if threshold is not None:\n results.update({\n 'precision':\n metrics.precision_score(true_labels, predictions > threshold),\n 'recall':\n metrics.recall_score(true_labels, predictions > threshold),\n 'accuracy':\n metrics.accuracy_score(true_labels, predictions > threshold),\n 'f1_score':\n metrics.f1_score(true_labels, predictions > threshold),\n })\n\n fpr, tpr, thresholds = metrics.roc_curve(true_labels, predictions)\n auc = metrics.auc(fpr, tpr)\n advantage = np.max(np.abs(tpr - fpr))\n\n results.update({\n 'fpr': fpr,\n 'tpr': tpr,\n 'thresholds': thresholds,\n 'auc': auc,\n 'advantage': advantage,\n })\n return ensure_1d(results)\n"
] |
[
[
"numpy.logical_not",
"sklearn.metrics.recall_score",
"numpy.abs",
"numpy.random.seed",
"sklearn.metrics.precision_score",
"sklearn.metrics.roc_curve",
"numpy.sort",
"numpy.atleast_1d",
"numpy.concatenate",
"sklearn.metrics.auc",
"sklearn.metrics.f1_score",
"numpy.array",
"numpy.where",
"numpy.sum",
"numpy.empty",
"sklearn.metrics.accuracy_score"
]
] |
choderalab/DDR1_and_kinase_promiscuity_materials
|
[
"510184518fdba59930bbed08331668d1267ecbf8"
] |
[
"2.WT_SIMULATIONS/MSM_analysis/MSM_analysis.py"
] |
[
"import matplotlib\nmatplotlib.use('Agg')\n\n# import general libraries\nimport mdtraj as md\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pyemma.coordinates as coor\nimport pyemma.msm as msm\nimport pyemma.plots as mplt\n\nprint('loading trajectories')\n\n# load trajectories\npath_to_trajs = './WT-sims/*.h5'\nfrom glob import glob\nfilenames = sorted(glob(path_to_trajs))\n\nfrom tables.exceptions import NoSuchNodeError\n\ntrajs = list()\nfilenames_checked=list()\nfor filename in filenames:\n try:\n traj = md.load(filename, stride=10)\n good_file = filename\n trajs.append(traj)\n filenames_checked.append(good_file)\n except NoSuchNodeError as e:\n print('Trajectory file %s is corrupted: %s' % (filename, str(e)))\n\ntop = trajs[0].topology\n\nprint('featurizing')\n\n# Make our featurizer\nfeat = coor.featurizer(top)\n\n# add our known kinase coordinates\n # Roux pseudo-dihedral\nRoux = ['resid 179 and resname ALA and name CB',\n 'resid 179 and resname ALA and name CA',\n 'resid 180 and resname ASP and name CA',\n 'resid 180 and resname ASP and name CG']\n\nRoux_atoms = np.array([],dtype=np.int64)\nfor atom in Roux:\n atom_select = int(top.select(atom))\n Roux_atoms = np.append(Roux_atoms, atom_select )\n\nfeat.add_dihedrals([Roux_atoms])\n\n# DFG distance\nDFG_distance = ['resid 149 and resname GLY and name CA',\n 'resid 181 and resname PHE and name CZ']\n\ndef_DFG_atom_1 = top.select(DFG_distance[0])\ndef_DFG_atom_2 = top.select(DFG_distance[1])\n\nfeat.add_distances([def_DFG_atom_1[0],def_DFG_atom_2[0]])\n\ndef convert_atom_list_to_resid(atom_list,topology):\n resid_set = set()\n for atom_index in atom_list:\n atom = topology.atom(atom_index)\n resid_set.add(atom.residue.index)\n resid = list(resid_set)\n if len(resid) == 1:\n resid = resid[0]\n else:\n print('your selection does not select a single residue')\n return resid\n\n # Two KER distances\nKER = ['resid 51 and resname LYS',\n 'resid 68 and resname GLU',\n 'resid 185 and resname ARG']\n\nKER_res = np.array([],dtype=np.int64)\nfor res in KER:\n atom_select = top.select(res)\n res_select = convert_atom_list_to_resid(atom_select,top)\n KER_res = np.append(KER_res, res_select )\n\nfeat.add_residue_mindist([[KER_res[0],KER_res[1]],[KER_res[1],KER_res[2]]])\n\n#Let's also add our D671 - R752 distance\nDR = ['resid 104 and (resname ASP or resname ASN)',\n 'resid 185 and resname ARG']\n\nDR_res = np.array([],dtype=np.int64)\nfor res in DR:\n atom_select = top.select(res)\n res_select = convert_atom_list_to_resid(atom_select,top)\n DR_res = np.append(DR_res, res_select )\n\nfeat.add_residue_mindist([[ DR_res[0], DR_res[1] ]])\n\n# DFG phi, psi, chi angles\n #Note that because of the way dihedrals are defined, we're also including\n # one residue before and after\nDFG_residues = ['resid 179 and resname ALA',\n 'resid 180 and resname ASP',\n 'resid 181 and resname PHE',\n 'resid 182 and resname GLY',\n 'resid 183 and resname MET']\nfor residue in DFG_residues:\n feat.add_backbone_torsions(residue)\n\nfor residue in DFG_residues:\n try: \n feat.add_chi1_torsions(residue)\n except:\n pass\n\n# other pseudo dihedrals\n# pseudo dihedrals from Roux Phys Chem B 2015 2D Umbrella Sampling paper\nUS2D_Abl = ['resid 179 and resname ALA and name CB',\n 'resid 179 and resname ALA and name CA',\n 'resid 181 and resname PHE and name CA',\n 'resid 181 and resname PHE and name CG']\n\nUS2D_Abl_atoms = np.array([],dtype=np.int64)\nfor atom in US2D_Abl:\n atom_select = int(top.select(atom))\n US2D_Abl_atoms = np.append(US2D_Abl_atoms, atom_select )\n\nfeat.add_dihedrals([US2D_Abl_atoms])\n\nUS2D_Src = ['resid 183 and resname MET and name CB',\n 'resid 183 and resname MET and name CA',\n 'resid 181 and resname PHE and name CA',\n 'resid 181 and resname PHE and name CG']\n\nUS2D_Src_atoms = np.array([],dtype=np.int64)\nfor atom in US2D_Src:\n atom_select = int(top.select(atom))\n US2D_Src_atoms = np.append(US2D_Src_atoms, atom_select )\n\nfeat.add_dihedrals([US2D_Src_atoms])\n\n# pseudo dihedrals from Mobitz are defined by four consecutive CA's\nMobitz1 = ['resid 179 and resname ALA and name CA',\n 'resid 180 and resname ASP and name CA',\n 'resid 181 and resname PHE and name CA',\n 'resid 182 and resname GLY and name CA']\n\nMobitz1_atoms = np.array([],dtype=np.int64)\nfor atom in Mobitz1:\n atom_select = int(top.select(atom))\n Mobitz1_atoms = np.append(Mobitz1_atoms, atom_select )\n\nfeat.add_dihedrals([Mobitz1_atoms])\n\nMobitz2 = ['resid 180 and resname ASP and name CA',\n 'resid 181 and resname PHE and name CA',\n 'resid 182 and resname GLY and name CA',\n 'resid 183 and resname MET and name CA']\n\nMobitz2_atoms = np.array([],dtype=np.int64)\nfor atom in Mobitz2:\n atom_select = int(top.select(atom))\n Mobitz2_atoms = np.append(Mobitz2_atoms, atom_select )\n\nfeat.add_dihedrals([Mobitz2_atoms])\n\n# minimal distances to include R-spine\nRspine = ['resid 72 and resname MET',\n 'resid 83 and resname LEU',\n 'resid 160 and resname HIS',\n 'resid 181 and resname PHE']\n\nRspine_res = np.array([],dtype=np.int64)\nfor res in Rspine:\n atom_select = top.select(res)\n res_select = convert_atom_list_to_resid(atom_select,top)\n Rspine_res = np.append(Rspine_res, res_select )\n\nfeat.add_residue_mindist([[Rspine_res[0],Rspine_res[1]],[Rspine_res[1],Rspine_res[2]],[Rspine_res[2],Rspine_res[3]]])\n\nprint('Final number of features')\nprint(feat.dimension())\n\nprint('running tica')\n\nsrc = coor.source(filenames_checked, features=feat)\ntica = coor.tica(src, stride=10,lag=100,kinetic_map=False,commute_map=True)\nY = tica.get_output()\n\nnp.save('tica_projection.npy',Y)\n\nY1 = [y[:,0] for y in Y]\nY2 = [y[:,1] for y in Y]\nY3 = [y[:,2] for y in Y]\nY4 = [y[:,3] for y in Y]\nY5 = [y[:,4] for y in Y]\nY6 = [y[:,5] for y in Y]\n\nimport corner\n\nsixtics=np.vstack((np.hstack(Y1),np.hstack(Y2),np.hstack(Y3),np.hstack(Y4),np.hstack(Y5),np.hstack(Y6))).T\n\ncorner.corner(sixtics, labels=[r\"$tic1$\", r\"$tic2$\", r\"$tic3$\",r\"$tic4$\", r\"$tic5$\", r\"$tic6$\", r\"$\\Gamma \\, [\\mathrm{parsec}]$\"], quantiles=[0.16, 0.5, 0.84],show_titles=True, title_kwargs={\"fontsize\": 12});\n\nplt.savefig('corner.png')\n\nplt.clf()\nplt.figure(figsize=(8,5))\nmplt.plot_free_energy(np.hstack(Y1),np.hstack(Y2))\nplt.xlabel('tic 1')\nplt.ylabel('tic 2')\n\nplt.savefig('tic1-tic2.png')\n\nplt.clf()\nplt.figure(figsize=(5,3))\nplt.plot(np.cumsum(tica.eigenvalues),'o')\nplt.xlabel('eigenvalue')\nplt.ylabel('cummulative sum')\n\nplt.savefig('cumsum_tica_eigenvalues.png')\n\nplt.clf()\nplt.title('Feature correlation to tIC 1')\nplt.bar(range(len(tica.feature_TIC_correlation[:,0])),abs(tica.feature_TIC_correlation[:,0]),align='center')\nplt.xlabel('Index within feature vector')\nplt.ylabel('Correlation')\nplt.tight_layout()\n\nplt.savefig('tic1_feature_corr.png')\n\nplt.clf()\nplt.title('Feature correlation to tIC 2')\nplt.bar(range(len(tica.feature_TIC_correlation[:,1])),abs(tica.feature_TIC_correlation[:,1]),align='center')\nplt.xlabel('Index within feature vector')\nplt.ylabel('Correlation')\nplt.tight_layout()\n\nplt.savefig('tic2_feature_corr.png')\n\nprint('running kmeans')\n\nclkmeans = coor.cluster_kmeans(Y,300,max_iter=300)\n\nplt.clf()\nplt.figure(figsize=(8,5))\nplt.plot(clkmeans.clustercenters[:,0], clkmeans.clustercenters[:,1],' ok')\nmplt.plot_free_energy(np.hstack(Y1),np.hstack(Y2))\nplt.xlabel('tic 1')\nplt.ylabel('tic 2')\n\nplt.savefig('kmeans_cluster-on_tic1tic2.png')\n\nnp.save('clkmeans_dtrajs.npy',clkmeans.dtrajs)\nnp.save('clkmeans_clustercenters.npy',clkmeans.clustercenters)\n\nprint('running MSM')\n\nMSM = msm.estimate_markov_model(clkmeans.dtrajs, 50)\n\ntime_scale_sep = MSM.timescales()[:-1]/MSM.timescales()[1:]\n##slow_indices = [index for index, value in enumerate(time_scale_sep) if value >= 1.5]\n##last_slow_index = slow_indices[-1]\n##n_macrostates_timescales = last_slow_index + 2\n#We are actually going to over ride all this machinery\nn_macrostates = 2\n\nplt.clf()\nplt.figure(figsize=(5,3))\nplt.plot(time_scale_sep, linewidth=0,marker='o')\n#plt.axvline(x=last_slow_index+0.5,color='r')\nplt.axvline(x=0.5,color='g')\nplt.xlabel('index'); plt.ylabel('timescale separation');\nplt.xlim(0,30)\n\nplt.savefig('timescale_separation.png')\n\n#print('%s macrostates chosen from timescale separation' %n_macrostates_timescales)\nprint('%s macrostates chosen because thats what we want' %n_macrostates)\n\nplt.clf()\nlags = [1,2,5,10,20,50,100,200,400]\nits = msm.its(clkmeans.dtrajs, lags=lags)\nmplt.plot_implied_timescales(its)\n\nplt.savefig('implied_timescale_plot.png')\nplt.clf()\n\nprint('fraction of states used = ', MSM.active_state_fraction)\nprint('fraction of counts used = ', MSM.active_count_fraction)\n\nmplt.plot_cktest(MSM.cktest(3));\n\nplt.savefig('cktest_msm.png')\n\nplt.clf()\nplt.figure(figsize=(8,5))\nmplt.plot_free_energy(np.hstack(Y1),np.hstack(Y2),weights=np.hstack(MSM.trajectory_weights()))\nplt.xlabel('tic 1')\nplt.ylabel('tic 2')\n\nplt.savefig('reweighted_tic1_tic2.png')\n\nprint('running hmm')\nHMM = msm.bayesian_hidden_markov_model(clkmeans.dtrajs,n_macrostates,lag=100)\nhmm_dist = HMM.metastable_distributions\nhmm_sets = HMM.metastable_sets\n\nplt.clf()\nplt.figure(figsize=(8,5))\nmplt.plot_free_energy(np.hstack(Y1),np.hstack(Y2),weights=np.hstack(MSM.trajectory_weights()))\ncolors = ['red','cyan','blue','purple','magenta','brown','black','white','orange','pink','yellowgreen']\nfor i in range(n_macrostates):\n plt.scatter(clkmeans.clustercenters[hmm_sets[i],0], clkmeans.clustercenters[hmm_sets[i],1], color=colors[i],s=50)\nplt.xlabel('tic 1')\nplt.ylabel('tic 2')\n\nplt.savefig('hmm_clusters_on_tic1_tic2.png')\n\nstate_1_colors = HMM.metastable_distributions[0]/max(HMM.metastable_distributions[0])\nstate_2_colors = HMM.metastable_distributions[1]/max(HMM.metastable_distributions[1])\n\nplt.clf()\nplt.figure(figsize=(8,5))\n#NOTE this needs to be changed if more than two macrostates are of interest\nmplt.plot_free_energy(np.hstack(Y1),np.hstack(Y2),weights=np.hstack(HMM.trajectory_weights()))\nfor i in range(len(clkmeans.clustercenters[:,0])):\n plt.scatter(clkmeans.clustercenters[i,0], clkmeans.clustercenters[i,1], color='red', s=100,alpha=(state_1_colors[i]))\n plt.scatter(clkmeans.clustercenters[i,0], clkmeans.clustercenters[i,1], color='cyan', s=100,alpha=(state_2_colors[i]))\nplt.xlabel('tic 1')\nplt.ylabel('tic 2')\n\nplt.savefig('hmm_clusters_on_tic1_tic2_fade.png')\n\nhmm_samples = HMM.sample_by_observation_probabilities(100)\n\nfor i in range(n_macrostates):\n coor.save_traj(src, hmm_samples[i], './hmm%s_100samples.xtc'%i)\n t = md.load( './hmm%s_100samples.xtc'%i,top=top)\n t[0].save_pdb('./hmm%s_100samples.pdb'%i)\n\nstatdist = MSM.stationary_distribution\nrelative_counts = MSM.count_matrix_active.sum(0) / np.sum(MSM.count_matrix_active)\n\nplt.clf()\nplt.figure()\nplt.scatter(statdist, relative_counts)\nplt.xlabel('MSM stationary distribution')\nplt.ylabel('Relative counts')\n\nplt.savefig('msm_sanity_check.png')\n\nstatdist = HMM.stationary_distribution\nrelative_counts = HMM.count_matrix_EM.sum(0) / np.sum(HMM.count_matrix_EM)\n\nplt.clf()\nplt.figure()\nplt.scatter(statdist, relative_counts)\nplt.xlabel('HMMstationary distribution')\nplt.ylabel('Relative counts')\n\nplt.savefig('hmm_sanity_check.png')\nplt.clf()\n\n# macrostate free energies\nf_i = -np.log(sorted(HMM.stationary_distribution))[::-1]\nf_i -= f_i.min()\nplt.figure()\nplt.plot(f_i, '.')\nplt.xlabel('Macrostate')\nplt.ylabel(r'$\\Delta G$ $(k_B T)$')\nplt.title('Macrostate free energies')\n\nplt.savefig('macrostate_free_energies.png')\nplt.clf()\n\ndelG_distribution = -np.log(np.transpose(HMM.sample_f('stationary_distribution'))[1]/\n np.transpose(HMM.sample_f('stationary_distribution'))[0])\n\ndelG_interval = np.percentile(a=delG_distribution, q=[2.5, 50.0, 97.5])\n\nplt.clf()\nplt.figure()\nplt.bar(0,delG_interval[1],yerr=[[delG_interval[1]-delG_interval[0]],[delG_interval[2]-delG_interval[1]]],color=colors,error_kw=dict(ecolor='gray',lw=2,capsize=5,capthick=2))\nplt.ylabel(r'$\\Delta G$ $(k_B T)$')\n\nplt.savefig('delG_states.png')\nplt.clf()\n\nnp.save('delG_distribution.npy',delG_distribution)\n\nprint('HMM stationary distribution')\nprint(HMM.stationary_distribution)\n\n#plot stationary distribution with errors\npi = HMM.stationary_distribution\npiL,piR = HMM.sample_conf('stationary_distribution')\nplt.xlim((-0.5,1.5))\nplt.ylabel('stationary distribution')\nplt.xlabel('state')\nfor i in range(2):\n plt.errorbar(i, pi[i], yerr=[[piL[i]], [piR[i]]],fmt='o',color=colors[i])\n\nplt.savefig('stationary_distribution.png')\nplt.clf()\n"
] |
[
[
"numpy.cumsum",
"matplotlib.pyplot.plot",
"numpy.hstack",
"matplotlib.pyplot.tight_layout",
"numpy.save",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"numpy.append",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.scatter",
"matplotlib.use",
"numpy.percentile",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel"
]
] |
LiYuRio/Paddle
|
[
"dbd6e2df9d074973b7ee177e2d6b96ed2318008e"
] |
[
"python/paddle/fluid/tests/unittests/test_switch_autotune.py"
] |
[
"# Copyright (c) 2022 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.\n\nimport paddle\nimport unittest\nimport numpy\n\n\nclass SimpleNet(paddle.nn.Layer):\n def __init__(self):\n super(SimpleNet, self).__init__()\n self.conv = paddle.nn.Conv2D(1, 2, (3, 3))\n\n def forward(self, image, label=None):\n return self.conv(image)\n\n\ndef train_dygraph(net, data):\n out = net(data)\n loss = paddle.mean(out)\n adam = paddle.optimizer.Adam(parameters=net.parameters())\n out.backward()\n adam.step()\n adam.clear_grad()\n\n\ndef static_program(net, data):\n out = net(data)\n loss = paddle.mean(out)\n adam = paddle.optimizer.Adam()\n adam.minimize(loss)\n return loss\n\n\nclass TestAutoTune(unittest.TestCase):\n def test_autotune(self):\n paddle.fluid.core.disable_autotune()\n status = paddle.fluid.core.autotune_status()\n self.assertEqual(status[\"use_autotune\"], False)\n\n paddle.fluid.core.enable_autotune()\n status = paddle.fluid.core.autotune_status()\n self.assertEqual(status[\"use_autotune\"], True)\n\n def check_status(self, expected_res):\n status = paddle.fluid.core.autotune_status()\n for key in status.keys():\n self.assertEqual(status[key], expected_res[key])\n\n\nclass TestDygraphAutoTuneStatus(TestAutoTune):\n def run_program(self, enable_autotune):\n if enable_autotune:\n paddle.fluid.core.enable_autotune()\n else:\n paddle.fluid.core.disable_autotune()\n paddle.fluid.core.autotune_range(1, 2)\n x_var = paddle.uniform((1, 1, 8, 8), dtype='float32', min=-1., max=1.)\n net = SimpleNet()\n for i in range(3):\n train_dygraph(net, x_var)\n if i >= 1 and i < 2:\n expected_res = {\n \"step_id\": i,\n \"use_autotune\": enable_autotune,\n \"cache_size\": 0,\n \"cache_hit_rate\": 0\n }\n self.check_status(expected_res)\n else:\n expected_res = {\n \"step_id\": i,\n \"use_autotune\": False,\n \"cache_size\": 0,\n \"cache_hit_rate\": 0\n }\n self.check_status(expected_res)\n\n def test_enable_autotune(self):\n self.run_program(enable_autotune=True)\n\n def test_disable_autotune(self):\n self.run_program(enable_autotune=False)\n\n\nclass TestStaticAutoTuneStatus(TestAutoTune):\n def run_program(self, enable_autotune):\n paddle.enable_static()\n if enable_autotune:\n paddle.fluid.core.enable_autotune()\n else:\n paddle.fluid.core.disable_autotune()\n paddle.fluid.core.autotune_range(1, 2)\n\n data_shape = [1, 1, 8, 8]\n data = paddle.static.data(name='X', shape=data_shape, dtype='float32')\n net = SimpleNet()\n loss = static_program(net, data)\n place = paddle.CUDAPlace(0) if paddle.fluid.core.is_compiled_with_cuda(\n ) else paddle.CPUPlace()\n exe = paddle.static.Executor(place)\n exe.run(paddle.static.default_startup_program())\n x = numpy.random.random(size=data_shape).astype('float32')\n\n for i in range(3):\n exe.run(feed={'X': x}, fetch_list=[loss])\n status = paddle.fluid.core.autotune_status()\n # In static mode, the startup_program will run at first.\n # The expected step_id will be increased by 1.\n if i >= 0 and i < 1:\n expected_res = {\n \"step_id\": i + 1,\n \"use_autotune\": enable_autotune,\n \"cache_size\": 0,\n \"cache_hit_rate\": 0\n }\n self.check_status(expected_res)\n else:\n expected_res = {\n \"step_id\": i + 1,\n \"use_autotune\": False,\n \"cache_size\": 0,\n \"cache_hit_rate\": 0\n }\n self.check_status(expected_res)\n paddle.disable_static()\n\n def test_enable_autotune(self):\n self.run_program(enable_autotune=True)\n\n def test_disable_autotune(self):\n self.run_program(enable_autotune=False)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.random.random"
]
] |
WangFeng18/dino
|
[
"1a4e49bd0e99d7e205338b14994a1d57c3084cfe"
] |
[
"FastLinear/vision_transformer.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nMostly copy-paste from timm library.\nhttps://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n\"\"\"\nimport math\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\n\nfrom utils import trunc_normal_\n\n\ndef drop_path(x, drop_prob: float = 0., training: bool = False):\n if drop_prob == 0. or not training:\n return x\n keep_prob = 1 - drop_prob\n shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets\n random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)\n random_tensor.floor_() # binarize\n output = x.div(keep_prob) * random_tensor\n return output\n\n\nclass DropPath(nn.Module):\n \"\"\"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n \"\"\"\n def __init__(self, drop_prob=None):\n super(DropPath, self).__init__()\n self.drop_prob = drop_prob\n\n def forward(self, x):\n return drop_path(x, self.drop_prob, self.training)\n\n\nclass Mlp(nn.Module):\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Linear(in_features, hidden_features)\n self.act = act_layer()\n self.fc2 = nn.Linear(hidden_features, out_features)\n self.drop = nn.Dropout(drop)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\nclass Attention(nn.Module):\n def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):\n super().__init__()\n self.num_heads = num_heads\n head_dim = dim // num_heads\n self.scale = qk_scale or head_dim ** -0.5\n\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n\n attn = (q @ k.transpose(-2, -1)) * self.scale\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x, attn\n\n\nclass Block(nn.Module):\n def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n super().__init__()\n self.norm1 = norm_layer(dim)\n self.attn = Attention(\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n def forward(self, x, return_attention=False):\n y, attn = self.attn(self.norm1(x))\n if return_attention:\n return attn\n x = x + self.drop_path(y)\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n return x\n\n\nclass PatchEmbed(nn.Module):\n \"\"\" Image to Patch Embedding\n \"\"\"\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\n super().__init__()\n num_patches = (img_size // patch_size) * (img_size // patch_size)\n self.img_size = img_size\n self.patch_size = patch_size\n self.num_patches = num_patches\n\n self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n\n def forward(self, x):\n B, C, H, W = x.shape\n x = self.proj(x).flatten(2).transpose(1, 2)\n return x\n\n\nclass VisionTransformer(nn.Module):\n \"\"\" Vision Transformer \"\"\"\n def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,\n num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,\n drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):\n super().__init__()\n self.num_features = self.embed_dim = embed_dim\n\n self.patch_embed = PatchEmbed(\n img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)\n num_patches = self.patch_embed.num_patches\n\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))\n self.pos_drop = nn.Dropout(p=drop_rate)\n\n dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule\n self.blocks = nn.ModuleList([\n Block(\n dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,\n drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)\n for i in range(depth)])\n self.norm = norm_layer(embed_dim)\n\n # Classifier head\n self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n\n trunc_normal_(self.pos_embed, std=.02)\n trunc_normal_(self.cls_token, std=.02)\n self.apply(self._init_weights)\n\n def _init_weights(self, m):\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n def interpolate_pos_encoding(self, x, w, h):\n npatch = x.shape[1] - 1\n N = self.pos_embed.shape[1] - 1\n if npatch == N and w == h:\n return self.pos_embed\n class_pos_embed = self.pos_embed[:, 0]\n patch_pos_embed = self.pos_embed[:, 1:]\n dim = x.shape[-1]\n w0 = w // self.patch_embed.patch_size\n h0 = h // self.patch_embed.patch_size\n # we add a small number to avoid floating point error in the interpolation\n # see discussion at https://github.com/facebookresearch/dino/issues/8\n w0, h0 = w0 + 0.1, h0 + 0.1\n patch_pos_embed = nn.functional.interpolate(\n patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),\n scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),\n mode='bicubic',\n )\n assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]\n patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\n return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)\n\n def prepare_tokens(self, x):\n B, nc, w, h = x.shape\n x = self.patch_embed(x) # patch linear embedding\n\n # add the [CLS] token to the embed patch tokens\n cls_tokens = self.cls_token.expand(B, -1, -1)\n x = torch.cat((cls_tokens, x), dim=1)\n\n # add positional encoding to each token\n x = x + self.interpolate_pos_encoding(x, w, h)\n\n return self.pos_drop(x)\n\n def forward(self, x):\n x = self.prepare_tokens(x)\n for blk in self.blocks:\n x = blk(x)\n x = self.norm(x)\n return x[:, 0]\n\n def get_last_selfattention(self, x):\n x = self.prepare_tokens(x)\n for i, blk in enumerate(self.blocks):\n if i < len(self.blocks) - 1:\n x = blk(x)\n else:\n # return attention of the last block\n return blk(x, return_attention=True)\n\n def get_intermediate_layers(self, x, n=1):\n x = self.prepare_tokens(x)\n # we return the output tokens from the `n` last blocks\n output = []\n for i, blk in enumerate(self.blocks):\n x = blk(x)\n if len(self.blocks) - i <= n:\n output.append(self.norm(x))\n return output\n\n\ndef vit_tiny(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\ndef vit_small(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n\ndef vit_base(patch_size=16, **kwargs):\n model = VisionTransformer(\n patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n return model\n\n"
] |
[
[
"torch.nn.Dropout",
"torch.linspace",
"torch.cat",
"torch.zeros",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.rand"
]
] |
jarad/dep
|
[
"fe73982f4c70039e1a31b9e8e2d9aac31502f803"
] |
[
"scripts/util/dump_ofe_results.py"
] |
[
"\"\"\"Summarize the OFE files\"\"\"\nfrom __future__ import print_function\nimport os\nimport datetime\n\nimport pandas as pd\nfrom tqdm import tqdm\nfrom pyiem.dep import read_ofe, read_man, read_slp\n\n\"\"\"\"\n No-till (1) (2-5)\n B - Soy B1 B25 IniCropDef.Default\n F - forest F1 F25 IniCropDef.Tre_2239\n G - Sorghum\n P - Pasture P1 P25 IniCropDef.gra_3425\n C - Corn C1 C25 IniCropDef.Default\n R - Other crops R1 R25 IniCropDef.Aft_12889\n T - Water\n U - Developed\n X - Unclassified\n I - Idle\n L - Double Crop (started previous year)\n W - Wheat\n N - ??? *see 27 Sep 2016 email from dave, it is unused, so treat as I*\n\"\"\"\nLABEL2CODE = {\n \"soybean2\": \"B\",\n \"Soy_2191\": \"B\",\n \"Soy_2192\": \"B\",\n \"Soy_2193\": \"B\",\n \"Soy_2194\": \"B\",\n \"Corn\": \"C\",\n \"Cor_0967\": \"C\",\n \"Cor_0966\": \"C\",\n \"Cor_0965\": \"C\",\n \"Cor_0964\": \"C\",\n \"Tre_2932\": \"I\",\n \"bromegr1\": \"P\",\n \"Bar_8319\": \"W\",\n}\n# 2007 is skipped\nYEARS = (2017 - 2008) + 1\n\n\ndef get_rotation_string(manres, ofe):\n \"\"\"Uffff\"\"\"\n codes = []\n for rot in manres[\"rotations\"]:\n idx = rot[ofe - 1][\"yearindex\"]\n ntype = manres[\"scens\"][idx - 1][\"ntype\"]\n codes.append(LABEL2CODE[manres[\"crops\"][ntype - 1][\"crpnam\"]])\n return \"\".join(codes)\n\n\ndef get_soils(prjfn):\n \"\"\"Hack to get soil names from prj and soil file\"\"\"\n soils = []\n for line in open(prjfn):\n if line.find(\"/sol_input/\") == -1:\n continue\n soils.append(line.split(\"_\")[2].split(\".\")[0])\n # now read sol file\n names = []\n for line in open(prjfn.replace(\"prj\", \"sol\")):\n if not line.startswith(\"'\"):\n continue\n names.append(line[1:].split(\"'\")[0])\n if len(names) == len(soils):\n return soils\n # uh oh, more work to do\n mapping = {}\n i = 0\n for name in names:\n if name in mapping:\n continue\n mapping[name] = soils[i]\n i += 1\n return [mapping[name] for name in names]\n\n\ndef main():\n \"\"\"Go Main Go\"\"\"\n # ['id', 'CropRotationString', 'slope',\n # 'rainfall', 'runoff', 'detach', 'delivery'])\n rows = []\n for root, _dirs, files in tqdm(os.walk(\"/i/0/ofe\")):\n for filename in files:\n ofedf = read_ofe(\"%s/%s\" % (root, filename))\n # Drop any 2007 or 2018+ data\n ofedf = ofedf[\n (ofedf[\"date\"] < datetime.date(2018, 1, 1))\n & (ofedf[\"date\"] >= datetime.date(2008, 1, 1))\n ]\n # Figure out the crop string\n man = \"%s/%s\" % (\n root.replace(\"ofe\", \"man\"),\n filename.replace(\"ofe\", \"man\"),\n )\n try:\n manres = read_man(man)\n except Exception as exp:\n print(\"failure reading %s\\n%s\" % (man, exp))\n continue\n\n slp = \"%s/%s\" % (\n root.replace(\"ofe\", \"slp\"),\n filename.replace(\"ofe\", \"slp\"),\n )\n slpres = read_slp(slp)\n soils = get_soils(slp.replace(\"slp\", \"prj\"))\n for ofe in ofedf[\"ofe\"].unique():\n myofe = ofedf[ofedf[\"ofe\"] == ofe]\n length = slpres[ofe - 1][\"x\"][-1] - slpres[ofe - 1][\"x\"][0]\n slp = (\n slpres[ofe - 1][\"y\"][0] - slpres[ofe - 1][\"y\"][-1]\n ) / length\n rows.append(\n {\n \"id\": \"%s_%s\" % (filename[:-4], ofe),\n \"huc12\": filename[:12],\n \"fpath\": filename.split(\"_\")[1][:-4],\n \"ofe\": ofe,\n \"CropRotationString\": (\n get_rotation_string(manres, ofe)\n ),\n \"slope[1]\": slp,\n \"soil_mukey\": soils[ofe - 1],\n \"rainfall\": -1,\n \"runoff[mm/yr]\": myofe[\"runoff\"].sum() / YEARS,\n \"detach\": -1,\n \"length[m]\": length,\n \"delivery[t/a/yr]\": (\n myofe[\"sedleave\"].sum() / YEARS / length * 4.463\n ),\n }\n )\n\n df = pd.DataFrame(rows)\n df.to_csv(\"results.csv\", index=False)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.DataFrame"
]
] |
dfyz/DeepSpeed
|
[
"163b392661c9f1dda09246e2309c6caf53d70992"
] |
[
"deepspeed/inference/engine.py"
] |
[
"'''\nCopyright 2021 The Microsoft DeepSpeed Team\n'''\nimport torch\nimport os\nfrom datetime import timedelta\nfrom torch.nn.modules import Module\nimport torch.distributed as dist\nfrom ..runtime.state_dict_factory import SDLoaderFactory\nfrom ..runtime.weight_quantizer import WeightQuantization\nfrom ..module_inject.replace_module import replace_transformer_layer\nfrom ..constants import INFERENCE_GENERIC_MODE\nfrom ..module_inject import replace_policy\nfrom ..utils import logger, init_distributed\n\nfrom ..pipe import PipelineModule\n\n\nclass InferenceEngine(Module):\n def __init__(self,\n model,\n mp_size=1,\n mpu=None,\n checkpoint=None,\n dtype=None,\n injection_dict=None,\n replace_method='auto',\n quantization_setting=None):\n\n super(InferenceEngine, self).__init__()\n\n self.module = model\n\n self._get_model_config_generate()\n\n self.mp_world_size = mp_size\n self.checkpoint = checkpoint\n self.dtype = dtype\n self.injection_dict = injection_dict\n self.mp_group = None\n self.mpu = mpu\n self._validate_args(mpu)\n self.replace_method = replace_method\n self.quantize_merge_count = 1\n self.quantization_scales = None\n\n if self.mpu:\n self.mp_world_size = dist.get_world_size(\n group=self.mpu.get_model_parallel_group())\n self.mp_group = self.mpu.get_model_parallel_group()\n elif self.mp_world_size > 1 and not dist.is_initialized():\n self._create_model_parallel_group()\n else:\n self.module.to(torch.cuda.current_device())\n\n self._check_quantize_setting(quantization_setting)\n\n if self.checkpoint:\n self._load_checkpoint(self.checkpoint)\n\n # convert model to intended dtype\n if self.dtype:\n self._convert_to_dtype()\n\n # apply injection policy\n if self.injection_dict:\n for client_module, injection_policy in self.injection_dict.items():\n self._apply_injection_policy(client_module, injection_policy)\n elif replace_method == 'auto':\n self._apply_injection_policy()\n\n if self.mp_world_size > 1:\n self.model_orig_fwd = self.module.forward\n self.module.forward = self.forward\n else:\n self.module.register_forward_pre_hook(self._pre_forward_hook)\n\n def _get_model_config_generate(self):\n if hasattr(self.module, 'config'):\n self.config = self.module.config\n else:\n self.config = None\n if hasattr(self.module, 'generate'):\n self.generate = self.module.generate\n else:\n self.generate = None\n\n def _create_model_parallel_group(self):\n # Call the init process\n\n init_distributed()\n\n local_rank = int(os.getenv('LOCAL_RANK', '0'))\n torch.cuda.set_device(local_rank)\n\n ranks = [i for i in range(self.mp_world_size)]\n self.mp_group = dist.new_group(ranks)\n\n self.module.to(torch.cuda.current_device())\n for p in self.module.parameters():\n if torch.is_tensor(p):\n dist.broadcast(p, 0)\n\n def _check_quantize_setting(self, quantization_setting):\n self.quatize_bits = 8\n self.mlp_extra_grouping = False\n self.quantize_groups = 1\n if quantization_setting is None:\n return\n elif type(quantization_setting) is tuple:\n self.mlp_extra_grouping, \\\n self.quantize_groups = quantization_setting\n else:\n self.quantize_groups = quantization_setting\n\n def _validate_args(self, mpu):\n assert isinstance(self.module, Module)\n assert isinstance(self.mp_world_size, int)\n assert self.mp_world_size >= 1\n\n if mpu:\n methods = [f\"get_model_parallel_group\"]\n methods.extend([f\"get_data_parallel_group\"])\n for method in methods:\n assert hasattr(mpu, method), f\"mpu is missing {method}\"\n\n assert self.checkpoint is None or isinstance(self.checkpoint, str)\n\n supported_dtypes = [torch.half, torch.int8, torch.float]\n assert self.dtype is None or self.dtype in supported_dtypes, f\"dtype={self.dtype} is not in the \\\n list of supported dtypes {supported_dtypes}\"\n\n assert self.injection_dict is None or isinstance(self.injection_dict, dict)\n\n def _apply_injection_policy(self, client_module=None, injection_policy=None):\n replace_transformer_layer(client_module,\n self.module,\n policy=injection_policy,\n mp_size=self.mp_world_size,\n mp_group=self.mp_group,\n config=self.config,\n fp16=(self.dtype == torch.half),\n training=False,\n quantize=(self.dtype == torch.int8),\n quantize_settings=(self.quantization_scales,\n self.quantize_merge_count,\n self.mlp_extra_grouping,\n self.quantize_groups))\n\n def _load_checkpoint(self, load_dir, load_module_strict=True):\n sd_loader = SDLoaderFactory.get_sd_loader_json(load_dir)\n is_pipe_parallel = isinstance(self.module, PipelineModule)\n\n assert (not is_pipe_parallel),\\\n 'pipeline parallelism is currently not supported in inference.'\n\n mp_rank = 0 if self.mp_group is None else dist.get_rank(group=self.mp_group)\n\n load_path, checkpoint, quantize_config = sd_loader.load(self.mp_world_size,\n mp_rank,\n is_pipe_parallel=is_pipe_parallel,\n quantize=(self.dtype is torch.int8),\n quantize_groups=self.quantize_groups,\n mlp_extra_grouping=self.mlp_extra_grouping)\n\n self.quantization_scales, self.quantize_merge_count = quantize_config\n\n if is_pipe_parallel:\n # Pipeline parallelism uses this to load its own checkpoint files.\n self._curr_ckpt_path = load_dir\n\n self.module.load_state_dict(state_dict=checkpoint['model'],\n strict=load_module_strict)\n\n def _convert_to_dtype(self):\n if self.dtype is torch.int8 and self.quantization_scales is None:\n quantizer = WeightQuantization(mlp_extra_grouping=self.mlp_extra_grouping)\n model, self.quantization_scales = quantizer.model_quantize(self.module,\n self.injection_dict,\n self.quatize_bits,\n self.quantize_groups)\n elif self.dtype == torch.half:\n self.module.half()\n elif self.dtype == torch.float:\n self.module.float()\n\n def _pre_forward_hook(self, module, *inputs, **kwargs):\n for input in inputs:\n if torch.is_tensor(input):\n input = input.to(torch.cuda.current_device())\n if self.mp_world_size > 1:\n if not input.is_contiguous():\n input = input.contiguous()\n dist.broadcast(input, 0)\n\n for k in kwargs:\n if torch.is_tensor(kwargs[k]):\n kwargs[k] = kwargs[k].to(torch.cuda.current_device())\n if self.mp_world_size > 1:\n if not kwargs[k].is_contiguous():\n kwargs[k] = kwargs[k].contiguous()\n dist.broadcast(kwargs[k], 0)\n\n def forward(self, *inputs, **kwargs):\n \"\"\"Execute forward propagation\n\n Arguments:\n *inputs: Variable length input list\n **kwargs: variable length keyword arguments\n \"\"\"\n if self.mp_world_size > 1:\n if self.mpu is None:\n for input in inputs:\n if torch.is_tensor(input):\n input = input.to(torch.cuda.current_device())\n if self.mp_world_size > 1:\n if not input.is_contiguous():\n input = input.contiguous()\n dist.broadcast(input, 0)\n\n for k in kwargs:\n if torch.is_tensor(kwargs[k]):\n kwargs[k] = kwargs[k].to(torch.cuda.current_device())\n if self.mp_world_size > 1:\n if not kwargs[k].is_contiguous():\n kwargs[k] = kwargs[k].contiguous()\n dist.broadcast(kwargs[k], 0)\n\n return self.model_orig_fwd(*inputs, **kwargs)\n return self.module(*inputs, **kwargs)\n"
] |
[
[
"torch.distributed.broadcast",
"torch.cuda.set_device",
"torch.cuda.current_device",
"torch.distributed.is_initialized",
"torch.is_tensor",
"torch.distributed.new_group",
"torch.distributed.get_rank"
]
] |
qihongl/ntm_keras
|
[
"f33d3c444ea4dd62bceb5011e46c452c51c9cf4a"
] |
[
"view_weights.py"
] |
[
"from keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\nfrom skimage.viewer import ImageViewer, CollectionViewer\n\nm = Sequential()\nm.add(Dense(100, input_dim=30))\n\n\ndef weights_viewer(path):\n w = []\n for i in range(1000):\n filename = \"model.ckpt.{:04d}.hdf5\".format(i)\n m.load_weights(path + filename)\n k, b = m.get_weights()\n i = np.concatenate((k, np.ones((2, 100)), b[None, ]))\n w.append(i)\n CollectionViewer(w).show()\n\n\nweights_viewer(\"logs/2017-08-19_17:54:43_-_NTM_-_dense/\")\n"
] |
[
[
"numpy.ones"
]
] |
chengxinjiang/NoisePy
|
[
"3a7c23cf3a069db10a620e1519f67434db0dd892"
] |
[
"src/noise_module.py"
] |
[
"import os\nimport glob\nimport copy\nimport obspy\nimport scipy\nimport time\nimport pycwt\nimport pyasdf\nimport datetime\nimport numpy as np\nimport pandas as pd\nfrom numba import jit\nfrom scipy.signal import hilbert\nfrom obspy.signal.util import _npts2nfft\nfrom obspy.signal.invsim import cosine_taper\nfrom scipy.fftpack import fft,ifft,next_fast_len\nfrom obspy.signal.filter import bandpass,lowpass\nfrom obspy.signal.regression import linear_regression\nfrom obspy.core.util.base import _get_function_from_entry_point\nfrom obspy.core.inventory import Inventory, Network, Station, Channel, Site\n\n\n'''\nThis VERY LONG noise module file is necessary to keep the NoisePy working properly. In general,\nthe modules are organized based on their functionality in the following way. it includes:\n\n1) core functions called directly by the main NoisePy scripts;\n2) utility functions used by the core functions;\n3) monitoring functions representing different methods to measure dv/v;\n4) monitoring utility functions used by the monitoring functions.\n\nby: Chengxin Jiang ([email protected])\n Marine Denolle ([email protected])\n\nseveral utility functions are modified based on https://github.com/tclements/noise\n'''\n\n####################################################\n############## CORE FUNCTIONS ######################\n####################################################\n\ndef get_event_list(str1,str2,inc_hours):\n '''\n this function calculates the event list between time1 and time2 by increment of inc_hours\n in the formate of %Y_%m_%d_%H_%M_%S' (used in S0A & S0B)\n PARAMETERS:\n ----------------\n str1: string of the starting time -> 2010_01_01_0_0\n str2: string of the ending time -> 2010_10_11_0_0\n inc_hours: integer of incremental hours\n RETURNS:\n ----------------\n event: a numpy character list\n '''\n date1=str1.split('_')\n date2=str2.split('_')\n y1=int(date1[0]);m1=int(date1[1]);d1=int(date1[2])\n h1=int(date1[3]);mm1=int(date1[4]);mn1=int(date1[5])\n y2=int(date2[0]);m2=int(date2[1]);d2=int(date2[2])\n h2=int(date2[3]);mm2=int(date2[4]);mn2=int(date2[5])\n\n d1=datetime.datetime(y1,m1,d1,h1,mm1,mn1)\n d2=datetime.datetime(y2,m2,d2,h2,mm2,mn2)\n dt=datetime.timedelta(hours=inc_hours)\n\n event = []\n while(d1<d2):\n event.append(d1.strftime('%Y_%m_%d_%H_%M_%S'))\n d1+=dt\n event.append(d2.strftime('%Y_%m_%d_%H_%M_%S'))\n\n return event\n\ndef make_timestamps(prepro_para):\n '''\n this function prepares the timestamps of both the starting and ending time of each mseed/sac file that\n is stored on local machine. this time info is used to search all stations in specific time chunck\n when preparing noise data in ASDF format. it creates a csv file containing all timestamp info if the\n file does not exist (used in S0B)f\n PARAMETERS:\n -----------------------\n prepro_para: a dic containing all pre-processing parameters used in S0B\n RETURNS:\n -----------------------\n all_stimes: numpy float array containing startting and ending time for all SAC/mseed files\n '''\n # load parameters from para dic\n wiki_file = prepro_para['wiki_file']\n messydata = prepro_para['messydata']\n RAWDATA = prepro_para['RAWDATA']\n allfiles_path = prepro_para['allfiles_path']\n\n if os.path.isfile(wiki_file):\n tmp = pd.read_csv(wiki_file)\n allfiles = tmp['names']\n all_stimes = np.zeros(shape=(len(allfiles),2),dtype=np.float)\n all_stimes[:,0] = tmp['starttime']\n all_stimes[:,1] = tmp['endtime']\n\n # have to read each sac/mseed data one by one\n else:\n allfiles = glob.glob(allfiles_path)\n nfiles = len(allfiles)\n if not nfiles: raise ValueError('Abort! no data found in subdirectory of %s'%RAWDATA)\n all_stimes = np.zeros(shape=(nfiles,2),dtype=np.float)\n\n if messydata:\n # get VERY precise trace-time from the header\n for ii in range(nfiles):\n try:\n tr = obspy.read(allfiles[ii])\n all_stimes[ii,0] = tr[0].stats.starttime-obspy.UTCDateTime(1970,1,1)\n all_stimes[ii,1] = tr[0].stats.endtime-obspy.UTCDateTime(1970,1,1)\n except Exception as e:\n print(e);continue\n else:\n # get rough estimates of the time based on the folder: need modified to accommodate your data\n for ii in range(nfiles):\n year = int(allfiles[ii].split('/')[-2].split('_')[1])\n #julia = int(allfiles[ii].split('/')[-2].split('_')[2])\n #all_stimes[ii,0] = obspy.UTCDateTime(year=year,julday=julia)-obspy.UTCDateTime(year=1970,month=1,day=1)\n month = int(allfiles[ii].split('/')[-2].split('_')[2])\n day = int(allfiles[ii].split('/')[-2].split('_')[3])\n all_stimes[ii,0] = obspy.UTCDateTime(year=year,month=month,day=day)-obspy.UTCDateTime(year=1970,month=1,day=1)\n all_stimes[ii,1] = all_stimes[ii,0]+86400\n\n # save name and time info for later use if the file not exist\n if not os.path.isfile(wiki_file):\n wiki_info = {'names':allfiles,'starttime':all_stimes[:,0],'endtime':all_stimes[:,1]}\n df = pd.DataFrame(wiki_info,columns=['names','starttime','endtime'])\n df.to_csv(wiki_file)\n return all_stimes\n\ndef preprocess_raw(st,inv,prepro_para,date_info):\n '''\n this function pre-processes the raw data stream by:\n 1) check samping rate and gaps in the data;\n 2) remove sigularity, trend and mean of each trace\n 3) filter and correct the time if integer time are between sampling points\n 4) remove instrument responses with selected methods including:\n \"inv\" -> using inventory information to remove_response;\n \"spectrum\" -> use the inverse of response spectrum. (a script is provided in additional_module to estimate response spectrum from RESP files)\n \"RESP_files\" -> use the raw download RESP files\n \"polezeros\" -> use pole/zero info for a crude correction of response\n 5) trim data to a day-long sequence and interpolate it to ensure starting at 00:00:00.000\n (used in S0A & S0B)\n PARAMETERS:\n -----------------------\n st: obspy stream object, containing noise data to be processed\n inv: obspy inventory object, containing stations info\n prepro_para: dict containing fft parameters, such as frequency bands and selection for instrument response removal etc.\n date_info: dict of start and end time of the stream data\n RETURNS:\n -----------------------\n ntr: obspy stream object of cleaned, merged and filtered noise data\n '''\n # load paramters from fft dict\n rm_resp = prepro_para['rm_resp']\n if 'rm_resp_out' in prepro_para.keys():\n rm_resp_out = prepro_para['rm_resp_out']\n else:\n rm_resp_out = 'VEL'\n respdir = prepro_para['respdir']\n freqmin = prepro_para['freqmin']\n freqmax = prepro_para['freqmax']\n samp_freq = prepro_para['samp_freq']\n\n # parameters for butterworth filter\n f1 = 0.9*freqmin;f2=freqmin\n if 1.1*freqmax > 0.45*samp_freq:\n f3 = 0.4*samp_freq\n f4 = 0.45*samp_freq\n else:\n f3 = freqmax\n f4= 1.1*freqmax\n pre_filt = [f1,f2,f3,f4]\n\n # check sampling rate and trace length\n st = check_sample_gaps(st,date_info)\n if len(st) == 0:\n print('No traces in Stream: Continue!');return st\n sps = int(st[0].stats.sampling_rate)\n station = st[0].stats.station\n\n # remove nan/inf, mean and trend of each trace before merging\n for ii in range(len(st)):\n\n #-----set nan/inf values to zeros (it does happens!)-----\n tttindx = np.where(np.isnan(st[ii].data))\n if len(tttindx) >0:st[ii].data[tttindx]=0\n tttindx = np.where(np.isinf(st[ii].data))\n if len(tttindx) >0:st[ii].data[tttindx]=0\n\n st[ii].data = np.float32(st[ii].data)\n st[ii].data = scipy.signal.detrend(st[ii].data,type='constant')\n st[ii].data = scipy.signal.detrend(st[ii].data,type='linear')\n\n # merge, taper and filter the data\n if len(st)>1:st.merge(method=1,fill_value=0)\n st[0].taper(max_percentage=0.05,max_length=50)\t# taper window\n st[0].data = np.float32(bandpass(st[0].data,pre_filt[0],pre_filt[-1],df=sps,corners=4,zerophase=True))\n\n # make downsampling if needed\n if abs(samp_freq-sps) > 1E-4:\n # downsampling here\n st.interpolate(samp_freq,method='weighted_average_slopes')\n delta = st[0].stats.delta\n\n # when starttimes are between sampling points\n fric = st[0].stats.starttime.microsecond%(delta*1E6)\n if fric>1E-4:\n st[0].data = segment_interpolate(np.float32(st[0].data),float(fric/(delta*1E6)))\n #--reset the time to remove the discrepancy---\n st[0].stats.starttime-=(fric*1E-6)\n\n # remove traces of too small length\n\n # options to remove instrument response\n if rm_resp != 'no':\n if rm_resp != 'inv':\n if (respdir is None) or (not os.path.isdir(respdir)):\n raise ValueError('response file folder not found! abort!')\n\n if rm_resp == 'inv':\n #----check whether inventory is attached----\n if not inv[0][0][0].response:\n raise ValueError('no response found in the inventory! abort!')\n else:\n try:\n print('removing response for %s using inv'%st[0])\n st[0].attach_response(inv)\n st[0].remove_response(output=rm_resp_out,pre_filt=pre_filt,water_level=60)\n except Exception:\n st = []\n return st\n\n elif rm_resp == 'spectrum':\n print('remove response using spectrum')\n specfile = glob.glob(os.path.join(respdir,'*'+station+'*'))\n if len(specfile)==0:\n raise ValueError('no response sepctrum found for %s' % station)\n st = resp_spectrum(st,specfile[0],samp_freq,pre_filt)\n\n elif rm_resp == 'RESP':\n print('remove response using RESP files')\n resp = glob.glob(os.path.join(respdir,'RESP.'+station+'*'))\n if len(resp)==0:\n raise ValueError('no RESP files found for %s' % station)\n seedresp = {'filename':resp[0],'date':date_info['starttime'],'units':'DIS'}\n st.simulate(paz_remove=None,pre_filt=pre_filt,seedresp=seedresp[0])\n\n elif rm_resp == 'polozeros':\n print('remove response using polos and zeros')\n paz_sts = glob.glob(os.path.join(respdir,'*'+station+'*'))\n if len(paz_sts)==0:\n raise ValueError('no polozeros found for %s' % station)\n st.simulate(paz_remove=paz_sts[0],pre_filt=pre_filt)\n\n else:\n raise ValueError('no such option for rm_resp! please double check!')\n\n ntr = obspy.Stream()\n # trim a continous segment into user-defined sequences\n st[0].trim(starttime=date_info['starttime'],endtime=date_info['endtime'],pad=True,fill_value=0)\n ntr.append(st[0])\n\n return ntr\n\n\ndef stats2inv(stats,prepro_para,locs=None):\n '''\n this function creates inventory given the stats parameters in an obspy stream or a station list.\n (used in S0B)\n PARAMETERS:\n ------------------------\n stats: obspy trace stats object containing all station header info\n prepro_para: dict containing fft parameters, such as frequency bands and selection for instrument response removal etc.\n locs: panda data frame of the station list. it is needed for convering miniseed files into ASDF\n RETURNS:\n ------------------------\n inv: obspy inventory object of all station info to be used later\n '''\n staxml = prepro_para['stationxml']\n respdir = prepro_para['respdir']\n input_fmt = prepro_para['input_fmt']\n\n if staxml:\n if not respdir:\n raise ValueError('Abort! staxml is selected but no directory is given to access the files')\n else:\n invfile = glob.glob(os.path.join(respdir,'*'+stats.station+'*'))\n if os.path.isfile(str(invfile)):\n inv = obspy.read_inventory(invfile)\n return inv\n\n inv = Inventory(networks=[],source=\"homegrown\")\n\n if input_fmt=='sac':\n net = Network(\n # This is the network code according to the SEED standard.\n code=stats.network,\n stations=[],\n description=\"created from SAC and resp files\",\n start_date=stats.starttime)\n\n sta = Station(\n # This is the station code according to the SEED standard.\n code=stats.station,\n latitude=stats.sac[\"stla\"],\n longitude=stats.sac[\"stlo\"],\n elevation=stats.sac[\"stel\"],\n creation_date=stats.starttime,\n site=Site(name=\"First station\"))\n\n cha = Channel(\n # This is the channel code according to the SEED standard.\n code=stats.channel,\n # This is the location code according to the SEED standard.\n location_code=stats.location,\n # Note that these coordinates can differ from the station coordinates.\n latitude=stats.sac[\"stla\"],\n longitude=stats.sac[\"stlo\"],\n elevation=stats.sac[\"stel\"],\n depth=-stats.sac[\"stel\"],\n azimuth=stats.sac[\"cmpaz\"],\n dip=stats.sac[\"cmpinc\"],\n sample_rate=stats.sampling_rate)\n\n elif input_fmt == 'mseed':\n ista=locs[locs['station']==stats.station].index.values.astype('int64')[0]\n\n net = Network(\n # This is the network code according to the SEED standard.\n code=locs.iloc[ista][\"network\"],\n stations=[],\n description=\"created from SAC and resp files\",\n start_date=stats.starttime)\n\n sta = Station(\n # This is the station code according to the SEED standard.\n code=locs.iloc[ista][\"station\"],\n latitude=locs.iloc[ista][\"latitude\"],\n longitude=locs.iloc[ista][\"longitude\"],\n elevation=locs.iloc[ista][\"elevation\"],\n creation_date=stats.starttime,\n site=Site(name=\"First station\"))\n\n cha = Channel(\n code=stats.channel,\n location_code=stats.location,\n latitude=locs.iloc[ista][\"latitude\"],\n longitude=locs.iloc[ista][\"longitude\"],\n elevation=locs.iloc[ista][\"elevation\"],\n depth=-locs.iloc[ista][\"elevation\"],\n azimuth=0,\n dip=0,\n sample_rate=stats.sampling_rate)\n\n response = obspy.core.inventory.response.Response()\n\n # Now tie it all together.\n cha.response = response\n sta.channels.append(cha)\n net.stations.append(sta)\n inv.networks.append(net)\n\n return inv\n\n\ndef sta_info_from_inv(inv):\n '''\n this function outputs station info from the obspy inventory object\n (used in S0B)\n PARAMETERS:\n ----------------------\n inv: obspy inventory object\n RETURNS:\n ----------------------\n sta: station name\n net: netowrk name\n lon: longitude of the station\n lat: latitude of the station\n elv: elevation of the station\n location: location code of the station\n '''\n # load from station inventory\n sta = inv[0][0].code\n net = inv[0].code\n lon = inv[0][0].longitude\n lat = inv[0][0].latitude\n if inv[0][0].elevation:\n elv = inv[0][0].elevation\n else: elv = 0.\n\n if inv[0][0][0].location_code:\n location = inv[0][0][0].location_code\n else: location = '00'\n\n return sta,net,lon,lat,elv,location\n\n\ndef cut_trace_make_stat(fc_para,source):\n '''\n this function cuts continous noise data into user-defined segments, estimate the statistics of\n each segment and keep timestamp of each segment for later use. (used in S1)\n PARAMETERS:\n ----------------------\n fft_para: A dictionary containing all fft and cc parameters.\n source: obspy stream object\n RETURNS:\n ----------------------\n trace_stdS: standard deviation of the noise amplitude of each segment\n dataS_t: timestamps of each segment\n dataS: 2D matrix of the segmented data\n '''\n # define return variables first\n source_params=[];dataS_t=[];dataS=[]\n\n # load parameter from dic\n inc_hours = fc_para['inc_hours']\n cc_len = fc_para['cc_len']\n step = fc_para['step']\n\n # useful parameters for trace sliding\n nseg = int(np.floor((inc_hours/24*86400-cc_len)/step))\n sps = int(source[0].stats.sampling_rate)\n starttime = source[0].stats.starttime-obspy.UTCDateTime(1970,1,1)\n # copy data into array\n data = source[0].data\n\n # if the data is shorter than the tim chunck, return zero values\n if data.size < sps*inc_hours*3600:\n return source_params,dataS_t,dataS\n\n # statistic to detect segments that may be associated with earthquakes\n all_madS = mad(data)\t # median absolute deviation over all noise window\n all_stdS = np.std(data)\t # standard deviation over all noise window\n if all_madS==0 or all_stdS==0 or np.isnan(all_madS) or np.isnan(all_stdS):\n print(\"continue! madS or stdS equals to 0 for %s\" % source)\n return source_params,dataS_t,dataS\n\n # initialize variables\n npts = cc_len*sps\n #trace_madS = np.zeros(nseg,dtype=np.float32)\n trace_stdS = np.zeros(nseg,dtype=np.float32)\n dataS = np.zeros(shape=(nseg,npts),dtype=np.float32)\n dataS_t = np.zeros(nseg,dtype=np.float)\n\n indx1 = 0\n for iseg in range(nseg):\n indx2 = indx1+npts\n dataS[iseg] = data[indx1:indx2]\n #trace_madS[iseg] = (np.max(np.abs(dataS[iseg]))/all_madS)\n trace_stdS[iseg] = (np.max(np.abs(dataS[iseg]))/all_stdS)\n dataS_t[iseg] = starttime+step*iseg\n indx1 = indx1+step*sps\n\n # 2D array processing\n dataS = demean(dataS)\n dataS = detrend(dataS)\n dataS = taper(dataS)\n\n return trace_stdS,dataS_t,dataS\n\n\ndef noise_processing(fft_para,dataS):\n '''\n this function performs time domain and frequency domain normalization if needed. in real case, we prefer use include\n the normalization in the cross-correaltion steps by selecting coherency or decon (Prieto et al, 2008, 2009; Denolle et al, 2013)\n PARMAETERS:\n ------------------------\n fft_para: dictionary containing all useful variables used for fft and cc\n dataS: 2D matrix of all segmented noise data\n # OUTPUT VARIABLES:\n source_white: 2D matrix of data spectra\n '''\n # load parameters first\n time_norm = fft_para['time_norm']\n freq_norm = fft_para['freq_norm']\n smooth_N = fft_para['smooth_N']\n N = dataS.shape[0]\n\n #------to normalize in time or not------\n if time_norm != 'no':\n\n if time_norm == 'one_bit': \t# sign normalization\n white = np.sign(dataS)\n elif time_norm == 'rma': # running mean: normalization over smoothed absolute average\n white = np.zeros(shape=dataS.shape,dtype=dataS.dtype)\n for kkk in range(N):\n white[kkk,:] = dataS[kkk,:]/moving_ave(np.abs(dataS[kkk,:]),smooth_N)\n\n else:\t# don't normalize\n white = dataS\n\n #-----to whiten or not------\n if freq_norm != 'no':\n source_white = whiten(white,fft_para)\t# whiten and return FFT\n else:\n Nfft = int(next_fast_len(int(dataS.shape[1])))\n source_white = scipy.fftpack.fft(white, Nfft, axis=1) # return FFT\n\n return source_white\n\n\ndef smooth_source_spect(cc_para,fft1):\n '''\n this function smoothes amplitude spectrum of the 2D spectral matrix. (used in S1)\n PARAMETERS:\n ---------------------\n cc_para: dictionary containing useful cc parameters\n fft1: source spectrum matrix\n\n RETURNS:\n ---------------------\n sfft1: complex numpy array with normalized spectrum\n '''\n cc_method = cc_para['cc_method']\n smoothspect_N = cc_para['smoothspect_N']\n\n if cc_method == 'deconv':\n\n #-----normalize single-station cc to z component-----\n temp = moving_ave(np.abs(fft1),smoothspect_N)\n try:\n sfft1 = np.conj(fft1)/temp**2\n except Exception:\n raise ValueError('smoothed spectrum has zero values')\n\n elif cc_method == 'coherency':\n temp = moving_ave(np.abs(fft1),smoothspect_N)\n try:\n sfft1 = np.conj(fft1)/temp\n except Exception:\n raise ValueError('smoothed spectrum has zero values')\n\n elif cc_method == 'xcorr':\n sfft1 = np.conj(fft1)\n\n else:\n raise ValueError('no correction correlation method is selected at L59')\n\n return sfft1\n\ndef correlate(fft1_smoothed_abs,fft2,D,Nfft,dataS_t):\n '''\n this function does the cross-correlation in freq domain and has the option to keep sub-stacks of\n the cross-correlation if needed. it takes advantage of the linear relationship of ifft, so that\n stacking is performed in spectrum domain first to reduce the total number of ifft. (used in S1)\n PARAMETERS:\n ---------------------\n fft1_smoothed_abs: smoothed power spectral density of the FFT for the source station\n fft2: raw FFT spectrum of the receiver station\n D: dictionary containing following parameters:\n maxlag: maximum lags to keep in the cross correlation\n dt: sampling rate (in s)\n nwin: number of segments in the 2D matrix\n method: cross-correlation methods selected by the user\n freqmin: minimum frequency (Hz)\n freqmax: maximum frequency (Hz)\n Nfft: number of frequency points for ifft\n dataS_t: matrix of datetime object.\n \n RETURNS:\n ---------------------\n s_corr: 1D or 2D matrix of the averaged or sub-stacks of cross-correlation functions in time domain\n t_corr: timestamp for each sub-stack or averaged function\n n_corr: number of included segments for each sub-stack or averaged function\n\n MODIFICATIONS:\n ---------------------\n output the linear stack of each time chunk even when substack is selected (by Chengxin @Aug2020)\n '''\n #----load paramters----\n dt = D['dt']\n maxlag = D['maxlag']\n method = D['cc_method']\n cc_len = D['cc_len']\n substack= D['substack']\n substack_len = D['substack_len']\n smoothspect_N = D['smoothspect_N']\n\n nwin = fft1_smoothed_abs.shape[0]\n Nfft2 = fft1_smoothed_abs.shape[1]\n\n #------convert all 2D arrays into 1D to speed up--------\n corr = np.zeros(nwin*Nfft2,dtype=np.complex64)\n corr = fft1_smoothed_abs.reshape(fft1_smoothed_abs.size,)*fft2.reshape(fft2.size,)\n\n if method == \"coherency\":\n temp = moving_ave(np.abs(fft2.reshape(fft2.size,)),smoothspect_N)\n corr /= temp\n corr = corr.reshape(nwin,Nfft2)\n\n if substack:\n if substack_len == cc_len:\n # choose to keep all fft data for a day\n s_corr = np.zeros(shape=(nwin,Nfft),dtype=np.float32) # stacked correlation\n ampmax = np.zeros(nwin,dtype=np.float32)\n n_corr = np.zeros(nwin,dtype=np.int16) # number of correlations for each substack\n t_corr = dataS_t # timestamp\n crap = np.zeros(Nfft,dtype=np.complex64)\n for i in range(nwin):\n n_corr[i]= 1\n crap[:Nfft2] = corr[i,:]\n crap[:Nfft2] = crap[:Nfft2]-np.mean(crap[:Nfft2]) # remove the mean in freq domain (spike at t=0)\n crap[-(Nfft2)+1:] = np.flip(np.conj(crap[1:(Nfft2)]),axis=0)\n crap[0]=complex(0,0)\n s_corr[i,:] = np.real(np.fft.ifftshift(scipy.fftpack.ifft(crap, Nfft, axis=0)))\n\n # remove abnormal data\n ampmax = np.max(s_corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n s_corr = s_corr[tindx,:]\n t_corr = t_corr[tindx]\n n_corr = n_corr[tindx]\n\n else:\n # get time information\n Ttotal = dataS_t[-1]-dataS_t[0] # total duration of what we have now\n tstart = dataS_t[0]\n\n nstack = int(np.round(Ttotal/substack_len))\n ampmax = np.zeros(nstack,dtype=np.float32)\n s_corr = np.zeros(shape=(nstack,Nfft),dtype=np.float32)\n n_corr = np.zeros(nstack,dtype=np.int)\n t_corr = np.zeros(nstack,dtype=np.float)\n crap = np.zeros(Nfft,dtype=np.complex64)\n\n for istack in range(nstack):\n # find the indexes of all of the windows that start or end within\n itime = np.where( (dataS_t >= tstart) & (dataS_t < tstart+substack_len) )[0]\n if len(itime)==0:tstart+=substack_len;continue\n\n crap[:Nfft2] = np.mean(corr[itime,:],axis=0) # linear average of the correlation\n crap[:Nfft2] = crap[:Nfft2]-np.mean(crap[:Nfft2]) # remove the mean in freq domain (spike at t=0)\n crap[-(Nfft2)+1:]=np.flip(np.conj(crap[1:(Nfft2)]),axis=0)\n crap[0]=complex(0,0)\n s_corr[istack,:] = np.real(np.fft.ifftshift(scipy.fftpack.ifft(crap, Nfft, axis=0)))\n n_corr[istack] = len(itime) # number of windows stacks\n t_corr[istack] = tstart # save the time stamps\n tstart += substack_len\n #print('correlation done and stacked at time %s' % str(t_corr[istack]))\n\n # remove abnormal data\n ampmax = np.max(s_corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n s_corr = s_corr[tindx,:]\n t_corr = t_corr[tindx]\n n_corr = n_corr[tindx]\n\n else:\n # average daily cross correlation functions\n ampmax = np.max(corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n n_corr = nwin\n s_corr = np.zeros(Nfft,dtype=np.float32)\n t_corr = dataS_t[0]\n crap = np.zeros(Nfft,dtype=np.complex64)\n crap[:Nfft2] = np.mean(corr[tindx],axis=0)\n crap[:Nfft2] = crap[:Nfft2]-np.mean(crap[:Nfft2],axis=0)\n crap[-(Nfft2)+1:]=np.flip(np.conj(crap[1:(Nfft2)]),axis=0)\n s_corr = np.real(np.fft.ifftshift(scipy.fftpack.ifft(crap, Nfft, axis=0)))\n\n # trim the CCFs in [-maxlag maxlag]\n # #####################################\n # t = np.arange(-Nfft2+1, Nfft2)*dt\n # the t vector is defined incorrectly in the previous version, as the starting time window \n # should start from -Nfft2*dt rather than -Nfft2+1. This causes the cross-correlation to shift\n # 1 sample point to the positive axis, which is particularly problematic for long-period studies. \n # this bug can not be found without Dr. Xingli Fan's help! Thank you Xingli! \n ########################################\n t = np.arange(-Nfft2,Nfft2)*dt\n ind = np.where(np.abs(t) <= maxlag)[0]\n if s_corr.ndim==1:\n s_corr = s_corr[ind]\n elif s_corr.ndim==2:\n s_corr = s_corr[:,ind]\n return s_corr,t_corr,n_corr\n\ndef correlate_nonlinear_stack(fft1_smoothed_abs,fft2,D,Nfft,dataS_t):\n '''\n this function does the cross-correlation in freq domain and has the option to keep sub-stacks of\n the cross-correlation if needed. it takes advantage of the linear relationship of ifft, so that\n stacking is performed in spectrum domain first to reduce the total number of ifft. (used in S1)\n PARAMETERS:\n ---------------------\n fft1_smoothed_abs: smoothed power spectral density of the FFT for the source station\n fft2: raw FFT spectrum of the receiver station\n D: dictionary containing following parameters:\n maxlag: maximum lags to keep in the cross correlation\n dt: sampling rate (in s)\n nwin: number of segments in the 2D matrix\n method: cross-correlation methods selected by the user\n freqmin: minimum frequency (Hz)\n freqmax: maximum frequency (Hz)\n Nfft: number of frequency points for ifft\n dataS_t: matrix of datetime object.\n RETURNS:\n ---------------------\n s_corr: 1D or 2D matrix of the averaged or sub-stacks of cross-correlation functions in time domain\n t_corr: timestamp for each sub-stack or averaged function\n n_corr: number of included segments for each sub-stack or averaged function\n '''\n #----load paramters----\n dt = D['dt']\n maxlag = D['maxlag']\n method = D['cc_method']\n cc_len = D['cc_len']\n substack= D['substack']\n stack_method = D['stack_method']\n substack_len = D['substack_len']\n smoothspect_N = D['smoothspect_N']\n\n nwin = fft1_smoothed_abs.shape[0]\n Nfft2 = fft1_smoothed_abs.shape[1]\n\n #------convert all 2D arrays into 1D to speed up--------\n corr = np.zeros(nwin*Nfft2,dtype=np.complex64)\n corr = fft1_smoothed_abs.reshape(fft1_smoothed_abs.size,)*fft2.reshape(fft2.size,)\n\n # normalize by receiver spectral for coherency\n if method == \"coherency\":\n temp = moving_ave(np.abs(fft2.reshape(fft2.size,)),smoothspect_N)\n corr /= temp\n corr = corr.reshape(nwin,Nfft2)\n\n # transform back to time domain waveforms\n s_corr = np.zeros(shape=(nwin,Nfft),dtype=np.float32) # stacked correlation\n ampmax = np.zeros(nwin,dtype=np.float32)\n n_corr = np.zeros(nwin,dtype=np.int16) # number of correlations for each substack\n t_corr = dataS_t # timestamp\n crap = np.zeros(Nfft,dtype=np.complex64)\n for i in range(nwin):\n n_corr[i]= 1\n crap[:Nfft2] = corr[i,:]\n crap[:Nfft2] = crap[:Nfft2]-np.mean(crap[:Nfft2]) # remove the mean in freq domain (spike at t=0)\n crap[-(Nfft2)+1:] = np.flip(np.conj(crap[1:(Nfft2)]),axis=0)\n crap[0]=complex(0,0)\n s_corr[i,:] = np.real(np.fft.ifftshift(scipy.fftpack.ifft(crap, Nfft, axis=0)))\n\n ns_corr = s_corr\n for iii in range(ns_corr.shape[0]):\n ns_corr[iii] /= np.max(np.abs(ns_corr[iii]))\n\n if substack:\n if substack_len == cc_len:\n\n # remove abnormal data\n ampmax = np.max(s_corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n s_corr = s_corr[tindx,:]\n t_corr = t_corr[tindx]\n n_corr = n_corr[tindx]\n\n else:\n # get time information\n Ttotal = dataS_t[-1]-dataS_t[0] # total duration of what we have now\n tstart = dataS_t[0]\n\n nstack = int(np.round(Ttotal/substack_len))\n ampmax = np.zeros(nstack,dtype=np.float32)\n s_corr = np.zeros(shape=(nstack,Nfft),dtype=np.float32)\n n_corr = np.zeros(nstack,dtype=np.int)\n t_corr = np.zeros(nstack,dtype=np.float)\n crap = np.zeros(Nfft,dtype=np.complex64)\n\n for istack in range(nstack):\n # find the indexes of all of the windows that start or end within\n itime = np.where( (dataS_t >= tstart) & (dataS_t < tstart+substack_len) )[0]\n if len(itime)==0:tstart+=substack_len;continue\n\n crap[:Nfft2] = np.mean(corr[itime,:],axis=0) # linear average of the correlation\n crap[:Nfft2] = crap[:Nfft2]-np.mean(crap[:Nfft2]) # remove the mean in freq domain (spike at t=0)\n crap[-(Nfft2)+1:]=np.flip(np.conj(crap[1:(Nfft2)]),axis=0)\n crap[0]=complex(0,0)\n s_corr[istack,:] = np.real(np.fft.ifftshift(scipy.fftpack.ifft(crap, Nfft, axis=0)))\n n_corr[istack] = len(itime) # number of windows stacks\n t_corr[istack] = tstart # save the time stamps\n tstart += substack_len\n #print('correlation done and stacked at time %s' % str(t_corr[istack]))\n\n # remove abnormal data\n ampmax = np.max(s_corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n s_corr = s_corr[tindx,:]\n t_corr = t_corr[tindx]\n n_corr = n_corr[tindx]\n\n else:\n # average daily cross correlation functions\n if stack_method == 'linear':\n ampmax = np.max(s_corr,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n s_corr = np.mean(s_corr[tindx],axis=0)\n t_corr = dataS_t[0]\n n_corr = len(tindx)\n elif stack_method == 'robust':\n print('do robust substacking')\n s_corr = robust_stack(s_corr,0.001)\n t_corr = dataS_t[0]\n n_corr = nwin\n # elif stack_method == 'selective':\n # print('do selective substacking')\n # s_corr = selective_stack(s_corr,0.001)\n # t_corr = dataS_t[0]\n # n_corr = nwin\n\n # trim the CCFs in [-maxlag maxlag]\n t = np.arange(-Nfft2+1, Nfft2)*dt\n ind = np.where(np.abs(t) <= maxlag)[0]\n if s_corr.ndim==1:\n s_corr = s_corr[ind]\n elif s_corr.ndim==2:\n s_corr = s_corr[:,ind]\n return s_corr,t_corr,n_corr,ns_corr[:,ind]\n\ndef cc_parameters(cc_para,coor,tcorr,ncorr,comp):\n '''\n this function assembles the parameters for the cc function, which is used\n when writing them into ASDF files\n PARAMETERS:\n ---------------------\n cc_para: dict containing parameters used in the fft_cc step\n coor: dict containing coordinates info of the source and receiver stations\n tcorr: timestamp matrix\n ncorr: matrix of number of good segments for each sub-stack/final stack\n comp: 2 character strings for the cross correlation component\n RETURNS:\n ------------------\n parameters: dict containing above info used for later stacking/plotting\n '''\n latS = coor['latS']\n lonS = coor['lonS']\n latR = coor['latR']\n lonR = coor['lonR']\n dt = cc_para['dt']\n maxlag = cc_para['maxlag']\n substack = cc_para['substack']\n cc_method = cc_para['cc_method']\n\n dist,azi,baz = obspy.geodetics.base.gps2dist_azimuth(latS,lonS,latR,lonR)\n parameters = {'dt':dt,\n 'maxlag':int(maxlag),\n 'dist':np.float32(dist/1000),\n 'azi':np.float32(azi),\n 'baz':np.float32(baz),\n 'lonS':np.float32(lonS),\n 'latS':np.float32(latS),\n 'lonR':np.float32(lonR),\n 'latR':np.float32(latR),\n 'ngood':ncorr,\n 'cc_method':cc_method,\n 'time':tcorr,\n 'substack':substack,\n 'comp':comp}\n return parameters\n\ndef stacking(cc_array,cc_time,cc_ngood,stack_para):\n '''\n this function stacks the cross correlation data according to the user-defined substack_len parameter\n\n PARAMETERS:\n ----------------------\n cc_array: 2D numpy float32 matrix containing all segmented cross-correlation data\n cc_time: 1D numpy array of timestamps for each segment of cc_array\n cc_ngood: 1D numpy int16 matrix showing the number of segments for each sub-stack and/or full stack\n stack_para: a dict containing all stacking parameters\n\n RETURNS:\n ----------------------\n cc_array, cc_ngood, cc_time: same to the input parameters but with abnormal cross-correaltions removed\n allstacks1: 1D matrix of stacked cross-correlation functions over all the segments\n nstacks: number of overall segments for the final stacks\n '''\n # load useful parameters from dict\n samp_freq = stack_para['samp_freq']\n smethod = stack_para['stack_method']\n start_date = stack_para['start_date']\n end_date = stack_para['end_date']\n npts = cc_array.shape[1]\n\n # remove abnormal data\n ampmax = np.max(cc_array,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n if not len(tindx):\n allstacks1=[];allstacks2=[];allstacks3=[];nstacks=0\n cc_array=[];cc_ngood=[];cc_time=[]\n return cc_array,cc_ngood,cc_time,allstacks1,allstacks2,allstacks3,nstacks\n else:\n\n # remove ones with bad amplitude\n cc_array = cc_array[tindx,:]\n cc_time = cc_time[tindx]\n cc_ngood = cc_ngood[tindx]\n\n # do stacking\n allstacks1 = np.zeros(npts,dtype=np.float32)\n allstacks2 = np.zeros(npts,dtype=np.float32)\n allstacks3 = np.zeros(npts,dtype=np.float32)\n allstacks4 = np.zeros(npts,dtype=np.float32)\n allstacks5 = np.zeros(npts,dtype=np.float32)\n\n if smethod == 'linear':\n allstacks1 = np.mean(cc_array,axis=0)\n elif smethod == 'pws':\n allstacks1 = pws(cc_array,samp_freq)\n elif smethod == 'robust':\n allstacks1,w,nstep = robust_stack(cc_array,0.001)\n elif smethod == 'auto_covariance':\n allstacks1 = adaptive_filter(cc_array,1)\n elif smethod == 'nroot':\n allstacks1 = nroot_stack(cc_array,2)\n elif smethod == 'all':\n allstacks1 = np.mean(cc_array,axis=0)\n allstacks2 = pws(cc_array,samp_freq)\n allstacks3,w,nstep = robust_stack(cc_array,0.001)\n allstacks4 = adaptive_filter(cc_array,1)\n allstacks5 = nroot_stack(cc_array,2)\n nstacks = np.sum(cc_ngood)\n\n # good to return\n return cc_array,cc_ngood,cc_time,allstacks1,allstacks2,allstacks3,nstacks\n\n\ndef stacking_rma(cc_array,cc_time,cc_ngood,stack_para):\n '''\n this function stacks the cross correlation data according to the user-defined substack_len parameter\n PARAMETERS:\n ----------------------\n cc_array: 2D numpy float32 matrix containing all segmented cross-correlation data\n cc_time: 1D numpy array of timestamps for each segment of cc_array\n cc_ngood: 1D numpy int16 matrix showing the number of segments for each sub-stack and/or full stack\n stack_para: a dict containing all stacking parameters\n RETURNS:\n ----------------------\n cc_array, cc_ngood, cc_time: same to the input parameters but with abnormal cross-correaltions removed\n allstacks1: 1D matrix of stacked cross-correlation functions over all the segments\n nstacks: number of overall segments for the final stacks\n '''\n # load useful parameters from dict\n samp_freq = stack_para['samp_freq']\n smethod = stack_para['stack_method']\n rma_substack = stack_para['rma_substack']\n rma_step = stack_para['rma_step']\n start_date = stack_para['start_date']\n end_date = stack_para['end_date']\n npts = cc_array.shape[1]\n\n # remove abnormal data\n ampmax = np.max(cc_array,axis=1)\n tindx = np.where( (ampmax<20*np.median(ampmax)) & (ampmax>0))[0]\n if not len(tindx):\n allstacks1=[];allstacks2=[];nstacks=0\n cc_array=[];cc_ngood=[];cc_time=[]\n return cc_array,cc_ngood,cc_time,allstacks1,allstacks2,nstacks\n else:\n\n # remove ones with bad amplitude\n cc_array = cc_array[tindx,:]\n cc_time = cc_time[tindx]\n cc_ngood = cc_ngood[tindx]\n\n # do substacks\n if rma_substack:\n tstart = obspy.UTCDateTime(start_date)-obspy.UTCDateTime(1970,1,1)\n tend = obspy.UTCDateTime(end_date)-obspy.UTCDateTime(1970,1,1)\n ttime = tstart\n nstack = int(np.round((tend-tstart)/(rma_step*3600)))\n ncc_array = np.zeros(shape=(nstack,npts),dtype=np.float32)\n ncc_time = np.zeros(nstack,dtype=np.float)\n ncc_ngood = np.zeros(nstack,dtype=np.int)\n\n # loop through each time\n for ii in range(nstack):\n sindx = np.where((cc_time>=ttime) & (cc_time<ttime+rma_substack*3600))[0]\n\n # when there are data in the time window\n if len(sindx):\n ncc_array[ii] = np.mean(cc_array[sindx],axis=0)\n ncc_time[ii] = ttime\n ncc_ngood[ii] = np.sum(cc_ngood[sindx],axis=0)\n ttime += rma_step*3600\n\n # remove bad ones\n tindx = np.where(ncc_ngood>0)[0]\n ncc_array = ncc_array[tindx]\n ncc_time = ncc_time[tindx]\n ncc_ngood = ncc_ngood[tindx]\n\n # do stacking\n allstacks1 = np.zeros(npts,dtype=np.float32)\n allstacks2 = np.zeros(npts,dtype=np.float32)\n allstacks3 = np.zeros(npts,dtype=np.float32)\n allstacks4 = np.zeros(npts,dtype=np.float32)\n\n if smethod == 'linear':\n allstacks1 = np.mean(cc_array,axis=0)\n elif smethod == 'pws':\n allstacks1 = pws(cc_array,samp_freq)\n elif smethod == 'robust':\n allstacks1,w, = robust_stack(cc_array,0.001)\n elif smethod == 'selective':\n allstacks1 = selective_stack(cc_array,0.001)\n elif smethod == 'all':\n allstacks1 = np.mean(cc_array,axis=0)\n allstacks2 = pws(cc_array,samp_freq)\n allstacks3 = robust_stack(cc_array,0.001)\n allstacks4 = selective_stack(cc_array,0.001)\n nstacks = np.sum(cc_ngood)\n\n # replace the array for substacks\n if rma_substack:\n cc_array = ncc_array\n cc_time = ncc_time\n cc_ngood = ncc_ngood\n\n # good to return\n return cc_array,cc_ngood,cc_time,allstacks1,allstacks2,allstacks3,allstacks4,nstacks\n\ndef rotation(bigstack,parameters,locs,flag):\n '''\n this function transfers the Green's tensor from a E-N-Z system into a R-T-Z one\n\n PARAMETERS:\n -------------------\n bigstack: 9 component Green's tensor in E-N-Z system\n parameters: dict containing all parameters saved in ASDF file\n locs: dict containing station angle info for correction purpose\n RETURNS:\n -------------------\n tcorr: 9 component Green's tensor in R-T-Z system\n '''\n # load parameter dic\n pi = np.pi\n azi = parameters['azi']\n baz = parameters['baz']\n ncomp,npts = bigstack.shape\n if ncomp<9:\n print('crap did not get enough components')\n tcorr=[]\n return tcorr\n staS = parameters['station_source']\n staR = parameters['station_receiver']\n\n if len(locs):\n sta_list = list(locs['station'])\n angles = list(locs['angle'])\n # get station info from the name of ASDF file\n ind = sta_list.index(staS)\n acorr = angles[ind]\n ind = sta_list.index(staR)\n bcorr = angles[ind]\n\n #---angles to be corrected----\n if len(locs):\n cosa = np.cos((azi+acorr)*pi/180)\n sina = np.sin((azi+acorr)*pi/180)\n cosb = np.cos((baz+bcorr)*pi/180)\n sinb = np.sin((baz+bcorr)*pi/180)\n else:\n cosa = np.cos(azi*pi/180)\n sina = np.sin(azi*pi/180)\n cosb = np.cos(baz*pi/180)\n sinb = np.sin(baz*pi/180)\n\n # rtz_components = ['ZR','ZT','ZZ','RR','RT','RZ','TR','TT','TZ']\n tcorr = np.zeros(shape=(9,npts),dtype=np.float32)\n tcorr[0] = -cosb*bigstack[7]-sinb*bigstack[6]\n tcorr[1] = sinb*bigstack[7]-cosb*bigstack[6]\n tcorr[2] = bigstack[8]\n tcorr[3] = -cosa*cosb*bigstack[4]-cosa*sinb*bigstack[3]-sina*cosb*bigstack[1]-sina*sinb*bigstack[0]\n tcorr[4] = cosa*sinb*bigstack[4]-cosa*cosb*bigstack[3]+sina*sinb*bigstack[1]-sina*cosb*bigstack[0]\n tcorr[5] = cosa*bigstack[5]+sina*bigstack[2]\n tcorr[6] = sina*cosb*bigstack[4]+sina*sinb*bigstack[3]-cosa*cosb*bigstack[1]-cosa*sinb*bigstack[0]\n tcorr[7] = -sina*sinb*bigstack[4]+sina*cosb*bigstack[3]+cosa*sinb*bigstack[1]-cosa*cosb*bigstack[0]\n tcorr[8] = -sina*bigstack[5]+cosa*bigstack[2]\n\n return tcorr\n\n\n####################################################\n############## UTILITY FUNCTIONS ###################\n####################################################\n\ndef check_sample_gaps(stream,date_info):\n \"\"\"\n this function checks sampling rate and find gaps of all traces in stream.\n PARAMETERS:\n -----------------\n stream: obspy stream object.\n date_info: dict of starting and ending time of the stream\n\n RETURENS:\n -----------------\n stream: List of good traces in the stream\n \"\"\"\n # remove empty/big traces\n if len(stream)==0 or len(stream)>100:\n stream = []\n return stream\n\n # remove traces with big gaps\n if portion_gaps(stream,date_info)>0.3:\n stream = []\n return stream\n\n freqs = []\n for tr in stream:\n freqs.append(int(tr.stats.sampling_rate))\n freq = max(freqs)\n for tr in stream:\n if int(tr.stats.sampling_rate) != freq:\n stream.remove(tr)\n if tr.stats.npts < 10:\n stream.remove(tr)\n\n return stream\n\n\ndef portion_gaps(stream,date_info):\n '''\n this function tracks the gaps (npts) from the accumulated difference between starttime and endtime\n of each stream trace. it removes trace with gap length > 30% of trace size.\n PARAMETERS:\n -------------------\n stream: obspy stream object\n date_info: dict of starting and ending time of the stream\n\n RETURNS:\n -----------------\n pgaps: proportion of gaps/all_pts in stream\n '''\n # ideal duration of data\n starttime = date_info['starttime']\n endtime = date_info['endtime']\n npts = (endtime-starttime)*stream[0].stats.sampling_rate\n\n pgaps=0\n #loop through all trace to accumulate gaps\n for ii in range(len(stream)-1):\n pgaps += (stream[ii+1].stats.starttime-stream[ii].stats.endtime)*stream[ii].stats.sampling_rate\n if npts!=0:pgaps=pgaps/npts\n if npts==0:pgaps=1\n return pgaps\n\n\n@jit('float32[:](float32[:],float32)')\ndef segment_interpolate(sig1,nfric):\n '''\n this function interpolates the data to ensure all points located on interger times of the\n sampling rate (e.g., starttime = 00:00:00.015, delta = 0.05.)\n PARAMETERS:\n ----------------------\n sig1: seismic recordings in a 1D array\n nfric: the amount of time difference between the point and the adjacent assumed samples\n RETURNS:\n ----------------------\n sig2: interpolated seismic recordings on the sampling points\n '''\n npts = len(sig1)\n sig2 = np.zeros(npts,dtype=np.float32)\n\n #----instead of shifting, do a interpolation------\n for ii in range(npts):\n\n #----deal with edges-----\n if ii==0 or ii==npts-1:\n sig2[ii]=sig1[ii]\n else:\n #------interpolate using a hat function------\n sig2[ii]=(1-nfric)*sig1[ii+1]+nfric*sig1[ii]\n\n return sig2\n\ndef resp_spectrum(source,resp_file,downsamp_freq,pre_filt=None):\n '''\n this function removes the instrument response using response spectrum from evalresp.\n the response spectrum is evaluated based on RESP/PZ files before inverted using the obspy\n function of invert_spectrum. a module of create_resp.py is provided in directory of 'additional_modules'\n to create the response spectrum\n PARAMETERS:\n ----------------------\n source: obspy stream object of targeted noise data\n resp_file: numpy data file of response spectrum\n downsamp_freq: sampling rate of the source data\n pre_filt: pre-defined filter parameters\n RETURNS:\n ----------------------\n source: obspy stream object of noise data with instrument response removed\n '''\n #--------resp_file is the inverted spectrum response---------\n respz = np.load(resp_file)\n nrespz= respz[1][:]\n spec_freq = max(respz[0])\n\n #-------on current trace----------\n nfft = _npts2nfft(source[0].stats.npts)\n sps = int(source[0].stats.sampling_rate)\n\n #---------do the interpolation if needed--------\n if spec_freq < 0.5*sps:\n raise ValueError('spectrum file has peak freq smaller than the data, abort!')\n else:\n indx = np.where(respz[0]<=0.5*sps)\n nfreq = np.linspace(0,0.5*sps,nfft//2+1)\n nrespz= np.interp(nfreq,np.real(respz[0][indx]),respz[1][indx])\n\n #----do interpolation if necessary-----\n source_spect = np.fft.rfft(source[0].data,n=nfft)\n\n #-----nrespz is inversed (water-leveled) spectrum-----\n source_spect *= nrespz\n source[0].data = np.fft.irfft(source_spect)[0:source[0].stats.npts]\n\n if pre_filt is not None:\n source[0].data = np.float32(bandpass(source[0].data,pre_filt[0],pre_filt[-1],df=sps,corners=4,zerophase=True))\n\n return source\n\n\ndef mad(arr):\n \"\"\"\n Median Absolute Deviation: MAD = median(|Xi- median(X)|)\n PARAMETERS:\n -------------------\n arr: numpy.ndarray, seismic trace data array\n RETURNS:\n data: Median Absolute Deviation of data\n \"\"\"\n if not np.ma.is_masked(arr):\n med = np.median(arr)\n data = np.median(np.abs(arr - med))\n else:\n med = np.ma.median(arr)\n data = np.ma.median(np.ma.abs(arr-med))\n return data\n\n\ndef detrend(data):\n '''\n this function removes the signal trend based on QR decomposion\n NOTE: QR is a lot faster than the least square inversion used by\n scipy (also in obspy).\n PARAMETERS:\n ---------------------\n data: input data matrix\n RETURNS:\n ---------------------\n data: data matrix with trend removed\n '''\n #ndata = np.zeros(shape=data.shape,dtype=data.dtype)\n if data.ndim == 1:\n npts = data.shape[0]\n X = np.ones((npts,2))\n X[:,0] = np.arange(0,npts)/npts\n Q,R = np.linalg.qr(X)\n rq = np.dot(np.linalg.inv(R),Q.transpose())\n coeff = np.dot(rq,data)\n data = data-np.dot(X,coeff)\n elif data.ndim == 2:\n npts = data.shape[1]\n X = np.ones((npts,2))\n X[:,0] = np.arange(0,npts)/npts\n Q,R = np.linalg.qr(X)\n rq = np.dot(np.linalg.inv(R),Q.transpose())\n for ii in range(data.shape[0]):\n coeff = np.dot(rq,data[ii])\n data[ii] = data[ii] - np.dot(X,coeff)\n return data\n\ndef demean(data):\n '''\n this function remove the mean of the signal\n PARAMETERS:\n ---------------------\n data: input data matrix\n RETURNS:\n ---------------------\n data: data matrix with mean removed\n '''\n #ndata = np.zeros(shape=data.shape,dtype=data.dtype)\n if data.ndim == 1:\n data = data-np.mean(data)\n elif data.ndim == 2:\n for ii in range(data.shape[0]):\n data[ii] = data[ii]-np.mean(data[ii])\n return data\n\ndef taper(data):\n '''\n this function applies a cosine taper using obspy functions\n PARAMETERS:\n ---------------------\n data: input data matrix\n RETURNS:\n ---------------------\n data: data matrix with taper applied\n '''\n #ndata = np.zeros(shape=data.shape,dtype=data.dtype)\n if data.ndim == 1:\n npts = data.shape[0]\n # window length\n if npts*0.05>20:wlen = 20\n else:wlen = npts*0.05\n # taper values\n func = _get_function_from_entry_point('taper', 'hann')\n if 2*wlen == npts:\n taper_sides = func(2*wlen)\n else:\n taper_sides = func(2*wlen+1)\n # taper window\n win = np.hstack((taper_sides[:wlen], np.ones(npts-2*wlen),taper_sides[len(taper_sides) - wlen:]))\n data *= win\n elif data.ndim == 2:\n npts = data.shape[1]\n # window length\n if npts*0.05>20:wlen = 20\n else:wlen = npts*0.05\n # taper values\n func = _get_function_from_entry_point('taper', 'hann')\n if 2*wlen == npts:\n taper_sides = func(2*wlen)\n else:\n taper_sides = func(2*wlen + 1)\n # taper window\n win = np.hstack((taper_sides[:wlen], np.ones(npts-2*wlen),taper_sides[len(taper_sides) - wlen:]))\n for ii in range(data.shape[0]):\n data[ii] *= win\n return data\n\n\n@jit(nopython = True)\ndef moving_ave(A,N):\n '''\n this Numba compiled function does running smooth average for an array.\n PARAMETERS:\n ---------------------\n A: 1-D array of data to be smoothed\n N: integer, it defines the half window length to smooth\n\n RETURNS:\n ---------------------\n B: 1-D array with smoothed data\n '''\n A = np.concatenate((A[:N],A,A[-N:]),axis=0)\n B = np.zeros(A.shape,A.dtype)\n\n tmp=0.\n for pos in range(N,A.size-N):\n # do summing only once\n if pos==N:\n for i in range(-N,N+1):\n tmp+=A[pos+i]\n else:\n tmp=tmp-A[pos-N-1]+A[pos+N]\n B[pos]=tmp/(2*N+1)\n if B[pos]==0:\n B[pos]=1\n return B[N:-N]\n\n\ndef robust_stack(cc_array,epsilon):\n \"\"\"\n this is a robust stacking algorithm described in Palvis and Vernon 2010\n\n PARAMETERS:\n ----------------------\n cc_array: numpy.ndarray contains the 2D cross correlation matrix\n epsilon: residual threhold to quit the iteration\n RETURNS:\n ----------------------\n newstack: numpy vector contains the stacked cross correlation\n\n Written by Marine Denolle\n \"\"\"\n res = 9E9 # residuals\n w = np.ones(cc_array.shape[0])\n nstep=0\n newstack = np.median(cc_array,axis=0)\n while res > epsilon:\n stack = newstack\n for i in range(cc_array.shape[0]):\n crap = np.multiply(stack,cc_array[i,:].T)\n crap_dot = np.sum(crap)\n di_norm = np.linalg.norm(cc_array[i,:])\n ri = cc_array[i,:] - crap_dot*stack\n ri_norm = np.linalg.norm(ri)\n w[i] = np.abs(crap_dot) /di_norm/ri_norm#/len(cc_array[:,1])\n # print(w)\n w =w /np.sum(w)\n newstack =np.sum( (w*cc_array.T).T,axis=0)#/len(cc_array[:,1])\n res = np.linalg.norm(newstack-stack,ord=1)/np.linalg.norm(newstack)/len(cc_array[:,1])\n nstep +=1\n if nstep>10:\n return newstack, w, nstep\n return newstack, w, nstep\n\n\n\ndef selective_stack(cc_array,epsilon):\n \"\"\"\n this is a selective stacking algorithm developed by Jared Bryan.\n\n PARAMETERS:\n ----------------------\n cc_array: numpy.ndarray contains the 2D cross correlation matrix\n epsilon: residual threhold to quit the iteration\n RETURNS:\n ----------------------\n newstack: numpy vector contains the stacked cross correlation\n\n Written by Marine Denolle\n \"\"\"\n res = 9E9 # residuals\n cc = np.ones(cc_array.shape[0])\n nstep=0\n newstack = np.mean(cc_array,axis=0)\n for i in range(cc_array.shape[0]):\n \tCC[i] = np.sum(np.multiply(stack,cc_array[i,:].T))\n ik = np.where(CC>=epsilon)\n newstack = np.mean(cc_array[ik,:],axis=0)\n\n return newstack, cc\n\n\n\ndef whiten(data, fft_para):\n '''\n This function takes 1-dimensional timeseries array, transforms to frequency domain using fft,\n whitens the amplitude of the spectrum in frequency domain between *freqmin* and *freqmax*\n and returns the whitened fft.\n PARAMETERS:\n ----------------------\n data: numpy.ndarray contains the 1D time series to whiten\n fft_para: dict containing all fft_cc parameters such as\n dt: The sampling space of the `data`\n freqmin: The lower frequency bound\n freqmax: The upper frequency bound\n smooth_N: integer, it defines the half window length to smooth\n freq_norm: whitening method between 'one-bit' and 'RMA'\n RETURNS:\n ----------------------\n FFTRawSign: numpy.ndarray contains the FFT of the whitened input trace between the frequency bounds\n '''\n\n # load parameters\n delta = fft_para['dt']\n freqmin = fft_para['freqmin']\n freqmax = fft_para['freqmax']\n smooth_N = fft_para['smooth_N']\n freq_norm = fft_para['freq_norm']\n\n # Speed up FFT by padding to optimal size for FFTPACK\n if data.ndim == 1:\n axis = 0\n elif data.ndim == 2:\n axis = 1\n\n Nfft = int(next_fast_len(int(data.shape[axis])))\n\n Napod = 100\n Nfft = int(Nfft)\n freqVec = scipy.fftpack.fftfreq(Nfft, d=delta)[:Nfft // 2]\n J = np.where((freqVec >= freqmin) & (freqVec <= freqmax))[0]\n low = J[0] - Napod\n if low <= 0:\n low = 1\n\n left = J[0]\n right = J[-1]\n high = J[-1] + Napod\n if high > Nfft/2:\n high = int(Nfft//2)\n\n FFTRawSign = scipy.fftpack.fft(data, Nfft,axis=axis)\n # Left tapering:\n if axis == 1:\n FFTRawSign[:,0:low] *= 0\n FFTRawSign[:,low:left] = np.cos(\n np.linspace(np.pi / 2., np.pi, left - low)) ** 2 * np.exp(\n 1j * np.angle(FFTRawSign[:,low:left]))\n # Pass band:\n if freq_norm == 'phase_only':\n FFTRawSign[:,left:right] = np.exp(1j * np.angle(FFTRawSign[:,left:right]))\n elif freq_norm == 'rma':\n for ii in range(data.shape[0]):\n tave = moving_ave(np.abs(FFTRawSign[ii,left:right]),smooth_N)\n FFTRawSign[ii,left:right] = FFTRawSign[ii,left:right]/tave\n # Right tapering:\n FFTRawSign[:,right:high] = np.cos(\n np.linspace(0., np.pi / 2., high - right)) ** 2 * np.exp(\n 1j * np.angle(FFTRawSign[:,right:high]))\n FFTRawSign[:,high:Nfft//2] *= 0\n\n # Hermitian symmetry (because the input is real)\n FFTRawSign[:,-(Nfft//2)+1:] = np.flip(np.conj(FFTRawSign[:,1:(Nfft//2)]),axis=axis)\n else:\n FFTRawSign[0:low] *= 0\n FFTRawSign[low:left] = np.cos(\n np.linspace(np.pi / 2., np.pi, left - low)) ** 2 * np.exp(\n 1j * np.angle(FFTRawSign[low:left]))\n # Pass band:\n if freq_norm == 'phase_only':\n FFTRawSign[left:right] = np.exp(1j * np.angle(FFTRawSign[left:right]))\n elif freq_norm == 'rma':\n tave = moving_ave(np.abs(FFTRawSign[left:right]),smooth_N)\n FFTRawSign[left:right] = FFTRawSign[left:right]/tave\n # Right tapering:\n FFTRawSign[right:high] = np.cos(\n np.linspace(0., np.pi / 2., high - right)) ** 2 * np.exp(\n 1j * np.angle(FFTRawSign[right:high]))\n FFTRawSign[high:Nfft//2] *= 0\n\n # Hermitian symmetry (because the input is real)\n FFTRawSign[-(Nfft//2)+1:] = FFTRawSign[1:(Nfft//2)].conjugate()[::-1]\n\n return FFTRawSign\n\ndef adaptive_filter(arr,g):\n '''\n the adaptive covariance filter to enhance coherent signals. Fellows the method of\n Nakata et al., 2015 (Appendix B)\n\n the filtered signal [x1] is given by x1 = ifft(P*x1(w)) where x1 is the ffted spectra\n and P is the filter. P is constructed by using the temporal covariance matrix.\n\n PARAMETERS:\n ----------------------\n arr: numpy.ndarray contains the 2D traces of daily/hourly cross-correlation functions\n g: a positive number to adjust the filter harshness\n RETURNS:\n ----------------------\n narr: numpy vector contains the stacked cross correlation function\n '''\n if arr.ndim == 1:\n return arr\n N,M = arr.shape\n Nfft = next_fast_len(M)\n\n # fft the 2D array\n spec = scipy.fftpack.fft(arr,axis=1,n=Nfft)[:,:M]\n\n # make cross-spectrm matrix\n cspec = np.zeros(shape=(N*N,M),dtype=np.complex64)\n for ii in range(N):\n for jj in range(N):\n kk = ii*N+jj\n cspec[kk] = spec[ii]*np.conjugate(spec[jj])\n\n S1 = np.zeros(M,dtype=np.complex64)\n S2 = np.zeros(M,dtype=np.complex64)\n # construct the filter P\n for ii in range(N):\n mm = ii*N+ii\n S2 += cspec[mm]\n for jj in range(N):\n kk = ii*N+jj\n S1 += cspec[kk]\n\n p = np.power((S1-S2)/(S2*(N-1)),g)\n\n # make ifft\n narr = np.real(scipy.fftpack.ifft(np.multiply(p,spec),Nfft,axis=1)[:,:M])\n return np.mean(narr,axis=0)\n\ndef pws(arr,sampling_rate,power=2,pws_timegate=5.):\n '''\n Performs phase-weighted stack on array of time series. Modified on the noise function by Tim Climents.\n Follows methods of Schimmel and Paulssen, 1997.\n If s(t) is time series data (seismogram, or cross-correlation),\n S(t) = s(t) + i*H(s(t)), where H(s(t)) is Hilbert transform of s(t)\n S(t) = s(t) + i*H(s(t)) = A(t)*exp(i*phi(t)), where\n A(t) is envelope of s(t) and phi(t) is phase of s(t)\n Phase-weighted stack, g(t), is then:\n g(t) = 1/N sum j = 1:N s_j(t) * | 1/N sum k = 1:N exp[i * phi_k(t)]|^v\n where N is number of traces used, v is sharpness of phase-weighted stack\n\n PARAMETERS:\n ---------------------\n arr: N length array of time series data (numpy.ndarray)\n sampling_rate: sampling rate of time series arr (int)\n power: exponent for phase stack (int)\n pws_timegate: number of seconds to smooth phase stack (float)\n\n RETURNS:\n ---------------------\n weighted: Phase weighted stack of time series data (numpy.ndarray)\n '''\n\n if arr.ndim == 1:\n return arr\n N,M = arr.shape\n analytic = hilbert(arr,axis=1, N=next_fast_len(M))[:,:M]\n phase = np.angle(analytic)\n phase_stack = np.mean(np.exp(1j*phase),axis=0)\n phase_stack = np.abs(phase_stack)**(power)\n\n # smoothing\n #timegate_samples = int(pws_timegate * sampling_rate)\n #phase_stack = moving_ave(phase_stack,timegate_samples)\n weighted = np.multiply(arr,phase_stack)\n return np.mean(weighted,axis=0)\n\n\ndef nroot_stack(cc_array,power):\n '''\n this is nth-root stacking algorithm translated based on the matlab function\n from https://github.com/xtyangpsp/SeisStack (by Xiaotao Yang; follows the \n reference of Millet, F et al., 2019 JGR) \n\n Parameters:\n ------------\n cc_array: numpy.ndarray contains the 2D cross correlation matrix\n power: np.int, nth root for the stacking\n\n Returns:\n ------------\n nstack: np.ndarray, final stacked waveforms\n\n Written by Chengxin Jiang @ANU (May2020)\n '''\n if cc_array.ndim == 1:\n print('2D matrix is needed for nroot_stack')\n return cc_array\n N,M = cc_array.shape \n dout = np.zeros(M,dtype=np.float32)\n\n # construct y\n for ii in range(N):\n dat = cc_array[ii,:]\n dout += np.sign(dat)*np.abs(dat)**(1/power)\n dout /= N\n\n # the final stacked waveform\n nstack = dout*np.abs(dout)**(power-1)\n\n return nstack\n\n\ndef selective_stack(cc_array,epsilon,cc_th):\n ''' \n this is a selective stacking algorithm developed by Jared Bryan/Kurama Okubo.\n\n PARAMETERS:\n ----------------------\n cc_array: numpy.ndarray contains the 2D cross correlation matrix\n epsilon: residual threhold to quit the iteration\n cc_th: numpy.float, threshold of correlation coefficient to be selected\n\n RETURNS:\n ----------------------\n newstack: numpy vector contains the stacked cross correlation\n nstep: np.int, total number of iterations for the stacking\n\n Originally ritten by Marine Denolle \n Modified by Chengxin Jiang @Harvard (Oct2020)\n '''\n if cc_array.ndim == 1:\n print('2D matrix is needed for nroot_stack')\n return cc_array\n N,M = cc_array.shape \n\n res = 9E9 # residuals\n cof = np.zeros(N,dtype=np.float32)\n newstack = np.mean(cc_array,axis=0)\n\n nstep = 0\n # start iteration\n while res>epsilon:\n for ii in range(N):\n cof[ii] = np.corrcoef(newstack, cc_array[ii,:])[0, 1]\n \n # find good waveforms\n indx = np.where(cof>=cc_th)[0]\n if not len(indx): raise ValueError('cannot find good waveforms inside selective stacking')\n oldstack = newstack\n newstack = np.mean(cc_array[indx],axis=0)\n res = np.linalg.norm(newstack-oldstack)/(np.linalg.norm(newstack)*M)\n nstep +=1\n\n return newstack, nstep\n\n\ndef get_cc(s1,s_ref):\n # returns the correlation coefficient between waveforms in s1 against reference\n # waveform s_ref.\n #\n cc=np.zeros(s1.shape[0])\n s_ref_norm = np.linalg.norm(s_ref)\n for i in range(s1.shape[0]):\n cc[i]=np.sum(np.multiply(s1[i,:],s_ref))/np.linalg.norm(s1[i,:])/s_ref_norm\n return cc\n\n\n########################################################\n################ MONITORING FUNCTIONS ##################\n########################################################\n\n'''\na compilation of all available core functions for computing phase delays based on ambient noise interferometry\n\nquick index of dv/v methods:\n1) stretching (time stretching; Weaver et al (2011))\n2) dtw_dvv (Dynamic Time Warping; Mikesell et al. 2015)\n3) mwcs_dvv (Moving Window Cross Spectrum; Clark et al., 2011)\n4) mwcc_dvv (Moving Window Cross Correlation; Snieder et al., 2012)\n5) wts_dvv (Wavelet Streching; Yuan et al., in prep)\n6) wxs_dvv (Wavelet Xross Spectrum; Mao et al., 2019)\n7) wdw_dvv (Wavelet Dynamic Warping; Yuan et al., in prep)\n'''\n\ndef stretching(ref, cur, dv_range, nbtrial, para):\n\n \"\"\"\n This function compares the Reference waveform to stretched/compressed current waveforms to get the relative seismic velocity variation (and associated error).\n It also computes the correlation coefficient between the Reference waveform and the current waveform.\n\n PARAMETERS:\n ----------------\n ref: Reference waveform (np.ndarray, size N)\n cur: Current waveform (np.ndarray, size N)\n dv_range: absolute bound for the velocity variation; example: dv=0.03 for [-3,3]% of relative velocity change ('float')\n nbtrial: number of stretching coefficient between dvmin and dvmax, no need to be higher than 100 ('float')\n para: vector of the indices of the cur and ref windows on wich you want to do the measurements (np.ndarray, size tmin*delta:tmax*delta)\n For error computation, we need parameters:\n fmin: minimum frequency of the data\n fmax: maximum frequency of the data\n tmin: minimum time window where the dv/v is computed\n tmax: maximum time window where the dv/v is computed\n RETURNS:\n ----------------\n dv: Relative velocity change dv/v (in %)\n cc: correlation coefficient between the reference waveform and the best stretched/compressed current waveform\n cdp: correlation coefficient between the reference waveform and the initial current waveform\n error: Errors in the dv/v measurements based on Weaver et al (2011), On the precision of noise-correlation interferometry, Geophys. J. Int., 185(3)\n\n Note: The code first finds the best correlation coefficient between the Reference waveform and the stretched/compressed current waveform among the \"nbtrial\" values.\n A refined analysis is then performed around this value to obtain a more precise dv/v measurement .\n\n Originally by L. Viens 04/26/2018 (Viens et al., 2018 JGR)\n modified by Chengxin Jiang\n \"\"\"\n # load common variables from dictionary\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvec = np.arange(tmin,tmax,dt)\n\n # make useful one for measurements\n dvmin = -np.abs(dv_range)\n dvmax = np.abs(dv_range)\n Eps = 1+(np.linspace(dvmin, dvmax, nbtrial))\n cof = np.zeros(Eps.shape,dtype=np.float32)\n\n # Set of stretched/compressed current waveforms\n for ii in range(len(Eps)):\n nt = tvec*Eps[ii]\n s = np.interp(x=tvec, xp=nt, fp=cur)\n waveform_ref = ref\n waveform_cur = s\n cof[ii] = np.corrcoef(waveform_ref, waveform_cur)[0, 1]\n\n cdp = np.corrcoef(cur, ref)[0, 1] # correlation coefficient between the reference and initial current waveforms\n\n # find the maximum correlation coefficient\n imax = np.nanargmax(cof)\n if imax >= len(Eps)-2:\n imax = imax - 2\n if imax <= 2:\n imax = imax + 2\n\n # Proceed to the second step to get a more precise dv/v measurement\n dtfiner = np.linspace(Eps[imax-2], Eps[imax+2], 100)\n ncof = np.zeros(dtfiner.shape,dtype=np.float32)\n for ii in range(len(dtfiner)):\n nt = tvec*dtfiner[ii]\n s = np.interp(x=tvec, xp=nt, fp=cur)\n waveform_ref = ref\n waveform_cur = s\n ncof[ii] = np.corrcoef(waveform_ref, waveform_cur)[0, 1]\n\n cc = np.max(ncof) # Find maximum correlation coefficient of the refined analysis\n dv = 100. * dtfiner[np.argmax(ncof)]-100 # Multiply by 100 to convert to percentage (Epsilon = -dt/t = dv/v)\n\n # Error computation based on Weaver et al (2011), On the precision of noise-correlation interferometry, Geophys. J. Int., 185(3)\n T = 1 / (fmax - fmin)\n X = cc\n wc = np.pi * (fmin + fmax)\n t1 = np.min([tmin, tmax])\n t2 = np.max([tmin, tmax])\n error = 100*(np.sqrt(1-X**2)/(2*X)*np.sqrt((6* np.sqrt(np.pi/2)*T)/(wc**2*(t2**3-t1**3))))\n\n return dv, error, cc, cdp\n\n\ndef stretching_vect(ref, cur, dv_range, nbtrial, para):\n \n \"\"\"\n This function compares the Reference waveform to stretched/compressed current waveforms to get the relative seismic velocity variation (and associated error).\n It also computes the correlation coefficient between the Reference waveform and the current waveform.\n \n PARAMETERS:\n ----------------\n ref: Reference waveform (np.ndarray, size N)\n cur: Current waveform (np.ndarray, size N)\n dv_range: absolute bound for the velocity variation; example: dv=0.03 for [-3,3]% of relative velocity change ('float')\n nbtrial: number of stretching coefficient between dvmin and dvmax, no need to be higher than 100 ('float')\n para: vector of the indices of the cur and ref windows on wich you want to do the measurements (np.ndarray, size tmin*delta:tmax*delta)\n For error computation, we need parameters:\n fmin: minimum frequency of the data\n fmax: maximum frequency of the data\n tmin: minimum time window where the dv/v is computed \n tmax: maximum time window where the dv/v is computed \n RETURNS:\n ----------------\n dv: Relative velocity change dv/v (in %)\n cc: correlation coefficient between the reference waveform and the best stretched/compressed current waveform\n cdp: correlation coefficient between the reference waveform and the initial current waveform\n error: Errors in the dv/v measurements based on Weaver et al (2011), On the precision of noise-correlation interferometry, Geophys. J. Int., 185(3)\n\n Note: The code first finds the best correlation coefficient between the Reference waveform and the stretched/compressed current waveform among the \"nbtrial\" values. \n A refined analysis is then performed around this value to obtain a more precise dv/v measurement .\n\n Originally by L. Viens 04/26/2018 (Viens et al., 2018 JGR)\n modified by Chengxin Jiang\n modified by Laura Ermert: vectorized version\n \"\"\" \n # load common variables from dictionary\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvec = np.arange(tmin, tmax, dt)\n\n # make useful one for measurements\n dvmin = -np.abs(dv_range)\n dvmax = np.abs(dv_range)\n Eps = 1 + (np.linspace(dvmin, dvmax, nbtrial))\n cdp = np.corrcoef(cur, ref)[0, 1] # correlation coefficient between the reference and initial current waveforms\n waveforms = np.zeros((nbtrial + 1, len(ref)))\n waveforms[0, :] = ref\n\n # Set of stretched/compressed current waveforms\n for ii in range(nbtrial):\n nt = tvec * Eps[ii]\n s = np.interp(x=tvec, xp=nt, fp=cur)\n waveforms[ii + 1, :] = s\n cof = np.corrcoef(waveforms)[0][1:]\n \n # find the maximum correlation coefficient\n imax = np.nanargmax(cof)\n if imax >= len(Eps)-2:\n imax = imax - 2\n if imax < 2:\n imax = imax + 2\n\n # Proceed to the second step to get a more precise dv/v measurement\n dtfiner = np.linspace(Eps[imax-2], Eps[imax+2], nbtrial)\n #ncof = np.zeros(dtfiner.shape,dtype=np.float32)\n waveforms = np.zeros((nbtrial + 1, len(ref)))\n waveforms[0, :] = ref\n for ii in range(len(dtfiner)):\n nt = tvec * dtfiner[ii]\n s = np.interp(x=tvec, xp=nt, fp=cur)\n waveforms[ii + 1, :] = s\n ncof = np.corrcoef(waveforms)[0][1: ]\n cc = np.max(ncof) # Find maximum correlation coefficient of the refined analysis\n dv = 100. * dtfiner[np.argmax(ncof)] - 100 # Multiply by 100 to convert to percentage (Epsilon = -dt/t = dv/v)\n\n # Error computation based on Weaver et al (2011), On the precision of noise-correlation interferometry, Geophys. J. Int., 185(3)\n T = 1 / (fmax - fmin)\n X = cc\n wc = np.pi * (fmin + fmax)\n t1 = np.min([tmin, tmax])\n t2 = np.max([tmin, tmax])\n error = 100*(np.sqrt(1-X**2)/(2*X)*np.sqrt((6* np.sqrt(np.pi/2)*T)/(wc**2*(t2**3-t1**3))))\n\n return dv, error, cc, cdp\n\ndef dtw_dvv(ref, cur, para, maxLag, b, direction):\n \"\"\"\n Dynamic time warping for dv/v estimation.\n\n PARAMETERS:\n ----------------\n ref : reference signal (np.array, size N)\n cur : current signal (np.array, size N)\n para: dict containing useful parameters about the data window and targeted frequency\n maxLag : max number of points to search forward and backward.\n Suggest setting it larger if window is set larger.\n b : b-value to limit strain, which is to limit the maximum velocity perturbation.\n See equation 11 in (Mikesell et al. 2015)\n direction: direction to accumulate errors (1=forward, -1=backward)\n RETURNS:\n ------------------\n -m0 : estimated dv/v\n em0 : error of dv/v estimation\n\n Original by Di Yang\n Last modified by Dylan Mikesell (25 Feb. 2015)\n Translated to python by Tim Clements (17 Aug. 2018)\n \"\"\"\n twin = para['twin']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n tvect = np.arange(tmin,tmax,dt)\n\n # setup other parameters\n npts = len(ref) # number of time samples\n\n # compute error function over lags, which is independent of strain limit 'b'.\n err = computeErrorFunction( cur, ref, npts, maxLag )\n\n # direction to accumulate errors (1=forward, -1=backward)\n dist = accumulateErrorFunction( direction, err, npts, maxLag, b )\n stbar = backtrackDistanceFunction( -1*direction, dist, err, -maxLag, b )\n stbarTime = stbar * dt # convert from samples to time\n\n # cut the first and last 5% for better regression\n indx = np.where((tvect>=0.05*npts*dt) & (tvect<=0.95*npts*dt))[0]\n\n # linear regression to get dv/v\n if npts >2:\n\n # weights\n w = np.ones(npts)\n #m, a, em, ea = linear_regression(time_axis[indx], delta_t[indx], w, intercept_origin=False)\n m0, em0 = linear_regression(tvect.flatten()[indx], stbarTime.flatten()[indx], w.flatten()[indx], intercept_origin=True)\n\n else:\n print('not enough points to estimate dv/v for dtw')\n m0=0;em0=0\n\n return m0*100,em0*100,dist\n\n\ndef mwcs_dvv(ref, cur, moving_window_length, slide_step, para, smoothing_half_win=5):\n \"\"\"\n Moving Window Cross Spectrum method to measure dv/v (relying on phi=2*pi*f*t in freq domain)\n\n PARAMETERS:\n ----------------\n ref: Reference waveform (np.ndarray, size N)\n cur: Current waveform (np.ndarray, size N)\n moving_window_length: moving window length to calculate cross-spectrum (np.float, in sec)\n slide_step: steps in time to shift the moving window (np.float, in seconds)\n para: a dict containing parameters about input data window and frequency info, including\n delta->The sampling rate of the input timeseries (in Hz)\n window-> The target window for measuring dt/t\n freq-> The frequency bound to compute the dephasing (in Hz)\n tmin: The leftmost time lag (used to compute the \"time lags array\")\n smoothing_half_win: If different from 0, defines the half length of the smoothing hanning window.\n\n RETURNS:\n ------------------\n time_axis: the central times of the windows.\n delta_t: dt\n delta_err:error\n delta_mcoh: mean coherence\n\n Copied from MSNoise (https://github.com/ROBelgium/MSNoise/tree/master/msnoise)\n Modified by Chengxin Jiang\n \"\"\"\n # common variables\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvect = np.arange(tmin,tmax,dt)\n\n # parameter initialize\n delta_t = []\n delta_err = []\n delta_mcoh = []\n time_axis = []\n\n # info on the moving window\n window_length_samples = np.int(moving_window_length/dt)\n padd = int(2 ** (nextpow2(window_length_samples) + 2))\n count = 0\n tp = cosine_taper(window_length_samples, 0.15)\n\n minind = 0\n maxind = window_length_samples\n\n # loop through all sub-windows\n while maxind <= len(ref):\n cci = cur[minind:maxind]\n cci = scipy.signal.detrend(cci, type='linear')\n cci *= tp\n\n cri = ref[minind:maxind]\n cri = scipy.signal.detrend(cri, type='linear')\n cri *= tp\n\n minind += int(slide_step/dt)\n maxind += int(slide_step/dt)\n\n # do fft\n fcur = scipy.fftpack.fft(cci, n=padd)[:padd // 2]\n fref = scipy.fftpack.fft(cri, n=padd)[:padd // 2]\n\n fcur2 = np.real(fcur) ** 2 + np.imag(fcur) ** 2\n fref2 = np.real(fref) ** 2 + np.imag(fref) ** 2\n\n # get cross-spectrum & do filtering\n X = fref * (fcur.conj())\n if smoothing_half_win != 0:\n dcur = np.sqrt(smooth(fcur2, window='hanning',half_win=smoothing_half_win))\n dref = np.sqrt(smooth(fref2, window='hanning',half_win=smoothing_half_win))\n X = smooth(X, window='hanning',half_win=smoothing_half_win)\n else:\n dcur = np.sqrt(fcur2)\n dref = np.sqrt(fref2)\n\n dcs = np.abs(X)\n\n # Find the values the frequency range of interest\n freq_vec = scipy.fftpack.fftfreq(len(X) * 2, dt)[:padd // 2]\n index_range = np.argwhere(np.logical_and(freq_vec >= fmin,freq_vec <= fmax))\n\n # Get Coherence and its mean value\n coh = getCoherence(dcs, dref, dcur)\n mcoh = np.mean(coh[index_range])\n\n # Get Weights\n w = 1.0 / (1.0 / (coh[index_range] ** 2) - 1.0)\n w[coh[index_range] >= 0.99] = 1.0 / (1.0 / 0.9801 - 1.0)\n w = np.sqrt(w * np.sqrt(dcs[index_range]))\n w = np.real(w)\n\n # Frequency array:\n v = np.real(freq_vec[index_range]) * 2 * np.pi\n\n # Phase:\n phi = np.angle(X)\n phi[0] = 0.\n phi = np.unwrap(phi)\n phi = phi[index_range]\n\n # Calculate the slope with a weighted least square linear regression\n # forced through the origin; weights for the WLS must be the variance !\n m, em = linear_regression(v.flatten(), phi.flatten(), w.flatten())\n delta_t.append(m)\n\n # print phi.shape, v.shape, w.shape\n e = np.sum((phi - m * v) ** 2) / (np.size(v) - 1)\n s2x2 = np.sum(v ** 2 * w ** 2)\n sx2 = np.sum(w * v ** 2)\n e = np.sqrt(e * s2x2 / sx2 ** 2)\n\n delta_err.append(e)\n delta_mcoh.append(np.real(mcoh))\n time_axis.append(tmin+moving_window_length/2.+count*slide_step)\n count += 1\n\n del fcur, fref\n del X\n del freq_vec\n del index_range\n del w, v, e, s2x2, sx2, m, em\n\n if maxind > len(cur) + int(slide_step/dt):\n print(\"The last window was too small, but was computed\")\n\n # ensure all matrix are np array\n delta_t = np.array(delta_t)\n delta_err = np.array(delta_err)\n delta_mcoh = np.array(delta_mcoh)\n time_axis = np.array(time_axis)\n\n # ready for linear regression\n delta_mincho = 0.65\n delta_maxerr = 0.1\n delta_maxdt = 0.1\n indx1 = np.where(delta_mcoh>delta_mincho)\n indx2 = np.where(delta_err<delta_maxerr)\n indx3 = np.where(delta_t<delta_maxdt)\n\n #-----find good dt measurements-----\n indx = np.intersect1d(indx1,indx2)\n indx = np.intersect1d(indx,indx3)\n\n if len(indx) >2:\n\n #----estimate weight for regression----\n w = 1/delta_err[indx]\n w[~np.isfinite(w)] = 1.0\n\n #---------do linear regression-----------\n #m, a, em, ea = linear_regression(time_axis[indx], delta_t[indx], w, intercept_origin=False)\n m0, em0 = linear_regression(time_axis[indx], delta_t[indx], w, intercept_origin=True)\n\n else:\n print('not enough points to estimate dv/v for mwcs')\n m0=0;em0=0\n\n return -m0*100,em0*100\n\n\ndef WCC_dvv(ref, cur, moving_window_length, slide_step, para):\n \"\"\"\n Windowed cross correlation (WCC) for dt or dv/v mesurement (Snieder et al. 2012)\n\n Parameters:\n -----------\n ref: The \"Reference\" timeseries\n cur: The \"Current\" timeseries\n moving_window_length: The moving window length (in seconds)\n slide_step: The step to jump for the moving window (in seconds)\n para: a dict containing freq/time info of the data matrix\n\n Returns:\n ------------\n time_axis: central times of the moving window\n delta_t: dt\n delta_err: error\n delta_mcoh: mean coherence for each window\n\n Written by Congcong Yuan (1 July, 2019)\n \"\"\"\n # common variables\n twin = para['twin']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n\n # parameter initialize\n delta_t = []\n delta_t_coef = []\n time_axis = []\n\n # info on the moving window\n window_length_samples = np.int(moving_window_length/dt)\n count = 0\n tp = cosine_taper(window_length_samples, 0.15)\n\n minind = 0\n maxind = window_length_samples\n\n # loop through all sub-windows\n while maxind <= len(ref):\n cci = cur[minind:maxind]\n cci = scipy.signal.detrend(cci, type='linear')\n cci *= tp\n\n cri = ref[minind:maxind]\n cri = scipy.signal.detrend(cri, type='linear')\n cri *= tp\n\n minind += int(slide_step/dt)\n maxind += int(slide_step/dt)\n\n # normalize signals before cross correlation\n cci = (cci - cci.mean()) / cci.std()\n cri = (cri - cri.mean()) / cri.std()\n\n # get maximum correlation coefficient and its index\n cc2 = np.correlate(cci, cri, mode='same')\n cc2 = cc2 / np.sqrt((cci**2).sum() * (cri**2).sum())\n\n imaxcc2 = np.where(cc2==np.max(cc2))[0]\n maxcc2 = np.max(cc2)\n\n # get the time shift\n m = (imaxcc2-((maxind-minind)//2))*dt\n delta_t.append(m)\n delta_t_coef.append(maxcc2)\n\n time_axis.append(tmin+moving_window_length/2.+count*slide_step)\n count += 1\n\n del cci, cri, cc2, imaxcc2, maxcc2\n del m\n\n if maxind > len(cur) + int(slide_step/dt):\n print(\"The last window was too small, but was computed\")\n\n delta_t = np.array(delta_t)\n delta_t_coef = np.array(delta_t_coef)\n time_axis = np.array(time_axis)\n\n # linear regression to get dv/v\n if count >2:\n # simple weight\n w = np.ones(count)\n #m, a, em, ea = linear_regression(time_axis[indx], delta_t[indx], w, intercept_origin=False)\n m0, em0 = linear_regression(time_axis.flatten(), delta_t.flatten(), w.flatten(),intercept_origin=True)\n\n else:\n print('not enough points to estimate dv/v for wcc')\n m0=0;em0=0\n\n return -m0*100,em0*100\n\n\ndef wxs_dvv(ref,cur,allfreq,para,dj=1/12, s0=-1, J=-1, sig=False, wvn='morlet',unwrapflag=False):\n \"\"\"\n Compute dt or dv/v in time and frequency domain from wavelet cross spectrum (wxs).\n for all frequecies in an interest range\n\n Parameters\n --------------\n ref: The \"Reference\" timeseries (numpy.ndarray)\n cur: The \"Current\" timeseries (numpy.ndarray)\n allfreq: a boolen variable to make measurements on all frequency range or not\n para: a dict containing freq/time info of the data matrix\n dj, s0, J, sig, wvn: common parameters used in 'wavelet.wct'\n unwrapflag: True - unwrap phase delays. Default is False\n\n RETURNS:\n ------------------\n dvv*100 : estimated dv/v in %\n err*100 : error of dv/v estimation in %\n\n Originally written by Tim Clements (1 March, 2019)\n Modified by Congcong Yuan (30 June, 2019) based on (Mao et al. 2019).\n Updated by Chengxin Jiang (10 Oct, 2019) to merge the functionality for mesurements across all frequency and one freq range\n \"\"\"\n # common variables\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvec = np.arange(tmin,tmax,dt)\n npts = len(tvec)\n\n # perform cross coherent analysis, modified from function 'wavelet.cwt'\n WCT, aWCT, coi, freq, sig = wct_modified(ref, cur, dt, dj=dj, s0=s0, J=J, sig=sig, wavelet=wvn, normalize=True)\n\n if unwrapflag:\n phase = np.unwrap(aWCT,axis=-1) # axis=0, upwrap along time; axis=-1, unwrap along frequency\n else:\n phase = aWCT\n\n # zero out data outside frequency band\n if (fmax> np.max(freq)) | (fmax <= fmin):\n raise ValueError('Abort: input frequency out of limits!')\n else:\n freq_indin = np.where((freq >= fmin) & (freq <= fmax))[0]\n\n # follow MWCS to do two steps of linear regression\n if not allfreq:\n\n delta_t_m, delta_t_unc = np.zeros(npts,dtype=np.float32),np.zeros(npts,dtype=np.float32)\n # assume the tvec is the time window to measure dt\n for it in range(npts):\n w = 1/WCT[freq_indin,it]\n w[~np.isfinite(w)] = 1.\n delta_t_m[it],delta_t_unc[it] = linear_regression(freq[freq_indin]*2*np.pi, phase[freq_indin,it], w)\n\n # new weights for regression\n w2 = 1/np.mean(WCT[freq_indin,:],axis=0)\n w2[~np.isfinite(w2)] = 1.\n\n # now use dt and t to get dv/v\n if len(w2)>2:\n if not np.any(delta_t_m):\n dvv, err = np.nan,np.nan\n m, em = linear_regression(tvec, delta_t_m, w2, intercept_origin=True)\n dvv, err = -m, em\n else:\n print('not enough points to estimate dv/v for wts')\n dvv, err=np.nan, np.nan\n\n return dvv*100,err*100\n\n # convert phase directly to delta_t for all frequencies\n else:\n\n # convert phase delay to time delay\n delta_t = phase / (2*np.pi*freq[:,None]) # normalize phase by (2*pi*frequency)\n dvv, err = np.zeros(freq_indin.shape), np.zeros(freq_indin.shape)\n\n # loop through freq for linear regression\n for ii, ifreq in enumerate(freq_indin):\n if len(tvec)>2:\n if not np.any(delta_t[ifreq]):\n continue\n\n # how to better approach the uncertainty of delta_t\n w = 1/WCT[ifreq]\n w[~np.isfinite(w)] = 1.0\n\n #m, a, em, ea = linear_regression(time_axis[indx], delta_t[indx], w, intercept_origin=False)\n m, em = linear_regression(tvec, delta_t[ifreq], w, intercept_origin=True)\n dvv[ii], err[ii] = -m, em\n else:\n print('not enough points to estimate dv/v for wts')\n dvv[ii], err[ii]=np.nan, np.nan\n\n return freq[freq_indin], dvv*100, err*100\n\n\ndef wts_dvv(ref,cur,allfreq,para,dv_range,nbtrial,dj=1/12,s0=-1,J=-1,wvn='morlet',normalize=True):\n \"\"\"\n Apply stretching method to continuous wavelet transformation (CWT) of signals\n for all frequecies in an interest range\n\n Parameters\n --------------\n ref: The \"Reference\" timeseries (numpy.ndarray)\n cur: The \"Current\" timeseries (numpy.ndarray)\n allfreq: a boolen variable to make measurements on all frequency range or not\n para: a dict containing freq/time info of the data matrix\n dv_range: absolute bound for the velocity variation; example: dv=0.03 for [-3,3]% of relative velocity change (float)\n nbtrial: number of stretching coefficient between dvmin and dvmax, no need to be higher than 100 (float)\n dj, s0, J, sig, wvn: common parameters used in 'wavelet.wct'\n normalize: normalize the wavelet spectrum or not. Default is True\n\n RETURNS:\n ------------------\n dvv: estimated dv/v\n err: error of dv/v estimation\n\n Written by Congcong Yuan (30 Jun, 2019)\n \"\"\"\n # common variables\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvec = np.arange(tmin,tmax,dt)\n\n # apply cwt on two traces\n cwt1, sj, freq, coi, _, _ = pycwt.cwt(cur, dt, dj, s0, J, wvn)\n cwt2, sj, freq, coi, _, _ = pycwt.cwt(ref, dt, dj, s0, J, wvn)\n\n # extract real values of cwt\n rcwt1, rcwt2 = np.real(cwt1), np.real(cwt2)\n\n # zero out data outside frequency band\n if (fmax> np.max(freq)) | (fmax <= fmin):\n raise ValueError('Abort: input frequency out of limits!')\n else:\n freq_indin = np.where((freq >= fmin) & (freq <= fmax))[0]\n\n # convert wavelet domain back to time domain (~filtering)\n if not allfreq:\n\n # inverse cwt to time domain\n icwt1 = pycwt.icwt(cwt1[freq_indin], sj[freq_indin], dt, dj, wvn)\n icwt2 = pycwt.icwt(cwt2[freq_indin], sj[freq_indin], dt, dj, wvn)\n\n # assume all time window is used\n wcwt1, wcwt2 = np.real(icwt1), np.real(icwt2)\n\n # Normalizes both signals, if appropriate.\n if normalize:\n ncwt1 = (wcwt1 - wcwt1.mean()) / wcwt1.std()\n ncwt2 = (wcwt2 - wcwt2.mean()) / wcwt2.std()\n else:\n ncwt1 = wcwt1\n ncwt2 = wcwt2\n\n # run stretching\n dvv, err, cc, cdp = stretching(ncwt2, ncwt1, dv_range, nbtrial, para)\n return dvv, err\n\n # directly take advantage of the\n else:\n # initialize variable\n nfreq=len(freq_indin)\n dvv, cc, cdp, err = np.zeros(nfreq,dtype=np.float32), np.zeros(nfreq,dtype=np.float32),\\\n np.zeros(nfreq,dtype=np.float32),np.zeros(nfreq,dtype=np.float32)\n\n # loop through each freq\n for ii, ifreq in enumerate(freq_indin):\n\n # prepare windowed data\n wcwt1, wcwt2 = rcwt1[ifreq], rcwt2[ifreq]\n\n # Normalizes both signals, if appropriate.\n if normalize:\n ncwt1 = (wcwt1 - wcwt1.mean()) / wcwt1.std()\n ncwt2 = (wcwt2 - wcwt2.mean()) / wcwt2.std()\n else:\n ncwt1 = wcwt1\n ncwt2 = wcwt2\n\n # run stretching\n dv, error, c1, c2 = stretching(ncwt2, ncwt1, dv_range, nbtrial, para)\n dvv[ii], cc[ii], cdp[ii], err[ii]=dv, c1, c2, error\n\n return freq[freq_indin], dvv, err\n\n\ndef wtdtw_allfreq(ref,cur,allfreq,para,maxLag,b,direction,dj=1/12,s0=-1,J=-1,wvn='morlet',normalize=True):\n \"\"\"\n Apply dynamic time warping method to continuous wavelet transformation (CWT) of signals\n for all frequecies in an interest range\n\n Parameters\n --------------\n ref: The \"Reference\" timeseries (numpy.ndarray)\n cur: The \"Current\" timeseries (numpy.ndarray)\n allfreq: a boolen variable to make measurements on all frequency range or not\n maxLag: max number of points to search forward and backward.\n b: b-value to limit strain, which is to limit the maximum velocity perturbation. See equation 11 in (Mikesell et al. 2015)\n direction: direction to accumulate errors (1=forward, -1=backward)\n dj, s0, J, sig, wvn: common parameters used in 'wavelet.wct'\n normalize: normalize the wavelet spectrum or not. Default is True\n\n RETURNS:\n ------------------\n dvv: estimated dv/v\n err: error of dv/v estimation\n\n Written by Congcong Yuan (30 Jun, 2019)\n \"\"\"\n # common variables\n twin = para['twin']\n freq = para['freq']\n dt = para['dt']\n tmin = np.min(twin)\n tmax = np.max(twin)\n fmin = np.min(freq)\n fmax = np.max(freq)\n tvec = np.arange(tmin,tmax)*dt\n\n # apply cwt on two traces\n cwt1, sj, freq, coi, _, _ = pycwt.cwt(cur, dt, dj, s0, J, wvn)\n cwt2, sj, freq, coi, _, _ = pycwt.cwt(ref, dt, dj, s0, J, wvn)\n\n # extract real values of cwt\n rcwt1, rcwt2 = np.real(cwt1), np.real(cwt2)\n\n # zero out cone of influence and data outside frequency band\n if (fmax> np.max(freq)) | (fmax <= fmin):\n raise ValueError('Abort: input frequency out of limits!')\n else:\n freq_indin = np.where((freq >= fmin) & (freq <= fmax))[0]\n\n # Use DTW method to extract dvv\n nfreq=len(freq_indin)\n dvv, err = np.zeros(nfreq,dtype=np.float32), np.zeros(nfreq,dtype=np.float32)\n\n for ii,ifreq in enumerate(freq_indin):\n\n # prepare windowed data\n wcwt1, wcwt2 = rcwt1[ifreq], rcwt2[ifreq]\n # Normalizes both signals, if appropriate.\n if normalize:\n ncwt1 = (wcwt1 - wcwt1.mean()) / wcwt1.std()\n ncwt2 = (wcwt2 - wcwt2.mean()) / wcwt2.std()\n else:\n ncwt1 = wcwt1\n ncwt2 = wcwt2\n\n # run dtw\n dv, error, dist = dtw_dvv(ncwt2, ncwt1, para, maxLag, b, direction)\n dvv[ii], err[ii] = dv, error\n\n del cwt1, cwt2, rcwt1, rcwt2, ncwt1, ncwt2, wcwt1, wcwt2, coi, sj, dist\n\n if not allfreq:\n return np.mean(dvv),np.mean(err)\n else:\n return freq[freq_indin], dvv, err\n\n\n#############################################################\n################ MONITORING UTILITY FUNCTIONS ###############\n#############################################################\n\n'''\nbelow are assembly of the monitoring utility functions called by monitoring functions\n'''\n\ndef smooth(x, window='boxcar', half_win=3):\n \"\"\"\n performs smoothing in interested time window\n\n Parameters\n --------------\n x: timeseris data\n window: types of window to do smoothing\n half_win: half window length\n\n RETURNS:\n ------------------\n y: smoothed time window\n \"\"\"\n # TODO: docsting\n window_len = 2 * half_win + 1\n # extending the data at beginning and at the end\n # to apply the window at the borders\n s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]\n if window == \"boxcar\":\n w = scipy.signal.boxcar(window_len).astype('complex')\n else:\n w = scipy.signal.hanning(window_len).astype('complex')\n y = np.convolve(w / w.sum(), s, mode='valid')\n return y[half_win:len(y) - half_win]\n\n\ndef nextpow2(x):\n \"\"\"\n Returns the next power of 2 of x.\n \"\"\"\n return int(np.ceil(np.log2(np.abs(x))))\n\n\ndef getCoherence(dcs, ds1, ds2):\n \"\"\"\n get cross coherence between reference and current waveforms following equation of A3 in Clark et al., 2011\n\n Parameters\n --------------\n dcs: amplitude of the cross spectrum\n ds1: amplitude of the spectrum of current waveform\n ds2: amplitude of the spectrum of reference waveform\n\n RETURNS:\n ------------------\n coh: cohrerency matrix used for estimate the robustness of the cross spectrum\n \"\"\"\n n = len(dcs)\n coh = np.zeros(n).astype('complex')\n valids = np.argwhere(np.logical_and(np.abs(ds1) > 0, np.abs(ds2) > 0))\n coh[valids] = dcs[valids] / (ds1[valids] * ds2[valids])\n coh[coh > (1.0 + 0j)] = 1.0 + 0j\n return coh\n\n\ndef computeErrorFunction(u1, u0, nSample, lag, norm='L2'):\n \"\"\"\n compute Error Function used in DTW. The error function is equation 1 in Hale, 2013. You could uncomment the\n L1 norm and comment the L2 norm if you want on Line 29\n\n Parameters\n --------------\n u1: trace that we want to warp; size = (nsamp,1)\n u0: reference trace to compare with: size = (nsamp,1)\n nSample: numer of points to compare in the traces\n lag: maximum lag in sample number to search\n norm: 'L2' or 'L1' (default is 'L2')\n\n RETURNS:\n ------------------\n err: the 2D error function; size = (nsamp,2*lag+1)\n\n Original by Di Yang\n Last modified by Dylan Mikesell (25 Feb. 2015)\n Translated to python by Tim Clements (17 Aug. 2018)\n\n \"\"\"\n\n if lag >= nSample:\n raise ValueError('computeErrorFunction:lagProblem','lag must be smaller than nSample')\n\n # Allocate error function variable\n err = np.zeros([nSample, 2 * lag + 1])\n\n # initial error calculation\n # loop over lags\n for ll in np.arange(-lag,lag + 1):\n thisLag = ll + lag\n\n # loop over samples\n for ii in range(nSample):\n\n # skip corners for now, we will come back to these\n if (ii + ll >= 0) & (ii + ll < nSample):\n err[ii,thisLag] = u1[ii] - u0[ii + ll]\n\n if norm == 'L2':\n err = err**2\n elif norm == 'L1':\n err = np.abs(err)\n\n # Now fix corners with constant extrapolation\n for ll in np.arange(-lag,lag + 1):\n thisLag = ll + lag\n\n for ii in range(nSample):\n if ii + ll < 0:\n err[ii, thisLag] = err[-ll, thisLag]\n\n elif ii + ll > nSample - 1:\n err[ii,thisLag] = err[nSample - ll - 1,thisLag]\n\n return err\n\n\ndef accumulateErrorFunction(dir, err, nSample, lag, b ):\n \"\"\"\n accumulation of the error, which follows the equation 6 in Hale, 2013.\n\n Parameters\n --------------\n dir: accumulation direction ( dir > 0 = forward in time, dir <= 0 = backward in time)\n err: the 2D error function; size = (nsamp,2*lag+1)\n nSample: numer of points to compare in the traces\n lag: maximum lag in sample number to search\n b: strain limit (integer value >= 1)\n\n RETURNS:\n ------------------\n d: the 2D distance function; size = (nsamp,2*lag+1)\n\n Original by Di Yang\n Last modified by Dylan Mikesell (25 Feb. 2015)\n Translated to python by Tim Clements (17 Aug. 2018)\n\n \"\"\"\n\n # number of lags from [ -lag : +lag ]\n nLag = ( 2 * lag ) + 1\n\n # allocate distance matrix\n d = np.zeros([nSample, nLag])\n\n # Setup indices based on forward or backward accumulation direction\n if dir > 0: # FORWARD\n iBegin, iEnd, iInc = 0, nSample - 1, 1\n else: # BACKWARD\n iBegin, iEnd, iInc = nSample - 1, 0, -1\n\n # Loop through all times ii in forward or backward direction\n for ii in range(iBegin,iEnd + iInc,iInc):\n\n # min/max to account for the edges/boundaries\n ji = max([0, min([nSample - 1, ii - iInc])])\n jb = max([0, min([nSample - 1, ii - iInc * b])])\n\n # loop through all lag\n for ll in range(nLag):\n\n # check limits on lag indices\n lMinus1 = ll - 1\n\n # check lag index is greater than 0\n if lMinus1 < 0:\n lMinus1 = 0 # make lag = first lag\n\n lPlus1 = ll + 1 # lag at l+1\n\n # check lag index less than max lag\n if lPlus1 > nLag - 1:\n lPlus1 = nLag - 1\n\n # get distance at lags (ll-1, ll, ll+1)\n distLminus1 = d[jb, lMinus1] # minus: d[i-b, j-1]\n distL = d[ji,ll] # actual d[i-1, j]\n distLplus1 = d[jb, lPlus1] # plus d[i-b, j+1]\n\n if ji != jb: # equation 10 in Hale, 2013\n for kb in range(ji,jb + iInc - 1, -iInc):\n distLminus1 = distLminus1 + err[kb, lMinus1]\n distLplus1 = distLplus1 + err[kb, lPlus1]\n\n # equation 6 (if b=1) or 10 (if b>1) in Hale (2013) after treating boundaries\n d[ii, ll] = err[ii,ll] + min([distLminus1, distL, distLplus1])\n\n return d\n\n\ndef backtrackDistanceFunction(dir, d, err, lmin, b):\n \"\"\"\n The function is equation 2 in Hale, 2013.\n\n Parameters\n --------------\n dir: side to start minimization ( dir > 0 = front, dir <= 0 = back)\n d : the 2D distance function; size = (nsamp,2*lag+1)\n err: the 2D error function; size = (nsamp,2*lag+1)\n lmin: minimum lag to search over\n b : strain limit (integer value >= 1)\n\n RETURNS:\n ------------------\n stbar: vector of integer shifts subject to |u(i)-u(i-1)| <= 1/b\n\n Original by Di Yang\n Last modified by Dylan Mikesell (19 Dec. 2014)\n\n Translated to python by Tim Clements (17 Aug. 2018)\n\n \"\"\"\n\n nSample, nLag = d.shape\n stbar = np.zeros(nSample)\n\n # Setup indices based on forward or backward accumulation direction\n if dir > 0: # FORWARD\n iBegin, iEnd, iInc = 0, nSample - 1, 1\n else: # BACKWARD\n iBegin, iEnd, iInc = nSample - 1, 0, -1\n\n # start from the end (front or back)\n ll = np.argmin(d[iBegin,:]) # find minimum accumulated distance at front or back depending on 'dir'\n stbar[iBegin] = ll + lmin # absolute value of integer shift\n\n # move through all time samples in forward or backward direction\n ii = iBegin\n\n while ii != iEnd:\n\n # min/max for edges/boundaries\n ji = np.max([0, np.min([nSample - 1, ii + iInc])])\n jb = np.max([0, np.min([nSample - 1, ii + iInc * b])])\n\n # check limits on lag indices\n lMinus1 = ll - 1\n\n if lMinus1 < 0: # check lag index is greater than 1\n lMinus1 = 0 # make lag = first lag\n\n lPlus1 = ll + 1\n\n if lPlus1 > nLag - 1: # check lag index less than max lag\n lPlus1 = nLag - 1\n\n # get distance at lags (ll-1, ll, ll+1)\n distLminus1 = d[jb, lMinus1] # minus: d[i-b, j-1]\n distL = d[ji,ll] # actual d[i-1, j]\n distLplus1 = d[jb, lPlus1] # plus d[i-b, j+1]\n\n # equation 10 in Hale (2013)\n # sum errors over i-1:i-b+1\n if ji != jb:\n for kb in range(ji, jb - iInc - 1, iInc):\n distLminus1 = distLminus1 + err[kb, lMinus1]\n distLplus1 = distLplus1 + err[kb, lPlus1]\n\n # update minimum distance to previous sample\n dl = np.min([distLminus1, distL, distLplus1 ])\n\n if dl != distL: # then ll ~= ll and we check forward and backward\n if dl == distLminus1:\n ll = lMinus1\n else:\n ll = lPlus1\n\n # assume ii = ii - 1\n ii += iInc\n\n # absolute integer of lag\n stbar[ii] = ll + lmin\n\n # now move to correct time index, if smoothing difference over many\n # time samples using 'b'\n if (ll == lMinus1) | (ll == lPlus1): # check edges to see about b values\n if ji != jb: # if b>1 then need to move more steps\n for kb in range(ji, jb - iInc - 1, iInc):\n ii = ii + iInc # move from i-1:i-b-1\n stbar[ii] = ll + lmin # constant lag over that time\n\n return stbar\n\n\ndef wct_modified(y1, y2, dt, dj=1/12, s0=-1, J=-1, sig=True, significance_level=0.95, wavelet='morlet', normalize=True, **kwargs):\n '''\n Wavelet coherence transform (WCT).\n\n The WCT finds regions in time frequency space where the two time\n series co-vary, but do not necessarily have high power.\n\n Parameters\n ----------\n y1, y2 : numpy.ndarray, list\n Input signals.\n dt : float\n Sample spacing.\n dj : float, optional\n Spacing between discrete scales. Default value is 1/12.\n Smaller values will result in better scale resolution, but\n slower calculation and plot.\n s0 : float, optional\n Smallest scale of the wavelet. Default value is 2*dt.\n J : float, optional\n Number of scales less one. Scales range from s0 up to\n s0 * 2**(J * dj), which gives a total of (J + 1) scales.\n Default is J = (log2(N*dt/so))/dj.\n significance_level (float, optional) :\n Significance level to use. Default is 0.95.\n normalize (boolean, optional) :\n If set to true, normalizes CWT by the standard deviation of\n the signals.\n\n Returns\n -------\n TODO: Something TBA and TBC\n\n See also\n --------\n cwt, xwt\n\n '''\n\n wavelet = pycwt.wavelet._check_parameter_wavelet(wavelet)\n # Checking some input parameters\n if s0 == -1:\n # Number of scales\n s0 = 2 * dt / wavelet.flambda()\n if J == -1:\n # Number of scales\n J = np.int(np.round(np.log2(y1.size * dt / s0) / dj))\n\n # Makes sure input signals are numpy arrays.\n y1 = np.asarray(y1)\n y2 = np.asarray(y2)\n # Calculates the standard deviation of both input signals.\n std1 = y1.std()\n std2 = y2.std()\n # Normalizes both signals, if appropriate.\n if normalize:\n y1_normal = (y1 - y1.mean()) / std1\n y2_normal = (y2 - y2.mean()) / std2\n else:\n y1_normal = y1\n y2_normal = y2\n\n # Calculates the CWT of the time-series making sure the same parameters\n # are used in both calculations.\n _kwargs = dict(dj=dj, s0=s0, J=J, wavelet=wavelet)\n W1, sj, freq, coi, _, _ = pycwt.cwt(y1_normal, dt, **_kwargs)\n W2, sj, freq, coi, _, _ = pycwt.cwt(y2_normal, dt, **_kwargs)\n\n scales1 = np.ones([1, y1.size]) * sj[:, None]\n scales2 = np.ones([1, y2.size]) * sj[:, None]\n\n # Smooth the wavelet spectra before truncating.\n S1 = wavelet.smooth(np.abs(W1) ** 2 / scales1, dt, dj, sj)\n S2 = wavelet.smooth(np.abs(W2) ** 2 / scales2, dt, dj, sj)\n\n # Now the wavelet transform coherence\n W12 = W1 * W2.conj()\n scales = np.ones([1, y1.size]) * sj[:, None]\n S12 = wavelet.smooth(W12 / scales, dt, dj, sj)\n WCT = np.abs(S12) ** 2 / (S1 * S2)\n aWCT = np.angle(W12)\n\n # Calculate cross spectrum & its amplitude\n WXS, WXA = W12, np.abs(S12)\n\n # Calculates the significance using Monte Carlo simulations with 95%\n # confidence as a function of scale.\n\n if sig:\n a1, b1, c1 = pycwt.ar1(y1)\n a2, b2, c2 = pycwt.ar1(y2)\n sig = pycwt.wct_significance(a1, a2, dt=dt, dj=dj, s0=s0, J=J,\n significance_level=significance_level,\n wavelet=wavelet, **kwargs)\n else:\n sig = np.asarray([0])\n\n return WCT, aWCT, coi, freq, sig\n\n\n################################################################\n################ DISPERSION EXTRACTION FUNCTIONS ###############\n################################################################\n\n# function to extract the dispersion from the image\ndef extract_dispersion(amp,per,vel):\n '''\n this function takes the dispersion image from CWT as input, tracks the global maxinum on\n the wavelet spectrum amplitude and extract the sections with continous and high quality data\n\n PARAMETERS:\n ----------------\n amp: 2D amplitude matrix of the wavelet spectrum\n phase: 2D phase matrix of the wavelet spectrum\n per: period vector for the 2D matrix\n vel: vel vector of the 2D matrix\n RETURNS:\n ----------------\n per: central frequency of each wavelet scale with good data\n gv: group velocity vector at each frequency\n '''\n maxgap = 5\n nper = amp.shape[0]\n gv = np.zeros(nper,dtype=np.float32)\n dvel = vel[1]-vel[0]\n\n # find global maximum\n for ii in range(nper):\n maxvalue = np.max(amp[ii],axis=0)\n indx = list(amp[ii]).index(maxvalue)\n gv[ii] = vel[indx]\n\n # check the continuous of the dispersion\n for ii in range(1,nper-15):\n # 15 is the minumum length needed for output\n for jj in range(15):\n if np.abs(gv[ii+jj]-gv[ii+1+jj])>maxgap*dvel:\n gv[ii] = 0\n break\n\n # remove the bad ones\n indx = np.where(gv>0)[0]\n\n return per[indx],gv[indx]\n"
] |
[
[
"numpy.dot",
"numpy.imag",
"numpy.sqrt",
"numpy.linspace",
"numpy.asarray",
"pandas.DataFrame",
"numpy.concatenate",
"numpy.max",
"scipy.fftpack.fft",
"numpy.int",
"numpy.mean",
"numpy.argmin",
"scipy.fftpack.fftfreq",
"numpy.round",
"numpy.linalg.qr",
"numpy.any",
"numpy.exp",
"numpy.where",
"numpy.ma.is_masked",
"numpy.conjugate",
"pandas.read_csv",
"scipy.fftpack.next_fast_len",
"numpy.arange",
"numpy.sin",
"numpy.intersect1d",
"numpy.std",
"numpy.real",
"numpy.size",
"numpy.interp",
"numpy.float32",
"numpy.argmax",
"scipy.signal.hanning",
"numpy.load",
"numpy.zeros",
"numpy.fft.irfft",
"scipy.fftpack.ifft",
"numpy.multiply",
"numpy.power",
"numpy.min",
"numpy.isnan",
"numpy.median",
"numpy.linalg.inv",
"numpy.ma.median",
"numpy.floor",
"numpy.corrcoef",
"numpy.array",
"numpy.correlate",
"numpy.sum",
"numpy.logical_and",
"scipy.signal.detrend",
"numpy.nanargmax",
"numpy.log2",
"numpy.abs",
"numpy.fft.rfft",
"numpy.conj",
"numpy.isfinite",
"numpy.linalg.norm",
"numpy.cos",
"numpy.ones",
"numpy.sign",
"numpy.ma.abs",
"numpy.unwrap",
"scipy.signal.boxcar",
"numpy.angle",
"numpy.isinf"
]
] |
mforbes/mmfutils-fork
|
[
"77deabc243e27cadedff3c2088dd3ff440da2da6"
] |
[
"mmfutils/tests/test_context.py"
] |
[
"import os\nimport signal\nimport time\n\nimport numpy as np\n\nimport pytest\n\nfrom mmfutils import contexts\n\[email protected]_fixture\ndef NoInterrupt():\n yield contexts.NoInterrupt\n # Restore original handlers\n contexts.NoInterrupt.unregister()\n\n \nclass TestNoInterrupt(object):\n @staticmethod\n def simulate_interrupt(force=False, signum=signal.SIGINT):\n \"\"\"Simulates an interrupt or forced interupt.\"\"\"\n # Simulate user interrupt\n os.kill(os.getpid(), signum)\n if force:\n # Simulated a forced interrupt with multiple signals\n os.kill(os.getpid(), signum)\n os.kill(os.getpid(), signum)\n time.sleep(0.1)\n\n def test_typical_use(self, NoInterrupt):\n \"\"\"Typical usage\"\"\"\n with NoInterrupt() as interrupted:\n done = False\n n = 0\n while not done and not interrupted:\n n += 1\n if n == 10:\n done = True\n\n assert n == 10\n \n def test_restoration_of_handlers(self, NoInterrupt):\n original_hs = {_sig: signal.getsignal(_sig)\n for _sig in NoInterrupt._signals}\n \n with NoInterrupt():\n with NoInterrupt():\n for _sig in original_hs:\n assert original_hs[_sig] is not signal.getsignal(_sig)\n for _sig in original_hs:\n assert original_hs[_sig] is not signal.getsignal(_sig)\n\n for _sig in original_hs:\n assert original_hs[_sig] is not signal.getsignal(_sig)\n \n NoInterrupt.unregister()\n \n for _sig in original_hs:\n assert original_hs[_sig] is signal.getsignal(_sig)\n\n def test_signal(self, NoInterrupt):\n with pytest.raises(KeyboardInterrupt):\n with NoInterrupt(ignore=False) as interrupted:\n m = -1\n for n in range(10):\n if n == 5:\n self.simulate_interrupt()\n if interrupted:\n m = n\n assert n == 9\n assert m >= 5\n\n # Make sure the signals can still be raised.\n with pytest.raises(KeyboardInterrupt):\n self.simulate_interrupt()\n time.sleep(1)\n\n # And that the interrupts are reset\n try:\n with NoInterrupt() as interrupted:\n n = 0\n while n < 10 and not interrupted:\n n += 1\n except KeyboardInterrupt:\n raise Exception(\"KeyboardInterrupt raised when it should not be!\")\n\n assert n == 10\n\n def test_set_signal(self, NoInterrupt):\n signals = set(NoInterrupt._signals)\n try:\n NoInterrupt.set_signals((signal.SIGHUP,))\n with pytest.raises(KeyboardInterrupt):\n with NoInterrupt(ignore=False) as interrupted:\n while not interrupted:\n self.simulate_interrupt()\n finally:\n # Reset signals\n NoInterrupt.set_signals(signals)\n\n def interrupted_loop(self, interrupted=False, force=False):\n \"\"\"Simulates an interrupt or forced interupt in the middle of a\n loop. Two counters are incremented from 0 in `self.n`. The interrupt\n is signaled self.n[0] == 5, and the loop naturally exist when self.n[0]\n >= 10. The first counter is incremented before the interrupt is\n simulated, while the second counter is incremented after.\"\"\"\n self.n = [0, 0]\n done = False\n while not done and not interrupted:\n self.n[0] += 1\n if self.n[0] == 5:\n self.simulate_interrupt(force=force)\n self.n[1] += 1\n done = self.n[0] >= 10\n\n def test_issue_14(self, NoInterrupt):\n \"\"\"Regression test for issue 14 and bug discovered there.\"\"\"\n with pytest.raises(KeyboardInterrupt):\n with NoInterrupt() as interrupted:\n self.interrupted_loop(interrupted=interrupted, force=True)\n assert np.allclose(self.n, [5, 4])\n\n try:\n # We need to wrap this in a try block otherwise py.test will think\n # that the user aborted the test.\n\n # All interrupts should be cleared and this should run to\n # completion.\n with NoInterrupt() as interrupted:\n self.interrupted_loop(force=False)\n except KeyboardInterrupt:\n pass\n\n # This used to fail since the interrupts were not cleared.\n assert np.allclose(self.n, [10, 10])\n\n def test_nested_handlers(self, NoInterrupt):\n completed = []\n for a in range(3):\n with NoInterrupt(ignore=True) as i2:\n for b in range(3):\n if i2:\n break\n if a == 1 and b == 1:\n self.simulate_interrupt()\n completed.append((a, b))\n \n assert completed == [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),\n (2, 0), (2, 1), (2, 2)]\n\n completed = []\n with NoInterrupt(ignore=True) as i1:\n for a in range(3):\n if i1:\n break\n with NoInterrupt(ignore=True) as i2:\n for b in range(3):\n if i2:\n break\n if a ==1 and b == 1:\n self.simulate_interrupt()\n completed.append((a, b))\n\n assert completed == [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]\n\n completed = []\n with NoInterrupt(ignore=True) as i1:\n for a in range(3):\n if i1:\n break\n with NoInterrupt(ignore=True) as i2:\n for b in [0, 1, 2]:\n if i2:\n break\n if a ==1 and b == 1:\n self.simulate_interrupt()\n completed.append((a, b))\n\n with NoInterrupt(ignore=True) as i3:\n for b in [3]:\n if i3:\n break\n completed.append((a, b))\n\n assert completed == [(0, 0), (0, 1), (0, 2), (0, 3),\n (1, 0), (1, 1), (1, 3)]\n\n def test_unused_context(self, NoInterrupt):\n \"\"\"Test issue 28: bare instance hides signals.\n\n Signals should only be caught in contexts.\n \"\"\"\n NoInterrupt()\n\n # Signals should no longer be caught\n with pytest.raises(KeyboardInterrupt):\n self.simulate_interrupt()\n time.sleep(1)\n\n def test_reused_context(self, NoInterrupt):\n \"\"\"Test that NoInterrupt() instances can be reused.\"\"\"\n ni = NoInterrupt()\n with pytest.raises(KeyboardInterrupt):\n with ni as interrupted:\n self.interrupted_loop(interrupted=interrupted, force=True)\n assert np.allclose(self.n, [5, 4])\n \n with ni as interrupted:\n self.interrupted_loop(interrupted=interrupted, force=False)\n assert np.allclose(self.n, [5, 5])\n\n def test_map(self, NoInterrupt):\n def f(x, values_computed):\n if x == 2:\n self.simulate_interrupt()\n values_computed.append(x)\n return x**2\n\n values_computed = []\n res = NoInterrupt().map(f, [1, 2, 3], values_computed=values_computed)\n assert res == [1, 4]\n \n with pytest.raises(KeyboardInterrupt):\n # Signals still work.\n self.simulate_interrupt()\n\n # Here the interrupt should not be ignored, but f() should be\n # allowed to complete.\n values_computed = []\n res = []\n with pytest.raises(KeyboardInterrupt):\n res = NoInterrupt(ignore=False).map(f, [1, 2, 3],\n values_computed=values_computed)\n assert res == []\n assert values_computed == [1, 2]\n \n # As opposed to a normal map:\n values_computed = []\n res = []\n with pytest.raises(KeyboardInterrupt):\n res = list(map(lambda x: f(x, values_computed), [1, 2, 3]))\n assert res == []\n assert values_computed == [1]\n\n def test_no_context(self, NoInterrupt):\n \"\"\"Test catching signals without a context.\"\"\"\n NoInterrupt._signal_count = {} # Don't do this... just for testing\n NoInterrupt.register()\n interrupted = NoInterrupt()\n assert interrupted._signal_count == {}\n with pytest.raises(KeyboardInterrupt):\n self.simulate_interrupt(signum=signal.SIGINT)\n # Won't get executed because we have not suspended signals\n self.simulate_interrupt(signum=signal.SIGINT)\n assert interrupted._signal_count == {signal.SIGINT: 1}\n\n NoInterrupt.reset() # Prevent triggering a forced interrupt\n\n interrupted1 = NoInterrupt()\n assert interrupted # Old interrupted still registers the interrupt\n assert not interrupted1 # New interrupted does not.\n\n # reset() does not reset counts.\n assert interrupted._signal_count == {signal.SIGINT: 1}\n assert interrupted1._signal_count == {signal.SIGINT: 1}\n \n NoInterrupt.suspend()\n self.simulate_interrupt(signum=signal.SIGTERM)\n self.simulate_interrupt(signum=signal.SIGTERM)\n assert interrupted1._signal_count == {signal.SIGINT: 1,\n signal.SIGTERM: 2}\n NoInterrupt.resume()\n with pytest.raises(KeyboardInterrupt):\n self.simulate_interrupt(signum=signal.SIGINT)\n\n def test_unregister_context(self, NoInterrupt):\n NoInterrupt.unregister()\n with NoInterrupt(ignore=True) as interrupted:\n self.simulate_interrupt(signum=signal.SIGINT)\n"
] |
[
[
"numpy.allclose"
]
] |
ellisdg/BRATS
|
[
"668728b9683316f57b999d4bbccc68dfe6f9769d"
] |
[
"unet3d/scripts/train.py"
] |
[
"import os\nimport argparse\nimport pandas as pd\nimport numpy as np\nfrom unet3d.train import run_training\nfrom unet3d.utils.filenames import wrapped_partial, generate_filenames, load_bias, load_sequence\nfrom unet3d.utils.sequences import (WholeVolumeToSurfaceSequence, HCPRegressionSequence, ParcelBasedSequence,\n WindowedAutoEncoderSequence)\nfrom unet3d.utils.pytorch.dataset import (WholeBrainCIFTI2DenseScalarDataset, HCPRegressionDataset, AEDataset,\n WholeVolumeSegmentationDataset, WindowedAEDataset)\nfrom unet3d.utils.utils import load_json, in_config, dump_json\nfrom unet3d.utils.custom import get_metric_data_from_config\nfrom unet3d.scripts.predict import format_parser as format_prediction_args\nfrom unet3d.scripts.predict import run_inference\nfrom unet3d.scripts.script_utils import get_machine_config, add_machine_config_to_parser\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config_filename\", required=True,\n help=\"JSON configuration file specifying the parameters for model training.\")\n parser.add_argument(\"--model_filename\",\n help=\"Location to save the model during and after training. If this filename exists \"\n \"prior to training, the model will be loaded from the filename.\",\n required=True)\n parser.add_argument(\"--training_log_filename\",\n help=\"CSV filename to save the to save the training and validation results for each epoch.\",\n required=True)\n parser.add_argument(\"--fit_gpu_mem\", type=float,\n help=\"Specify the amount of gpu memory available on a single gpu and change the image size to \"\n \"fit into gpu memory automatically. Will try to find the largest image size that will fit \"\n \"onto a single gpu. The batch size is overwritten and set to the number of gpus available.\"\n \" The new image size will be written to a new config file ending named \"\n \"'<original_config>_auto.json'. This option is experimental and only works with the UNet \"\n \"model. It has only been tested with gpus that have 12GB and 32GB of memory.\")\n parser.add_argument(\"--group_average_filenames\")\n parser.add_argument(\"--batch_size\", help=\"Override the batch size from the config file.\", type=int)\n parser.add_argument(\"--debug\", action=\"store_true\", default=False,\n help=\"Raises an error if a training file is not found. The default is to silently skip\"\n \"any training files that cannot be found. Use this flag to debug the config for finding\"\n \"the data.\")\n add_machine_config_to_parser(parser)\n subparsers = parser.add_subparsers(help=\"sub-commands\", dest='sub_command')\n prediction_parser = subparsers.add_parser(name=\"predict\",\n help=\"Run prediction after the model has finished training\")\n format_prediction_args(prediction_parser, sub_command=True)\n args = parser.parse_args()\n\n return args\n\n\ndef check_hierarchy(config):\n if in_config(\"labels\", config[\"sequence_kwargs\"]) and in_config(\"use_label_hierarchy\", config[\"sequence_kwargs\"]):\n config[\"sequence_kwargs\"].pop(\"use_label_hierarchy\")\n labels = config[\"sequence_kwargs\"].pop(\"labels\")\n new_labels = list()\n while len(labels):\n new_labels.append(labels)\n labels = labels[1:]\n config[\"sequence_kwargs\"][\"labels\"] = new_labels\n\n\ndef compute_unet_number_of_voxels(window, channels, n_layers):\n n_voxels = 0\n for i in range(n_layers):\n n_voxels = n_voxels + ((1/(2**(3*i))) * window[0] * window[1] * window[2] * channels * 2**i * 2)\n return n_voxels\n\n\ndef compute_window_size(step, step_size, ratios):\n step_ratios = np.asarray(ratios) * step * step_size\n mod = np.mod(step_ratios, step_size)\n return np.asarray(step_ratios - mod + np.round(mod / step_size) * step_size, dtype=int)\n\n\ndef update_config_to_fit_gpu_memory(config, n_gpus, gpu_memory, output_filename, voxels_per_gb=17000000.0,\n ratios=(1.22, 1.56, 1.0)):\n max_voxels = voxels_per_gb * gpu_memory\n n_layers = len(config[\"model_kwargs\"][\"encoder_blocks\"])\n step_size = 2**(n_layers - 1)\n step = 1\n window = compute_window_size(step, step_size, ratios)\n n_voxels = compute_unet_number_of_voxels(window, config[\"model_kwargs\"][\"base_width\"], n_layers)\n while n_voxels <= max_voxels:\n step = step + 1\n window = compute_window_size(step, step_size, ratios)\n n_voxels = compute_unet_number_of_voxels(window, config[\"model_kwargs\"][\"base_width\"], n_layers)\n window = compute_window_size(step - 1, step_size, ratios).tolist()\n print(\"Setting window size to {} x {} x {}\".format(*window))\n print(\"Setting batch size to\", n_gpus)\n config[\"window\"] = window\n config[\"model_kwargs\"][\"input_shape\"] = window\n config[\"batch_size\"] = n_gpus\n config[\"validation_batch_size\"] = n_gpus\n print(\"Writing new configuration file:\", output_filename)\n dump_json(config, output_filename)\n\n\ndef main():\n import nibabel as nib\n nib.imageglobals.logger.level = 40\n\n namespace = parse_args()\n\n print(\"Config: \", namespace.config_filename)\n config = load_json(namespace.config_filename)\n\n if \"package\" in config:\n package = config[\"package\"]\n else:\n package = \"keras\"\n\n if \"metric_names\" in config and not config[\"n_outputs\"] == len(config[\"metric_names\"]):\n raise ValueError(\"n_outputs set to {}, but number of metrics is {}.\".format(config[\"n_outputs\"],\n len(config[\"metric_names\"])))\n\n print(\"Model: \", namespace.model_filename)\n print(\"Log: \", namespace.training_log_filename)\n system_config = get_machine_config(namespace)\n training_function_kwargs = in_config(\"training_function_kwargs\", config, dict())\n\n # set verbosity\n if namespace.debug:\n if \"sequence_kwargs\" not in config:\n config[\"sequence_kwargs\"] = dict()\n config[\"sequence_kwargs\"][\"verbose\"] = namespace.debug\n\n # Override the batch size from the config file\n if namespace.batch_size:\n config[\"batch_size\"] = namespace.batch_size\n\n if namespace.fit_gpu_mem and namespace.fit_gpu_mem > 0:\n update_config_to_fit_gpu_memory(config=config, n_gpus=system_config[\"n_gpus\"], gpu_memory=namespace.fit_gpu_mem,\n output_filename=namespace.config_filename.replace(\".json\", \"_auto.json\"))\n\n if namespace.group_average_filenames is not None:\n group_average = get_metric_data_from_config(namespace.group_average_filenames, namespace.config_filename)\n from unet3d.models.keras.resnet.resnet import compare_scores\n model_metrics = [wrapped_partial(compare_scores, comparison=group_average)]\n metric_to_monitor = \"compare_scores\"\n else:\n model_metrics = []\n if config['skip_validation']:\n metric_to_monitor = \"loss\"\n else:\n metric_to_monitor = \"val_loss\"\n\n if config[\"skip_validation\"]:\n groups = (\"training\",)\n else:\n groups = (\"training\", \"validation\")\n\n if \"directory\" in system_config:\n directory = system_config.pop(\"directory\")\n elif \"directory\" in config:\n directory = config[\"directory\"]\n else:\n directory = \"\"\n\n for name in groups:\n key = name + \"_filenames\"\n if key not in config:\n config[key] = generate_filenames(config, name, directory,\n raise_if_not_exists=namespace.debug)\n if \"sequence\" in config:\n sequence_class = load_sequence(config[\"sequence\"])\n elif \"_wb_\" in os.path.basename(namespace.config_filename):\n if \"package\" in config and config[\"package\"] == \"pytorch\":\n if config[\"sequence\"] == \"AEDataset\":\n sequence_class = AEDataset\n elif config[\"sequence\"] == \"WholeVolumeSegmentationDataset\":\n sequence_class = WholeVolumeSegmentationDataset\n else:\n sequence_class = WholeBrainCIFTI2DenseScalarDataset\n else:\n sequence_class = WholeVolumeToSurfaceSequence\n elif config[\"sequence\"] == \"WindowedAutoEncoderSequence\":\n sequence_class = WindowedAutoEncoderSequence\n elif config[\"sequence\"] == \"WindowedAEDataset\":\n sequence_class = WindowedAEDataset\n elif \"_pb_\" in os.path.basename(namespace.config_filename):\n sequence_class = ParcelBasedSequence\n config[\"sequence_kwargs\"][\"parcellation_template\"] = os.path.join(\n directory, config[\"sequence_kwargs\"][\"parcellation_template\"])\n else:\n if config[\"package\"] == \"pytorch\":\n sequence_class = HCPRegressionDataset\n else:\n sequence_class = HCPRegressionSequence\n\n if \"bias_filename\" in config and config[\"bias_filename\"] is not None:\n bias = load_bias(config[\"bias_filename\"])\n else:\n bias = None\n\n check_hierarchy(config)\n\n if in_config(\"add_contours\", config[\"sequence_kwargs\"], False):\n config[\"n_outputs\"] = config[\"n_outputs\"] * 2\n\n if sequence_class == ParcelBasedSequence:\n target_parcels = config[\"sequence_kwargs\"].pop(\"target_parcels\")\n for target_parcel in target_parcels:\n config[\"sequence_kwargs\"][\"target_parcel\"] = target_parcel\n print(\"Training on parcel: {}\".format(target_parcel))\n if type(target_parcel) == list:\n parcel_id = \"-\".join([str(i) for i in target_parcel])\n else:\n parcel_id = str(target_parcel)\n _training_log_filename = namespace.training_log_filename.replace(\".csv\", \"_{}.csv\".format(parcel_id))\n if os.path.exists(_training_log_filename):\n _training_log = pd.read_csv(_training_log_filename)\n if (_training_log[metric_to_monitor].values.argmin()\n <= len(_training_log) - int(config[\"early_stopping_patience\"])):\n print(\"Already trained\")\n continue\n run_training(package,\n config,\n namespace.model_filename.replace(\".h5\", \"_{}.h5\".format(parcel_id)),\n _training_log_filename,\n sequence_class=sequence_class,\n model_metrics=model_metrics,\n metric_to_monitor=metric_to_monitor,\n **training_function_kwargs,\n **system_config)\n\n else:\n run_training(package, config, namespace.model_filename, namespace.training_log_filename,\n sequence_class=sequence_class,\n model_metrics=model_metrics,\n metric_to_monitor=metric_to_monitor,\n bias=bias,\n **training_function_kwargs,\n **system_config)\n\n if namespace.sub_command == \"predict\":\n run_inference(namespace)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.mod",
"numpy.round",
"pandas.read_csv",
"numpy.asarray"
]
] |
elixiruhig/DRDetetction-Final
|
[
"a00e957424a95d41b232b9d3cdf7d11ceca83174"
] |
[
"DiabeticRetinopathy/inference.py"
] |
[
"# Ignore the warnings\nimport warnings\n\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n\n# data visualisation and manipulation\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport seaborn as sns\n\n# configure\n# sets matplotlib to inline and displays graphs below the corressponding cell.\n\nfrom sklearn.metrics import confusion_matrix\n\n# specifically for manipulating zipped images and getting numpy arrays of pixel values of images.\nimport cv2\nimport numpy as np\n# from tqdm import tqdm, tqdm_notebook\n# import os, random\n# from random import shuffle\n# from zipfile import ZipFile\n# from PIL import Image\n# from sklearn.utils import shuffle\nimport sys\n\nimport fastai\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks import *\nfrom fastai.basic_train import *\nfrom efficientnet_pytorch import EfficientNet\nfrom fastai.vision.learner import *\n\n\n\n\n\n\n\n\nmodel = EfficientNet.from_name('efficientnet-b6', override_params={'num_classes': 5 })\n\n\nclass FocalLoss(nn.Module):\n def __init__(self, gamma=3., reduction='mean'):\n super().__init__()\n self.gamma = gamma\n self.reduction = reduction\n\n def forward(self, inputs, targets):\n CE_loss = nn.CrossEntropyLoss(reduction='none')(inputs, targets)\n pt = torch.exp(-CE_loss)\n F_loss = ((1 - pt)**self.gamma) * CE_loss\n if self.reduction == 'sum':\n return F_loss.sum()\n elif self.reduction == 'mean':\n return F_loss.mean()\n\nfrom torch.utils.data.sampler import WeightedRandomSampler\n\nclass OverSamplingCallback(LearnerCallback):\n def __init__(self,learn:Learner, weights:torch.Tensor=None):\n super().__init__(learn)\n self.labels = self.learn.data.train_dl.dataset.y.items\n _, counts = np.unique(self.labels, return_counts=True)\n self.weights = (weights if weights is not None else\n torch.DoubleTensor((1/counts)[self.labels]))\n\n def on_train_begin(self, **kwargs):\n self.learn.data.train_dl.dl.batch_sampler = BatchSampler(\n WeightedRandomSampler(self.weights, len(self.learn.data.train_dl.dataset)),\n self.learn.data.train_dl.batch_size,False)\n\npath=''\nlearn = load_learner(path)\n\ndata1 = [['00a8624548a9',0],['00b74780d31d',0],['000c1434d8d7',0],['0d0a21fd354f',0]]\ndf_train = pd.DataFrame(data1, columns=['id_code','diagnosis'])\n\naptos19_stats = ([0.42, 0.22, 0.075], [0.27, 0.15, 0.081])\ntrain_path19 = Path('')\ndata = ImageDataBunch.from_df(df=df_train,\n path=train_path19, folder='imagelist', suffix='.png',\n ds_tfms=get_transforms(flip_vert=False),\n size=356\n ).normalize(aptos19_stats)\n\nimg = data.train_ds[1][0]\nprint(learn.predict(img))"
] |
[
[
"pandas.DataFrame",
"numpy.unique"
]
] |
andrewwarrington/vesicle-cnn-2
|
[
"cff34d1451fb196616624efaeba00b6e6816ed13"
] |
[
"vesicle-cnn-2/vesicle-cnn-2.py"
] |
[
"# MIT License\n#\n# Copyright (c) 2017, Andrew Warrington\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software 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\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nAdaptation of VESICLE-CNN (Roncal et al 2014) to be fully convolutional instead of patch-based.\nScript loads, builds, trains and then deploys a fully convolutional approximation of VESCILE-CNN.\nWork is described in more detail in [include citation].\n\"\"\"\n\n# Import stock libraries. ----------------------------------------------------------------------------------------------\nimport os\nimport time\nimport timeit\nimport matplotlib.pyplot as plt\nimport h5py\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport argparse\nfrom shutil import copyfile\n\n# Import additional libraries. -----------------------------------------------------------------------------------------\nimport utilities as util\n\n# Parse arguments. -----------------------------------------------------------------------------------------------------\nparser = argparse.ArgumentParser(description='VESICLE-CNN-2 training and deployment framework.')\n\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument('--train_new', help='Are we training a new network? (mutually exclusive with --deploy_trained).', action='store_true')\ngroup.add_argument('--deploy_pretrained', help='File location of classifier to be deployed. (mutually exclusive with --training).', default=False)\n\nparser.add_argument('--gpu', help='GPU ID to run computations on.', default=False)\nparser.add_argument('--train_fraction', help='Fraction of training batches that are positive instances.', default=0.1)\nparser.add_argument('--positive_weight', help='The balancing weight used in weighted cross entropy calculations.', default=10)\nparser.add_argument('--deploy_train', help='Deploy network to train data set?', action='store_true', default=True)\nparser.add_argument('--deploy_validation', help='Deploy network to validation dataset', action='store_true', default=True)\nparser.add_argument('--deploy_test', help='Deploy network to test data set', action='store_true', default=False)\nparser.add_argument('--deploy_unlabelled', help='Deploy network to test dataset', action='store_true', default=False)\nargs = parser.parse_args()\n\n# Configure GPU settings. ----------------------------------------------------------------------------------------------\nif args.gpu:\n\tos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' # see issue #152\n\tos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n''' Configure network settings. -------------------------------------------------------------------------------------'''\n\n# Configure network architecture parameters.\npatchSize = [67, 67]\nimSizeFC = [5, 5]\nconvolutionalFilters = 48\nfirstLayerDimensions = [5, 5, 1, convolutionalFilters]\nsecondLayerDimensions = [5, 5, convolutionalFilters, convolutionalFilters]\nthirdLayerDimensions = [5, 5, convolutionalFilters, convolutionalFilters]\nfcNeurons = 1024\nfcLayerDimensions = [imSizeFC[0], imSizeFC[1], convolutionalFilters, fcNeurons]\n\n# Configure training parameters.\ntrainingSteps = 300000\nbatch_size = 100\npos_frac = float(args.train_fraction)\npos_weight = float(args.positive_weight)\nlearningRate = 1e-04\nvalRegularity = 1000\nvalFirst = 150000\n\n# Define data locations.\ndataLocations = ['./../kasthuri_data/train/train.h5', './../kasthuri_data/validation/validation.h5', './../kasthuri_data/test/test.h5']\nchannelLocations = ['/synapse'] # Label location _within_ the H5 file.\ninternalLocations = ['SYN']\nimgLocation = '/image' # Image location _within_ the H5 file.\n\n# Define experimental setup.\ntraining = args.train_new\ndeployTrain = args.deploy_train\ndeployValidation = args.deploy_validation\ndeployTest = args.deploy_test\ndeployUnlabelled = args.deploy_unlabelled\nload_path = args.deploy_pretrained\n\n# Misc.\ntrainingSteps += 1\n\n''' Read in images from h5. -----------------------------------------------------------------------------------------'''\n\n[trainImage, trainLabels] = util.load_data(dataLocations[0], imgLocation, channelLocations, internalLocations)\n[validateImage, validateLabels] = util.load_data(dataLocations[1], imgLocation, channelLocations, internalLocations)\n[testImage, testLabels] = util.load_data(dataLocations[2], imgLocation, channelLocations, internalLocations)\n\nassert trainImage.shape[1] == trainImage.shape[2]\n\n# Configure settings pertaining to window size.\nborder = int(math.floor(patchSize[0]/2))\nwindowSize = [trainImage.shape[1], trainImage.shape[2]]\nfinalSize = [windowSize[0] - 2*border, windowSize[1] - 2*border]\nimSize = trainImage.shape\nimElements = windowSize[0] * windowSize[1]\ntrainImages = trainImage.shape[0]\nvalidationImages = validateImage.shape[0]\ntestImages = testImage.shape[0]\n\n# Prepare locations lists.\npad = int(math.floor(patchSize[0] / 2))\npositive_locations = np.where(trainLabels['SYN'][:, pad:imSize[1]-pad, pad:imSize[2]-pad, :])\nnegative_locations = np.where(1 - trainLabels['SYN'][:, pad:imSize[1]-pad, pad:imSize[2]-pad, :])\n\n''' Configure output file -------------------------------------------------------------------------------------------'''\n\n# Configure file for output.\nif not args.deploy_pretrained:\n\tfileOutputName = \"Results/VCNN-2_\" + time.strftime(\"%Y_%m_%d\") + \"_\" + time.strftime(\"%H_%M_%S\")\nelse:\n\tfileOutputName = args.deploy_pretrained\n\nif not os.path.exists(fileOutputName):\n os.makedirs(fileOutputName)\n\t\nreportLocation = fileOutputName + \"/report.txt\"\nutil.echo_to_file(reportLocation, \"\\n-- VESICLE-CNN-2 synapse detector. --\\n\")\n\nutil.echo_to_file(reportLocation, \"Experiment to train VESICLE-CNN-2 to predict synapses.\\n\")\nutil.echo_to_file(reportLocation, \"Experiment conducted at:\" + time.strftime(\"%d/%m/%Y\") + \" \" + time.strftime(\"%H:%M:%S\") + \".\\n\\n\")\n\nif args.deploy_pretrained is not False:\n\tutil.echo_to_file(reportLocation, \"Deploying pre-trained network saved at %s\" % args.deploy_pretrained)\nelse:\n\tutil.echo_to_file(reportLocation, \"Training new network.\")\n\t# Copy current version of this script, as well as the makefile just to make sure we capture the experiment.\n\tif not os.path.exists(fileOutputName + \"/backup\"):\n\t\tos.makedirs(fileOutputName + \"/backup\")\n\tcopyfile('./vesicle-cnn-2.py', fileOutputName + \"/backup/vesicle-cnn-2.py\")\n\tcopyfile('./Makefile', fileOutputName + \"/backup/Makefile\")\n\nutil.echo_to_file(reportLocation, \"Experimental setup:\\n\")\nutil.echo_to_file(reportLocation, \"Training settings:\\n\")\nutil.echo_to_file(reportLocation, \"\\tLearning scheme: ADAM\\n\")\nutil.echo_to_file(reportLocation, \"\\tLearning rate: %f\\n\" % learningRate)\nutil.echo_to_file(reportLocation, \"\\tTraining steps: %s\\n\" % trainingSteps)\nutil.echo_to_file(reportLocation, \"\\tOptimize weighted cross entropy\\n\")\nutil.echo_to_file(reportLocation, \"\\tSelect best network from F1\\n\\n\")\nutil.echo_to_file(reportLocation, \"\\tTraining ratio: %f\\n\" % pos_frac)\nutil.echo_to_file(reportLocation, \"\\tTraining weight: %f\\n\" % pos_weight)\nutil.echo_to_file(reportLocation, \"\\tBatch size: %f\\n\" % batch_size)\nutil.echo_to_file(reportLocation, \"\\tFirst validation at: %f\\n\" % valFirst)\n\nutil.echo_to_file(reportLocation, \"Architecture settings:\\n\")\nutil.echo_to_file(reportLocation, \"\\tConvolution layer 1: %s\\n\" % firstLayerDimensions)\nutil.echo_to_file(reportLocation, \"\\tConvolution layer 2: %s\\n\" % secondLayerDimensions)\nutil.echo_to_file(reportLocation, \"\\tConvolution layer 3: %s\\n\" % thirdLayerDimensions)\nutil.echo_to_file(reportLocation, \"\\tFC units: %f\\n\" % fcNeurons)\nutil.echo_to_file(reportLocation, \"\\tInput patch size: %s\\n\" % patchSize)\n\n''' Configure TensorFlow graph -------------------------------------------------------------------------------------'''\n\nutil.echo_to_file(reportLocation, \"\\nConfiguring network.\\n\")\n\n# Create placeholders for independent and dependant variables once batch has been selected.\nwith tf.name_scope('Input_Image'):\n x = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='Image') # Independent variables.\n # Reshape to amenable shape.\n # x_image = tf.reshape(x, [-1, windowSize[0], windowSize[1], 1])\nwith tf.name_scope('Input_Synapse'):\n y_syn = tf.placeholder(tf.float32, shape=[None, 2]) # Target values.\n\nwith tf.name_scope('First_Layer'):\n # Create first convolutional layer. (No pooling.)\n W_conv1 = util.weight_variable(firstLayerDimensions, \"w_conv_1\") # Weights in first layer.\n b_conv1 = util.bias_variable([firstLayerDimensions[3]], \"b_conv_1\") # Biases in first layer.\n h_conv1 = tf.nn.relu(util.conv2d(x, W_conv1, valid=True, stride=1) + b_conv1) # Perform convolution (with zero padding) and apply ReLU.\n h_pool1 = util.max_pool(h_conv1, 1, kernelWidth=2)\n\nwith tf.name_scope('Second_Layer'):\n # Create first convolutional layer. (No pooling.)\n W_conv2 = util.weight_variable(secondLayerDimensions, \"w_conv_2\") # Weights in first layer.\n b_conv2 = util.bias_variable([secondLayerDimensions[3]], \"b_conv_2\") # Biases in first layer.\n h_conv2 = tf.nn.relu(util.atrous_conv2d(h_pool1, W_conv2, valid=True, rate=2) + b_conv2) # Perform convolution (with zero padding) and apply ReLU.\n h_pool2 = util.atrous_max_pool(h_conv2, mask_size=2, rate=2)\n\nwith tf.name_scope('Third_Layer'):\n # Create first convolutional layer. (No pooling.)\n W_conv3 = util.weight_variable(thirdLayerDimensions, \"w_conv_3\") # Weights in first layer.\n b_conv3 = util.bias_variable([thirdLayerDimensions[3]], \"b_conv_3\") # Biases in first layer.\n h_conv3 = tf.nn.relu(util.atrous_conv2d(h_pool2, W_conv3, valid=True, rate=4) + b_conv3) # Perform convolution (with zero padding) and apply ReLU.\n h_pool3 = util.atrous_max_pool(h_conv3, mask_size=2, rate=4)\n\nwith tf.name_scope('fccnn_Layer'):\n # Create FC layer for final classification.\n W_fccnn1 = util.weight_variable(fcLayerDimensions, \"w_fccnn_1\") # Image patch for FC, with firstFCNeurons neurons.\n b_fccnn1 = util.bias_variable([fcLayerDimensions[3]], \"b_fccnn_1\") # Biases for firstFCNeurons neurons.\n h_fccnn1 = tf.nn.relu(util.atrous_conv2d(h_pool3, W_fccnn1, valid=True, rate=8) + b_fccnn1) # Perform convolution (with zero padding) and apply ReLU.\n\n# Insert more FC layers here.\n\nwith tf.name_scope('Output_Layer'):\n # Now add a final sigmoid layer for prediction of 0-1 probability and readout.\n W_fccnn2 = util.weight_variable([1, 1, fcLayerDimensions[3], 2], \"w_fccnn_2\")\n b_fccnn2 = util.bias_variable([2], \"b_fccnn_2\")\n y_syn_logit = tf.nn.relu(util.conv2d(h_fccnn1, W_fccnn2, valid=True) + b_fccnn2)\n y_syn_soft = tf.nn.softmax(y_syn_logit)\n y_syn_logit_flat = tf.reshape(y_syn_logit, [-1, 2])\n y_syn_soft_flat = tf.reshape(y_syn_soft, [-1, 2])\n\t\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\n# Define cross entropy as loss function.\nwith tf.name_scope('XEnt'):\n\tcross_entropy = tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(targets=y_syn, logits=y_syn_logit_flat, pos_weight=pos_weight, name='syn_Loss'))\n\n# Calculate accuracy as an average across vector.\nwith tf.name_scope('Acc'):\n\t# Get the predictions for later evaluation.\n\tpredictions = tf.argmax(y_syn_soft, 3)\n\t\n\t# Binary vector of correct predictions.\n\tcorrect_prediction = tf.equal(tf.argmax(y_syn_logit_flat, 1), tf.argmax(y_syn, 1))\n\t\n\t# Now calc accuracy.\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\t\n\t# Calculate f1\n\taccuracyF1, precision, recall, fmeasure = util.tf_calculate_PR(y_syn_soft_flat, y_syn)\n\n# Use ADAM as optimizer to minimize the cross entropy.\ntrain_step = tf.train.AdamOptimizer(learningRate).minimize(cross_entropy)\n\n# Merge all the summaries and write them out.\nwriter = tf.summary.FileWriter(fileOutputName + '/LOGS', graph=tf.get_default_graph())\n\nwith tf.name_scope('Losses'):\n\ttf.summary.scalar(\"cost\", cross_entropy)\n\ttf.summary.scalar(\"accuracy\", accuracy)\n\nwith tf.name_scope('F-Metrics'):\n\ttf.summary.scalar(\"accuracy_(f1)\", accuracyF1)\n\ttf.summary.scalar(\"precision\", precision)\n\ttf.summary.scalar(\"recall\", recall)\n\ttf.summary.scalar(\"fmeasure\", fmeasure)\n\n# Merge all summaries into a single \"operation\" which we can execute in a session.\nsummary_op = tf.summary.merge_all()\n\n# Use an interactive session for debugging.\nconfig_opt = tf.ConfigProto()\nconfig_opt.gpu_options.allow_growth = True\nsess = tf.Session(config=config_opt)\n\n# Initialize the variables.\nsess.run(tf.global_variables_initializer())\n\n# Declare misc variables for storing times etc.\nf1s = []\nxEnts = []\naccs = []\ntrainTimes = np.zeros((trainingSteps, 1))\ngpuTimes = np.zeros((trainingSteps, 1))\n\n''' Train network -------------------------------------------------------------------------------------------'''\n\n\n# Function to automate application of a classifier to the validation volume.\ndef validate_network(_f1s=[], _accs=[], _xents=[], final_val=False, first_val=False):\n\tval_cross_entropy, val_accuracy, val_fmeasure = np.zeros((validationImages, 8)), np.zeros((validationImages, 8)), np.zeros((validationImages, 8))\n\tfor j in range(validationImages):\n\t\tfor k in range(8):\n\t\t\tval_batch = util.get_minibatch_image(validateImage, validateLabels, batch_size=1, valN=j, orientation=k, border=border)\n\t\t\treshaped = np.reshape(val_batch[0], [-1, windowSize[0], windowSize[1], 1])\n\t\t\tval_cross_entropy[j, k], val_accuracy[j, k], val_fmeasure[j, k] = sess.run([cross_entropy, accuracy, fmeasure], feed_dict={x: reshaped, y_syn: val_batch[1]['SYN']})\n\t\n\tvalidation_accuracy = np.average(np.average(val_accuracy))\n\tvalidation_cross_entropy = np.average(np.average(val_cross_entropy))\n\tvalidation_fmeasure = np.average(np.average(val_fmeasure))\n\n\t_f1s.append(validation_fmeasure)\n\t_accs.append(validation_accuracy)\n\t_xents.append(validation_fmeasure)\n\t\n\tif (np.nanmax(f1s) == validation_fmeasure) | first_val:\n\t\tsaver.save(sess, fileOutputName + \"/CNN.ckpt\")\n\t\n\tif not final_val:\n\t\toutput_string = (\"step %d, validation accuracy %g, cross entropy %g, f1(ave) %g\\n\" % (i, validation_accuracy, validation_cross_entropy, validation_fmeasure))\n\telse:\n\t\toutput_string = (\"Validation accuracy using single best validated model, applied to whole of validation set: \\n\\n\\t Validation error: %g\\n\\t Validation XEnt: %g\\n\\t Validation F1: %g\\n\\t\" % (_accs[0], _xents[0], _f1s[0]))\n\t\n\tutil.echo_to_file(reportLocation, output_string)\n\t\n\treturn _f1s, _accs, _xents\n\n\n# If we are training the network (as opposed to deploying an existing network).\nif training:\n\t\n\tutil.echo_to_file(reportLocation, \"\\nTraining network.\\n\")\n\t\n\tfor i in range(trainingSteps):\n\t\t\n\t\tif ((i % valRegularity) == 0) and ((i >= valFirst) or (i == 0)):\n\t\t\tf1s, accs, xEnts = validate_network(f1s, accs, xEnts, first_val=(i==0))\n\t\t\t\n\t\tstartTime = timeit.default_timer()\n\t\tbatch = util.get_minibatch_patch(trainImage, trainLabels['SYN'], batch_size, patchSize, pos_frac=pos_frac, pos_locs=positive_locations, neg_locs=negative_locations)\n\t\tstartTimeGPU = timeit.default_timer()\n\t\t_, summary = sess.run([train_step, summary_op], feed_dict={x: batch[0], y_syn: batch[1]})\n\t\telapsed = timeit.default_timer() - startTime\n\t\tgpuElapsed = timeit.default_timer() - startTimeGPU\n\t\ttrainTimes[i] = elapsed\n\t\tgpuTimes[i] = gpuElapsed\n\t\twriter.add_summary(summary, i)\t\n\n\tav = np.sum(trainTimes) / trainingSteps\n\tgpu_av = np.sum(gpuTimes) / trainingSteps\n\t# Now write the timings to the output file.\n\tutil.echo_to_file(reportLocation, \"\\nAverage training step time: %g s (%g GPU s). \\n\\n\" % (av, gpu_av))\n\t\n\t# Restore the best net.\n\tsaver.restore(sess, fileOutputName + \"/CNN.ckpt\")\n\t\n\t# Do final validation on network.\n\tvalidate_network(final_val=True)\n\nelse:\n\t# Odd hack required. Deployment to GPU without taking at least a single training step causes memory error. TODO fix this.\n batch = util.get_minibatch_patch(trainImage, trainLabels['SYN'], batch_size, patchSize, pos_frac=pos_frac, pos_locs=positive_locations, neg_locs=negative_locations)\n _, summary = sess.run([train_step, summary_op], feed_dict={x: batch[0], y_syn: batch[1]})\n\n\n\t\n''' Define targets to allow for validation and deployment of network ---------------------------------------------'''\n\n\n# Apply the classifier (defined by _func) to the image stack (defined by _images).\ndef apply_classifier(_func, _images):\n\n\t_numFrames = _images.shape[0]\n\t\n\tvolume_prediction = np.zeros((_numFrames, finalSize[0], finalSize[1], 2))\n\t_application_times = np.zeros((_numFrames, 1))\n\t_gpu_times = np.zeros((_numFrames, 1))\t\n\t\n\tfor i in range(_numFrames):\n\t\tstartTime = timeit.default_timer()\n\t\t_single_im = np.expand_dims(_images[i, :, :].astype(np.float32), axis=0)\n\t\tstartTimeGPU = timeit.default_timer()\n\t\tpredFlat = sess.run(_func, feed_dict={x: _single_im}) \n\t\telapsed = timeit.default_timer() - startTimeGPU\n\t\t_gpu_times[i] = elapsed\n\t\t\n\t\tsinglePred = np.reshape(predFlat[0, :, :, 0], finalSize)\n\t\tvolume_prediction[i, :, :, 0] = singlePred\n\t\t\n\t\tsinglePred = np.reshape(predFlat[0, :, :, 1], finalSize)\n\t\tvolume_prediction[i, :, :, 1] = singlePred\n\t\t\n\t\telapsed = timeit.default_timer() - startTime\n\t\t_application_times[i] = elapsed\n\n\t\tprint(\"Prediction of layer %g/%g complete.\" % (i + 1, _numFrames))\n\t\n\tav = np.sum(_application_times) / _numFrames\n\tgpu_av = np.sum(_gpu_times) / _numFrames\n\tutil.echo_to_file(reportLocation, \"\\nAverage time application time per frame: %g s (%g GPU s). \\n\\n\" % (av, gpu_av))\n\n\treturn volume_prediction\n\n\n# Evaluate F1 score for a test volume (volume_prediction) to a ground truth volume (_labels).\n# Use _channel as a tag for output.\ndef evaluate_f1(volume_prediction, _labels, _channel):\n\tprecision, recall, f1 = util.calculate_PR(volume_prediction, _labels)\n\t\n\t# Now write the timings to the output file.\n\tutil.echo_to_file(reportLocation, \"\\n\" + _channel + \"\\n\")\n\tutil.echo_to_file(reportLocation, \"\\nPrecision: %g \\n\" % precision)\n\tutil.echo_to_file(reportLocation, \"\\nRecall: %g \\n\" % recall)\n\tutil.echo_to_file(reportLocation, \"\\nF1: %g \\n\" % f1)\n\tutil.echo_to_file(reportLocation, \"\\n\")\n\t\n\treturn precision, recall, f1\n\n\n# Deploy the classifier, defined by its logit function (_logit_func), to an image stack (_image).\n# Which channel to apply to is defined by _channel.\n# _set defines whether we are applying to train, validate or test set, and stores results inside _file.\n# _label then defines the ground truth stack (may not exist for new, unlabelled data).\ndef deploy_to_channel(_logit_func, _image, _channel, _set, _file, _label=None):\n\tprint(_channel + \" \" + _set + \" prediction.\")\n\t\n\t_file.create_dataset('image', data=_image)\n\t\n\tlogits = apply_classifier(_logit_func, _image)\n\t# Now save output and truth values sed.\n\tgroup = _file.create_group(_channel)\n\tgroup.create_dataset('zeros', data=np.squeeze(logits[:, :, :, 0]))\n\tgroup.create_dataset('ones', data=np.squeeze(logits[:, :, :, 1]))\n\t\n\tif _label is not None:\n\t\ttrimmed_labels = _label[:, border:finalSize[0]+border, border:finalSize[1]+border, :]\n\t\tgroup.create_dataset('truth', data=np.squeeze(trimmed_labels))\n\t\t# Create P-R metrics using softmax layer.\n\t\tprediction = (logits[:, :, :, 1] > logits[:, :, :, 0]).astype(np.int8)\n\t\tprecision, recall, f1 = evaluate_f1(prediction, trimmed_labels, _channel + \"-\" + _set)\n\t\tgroup.attrs['Precision'] = precision\n\t\tgroup.attrs['Recall'] = recall\n\t\tgroup.attrs['F1'] = f1\n\n\n# Script for testing speed of application of _func to _image.\ndef application_speed_test(_func, _image):\n\t_application_times = np.zeros((_image.size[0], 1))\n\tfor i in range(_image.size[0]):\n\t\t_single_im = np.expand_dims(trainImage[i, :, :].astype(np.float32), axis=0)\n\t\tstartTime = timeit.default_timer()\n\t\t_ = sess.run(_func, feed_dict={x: _single_im, keep_prob: 1.0}) \n\t\telapsed = timeit.default_timer() - startTime\n\t\t_application_times[i] = elapsed\n\t\n\tav = np.sum(_application_times) / _image.size[0]\n\tutil.echo_to_file(reportLocation, \"\\nAverage application time per frame: %g s \\n\" % av)\n\n\n# Now lets go and deploy the algorithm to the datasets.\nif deployTrain | deployValidation | deployTest | deployUnlabelled:\n\t\n\t# Load the correct classifier file.\n\t# If we have been training, re-load the optimally trained classifier.\n\t# Else, load the classifier defined by the input.\n\tif training:\n\t\tsaver.restore(sess, fileOutputName + \"/CNN.ckpt\")\n\t\tload_path = fileOutputName\n\telse:\n\t\tsaver.restore(sess, load_path + \"/CNN.ckpt\")\n\t\n\tutil.echo_to_file(reportLocation, \"\\nTesting network parameters saved at: \" + load_path + \"\\n\")\n\t\n\tif deployTrain:\n\t\tutil.echo_to_file(reportLocation, \"Beginning dense application to training set.\")\n\t\t\n\t\t# Create h5 file for saving output.\n\t\th5f = h5py.File(fileOutputName + '/train_results.h5', 'w')\n\t\th5f.attrs['Creation_Date'] = time.strftime(\"%Y_%m_%d\") + \"_\" + time.strftime(\"%H_%M_%S\")\n\t\th5f.attrs['Data_Set'] = \"Training\"\n\t\th5f.attrs['Network_Location'] = load_path\n\t\th5f.attrs['Network'] = \"VESICLE-CNN-2\"\n\t\t\n\t\tdeploy_to_channel(y_syn_logit, trainImage, 'syn', 'train', h5f, trainLabels['SYN']) # Syn.\n\t\t\n\t\th5f.close()\n\t\n\tif deployValidation:\n\t\tutil.echo_to_file(reportLocation, \"Beginning dense validation to training set.\")\n\t\t\n\t\t# Create h5 file for saving output.\n\t\th5f = h5py.File(fileOutputName + '/validation_results.h5', 'w')\n\t\th5f.attrs['Creation_Date'] = time.strftime(\"%Y_%m_%d\") + \"_\" + time.strftime(\"%H_%M_%S\")\n\t\th5f.attrs['Data_Set'] = \"Validation\"\n\t\th5f.attrs['Network_Location'] = load_path\n\t\th5f.attrs['Network'] = \"VESICLE-CNN-2\"\n\t\t\n\t\tdeploy_to_channel(y_syn_logit, validateImage, 'syn', 'validation', h5f, validateLabels['SYN']) # Syn.\n\t\t\n\t\th5f.close()\n\t\n\tif deployTest:\n\t\tutil.echo_to_file(reportLocation, \"Beginning dense application to test set.\")\n\t\t\n\t\t# Create h5 file for saving output.\n\t\th5f = h5py.File(fileOutputName + '/test_results.h5', 'w')\n\t\th5f.attrs['Creation_Date'] = time.strftime(\"%Y_%m_%d\") + \"_\" + time.strftime(\"%H_%M_%S\")\n\t\th5f.attrs['Data_Set'] = \"Test\"\n\t\th5f.attrs['Network_Location'] = load_path\n\t\th5f.attrs['Network'] = \"VESICLE-CNN-2\"\n\t\t\n\t\tdeploy_to_channel(y_syn_logit, testImage, 'syn', 'test', h5f, testLabels['SYN']) # Syn.\n\t\t\n\t\th5f.close()\n\n\tif deployUnlabelled:\n\t\tutil.echo_to_file(reportLocation, \"Beginning dense application to unlabelled set.\")\n\t\t\n\t\t# We need to load this one.\n\t\tunlabelledLoc = dataLocations[0]\n\t\tunlabelledImage, _ = util.load_data(unlabelledLoc, imgLocation)\n\t\t\n\t\t# Create h5 file for saving output.\n\t\th5f = h5py.File(fileOutputName + '/unlabelled_results.h5', 'w')\n\t\th5f.create_dataset('image', data=testImage)\n\t\th5f.attrs['Creation_Date'] = time.strftime(\"%Y_%m_%d\") + \"_\" + time.strftime(\"%H_%M_%S\")\n\t\th5f.attrs['Data_Set'] = \"Unlabelled\"\n\t\th5f.attrs['Network_Location'] = load_path\n\t\th5f.attrs['Network'] = \"VESICLE-CNN-2\"\n\t\t\n\t\tdeploy_to_channel(y_syn_logit, testImage, 'syn', 'unlabelled', h5f) # Syn.\n\t\t\n\t\th5f.close()\n\n# Close the TF session to release the resources.\nsess.close()\ndel sess\n\n# Now run the MATLAB accuracy evaluation script.\n# This makes a call to matlab and passes in the arguements to the evaluation script.\n# This is only done if it has also been deployed to validation and test datasets.\nif deployValidation & deployTest:\n\t# Make the MATLAB call.\n\t# GPU resources dont seem to be properly released so this call `blocks' the GPU memory... need to fix this somehow.\n\tos.system('matlab -r \"addpath(genpath(\\'../evaluation\\')); wrap_synapse_pr(\\'./' + fileOutputName +'\\' ,\\'syn\\'); wrap_voxel_pr(\\'./' + fileOutputName +'\\' ,\\'syn\\'); exit\"')\n\n\n## Finish up.\nutil.echo_to_file(reportLocation, \"-- End of VESICLE-CNN-2 report. --\")\n"
] |
[
[
"numpy.nanmax",
"numpy.squeeze",
"tensorflow.cast",
"tensorflow.train.AdamOptimizer",
"tensorflow.get_default_graph",
"tensorflow.summary.scalar",
"numpy.where",
"numpy.reshape",
"tensorflow.ConfigProto",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"numpy.sum",
"tensorflow.nn.softmax",
"tensorflow.reshape",
"numpy.average",
"tensorflow.nn.weighted_cross_entropy_with_logits"
]
] |
sedgewickmm18/mmfunctions
|
[
"1969eb198058ec4d4339f3a953f33d4d09675de8"
] |
[
"mmfunctions/anomaly.py"
] |
[
"# *****************************************************************************\n# © Copyright IBM Corp. 2018-2021. All Rights Reserved.\n#\n# This program and the accompanying materials\n# are made available under the terms of the Apache V2.0 license\n# which accompanies this distribution, and is available at\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# *****************************************************************************\n\n\"\"\"\nThe Built In Functions module contains preinstalled functions\n\"\"\"\n\nimport itertools as it\nimport datetime as dt\nimport importlib\nimport logging\nimport time\n\n# for gradient boosting\nimport lightgbm\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom pyod.models.cblof import CBLOF\nimport ruptures as rpt\n\n# for Spectral Analysis\nfrom scipy import signal, fftpack\n\nimport skimage as ski\nfrom skimage import util as skiutil # for nifty windowing\n\n# for KMeans\nfrom sklearn import ensemble\nfrom sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn.covariance import MinCovDet\nfrom sklearn.neighbors import (KernelDensity, LocalOutlierFactor)\nfrom sklearn.pipeline import Pipeline, TransformerMixin\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import (StandardScaler, RobustScaler, MinMaxScaler,\n minmax_scale, PolynomialFeatures)\nfrom sklearn.utils import check_array\n\n# for Matrix Profile\nimport iotfunctions\nif iotfunctions.__version__ != '8.2.1':\n import stumpy\n\nimport statsmodels.api as sm\nfrom statsmodels.nonparametric.kernel_density import KDEMultivariate\nfrom statsmodels.tsa.arima.model import ARIMA\n# EXCLUDED until we upgrade to statsmodels 0.12\n#from statsmodels.tsa.forecasting.stl import STLForecast\n\nfrom iotfunctions.base import (BaseTransformer, BaseRegressor, BaseEstimatorFunction, BaseSimpleAggregator)\nfrom iotfunctions.bif import (AlertHighValue)\nfrom iotfunctions.ui import (UISingle, UIMulti, UIMultiItem, UIFunctionOutSingle, UISingleItem, UIFunctionOutMulti)\n\n# VAE\nimport torch\nimport torch.autograd\nimport torch.nn as nn\n\nlogger = logging.getLogger(__name__)\nlogger.info('IOT functions version ' + iotfunctions.__version__)\n\nPACKAGE_URL = 'git+https://github.com/sedgewickmm18/mmfunctions.git'\n_IS_PREINSTALLED = False\n\nError_SmallWindowsize = 0.0001\nError_Generic = 0.0002\n\nFrequencySplit = 0.3\nDefaultWindowSize = 12\nSmallEnergy = 1e-20\n\nKMeans_normalizer = 1\nSpectral_normalizer = 100 / 2.8\nFFT_normalizer = 1\nSaliency_normalizer = 1\nGeneralized_normalizer = 1 / 300\n\n\n# from\n# https://stackoverflow.com/questions/44790072/sliding-window-on-time-series-data\ndef view_as_windows1(temperature, length, step):\n logger.info('VIEW ' + str(temperature.shape) + ' ' + str(length) + ' ' + str(step))\n\n def moving_window(x, length, _step=1):\n if type(step) != 'int' or _step < 1:\n logger.info('MOVE ' + str(_step))\n _step = 1\n streams = it.tee(x, length)\n return zip(*[it.islice(stream, i, None, _step) for stream, i in zip(streams, it.count(step=1))])\n\n x_ = list(moving_window(temperature, length, step))\n return np.asarray(x_)\n\n\ndef view_as_windows(temperature, length, step):\n return skiutil.view_as_windows(temperature, window_shape=(length,), step=step)\n\n\ndef custom_resampler(array_like):\n # initialize\n if 'gap' not in dir():\n gap = 0\n\n if array_like.values.size > 0:\n gap = 0\n return 0\n else:\n gap += 1\n return gap\n\n\ndef min_delta(df):\n # minimal time delta for merging\n\n if df is None:\n return pd.Timedelta('5 seconds'), df\n elif len(df.index.names) > 1:\n df2 = df.reset_index(level=df.index.names[1:], drop=True)\n else:\n df2 = df\n\n try:\n mindelta = df2.index.to_series().diff().min()\n except Exception as e:\n logger.debug('Min Delta error: ' + str(e))\n mindelta = pd.Timedelta('5 seconds')\n\n if mindelta == dt.timedelta(seconds=0) or pd.isnull(mindelta):\n mindelta = pd.Timedelta('5 seconds')\n\n return mindelta, df2\n\n\ndef set_window_size_and_overlap(windowsize, trim_value=2 * DefaultWindowSize):\n # make sure it exists\n if windowsize is None:\n windowsize = DefaultWindowSize\n\n # make sure it is positive and not too large\n trimmed_ws = np.minimum(np.maximum(windowsize, 1), trim_value)\n\n # overlap\n if trimmed_ws == 1:\n ws_overlap = 0\n else:\n # larger overlap - half the window\n ws_overlap = trimmed_ws // 2\n\n return trimmed_ws, ws_overlap\n\n\ndef dampen_anomaly_score(array, dampening):\n if dampening is None:\n dampening = 0.9 # gradient dampening\n\n if dampening >= 1:\n return array\n\n if dampening < 0.01:\n return array\n\n if array.size <= 1:\n return array\n\n gradient = np.gradient(array)\n\n # dampened\n grad_damp = np.float_power(abs(gradient), dampening) * np.sign(gradient)\n\n # reconstruct (dampened) anomaly score by discrete integration\n integral = []\n x = array[0]\n for x_el in np.nditer(grad_damp):\n x = x + x_el\n integral.append(x)\n\n # shift array slightly to the right to position anomaly score\n array_damp = np.roll(np.asarray(integral), 1)\n array_damp[0] = array_damp[1]\n\n # normalize\n return array_damp / dampening / 2\n\n\n# Saliency helper functions\n# copied from https://github.com/y-bar/ml-based-anomaly-detection\n# remove the boring part from an image resp. time series\ndef series_filter(values, kernel_size=3):\n \"\"\"\n Filter a time series. Practically, calculated mean value inside kernel size.\n As math formula, see https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html.\n :param values:\n :param kernel_size:\n :return: The list of filtered average\n \"\"\"\n filter_values = np.cumsum(values, dtype=float)\n logger.info('SERIES_FILTER: ' + str(values.shape) + ',' + str(filter_values.shape) + ',' + str(kernel_size))\n\n filter_values[kernel_size:] = filter_values[kernel_size:] - filter_values[:-kernel_size]\n filter_values[kernel_size:] = filter_values[kernel_size:] / kernel_size\n\n for i in range(1, kernel_size):\n filter_values[i] /= i + 1\n\n return filter_values\n\n\n# Saliency class\n# see https://www.inf.uni-hamburg.de/en/inst/ab/cv/research/research1-visual-attention.html\nclass Saliency(object):\n def __init__(self, amp_window_size, series_window_size, score_window_size):\n self.amp_window_size = amp_window_size\n self.series_window_size = series_window_size\n self.score_window_size = score_window_size\n\n def transform_saliency_map(self, values):\n \"\"\"\n Transform a time-series into spectral residual, which is method in computer vision.\n For example, See https://docs.opencv.org/master/d8/d65/group__saliency.html\n :param values: a list or numpy array of float values.\n :return: silency map and spectral residual\n \"\"\"\n\n freq = np.fft.fft(values)\n mag = np.sqrt(freq.real ** 2 + freq.imag ** 2)\n\n # remove the boring part of a timeseries\n spectral_residual = np.exp(np.log(mag) - series_filter(np.log(mag), self.amp_window_size))\n\n freq.real = freq.real * spectral_residual / mag\n freq.imag = freq.imag * spectral_residual / mag\n\n # and apply inverse fourier transform\n saliency_map = np.fft.ifft(freq)\n return saliency_map\n\n def transform_spectral_residual(self, values):\n saliency_map = self.transform_saliency_map(values)\n spectral_residual = np.sqrt(saliency_map.real ** 2 + saliency_map.imag ** 2)\n return spectral_residual\n\n\ndef merge_score(dfEntity, dfEntityOrig, column_name, score, mindelta):\n \"\"\"\n Fit interpolated score to original entity slice of the full dataframe\n \"\"\"\n\n # equip score with time values, make sure it's positive\n score[score < 0] = 0\n dfEntity[column_name] = score\n\n # merge\n dfEntityOrig = pd.merge_asof(dfEntityOrig, dfEntity[column_name], left_index=True, right_index=True,\n direction='nearest', tolerance=mindelta)\n\n if column_name + '_y' in dfEntityOrig:\n merged_score = dfEntityOrig[column_name + '_y'].to_numpy()\n else:\n merged_score = dfEntityOrig[column_name].to_numpy()\n\n return merged_score\n\n\n#######################################################################################\n# Scalers\n#######################################################################################\n\nclass Standard_Scaler(BaseEstimatorFunction):\n \"\"\"\n Learns and applies standard scaling\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n\n def set_estimators(self):\n self.estimators['standard_scaler'] = (StandardScaler, self.params)\n logger.info('Standard Scaler initialized')\n\n def __init__(self, features=None, targets=None, predictions=None):\n super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)\n\n # do not run score and call transform instead of predict\n self.is_scaler = True\n self.experiments_per_execution = 1\n self.normalize = True # support for optional scaling in subclasses\n self.prediction = self.predictions[0] # support for subclasses with univariate focus\n\n self.params = {}\n self.whoami = 'Standard_Scaler'\n\n # used by all the anomaly scorers based on it\n def prepare_data(self, dfEntity):\n\n logger.debug(self.whoami + ': prepare Data for ' + self.prediction + ' column')\n\n # operate on simple timestamp index\n # needed for aggregated data with 3 or more indices\n if len(dfEntity.index.names) > 1:\n index_names = dfEntity.index.names\n dfe = dfEntity.reset_index(index_names[1:])\n else:\n dfe = dfEntity\n\n # interpolate gaps - data imputation\n try:\n dfe = dfe.interpolate(method=\"time\")\n except Exception as e:\n logger.error('Prepare data error: ' + str(e))\n\n # one dimensional time series - named temperature for catchyness\n temperature = dfe[self.prediction].fillna(0).to_numpy(dtype=np.float64)\n\n return dfe, temperature\n\n # dummy function for scaler, can be replaced with anomaly functions\n def kexecute(self, entity, df_copy):\n return df_copy\n\n def execute(self, df):\n\n df_copy = df.copy()\n entities = np.unique(df_copy.index.levels[0])\n logger.debug(str(entities))\n\n missing_cols = [x for x in self.predictions if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n for entity in entities:\n\n normalize_entity = self.normalize\n\n try:\n check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)\n except Exception as e:\n normalize_entity = False\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n\n # support for optional scaling in subclasses\n if normalize_entity:\n dfe = super()._execute(df_copy.loc[[entity]], entity)\n df_copy.loc[entity, self.predictions] = dfe[self.predictions]\n else:\n self.prediction = self.features[0]\n\n df_copy = self.kexecute(entity, df_copy)\n self.prediction = self.predictions[0]\n\n logger.info('Standard_Scaler: Found columns ' + str(df_copy.columns))\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass Robust_Scaler(BaseEstimatorFunction):\n \"\"\"\n Learns and applies robust scaling, scaling after outlier removal\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n\n def set_estimators(self):\n self.estimators['robust_scaler'] = (RobustScaler, self.params)\n logger.info('Robust Scaler initialized')\n\n def __init__(self, features=None, targets=None, predictions=None):\n super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)\n\n # do not run score and call transform instead of predict\n self.is_scaler = True\n self.experiments_per_execution = 1\n\n self.params = {}\n\n def execute(self, df):\n\n df_copy = df.copy()\n entities = np.unique(df_copy.index.levels[0])\n logger.debug(str(entities))\n\n missing_cols = [x for x in self.predictions if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n for entity in entities:\n # per entity - copy for later inplace operations\n try:\n check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n continue\n\n dfe = super()._execute(df_copy.loc[[entity]], entity)\n df_copy.loc[entity, self.predictions] = dfe[self.predictions]\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass MinMax_Scaler(BaseEstimatorFunction):\n \"\"\"\n Learns and applies minmax scaling\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n\n def set_estimators(self):\n self.estimators['minmax_scaler'] = (MinMaxScaler, self.params)\n logger.info('MinMax Scaler initialized')\n\n def __init__(self, features=None, targets=None, predictions=None):\n super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)\n\n # do not run score and call transform instead of predict\n self.is_scaler = True\n self.experiments_per_execution = 1\n\n self.params = {}\n\n def execute(self, df):\n\n df_copy = df.copy()\n entities = np.unique(df_copy.index.levels[0])\n logger.debug(str(entities))\n\n missing_cols = [x for x in self.predictions if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n for entity in entities:\n try:\n check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n continue\n\n dfe = super()._execute(df_copy.loc[[entity]], entity)\n df_copy.loc[entity, self.predictions] = dfe[self.predictions]\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\n#######################################################################################\n# Anomaly Scorers\n#######################################################################################\n\nclass AnomalyScorer(BaseTransformer):\n \"\"\"\n Superclass of all unsupervised anomaly detection functions.\n \"\"\"\n def __init__(self, input_item, windowsize, output_items):\n super().__init__()\n logger.debug(input_item)\n self.input_item = input_item\n\n # use 12 by default\n self.windowsize, self.windowoverlap = set_window_size_and_overlap(windowsize)\n\n # assume 1 per sec for now\n self.frame_rate = 1\n\n # step\n self.step = self.windowsize - self.windowoverlap\n\n self.output_items = output_items\n\n self.normalize = False\n\n self.whoami = 'Anomaly'\n\n def get_model_name(self, prefix='model', suffix=None):\n\n name = []\n if prefix is not None:\n name.append(prefix)\n\n name.extend([self._entity_type.name, self.whoami])\n name.append(self.output_items[0])\n if suffix is not None:\n name.append(suffix)\n name = '.'.join(name)\n\n return name\n\n # make sure data is evenly spaced\n def prepare_data(self, dfEntity):\n\n logger.debug(self.whoami + ': prepare Data')\n\n # operate on simple timestamp index\n if len(dfEntity.index.names) > 1:\n index_names = dfEntity.index.names\n dfe = dfEntity.reset_index(index_names[1:])\n else:\n dfe = dfEntity\n\n # interpolate gaps - data imputation\n try:\n dfe = dfe.dropna(subset=[self.input_item]).interpolate(method=\"time\")\n except Exception as e:\n logger.error('Prepare data error: ' + str(e))\n\n # one dimensional time series - named temperature for catchyness\n temperature = dfe[self.input_item].fillna(0).to_numpy(dtype=np.float64)\n\n return dfe, temperature\n\n def execute(self, df):\n\n logger.debug('Execute ' + self.whoami)\n df_copy = df # no copy\n\n # check data type\n if not pd.api.types.is_numeric_dtype(df_copy[self.input_item].dtype):\n logger.error('Anomaly scoring on non-numeric feature:' + str(self.input_item))\n return df_copy\n\n # set output columns to zero\n for output_item in self.output_items:\n df_copy[output_item] = 0\n\n # delegate to _calc\n logger.debug('Execute ' + self.whoami + ' enter per entity execution')\n\n # group over entities\n group_base = [pd.Grouper(axis=0, level=0)]\n\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n logger.debug('Scoring done')\n return df_copy\n\n def _calc(self, df):\n\n entity = df.index.levels[0][0]\n\n # get rid of entity id as part of the index\n df = df.droplevel(0)\n\n # Get new data frame with sorted index\n dfe_orig = df.sort_index()\n\n # remove all rows with only null entries\n dfe = dfe_orig.dropna(how='all')\n\n # minimal time delta for merging\n mindelta, dfe_orig = min_delta(dfe_orig)\n\n logger.debug('Timedelta:' + str(mindelta) + ' Index: ' + str(dfe_orig.index))\n\n # one dimensional time series - named temperature for catchyness\n # interpolate gaps - data imputation by default\n # for missing data detection we look at the timestamp gradient instead\n dfe, temperature = self.prepare_data(dfe)\n\n logger.debug(\n self.whoami + ', Entity: ' + str(entity) + ', Input: ' + str(self.input_item) + ', Windowsize: ' + str(\n self.windowsize) + ', Output: ' + str(self.output_items) + ', Overlap: ' + str(\n self.windowoverlap) + ', Inputsize: ' + str(temperature.size))\n\n if temperature.size <= self.windowsize:\n logger.debug(str(temperature.size) + ' <= ' + str(self.windowsize))\n for output_item in self.output_items:\n dfe[output_item] = Error_SmallWindowsize\n else:\n logger.debug(str(temperature.size) + str(self.windowsize))\n\n for output_item in self.output_items:\n dfe[output_item] = Error_Generic\n\n temperature = self.scale(temperature, entity)\n\n scores = self.score(temperature)\n\n # length of time_series_temperature, signal_energy and ets_zscore is smaller than half the original\n # extend it to cover the full original length\n logger.debug('->')\n try:\n for i,output_item in enumerate(self.output_items):\n\n # check for fast path, no interpolation required\n diff = temperature.size - scores[i].size\n\n # slow path - interpolate result score to stretch it to the size of the input data\n if diff > 0:\n dfe[output_item] = 0.0006\n time_series_temperature = np.linspace(self.windowsize // 2, temperature.size - self.windowsize // 2 + 1,\n temperature.size - diff)\n linear_interpolate = sp.interpolate.interp1d(time_series_temperature, scores[i], kind='linear',\n fill_value='extrapolate')\n\n zScoreII = merge_score(dfe, dfe_orig, output_item,\n abs(linear_interpolate(np.arange(0, temperature.size, 1))), mindelta)\n # fast path - either cut off or just copy\n elif diff < 0:\n zScoreII = scores[i][0:temperature.size]\n else:\n zScoreII = scores[i]\n\n df[output_item] = zScoreII\n\n except Exception as e:\n logger.error(self.whoami + ' score integration failed with ' + str(e))\n\n logger.debug('--->')\n\n return df\n\n def score(self, temperature):\n\n #scores = np.zeros((len(self.output_items), ) + temperature.shape)\n scores = []\n for output_item in self.output_items:\n scores.append(np.zeros(temperature.shape))\n\n try:\n # super simple 1-dimensional z-score\n ets_zscore = abs(sp.stats.zscore(temperature))\n\n scores[0] = ets_zscore\n\n # 2nd argument to return the modified input argument (for no data)\n if len(self.output_items) > 1:\n scores[1] = temperature\n\n except Exception as e:\n logger.error(self.whoami + ' failed with ' + str(e))\n\n return scores\n\n\n def scale(self, temperature, entity):\n\n normalize_entity = self.normalize\n if not normalize_entity:\n return temperature\n\n temp = temperature.reshape(-1, 1)\n logger.info(self.whoami + ' scaling ' + str(temperature.shape))\n try:\n check_array(temp, allow_nd=True)\n except Exception as e:\n logger.error('Found Nan or infinite value in input data, error: ' + str(e))\n return temperature\n\n db = self._entity_type.db\n\n scaler_model = None\n # per entity - copy for later inplace operations\n model_name = self.get_model_name(suffix=entity)\n try:\n scaler_model = db.model_store.retrieve_model(model_name)\n logger.info('load model %s' % str(scaler_model))\n except Exception as e:\n logger.error('Model retrieval failed with ' + str(e))\n\n # failed to load a model, so train it\n if scaler_model is None:\n # all variables should be continuous\n scaler_model = StandardScaler().fit(temp)\n logger.debug('Created Scaler ' + str(scaler_model))\n\n try:\n db.model_store.store_model(model_name, scaler_model)\n except Exception as e:\n logger.error('Model store failed with ' + str(e))\n\n if scaler_model is not None:\n temp = scaler_model.transform(temp)\n return temp.reshape(temperature.shape)\n\n return temperature\n\n\n#####\n# experimental function to interpolate over larger gaps\n####\nclass Interpolator(AnomalyScorer):\n \"\"\"\n Interpolates NaN and data to be interpreted as NaN (for example 0 as invalid sensor reading)\n The window size is typically set large enough to allow for \"bridging\" gaps\n Missing indicates sensor readings to be interpreted as invalid.\n \"\"\"\n\n def __init__(self, input_item, windowsize, missing, output_item):\n super().__init__(input_item, windowsize, [output_item])\n logger.debug(input_item)\n\n self.missing = missing\n\n self.whoami = 'Interpolator'\n\n def prepare_data(self, dfEntity):\n\n logger.debug(self.whoami + ': prepare Data')\n\n # operate on simple timestamp index\n if len(dfEntity.index.names) > 1:\n index_names = dfEntity.index.names\n dfe = dfEntity.reset_index(index_names[1:])\n else:\n dfe = dfEntity\n\n # remove Nan\n dfe = dfe[dfe[self.input_item].notna()]\n\n # remove self.missing\n dfe = dfe[dfe[self.input_item] != self.missing]\n\n # interpolate gaps - data imputation\n try:\n dfe = dfe.interpolate(method=\"time\")\n except Exception as e:\n logger.error('Prepare data error: ' + str(e))\n\n # one dimensional time series - named temperature for catchyness\n # replace NaN with self.missing\n temperature = dfe[self.input_item].fillna(0).to_numpy(dtype=np.float64)\n\n return dfe, temperature\n\n @classmethod\n def build_ui(cls):\n\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to interpolate'))\n\n inputs.append(\n UISingle(name='windowsize', datatype=int, description='Minimal size of the window for interpolating data.'))\n inputs.append(UISingle(name='missing', datatype=int, description='Data to be interpreted as not-a-number.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='Interpolated data'))\n return (inputs, outputs)\n\n\nclass NoDataAnomalyScoreExt(AnomalyScorer):\n \"\"\"\n An unsupervised anomaly detection function.\n Uses z-score AnomalyScorer to find gaps in data.\n The function moves a sliding window across the data signal and applies the anomaly model to each window.\n The window size is typically set to 12 data points.\n \"\"\"\n def __init__(self, input_item, windowsize, output_item):\n super().__init__(input_item, windowsize, [output_item])\n\n self.whoami = 'NoDataExt'\n self.normalizer = 1\n\n logger.debug('NoDataExt')\n\n def prepare_data(self, dfEntity):\n\n logger.debug(self.whoami + ': prepare Data')\n\n # operate on simple timestamp index\n if len(dfEntity.index.names) > 1:\n index_names = dfEntity.index.names\n dfe = dfEntity.reset_index(index_names[1:])\n else:\n dfe = dfEntity\n\n # count the timedelta in seconds between two events\n timeSeq = (dfe.index.values - dfe.index[0].to_datetime64()) / np.timedelta64(1, 's')\n\n #dfe = dfEntity.copy()\n\n # one dimensional time series - named temperature for catchyness\n # we look at the gradient of the time series timestamps for anomaly detection\n # might throw an exception - we catch it in the super class !!\n try:\n temperature = np.gradient(timeSeq)\n dfe[[self.input_item]] = temperature\n except Exception as pe:\n logger.info(\"NoData Gradient failed with \" + str(pe))\n dfe[[self.input_item]] = 0\n temperature = dfe[[self.input_item]].values\n temperature[0] = 10 ** 10\n\n return dfe, temperature\n\n @classmethod\n def build_ui(cls):\n\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='No data anomaly score'))\n return inputs, outputs\n\n\nclass ChangePointDetector(AnomalyScorer):\n '''\n An unsupervised anomaly detection function.\n Applies a spectral analysis clustering techniqueto extract features from time series data and to create z scores.\n Moves a sliding window across the data signal and applies the anomalymodelto each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n '''\n def __init__(self, input_item, windowsize, chg_pts):\n super().__init__(input_item, windowsize, [chg_pts])\n\n logger.debug(input_item)\n\n self.whoami = 'ChangePointDetector'\n\n def score(self, temperature):\n\n scores = []\n\n sc = np.zeros(temperature.shape)\n\n try:\n algo = rpt.BottomUp(model=\"l2\", jump=2).fit(temperature)\n chg_pts = algo.predict(n_bkps=15)\n\n for j in chg_pts:\n x = np.arange(0, temperature.shape[0], 1)\n Gaussian = sp.stats.norm(j-1, temperature.shape[0]/20) # high precision\n y = Gaussian.pdf(x) * temperature.shape[0]/8 # max is ~1\n\n sc += y\n\n except Exception as e:\n logger.error(self.whoami + ' failed with ' + str(e))\n\n scores.append(sc)\n return scores\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='chg_pts', datatype=float, description='Change points'))\n return inputs, outputs\n\n\nENSEMBLE = '_ensemble_'\nSPECTRALEXT = 'SpectralAnomalyScoreExt'\n\nclass EnsembleAnomalyScore(BaseTransformer):\n '''\n Call a set of anomaly detectors and return an joint vote along with the individual results\n '''\n def __init__(self, input_item, windowsize, scorers, thresholds, output_item):\n super().__init__()\n\n self.input_item = input_item\n self.windowsize = windowsize\n self.output_item = output_item\n\n logger.debug(input_item)\n\n self.whoami = 'EnsembleAnomalyScore'\n\n self.list_of_scorers = scorers.split(',')\n self.thresholds = list(map(int, thresholds.split(',')))\n\n self.klasses = []\n self.instances = []\n self.output_items = []\n\n module = importlib.import_module('mmfunctions.anomaly')\n\n for m in self.list_of_scorers:\n klass = getattr(module, m)\n self.klasses.append(klass)\n print(klass.__name__)\n if klass.__name__ == SPECTRALEXT:\n inst = klass(input_item, windowsize, output_item + ENSEMBLE + klass.__name__,\n output_item + ENSEMBLE + klass.__name__ + '_inv')\n else:\n inst = klass(input_item, windowsize, output_item + ENSEMBLE + klass.__name__)\n self.output_items.append(output_item + ENSEMBLE + klass.__name__)\n self.instances.append(inst)\n\n def execute(self, df):\n logger.debug('Execute ' + self.whoami)\n df_copy = df # no copy\n\n binned_indices_list = []\n for inst, output, threshold in zip(self.instances, self.output_items, self.thresholds):\n logger.info('Execute anomaly scorer ' + str(inst.__class__.__name__) + ' with threshold ' + str(threshold))\n tic = time.perf_counter_ns()\n df_copy = inst.execute(df_copy)\n toc = time.perf_counter_ns()\n logger.info('Executed anomaly scorer ' + str(inst.__class__.__name__) + ' in ' +\\\n str((toc-tic)//1000000) + ' milliseconds')\n\n arr = df_copy[output]\n\n # sort results into bins that depend on the thresholds\n # 0 - below 3/4 threshold, 1 - up to the threshold, 2 - crossed the threshold,\n # 3 - very high, 4 - extreme\n if inst.__class__.__name__ == SPECTRALEXT and isinstance(threshold, int):\n # hard coded threshold for inverted values\n threshold_ = 5\n\n bins = [threshold * 0.75, threshold, threshold * 1.5, threshold * 2]\n binned_indices_list.append(np.searchsorted(bins, arr, side='left'))\n\n if inst.__class__.__name__ == SPECTRALEXT:\n bins = [threshold_ * 0.75, threshold_, threshold_ * 1.5, threshold_ * 2]\n arr = df_copy[output + '_inv']\n binned_indices_list.append(np.searchsorted(bins, arr, side='left'))\n\n binned_indices = np.vstack(binned_indices_list).mean(axis=0)\n\n # should we explicitly drop the columns generated by the ensemble members\n #df[self.output_item] = binned_indices\n df_copy[self.output_item] = binned_indices\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutSingle(name='output_item', datatype=float, description='Spectral anomaly score (z-score)'))\n return inputs, outputs\n\n\n\nclass SpectralAnomalyScore(AnomalyScorer):\n '''\n An unsupervised anomaly detection function.\n Applies a spectral analysis clustering techniqueto extract features from time series data and to create z scores.\n Moves a sliding window across the data signal and applies the anomalymodelto each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n '''\n def __init__(self, input_item, windowsize, output_item):\n if isinstance(output_item, list):\n super().__init__(input_item, windowsize, output_item)\n else:\n super().__init__(input_item, windowsize, [output_item])\n\n logger.debug(input_item)\n\n self.whoami = 'SpectralAnomalyScore'\n\n def score(self, temperature):\n\n scores = []\n for output_item in self.output_items:\n scores.append(np.zeros(temperature.shape))\n\n try:\n # Fourier transform:\n # frequency, time, spectral density\n frequency_temperature, time_series_temperature, spectral_density_temperature = signal.spectrogram(\n temperature, fs=self.frame_rate, window='hanning', nperseg=self.windowsize,\n noverlap=self.windowoverlap, detrend='l', scaling='spectrum')\n\n # cut off freqencies too low to fit into the window\n frequency_temperatureb = (frequency_temperature > 2 / self.windowsize).astype(int)\n frequency_temperature = frequency_temperature * frequency_temperatureb\n frequency_temperature[frequency_temperature == 0] = 1 / self.windowsize\n\n signal_energy = np.dot(spectral_density_temperature.T, frequency_temperature)\n\n signal_energy[signal_energy < SmallEnergy] = SmallEnergy\n inv_signal_energy = np.divide(np.ones(signal_energy.size), signal_energy)\n\n ets_zscore = abs(sp.stats.zscore(signal_energy)) * Spectral_normalizer\n inv_zscore = abs(sp.stats.zscore(inv_signal_energy))\n\n scores[0] = ets_zscore\n if len(self.output_items) > 1:\n scores[1] = inv_zscore\n\n # 3rd argument to return the raw windowed signal energy\n if len(self.output_items) > 2:\n scores[2] = signal_energy\n\n # 4th argument to return the modified input argument (for no data)\n if len(self.output_items) > 3:\n scores[3] = temperature.copy()\n\n logger.debug(\n 'Spectral z-score max: ' + str(ets_zscore.max()) + ', Spectral inv z-score max: ' + str(\n inv_zscore.max()))\n\n except Exception as e:\n logger.error(self.whoami + ' failed with ' + str(e))\n\n return scores\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutSingle(name='output_item', datatype=float, description='Spectral anomaly score (z-score)'))\n return inputs, outputs\n\n\nclass SpectralAnomalyScoreExt(SpectralAnomalyScore):\n '''\n An unsupervised anomaly detection function.\n Applies a spectral analysis clustering techniqueto extract features from time series data and to create z scores.\n Moves a sliding window across the data signal and applies the anomalymodelto each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n '''\n def __init__(self, input_item, windowsize, output_item, inv_zscore, signal_energy=None):\n if signal_energy is None:\n super().__init__(input_item, windowsize, [output_item, inv_zscore])\n else:\n super().__init__(input_item, windowsize, [output_item, inv_zscore, signal_energy])\n\n logger.debug(input_item)\n\n self.whoami = 'SpectralAnomalyScoreExt'\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutSingle(name='output_item', datatype=float, description='Spectral anomaly score (z-score)'))\n outputs.append(UIFunctionOutSingle(name='inv_zscore', datatype=float,\n description='z-score of inverted signal energy - detects unusually low activity'))\n outputs.append(UIFunctionOutSingle(name='signal_enerty', datatype=float,\n description='signal energy'))\n return inputs, outputs\n\n\n\nclass KMeansAnomalyScore(AnomalyScorer):\n \"\"\"\n An unsupervised anomaly detection function.\n Applies a k-means analysis clustering technique to time series data.\n Moves a sliding window across the data signal and applies the anomaly model to each window.\n The window size is typically set to 12 data points.\n Try several anomaly models on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, output_item, expr=None):\n super().__init__(input_item, windowsize, [output_item])\n\n logger.debug(input_item)\n\n self.whoami = 'KMeans'\n\n\n def score(self, temperature):\n\n scores = []\n for output_item in self.output_items:\n scores.append(np.zeros(temperature.shape))\n\n try:\n # Chop into overlapping windows\n slices = view_as_windows(temperature, self.windowsize, self.step)\n\n if self.windowsize > 1:\n n_cluster = 40\n else:\n n_cluster = 20\n\n n_cluster = np.minimum(n_cluster, slices.shape[0] // 2)\n\n logger.debug(self.whoami + 'params, Clusters: ' + str(n_cluster) + ', Slices: ' + str(slices.shape))\n\n cblofwin = CBLOF(n_clusters=n_cluster, n_jobs=-1)\n try:\n cblofwin.fit(slices)\n except Exception as e:\n logger.info('KMeans failed with ' + str(e))\n self.trace_append('KMeans failed with' + str(e))\n return scores\n\n pred_score = cblofwin.decision_scores_.copy() * KMeans_normalizer\n\n scores[0] = pred_score\n\n logger.debug('KMeans score max: ' + str(pred_score.max()))\n\n except Exception as e:\n logger.error(self.whoami + ' failed with ' + str(e))\n\n return scores\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='Anomaly score (kmeans)'))\n return inputs, outputs\n\n\nclass GeneralizedAnomalyScore(AnomalyScorer):\n \"\"\"\n An unsupervised anomaly detection function.\n Applies the Minimum Covariance Determinant (FastMCD) technique to detect outliers.\n Moves a sliding window across the data signal and applies the anomaly model to each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, output_item):\n super().__init__(input_item, windowsize, [output_item])\n logger.debug(input_item)\n\n self.whoami = 'GAM'\n\n self.normalizer = Generalized_normalizer\n\n def feature_extract(self, temperature):\n\n logger.debug(self.whoami + ': feature extract')\n\n slices = view_as_windows(temperature, self.windowsize, self.step)\n\n return slices\n\n def score(self, temperature):\n\n scores = []\n for output_item in self.output_items:\n scores.append(np.zeros(temperature.shape))\n\n logger.debug(str(temperature.size) + \",\" + str(self.windowsize))\n\n temperature -= np.mean(temperature, axis=0)\n mcd = MinCovDet()\n\n # Chop into overlapping windows (default) or run through FFT first\n slices = self.feature_extract(temperature)\n\n try:\n mcd.fit(slices)\n pred_score = mcd.mahalanobis(slices).copy() * self.normalizer\n\n except ValueError as ve:\n\n pred_score = np.zeros(temperature.shape)\n logger.info(self.whoami + \", Input: \" + str(\n self.input_item) + \", WindowSize: \" + str(self.windowsize) + \", Output: \" + str(\n self.output_items[0]) + \", Step: \" + str(self.step) + \", InputSize: \" + str(\n slices.shape) + \" failed in the fitting step with \\\"\" + str(ve) + \"\\\" - scoring zero\")\n\n except Exception as e:\n\n pred_score = np.zeros(temperature.shape)\n logger.error(self.whoami + \", Input: \" + str(\n self.input_item) + \", WindowSize: \" + str(self.windowsize) + \", Output: \" + str(\n self.output_items[0]) + \", Step: \" + str(self.step) + \", InputSize: \" + str(\n slices.shape) + \" failed in the fitting step with \" + str(e))\n\n scores[0] = pred_score\n\n logger.debug(self.whoami + ' score max: ' + str(pred_score.max()))\n\n return scores\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\", ))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\"))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutSingle(name=\"output_item\", datatype=float, description=\"Anomaly score (GeneralizedAnomaly)\", ))\n return inputs, outputs\n\n\nclass NoDataAnomalyScore(GeneralizedAnomalyScore):\n \"\"\"\n An unsupervised anomaly detection function.\n Uses FastMCD to find gaps in data.\n The function moves a sliding window across the data signal and applies the anomaly model to each window.\n The window size is typically set to 12 data points.\n \"\"\"\n\n def __init__(self, input_item, windowsize, output_item):\n super().__init__(input_item, windowsize, output_item)\n\n self.whoami = 'NoData'\n self.normalizer = 1\n\n logger.debug('NoData')\n\n def prepare_data(self, dfEntity):\n\n logger.debug(self.whoami + ': prepare Data')\n\n # operate on simple timestamp index\n if len(dfEntity.index.names) > 1:\n index_names = dfEntity.index.names[1:]\n dfe = dfEntity.reset_index(index_names)\n else:\n dfe = dfEntity\n\n # count the timedelta in seconds between two events\n logger.debug('type of index[0] is ' + str(type(dfEntity.index[0])))\n\n try:\n timeSeq = (dfe.index.values - dfe.index[0].to_datetime64()) / np.timedelta64(1, 's')\n except Exception:\n try:\n time_to_numpy = np.array(dfe.index[0], dtype='datetime64')\n print('5. ', type(time_to_numpy), dfe.index[0][0])\n timeSeq = (time_to_numpy - dfe.index[0][0].to_datetime64()) / np.timedelta64(1, 's')\n except Exception:\n print('Nochens')\n timeSeq = 1.0\n\n #dfe = dfEntity.copy()\n\n # one dimensional time series - named temperature for catchyness\n # we look at the gradient of the time series timestamps for anomaly detection\n # might throw an exception - we catch it in the super class !!\n try:\n temperature = np.gradient(timeSeq)\n dfe[[self.input_item]] = temperature\n except Exception as pe:\n logger.info(\"NoData Gradient failed with \" + str(pe))\n dfe[[self.input_item]] = 0\n temperature = dfe[[self.input_item]].values\n temperature[0] = 10 ** 10\n\n return dfe, temperature\n\n @classmethod\n def build_ui(cls):\n\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='No data anomaly score'))\n return inputs, outputs\n\n\nclass FFTbasedGeneralizedAnomalyScore(GeneralizedAnomalyScore):\n \"\"\"\n An unsupervised and robust anomaly detection function.\n Extracts temporal features from time series data using Fast Fourier Transforms.\n Applies the GeneralizedAnomalyScore to the features to detect outliers.\n Moves a sliding window across the data signal and applies the anomaly models to each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, output_item):\n super().__init__(input_item, windowsize, output_item)\n\n self.whoami = 'FFT'\n self.normalizer = FFT_normalizer\n\n logger.debug('FFT')\n\n def feature_extract(self, temperature):\n logger.debug(self.whoami + ': feature extract')\n\n slices_ = view_as_windows(temperature, self.windowsize, self.step)\n\n slicelist = []\n for slice in slices_:\n slicelist.append(fftpack.rfft(slice))\n\n return np.stack(slicelist, axis=0)\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\", ))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\"))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name=\"output_item\", datatype=float,\n description=\"Anomaly score (FFTbasedGeneralizedAnomalyScore)\", ))\n return inputs, outputs\n\n\nif iotfunctions.__version__ != '8.2.1':\n class MatrixProfileAnomalyScore(AnomalyScorer):\n \"\"\"\n An unsupervised anomaly detection function.\n Applies matrix profile analysis on time series data.\n Moves a sliding window across the data signal to calculate the euclidean distance from one window to all others to build a distance profile.\n The window size is typically set to 12 data points.\n Try several anomaly models on your data and use the one that fits your data best.\n \"\"\"\n DATAPOINTS_AFTER_LAST_WINDOW = 1e-15\n INIT_SCORES = 1e-20\n ERROR_SCORES = 1e-16\n\n def __init__(self, input_item, window_size, output_item):\n super().__init__(input_item, window_size, [output_item])\n logger.debug(f'Input item: {input_item}')\n\n self.whoami = 'MatrixProfile'\n\n\n def score(self, temperature):\n\n scores = []\n for output_item in self.output_items:\n scores.append(np.zeros(temperature.shape))\n\n try: # calculate scores\n # replaced aamp with stump for stumpy 1.8.0 and above\n #matrix_profile = stumpy.aamp(temperature, m=self.windowsize)[:, 0]\n matrix_profile = stumpy.stump(temperature, m=self.windowsize, normalize=False)[:, 0]\n # fill in a small value for newer data points outside the last possible window\n fillers = np.array([self.DATAPOINTS_AFTER_LAST_WINDOW] * (self.windowsize - 1))\n matrix_profile = np.append(matrix_profile, fillers)\n except Exception as er:\n logger.warning(f' Error in calculating Matrix Profile Scores. {er}')\n matrix_profile = np.array([self.ERROR_SCORES] * temperature.shape[0])\n\n scores[0] = matrix_profile\n\n logger.debug('Matrix Profile score max: ' + str(matrix_profile.max()))\n\n return scores\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = [UISingleItem(name=\"input_item\", datatype=float, description=\"Time series data item to analyze\", ),\n UISingle(name=\"window_size\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\")]\n\n # define arguments that behave as function outputs\n outputs = [UIFunctionOutSingle(name=\"output_item\", datatype=float,\n description=\"Anomaly score (MatrixProfileAnomalyScore)\", )]\n return inputs, outputs\n\n\nclass SaliencybasedGeneralizedAnomalyScore(GeneralizedAnomalyScore):\n \"\"\"\n An unsupervised anomaly detection function.\n Based on salient region detection models,\n it uses fast fourier transform to reconstruct a signal using the salient features of a the signal.\n It applies GeneralizedAnomalyScore to the reconstructed signal.\n The function moves a sliding window across the data signal and applies its analysis to each window.\n The window size is typically set to 12 data points.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, output_item):\n super().__init__(input_item, windowsize, output_item)\n\n self.whoami = 'Saliency'\n self.saliency = Saliency(windowsize, 0, 0)\n self.normalizer = Saliency_normalizer\n\n logger.debug('Saliency')\n\n def feature_extract(self, temperature):\n logger.debug(self.whoami + ': feature extract')\n\n slices = view_as_windows(temperature, self.windowsize, self.step)\n\n return slices\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\"))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\", ))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name=\"output_item\", datatype=float,\n description=\"Anomaly score (SaliencybasedGeneralizedAnomalyScore)\", ))\n return (inputs, outputs)\n\n\n#######################################################################################\n# Anomaly detectors with scaling\n#######################################################################################\nclass KMeansAnomalyScoreV2(KMeansAnomalyScore):\n\n def __init__(self, input_item, windowsize, normalize, output_item, expr=None):\n super().__init__(input_item, windowsize, output_item)\n\n logger.debug(input_item)\n self.normalize = normalize\n\n self.whoami = 'KMeansV2'\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to analyze'))\n\n inputs.append(UISingle(name='windowsize', datatype=int,\n description='Size of each sliding window in data points. Typically set to 12.'))\n\n inputs.append(UISingle(name='normalize', datatype=bool, description='Flag for normalizing data.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='Anomaly score (kmeans)'))\n return (inputs, outputs)\n\n\nclass GeneralizedAnomalyScoreV2(GeneralizedAnomalyScore):\n \"\"\"\n An unsupervised anomaly detection function.\n Applies the Minimum Covariance Determinant (FastMCD) technique to detect outliers.\n Moves a sliding window across the data signal and applies the anomaly model to each window.\n The window size is typically set to 12 data points.\n The normalize switch allows to learn and apply a standard scaler prior to computing the anomaly score.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, normalize, output_item, expr=None):\n super().__init__(input_item, windowsize, output_item)\n\n logger.debug(input_item)\n # do not run score and call transform instead of predict\n\n self.normalize = normalize\n\n self.whoami = 'GAMV2'\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\", ))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\"))\n\n inputs.append(UISingle(name='normalize', datatype=bool, description='Flag for normalizing data.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutSingle(name=\"output_item\", datatype=float, description=\"Anomaly score (GeneralizedAnomaly)\", ))\n return inputs, outputs\n\n\nclass FFTbasedGeneralizedAnomalyScoreV2(GeneralizedAnomalyScoreV2):\n \"\"\"\n An unsupervised and robust anomaly detection function.\n Extracts temporal features from time series data using Fast Fourier Transforms.\n Applies the GeneralizedAnomalyScore to the features to detect outliers.\n Moves a sliding window across the data signal and applies the anomaly models to each window.\n The window size is typically set to 12 data points.\n The normalize switch allows to learn and apply a standard scaler prior to computing the anomaly score.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, normalize, output_item):\n super().__init__(input_item, windowsize, normalize, output_item)\n\n self.normalize = normalize\n\n self.whoami = 'FFTV2'\n self.normalizer = FFT_normalizer\n\n logger.debug('FFT')\n\n def feature_extract(self, temperature):\n logger.debug(self.whoami + ': feature extract')\n\n slices_ = view_as_windows(temperature, self.windowsize, self.step)\n\n slicelist = []\n for slice in slices_:\n slicelist.append(fftpack.rfft(slice))\n\n return np.stack(slicelist, axis=0)\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\", ))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\"))\n\n inputs.append(UISingle(name='normalize', datatype=bool, description='Flag for normalizing data.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name=\"output_item\", datatype=float,\n description=\"Anomaly score (FFTbasedGeneralizedAnomalyScore)\", ))\n return inputs, outputs\n\n\nclass SaliencybasedGeneralizedAnomalyScoreV2(SaliencybasedGeneralizedAnomalyScore):\n \"\"\"\n An unsupervised anomaly detection function.\n Based on salient region detection models,\n it uses fast fourier transform to reconstruct a signal using the salient features of a the signal.\n It applies GeneralizedAnomalyScore to the reconstructed signal.\n The function moves a sliding window across the data signal and applies its analysis to each window.\n The window size is typically set to 12 data points.\n The normalize switch allows to learn and apply a standard scaler prior to computing the anomaly score.\n Try several anomaly detectors on your data and use the one that fits your data best.\n \"\"\"\n\n def __init__(self, input_item, windowsize, normalize, output_item):\n super().__init__(input_item, windowsize, output_item)\n\n self.whoami = 'SaliencyV2'\n\n self.normalize = normalize\n\n logger.debug('SaliencyV2')\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\"))\n\n inputs.append(UISingle(name=\"windowsize\", datatype=int,\n description=\"Size of each sliding window in data points. Typically set to 12.\", ))\n\n inputs.append(UISingle(name='normalize', datatype=bool, description='Flag for normalizing data.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name=\"output_item\", datatype=float,\n description=\"Anomaly score (SaliencybasedGeneralizedAnomalyScore)\", ))\n return inputs, outputs\n\n\nKMeansAnomalyScorev2 = KMeansAnomalyScoreV2\nFFTbasedGeneralizedAnomalyScorev2 = FFTbasedGeneralizedAnomalyScoreV2\nSaliencybasedGeneralizedAnomalyScorev2 = SaliencybasedGeneralizedAnomalyScoreV2\nGeneralizedAnomalyScorev2 = GeneralizedAnomalyScoreV2\n\n\n#######################################################################################\n# Base class to handle models\n#######################################################################################\n\nclass SupervisedLearningTransformer(BaseTransformer):\n\n name = 'SupervisedLearningTransformer'\n\n \"\"\"\n Base class for anomaly scorers that can be trained with historic data in a notebook\n and automatically store a trained model in the tenant database\n Inferencing is run in the pipeline\n \"\"\"\n def __init__(self, features, targets):\n super().__init__()\n\n logging.debug(\"__init__\" + self.name)\n\n # do NOT automatically train if no model is found (subclasses)\n self.auto_train = False\n self.delete_model = False\n\n self.features = features\n self.targets = targets\n parms = []\n if features is not None:\n parms.extend(features)\n if targets is not None:\n parms.extend(targets)\n parms = '.'.join(parms)\n logging.debug(\"__init__ done with parameters: \" + parms)\n\n '''\n Generate unique model name from entity, optionally features and target for consistency checks\n '''\n def get_model_name(self, prefix='model', features=None, targets=None, suffix=None):\n\n name = []\n if prefix is not None:\n name.append(prefix)\n\n name.extend([self._entity_type.name, self.name])\n if features is not None:\n name.extend(features)\n if targets is not None:\n name.extend(targets)\n if suffix is not None:\n name.append(suffix)\n name = '.'.join(name)\n return name\n\n\n def load_model(self, suffix=None):\n model_name = self.get_model_name(targets=self.targets, suffix=suffix)\n my_model = None\n try:\n my_model = self._entity_type.db.model_store.retrieve_model(model_name)\n logger.info('load model %s' % str(my_model))\n except Exception as e:\n logger.error('Model retrieval failed with ' + str(e))\n pass\n\n # ditch old model\n version = 1\n if self.delete_model:\n if my_model is not None:\n if hasattr(my_model, 'version'):\n version = my_model.version + 1\n logger.debug('Deleting robust model ' + str(version-1) + ' for entity: ' + str(suffix))\n my_model = None\n\n return model_name, my_model, version\n\n\n def execute(self, df):\n logger.debug('Execute ' + self.whoami)\n df_copy = df # no copy\n\n # check data type\n #if df[self.input_item].dtype != np.float64:\n for feature in self.features:\n if not pd.api.types.is_numeric_dtype(df_copy[feature].dtype):\n logger.error('Regression on non-numeric feature:' + str(feature))\n return (df_copy)\n\n # delegate to _calc\n logger.debug('Execute ' + self.whoami + ' enter per entity execution')\n\n # group over entities\n group_base = [pd.Grouper(axis=0, level=0)]\n\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n logger.debug('Scoring done')\n return df_copy\n\n\n#######################################################################################\n# Outlier removal in pipeline\n#######################################################################################\n\nclass LocalOutlierFactor:\n def __init__(self):\n self.lof = LocalOutlierFactor() #**kwargs)\n self.version = 1\n\n def fit(self, X):\n self.lof.fit(X.reshape(-1,1))\n\n def predict(self, X, threshold):\n #return (X >= self.MinMax[0]) & (X <= self.MinMax[1])\n return self.lof.negative_outlier_factor_ < threshold\n\nclass KDEMaxMin:\n def __init__(self, version=1):\n self.version = version\n self.kde = KernelDensity(kernel='gaussian')\n self.Min = None\n self.Max = None\n\n def fit(self, X, alpha):\n\n self.kde.fit(X.reshape(-1,1))\n\n kde_X = self.kde.score_samples(X.reshape(-1,1))\n\n # find outliers of the kde score\n tau_kde = sp.stats.mstats.mquantiles(kde_X, 1. - alpha) # alpha = 0.995\n\n # determine outliers\n X_outliers = X[np.argwhere(kde_X < tau_kde).flatten()]\n X_valid = X[np.argwhere(kde_X >= tau_kde).flatten()]\n\n # determine max of all sample that are not outliers\n self.Min = X_valid.min()\n self.Max = X_valid.max()\n if len(X_outliers) > 0:\n X_min = X_outliers[X_outliers < self.Min]\n X_max = X_outliers[X_outliers > self.Max]\n if len(X_min) > 0:\n self.Min = max(X_min.max(), self.Min)\n if len(X_max) > 0:\n self.Max = min(X_max.min(), self.Max)\n # self.Min = max(X_outliers[X_outliers < self.Min].max(), self.Min)\n # self.Max = min(X_outliers[X_outliers > self.Max].min(), self.Max)\n\n logger.info('KDEMaxMin - Min: ' + str(self.Min) + ', ' + str(self.Max))\n\n return kde_X\n\n def predict(self, X, threshold=None):\n return (X >= self.Min) & (X <= self.Max)\n\nclass RobustThreshold(SupervisedLearningTransformer):\n\n def __init__(self, input_item, threshold, output_item):\n super().__init__(features=[input_item], targets=[output_item])\n\n self.input_item = input_item\n self.threshold = threshold\n self.output_item = output_item\n self.auto_train = True\n self.Min = dict()\n self.Max = dict()\n\n self.whoami = 'RobustThreshold'\n\n logger.info(self.whoami + ' from ' + self.input_item + ' quantile threshold ' + str(self.threshold) +\n ' exceeding boolean ' + self.output_item)\n\n\n def execute(self, df):\n # set output columns to zero\n logger.debug('Called ' + self.whoami + ' with columns: ' + str(df.columns))\n df[self.output_item] = 0\n return super().execute(df)\n\n\n def _calc(self, df):\n # per entity - copy for later inplace operations\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n model_name, robust_model, version = self.load_model(suffix=entity)\n\n feature = df[self.input_item].values\n\n if robust_model is None and self.auto_train:\n robust_model = KDEMaxMin(version=version)\n try:\n robust_model.fit(feature, self.threshold)\n db.model_store.store_model(model_name, robust_model)\n except Exception as e:\n logger.error('Model store failed with ' + str(e))\n robust_model = None\n\n if robust_model is not None:\n self.Min[entity] = robust_model.Min\n self.Max[entity] = robust_model.Max\n\n df[self.output_item] = robust_model.predict(feature, self.threshold)\n else:\n df[self.output_item] = 0\n\n return df.droplevel(0)\n\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name=\"input_item\", datatype=float, description=\"Data item to analyze\"))\n\n inputs.append(UISingle(name=\"threshold\", datatype=int,\n description=\"Threshold to determine outliers by quantile. Typically set to 0.95\", ))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name=\"output_item\", datatype=bool,\n description=\"Boolean outlier condition\"))\n return (inputs, outputs)\n\n\n\n#######################################################################################\n# Regressors\n#######################################################################################\n\nclass BayesRidgeRegressor(BaseEstimatorFunction):\n \"\"\"\n Linear regressor based on a probabilistic model as provided by sklearn\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n num_rounds_per_estimator = 3\n\n def BRidgePipeline(self):\n steps = [('scaler', StandardScaler()), ('bridge', linear_model.BayesianRidge(compute_score=True))]\n return Pipeline(steps)\n\n def set_estimators(self):\n params = {}\n self.estimators['bayesianridge'] = (self.BRidgePipeline, params)\n\n logger.info('Bayesian Ridge Regressor start searching for best model')\n\n def __init__(self, features, targets, predictions=None, deviations=None):\n super().__init__(features=features, targets=targets, predictions=predictions, stddev=True, keep_current_models=True)\n\n if deviations is not None:\n self.pred_stddev = deviations\n\n self.experiments_per_execution = 1\n self.auto_train = True\n self.correlation_threshold = 0\n self.stop_auto_improve_at = -2\n\n self.whoami = 'BayesianRidgeRegressor'\n\n\n def execute(self, df):\n\n logger.debug('Execute ' + self.whoami)\n\n df_copy = df.copy()\n # Create missing columns before doing group-apply\n missing_cols = [x for x in self.predictions + self.pred_stddev if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n # check data type\n #if df[self.input_item].dtype != np.float64:\n for feature in self.features:\n if not pd.api.types.is_numeric_dtype(df_copy[feature].dtype):\n logger.error('Regression on non-numeric feature:' + str(feature))\n return (df_copy)\n\n # delegate to _calc\n logger.debug('Execute ' + self.whoami + ' enter per entity execution')\n\n # group over entities\n group_base = [pd.Grouper(axis=0, level=0)]\n\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n logger.debug('Scoring done')\n return df_copy\n\n\n def _calc(self, df):\n\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n logger.debug('BayesRidgeRegressor execute: ' + str(type(df)) + ' for entity ' + str(entity) +\n ' predicting ' + str(self.targets) + ' from ' + str(self.features) +\n ' to appear in ' + str(self.predictions) + ' with confidence interval ' + str(self.pred_stddev))\n\n try:\n dfe = super()._execute(df, entity)\n\n logger.debug('BayesianRidge: Entity ' + str(entity) + ' Type of pred, stddev arrays ' +\n str(type(dfe[self.predictions])) + str(type(dfe[self.pred_stddev].values)))\n\n dfe.fillna(0, inplace=True)\n\n df[self.predictions] = dfe[self.predictions]\n df[self.pred_stddev] = dfe[self.pred_stddev]\n\n except Exception as e:\n logger.info('Bayesian Ridge regressor for entity ' + str(entity) + ' failed with: ' + str(e))\n df[self.predictions] = 0\n df[self.pred_stddev] = 0\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True, output_item='deviations',\n is_output_datatype_derived=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass BayesRidgeRegressorExt(BaseEstimatorFunction):\n \"\"\"\n Linear regressor based on a probabilistic model as provided by sklearn\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n num_rounds_per_estimator = 3\n\n def BRidgePipelineDeg(self):\n steps = [('scaler', StandardScaler()),\n ('poly', PolynomialFeatures(degree=self.degree)),\n ('bridge', linear_model.BayesianRidge(compute_score=True))]\n return Pipeline(steps)\n\n def set_estimators(self):\n params = {}\n self.estimators['bayesianridge'] = (self.BRidgePipelineDeg, params)\n\n logger.info('Bayesian Ridge Regressor start searching for best polynomial model of degree ' + str(self.degree))\n\n def __init__(self, features, targets, predictions=None, deviations=None, degree=3):\n super().__init__(features=features, targets=targets, predictions=predictions, stddev=True, keep_current_models=True)\n\n if deviations is not None:\n self.pred_stddev = deviations\n\n self.experiments_per_execution = 1\n self.auto_train = True\n self.correlation_threshold = 0\n self.stop_auto_improve_at = -2\n self.degree = degree\n\n self.whoami = 'BayesianRidgeRegressorExt'\n\n\n def execute(self, df):\n\n logger.debug('Execute ' + self.whoami)\n\n df_copy = df.copy()\n # Create missing columns before doing group-apply\n missing_cols = [x for x in self.predictions + self.pred_stddev if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n # check data type\n #if df[self.input_item].dtype != np.float64:\n for feature in self.features:\n if not pd.api.types.is_numeric_dtype(df_copy[feature].dtype):\n logger.error('Regression on non-numeric feature:' + str(feature))\n return (df_copy)\n\n # delegate to _calc\n logger.debug('Execute ' + self.whoami + ' enter per entity execution')\n\n # group over entities\n group_base = [pd.Grouper(axis=0, level=0)]\n\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n logger.debug('Scoring done')\n return df_copy\n\n\n def _calc(self, df):\n\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n logger.debug('BayesRidgeRegressor execute: ' + str(type(df)) + ' for entity ' + str(entity) +\n ' predicting ' + str(self.targets) + ' from ' + str(self.features) +\n ' to appear in ' + str(self.predictions) + ' with confidence interval ' + str(self.pred_stddev))\n\n try:\n logger.debug('check passed')\n\n dfe = super()._execute(df, entity)\n\n logger.debug('BayesianRidge: Entity ' + str(entity) + ' Type of pred, stddev arrays ' +\n str(type(dfe[self.predictions])) + str(type(dfe[self.pred_stddev].values)))\n\n dfe.fillna(0, inplace=True)\n\n df[self.predictions] = dfe[self.predictions]\n df[self.pred_stddev] = dfe[self.pred_stddev]\n\n except Exception as e:\n logger.info('Bayesian Ridge regressor for entity ' + str(entity) + ' failed with: ' + str(e))\n df[self.predictions] = 0\n df[self.pred_stddev] = 0\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True, output_item='deviations',\n is_output_datatype_derived=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n inputs.append(\n UISingle(name='degree', datatype=int, required=False, description='Degree of polynomial'))\n\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass GBMRegressor(BaseEstimatorFunction):\n \"\"\"\n Regressor based on gradient boosting method as provided by lightGBM\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n\n def GBMPipeline(self):\n steps = [('scaler', StandardScaler()), ('gbm', lightgbm.LGBMRegressor())]\n return Pipeline(steps=steps)\n\n def set_estimators(self):\n # gradient_boosted\n self.estimators['light_gradient_boosted_regressor'] = (self.GBMPipeline, self.params)\n logger.info('GBMRegressor start searching for best model')\n\n def __init__(self, features, targets, predictions=None, n_estimators=None, num_leaves=None, learning_rate=None,\n max_depth=None, lags=None):\n #\n # from https://github.com/ashitole/Time-Series-Project/blob/main/Auto-Arima%20and%20LGBM.ipynb\n # as taken from https://www.kaggle.com/rohanrao/ashrae-half-and-half\n #\n self.n_estimators = n_estimators # 500\n self.num_leaves = num_leaves # 40\n self.learning_rate = learning_rate #0.2 # default 0.001\n feature_fraction = 0.85 # default 1.0\n reg_lambda = 2 # default 0\n self.max_depth = max_depth # -1\n self.lagged_features = features\n self.lags = lags\n\n self.forecast = None\n if lags is not None:\n self.forecast = min(lags) # forecast = number to shift features back is the negative minimum lag\n newfeatures, _ = self.lag_features()\n\n super().__init__(features=newfeatures, targets=targets, predictions=predictions, keep_current_models=True)\n else:\n super().__init__(features=features, targets=targets, predictions=predictions, keep_current_models=True)\n\n self.experiments_per_execution = 1\n self.correlation_threshold = 0\n self.auto_train = True\n\n self.num_rounds_per_estimator = 1\n self.parameter_tuning_iterations = 1\n self.cv = 1\n\n self.set_parameters()\n\n self.stop_auto_improve_at = -2\n self.whoami = 'GBMRegressor'\n\n\n def set_parameters(self):\n self.params = {'gbm__n_estimators': [self.n_estimators], 'gbm__num_leaves': [self.num_leaves],\n 'gbm__learning_rate': [self.learning_rate], 'gbm__max_depth': [self.max_depth], 'gbm__verbosity': [2]}\n\n #\n # forecasting support\n # return list of new columns for the lagged features and dataframe extended with these new columns\n #\n def lag_features(self, df=None, Train=True):\n logger.debug('lags ' + str(self.lags) + ' lagged_features ' + str(self.lagged_features) + ' Train mode: '\n + str(Train))\n create_feature_triplets = []\n new_features = []\n\n if self.lags is None or self.lagged_features is None:\n return new_features, None\n\n for lagged_feature in self.lagged_features:\n for lag in self.lags:\n # collect triple of new column, original column and lag\n if Train:\n create_feature_triplets.append((lagged_feature + '_' + str(lag), lagged_feature, lag))\n else:\n create_feature_triplets.append((lagged_feature + '_' + str(lag), lagged_feature, lag - self.forecast))\n\n new_features.append(lagged_feature + '_' + str(lag))\n\n # find out proper timescale\n mindelta, df_copy = min_delta(df)\n\n # add day of week and month of year as two feature pairs for at least hourly timescales\n include_day_of_week = False\n include_hour_of_day = False\n if mindelta >= pd.Timedelta('1h'):\n logger.info(self.whoami + ' adding day_of_week feature')\n include_day_of_week = True\n elif mindelta >= pd.Timedelta('1m'):\n logger.info(self.whoami + ' adding hour_of_day feature')\n include_hour_of_day = True\n\n # add day of week or hour of day if appropriate\n\n if df is not None:\n df_copy = df.copy()\n missing_cols = [x[0] for x in create_feature_triplets if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n # I hope I can do that for all entities in one fell swoop\n for new_feature in create_feature_triplets:\n df_copy[new_feature[0]] = df[new_feature[1]].shift(new_feature[2])\n\n # get rid of NaN as result of shifting columns\n df_copy.dropna(inplace=True)\n\n # add day of week and month of year as two feature pairs\n # operate on simple timestamp index\n if include_day_of_week:\n new_features = np.concatenate((new_features, ['_DayOfWeekCos_', '_DayOfWeekSin_', '_DayOfYearCos_', '_DayOfYearSin_']))\n df_copy['_DayOfWeekCos_'] = np.cos(df_copy.index.get_level_values(1).dayofweek / 7)\n df_copy['_DayOfWeekSin_'] = np.sin(df_copy.index.get_level_values(1).dayofweek / 7)\n df_copy['_DayOfYearCos_'] = np.cos(df_copy.index.get_level_values(1).dayofyear / 365)\n df_copy['_DayOfYearSin_'] = np.sin(df_copy.index.get_level_values(1).dayofyear / 365)\n elif include_hour_of_day:\n new_features = np.concatenate((new_features, ['_HourOfDayCos_', '_HourOfDaySin_']))\n df_copy['_HourOfDayCos_'] = np.cos(df_copy.index.get_level_values(1).hour / 24)\n df_copy['_HourOfDaySin_'] = np.sin(df_copy.index.get_level_values(1).hour / 24)\n\n else:\n df_copy = df\n\n return new_features, df_copy\n\n def execute(self, df):\n\n logger.debug('Execute ' + self.whoami)\n\n # forecasting support\n if self.lags is not None:\n _, df_copy = self.lag_features(df=df, Train=True)\n else:\n df_copy = df.copy()\n\n # Create missing columns before doing group-apply\n missing_cols = [x for x in self.predictions if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n # check data type\n #if df[self.input_item].dtype != np.float64:\n for feature in self.features:\n if not pd.api.types.is_numeric_dtype(df_copy[feature].dtype):\n logger.error('Regression on non-numeric feature:' + str(feature))\n return (df_copy)\n\n # delegate to _calc\n logger.debug('Execute ' + self.whoami + ' enter per entity execution')\n\n # group over entities\n group_base = [pd.Grouper(axis=0, level=0)]\n\n # first round - training\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n\n # strip off lagged features\n if self.lags is not None:\n strip_features, df_copy = self.lag_features(df=df, Train=False)\n\n # second round - inferencing\n df_copy = df_copy.groupby(group_base).apply(self._calc)\n\n logger.debug('Drop artificial features ' + str(strip_features))\n df_copy.drop(columns = strip_features, inplace=True)\n\n logger.debug('Scoring done')\n return df_copy\n\n\n def _calc(self, df):\n\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n logger.debug('GBMRegressor execute: ' + str(type(df)) + ' for entity ' + str(entity) +\n ' predicting ' + str(self.targets) + ' from ' + str(self.features) +\n ' to appear in ' + str(self.predictions))\n\n try:\n check_array(df[self.features].values, allow_nd=True)\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n return df\n\n try:\n dfe = super()._execute(df, entity)\n\n logger.debug('GBMRegressor: Entity ' + str(entity) + ' Type of pred ' +\n str(type(dfe[self.predictions])))\n\n dfe.fillna(0, inplace=True)\n\n df[self.predictions] = dfe[self.predictions]\n\n except Exception as e:\n logger.info('GBMRegressor for entity ' + str(entity) + ' failed with: ' + str(e))\n df[self.predictions] = 0\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n inputs.append(\n UISingle(name='n_estimators', datatype=int, required=False, description='Max rounds of boosting'))\n inputs.append(\n UISingle(name='num_leaves', datatype=int, required=False, description='Max leaves in a boosting tree'))\n inputs.append(UISingle(name='learning_rate', datatype=float, required=False, description='Learning rate'))\n inputs.append(\n UISingle(name='max_depth', datatype=int, required=False, description='Cut tree to prevent overfitting'))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass SimpleRegressor(BaseEstimatorFunction):\n \"\"\"\n Regressor based on stochastic gradient descent and gradient boosting method as provided by sklearn\n \"\"\"\n eval_metric = staticmethod(metrics.r2_score)\n\n # class variables\n train_if_no_model = True\n num_rounds_per_estimator = 3\n\n def GBRPipeline(self):\n steps = [('scaler', StandardScaler()), ('gbr', ensemble.GradientBoostingRegressor)]\n return Pipeline(steps)\n\n def SGDPipeline(self):\n steps = [('scaler', StandardScaler()), ('sgd', linear_model.SGDRegressor)]\n return Pipeline(steps)\n\n def set_estimators(self):\n # gradient_boosted\n params = {'n_estimators': [100, 250, 500, 1000], 'max_depth': [2, 4, 10], 'min_samples_split': [2, 5, 9],\n 'learning_rate': [0.01, 0.02, 0.05], 'loss': ['ls']}\n self.estimators['gradient_boosted_regressor'] = (ensemble.GradientBoostingRegressor, params)\n logger.info('SimpleRegressor start searching for best model')\n\n def __init__(self, features, targets, predictions=None, n_estimators=None, num_leaves=None, learning_rate=None,\n max_depth=None):\n super().__init__(features=features, targets=targets, predictions=predictions)\n\n self.experiments_per_execution = 1\n self.auto_train = True\n self.correlation_threshold = 0\n\n def execute(self, df):\n\n df_copy = df.copy()\n entities = np.unique(df_copy.index.levels[0])\n logger.debug(str(entities))\n\n missing_cols = [x for x in self.predictions if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n for entity in entities:\n try:\n check_array(df_copy.loc[[entity]][self.features].values)\n dfe = super()._execute(df_copy.loc[[entity]], entity)\n df_copy.loc[entity, self.predictions] = dfe[self.predictions]\n\n except Exception as e:\n logger.info('GBMRegressor for entity ' + str(entity) + ' failed with: ' + str(e))\n df_copy.loc[entity, self.predictions] = 0\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass SimpleAnomaly(BaseRegressor):\n \"\"\"\n A supervised anomaly detection function.\n Uses a regression model to predict the value of target data items based on dependent data items or features.\n Then, it compares the actual value to the predicted valueand generates an alert when the difference falls outside of a threshold.\n \"\"\"\n\n # class variables\n train_if_no_model = True\n num_rounds_per_estimator = 3\n\n def __init__(self, features, targets, threshold, predictions=None, alerts=None):\n super().__init__(features=features, targets=targets, predictions=predictions)\n if alerts is None:\n alerts = ['%s_alert' % x for x in self.targets]\n self.alerts = alerts\n self.threshold = threshold\n self.correlation_threshold = 0\n\n def execute(self, df):\n\n try:\n df_new = super().execute(df)\n df = df_new\n for i, t in enumerate(self.targets):\n prediction = self.predictions[i]\n df['_diff_'] = (df[t] - df[prediction]).abs()\n alert = AlertHighValue(input_item='_diff_', upper_threshold=self.threshold, alert_name=self.alerts[i])\n alert.set_entity_type(self.get_entity_type())\n df = alert.execute(df)\n except Exception as e:\n logger.info('Simple Anomaly failed with: ' + str(e))\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n inputs.append(UISingle(name='threshold', datatype=float,\n description='Threshold for firing an alert. Expressed as absolute value not percent.'))\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(\n UIFunctionOutMulti(name='alerts', datatype=bool, cardinality_from='targets', is_datatype_derived=False, ))\n\n return inputs, outputs\n\n\n#######################################################################################\n# Forecasting\n#######################################################################################\n\nclass FeatureBuilder(BaseTransformer):\n\n def __init__(self, features, lag, method, lagged_features):\n super().__init__()\n\n self.features = features\n self.lagged_features = lagged_features\n\n self.lag = lag # list of integers (days) to define lags\n\n self.method = method #\n\n self.whoami = 'FeatureBuilder'\n\n logger.debug(self.whoami, self.features, self.lagged_features, self.lag, self.method)\n\n def execute(self, df):\n\n df_copy = df.copy()\n entities = np.unique(df_copy.index.levels[0])\n logger.debug(str(entities))\n\n missing_cols = [x for x in self.lagged_features if x not in df_copy.columns]\n for m in missing_cols:\n df_copy[m] = None\n\n for entity in entities:\n # per entity - copy for later inplace operations\n try:\n check_array(df_copy.loc[[entity]][self.features].values, allow_nd=True)\n dfe = df_copy.loc[[entity]]\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n continue\n\n dfroll = dfe[self.features].rolling(window=self.lag, min_periods=0)\n if self.method == 'mean':\n dfe[self.lagged_features] = dfroll.mean().shift(1)\n elif self.method == 'stddev':\n dfe[self.lagged_features] = dfroll.std().shift(1)\n else:\n dfe[self.lagged_features] = dfe[self.features].shift(1)\n\n df_copy.loc[entity, self.lagged_features] = dfe[self.lagged_features]\n\n return df_copy\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True, output_item='lagged_features',\n is_output_datatype_derived=True))\n inputs.append(UISingle(name='lag', datatype=int, description='Lag for each input_item'))\n inputs.append(UISingle(name='method', datatype=str, description='Method: Plain, Mean, Stddev'))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\nclass GBMForecaster(GBMRegressor):\n \"\"\"\n Forecasting regressor based on gradient boosting method as provided by lightGBM\n \"\"\"\n def __init__(self, features, targets, predictions=None, lags=None):\n #\n # from https://github.com/ashitole/Time-Series-Project/blob/main/Auto-Arima%20and%20LGBM.ipynb\n # as taken from https://www.kaggle.com/rohanrao/ashrae-half-and-half\n #\n super().__init__(features=features, targets=targets, predictions=predictions, n_estimators=500,\n num_leaves=40, learning_rate=0.2, max_depth=-1, lags=lags)\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n inputs.append(UIMulti(name='lags', datatype=int, description='Comma separated list of lags'))\n\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\n#######################################################################################\n# ARIMA\n#######################################################################################\n\n# self.model_class = STLForecast(np.arange(0,1), ARIMA, model_kwargs=dict(order=(1,1,1), trend=\"c\"), period=7*24)\nclass ARIMAForecaster(SupervisedLearningTransformer):\n \"\"\"\n Provides a forecast for 'n_forecast' data points for from endogenous data in input_item\n Data is returned as input_item shifted by n_forecast positions with the forecast appended\n \"\"\"\n\n def __init__(self, input_item, n_forecast, output_item):\n super().__init__(features=[input_item], targets=[output_item])\n\n self.input_item = input_item\n self.n_forecast = n_forecast\n self.output_item = output_item\n\n self.power = None # used to store box cox lambda\n self.active_models = dict()\n\n self.name = 'ARIMAForecaster'\n\n\n def execute(self, df):\n # set output columns to zero\n df[self.output_item] = 0\n\n # check data type\n if df[self.input_item].dtype != np.float64:\n logger.error('ARIMA forecasting on non-numeric feature:' + str(self.input_item))\n return df\n\n return super().execute(df)\n\n\n # EXCLUDED until we upgrade to statsmodels 0.12\n '''\n def _calc(self, df):\n # per entity - copy for later inplace operations\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n df = df.droplevel(0)\n\n model_name, arima_model, version = self.load_model(suffix=entity)\n\n logger.debug('Module ARIMA Forecaster, Entity: ' + str(entity) + ', Input: ' + str(\n self.input_item) + ', Forecasting: ' + str(self.n_forecast) + ', Output: ' + str(\n self.output_item))\n\n feature = df[self.input_item].values\n\n if arima_model is None and self.auto_train:\n\n # all variables should be continuous\n stlf = STLForecast(temperature, ARIMA, model_kwargs=dict(order=(1, 0, 1), trend=\"n\"), period=7*24)\n\n arima_model = stlf.fit()\n\n logger.debug('Created STL + ARIMA' + str(arima_model))\n\n try:\n db.model_store.store_model(model_name, arima_model)\n except Exception as e:\n logger.error('Model store failed with ' + str(e))\n pass\n\n # remove n_forecast elements and append the forecast of length n_forecast\n predictions_ = arima_model.forecast(self.n_forecast)\n logger.debug(predictions_.shape, temperature.shape)\n predictions = np.hstack([temperature[self.n_forecast:].reshape(-1,), predictions_])\n\n self.active_models[entity] = arima_model\n\n logger.debug(arima_model.summary())\n\n df[self.output_item] = predictions\n\n return df\n '''\n\n @classmethod\n def build_ui(cls):\n\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingleItem(name='input_item', datatype=float, description='Data item to interpolate'))\n\n inputs.append(\n UISingle(name='n_forecast', datatype=int, description='Forecasting n_forecast data points.'))\n\n # define arguments that behave as function outputs\n outputs = []\n outputs.append(UIFunctionOutSingle(name='output_item', datatype=float, description='Interpolated data'))\n return inputs, outputs\n\n\n#\n# following Jake Vanderplas Data Science Handbook\n# https://jakevdp.github.io/PythonDataScienceHandbook/05.13-kernel-density-estimation.html\n#\n\nclass KDEAnomalyScore(SupervisedLearningTransformer):\n \"\"\"\n A supervised anomaly detection function.\n Uses kernel density estimate to assign an anomaly score\n \"\"\"\n def __init__(self, threshold, features, targets, predictions=None):\n logger.debug(\"init KDE Estimator\")\n self.name = 'KDEAnomalyScore'\n self.whoami= 'KDEAnomalyScore'\n super().__init__(features, targets)\n\n self.threshold = threshold\n self.active_models = dict()\n if predictions is None:\n predictions = ['predicted_%s' % x for x in self.targets]\n self.predictions = predictions\n\n def execute(self, df):\n\n # Create missing columns before doing group-apply\n df = df.copy()\n missing_cols = [x for x in self.predictions if x not in df.columns]\n for m in missing_cols:\n df[m] = None\n\n return super().execute(df)\n\n\n def _calc(self, df):\n\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n logger.debug('KDEAnomalyScore execute: ' + str(type(df)) + ' for entity ' + str(entity))\n\n # check data okay\n try:\n logger.debug(self.features)\n check_array(df[self.features].values, allow_nd=True)\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n\n # per entity - copy for later inplace operations\n model_name, kde_model, version = self.load_model(suffix=entity)\n\n xy = np.hstack([df[self.features].values, df[self.targets].values])\n\n # train new model\n if kde_model is None:\n\n logger.debug('Running KDE with ' + str(xy.shape))\n # all variables should be continuous\n kde_model = KDEMultivariate(xy, var_type=\"c\" * (len(self.features) + len(self.targets)))\n logger.debug('Created KDE ' + str(kde_model))\n\n try:\n db.model_store.store_model(model_name, kde_model)\n except Exception as e:\n logger.error('Model store failed with ' + str(e))\n\n self.active_models[entity] = kde_model\n\n predictions = kde_model.pdf(xy).reshape(-1,1)\n print(predictions.shape, df[self.predictions].values.shape)\n df[self.predictions] = predictions\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UISingle(name=\"threshold\", datatype=float,\n description=\"Probability threshold for outliers. Typically set to 10e-6.\", required=True))\n inputs.append(UIMultiItem(name='features', datatype=float, required=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True, output_item='predictions',\n is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n\n'''\n def fit(self, X, y):\n xy = np.vstack(X, y).T\n self.kde = KDEMultivariate(xy, var_type='cc')\n return self\n\n def predict_proba(self, X):\n logprobs = np.vstack([model.score_samples(X)\n for model in self.models_]).T\n result = np.exp(logprobs + self.logpriors_)\n return result / result.sum(1, keepdims=True)\n\n def predict(self, X):\n return self.classes_[np.argmax(self.predict_proba(X), 1)]\n'''\n\n\n#######################################################################################\n# Variational Autoencoder\n# to approximate probability distribution of targets with respect to features\n#######################################################################################\n# from https://www.ritchievink.com/blog/2019/09/16/variational-inference-from-scratch/\n# usual ELBO with standard prior N(0,1), standard reparametrization\n\n# helper function\ndef ll_gaussian(y, mu, log_var):\n sigma = torch.exp(0.5 * log_var)\n return -0.5 * torch.log(2 * np.pi * sigma**2) - (1 / (2 * sigma**2)) * (y-mu)**2\n\n\ndef l_gaussian(y, mu, log_var):\n sigma = torch.exp(0.5 * log_var)\n return 1/torch.sqrt(2 * np.pi * sigma**2) / torch.exp((1 / (2 * sigma**2)) * (y-mu)**2)\n\n\ndef kl_div(mu1, mu2, lg_sigma1, lg_sigma2):\n return 0.5 * (2 * lg_sigma2 - 2 * lg_sigma1 + (lg_sigma1.exp() ** 2 + (mu1 - mu2)**2)/lg_sigma2.exp()**2 - 1)\n\n\nclass VI(nn.Module):\n def __init__(self, scaler, prior_mu=0.0, prior_sigma=1.0, beta=1.0, adjust_mean=0.0, version=None):\n self.prior_mu = prior_mu\n self.prior_sigma = prior_sigma\n self.beta = beta\n self.onnx_session = None\n self.version = version\n self.build_time = pd.Timestamp.now()\n self.scaler = scaler\n self.show_once = True\n self.adjust_mean = adjust_mean\n super().__init__()\n\n self.q_mu = nn.Sequential(\n nn.Linear(1, 20),\n nn.ReLU(),\n nn.Linear(20, 10),\n nn.ReLU(),\n nn.Linear(10, 1)\n )\n\n self.q_log_var = nn.Sequential(\n nn.Linear(1, 50), # more parameters for sigma\n nn.ReLU(),\n nn.Linear(50, 35),\n nn.ReLU(),\n nn.Linear(35, 10),\n nn.ReLU(),\n nn.Linear(10, 1)\n )\n\n # draw from N(mu, sigma)\n def reparameterize(self, mu, log_var):\n # std can not be negative, thats why we use log variance\n sigma = torch.add(torch.exp(0.5 * log_var), 1e-7)\n eps = torch.randn_like(sigma)\n return mu + sigma * eps\n\n # sample from the one-dimensional normal distribution N(mu, exp(log_var))\n def forward(self, x):\n mu = self.q_mu(x)\n log_var = self.q_log_var(x)\n return self.reparameterize(mu, log_var), mu, log_var\n\n # see 2.3 in https://arxiv.org/pdf/1312.6114.pdf\n #\n def elbo(self, y_pred, y, mu, log_var):\n # likelihood of observing y given Variational mu and sigma - reconstruction error\n loglikelihood = ll_gaussian(y, mu, log_var)\n # Sample from p(x|z) by sampling from q(z|x), passing through decoder (y_pred)\n # likelihood of observing y given Variational decoder mu and sigma - reconstruction error\n log_qzCx = ll_gaussian(y, mu, log_var)\n\n # KL - prior probability of sample y_pred w.r.t. N(0,1)\n log_pz = ll_gaussian(y_pred, self.prior_mu, torch.log(torch.tensor(self.prior_sigma)))\n\n # KL - probability of y_pred w.r.t the variational likelihood\n log_pxCz = ll_gaussian(y_pred, mu, log_var)\n\n if self.show_once:\n self.show_once = False\n logger.info('Cardinalities: Mu: ' + str(mu.shape) + ' Sigma: ' + str(log_var.shape) +\n ' loglikelihood: ' + str(log_qzCx.shape) + ' KL value: ' +\n str((log_pz - log_pxCz).mean()))\n\n # by taking the mean we approximate the expectation according to the law of large numbers\n return (log_qzCx + self.beta * (log_pz - log_pxCz)).mean()\n\n\n # from https://arxiv.org/pdf/1509.00519.pdf\n # and https://justin-tan.github.io/blog/2020/06/20/Intuitive-Importance-Weighted-ELBO-Bounds\n def iwae(self, x, y, k_samples):\n\n log_iw = None\n for _ in range(k_samples):\n\n\n # Encode - sample from the encoder\n # Latent variables mean,variance: mu_enc, log_var_enc\n # y_pred: Sample from q(z|x) by passing data through encoder and reparametrizing\n y_pred, mu_enc, log_var_enc = self.forward(x)\n\n # there is not much of a decoder - hence we use the identity below as decoder 'stub'\n dec_mu = mu_enc\n dec_log_var = log_var_enc\n\n # Sample from p(x|z) by sampling from q(z|x), passing through decoder (y_pred)\n # likelihood of observing y given Variational decoder mu and sigma - reconstruction error\n log_qzCx = ll_gaussian(y, dec_mu, dec_log_var)\n\n # KL (well, not true for IWAE) - prior probability of y_pred w.r.t. N(0,1)\n log_pz = ll_gaussian(y_pred, self.prior_mu, torch.log(torch.tensor(self.prior_sigma)))\n\n # KL (well, not true for IWAE) - probability of y_pred w.r.t the decoded variational likelihood\n log_pxCz = ll_gaussian(y_pred, dec_mu, dec_log_var)\n\n i_sum = log_qzCx + log_pz - log_pxCz\n if log_iw is None:\n log_iw = i_sum\n else:\n log_iw = torch.cat([log_iw, i_sum], 1)\n\n # loss calculation\n log_iw = log_iw.reshape(-1, k_samples)\n\n iwelbo = torch.logsumexp(log_iw, dim=1) - np.log(k_samples)\n\n return iwelbo.mean()\n\n\nclass VIAnomalyScore(SupervisedLearningTransformer):\n \"\"\"\n A supervised anomaly detection function.\n Uses VAE based density approximation to assign an anomaly score\n \"\"\"\n # set self.auto_train and self.delete_model\n def __init__(self, features, targets, predictions=None, pred_stddev=None):\n\n self.name = \"VIAnomalyScore\"\n self.whoami = \"VIAnomalyScore\"\n super().__init__(features, targets)\n\n self.epochs = 1500\n self.learning_rate = 0.005\n\n self.active_models = dict()\n self.Input = {}\n self.Output = {}\n self.mu = {}\n self.quantile095 = {}\n\n if predictions is None:\n predictions = ['predicted_%s' % x for x in self.targets]\n if pred_stddev is None:\n pred_stddev = ['pred_dev_%s' % x for x in self.targets]\n\n self.predictions = predictions\n self.pred_stddev = pred_stddev\n\n self.prior_mu = 0.0\n self.prior_sigma = 1.0\n self.beta = 1.0\n self.iwae_samples = 10\n\n def execute(self, df):\n\n # Create missing columns before doing group-apply\n df = df.copy()\n missing_cols = [x for x in (self.predictions + self.pred_stddev) if x not in df.columns]\n for m in missing_cols:\n df[m] = None\n\n return super().execute(df)\n\n\n def _calc(self, df):\n\n db = self._entity_type.db\n entity = df.index.levels[0][0]\n\n logger.debug('VIAnomalyScore execute: ' + str(type(df)) + ' for entity ' + str(entity))\n\n # check data okay\n try:\n logger.debug(self.features)\n check_array(df[self.features].values, allow_nd=True)\n except Exception as e:\n logger.error(\n 'Found Nan or infinite value in feature columns for entity ' + str(entity) + ' error: ' + str(e))\n\n # per entity - copy for later inplace operations\n model_name, vi_model, version = self.load_model(suffix=entity)\n\n # learn to scale features\n if vi_model is not None:\n scaler = vi_model.scaler\n else:\n scaler = StandardScaler().fit(df[self.features].values)\n\n features = scaler.transform(df[self.features].values)\n targets = df[self.targets].values\n\n # deal with negative means - are the issues related to ReLU ?\n # adjust targets to have mean == 0\n if vi_model is None:\n adjust_mean = targets.mean()\n else:\n adjust_mean = vi_model.adjust_mean\n logger.info('Adjusting target mean with ' + str(adjust_mean))\n targets -= adjust_mean\n\n xy = np.hstack([features, targets])\n\n # TODO: assumption is cardinality of One for features and targets !!!\n ind = np.lexsort((xy[:, 1], xy[:, 0]))\n ind_r = np.argsort(ind)\n\n self.Input[entity] = xy[ind][:, 0]\n\n X = torch.tensor(xy[ind][:, 0].reshape(-1, 1), dtype=torch.float)\n Y = torch.tensor(xy[ind][:, 1].reshape(-1, 1), dtype=torch.float)\n\n # train new model if there is none and autotrain is set\n if vi_model is None and self.auto_train:\n\n self.prior_sigma = targets.std()\n\n vi_model = VI(scaler, prior_mu=self.prior_mu, prior_sigma=self.prior_sigma,\n beta=self.beta, adjust_mean=adjust_mean, version=version)\n\n logger.debug('Training VI model ' + str(vi_model.version) + ' for entity: ' + str(entity) +\n 'Prior mean: ' + str(self.prior_mu) + ', sigma: ' + str(self.prior_sigma))\n\n optim = torch.optim.Adam(vi_model.parameters(), lr=self.learning_rate)\n\n for epoch in range(self.epochs):\n optim.zero_grad()\n y_pred, mu, log_var = vi_model(X)\n loss = -vi_model.elbo(y_pred, Y, mu, log_var)\n iwae = -vi_model.iwae(X, Y, self.iwae_samples) # default is to try with 10 samples\n if epoch % 10 == 0:\n logger.debug('Epoch: ' + str(epoch) + ', neg ELBO: ' + str(loss.item()) + ', IWAE ELBO: ' + str(iwae.item()))\n\n #loss.backward()\n iwae.backward()\n optim.step()\n\n logger.debug('Created VAE ' + str(vi_model))\n\n try:\n db.model_store.store_model(model_name, vi_model)\n except Exception as e:\n logger.error('Model store failed with ' + str(e))\n\n # check if training was not allowed or failed\n if vi_model is not None:\n self.active_models[entity] = vi_model\n\n with torch.no_grad():\n mu_and_log_sigma = vi_model(X)\n mue = mu_and_log_sigma[1]\n sigma = torch.exp(0.5 * mu_and_log_sigma[2]) + 1e-5\n mu = sp.stats.norm.ppf(0.5, loc=mue, scale=sigma).reshape(-1,)\n q1 = sp.stats.norm.ppf(0.95, loc=mue, scale=sigma).reshape(-1,)\n self.mu[entity] = mu\n self.quantile095[entity] = q1\n\n df[self.predictions] = (mu[ind_r] + vi_model.adjust_mean).reshape(-1,1)\n df[self.pred_stddev] = (q1[ind_r]).reshape(-1,1)\n else:\n logger.debug('No VI model for entity: ' + str(entity))\n\n return df\n\n @classmethod\n def build_ui(cls):\n # define arguments that behave as function inputs\n inputs = []\n inputs.append(UIMultiItem(name='features', datatype=float, required=True,\n output_item='pred_stddev', is_output_datatype_derived=True))\n inputs.append(UIMultiItem(name='targets', datatype=float, required=True,\n output_item='predictions', is_output_datatype_derived=True))\n # define arguments that behave as function outputs\n outputs = []\n return inputs, outputs\n\n#######################################################################################\n# Crude change point detection\n#######################################################################################\n\ndef make_histogram(t, bins):\n rv = ''\n if t is None:\n logger.warning('make_histogram encountered None')\n return rv\n logger.info('make_histogram ' + str(type(t)) + ' ' + str(t.shape))\n if np.isnan(t).any():\n logger.warning('make_histogram encountered NaN')\n return rv\n try:\n tv = minmax_scale(t.values)\n hist = np.histogram(tv, bins=bins, density=True)\n logger.info('make_histogram returns ' + str(hist))\n rv = str(hist[0])\n except Exception as e:\n logger.warning('make_histogram np.hist failed with ' + str(e))\n return rv\n\n\nclass HistogramAggregator(BaseSimpleAggregator):\n \"\"\"\n The docstring of the function will show as the function description in the UI.\n \"\"\"\n\n def __init__(self, source=None, bins=None):\n\n super().__init__()\n\n self.input_item = source\n if bins is None:\n self.bins = 15\n else:\n self.bins = int(bins)\n\n def execute(self, group):\n #\n # group is a series\n # when calling agg(<aggregator functions>) for each element of the group dictionary\n # df_input.groupby([pd.Grouper(freq='1H', level='timestamp'), pd.Grouper(level='deviceid')])\n #\n return make_histogram(group, self.bins)\n\n @classmethod\n def build_ui(cls):\n inputs = []\n inputs.append(UISingleItem(name='source', datatype=float,\n description='Choose the data items that you would like to aggregate'))\n # output_item='name', is_output_datatype_derived=True))\n inputs.append(UISingle(name='bins', datatype=int, description='Histogram bins - 15 by default'))\n\n outputs = []\n outputs.append(UIFunctionOutSingle(name='name', datatype=str, description='Histogram encoded as string'))\n return inputs, outputs\n"
] |
[
[
"torch.randn_like",
"numpy.dot",
"scipy.stats.norm.ppf",
"numpy.minimum",
"numpy.sqrt",
"numpy.linspace",
"torch.cat",
"numpy.asarray",
"scipy.stats.zscore",
"numpy.cumsum",
"pandas.api.types.is_numeric_dtype",
"sklearn.neighbors.LocalOutlierFactor",
"scipy.fftpack.rfft",
"sklearn.preprocessing.PolynomialFeatures",
"numpy.concatenate",
"numpy.mean",
"torch.no_grad",
"numpy.searchsorted",
"numpy.histogram",
"torch.logsumexp",
"numpy.hstack",
"numpy.unique",
"torch.sqrt",
"numpy.arange",
"sklearn.pipeline.Pipeline",
"numpy.stack",
"numpy.lexsort",
"torch.tensor",
"scipy.interpolate.interp1d",
"numpy.zeros",
"numpy.log",
"numpy.isnan",
"pandas.Timedelta",
"torch.exp",
"numpy.fft.ifft",
"numpy.timedelta64",
"torch.nn.Linear",
"torch.log",
"numpy.append",
"sklearn.preprocessing.StandardScaler",
"sklearn.linear_model.BayesianRidge",
"sklearn.neighbors.KernelDensity",
"numpy.argsort",
"sklearn.covariance.MinCovDet",
"numpy.array",
"sklearn.preprocessing.minmax_scale",
"pandas.merge_asof",
"numpy.maximum",
"numpy.nditer",
"pandas.isnull",
"numpy.gradient",
"numpy.fft.fft",
"sklearn.utils.check_array",
"pandas.Grouper",
"scipy.signal.spectrogram",
"numpy.ones",
"numpy.sign",
"scipy.stats.norm",
"numpy.argwhere",
"pandas.Timestamp.now",
"torch.nn.ReLU",
"numpy.vstack",
"scipy.stats.mstats.mquantiles"
]
] |
AllenDowney/pandas
|
[
"4875a3dcc23fac851627c0c6b93ded9d6b1aca5a"
] |
[
"pandas/tests/indexes/timedeltas/test_timedelta.py"
] |
[
"import pytest\n\nimport numpy as np\nfrom datetime import timedelta\n\nimport pandas as pd\nimport pandas.util.testing as tm\nfrom pandas import (timedelta_range, date_range, Series, Timedelta,\n DatetimeIndex, TimedeltaIndex, Index, DataFrame,\n Int64Index, _np_version_under1p8)\nfrom pandas.util.testing import (assert_almost_equal, assert_series_equal,\n assert_index_equal)\n\nfrom ..datetimelike import DatetimeLike\n\nrandn = np.random.randn\n\n\nclass TestTimedeltaIndex(DatetimeLike):\n _holder = TimedeltaIndex\n _multiprocess_can_split_ = True\n\n def setup_method(self, method):\n self.indices = dict(index=tm.makeTimedeltaIndex(10))\n self.setup_indices()\n\n def create_index(self):\n return pd.to_timedelta(range(5), unit='d') + pd.offsets.Hour(1)\n\n def test_shift(self):\n # test shift for TimedeltaIndex\n # err8083\n\n drange = self.create_index()\n result = drange.shift(1)\n expected = TimedeltaIndex(['1 days 01:00:00', '2 days 01:00:00',\n '3 days 01:00:00',\n '4 days 01:00:00', '5 days 01:00:00'],\n freq='D')\n tm.assert_index_equal(result, expected)\n\n result = drange.shift(3, freq='2D 1s')\n expected = TimedeltaIndex(['6 days 01:00:03', '7 days 01:00:03',\n '8 days 01:00:03', '9 days 01:00:03',\n '10 days 01:00:03'], freq='D')\n tm.assert_index_equal(result, expected)\n\n def test_get_loc(self):\n idx = pd.to_timedelta(['0 days', '1 days', '2 days'])\n\n for method in [None, 'pad', 'backfill', 'nearest']:\n assert idx.get_loc(idx[1], method) == 1\n assert idx.get_loc(idx[1].to_pytimedelta(), method) == 1\n assert idx.get_loc(str(idx[1]), method) == 1\n\n assert idx.get_loc(idx[1], 'pad',\n tolerance=pd.Timedelta(0)) == 1\n assert idx.get_loc(idx[1], 'pad',\n tolerance=np.timedelta64(0, 's')) == 1\n assert idx.get_loc(idx[1], 'pad',\n tolerance=timedelta(0)) == 1\n\n with tm.assert_raises_regex(ValueError, 'must be convertible'):\n idx.get_loc(idx[1], method='nearest', tolerance='foo')\n\n for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]:\n assert idx.get_loc('1 day 1 hour', method) == loc\n\n def test_get_loc_nat(self):\n tidx = TimedeltaIndex(['1 days 01:00:00', 'NaT', '2 days 01:00:00'])\n\n assert tidx.get_loc(pd.NaT) == 1\n assert tidx.get_loc(None) == 1\n assert tidx.get_loc(float('nan')) == 1\n assert tidx.get_loc(np.nan) == 1\n\n def test_get_indexer(self):\n idx = pd.to_timedelta(['0 days', '1 days', '2 days'])\n tm.assert_numpy_array_equal(idx.get_indexer(idx),\n np.array([0, 1, 2], dtype=np.intp))\n\n target = pd.to_timedelta(['-1 hour', '12 hours', '1 day 1 hour'])\n tm.assert_numpy_array_equal(idx.get_indexer(target, 'pad'),\n np.array([-1, 0, 1], dtype=np.intp))\n tm.assert_numpy_array_equal(idx.get_indexer(target, 'backfill'),\n np.array([0, 1, 2], dtype=np.intp))\n tm.assert_numpy_array_equal(idx.get_indexer(target, 'nearest'),\n np.array([0, 1, 1], dtype=np.intp))\n\n res = idx.get_indexer(target, 'nearest',\n tolerance=pd.Timedelta('1 hour'))\n tm.assert_numpy_array_equal(res, np.array([0, -1, 1], dtype=np.intp))\n\n def test_numeric_compat(self):\n\n idx = self._holder(np.arange(5, dtype='int64'))\n didx = self._holder(np.arange(5, dtype='int64') ** 2)\n result = idx * 1\n tm.assert_index_equal(result, idx)\n\n result = 1 * idx\n tm.assert_index_equal(result, idx)\n\n result = idx / 1\n tm.assert_index_equal(result, idx)\n\n result = idx // 1\n tm.assert_index_equal(result, idx)\n\n result = idx * np.array(5, dtype='int64')\n tm.assert_index_equal(result,\n self._holder(np.arange(5, dtype='int64') * 5))\n\n result = idx * np.arange(5, dtype='int64')\n tm.assert_index_equal(result, didx)\n\n result = idx * Series(np.arange(5, dtype='int64'))\n tm.assert_index_equal(result, didx)\n\n result = idx * Series(np.arange(5, dtype='float64') + 0.1)\n tm.assert_index_equal(result, self._holder(np.arange(\n 5, dtype='float64') * (np.arange(5, dtype='float64') + 0.1)))\n\n # invalid\n pytest.raises(TypeError, lambda: idx * idx)\n pytest.raises(ValueError, lambda: idx * self._holder(np.arange(3)))\n pytest.raises(ValueError, lambda: idx * np.array([1, 2]))\n\n def test_pickle_compat_construction(self):\n pass\n\n def test_ufunc_coercions(self):\n # normal ops are also tested in tseries/test_timedeltas.py\n idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'],\n freq='2H', name='x')\n\n for result in [idx * 2, np.multiply(idx, 2)]:\n assert isinstance(result, TimedeltaIndex)\n exp = TimedeltaIndex(['4H', '8H', '12H', '16H', '20H'],\n freq='4H', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == '4H'\n\n for result in [idx / 2, np.divide(idx, 2)]:\n assert isinstance(result, TimedeltaIndex)\n exp = TimedeltaIndex(['1H', '2H', '3H', '4H', '5H'],\n freq='H', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == 'H'\n\n idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'],\n freq='2H', name='x')\n for result in [-idx, np.negative(idx)]:\n assert isinstance(result, TimedeltaIndex)\n exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'],\n freq='-2H', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == '-2H'\n\n idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'],\n freq='H', name='x')\n for result in [abs(idx), np.absolute(idx)]:\n assert isinstance(result, TimedeltaIndex)\n exp = TimedeltaIndex(['2H', '1H', '0H', '1H', '2H'],\n freq=None, name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq is None\n\n def test_fillna_timedelta(self):\n # GH 11343\n idx = pd.TimedeltaIndex(['1 day', pd.NaT, '3 day'])\n\n exp = pd.TimedeltaIndex(['1 day', '2 day', '3 day'])\n tm.assert_index_equal(idx.fillna(pd.Timedelta('2 day')), exp)\n\n exp = pd.TimedeltaIndex(['1 day', '3 hour', '3 day'])\n idx.fillna(pd.Timedelta('3 hour'))\n\n exp = pd.Index(\n [pd.Timedelta('1 day'), 'x', pd.Timedelta('3 day')], dtype=object)\n tm.assert_index_equal(idx.fillna('x'), exp)\n\n def test_difference_freq(self):\n # GH14323: Difference of TimedeltaIndex should not preserve frequency\n\n index = timedelta_range(\"0 days\", \"5 days\", freq=\"D\")\n\n other = timedelta_range(\"1 days\", \"4 days\", freq=\"D\")\n expected = TimedeltaIndex([\"0 days\", \"5 days\"], freq=None)\n idx_diff = index.difference(other)\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal('freq', idx_diff, expected)\n\n other = timedelta_range(\"2 days\", \"5 days\", freq=\"D\")\n idx_diff = index.difference(other)\n expected = TimedeltaIndex([\"0 days\", \"1 days\"], freq=None)\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal('freq', idx_diff, expected)\n\n def test_take(self):\n\n tds = ['1day 02:00:00', '1 day 04:00:00', '1 day 10:00:00']\n idx = TimedeltaIndex(start='1d', end='2d', freq='H', name='idx')\n expected = TimedeltaIndex(tds, freq=None, name='idx')\n\n taken1 = idx.take([2, 4, 10])\n taken2 = idx[[2, 4, 10]]\n\n for taken in [taken1, taken2]:\n tm.assert_index_equal(taken, expected)\n assert isinstance(taken, TimedeltaIndex)\n assert taken.freq is None\n assert taken.name == expected.name\n\n def test_take_fill_value(self):\n # GH 12631\n idx = pd.TimedeltaIndex(['1 days', '2 days', '3 days'],\n name='xxx')\n result = idx.take(np.array([1, 0, -1]))\n expected = pd.TimedeltaIndex(['2 days', '1 days', '3 days'],\n name='xxx')\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = idx.take(np.array([1, 0, -1]), fill_value=True)\n expected = pd.TimedeltaIndex(['2 days', '1 days', 'NaT'],\n name='xxx')\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False,\n fill_value=True)\n expected = pd.TimedeltaIndex(['2 days', '1 days', '3 days'],\n name='xxx')\n tm.assert_index_equal(result, expected)\n\n msg = ('When allow_fill=True and fill_value is not None, '\n 'all indices must be >= -1')\n with tm.assert_raises_regex(ValueError, msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with tm.assert_raises_regex(ValueError, msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n with pytest.raises(IndexError):\n idx.take(np.array([1, -5]))\n\n def test_isin(self):\n\n index = tm.makeTimedeltaIndex(4)\n result = index.isin(index)\n assert result.all()\n\n result = index.isin(list(index))\n assert result.all()\n\n assert_almost_equal(index.isin([index[2], 5]),\n np.array([False, False, True, False]))\n\n def test_factorize(self):\n idx1 = TimedeltaIndex(['1 day', '1 day', '2 day', '2 day', '3 day',\n '3 day'])\n\n exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)\n exp_idx = TimedeltaIndex(['1 day', '2 day', '3 day'])\n\n arr, idx = idx1.factorize()\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n\n arr, idx = idx1.factorize(sort=True)\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n\n # freq must be preserved\n idx3 = timedelta_range('1 day', periods=4, freq='s')\n exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)\n arr, idx = idx3.factorize()\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, idx3)\n\n def test_join_self(self):\n\n index = timedelta_range('1 day', periods=10)\n kinds = 'outer', 'inner', 'left', 'right'\n for kind in kinds:\n joined = index.join(index, how=kind)\n tm.assert_index_equal(index, joined)\n\n def test_slice_keeps_name(self):\n\n # GH4226\n dr = pd.timedelta_range('1d', '5d', freq='H', name='timebucket')\n assert dr[1:].name == dr.name\n\n def test_does_not_convert_mixed_integer(self):\n df = tm.makeCustomDataframe(10, 10,\n data_gen_f=lambda *args, **kwargs: randn(),\n r_idx_type='i', c_idx_type='td')\n str(df)\n\n cols = df.columns.join(df.index, how='outer')\n joined = cols.join(df.columns)\n assert cols.dtype == np.dtype('O')\n assert cols.dtype == joined.dtype\n tm.assert_index_equal(cols, joined)\n\n def test_sort_values(self):\n\n idx = TimedeltaIndex(['4d', '1d', '2d'])\n\n ordered = idx.sort_values()\n assert ordered.is_monotonic\n\n ordered = idx.sort_values(ascending=False)\n assert ordered[::-1].is_monotonic\n\n ordered, dexer = idx.sort_values(return_indexer=True)\n assert ordered.is_monotonic\n\n tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0]),\n check_dtype=False)\n\n ordered, dexer = idx.sort_values(return_indexer=True, ascending=False)\n assert ordered[::-1].is_monotonic\n\n tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1]),\n check_dtype=False)\n\n def test_get_duplicates(self):\n idx = TimedeltaIndex(['1 day', '2 day', '2 day', '3 day', '3day',\n '4day'])\n\n result = idx.get_duplicates()\n ex = TimedeltaIndex(['2 day', '3day'])\n tm.assert_index_equal(result, ex)\n\n def test_argmin_argmax(self):\n idx = TimedeltaIndex(['1 day 00:00:05', '1 day 00:00:01',\n '1 day 00:00:02'])\n assert idx.argmin() == 1\n assert idx.argmax() == 0\n\n def test_misc_coverage(self):\n\n rng = timedelta_range('1 day', periods=5)\n result = rng.groupby(rng.days)\n assert isinstance(list(result.values())[0][0], Timedelta)\n\n idx = TimedeltaIndex(['3d', '1d', '2d'])\n assert not idx.equals(list(idx))\n\n non_td = Index(list('abc'))\n assert not idx.equals(list(non_td))\n\n def test_map(self):\n\n rng = timedelta_range('1 day', periods=10)\n\n f = lambda x: x.days\n result = rng.map(f)\n exp = Int64Index([f(x) for x in rng])\n tm.assert_index_equal(result, exp)\n\n def test_comparisons_nat(self):\n\n tdidx1 = pd.TimedeltaIndex(['1 day', pd.NaT, '1 day 00:00:01', pd.NaT,\n '1 day 00:00:01', '5 day 00:00:03'])\n tdidx2 = pd.TimedeltaIndex(['2 day', '2 day', pd.NaT, pd.NaT,\n '1 day 00:00:02', '5 days 00:00:03'])\n tdarr = np.array([np.timedelta64(2, 'D'),\n np.timedelta64(2, 'D'), np.timedelta64('nat'),\n np.timedelta64('nat'),\n np.timedelta64(1, 'D') + np.timedelta64(2, 's'),\n np.timedelta64(5, 'D') + np.timedelta64(3, 's')])\n\n if _np_version_under1p8:\n # cannot test array because np.datetime('nat') returns today's date\n cases = [(tdidx1, tdidx2)]\n else:\n cases = [(tdidx1, tdidx2), (tdidx1, tdarr)]\n\n # Check pd.NaT is handles as the same as np.nan\n for idx1, idx2 in cases:\n\n result = idx1 < idx2\n expected = np.array([True, False, False, False, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx2 > idx1\n expected = np.array([True, False, False, False, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 <= idx2\n expected = np.array([True, False, False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx2 >= idx1\n expected = np.array([True, False, False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 == idx2\n expected = np.array([False, False, False, False, False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 != idx2\n expected = np.array([True, True, True, True, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n def test_comparisons_coverage(self):\n rng = timedelta_range('1 days', periods=10)\n\n result = rng < rng[3]\n exp = np.array([True, True, True] + [False] * 7)\n tm.assert_numpy_array_equal(result, exp)\n\n # raise TypeError for now\n pytest.raises(TypeError, rng.__lt__, rng[3].value)\n\n result = rng == list(rng)\n exp = rng == rng\n tm.assert_numpy_array_equal(result, exp)\n\n def test_total_seconds(self):\n # GH 10939\n # test index\n rng = timedelta_range('1 days, 10:11:12.100123456', periods=2,\n freq='s')\n expt = [1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456. / 1e9,\n 1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456. / 1e9]\n tm.assert_almost_equal(rng.total_seconds(), Index(expt))\n\n # test Series\n s = Series(rng)\n s_expt = Series(expt, index=[0, 1])\n tm.assert_series_equal(s.dt.total_seconds(), s_expt)\n\n # with nat\n s[1] = np.nan\n s_expt = Series([1 * 86400 + 10 * 3600 + 11 * 60 +\n 12 + 100123456. / 1e9, np.nan], index=[0, 1])\n tm.assert_series_equal(s.dt.total_seconds(), s_expt)\n\n # with both nat\n s = Series([np.nan, np.nan], dtype='timedelta64[ns]')\n tm.assert_series_equal(s.dt.total_seconds(),\n Series([np.nan, np.nan], index=[0, 1]))\n\n def test_pass_TimedeltaIndex_to_index(self):\n\n rng = timedelta_range('1 days', '10 days')\n idx = Index(rng, dtype=object)\n\n expected = Index(rng.to_pytimedelta(), dtype=object)\n\n tm.assert_numpy_array_equal(idx.values, expected.values)\n\n def test_pickle(self):\n\n rng = timedelta_range('1 days', periods=10)\n rng_p = tm.round_trip_pickle(rng)\n tm.assert_index_equal(rng, rng_p)\n\n def test_hash_error(self):\n index = timedelta_range('1 days', periods=10)\n with tm.assert_raises_regex(TypeError, \"unhashable type: %r\" %\n type(index).__name__):\n hash(index)\n\n def test_append_join_nondatetimeindex(self):\n rng = timedelta_range('1 days', periods=10)\n idx = Index(['a', 'b', 'c', 'd'])\n\n result = rng.append(idx)\n assert isinstance(result[0], Timedelta)\n\n # it works\n rng.join(idx, how='outer')\n\n def test_append_numpy_bug_1681(self):\n\n td = timedelta_range('1 days', '10 days', freq='2D')\n a = DataFrame()\n c = DataFrame({'A': 'foo', 'B': td}, index=td)\n str(c)\n\n result = a.append(c)\n assert (result['B'] == td).all()\n\n def test_fields(self):\n rng = timedelta_range('1 days, 10:11:12.100123456', periods=2,\n freq='s')\n tm.assert_index_equal(rng.days, Index([1, 1], dtype='int64'))\n tm.assert_index_equal(\n rng.seconds,\n Index([10 * 3600 + 11 * 60 + 12, 10 * 3600 + 11 * 60 + 13],\n dtype='int64'))\n tm.assert_index_equal(\n rng.microseconds,\n Index([100 * 1000 + 123, 100 * 1000 + 123], dtype='int64'))\n tm.assert_index_equal(rng.nanoseconds,\n Index([456, 456], dtype='int64'))\n\n pytest.raises(AttributeError, lambda: rng.hours)\n pytest.raises(AttributeError, lambda: rng.minutes)\n pytest.raises(AttributeError, lambda: rng.milliseconds)\n\n # with nat\n s = Series(rng)\n s[1] = np.nan\n\n tm.assert_series_equal(s.dt.days, Series([1, np.nan], index=[0, 1]))\n tm.assert_series_equal(s.dt.seconds, Series(\n [10 * 3600 + 11 * 60 + 12, np.nan], index=[0, 1]))\n\n # preserve name (GH15589)\n rng.name = 'name'\n assert rng.days.name == 'name'\n\n def test_freq_conversion(self):\n\n # doc example\n\n # series\n td = Series(date_range('20130101', periods=4)) - \\\n Series(date_range('20121201', periods=4))\n td[2] += timedelta(minutes=5, seconds=3)\n td[3] = np.nan\n\n result = td / np.timedelta64(1, 'D')\n expected = Series([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan\n ])\n assert_series_equal(result, expected)\n\n result = td.astype('timedelta64[D]')\n expected = Series([31, 31, 31, np.nan])\n assert_series_equal(result, expected)\n\n result = td / np.timedelta64(1, 's')\n expected = Series([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3,\n np.nan])\n assert_series_equal(result, expected)\n\n result = td.astype('timedelta64[s]')\n assert_series_equal(result, expected)\n\n # tdi\n td = TimedeltaIndex(td)\n\n result = td / np.timedelta64(1, 'D')\n expected = Index([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan])\n assert_index_equal(result, expected)\n\n result = td.astype('timedelta64[D]')\n expected = Index([31, 31, 31, np.nan])\n assert_index_equal(result, expected)\n\n result = td / np.timedelta64(1, 's')\n expected = Index([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3,\n np.nan])\n assert_index_equal(result, expected)\n\n result = td.astype('timedelta64[s]')\n assert_index_equal(result, expected)\n\n\nclass TestSlicing(object):\n @pytest.mark.parametrize('freq', ['B', 'D'])\n def test_timedelta(self, freq):\n index = date_range('1/1/2000', periods=50, freq=freq)\n\n shifted = index + timedelta(1)\n back = shifted + timedelta(-1)\n tm.assert_index_equal(index, back)\n\n if freq == 'D':\n expected = pd.tseries.offsets.Day(1)\n assert index.freq == expected\n assert shifted.freq == expected\n assert back.freq == expected\n else: # freq == 'B'\n assert index.freq == pd.tseries.offsets.BusinessDay(1)\n assert shifted.freq is None\n assert back.freq == pd.tseries.offsets.BusinessDay(1)\n\n result = index - timedelta(1)\n expected = index + timedelta(-1)\n tm.assert_index_equal(result, expected)\n\n # GH4134, buggy with timedeltas\n rng = date_range('2013', '2014')\n s = Series(rng)\n result1 = rng - pd.offsets.Hour(1)\n result2 = DatetimeIndex(s - np.timedelta64(100000000))\n result3 = rng - np.timedelta64(100000000)\n result4 = DatetimeIndex(s - pd.offsets.Hour(1))\n tm.assert_index_equal(result1, result4)\n tm.assert_index_equal(result2, result3)\n\n\nclass TestTimeSeries(object):\n _multiprocess_can_split_ = True\n\n def test_series_box_timedelta(self):\n rng = timedelta_range('1 day 1 s', periods=5, freq='h')\n s = Series(rng)\n assert isinstance(s[1], Timedelta)\n assert isinstance(s.iat[2], Timedelta)\n"
] |
[
[
"pandas.tseries.offsets.Day",
"pandas.Series",
"pandas.DataFrame",
"numpy.dtype",
"pandas.util.testing.assert_index_equal",
"pandas.util.testing.round_trip_pickle",
"numpy.negative",
"numpy.divide",
"pandas.util.testing.assert_numpy_array_equal",
"numpy.arange",
"pandas.Index",
"pandas.util.testing.assert_series_equal",
"pandas.util.testing.assert_attr_equal",
"numpy.multiply",
"pandas.Timedelta",
"numpy.timedelta64",
"pandas.tseries.offsets.BusinessDay",
"pandas.date_range",
"pandas.util.testing.makeTimedeltaIndex",
"numpy.array",
"pandas.timedelta_range",
"numpy.absolute",
"pandas.TimedeltaIndex",
"pandas.util.testing.assert_raises_regex",
"pandas.to_timedelta",
"pandas.offsets.Hour"
]
] |
ZhengPeng7/GLCNet
|
[
"5ec7d4eb0ddece3f789df0b25f414bc4b5ac1d9e"
] |
[
"models/seqnet.py"
] |
[
"from copy import deepcopy\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection.roi_heads import RoIHeads\nfrom torchvision.models.detection.rpn import AnchorGenerator, RegionProposalNetwork, RPNHead\nfrom torchvision.models.detection.transform import GeneralizedRCNNTransform\nfrom torchvision.ops import MultiScaleRoIAlign\nfrom torchvision.ops import boxes as box_ops\n\nfrom models.oim import OIMLoss\nfrom models.resnet import build_resnet\nfrom config import Config\nfrom models.modules import SpatialGroupEnhance, SEAttention\n\n\nclass SeqNet(nn.Module):\n def __init__(self, cfg):\n super(SeqNet, self).__init__()\n\n backbone, box_head = build_resnet(name=\"resnet50\", pretrained=True)\n\n anchor_generator = AnchorGenerator(\n sizes=((32, 64, 128, 256, 512),), aspect_ratios=((0.5, 1.0, 2.0),)\n )\n head = RPNHead(\n in_channels=backbone.out_channels,\n num_anchors=anchor_generator.num_anchors_per_location()[0],\n )\n pre_nms_top_n = dict(\n training=cfg.MODEL.RPN.PRE_NMS_TOPN_TRAIN, testing=cfg.MODEL.RPN.PRE_NMS_TOPN_TEST\n )\n post_nms_top_n = dict(\n training=cfg.MODEL.RPN.POST_NMS_TOPN_TRAIN, testing=cfg.MODEL.RPN.POST_NMS_TOPN_TEST\n )\n rpn = RegionProposalNetwork(\n anchor_generator=anchor_generator,\n head=head,\n fg_iou_thresh=cfg.MODEL.RPN.POS_THRESH_TRAIN,\n bg_iou_thresh=cfg.MODEL.RPN.NEG_THRESH_TRAIN,\n batch_size_per_image=cfg.MODEL.RPN.BATCH_SIZE_TRAIN,\n positive_fraction=cfg.MODEL.RPN.POS_FRAC_TRAIN,\n pre_nms_top_n=pre_nms_top_n,\n post_nms_top_n=post_nms_top_n,\n nms_thresh=cfg.MODEL.RPN.NMS_THRESH,\n )\n\n faster_rcnn_predictor = FastRCNNPredictor(2048, 2)\n reid_head = deepcopy(box_head)\n box_roi_pool = MultiScaleRoIAlign(\n featmap_names=[\"feat_res4\"], output_size=14, sampling_ratio=2\n )\n box_predictor = BBoxRegressor(2048, num_classes=2, bn_neck=cfg.MODEL.ROI_HEAD.BN_NECK)\n\n fusion_layers_att = []\n fusion_layers_mlp = []\n fusion_layers_conv = []\n if Config().cxt_feat or Config().psn_feat:\n if Config().cxt_feat:\n if Config().conv_before_fusion_scenario:\n self.cxt_feat_extractor_scenario = nn.Sequential(\n nn.Conv2d(1024, 256, 3, 1, 1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, 3, 1, 1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, Config().cxt_feat_len, 3, 1, 1),\n nn.BatchNorm2d(Config().cxt_feat_len),\n nn.ReLU(inplace=True),\n nn.AdaptiveMaxPool2d(1)\n )\n else:\n self.cxt_feat_extractor_scenario = nn.Sequential(\n nn.AdaptiveMaxPool2d(1)\n )\n if Config().psn_feat:\n if Config().conv_before_fusion_psn:\n self.cxt_feat_extractor_psn = nn.Sequential(\n nn.Conv2d(2048, 256, 1, 1, 0),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, 1, 1, 0),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, Config().psn_feat_len, 3, 1, 1),\n nn.BatchNorm2d(Config().psn_feat_len),\n nn.ReLU(inplace=True),\n nn.AdaptiveMaxPool2d(1)\n )\n else:\n self.cxt_feat_extractor_psn = nn.Sequential(\n nn.AdaptiveMaxPool2d(1)\n )\n if Config().use_fusion:\n if Config().fusion_attention == 'sea':\n fusion_layers_att.append(\n SEAttention(Config().feat_cxt_reid_len)\n )\n channel_opt = 2048\n for k, v in Config().fusion_style.items():\n for idx_layer in range(v):\n if not idx_layer:\n channel_ipt = Config().feat_cxt_reid_len\n else:\n channel_ipt = channel_opt\n if k == 'mlp':\n fusion_layers_mlp.append(nn.Linear(channel_ipt, channel_opt))\n if Config().relu_after_mlp:\n fusion_layers_mlp.append(nn.ReLU(inplace=True))\n elif k == 'conv':\n fusion_layers_conv.append(nn.Conv1d(channel_ipt, channel_opt, 1, 1))\n if Config().bnRelu_after_conv:\n fusion_layers_conv.append(nn.BatchNorm1d(channel_opt))\n fusion_layers_conv.append(nn.ReLU(inplace=True))\n self.fuser_att = nn.Sequential(*fusion_layers_att)\n self.fuser_mlp = nn.Sequential(*fusion_layers_mlp)\n self.fuser_conv = nn.Sequential(*fusion_layers_conv)\n self.fuser = [self.fuser_att, self.fuser_mlp, self.fuser_conv]\n roi_heads = SeqRoIHeads(\n # OIM\n num_pids=cfg.MODEL.LOSS.LUT_SIZE,\n num_cq_size=cfg.MODEL.LOSS.CQ_SIZE,\n oim_momentum=cfg.MODEL.LOSS.OIM_MOMENTUM,\n oim_scalar=cfg.MODEL.LOSS.OIM_SCALAR,\n # SeqNet\n faster_rcnn_predictor=faster_rcnn_predictor,\n reid_head=reid_head,\n # parent class\n box_roi_pool=box_roi_pool,\n box_head=box_head,\n box_predictor=box_predictor,\n fg_iou_thresh=cfg.MODEL.ROI_HEAD.POS_THRESH_TRAIN,\n bg_iou_thresh=cfg.MODEL.ROI_HEAD.NEG_THRESH_TRAIN,\n batch_size_per_image=cfg.MODEL.ROI_HEAD.BATCH_SIZE_TRAIN,\n positive_fraction=cfg.MODEL.ROI_HEAD.POS_FRAC_TRAIN,\n bbox_reg_weights=None,\n score_thresh=cfg.MODEL.ROI_HEAD.SCORE_THRESH_TEST,\n nms_thresh=cfg.MODEL.ROI_HEAD.NMS_THRESH_TEST,\n detections_per_img=cfg.MODEL.ROI_HEAD.DETECTIONS_PER_IMAGE_TEST,\n cxt_feat_extractor_scenario=self.cxt_feat_extractor_scenario if Config().cxt_feat else None,\n cxt_feat_extractor_psn=self.cxt_feat_extractor_psn if Config().psn_feat else None,\n fuser=self.fuser if Config().use_fusion else [[], [], []],\n )\n\n transform = GeneralizedRCNNTransform(\n min_size=cfg.INPUT.MIN_SIZE,\n max_size=cfg.INPUT.MAX_SIZE,\n image_mean=[0.485, 0.456, 0.406],\n image_std=[0.229, 0.224, 0.225],\n )\n\n self.backbone = backbone\n self.rpn = rpn\n self.roi_heads = roi_heads\n self.transform = transform\n\n # loss weights\n self.lw_rpn_reg = cfg.SOLVER.LW_RPN_REG\n self.lw_rpn_cls = cfg.SOLVER.LW_RPN_CLS\n self.lw_proposal_reg = cfg.SOLVER.LW_PROPOSAL_REG\n self.lw_proposal_cls = cfg.SOLVER.LW_PROPOSAL_CLS\n self.lw_box_reg = cfg.SOLVER.LW_BOX_REG\n self.lw_box_cls = cfg.SOLVER.LW_BOX_CLS\n self.lw_box_reid = cfg.SOLVER.LW_BOX_REID\n\n def inference(self, images, targets=None, query_img_as_gallery=False):\n \"\"\"\n query_img_as_gallery: Set to True to detect all people in the query image.\n Meanwhile, the gt box should be the first of the detected boxes.\n This option serves CBGM.\n \"\"\"\n original_image_sizes = [img.shape[-2:] for img in images]\n images, targets = self.transform(images, targets)\n features = self.backbone(images.tensors)\n\n if query_img_as_gallery:\n assert targets is not None\n\n if targets is not None and not query_img_as_gallery:\n # query\n boxes = [t[\"boxes\"] for t in targets]\n box_features = self.roi_heads.box_roi_pool(features, boxes, images.image_sizes)\n box_features = self.roi_heads.reid_head(box_features)\n if Config().cxt_feat or Config().psn_feat:\n feat_res5_ori = box_features['feat_res5']\n if Config().cxt_feat:\n cxt_feat_scenario = self.cxt_feat_extractor_scenario(features['feat_res4']).squeeze(-1)\n cxt_feat_scenario_proposalNum = torch.cat([\n cxt_feat_scenario[idx_bs].unsqueeze(0).repeat(box.shape[0], 1, 1) for idx_bs, box in enumerate(boxes)\n ], dim=0)\n if Config().nae_multi:\n box_features['cxt_scenario'] = cxt_feat_scenario_proposalNum.unsqueeze(-1)\n else:\n box_features[\"feat_res5\"] = torch.cat([box_features[\"feat_res5\"], cxt_feat_scenario_proposalNum.unsqueeze(-1)], 1)\n if Config().psn_feat:\n feat_res5_per_image = []\n num_box = 0\n for box in boxes:\n feat_res5_per_image.append(feat_res5_ori[num_box:num_box+box.shape[0]])\n num_box += box.shape[0]\n cxt_feat_psn_per_image = []\n for feat_res5 in feat_res5_per_image:\n cxt_feat_psn_per_image.append(torch.mean(feat_res5 * 1, dim=0).unsqueeze(0))\n cxt_feat_psn_per_image = torch.cat(cxt_feat_psn_per_image, dim=0)\n cxt_feat_psn_per_image = self.cxt_feat_extractor_psn(cxt_feat_psn_per_image)\n cxt_feat_psn_proposalNum = torch.cat([\n cxt_feat_psn_per_image[idx_bs].repeat(box.shape[0], 1, 1, 1) for idx_bs, box in enumerate(boxes)\n ], dim=0)\n if Config().nae_multi:\n box_features['cxt_psn'] = cxt_feat_psn_proposalNum\n else:\n box_features[\"feat_res5\"] = torch.cat([box_features[\"feat_res5\"], cxt_feat_psn_proposalNum], 1)\n if not Config().nae_multi:\n if self.fuser_att:\n box_features[\"feat_res5\"] = self.fuser_att(box_features[\"feat_res5\"])\n if self.fuser_mlp:\n box_features[\"feat_res5\"] = self.fuser_mlp(box_features[\"feat_res5\"].squeeze(-1).squeeze(-1)).unsqueeze(-1).unsqueeze(-1)\n elif self.fuser_conv:\n box_features[\"feat_res5\"] = self.fuser_conv(box_features[\"feat_res5\"].squeeze(-1)).unsqueeze(-1)\n embeddings, _ = self.roi_heads.embedding_head(box_features if Config().nae_mix_res4 or Config().nae_multi else OrderedDict([['feat_res5', box_features[\"feat_res5\"]]]))\n return embeddings.split(1, 0)\n else:\n # gallery\n proposals, _ = self.rpn(images, features, targets)\n detections, _ = self.roi_heads(\n features, proposals, images.image_sizes, targets, query_img_as_gallery\n )\n detections = self.transform.postprocess(\n detections, images.image_sizes, original_image_sizes\n )\n return detections\n\n def forward(self, images, targets=None, query_img_as_gallery=False):\n if not self.training:\n return self.inference(images, targets, query_img_as_gallery)\n\n images, targets = self.transform(images, targets)\n features = self.backbone(images.tensors)\n proposals, proposal_losses = self.rpn(images, features, targets)\n _, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)\n\n # rename rpn losses to be consistent with detection losses\n proposal_losses[\"loss_rpn_reg\"] = proposal_losses.pop(\"loss_rpn_box_reg\")\n proposal_losses[\"loss_rpn_cls\"] = proposal_losses.pop(\"loss_objectness\")\n\n losses = {}\n losses.update(detector_losses)\n losses.update(proposal_losses)\n\n # apply loss weights\n losses[\"loss_rpn_reg\"] *= self.lw_rpn_reg\n losses[\"loss_rpn_cls\"] *= self.lw_rpn_cls\n losses[\"loss_proposal_reg\"] *= self.lw_proposal_reg\n losses[\"loss_proposal_cls\"] *= self.lw_proposal_cls\n losses[\"loss_box_reg\"] *= self.lw_box_reg\n losses[\"loss_box_cls\"] *= self.lw_box_cls\n losses[\"loss_box_reid\"] *= self.lw_box_reid\n return losses\n\n\nclass SeqRoIHeads(RoIHeads):\n def __init__(\n self,\n num_pids,\n num_cq_size,\n oim_momentum,\n oim_scalar,\n faster_rcnn_predictor,\n reid_head,\n cxt_feat_extractor_scenario,\n cxt_feat_extractor_psn,\n fuser,\n *args,\n **kwargs\n ):\n super(SeqRoIHeads, self).__init__(*args, **kwargs)\n if not Config().nae_multi:\n if Config().nae_mix_res4:\n featmap_names = ['feat_res4', 'feat_res5']\n in_channels=[1024, Config().nae_norm2_len]\n else:\n featmap_names = ['feat_res5']\n in_channels=[Config().nae_norm2_len]\n else:\n featmap_names = ['feat_res4', 'feat_res5']\n in_channels=[1024, Config().nae_norm2_len]\n if Config().cxt_feat:\n featmap_names.append('cxt_scenario')\n in_channels.append(Config().cxt_feat_len)\n if Config().psn_feat:\n featmap_names.append('cxt_psn')\n in_channels.append(Config().psn_feat_len)\n self.embedding_head = NormAwareEmbedding(\n featmap_names=featmap_names,\n in_channels=in_channels\n )\n self.reid_loss = OIMLoss(sum(Config().nae_dims), num_pids, num_cq_size, oim_momentum, oim_scalar)\n self.faster_rcnn_predictor = faster_rcnn_predictor\n self.reid_head = reid_head\n # rename the method inherited from parent class\n self.postprocess_proposals = self.postprocess_detections\n self.cxt_feat_extractor_scenario = cxt_feat_extractor_scenario\n self.cxt_feat_extractor_psn = cxt_feat_extractor_psn\n self.fuser_att, self.fuser_mlp, self.fuser_conv = fuser\n\n def forward(self, features, proposals, image_shapes, targets=None, query_img_as_gallery=False):\n \"\"\"\n Arguments:\n features (List[Tensor])\n proposals (List[Tensor[N, 4]])\n image_shapes (List[Tuple[H, W]])\n targets (List[Dict])\n \"\"\"\n if self.training:\n proposals, _, proposal_pid_labels, proposal_reg_targets = self.select_training_samples(\n proposals, targets\n )\n\n # ------------------- Faster R-CNN head ------------------ #\n proposal_features = self.box_roi_pool(features, proposals, image_shapes)\n proposal_features = self.box_head(proposal_features)\n proposal_cls_scores, proposal_regs = self.faster_rcnn_predictor(\n proposal_features[\"feat_res5\"]\n )\n\n if self.training:\n boxes = self.get_boxes(proposal_regs, proposals, image_shapes)\n boxes = [boxes_per_image.detach() for boxes_per_image in boxes]\n boxes, _, box_pid_labels, box_reg_targets = self.select_training_samples(boxes, targets)\n else:\n # invoke the postprocess method inherited from parent class to process proposals\n boxes, scores, _ = self.postprocess_proposals(\n proposal_cls_scores, proposal_regs, proposals, image_shapes\n )\n \n if Config().psn_feat:\n if self.training:\n psn_selections = []\n for box_pid_label in box_pid_labels:\n if Config().psn_feat_labelledOnly:\n psn_selections.append((0 < box_pid_label < 5555).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1))\n else:\n psn_selections.append((box_pid_label > 0).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1))\n else:\n psn_selections = None\n\n cws = True\n gt_det = None\n if not self.training and query_img_as_gallery:\n # When regarding the query image as gallery, GT boxes may be excluded\n # from detected boxes. To avoid this, we compulsorily include GT in the\n # detection results. Additionally, CWS should be disabled as the\n # confidences of these people in query image are 1\n cws = False\n gt_box = [targets[0][\"boxes\"]]\n gt_box_features = self.box_roi_pool(features, gt_box, image_shapes)\n gt_box_features = self.reid_head(gt_box_features)\n feat_res5_ori = gt_box_features['feat_res5']\n if Config().cxt_feat:\n cxt_feat_scenario = self.cxt_feat_extractor_scenario(features['feat_res4']).squeeze(-1)\n cxt_feat_scenario_proposalNum = torch.cat([\n cxt_feat_scenario[idx_bs].unsqueeze(0).repeat(box.shape[0], 1, 1) for idx_bs, box in enumerate(gt_box)\n ], dim=0)\n if Config().nae_multi:\n gt_box_features['cxt_scenario'] = cxt_feat_scenario_proposalNum.unsqueeze(-1)\n else:\n gt_box_features[\"feat_res5\"] = torch.cat([gt_box_features[\"feat_res5\"], cxt_feat_scenario_proposalNum.unsqueeze(-1)], 1)\n if Config().psn_feat:\n feat_res5_per_image = []\n num_box = 0\n for box in boxes:\n feat_res5_per_image.append(feat_res5_ori[num_box:num_box+box.shape[0]])\n num_box += box.shape[0]\n cxt_feat_psn_per_image = []\n for feat_res5 in feat_res5_per_image:\n cxt_feat_psn_per_image.append(torch.mean(feat_res5 * 1, dim=0).unsqueeze(0))\n cxt_feat_psn_per_image = torch.cat(cxt_feat_psn_per_image, dim=0)\n cxt_feat_psn_per_image = self.cxt_feat_extractor_psn(cxt_feat_psn_per_image)\n cxt_feat_psn_proposalNum = torch.cat([\n cxt_feat_psn_per_image[idx_bs].repeat(box.shape[0], 1, 1, 1) for idx_bs, box in enumerate(gt_box)\n ], dim=0)\n if Config().nae_multi:\n gt_box_features['cxt_psn'] = cxt_feat_psn_proposalNum\n else:\n gt_box_features[\"feat_res5\"] = torch.cat([gt_box_features[\"feat_res5\"], cxt_feat_psn_proposalNum], 1)\n if not Config().nae_multi:\n if self.fuser_att:\n gt_box_features[\"feat_res5\"] = self.fuser_att(gt_box_features[\"feat_res5\"])\n if self.fuser_mlp:\n gt_box_features[\"feat_res5\"] = self.fuser_mlp(gt_box_features[\"feat_res5\"].squeeze(-1).squeeze(-1)).unsqueeze(-1).unsqueeze(-1)\n elif self.fuser_conv:\n gt_box_features[\"feat_res5\"] = self.fuser_conv(gt_box_features[\"feat_res5\"].squeeze(-1)).unsqueeze(-1)\n embeddings, _ = self.embedding_head(gt_box_features if Config().nae_mix_res4 or Config().nae_multi else OrderedDict([['feat_res5', gt_box_features[\"feat_res5\"]]]))\n gt_det = {\"boxes\": targets[0][\"boxes\"], \"embeddings\": embeddings}\n\n # no detection predicted by Faster R-CNN head in test phase\n if boxes[0].shape[0] == 0:\n assert not self.training\n boxes = gt_det[\"boxes\"] if gt_det else torch.zeros(0, 4)\n labels = torch.ones(1).type_as(boxes) if gt_det else torch.zeros(0)\n scores = torch.ones(1).type_as(boxes) if gt_det else torch.zeros(0)\n embeddings = gt_det[\"embeddings\"] if gt_det else torch.zeros(0, sum(Config().nae_dims))\n return [dict(boxes=boxes, labels=labels, scores=scores, embeddings=embeddings)], []\n\n # --------------------- Baseline head -------------------- #\n box_features = self.box_roi_pool(features, boxes, image_shapes)\n box_features = self.reid_head(box_features)\n box_regs = self.box_predictor(box_features[\"feat_res5\"])\n if Config().cxt_feat or Config().psn_feat:\n feat_res5_ori = box_features['feat_res5']\n if Config().cxt_feat:\n cxt_feat_scenario = self.cxt_feat_extractor_scenario(features['feat_res4']).squeeze(-1)\n cxt_feat_scenario_proposalNum = torch.cat([\n cxt_feat_scenario[idx_bs].unsqueeze(0).repeat(box.shape[0], 1, 1) for idx_bs, box in enumerate(boxes)\n ], dim=0)\n if Config().nae_multi:\n box_features['cxt_scenario'] = cxt_feat_scenario_proposalNum.unsqueeze(-1)\n else:\n box_features[\"feat_res5\"] = torch.cat([box_features[\"feat_res5\"], cxt_feat_scenario_proposalNum.unsqueeze(-1)], 1)\n if Config().psn_feat:\n feat_res5_per_image = []\n num_box = 0\n for box in boxes:\n feat_res5_per_image.append(feat_res5_ori[num_box:num_box+box.shape[0]])\n num_box += box.shape[0]\n cxt_feat_psn_per_image = []\n if psn_selections:\n for feat_res5, psn_selection in zip(feat_res5_per_image, psn_selections):\n cxt_feat_psn_per_image.append(torch.sum(feat_res5 * psn_selection, dim=0).unsqueeze(0) / (torch.sum(psn_selection) + 1e-5))\n else:\n for feat_res5 in feat_res5_per_image:\n cxt_feat_psn_per_image.append(torch.mean(feat_res5 * 1, dim=0).unsqueeze(0))\n cxt_feat_psn_per_image = torch.cat(cxt_feat_psn_per_image, dim=0)\n cxt_feat_psn_per_image = self.cxt_feat_extractor_psn(cxt_feat_psn_per_image)\n cxt_feat_psn_proposalNum = torch.cat([\n cxt_feat_psn_per_image[idx_bs].repeat(box.shape[0], 1, 1, 1) for idx_bs, box in enumerate(boxes)\n ], dim=0)\n if Config().nae_multi:\n box_features['cxt_psn'] = cxt_feat_psn_proposalNum\n else:\n box_features[\"feat_res5\"] = torch.cat([box_features[\"feat_res5\"], cxt_feat_psn_proposalNum], 1)\n if not Config().nae_multi:\n if self.fuser_att:\n box_features[\"feat_res5\"] = self.fuser_att(box_features[\"feat_res5\"])\n if self.fuser_mlp:\n box_features[\"feat_res5\"] = self.fuser_mlp(box_features[\"feat_res5\"].squeeze(-1).squeeze(-1)).unsqueeze(-1).unsqueeze(-1)\n elif self.fuser_conv:\n box_features[\"feat_res5\"] = self.fuser_conv(box_features[\"feat_res5\"].squeeze(-1)).unsqueeze(-1)\n box_embeddings, box_cls_scores = self.embedding_head(box_features if Config().nae_mix_res4 or Config().nae_multi else OrderedDict([['feat_res5', box_features[\"feat_res5\"]]]))\n if box_cls_scores.dim() == 0:\n box_cls_scores = box_cls_scores.unsqueeze(0)\n\n result, losses = [], {}\n if self.training:\n proposal_labels = [y.clamp(0, 1) for y in proposal_pid_labels]\n box_labels = [y.clamp(0, 1) for y in box_pid_labels]\n losses = detection_losses(\n proposal_cls_scores,\n proposal_regs,\n proposal_labels,\n proposal_reg_targets,\n box_cls_scores,\n box_regs,\n box_labels,\n box_reg_targets,\n )\n loss_box_reid = self.reid_loss(box_embeddings, box_pid_labels)\n losses.update(loss_box_reid=loss_box_reid)\n else:\n # The IoUs of these boxes are higher than that of proposals,\n # so a higher NMS threshold is needed\n orig_thresh = self.nms_thresh\n self.nms_thresh = 0.5\n boxes, scores, embeddings, labels = self.postprocess_boxes(\n box_cls_scores,\n box_regs,\n box_embeddings,\n boxes,\n image_shapes,\n fcs=scores,\n gt_det=gt_det,\n cws=cws,\n )\n # set to original thresh after finishing postprocess\n self.nms_thresh = orig_thresh\n num_images = len(boxes)\n for i in range(num_images):\n result.append(\n dict(\n boxes=boxes[i], labels=labels[i], scores=scores[i], embeddings=embeddings[i]\n )\n )\n return result, losses\n\n def get_boxes(self, box_regression, proposals, image_shapes):\n \"\"\"\n Get boxes from proposals.\n \"\"\"\n boxes_per_image = [len(boxes_in_image) for boxes_in_image in proposals]\n pred_boxes = self.box_coder.decode(box_regression, proposals)\n pred_boxes = pred_boxes.split(boxes_per_image, 0)\n\n all_boxes = []\n for boxes, image_shape in zip(pred_boxes, image_shapes):\n boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n # remove predictions with the background label\n boxes = boxes[:, 1:].reshape(-1, 4)\n all_boxes.append(boxes)\n\n return all_boxes\n\n def postprocess_boxes(\n self,\n class_logits,\n box_regression,\n embeddings,\n proposals,\n image_shapes,\n fcs=None,\n gt_det=None,\n cws=True,\n ):\n \"\"\"\n Similar to RoIHeads.postprocess_detections, but can handle embeddings and implement\n First Classification Score (FCS).\n \"\"\"\n device = class_logits.device\n\n boxes_per_image = [len(boxes_in_image) for boxes_in_image in proposals]\n pred_boxes = self.box_coder.decode(box_regression, proposals)\n\n if fcs is not None:\n # Fist Classification Score (FCS)\n pred_scores = fcs[0]\n else:\n pred_scores = torch.sigmoid(class_logits)\n if cws:\n # Confidence Weighted Similarity (CWS)\n embeddings = embeddings * pred_scores.view(-1, 1)\n\n # split boxes and scores per image\n pred_boxes = pred_boxes.split(boxes_per_image, 0)\n pred_scores = pred_scores.split(boxes_per_image, 0)\n pred_embeddings = embeddings.split(boxes_per_image, 0)\n\n all_boxes = []\n all_scores = []\n all_labels = []\n all_embeddings = []\n for boxes, scores, embeddings, image_shape in zip(\n pred_boxes, pred_scores, pred_embeddings, image_shapes\n ):\n boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n\n # create labels for each prediction\n labels = torch.ones(scores.size(0), device=device)\n\n # remove predictions with the background label\n boxes = boxes[:, 1:]\n scores = scores.unsqueeze(1)\n labels = labels.unsqueeze(1)\n\n # batch everything, by making every class prediction be a separate instance\n boxes = boxes.reshape(-1, 4)\n scores = scores.flatten()\n labels = labels.flatten()\n embeddings = embeddings.reshape(-1, self.embedding_head.dim if isinstance(self.embedding_head.dim, int) else sum(self.embedding_head.dim))\n\n # remove low scoring boxes\n inds = torch.nonzero(scores > self.score_thresh).squeeze(1)\n boxes, scores, labels, embeddings = (\n boxes[inds],\n scores[inds],\n labels[inds],\n embeddings[inds],\n )\n\n # remove empty boxes\n keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)\n boxes, scores, labels, embeddings = (\n boxes[keep],\n scores[keep],\n labels[keep],\n embeddings[keep],\n )\n\n if gt_det is not None:\n # include GT into the detection results\n boxes = torch.cat((boxes, gt_det[\"boxes\"]), dim=0)\n labels = torch.cat((labels, torch.tensor([1.0]).to(device)), dim=0)\n scores = torch.cat((scores, torch.tensor([1.0]).to(device)), dim=0)\n embeddings = torch.cat((embeddings, gt_det[\"embeddings\"]), dim=0)\n\n # non-maximum suppression, independently done per class\n keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)\n # keep only topk scoring predictions\n keep = keep[: self.detections_per_img]\n boxes, scores, labels, embeddings = (\n boxes[keep],\n scores[keep],\n labels[keep],\n embeddings[keep],\n )\n\n all_boxes.append(boxes)\n all_scores.append(scores)\n all_labels.append(labels)\n all_embeddings.append(embeddings)\n\n return all_boxes, all_scores, all_embeddings, all_labels\n\n\nclass NormAwareEmbedding(nn.Module):\n \"\"\"\n Implements the Norm-Aware Embedding proposed in\n Chen, Di, et al. \"Norm-aware embedding for efficient person search.\" CVPR 2020.\n \"\"\"\n\n def __init__(self, featmap_names=[\"feat_res4\", \"feat_res5\"], in_channels=[1024, 2048], dim=Config().nae_dims):\n super(NormAwareEmbedding, self).__init__()\n self.featmap_names = featmap_names\n self.in_channels = in_channels\n self.dim = dim\n\n self.projectors = nn.ModuleDict()\n if len(dim) == 1:\n indv_dims = self._split_embedding_dim(self.dim[0])\n else:\n indv_dims = dim\n for ftname, in_channel, indv_dim in zip(self.featmap_names, self.in_channels, indv_dims):\n proj = nn.Sequential(nn.Linear(in_channel, indv_dim), nn.BatchNorm1d(indv_dim))\n init.normal_(proj[0].weight, std=0.01)\n init.normal_(proj[1].weight, std=0.01)\n init.constant_(proj[0].bias, 0)\n init.constant_(proj[1].bias, 0)\n self.projectors[ftname] = proj\n\n self.rescaler = []\n if Config().bn_feature_seperately:\n for _ in dim:\n self.rescaler.append(nn.BatchNorm1d(1, affine=True))\n else:\n self.rescaler = nn.BatchNorm1d(1, affine=True)\n\n def forward(self, featmaps):\n \"\"\"\n Arguments:\n featmaps: OrderedDict[Tensor], and in featmap_names you can choose which\n featmaps to use\n Returns:\n tensor of size (BatchSize, dim), L2 normalized embeddings.\n tensor of size (BatchSize, ) rescaled norm of embeddings, as class_logits.\n \"\"\"\n assert len(featmaps) == len(self.featmap_names)\n if len(featmaps) == 1:\n for k, v in featmaps.items():\n pass\n v = self._flatten_fc_input(v)\n embeddings = self.projectors[k](v)\n norms = embeddings.norm(2, 1, keepdim=True)\n embeddings = embeddings / norms.expand_as(embeddings).clamp(min=1e-12)\n norms = self.rescaler(norms).squeeze()\n return embeddings, norms\n else:\n if Config().bn_feature_seperately:\n embeddings = []\n norms = []\n for idx_fm, (k, v) in enumerate(featmaps.items()):\n v = self._flatten_fc_input(v)\n proj_feat = self.projectors[k](v)\n norm = proj_feat.norm(2, 1, keepdim=True)\n embedding = proj_feat / norm.expand_as(proj_feat).clamp(min=1e-12)\n norm = self.rescaler[idx_fm](norm).squeeze()\n embeddings.append(embedding)\n norms.append(norm)\n embeddings = torch.cat(embeddings, dim=1)\n norms = torch.cat(norms, dim=1)\n else:\n outputs = []\n for k, v in featmaps.items():\n v = self._flatten_fc_input(v)\n proj_feat = self.projectors[k](v)\n outputs.append(proj_feat)\n embeddings = torch.cat(outputs, dim=1)\n norms = embeddings.norm(2, 1, keepdim=True)\n embeddings = embeddings / norms.expand_as(embeddings).clamp(min=1e-12)\n norms = self.rescaler(norms).squeeze()\n return embeddings, norms\n\n def _flatten_fc_input(self, x):\n if x.ndimension() == 4:\n assert list(x.shape[2:]) == [1, 1]\n return x.flatten(start_dim=1)\n return x\n\n def _split_embedding_dim(self, dim):\n parts = len(self.in_channels)\n tmp = [dim // parts] * parts\n if sum(tmp) == dim:\n return tmp\n else:\n res = dim % parts\n for i in range(1, res + 1):\n tmp[-i] += 1\n assert sum(tmp) == dim\n return tmp\n\n\nclass BBoxRegressor(nn.Module):\n \"\"\"\n Bounding box regression layer.\n \"\"\"\n\n def __init__(self, in_channels, num_classes=2, bn_neck=True):\n \"\"\"\n Args:\n in_channels (int): Input channels.\n num_classes (int, optional): Defaults to 2 (background and pedestrian).\n bn_neck (bool, optional): Whether to use BN after Linear. Defaults to True.\n \"\"\"\n super(BBoxRegressor, self).__init__()\n if bn_neck:\n self.bbox_pred = nn.Sequential(\n nn.Linear(in_channels, 4 * num_classes), nn.BatchNorm1d(4 * num_classes)\n )\n init.normal_(self.bbox_pred[0].weight, std=0.01)\n init.normal_(self.bbox_pred[1].weight, std=0.01)\n init.constant_(self.bbox_pred[0].bias, 0)\n init.constant_(self.bbox_pred[1].bias, 0)\n else:\n self.bbox_pred = nn.Linear(in_channels, 4 * num_classes)\n init.normal_(self.bbox_pred.weight, std=0.01)\n init.constant_(self.bbox_pred.bias, 0)\n\n def forward(self, x):\n if x.ndimension() == 4:\n if list(x.shape[2:]) != [1, 1]:\n x = F.adaptive_avg_pool2d(x, output_size=1)\n x = x.flatten(start_dim=1)\n bbox_deltas = self.bbox_pred(x)\n return bbox_deltas\n\n\ndef detection_losses(\n proposal_cls_scores,\n proposal_regs,\n proposal_labels,\n proposal_reg_targets,\n box_cls_scores,\n box_regs,\n box_labels,\n box_reg_targets,\n):\n proposal_labels = torch.cat(proposal_labels, dim=0)\n box_labels = torch.cat(box_labels, dim=0)\n proposal_reg_targets = torch.cat(proposal_reg_targets, dim=0)\n box_reg_targets = torch.cat(box_reg_targets, dim=0)\n\n loss_proposal_cls = F.cross_entropy(proposal_cls_scores, proposal_labels)\n loss_box_cls = F.binary_cross_entropy_with_logits(box_cls_scores, box_labels.float())\n\n # get indices that correspond to the regression targets for the\n # corresponding ground truth labels, to be used with advanced indexing\n sampled_pos_inds_subset = torch.nonzero(proposal_labels > 0).squeeze(1)\n labels_pos = proposal_labels[sampled_pos_inds_subset]\n N = proposal_cls_scores.size(0)\n proposal_regs = proposal_regs.reshape(N, -1, 4)\n\n loss_proposal_reg = F.smooth_l1_loss(\n proposal_regs[sampled_pos_inds_subset, labels_pos],\n proposal_reg_targets[sampled_pos_inds_subset],\n reduction=\"sum\",\n )\n loss_proposal_reg = loss_proposal_reg / proposal_labels.numel()\n\n sampled_pos_inds_subset = torch.nonzero(box_labels > 0).squeeze(1)\n labels_pos = box_labels[sampled_pos_inds_subset]\n N = box_cls_scores.size(0)\n box_regs = box_regs.reshape(N, -1, 4)\n\n loss_box_reg = F.smooth_l1_loss(\n box_regs[sampled_pos_inds_subset, labels_pos],\n box_reg_targets[sampled_pos_inds_subset],\n reduction=\"sum\",\n )\n loss_box_reg = loss_box_reg / box_labels.numel()\n\n return dict(\n loss_proposal_cls=loss_proposal_cls,\n loss_proposal_reg=loss_proposal_reg,\n loss_box_cls=loss_box_cls,\n loss_box_reg=loss_box_reg,\n )\n\n"
] |
[
[
"torch.mean",
"torch.cat",
"torch.zeros",
"torch.sum",
"torch.nn.functional.smooth_l1_loss",
"torch.nn.AdaptiveMaxPool2d",
"torch.ones",
"torch.nn.ModuleDict",
"torch.tensor",
"torch.nonzero",
"torch.nn.Sequential",
"torch.sigmoid",
"torch.nn.BatchNorm1d",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Linear",
"torch.nn.init.normal_",
"torch.nn.BatchNorm2d",
"torch.nn.Conv1d",
"torch.nn.functional.cross_entropy",
"torch.nn.ReLU"
]
] |
LafeLabs/codeserver
|
[
"ca3f7bbe3acbcd6755e04627c97fe4fcd5186711"
] |
[
"matplotlib/code/php.py"
] |
[
"############### GET INPUT FILE ###############\ninfile = open(\"data.txt\",\"r\")\ntextin = infile.read()\ninfile.close()\n##############################################\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\njsondata = json.loads(textin)\nt = []\nv = []\nfor i in range(len(jsondata)):\n v.append(jsondata[i]['voltage'])\n t.append(jsondata[i]['timestamp'])\n\n#t = np.arange(0,100)\n#v0 = 100\n#v1 = 100\n#tau = 30.0\n#v = v1 + v0*np.exp(-t/tau)\n#noise = np.random.normal(0,3,100)\n#v += noise\n\nfig, ax = plt.subplots()\nax.plot(t, v)\n\nax.set(xlabel='time [s]', ylabel='voltage [V]',\n title='voltage vs. time')\nax.grid()\n\nfig.savefig(\"plot.png\")\n#plt.show()\n\n\n######### SAVE OUTPUT FILE ###### \nfile = open(\"textout.txt\", \"w\")\nfile.write(textin)\nfile.close()\n\n"
] |
[
[
"matplotlib.pyplot.subplots"
]
] |
yangxin0/waymo-open-dataset
|
[
"1297cdcbcd103d4befb4b498e50a0c030053e6c0"
] |
[
"waymo_open_dataset/utils/keypoint_draw_test.py"
] |
[
"# Copyright 2022 The Waymo Open Dataset 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\"\"\"Tests for keypoint_draw.\"\"\"\n\nfrom matplotlib import collections as mc\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport plotly.graph_objects as go\nimport tensorflow as tf\n\nfrom waymo_open_dataset import label_pb2\nfrom waymo_open_dataset.protos import keypoint_pb2\nfrom waymo_open_dataset.utils import keypoint_data as _data\nfrom waymo_open_dataset.utils import keypoint_draw as _lib\nfrom waymo_open_dataset.utils import keypoint_test_util as _util\n\n_NOSE = keypoint_pb2.KeypointType.KEYPOINT_TYPE_NOSE\n_LEFT_SHOULDER = keypoint_pb2.KeypointType.KEYPOINT_TYPE_LEFT_SHOULDER\n_RIGHT_SHOULDER = keypoint_pb2.KeypointType.KEYPOINT_TYPE_RIGHT_SHOULDER\n\n\ndef _get_collection(ax, col_type):\n cols = [c for c in ax.collections if isinstance(c, col_type)]\n assert len(cols) == 1, f'Required a single {col_type}, got {cols}'\n return cols[0]\n\n\ndef _vec2d_as_array(location_px: keypoint_pb2.Vec2d) -> np.ndarray:\n return np.array([location_px.x, location_px.y])\n\n\nclass EdgeTest(tf.test.TestCase):\n\n def test_simple_edge_between_two_points_creates_single_line(self):\n coords = {\n _LEFT_SHOULDER: _data.Point([0, 0]),\n _RIGHT_SHOULDER: _data.Point([1, 1])\n }\n colors = {_LEFT_SHOULDER: '#AAAAAA', _RIGHT_SHOULDER: '#BBBBBB'}\n\n edge = _lib.SolidLineEdge(_LEFT_SHOULDER, _RIGHT_SHOULDER, 1)\n lines = edge.create_lines(coords, colors)\n\n self.assertLen(lines, 1)\n # Line has the same color as the start point.\n self.assertEqual(lines[0].color, '#AAAAAA')\n\n def test_bicolored_edge_between_two_points_creates_two_lines(self):\n coords = {\n _LEFT_SHOULDER: _data.Point([0, 0]),\n _RIGHT_SHOULDER: _data.Point([1, 1])\n }\n colors = {_LEFT_SHOULDER: '#AAAAAA', _RIGHT_SHOULDER: '#BBBBBB'}\n\n edge = _lib.BicoloredEdge(_LEFT_SHOULDER, _RIGHT_SHOULDER, 1)\n lines = edge.create_lines(coords, colors)\n\n self.assertLen(lines, 2)\n self.assertEqual(lines[0].color, '#AAAAAA')\n self.assertEqual(lines[1].color, '#BBBBBB')\n\n def test_multipoint_edge_averages_locations_to_get_ends(self):\n coords = {\n _LEFT_SHOULDER: _data.Point([2, 0]),\n _RIGHT_SHOULDER: _data.Point([0, 2]),\n _NOSE: _data.Point([3, 3])\n }\n colors = {\n _LEFT_SHOULDER: '#AAAAAA',\n _RIGHT_SHOULDER: '#BBBBBB',\n _NOSE: '#CCCCCC'\n }\n\n edge = _lib.MultipointEdge([_LEFT_SHOULDER, _RIGHT_SHOULDER], [_NOSE], 1)\n lines = edge.create_lines(coords, colors)\n\n self.assertLen(lines, 2)\n np.testing.assert_allclose(lines[0].start, [1, 1])\n np.testing.assert_allclose(lines[0].end, [2, 2])\n self.assertEqual(lines[0].color, _lib.DEFAULT_COLOR)\n np.testing.assert_allclose(lines[1].start, [2, 2])\n np.testing.assert_allclose(lines[1].end, [3, 3])\n self.assertEqual(lines[1].color, '#CCCCCC')\n\n\nclass WireframeTest(tf.test.TestCase):\n\n def test_build_camera_wireframe_dot_and_lines_have_correct_attributes(self):\n camera_keypoints = [\n _util.camera_keypoint(_NOSE, location_px=(2, 1), is_occluded=True),\n _util.camera_keypoint(_LEFT_SHOULDER, location_px=(1, 0)),\n _util.camera_keypoint(_RIGHT_SHOULDER, location_px=(3, 0))\n ]\n config = _lib.WireframeConfig(\n edges=[_lib.BicoloredEdge(_LEFT_SHOULDER, _RIGHT_SHOULDER, width=2)],\n point_colors={\n _NOSE: '#FFFFFF',\n _LEFT_SHOULDER: '#AAAAAA',\n _RIGHT_SHOULDER: '#BBBBBB'\n },\n point_sizes={\n _NOSE: 1,\n _LEFT_SHOULDER: 2,\n _RIGHT_SHOULDER: 3\n })\n\n wireframe = _lib.build_camera_wireframe(camera_keypoints, config)\n\n with self.subTest(name='CorrectNumberOfLines'):\n # Two lines per edge, e.g. 2 for the edge between shoulders.\n self.assertLen(wireframe.lines, 2)\n with self.subTest(name='PopulatesLineColors'):\n self.assertEqual([l.color for l in wireframe.lines],\n ['#AAAAAA', '#BBBBBB'])\n with self.subTest(name='PopulatesLineWidth'):\n self.assertEqual([l.width for l in wireframe.lines], [2, 2])\n with self.subTest(name='CorrectNumberOfDots'):\n # One dot per keypoint.\n self.assertLen(wireframe.dots, 3)\n with self.subTest(name='PopulatesDotColors'):\n self.assertEqual([d.color for d in wireframe.dots],\n ['#FFFFFF', '#AAAAAA', '#BBBBBB'])\n with self.subTest(name='PopulatesDotSizes'):\n self.assertEqual([d.size for d in wireframe.dots], [1, 2, 3])\n with self.subTest(name='PopulatesBoarderColorForOccludedPoints'):\n self.assertEqual([d.border_color for d in wireframe.dots],\n [_lib.OCCLUDED_COLOR, None, None])\n self.assertEqual([d.actual_border_color for d in wireframe.dots],\n [_lib.OCCLUDED_COLOR, '#AAAAAA', '#BBBBBB'])\n\n def test_build_laser_wireframe_dot_and_lines_have_correct_attributes(self):\n laser_keypoints = [\n _util.laser_keypoint(_NOSE, location_m=(2, 1, 1), is_occluded=True),\n _util.laser_keypoint(_LEFT_SHOULDER, location_m=(1, 0, 1)),\n _util.laser_keypoint(_RIGHT_SHOULDER, location_m=(3, 0, 1))\n ]\n config = _lib.WireframeConfig(\n edges=[_lib.BicoloredEdge(_LEFT_SHOULDER, _RIGHT_SHOULDER, width=2)],\n point_colors={\n _NOSE: '#FFFFFF',\n _LEFT_SHOULDER: '#AAAAAA',\n _RIGHT_SHOULDER: '#BBBBBB'\n },\n point_sizes={\n _NOSE: 1,\n _LEFT_SHOULDER: 2,\n _RIGHT_SHOULDER: 3\n })\n\n wireframe = _lib.build_laser_wireframe(laser_keypoints, config)\n\n with self.subTest(name='CorrectNumberOfLines'):\n # Two lines per edge, e.g. 2 for the edge between shoulders.\n self.assertLen(wireframe.lines, 2)\n with self.subTest(name='PopulatesLineColors'):\n self.assertEqual([l.color for l in wireframe.lines],\n ['#AAAAAA', '#BBBBBB'])\n with self.subTest(name='PopulatesLineWidth'):\n self.assertEqual([l.width for l in wireframe.lines], [2, 2])\n with self.subTest(name='CorrectNumberOfDots'):\n # One dot per keypoint.\n self.assertLen(wireframe.dots, 3)\n with self.subTest(name='PopulatesDotColors'):\n self.assertEqual([d.color for d in wireframe.dots],\n ['#FFFFFF', '#AAAAAA', '#BBBBBB'])\n with self.subTest(name='PopulatesDotSizes'):\n self.assertEqual([d.size for d in wireframe.dots], [1, 2, 3])\n with self.subTest(name='PopulatesDotNames'):\n self.assertEqual([d.name for d in wireframe.dots],\n ['NOSE?', 'LEFT_SHOULDER', 'RIGHT_SHOULDER'])\n with self.subTest(name='PopulatesBoarderColorForOccludedPoints'):\n self.assertEqual([d.border_color for d in wireframe.dots],\n [_lib.OCCLUDED_COLOR, None, None])\n self.assertEqual([d.actual_border_color for d in wireframe.dots],\n [_lib.OCCLUDED_COLOR, '#AAAAAA', '#BBBBBB'])\n\n def test_build_camera_wireframe_factors_modify_sizes(self):\n camera_keypoints = [\n _util.camera_keypoint(_NOSE, location_px=(2, 1)),\n _util.camera_keypoint(_LEFT_SHOULDER, location_px=(1, 0)),\n _util.camera_keypoint(_RIGHT_SHOULDER, location_px=(3, 0))\n ]\n config = _lib.WireframeConfig(\n edges=[_lib.BicoloredEdge(_LEFT_SHOULDER, _RIGHT_SHOULDER, width=2)],\n point_colors={\n _NOSE: '#FFFFFF',\n _LEFT_SHOULDER: '#AAAAAA',\n _RIGHT_SHOULDER: '#BBBBBB'\n },\n point_sizes={\n _NOSE: 1,\n _LEFT_SHOULDER: 2,\n _RIGHT_SHOULDER: 3\n },\n dot_size_factor=2.0,\n line_width_factor=3.0)\n\n wireframe = _lib.build_camera_wireframe(camera_keypoints, config)\n\n with self.subTest(name='ModfiesLineWidth'):\n self.assertEqual([l.width for l in wireframe.lines], [6, 6])\n with self.subTest(name='ModifiesDotSizes'):\n self.assertEqual([l.size for l in wireframe.dots], [2, 4, 6])\n\n\nclass DrawTest(tf.test.TestCase):\n\n def test_draw_camera_wireframe_adds_collections_to_the_axis(self):\n wireframe = _lib.Wireframe(\n lines=[\n _lib.Line(start=[0, 0], end=[1, 1], color='#AAAAAA', width=1),\n _lib.Line(start=[1, 1], end=[2, 2], color='#BBBBBB', width=1),\n ],\n dots=[\n _lib.Dot(location=[0, 0], color='#FFFFFF', size=1, name='A'),\n _lib.Dot(location=[1, 1], color='#FFFFFF', size=2, name='B'),\n _lib.Dot(location=[2, 2], color='#FFFFFF', size=3, name='C')\n ])\n\n _, ax = plt.subplots()\n _lib.draw_camera_wireframe(ax, wireframe)\n\n with self.subTest(name='CorrectNumberOfLineSegments'):\n line_collection = _get_collection(ax, mc.LineCollection)\n self.assertLen(line_collection.get_segments(), 2)\n with self.subTest(name='CorrectNumberOfDots'):\n el_collection = _get_collection(ax, mc.EllipseCollection)\n self.assertEqual(el_collection.get_offsets().shape, (3, 2))\n\n def test_draw_laser_wireframe_adds_traces_to_the_figure(self):\n wireframe = _lib.Wireframe(\n lines=[\n _lib.Line(start=[0, 0, 0], end=[1, 1, 1], color='#AAAAAA', width=1),\n _lib.Line(start=[1, 1, 1], end=[2, 2, 2], color='#BBBBBB', width=1),\n ],\n dots=[\n _lib.Dot(location=[0, 0, 0], color='#FFFFFF', size=1, name='A'),\n _lib.Dot(location=[1, 1, 1], color='#FFFFFF', size=2, name='B'),\n _lib.Dot(location=[2, 2, 2], color='#FFFFFF', size=3, name='C')\n ])\n\n fig = go.Figure()\n _lib.draw_laser_wireframe(fig, wireframe)\n\n with self.subTest(name='CorrectNumberOfLineSegments'):\n line_traces = list(fig.select_traces({'mode': 'lines'}))\n self.assertLen(line_traces, 2)\n with self.subTest(name='CorrectNumberOfDots'):\n dot_traces = list(fig.select_traces({'mode': 'markers'}))\n self.assertLen(dot_traces, 1)\n self.assertLen(dot_traces[0].x, 3)\n\n def test_crop_camera_keypoints_returns_updated_keypoints_and_image(self):\n image = np.zeros((450, 250, 3))\n camera_keypoints = [\n _util.camera_keypoint(location_px=(100, 200)),\n _util.camera_keypoint(location_px=(150, 200)),\n ]\n # NOTE: Box.length is along OX, Box.width is along OY\n box = label_pb2.Label.Box(center_x=100, center_y=200, length=100, width=200)\n\n new_image, new_keypoints = _lib.crop_camera_keypoints(\n image, camera_keypoints, box)\n\n with self.subTest(name='CroppedImageSizeIsCorrect'):\n self.assertEqual(new_image.shape, (200, 100, 3))\n with self.subTest(name='CroppedKeypointsShifted'):\n np.testing.assert_allclose(\n _vec2d_as_array(new_keypoints[0].keypoint_2d.location_px), [50, 100])\n np.testing.assert_allclose(\n _vec2d_as_array(new_keypoints[1].keypoint_2d.location_px), [100, 100])\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"matplotlib.pyplot.subplots",
"tensorflow.test.main",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros"
]
] |
Xlinford/TDNet
|
[
"e7cb59c40b8751b6dab9691d26ad224fd61c24d1"
] |
[
"Training/ptsemseg/optimizers/adaoptimizer.py"
] |
[
"#!/usr/bin/python\r\n# -*- encoding: utf-8 -*-\r\n\r\n\r\nimport torch\r\nimport logging\r\n\r\nlogger = logging.getLogger(\"ptsemseg\")\r\n\r\nclass AdaOptimizer(object):\r\n def __init__(self,\r\n model,\r\n lr0,\r\n momentum,\r\n wd,\r\n warmup_steps,\r\n warmup_start_lr,\r\n max_iter,\r\n power,\r\n *args, **kwargs):\r\n self.warmup_steps = warmup_steps\r\n self.warmup_start_lr = warmup_start_lr\r\n self.lr0 = lr0\r\n self.lr = self.lr0\r\n self.max_iter = float(max_iter)\r\n self.power = power\r\n self.it = 0\r\n wd_params, nowd_params, lr_mul_wd_params, lr_mul_nowd_params = model.get_params()\r\n param_list = [\r\n {'params': wd_params},\r\n {'params': nowd_params, 'weight_decay': 0},\r\n {'params': lr_mul_wd_params, 'lr_mul': True},\r\n {'params': lr_mul_nowd_params, 'weight_decay': 0, 'lr_mul': True}]\r\n self.optim = torch.optim.SGD(\r\n param_list,\r\n lr = lr0,\r\n momentum = momentum,\r\n weight_decay = wd)\r\n self.warmup_factor = (self.lr0/self.warmup_start_lr)**(1./self.warmup_steps)\r\n\r\n\r\n def get_lr(self):\r\n if self.it <= self.warmup_steps:\r\n lr = self.warmup_start_lr*(self.warmup_factor**self.it)\r\n else:\r\n factor = (1-(self.it-self.warmup_steps)/(self.max_iter-self.warmup_steps))**self.power\r\n lr = self.lr0 * factor\r\n return lr\r\n\r\n\r\n def step(self):\r\n self.lr = self.get_lr()\r\n for pg in self.optim.param_groups:\r\n if pg.get('lr_mul', False):\r\n pg['lr'] = self.lr * 1\r\n else:\r\n pg['lr'] = self.lr\r\n if self.optim.defaults.get('lr_mul', False):\r\n self.optim.defaults['lr'] = self.lr * 1\r\n else:\r\n self.optim.defaults['lr'] = self.lr\r\n self.it += 1\r\n self.optim.step()\r\n if self.it == self.warmup_steps+2:\r\n logger.info('==> warmup done, start to implement poly lr strategy')\r\n\r\n def zero_grad(self):\r\n self.optim.zero_grad()\r\n\r\n"
] |
[
[
"torch.optim.SGD"
]
] |
A03ki/PFN_internship2019_ML
|
[
"2353005e16217ec7b55d98da9c125d44005f3960"
] |
[
"1/src/gnn.py"
] |
[
"import numpy as np\n\n\nclass GraphNeuralNetwork:\n def __init__(self, vertex_size, vector_size):\n np.random.seed(0)\n self.W = np.random.randn(vector_size, vector_size)\n self.x = np.zeros((vertex_size, vector_size))\n self.x[:, 0] = 1 # one-hot of row\n\n def forward(self, graph, step_size=2):\n for _ in range(step_size):\n a = np.dot(graph, self.x)\n self.x = relu(np.dot(a, self.W))\n return self.x.sum(0)\n\n\ndef relu(x):\n return np.maximum(0, x)\n"
] |
[
[
"numpy.dot",
"numpy.maximum",
"numpy.random.seed",
"numpy.random.randn",
"numpy.zeros"
]
] |
2AUK/SFED
|
[
"6c50c727ea6c63b31af04a648b3d9cb481e1d6ae"
] |
[
"test/test_GF_KH.py"
] |
[
"from gridData import Grid\nimport numpy as np\nimport sys\n\nsys.path.append(\"/home/abdullah/Code/Python/SFED/\")\nfrom gridcollector import GridCollector\nfrom SFED_routines import sfed_gf_3drism, integrate_sfed\nfrom pathlib import Path\n\nbase_path = Path(__file__).parent\ndata_path = file_path = (base_path / \"../data/DATA/KH/\").resolve()\n\ngc3methbut1e = GridCollector(\"3methbut1e\", str(data_path) + \"/3methbut1e/3\")\ngc3methbut1ol = GridCollector(\"3methbut1ol\", str(data_path) + \"/3methbut1ol/3\")\ngc24dimepen = GridCollector(\"24dimepen\", str(data_path) + \"/24dimepen/3\")\ngcethene = GridCollector(\"ethene\", str(data_path) + \"/ethene/3\")\ngcethylbenzene = GridCollector(\"ethylbenzene\", str(data_path) + \"/ethylbenzene/3\")\ngcn_decane = GridCollector(\"n_decane\", str(data_path) + \"/n_decane/3\")\ngcn_hexane = GridCollector(\"n_hexane\", str(data_path) + \"/n_hexane/3\")\ngcphenol = GridCollector(\"phenol\", str(data_path) + \"/phenol/3\")\ngcnhexylbenzene = GridCollector(\"nhexylbenzene\", str(data_path )+ \"/nhexylbenzene/3\")\n\nprec = 3\n\ndef test_kh_3methbut1e():\n sfed_o = sfed_gf_3drism(gc3methbut1e.grids[\"HO\"].grid, gc3methbut1e.grids[\"CO\"].grid, gc3methbut1e.grids[\"HH1\"].grid, gc3methbut1e.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gc3methbut1e.delta)\n np.testing.assert_almost_equal(sfe, 16.992602400000003, prec)\n\ndef test_kh_3methbut1ol():\n sfed_o = sfed_gf_3drism(gc3methbut1ol.grids[\"HO\"].grid, gc3methbut1ol.grids[\"CO\"].grid, gc3methbut1ol.grids[\"HH1\"].grid, gc3methbut1ol.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gc3methbut1ol.delta)\n np.testing.assert_almost_equal(sfe, 13.032708299999999, prec)\n\ndef test_kh_24dimepen():\n sfed_o = sfed_gf_3drism(gc24dimepen.grids[\"HO\"].grid, gc24dimepen.grids[\"CO\"].grid, gc24dimepen.grids[\"HH1\"].grid, gc24dimepen.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gc24dimepen.delta)\n np.testing.assert_almost_equal(sfe, 23.5298981, prec)\n\ndef test_kh_ethene():\n sfed_o = sfed_gf_3drism(gcethene.grids[\"HO\"].grid, gcethene.grids[\"CO\"].grid, gcethene.grids[\"HH1\"].grid, gcethene.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcethene.delta)\n np.testing.assert_almost_equal(sfe, 8.2472757000000012, prec)\n\ndef test_kh_ethylbenzene():\n sfed_o = sfed_gf_3drism(gcethylbenzene.grids[\"HO\"].grid, gcethylbenzene.grids[\"CO\"].grid, gcethylbenzene.grids[\"HH1\"].grid, gcethylbenzene.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcethylbenzene.delta)\n np.testing.assert_almost_equal(sfe, 17.4067188, prec)\n\ndef test_kh_n_decane():\n sfed_o = sfed_gf_3drism(gcn_decane.grids[\"HO\"].grid, gcn_decane.grids[\"CO\"].grid, gcn_decane.grids[\"HH1\"].grid, gcn_decane.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcn_decane.delta)\n np.testing.assert_almost_equal(sfe, 33.628554900000012, prec)\n\ndef test_kh_n_hexane():\n sfed_o = sfed_gf_3drism(gcn_hexane.grids[\"HO\"].grid, gcn_hexane.grids[\"CO\"].grid, gcn_hexane.grids[\"HH1\"].grid, gcn_hexane.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcn_hexane.delta)\n np.testing.assert_almost_equal(sfe, 21.6218, prec)\n\ndef test_kh_phenol():\n sfed_o = sfed_gf_3drism(gcphenol.grids[\"HO\"].grid, gcphenol.grids[\"CO\"].grid, gcphenol.grids[\"HH1\"].grid, gcphenol.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcphenol.delta)\n np.testing.assert_almost_equal(sfe, 7.05341, prec)\n\ndef test_kh_nhexylbenzene():\n sfed_o = sfed_gf_3drism(gcnhexylbenzene.grids[\"HO\"].grid, gcnhexylbenzene.grids[\"CO\"].grid, gcnhexylbenzene.grids[\"HH1\"].grid, gcnhexylbenzene.grids[\"CH1\"].grid)\n sfe = integrate_sfed(sfed_o, gcnhexylbenzene.delta)\n np.testing.assert_almost_equal(sfe, 29.3887, prec)"
] |
[
[
"numpy.testing.assert_almost_equal"
]
] |
kant/rl-baselines3-zoo
|
[
"75f9c4c8395d622184177795696973ae37c58ae7"
] |
[
"enjoy.py"
] |
[
"import argparse\nimport glob\nimport importlib\nimport os\nimport sys\n\nimport numpy as np\nimport torch as th\nimport yaml\nfrom stable_baselines3.common.utils import set_random_seed\n\nimport utils.import_envs # noqa: F401 pylint: disable=unused-import\nfrom utils import ALGOS, create_test_env, get_latest_run_id, get_saved_hyperparams\nfrom utils.exp_manager import ExperimentManager\nfrom utils.utils import StoreDict\n\n\ndef main(): # noqa: C901\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--env\", help=\"environment ID\", type=str, default=\"CartPole-v1\")\n parser.add_argument(\"-f\", \"--folder\", help=\"Log folder\", type=str, default=\"rl-trained-agents\")\n parser.add_argument(\"--algo\", help=\"RL Algorithm\", default=\"ppo\", type=str, required=False, choices=list(ALGOS.keys()))\n parser.add_argument(\"-n\", \"--n-timesteps\", help=\"number of timesteps\", default=1000, type=int)\n parser.add_argument(\"--num-threads\", help=\"Number of threads for PyTorch (-1 to use default)\", default=-1, type=int)\n parser.add_argument(\"--n-envs\", help=\"number of environments\", default=1, type=int)\n parser.add_argument(\"--exp-id\", help=\"Experiment ID (default: 0: latest, -1: no exp folder)\", default=0, type=int)\n parser.add_argument(\"--verbose\", help=\"Verbose mode (0: no output, 1: INFO)\", default=1, type=int)\n parser.add_argument(\n \"--no-render\", action=\"store_true\", default=False, help=\"Do not render the environment (useful for tests)\"\n )\n parser.add_argument(\"--deterministic\", action=\"store_true\", default=False, help=\"Use deterministic actions\")\n parser.add_argument(\n \"--load-best\", action=\"store_true\", default=False, help=\"Load best model instead of last model if available\"\n )\n parser.add_argument(\n \"--load-checkpoint\",\n type=int,\n help=\"Load checkpoint instead of last model if available, \"\n \"you must pass the number of timesteps corresponding to it\",\n )\n parser.add_argument(\n \"--load-last-checkpoint\",\n action=\"store_true\",\n default=False,\n help=\"Load last checkpoint instead of last model if available\",\n )\n parser.add_argument(\"--stochastic\", action=\"store_true\", default=False, help=\"Use stochastic actions\")\n parser.add_argument(\n \"--norm-reward\", action=\"store_true\", default=False, help=\"Normalize reward if applicable (trained with VecNormalize)\"\n )\n parser.add_argument(\"--seed\", help=\"Random generator seed\", type=int, default=0)\n parser.add_argument(\"--reward-log\", help=\"Where to log reward\", default=\"\", type=str)\n parser.add_argument(\n \"--gym-packages\",\n type=str,\n nargs=\"+\",\n default=[],\n help=\"Additional external Gym environment package modules to import (e.g. gym_minigrid)\",\n )\n parser.add_argument(\n \"--env-kwargs\", type=str, nargs=\"+\", action=StoreDict, help=\"Optional keyword argument to pass to the env constructor\"\n )\n args = parser.parse_args()\n\n # Going through custom gym packages to let them register in the global registory\n for env_module in args.gym_packages:\n importlib.import_module(env_module)\n\n env_id = args.env\n algo = args.algo\n folder = args.folder\n\n if args.exp_id == 0:\n args.exp_id = get_latest_run_id(os.path.join(folder, algo), env_id)\n print(f\"Loading latest experiment, id={args.exp_id}\")\n\n # Sanity checks\n if args.exp_id > 0:\n log_path = os.path.join(folder, algo, f\"{env_id}_{args.exp_id}\")\n else:\n log_path = os.path.join(folder, algo)\n\n assert os.path.isdir(log_path), f\"The {log_path} folder was not found\"\n\n found = False\n for ext in [\"zip\"]:\n model_path = os.path.join(log_path, f\"{env_id}.{ext}\")\n found = os.path.isfile(model_path)\n if found:\n break\n\n if args.load_best:\n model_path = os.path.join(log_path, \"best_model.zip\")\n found = os.path.isfile(model_path)\n\n if args.load_checkpoint is not None:\n model_path = os.path.join(log_path, f\"rl_model_{args.load_checkpoint}_steps.zip\")\n found = os.path.isfile(model_path)\n\n if args.load_last_checkpoint:\n checkpoints = glob.glob(os.path.join(log_path, \"rl_model_*_steps.zip\"))\n if len(checkpoints) == 0:\n raise ValueError(f\"No checkpoint found for {algo} on {env_id}, path: {log_path}\")\n model_path = checkpoints[-1]\n found = True\n\n if not found:\n raise ValueError(f\"No model found for {algo} on {env_id}, path: {model_path}\")\n\n print(f\"Loading {model_path}\")\n\n # Off-policy algorithm only support one env for now\n off_policy_algos = [\"qrdqn\", \"dqn\", \"ddpg\", \"sac\", \"her\", \"td3\", \"tqc\"]\n\n if algo in off_policy_algos:\n args.n_envs = 1\n\n set_random_seed(args.seed)\n\n if args.num_threads > 0:\n if args.verbose > 1:\n print(f\"Setting torch.num_threads to {args.num_threads}\")\n th.set_num_threads(args.num_threads)\n\n is_atari = ExperimentManager.is_atari(env_id)\n\n stats_path = os.path.join(log_path, env_id)\n hyperparams, stats_path = get_saved_hyperparams(stats_path, norm_reward=args.norm_reward, test_mode=True)\n\n # load env_kwargs if existing\n env_kwargs = {}\n args_path = os.path.join(log_path, env_id, \"args.yml\")\n if os.path.isfile(args_path):\n with open(args_path, \"r\") as f:\n loaded_args = yaml.load(f, Loader=yaml.UnsafeLoader) # pytype: disable=module-attr\n if loaded_args[\"env_kwargs\"] is not None:\n env_kwargs = loaded_args[\"env_kwargs\"]\n # overwrite with command line arguments\n if args.env_kwargs is not None:\n env_kwargs.update(args.env_kwargs)\n\n log_dir = args.reward_log if args.reward_log != \"\" else None\n\n env = create_test_env(\n env_id,\n n_envs=args.n_envs,\n stats_path=stats_path,\n seed=args.seed,\n log_dir=log_dir,\n should_render=not args.no_render,\n hyperparams=hyperparams,\n env_kwargs=env_kwargs,\n )\n\n kwargs = dict(seed=args.seed)\n if algo in off_policy_algos:\n # Dummy buffer size as we don't need memory to enjoy the trained agent\n kwargs.update(dict(buffer_size=1))\n\n # Check if we are running python 3.8+\n # we need to patch saved model under python 3.6/3.7 to load them\n newer_python_version = sys.version_info.major == 3 and sys.version_info.minor >= 8\n\n custom_objects = {}\n if newer_python_version:\n custom_objects = {\n \"learning_rate\": 0.0,\n \"lr_schedule\": lambda _: 0.0,\n \"clip_range\": lambda _: 0.0,\n }\n\n model = ALGOS[algo].load(model_path, env=env, custom_objects=custom_objects, **kwargs)\n\n obs = env.reset()\n\n # Deterministic by default except for atari games\n stochastic = args.stochastic or is_atari and not args.deterministic\n deterministic = not stochastic\n\n state = None\n episode_reward = 0.0\n episode_rewards, episode_lengths = [], []\n ep_len = 0\n # For HER, monitor success rate\n successes = []\n try:\n for _ in range(args.n_timesteps):\n action, state = model.predict(obs, state=state, deterministic=deterministic)\n obs, reward, done, infos = env.step(action)\n if not args.no_render:\n env.render(\"human\")\n\n episode_reward += reward[0]\n ep_len += 1\n\n if args.n_envs == 1:\n # For atari the return reward is not the atari score\n # so we have to get it from the infos dict\n if is_atari and infos is not None and args.verbose >= 1:\n episode_infos = infos[0].get(\"episode\")\n if episode_infos is not None:\n print(f\"Atari Episode Score: {episode_infos['r']:.2f}\")\n print(\"Atari Episode Length\", episode_infos[\"l\"])\n\n if done and not is_atari and args.verbose > 0:\n # NOTE: for env using VecNormalize, the mean reward\n # is a normalized reward when `--norm_reward` flag is passed\n print(f\"Episode Reward: {episode_reward:.2f}\")\n print(\"Episode Length\", ep_len)\n episode_rewards.append(episode_reward)\n episode_lengths.append(ep_len)\n episode_reward = 0.0\n ep_len = 0\n state = None\n\n # Reset also when the goal is achieved when using HER\n if done and infos[0].get(\"is_success\") is not None:\n if args.verbose > 1:\n print(\"Success?\", infos[0].get(\"is_success\", False))\n\n if infos[0].get(\"is_success\") is not None:\n successes.append(infos[0].get(\"is_success\", False))\n episode_reward, ep_len = 0.0, 0\n\n except KeyboardInterrupt:\n pass\n\n if args.verbose > 0 and len(successes) > 0:\n print(f\"Success rate: {100 * np.mean(successes):.2f}%\")\n\n if args.verbose > 0 and len(episode_rewards) > 0:\n print(f\"{len(episode_rewards)} Episodes\")\n print(f\"Mean reward: {np.mean(episode_rewards):.2f} +/- {np.std(episode_rewards):.2f}\")\n\n if args.verbose > 0 and len(episode_lengths) > 0:\n print(f\"Mean episode length: {np.mean(episode_lengths):.2f} +/- {np.std(episode_lengths):.2f}\")\n\n env.close()\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.std",
"torch.set_num_threads",
"numpy.mean"
]
] |
ikestar99/endopy
|
[
"f8d330d93ad12fa1654f717fef8a0ce28540a1c9"
] |
[
"endopy/data/endodataset.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 24 21:28:00 2020\n\n\n@author: ike\n\"\"\"\n\nimport numpy as np\n\nimport torch\n\nfrom ..utils.base import BaseDataset\nfrom ..utils.pathutils import firstGlob, recursiveGlob\nfrom ..utils.multipagetiff import MultipageTiff\n\n\nclass FlyGuys(BaseDataset):\n def __init__(self, cfg, masks=True):\n super(FlyGuys, self).__init__(cfg, masks)\n\n self.samples = None\n self.mask = None\n self.multipageTiff = sum(\n [MultipageTiff(f) for f in recursiveGlob(\n self.cfg[\"DataDir\"], \"**\", self.cfg[\"Channel\"], ext=\"tif\")])\n if masks:\n self.mask = np.load(firstGlob(\n self.cfg[\"DataDir\"], \"**\", self.cfg[\"MaskPath\"]))\n\n self.parseSamples()\n if len(self) == 0:\n raise IndexError(\n (\"FlyGuys dataset could not find raw data \",\n \"in: \\n {}\".format(self.cfg[\"DataDir\"])))\n \n def parseSamples(self):\n self.multipageTiff.pad(self.cfg[\"Hin\"], self.cfg[\"Win\"])\n self.samples = list(range(len(self.multipageTiff)))\n self.samples = np.array(self.adjustKeys(\n self.samples)).reshape(-1, self.cfg[\"SampleSize\"])\n\n def __getitem__(self, idx): \n sample = np.array(\n [self.multipageTiff[mdx] for _, mdx in enumerate(\n self.samples[idx])])\n mySize = (\n (self.cfg[\"Cin\"], sample.shape[-2], sample.shape[-1])\n if self.cfg[\"Din\"] == 2 else\n (self.cfg[\"Cin\"], self.cfg[\"Depth\"], sample.shape[-2],\n sample.shape[-1]))\n sample = dict(In=torch.tensor(\n np.reshape(sample, newshape=mySize)))\n if self.masks:\n sample[\"GT\"] = torch.tensor(self.mask)\n\n return sample\n"
] |
[
[
"numpy.reshape",
"torch.tensor"
]
] |
CSCfi/machine-learning-scripts
|
[
"005f9343fb703ca2b6b11b5c2369e19efcaa5f62"
] |
[
"examples/tf2-dvc-vit.py"
] |
[
"# coding: utf-8\n\n# # Dogs-vs-cats classification with ViT\n# \n# In this notebook, we'll finetune a [Vision Transformer]\n# (https://arxiv.org/abs/2010.11929) (ViT) to classify images of dogs\n# from images of cats using TensorFlow 2 / Keras and HuggingFace's\n# [Transformers](https://github.com/huggingface/transformers).\n# \n# **Note that using a GPU with this notebook is highly recommended.**\n# \n# First, the needed imports.\n\nfrom transformers import __version__ as transformers_version\nfrom transformers.utils import check_min_version\ncheck_min_version(\"4.13.0.dev0\")\nfrom transformers import ViTFeatureExtractor, TFViTForImageClassification\n\nimport tensorflow as tf\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom PIL import Image\n\nimport os, sys, datetime\nimport pathlib\nfrom time import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nprint('Using TensorFlow version:', tf.__version__,\n 'Keras version:', tf.keras.__version__,\n 'Transformers version:', transformers_version)\n\n# ## Data\n#\n# The training dataset consists of 2000 images of dogs and cats, split\n# in half. In addition, the validation set consists of 1000 images.\n\nif 'DATADIR' in os.environ:\n DATADIR = os.environ['DATADIR']\nelse:\n DATADIR = \"/scratch/project_2005299/data/\"\n\nprint('Using DATADIR', DATADIR)\ndatapath = os.path.join(DATADIR, \"dogs-vs-cats/train-2000/\")\nassert os.path.exists(datapath), \"Data not found at \"+datapath\n\nnimages = {'train':2000, 'validation':1000, 'test':22000}\n\n# ### Image paths and labels\n\ndef get_paths(dataset):\n data_root = pathlib.Path(datapath+dataset)\n image_paths = list(data_root.glob('*/*'))\n image_paths = [str(path) for path in image_paths]\n image_count = len(image_paths)\n assert image_count == nimages[dataset], \\\n \"Found {} images, expected {}\".format(image_count, nimages[dataset])\n return image_paths\n\nimage_paths = dict()\nimage_paths['train'] = get_paths('train')\nimage_paths['validation'] = get_paths('validation')\nimage_paths['test'] = get_paths('test')\n\nlabel_names = sorted(item.name for item in\n pathlib.Path(datapath+'train').glob('*/')\n if item.is_dir())\nlabel_to_index = dict((name, index) for index,name in enumerate(label_names))\n\ndef get_labels(dataset):\n return [label_to_index[pathlib.Path(path).parent.name]\n for path in image_paths[dataset]]\n \nimage_labels = dict()\nimage_labels['train'] = get_labels('train')\nimage_labels['validation'] = get_labels('validation')\nimage_labels['test'] = get_labels('test')\n\n# ### Data loading\n# \n# We now define a function to load the images. \n\ndef pil_loadimg(path: str):\n with open(path, \"rb\") as f:\n im = Image.open(f)\n return im.convert(\"RGB\")\n \ndef pil_loader(imglist: list):\n res = []\n for i in imglist:\n res.append(pil_loadimg(i))\n return res\n\n# Next we specify the pre-trained ViT model we are going to use. The\n# model [\"google/vit-base-patch16-224\"]\n# (https://huggingface.co/google/vit-base-patch16-224) is pre-trained\n# on ImageNet-21k (14 million images, 21,843 classes) at resolution\n# 224x224, and fine-tuned on ImageNet 2012 (1 million images, 1,000\n# classes) at resolution 224x224.\n# \n# We'll use a pre-trained ViT feature extractor that matches the ViT\n# model to preprocess the input images.\n\nVITMODEL = 'google/vit-base-patch16-224'\n\nfeature_extractor = ViTFeatureExtractor.from_pretrained(VITMODEL)\n\n# We load and process the training and validation images:\n\nprint('Loading and processing training and validation images')\nt0 = time()\ninputs_train = feature_extractor(\n images=pil_loader(image_paths['train']), return_tensors=\"tf\")\ninputs_validation = feature_extractor(\n images=pil_loader(image_paths['validation']), return_tensors=\"tf\")\nprint('Done in {:.2f} seconds'.format(time()-t0))\n\n# ### TF Datasets\n# \n# Let's now define our TF `Dataset`s for training and validation data. \n\nBATCH_SIZE = 32\n\ndataset_train = tf.data.Dataset.from_tensor_slices((inputs_train.data,\n image_labels['train']))\ndataset_train = dataset_train.shuffle(len(dataset_train)).batch(BATCH_SIZE,\n drop_remainder=True)\ndataset_validation = tf.data.Dataset.from_tensor_slices((inputs_validation.data,\n image_labels['validation']))\ndataset_validation = dataset_validation.batch(BATCH_SIZE, drop_remainder=True)\n\n# ## Model\n# \n# ### Initialization\n\nmodel = TFViTForImageClassification.from_pretrained(VITMODEL, num_labels=1,\n ignore_mismatched_sizes=True)\n\nLR = 1e-5\n\noptimizer = tf.keras.optimizers.Adam(learning_rate=LR)\nloss = tf.keras.losses.BinaryCrossentropy(from_logits=False)\nmetric = 'accuracy'\n\nmodel.compile(optimizer=optimizer, loss=loss, metrics=[metric])\n\nprint(model.summary())\n\n# ### Learning\n\nlogdir = os.path.join(os.getcwd(), \"logs\",\n \"dvc-vit-\"+datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))\nprint('TensorBoard log directory:', logdir)\nos.makedirs(logdir)\ncallbacks = [TensorBoard(log_dir=logdir)]\n\nEPOCHS = 4\n\nhistory = model.fit(dataset_train, validation_data=dataset_validation,\n epochs=EPOCHS, verbose=2, callbacks=callbacks)\n\n# ### Inference\n# \n# We now evaluate the model using the test set. First we'll load and\n# preprocess the test images and define the TF Dataset. Due to\n# memory issues, we limit the evaluation to N_test images.\n\nN_test = 5000\nprint('Loading and processing', N_test, 'test images')\nt0 = time()\ninputs_test = feature_extractor(images=pil_loader(image_paths['test'][:N_test]),\n return_tensors=\"tf\")\ndataset_test = tf.data.Dataset.from_tensor_slices((inputs_test.data,\n image_labels['test'][:N_test]))\ndataset_test = dataset_test.batch(BATCH_SIZE, drop_remainder=True)\nprint('Done in {:.2f} seconds'.format(time()-t0))\n\nscores = model.evaluate(dataset_test, verbose=2)\nprint(\"Test set %s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n"
] |
[
[
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.losses.BinaryCrossentropy"
]
] |
avalenzu/manipulation
|
[
"13cacd5731557c3f2d844e7d72d8c40af2762821"
] |
[
"manipulation/test/test_open3d_utils.py"
] |
[
"\"\"\"\nAn example of converting from the Drake RGBD image representation to the\nOpen3D RGBD image representation.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport open3d as o3d\nimport meshcat\n\nfrom manipulation.mustard_depth_camera_example import MustardExampleSystem\nfrom manipulation.meshcat_utils import draw_open3d_point_cloud\nfrom manipulation.open3d_utils import *\n\nsystem = MustardExampleSystem()\n\n# Evaluate the camera output ports to get the images.\ncontext = system.CreateDefaultContext()\n\nv = meshcat.Visualizer()\n\nfor i in range(3):\n color_image = system.GetOutputPort(f\"camera{i}_rgb_image\").Eval(context)\n depth_image = system.GetOutputPort(f\"camera{i}_depth_image\").Eval(context)\n rgbd_image = create_open3d_rgbd_image(color_image, depth_image)\n\n # Plot the two images.\n plt.subplot(3, 2, 2 * i + 1)\n plt.imshow(rgbd_image.color)\n plt.title('Color image')\n plt.subplot(3, 2, 2 * i + 2)\n plt.imshow(rgbd_image.depth)\n plt.title('Depth image')\n\n point_cloud = system.GetOutputPort(f\"camera{i}_point_cloud\").Eval(context)\n pcd = create_open3d_point_cloud(point_cloud)\n draw_open3d_point_cloud(v[f\"camera{i}_point_cloud\"], pcd)\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.title"
]
] |
mynameisjanus/irisNN
|
[
"b4b15ba0b952c75bc7034049c822edb7217f7cd6"
] |
[
"irisneuralnet.py"
] |
[
"# Neural Network\nimport numpy as np\n\ndef relu(x):\n return np.maximum(0, x)\n\ndef drelu(x):\n return 1 * (x > 0)\n\ndef output_layer_activation(x):\n return x\n\ndef output_layer_activation_derivative(x):\n return 1\n \nclass NeuralNet():\n \n def __init__(self, X_train, y_train, hidden_layer, lr, epochs):\n self.W1 = np.random.randint(10, size = (hidden_layer, X_train.shape[1]))\n self.W2 = np.ones((hidden_layer, 3))\n self.b = np.zeros(hidden_layer)\n self.learning_rate = lr\n self.epochs = epochs\n self.training_points = X_train\n self.ypoints = y_train\n \n def train(self, X, y):\n f1 = np.vectorize(relu)\n df1 = np.vectorize(drelu)\n \n # Forward propagation\n z1 = self.W1 @ X + self.b\n a1 = f1(z1)\n z2 = a1 @ self.W2\n output = output_layer_activation(z2)\n \n # Backpropagation\n output_layer_error = (output - y) * output_layer_activation_derivative(z2)\n hidden_layer_error = np.multiply(self.W2 * output_layer_error, df1(z1))\n \n # Gradients\n b_grad = hidden_layer_error\n W2_grad = (a1 * output_layer_error).T\n W1_grad = np.outer(hidden_layer_error, X)\n \n # Update the parameters\n self.b = self.b - self.learning_rate * b_grad\n self.W1 = self.W1 - self.learning_rate * W1_grad\n self.W2 = self.W2 - self.learning_rate * W2_grad\n \n def predict(self, X):\n f1 = np.vectorize(relu)\n \n z1 = self.W1 @ X + self.b\n a1 = f1(z1)\n z2 = self.W2 @ a1\n activated_output = output_layer_activation(z2)\n \n return activated_output.item()\n \n def train_neural_network(self):\n for epoch in range(self.epochs):\n for x, y in zip(self.training_points, self.ypoints):\n self.train(x, y)\n \n def test_neural_network(self, X_test, y_test):\n y_pred = []\n for point in X_test:\n y_pred.append(self.predict(point))\n return np.mean(y_pred == y_test)"
] |
[
[
"numpy.maximum",
"numpy.ones",
"numpy.vectorize",
"numpy.mean",
"numpy.outer",
"numpy.zeros",
"numpy.random.randint"
]
] |
albertoa/keras_zmq_scaling_data_generators
|
[
"bfd68e1a28de72c8dbb6669d20f97fe9cdfdeade"
] |
[
"testsink_zmq.py"
] |
[
"\n# Copyright (c) 2018 Alberto Alonso\n# MIT license. See LICENSE file for details\n\n# Import standard python modules\nimport numpy as np\nimport argparse\nimport json\nimport os\nimport sys\nimport zmq\nimport cv2\nimport time\n\n# Get the base configuration for the project\nimport cfg.base as cfg\n\n# Default parameters\nparams = {\n # How many batches to get\n\t\"batch_count\": 3\n # Image patches per batch (for the testsink it should be be a\n # multiple of 10, since we are stacking the images based on 10)\n\t,\"batch_size\": 50\n\n # Default training data port\n\t,\"train_zmq_port\": 11000\n\n # Patch width. Must match the generator\n\t,\"patch_width\": 224\n # Patch height. Must match the generator\n\t,\"patch_height\": 224\n # Patch channel depth. Must match the generator\n\t,\"patch_depth\": 3\n}\n\n# Use the appropriate configuration settings to override defaults\nparams[\"class_labels\"] = cfg.dataset_classes\nparams[\"train_zmq_port\"] = cfg.zmq_train_sink_port\n\n# The manipulation keys prepends the no-manipulation operation (as in '') to the\n# official manipulation operations. That means that a key of 0 is no manipulation\nparams[\"manip_keys\"] = [''] + cfg.manip\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"--batch-size\", type=int\n\t\t\t\t,help=\"batch size\")\n\nap.add_argument(\"--patch-width\", type=int\n\t\t\t\t,help=\"patch-width\")\nap.add_argument(\"--patch-height\", type=int\n\t\t\t\t,help=\"patch-height\")\nap.add_argument(\"--patch-depth\", type=int\n\t\t\t\t,help=\"patch-depth\")\n\nap.add_argument(\"--train_zmq_port\", type=int\n\t\t\t\t,help=\"ZMQ port to listen at for training images\")\nargs = vars(ap.parse_args())\n\n# Handle command line overrides\nif args[\"batch_size\"] is not None:\n\tparams[\"batch_size\"] = args[\"batch_size\"]\n\nif args[\"patch_width\"] is not None:\n\tparams[\"patch_width\"] = args[\"patch_width\"]\nif args[\"patch_height\"] is not None:\n\tparams[\"patch_height\"] = args[\"patch_height\"]\nif args[\"patch_depth\"] is not None:\n\tparams[\"patch_depth\"] = args[\"patch_depth\"]\n\nif args[\"train_zmq_port\"] is not None:\n\tparams[\"train_zmq_port\"] = args[\"train_zmq_port\"]\n\n# For the fake sink make the batch_size a multiple of 10 so\n# that we can display the patches easily stacked\nparams[\"batch_size\"] = params[\"batch_size\"] // 10 * 10\n\n# Get a ZMQ context\ncontext = zmq.Context()\n\n# Socket for getting the training data\ntrain_socket = context.socket(zmq.PULL)\n# Set the high water mark to 2 * batch_size\ntrain_socket.set_hwm(2 * params[\"batch_size\"])\ntrain_socket.bind(\"tcp://*:\"+str(params[\"train_zmq_port\"]))\n\n# Pre-allocate the batch data arrays\nimgs = np.zeros((params[\"batch_size\"], params[\"patch_height\"], params[\"patch_width\"], params[\"patch_depth\"]), dtype=np.uint8)\ny = np.zeros((params[\"batch_size\"]), dtype=np.uint8)\nops = np.zeros((params[\"batch_size\"]), dtype=np.uint8)\n\n# Go ahead and read the batches\nfor batchidx in range(params[\"batch_count\"]):\n\t# Start our timing\n\ttstart = time.time()\n\n # Get all the images in a batch\n\tfor i in range(params[\"batch_size\"]):\n # Get the message buffer\n\t\tmsg = train_socket.recv()\n\n\t\t# Make sure the msg is of the right size, ignore it otherwise\n\t\tif len(msg) != (2 + params[\"patch_height\"] * params[\"patch_width\"] * params[\"patch_depth\"]):\n\t\t\tprint(\"Ignoring bad ZMQ message of size \",len(msg))\n\t\t\tcontinue\n\n\t\t# Get the class id\n\t\ty[i] = msg[0]\n\t\t# Get the operation code\n\t\tops[i] = msg[1]\n\n\t\t# Get the patch image data reshaped to the proper dimensions\n\t\timgs[i] = np.frombuffer(msg[2:],np.uint8).reshape(\n\t\t\tparams[\"patch_height\"],params[\"patch_width\"],params[\"patch_depth\"])\n\n\t# Figure out how long it took to get the batch data\n\ttend = time.time()\n\tprint(\"Get batch took: %d msec\" % ((tend-tstart)*1000))\n\n # Create a contact sheet of all the images and display it\n\timgstack = []\n\tfor i in range(params[\"batch_size\"] // 10):\n\t\timgstack.append(np.hstack(imgs[i*10:i*10+10]))\n\timg = np.vstack(imgstack)\n\tcv2.imshow(\"imgbatch\",img)\n\tk = cv2.waitKey(0)\n # Allow early termination\n\tif k & 0xFF == ord('q'):\n\t\tbreak\n\telif k & 0xFF == ord('Q'):\n\t\tbreak\n\telif k & 0xFF == 27: # Also check for escape key\n\t\tbreak\n"
] |
[
[
"numpy.hstack",
"numpy.zeros",
"numpy.vstack",
"numpy.frombuffer"
]
] |
Fudan-Autonomous-Driving-Perception/HRNet-Semantic-Segmentation
|
[
"37a403e68047b29b03d564ee5c6df6c27b332c64"
] |
[
"lib/datasets/a2d2-split-mask.py"
] |
[
"import os\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom .base_dataset import BaseDataset\n\nclass A2D2(BaseDataset):\n def __init__(self, \n root, \n list_path, \n num_samples=None, \n num_classes=19,\n multi_scale=True, \n flip=True, \n ignore_label=-1, \n base_size=2048, \n crop_size=(512, 1024), \n downsample_rate=1,\n scale_factor=16,\n mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225]):\n\n super(A2D2, self).__init__(ignore_label, base_size,\n crop_size, downsample_rate, scale_factor, mean, std,)\n\n self.root = root\n self.list_path = list_path\n self.num_classes = num_classes\n\n self.multi_scale = multi_scale\n self.flip = flip\n \n imgs_path = os.path.join(self.root, self.list_path, 'image')\n img_list = os.listdir(imgs_path)\n self.img_list = [(os.path.join(imgs_path, il), os.path.join(self.root, self.list_path, 'mask', il))\n for il in img_list]\n\n self.files = self.read_files()\n if num_samples:\n self.files = self.files[:num_samples]\n\n self.label_mapping = {6: 1, 9: 2, 18: 3, 30: 4}\n self.label_mapping_inv = {v:k for k,v in self.label_mapping.items()}\n self.class_weights = torch.FloatTensor([1., 1., 1., 1., 1., 1., 1.5, 1., 1., 1.5, \n 1., 1., 1., 1., 1., 1., 1., 1., 1.5, 1., \n 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., \n 1.5, 1., 1., 1., 1., 1., 1., 1.]).cuda()\n \n def read_files(self):\n files = []\n if 'test' in self.list_path:\n for item in self.img_list:\n image_path = item\n name = os.path.splitext(os.path.basename(image_path[0]))[0]\n files.append({\n \"img\": image_path[0],\n \"name\": name,\n })\n else:\n for item in self.img_list:\n image_path, label_path = item\n name = os.path.splitext(os.path.basename(label_path))[0]\n files.append({\n \"img\": image_path,\n \"label\": label_path,\n \"name\": name,\n \"weight\": 1\n })\n return files\n \n def convert_label(self, label, inverse=False):\n if inverse:\n mask = np.zeros(label.shape)\n trainids = self.label_mapping.values()\n label_inv = np.zeros_like(label)\n for i in trainids:\n label_inv[label == i] = self.label_mapping_inv[i]\n label = label_inv\n else:\n mask = np.zeros(label.shape)\n needs = self.label_mapping.keys()\n for c in needs:\n mask[label == c] = self.label_mapping[c] \n label = mask\n return label\n\n def __getitem__(self, index):\n item = self.files[index]\n name = item[\"name\"]\n # image = cv2.imread(os.path.join(self.root,'cityscapes',item[\"img\"]),\n # cv2.IMREAD_COLOR)\n image = cv2.imread(item[\"img\"],\n cv2.IMREAD_COLOR)\n size = image.shape\n\n if 'test' in self.list_path:\n image = self.input_transform(image)\n image = image.transpose((2, 0, 1))\n\n return image.copy(), np.array(size), name\n\n # label = cv2.imread(os.path.join(self.root,'cityscapes',item[\"label\"]),\n # cv2.IMREAD_GRAYSCALE)\n label = cv2.imread(item[\"label\"])\n label = self.convert_label(cv2.cvtColor(label, cv2.COLOR_BGR2RGB))\n\n image, label = self.gen_sample(image, label, \n self.multi_scale, self.flip)\n\n return image.copy(), label.copy(), np.array(size), name\n\n def multi_scale_inference(self, config, model, image, scales=[1], flip=False):\n batch, _, ori_height, ori_width = image.size()\n assert batch == 1, \"only supporting batchsize 1.\"\n image = image.numpy()[0].transpose((1,2,0)).copy()\n stride_h = np.int(self.crop_size[0] * 1.0)\n stride_w = np.int(self.crop_size[1] * 1.0)\n final_pred = torch.zeros([1, self.num_classes,\n ori_height,ori_width]).cuda()\n for scale in scales:\n new_img = self.multi_scale_aug(image=image,\n rand_scale=scale,\n rand_crop=False)\n height, width = new_img.shape[:-1]\n \n if scale <= 1.0:\n new_img = new_img.transpose((2, 0, 1))\n new_img = np.expand_dims(new_img, axis=0)\n new_img = torch.from_numpy(new_img)\n preds = self.inference(config, model, new_img, flip)\n preds = preds[:, :, 0:height, 0:width]\n else:\n new_h, new_w = new_img.shape[:-1]\n rows = np.int(np.ceil(1.0 * (new_h - \n self.crop_size[0]) / stride_h)) + 1\n cols = np.int(np.ceil(1.0 * (new_w - \n self.crop_size[1]) / stride_w)) + 1\n preds = torch.zeros([1, self.num_classes,\n new_h,new_w]).cuda()\n count = torch.zeros([1,1, new_h, new_w]).cuda()\n\n for r in range(rows):\n for c in range(cols):\n h0 = r * stride_h\n w0 = c * stride_w\n h1 = min(h0 + self.crop_size[0], new_h)\n w1 = min(w0 + self.crop_size[1], new_w)\n h0 = max(int(h1 - self.crop_size[0]), 0)\n w0 = max(int(w1 - self.crop_size[1]), 0)\n crop_img = new_img[h0:h1, w0:w1, :]\n crop_img = crop_img.transpose((2, 0, 1))\n crop_img = np.expand_dims(crop_img, axis=0)\n crop_img = torch.from_numpy(crop_img)\n pred = self.inference(config, model, crop_img, flip)\n preds[:,:,h0:h1,w0:w1] += pred[:,:, 0:h1-h0, 0:w1-w0]\n count[:,:,h0:h1,w0:w1] += 1\n preds = preds / count\n preds = preds[:,:,:height,:width]\n\n preds = F.interpolate(\n preds, (ori_height, ori_width), \n mode='bilinear', align_corners=config.MODEL.ALIGN_CORNERS\n ) \n final_pred += preds\n return final_pred\n\n def get_palette(self, n):\n palette = [0] * (n * 3)\n for j in range(0, n):\n lab = j\n palette[j * 3 + 0] = 0\n palette[j * 3 + 1] = 0\n palette[j * 3 + 2] = 0\n i = 0\n while lab:\n palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))\n palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))\n palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))\n i += 1\n lab >>= 3\n return palette\n\n def save_pred(self, preds, sv_path, name):\n palette = self.get_palette(256)\n preds = np.asarray(np.argmax(preds.cpu(), axis=1), dtype=np.uint8)\n for i in range(preds.shape[0]):\n pred = self.convert_label(preds[i], inverse=True)\n save_img = Image.fromarray(pred)\n save_img.putpalette(palette)\n save_img.save(os.path.join(sv_path, name[i]+'.png'))\n\n \n \n"
] |
[
[
"numpy.expand_dims",
"torch.zeros",
"torch.from_numpy",
"numpy.int",
"numpy.ceil",
"numpy.zeros_like",
"torch.FloatTensor",
"torch.nn.functional.interpolate",
"numpy.array",
"numpy.zeros"
]
] |
kuredatan/suboptimal-buqo
|
[
"1bb892bfac6f895153cd34679f4d493a2920ce50"
] |
[
"main.py"
] |
[
"#coding:utf-8\n\nfrom parameters import selection_phi, noise, P, print_probas, print_image, get_image, g1, g2, l2, iota, N, alpha, compute_epsilon, compute_tau, characteristic\nfrom tools import estimation_MAP, projection_C, projection_S, in_S\nimport numpy as np\n\n#-------------- BUQO ALGORITHM\n\ndef main(x, sigma=5, niter=1, true_sigma=None, Phi=None, eps = 1e-5, print_stuff=True):\n\trhos, vs = [], []\n\tif (not true_sigma):\n\t\ttrue_sigma = sigma\n\tepsilon = compute_epsilon(sigma)\n\ttau = compute_tau(alpha)\n\tfor _ in range(niter):\n\t\tPhi = selection_phi(x) if (not Phi) else Phi\n\t\tprint(\"Phi = \" + str(Phi))\n\t\t## Preprocessing: turn x into the observation y\n\t\tprint(\"\\n>>>>>>>>> Observation\")\n\t\ty = P(x) + noise(sigma=true_sigma)\n\t\tif (print_stuff):\n\t\t\tprint(\"[True value] p(x|y) = \" + str(round(np.exp(-g1(x, y, sigma)-g2(x, Phi)), 5)))\n\t\t\tprint_image(y, \"Observation of true image\")\n\t\t## I. MAP estimation\n\t\tprint(\"\\n>>>>>>>>> MAP estimation\")\n\t\tx_hat = estimation_MAP(y, sigma, P, g1, g2, N, Phi, epsilon)\n\t\tif (print_stuff):\n\t\t\tprint_probas(x_hat, Phi, y, sigma, var=\"x_hat\")\n\t\t\tprint_image(x_hat, \"MAP estimation\")\n\t\t## II. Define S (see tools.py)\n\t\t## III. Compute C_alpha (see tools.py)\n\t\t## IV. Compute dist(S, C_alpha)\n\t\tprint(\"\\n>>>>>>>>> Distance C_alpha - S\")\n\t\t## Alternating projection algorithm (Von Neumann's)\n\t\tf_C = lambda u : g1(u, y, sigma)+iota(g2(x, Phi) <= g2(x_hat, Phi)+N*(tau+1))\n\t\tf_S = lambda u : iota(in_S(u))\n\t\t## Random initialization for POCS\n\t\tx0 = np.random.normal(50, 50, len(x_hat))\n\t\tif (print_stuff):\n\t\t\tprint_image(x0, \"Image initiale\")\n\t\ty_old = projection_C(x0, P, y, epsilon, g1, g2, sigma, Phi, x_hat, tau, N)\n\t\tx_old = projection_S(y_old.copy())\n\t\ti = 0\n\t\tniter = 1\n\t\twhile (i < niter):\n\t\t\ty_s = projection_C(x_old.copy(), P, y, epsilon, g1, g2, sigma, Phi, x_hat, tau, N)\n\t\t\tx_s = projection_S(y_s.copy())\n\t\t\tif (l2(x_s-x_old) < eps or l2(y_s-y_old) < eps):\n\t\t\t\tprint(\"\\n(*) Converged: True in \" + str(i+1) + \" iterations.\")\n\t\t\t\tbreak\n\t\t\ti += 1\n\t\t\ty_old = y_s.copy()\n\t\t\tx_old = x_s.copy()\n\t\tif (not niter):\n\t\t\ty_s = y_old.copy()\n\t\t\tx_s = x_old.copy()\n\t\tif (i == niter):\n\t\t\tprint(\"Warning: Maximum number of iterations (niter=\" + str(niter) + \") has been exceeded.\")\n\t\td = l2(x_s-y_s)\n\t\tif (print_stuff):\n\t\t\tprint(\"\\n | f_C | f_S\")\n\t\t\tprint(\"----|---------|-----\")\n\t\t\tprint(\"y_C | \" + str(f_C(y_s)) + \" | \" + str(f_S(y_s)))\n\t\t\tprint(\"\\^x | \" + str(f_C(x_hat)) + \" | \" + str(f_S(x_hat)))\n\t\t\tprint(\"x_S | \" + str(f_C(x_s)) + \" | \" + str(f_S(x_s)) + \"\\n\")\n\t\t\tprint(\"d(C_alpha, S) = \" + str(round(d, 3)))\n\t\t\tprint_probas(x_s, Phi, y, sigma, var=\"x_S\")\n\t\t\tprint_image(x_s, \"Argmin_{x \\in S} d(x, C_alpha)\")\n\t\tprint(\"\\n>>>>>>>>> Statistical test\")\n\t\trho_alpha = d/l2(x_hat-x_s)\n\t\t## V. \"Statistical\" test\n\t\tif (d > 0):\n\t\t\tprint(\"REJECT H0 with alpha = \" + str(alpha))\n\t\t\tv = 1\n\t\telse:\n\t\t\tprint(\"CANNOT REJECT H0 with alpha = \" + str(alpha))\n\t\t\tv = 0\n\t\tprint(\"rho_alpha = \" + str(round(rho_alpha, 2)))\n\t\tprint(\"----------------------------------------\")\n\t\trhos.append(rho_alpha)\n\t\tvs.append(v)\n\treturn rhos, vs\n\n#-------------- TESTS\n\nif __name__ == '__main__':\n\timport matplotlib.pyplot as plt\n\tniter = 1\n\tx = get_image()\n\trhos, vs = main(x, niter=niter, print_stuff=True)\n\tif (niter > 1):\n\t\tplt.plot(range(niter), rhos, col=[\"g+\" if (v==1) else \"r+\" for v in vs])\n\tplt.show()\n"
] |
[
[
"matplotlib.pyplot.show"
]
] |
SweepTest/HUXt
|
[
"0f5ad68aa6a88eff7921a5325aefa71be92af781"
] |
[
"code/huxt_inputs.py"
] |
[
"import httplib2\nimport urllib\nimport huxt as H\nimport os\nfrom pyhdf.SD import SD, SDC \nimport numpy as np\nimport astropy.units as u\nfrom scipy.io import netcdf\n\n\ndef get_MAS_boundary_conditions(cr=np.NaN, observatory='', runtype='', runnumber=''):\n \"\"\"\n A function to grab the Vr and Br boundary conditions from MHDweb. An order\n of preference for observatories is given in the function. Checks first if\n the data already exists in the HUXt boundary condition folder\n\n Parameters\n ----------\n cr : INT\n Carrington rotation number \n observatory : STRING\n Name of preferred observatory (e.g., 'hmi','mdi','solis',\n 'gong','mwo','wso','kpo'). Empty if no preference and automatically selected \n runtype : STRING\n Name of preferred MAS run type (e.g., 'mas','mast','masp').\n Empty if no preference and automatically selected \n runnumber : STRING\n Name of preferred MAS run number (e.g., '0101','0201').\n Empty if no preference and automatically selected \n\n Returns\n -------\n flag : INT\n 1 = successful download. 0 = files exist, -1 = no file found.\n\n \"\"\"\n \n assert(np.isnan(cr) == False)\n \n # The order of preference for different MAS run results\n overwrite = False\n if not observatory:\n observatories_order = ['hmi', 'mdi', 'solis', 'gong', 'mwo', 'wso', 'kpo']\n else:\n observatories_order = [str(observatory)]\n overwrite = True # If the user wants a specific observatory, overwrite what's already downloaded\n \n if not runtype:\n runtype_order = ['masp', 'mas', 'mast']\n else:\n runtype_order = [str(runtype)]\n overwrite = True\n \n if not runnumber:\n runnumber_order = ['0201', '0101']\n else:\n runnumber_order = [str(runnumber)]\n overwrite = True\n \n # Get the HUXt boundary condition directory\n dirs = H._setup_dirs_()\n _boundary_dir_ = dirs['boundary_conditions'] \n \n # Example URL: http://www.predsci.com/data/runs/cr2010-medium/mdi_mas_mas_std_0101/helio/br_r0.hdf\n heliomas_url_front = 'http://www.predsci.com/data/runs/cr'\n heliomas_url_end = '_r0.hdf'\n \n vrfilename = 'HelioMAS_CR'+str(int(cr)) + '_vr'+heliomas_url_end\n brfilename = 'HelioMAS_CR'+str(int(cr)) + '_br'+heliomas_url_end\n \n if (os.path.exists(os.path.join(_boundary_dir_, brfilename)) == False or\n os.path.exists(os.path.join(_boundary_dir_, vrfilename)) == False or\n overwrite == True): # Check if the files already exist\n\n # Search MHDweb for a HelioMAS run, in order of preference\n h = httplib2.Http()\n foundfile = False\n for masob in observatories_order:\n for masrun in runtype_order:\n for masnum in runnumber_order:\n urlbase = (heliomas_url_front + str(int(cr)) + '-medium/' + masob + '_' +\n masrun + '_mas_std_' + masnum + '/helio/')\n url = urlbase + 'br' + heliomas_url_end\n\n # See if this br file exists\n resp = h.request(url, 'HEAD')\n if int(resp[0]['status']) < 400:\n foundfile = True\n \n # Exit all the loops - clumsy, but works\n if foundfile: \n break\n if foundfile:\n break\n if foundfile:\n break\n \n if foundfile == False:\n print('No data available for given CR and observatory preferences')\n return -1\n \n # Download teh vr and br files\n print('Downloading from: ', urlbase)\n urllib.request.urlretrieve(urlbase + 'br' + heliomas_url_end,\n os.path.join(_boundary_dir_, brfilename))\n urllib.request.urlretrieve(urlbase+'vr'+heliomas_url_end,\n os.path.join(_boundary_dir_, vrfilename))\n \n return 1\n else:\n print('Files already exist for CR' + str(int(cr)))\n return 0\n\n \ndef read_MAS_vr_br(cr):\n \"\"\"\n A function to read in the MAS coundary conditions for a given CR\n\n Parameters\n ----------\n cr : INT\n Carrington rotation number\n\n Returns\n -------\n MAS_vr : NP ARRAY (NDIM = 2)\n Solar wind speed at 30rS, in km/s\n MAS_vr_Xa : NP ARRAY (NDIM = 1)\n Carrington longitude of Vr map, in rad\n MAS_vr_Xm : NP ARRAY (NDIM = 1)\n Latitude of Vr as angle down from N pole, in rad\n MAS_br : NP ARRAY (NDIM = 2)\n Radial magnetic field at 30rS, in model units\n MAS_br_Xa : NP ARRAY (NDIM = 1)\n Carrington longitude of Br map, in rad\n MAS_br_Xm : NP ARRAY (NDIM = 1)\n Latitude of Br as angle down from N pole, in rad\n\n \"\"\"\n # Get the boundary condition directory\n dirs = H._setup_dirs_()\n _boundary_dir_ = dirs['boundary_conditions'] \n # Create the filenames\n heliomas_url_end = '_r0.hdf'\n vrfilename = 'HelioMAS_CR'+str(int(cr)) + '_vr' + heliomas_url_end\n brfilename = 'HelioMAS_CR'+str(int(cr)) + '_br' + heliomas_url_end\n\n filepath = os.path.join(_boundary_dir_, vrfilename)\n assert os.path.exists(filepath)\n \n file = SD(filepath, SDC.READ)\n \n sds_obj = file.select('fakeDim0') # select sds\n MAS_vr_Xa = sds_obj.get() # get sds data\n sds_obj = file.select('fakeDim1') # select sds\n MAS_vr_Xm = sds_obj.get() # get sds data\n sds_obj = file.select('Data-Set-2') # select sds\n MAS_vr = sds_obj.get() # get sds data\n \n # Convert from model to physicsal units\n MAS_vr = MAS_vr*481.0 * u.km/u.s\n MAS_vr_Xa = MAS_vr_Xa * u.rad\n MAS_vr_Xm = MAS_vr_Xm * u.rad\n \n filepath = os.path.join(_boundary_dir_, brfilename)\n assert os.path.exists(filepath)\n file = SD(filepath, SDC.READ)\n \n sds_obj = file.select('fakeDim0') # select sds\n MAS_br_Xa = sds_obj.get() # get sds data\n sds_obj = file.select('fakeDim1') # select sds\n MAS_br_Xm = sds_obj.get() # get sds data\n sds_obj = file.select('Data-Set-2') # select sds\n MAS_br = sds_obj.get() # get sds data\n \n MAS_br_Xa = MAS_br_Xa * u.rad\n MAS_br_Xm = MAS_br_Xm * u.rad\n \n return MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm\n\n\ndef get_MAS_long_profile(cr, lat=0.0*u.deg):\n \"\"\"\n a function to download, read and process MAS output to provide HUXt boundary\n conditions at a given latitude\n\n Parameters\n ----------\n cr : INT\n Carrington rotation number\n lat : FLOAT\n Latitude at which to extract the longitudinal profile, measure up from equator\n\n Returns\n -------\n vr_in : NP ARRAY (NDIM = 1)\n Solar wind speed as a function of Carrington longitude at solar equator.\n Interpolated to HUXt longitudinal resolution. In km/s\n br_in : NP ARRAY(NDIM = 1)\n Radial magnetic field as a function of Carrington longitude at solar equator.\n Interpolated to HUXt longitudinal resolution. Dimensionless\n\n \"\"\"\n assert(np.isnan(cr) == False and cr > 0)\n assert(lat >= -90.0*u.deg)\n assert(lat <= 90.0*u.deg)\n \n # Convert angle from equator to angle down from N pole\n ang_from_N_pole = np.pi/2 - (lat.to(u.rad)).value\n \n # Check the data exist, if not, download them\n flag = get_MAS_boundary_conditions(cr)\n assert(flag > -1)\n \n # Read the HelioMAS data\n MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)\n \n # Extract the value at the given latitude\n vr = np.ones(len(MAS_vr_Xa))\n for i in range(0, len(MAS_vr_Xa)):\n vr[i] = np.interp(ang_from_N_pole, MAS_vr_Xm.value, MAS_vr[i][:].value)\n \n br = np.ones(len(MAS_br_Xa))\n for i in range(0, len(MAS_br_Xa)):\n br[i] = np.interp(ang_from_N_pole, MAS_br_Xm.value, MAS_br[i][:])\n \n # Now interpolate on to the HUXt longitudinal grid\n longs, dlon, nlon = H.longitude_grid(lon_start=0.0 * u.rad, lon_stop=2*np.pi * u.rad)\n vr_in = np.interp(longs.value, MAS_vr_Xa.value, vr)*u.km/u.s\n br_in = np.interp(longs.value, MAS_br_Xa.value, br)\n \n return vr_in\n\n\ndef get_MAS_maps(cr):\n \"\"\"\n a function to download, read and process MAS output to provide HUXt boundary\n conditions as lat-long maps, along with angle from equator for the maps\n maps returned in native resolution, not HUXt resolution\n\n Parameters\n ----------\n cr : INT\n Carrington rotation number\n\n\n Returns\n -------\n vr_map : NP ARRAY \n Solar wind speed as a Carrington longitude-latitude map. In km/s \n vr_lats :\n The latitudes for the Vr map, in radians from trhe equator \n vr_longs :\n The Carrington longitudes for the Vr map, in radians\n br_map : NP ARRAY\n Br as a Carrington longitude-latitude map. Dimensionless\n br_lats :\n The latitudes for the Br map, in radians from trhe equator\n br_longs :\n The Carrington longitudes for the Br map, in radians \n \"\"\"\n \n assert(np.isnan(cr) == False and cr > 0)\n \n # Check the data exist, if not, download them\n flag = get_MAS_boundary_conditions(cr)\n assert(flag > -1)\n \n # Read the HelioMAS data\n MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)\n \n vr_map = MAS_vr\n br_map = MAS_br\n \n # Convert the lat angles from N-pole to equator centred\n vr_lats = (np.pi/2)*u.rad - MAS_vr_Xm\n br_lats = (np.pi/2)*u.rad - MAS_br_Xm\n \n # Flip lats, so they're increasing in value\n vr_lats = np.flipud(vr_lats)\n br_lats = np.flipud(br_lats)\n vr_map = np.fliplr(vr_map)\n br_map = np.fliplr(br_map)\n \n vr_longs = MAS_vr_Xa\n br_longs = MAS_br_Xa\n\n return vr_map, vr_lats, vr_longs\n\n\[email protected]_input(v_outer=u.km / u.s)\[email protected]_input(r_outer=u.solRad)\[email protected]_input(lon_outer=u.rad)\[email protected]_input(r_inner=u.solRad)\ndef map_v_inwards(v_outer, r_outer, lon_outer, r_inner):\n \"\"\"\n Function to map v from r_outer (in rs) to r_inner (in rs) accounting for \n residual acceleration, but neglecting stream interactions.\n \n :param v_outer: Solar wind speed at outer radial distance. Units of km/s.\n :param r_outer: Radial distance at outer radial distance. Units of km. \n :param lon_outer: Carrington longitude at outer distance. Units of rad\n :param r_inner: Radial distance at inner radial distance. Units of km.\n :return v_inner: Solar wind speed mapped from r_outer to r_inner. Units of km/s.\n :return lon_inner: Carrington longitude at r_inner. Units of rad.\n \"\"\"\n\n # Get the acceleration parameters\n constants = H.huxt_constants()\n alpha = constants['alpha'] # Scale parameter for residual SW acceleration\n rH = constants['r_accel'].to(u.kilometer).value # Spatial scale parameter for residual SW acceleration\n Tsyn = constants['synodic_period'].to(u.s).value\n r_outer = r_outer.to(u.km).value\n r_inner = r_inner.to(u.km).value\n r_30 = 30*u.solRad\n r_30 = r_30.to(u.km).value\n\n # Compute the 30 rS speed\n v30 = v_outer.value * (1 + alpha * (1 - np.exp((r_30 - r_outer) / rH)))\n \n # Compute the speed at the new inner boundary height (using Vacc term, equation 5 in the paper)\n v0 = v30 * (1 + alpha * (1 - np.exp((r_30 - r_inner) / rH)))\n\n # Compute the transit time from the new to old inner boundary heights (i.e., integrate equations 3 and 4 wrt to r)\n A = v0 + alpha * v0\n term1 = rH * np.log(A * np.exp(r_outer / rH) - alpha * v0 * np.exp(r_inner / rH)) / A\n term2 = rH * np.log(A * np.exp(r_inner / rH) - alpha * v0 * np.exp(r_inner / rH)) / A\n T_integral = term1 - term2\n\n # Work out the longitudinal shift\n phi_new = H._zerototwopi_(lon_outer.value + (T_integral / Tsyn) * 2 * np.pi)\n\n return v0*u.km/u.s, phi_new*u.rad\n\n\[email protected]_input(v_outer=u.km / u.s)\[email protected]_input(r_outer=u.solRad)\[email protected]_input(r_inner=u.solRad)\ndef map_v_boundary_inwards(v_outer, r_outer, r_inner):\n \"\"\"\n Function to map a longitudinal V series from r_outer (in rs) to r_inner (in rs)\n accounting for residual acceleration, but neglecting stream interactions.\n Series return on HUXt longitudinal grid, not input grid\n \n :param v_outer: Solar wind speed at outer radial boundary. Units of km/s.\n :param r_outer: Radial distance at outer radial boundary. Units of km.\n :param r_inner: Radial distance at inner radial boundary. Units of km.\n :return v_inner: Solar wind speed mapped from r_outer to r_inner. Units of km/s.\n \"\"\"\n\n if r_outer < r_inner:\n raise ValueError(\"Warning: r_outer < r_inner. Mapping will not work.\")\n\n # Compute the longitude grid from the length of the vouter input variable\n lon, dlon, nlon = H.longitude_grid() \n \n # Map each point in to a new speed and longitude\n v0, phis_new = map_v_inwards(v_outer, r_outer, lon, r_inner)\n\n # Interpolate the mapped speeds back onto the regular Carr long grid,\n # making boundaries periodic\n v_inner = np.interp(lon, phis_new, v0, period=2*np.pi) \n\n return v_inner\n\n\[email protected]_input(v_map=u.km / u.s)\[email protected]_input(v_map_lat=u.rad)\[email protected]_input(v_map_long=u.rad)\[email protected]_input(r_outer=u.solRad)\[email protected]_input(r_inner=u.solRad)\ndef map_vmap_inwards(v_map, v_map_lat, v_map_long, r_outer, r_inner):\n \"\"\"\n Function to map a V Carrington map from r_outer (in rs) to r_inner (in rs),\n accounting for acceleration, but ignoring stream interaction\n Map returned on input coord system, not HUXT resolution\n :param v_map: Solar wind speed Carrington map at outer radial boundary. Units of km/s.\n :param v_map_lat: Latitude (from equator) of v_map positions. Units of radians\n :param v_map_long: Carrington longitude of v_map positions. Units of radians\n :param r_outer: Radial distance at outer radial boundary. Units of km.\n :param r_inner: Radial distance at inner radial boundary. Units of km.\n :return v_map_inner: Solar wind speed map at r_inner. Units of km/s.\n \"\"\"\n\n if r_outer < r_inner:\n raise ValueError(\"Warning: r_outer < r_inner. Mapping will not work.\")\n\n # Check the dimensions\n assert(len(v_map_lat) == len(v_map[1, :]))\n assert(len(v_map_long) == len(v_map[:, 1]))\n\n v_map_inner = np.ones((len(v_map_long), len(v_map_lat)))\n for ilat in range(0, len(v_map_lat)):\n # Map each point in to a new speed and longitude\n v0, phis_new = map_v_inwards(v_map[:, ilat], r_outer, v_map_long, r_inner)\n\n # Interpolate the mapped speeds back onto the regular Carr long grid,\n # making boundaries periodic * u.km/u.s\n v_map_inner[:, ilat] = np.interp(v_map_long.value, phis_new.value, v0.value, period=2*np.pi)\n\n return v_map_inner * u.km / u.s\n\n\ndef get_PFSS_maps(filepath):\n \"\"\"\n a function to load, read and process PFSSpy output to provide HUXt boundary\n conditions as lat-long maps, along with angle from equator for the maps\n maps returned in native resolution, not HUXt resolution\n\n Parameters\n ----------\n filepath : STR \n The filepath for the PFSSpy .nc file\n\n Returns\n -------\n vr_map : NP ARRAY \n Solar wind speed as a Carrington longitude-latitude map. In km/s \n vr_lats :\n The latitudes for the Vr map, in radians from trhe equator \n vr_longs :\n The Carrington longitudes for the Vr map, in radians\n br_map : NP ARRAY\n Br as a Carrington longitude-latitude map. Dimensionless\n br_lats :\n The latitudes for the Br map, in radians from trhe equator\n br_longs :\n The Carrington longitudes for the Br map, in radians \n\n \"\"\"\n \n assert os.path.exists(filepath)\n nc = netcdf.netcdf_file(filepath, 'r')\n \n cotheta = nc.variables['cos(th)'].data\n vr_lats = np.arcsin(cotheta[:, 0])*u.rad\n br_lats = vr_lats\n \n phi = nc.variables['ph'].data\n vr_longs = phi[0, :] * u.rad\n br_longs = vr_longs\n \n br_map = np.rot90(nc.variables['br'].data)\n vr_map = np.rot90(nc.variables['vr'].data) * u.km / u.s\n\n return vr_map, vr_lats, vr_longs, br_map, br_lats, br_longs\n"
] |
[
[
"numpy.rot90",
"numpy.arcsin",
"numpy.fliplr",
"numpy.isnan",
"numpy.flipud",
"scipy.io.netcdf.netcdf_file",
"numpy.interp",
"numpy.exp"
]
] |
TomF98/torchphysics
|
[
"775d9aca71752a568f1fca972c958b99107f3b7c",
"775d9aca71752a568f1fca972c958b99107f3b7c"
] |
[
"src/torchphysics/models/qres.py",
"tests/test_points.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom .model import Model\nfrom ..problem.spaces import Points\n\n\nclass Quadratic(nn.Module):\n \"\"\"Implements a quadratic layer of the form: W_1*x (*) W_2*x + W_1*x + b.\n Here (*) means the hadamard product of two vectors (elementwise multiplication).\n W_1, W_2 are weight matrices and b is a bias vector.\n\n Parameters\n ----------\n in_features : int \n size of each input sample.\n out_features :\n size of each output sample.\n xavier_gains : float or list\n For the weight initialization a Xavier/Glorot algorithm will be used.\n The gain can be specified over this value.\n Default is 5/3. \n \"\"\"\n def __init__(self, in_features, out_features, xavier_gains):\n super().__init__()\n bias = torch.nn.init.xavier_normal_(torch.zeros(1, out_features), \n gain=xavier_gains) \n self.bias = torch.nn.Parameter(bias)\n self.linear_weights = torch.nn.Linear(in_features=in_features, \n out_features=out_features, \n bias=False)\n torch.nn.init.xavier_normal_(self.linear_weights.weight, gain=xavier_gains) \n self.quadratic_weights = torch.nn.Linear(in_features=in_features, \n out_features=out_features,\n bias=False)\n torch.nn.init.xavier_normal_(self.quadratic_weights.weight, gain=xavier_gains) \n\n def forward(self, points):\n linear_out = self.linear_weights(points)\n quad_out = self.quadratic_weights(points)\n return quad_out * linear_out + linear_out + self.bias\n\n @property\n def in_features(self):\n return self.linear_weights.weight.shape[1]\n\n @property\n def out_features(self):\n return self.linear_weights.weight.shape[0]\n\n\nclass QRES(Model):\n \"\"\"Implements the quadratic residual networks from [1].\n Instead of a linear layer, a quadratic layer W_1*x (*) W_2*x + W_1*x + b\n will be used. Here (*) means the hadamard product of two vectors \n (elementwise multiplication).\n\n Parameters\n ----------\n input_space : Space\n The space of the points the can be put into this model.\n output_space : Space\n The space of the points returned by this model.\n hidden : list or tuple\n The number and size of the hidden layers of the neural network.\n The lenght of the list/tuple will be equal to the number\n of hidden layers, while the i-th entry will determine the number\n of neurons of each layer.\n E.g hidden = (10, 5) -> 2 layers, with 10 and 5 neurons.\n activations : torch.nn or list, optional\n The activation functions of this network. If a single function is passed\n as an input, will use this function for each layer.\n If a list is used, will use the i-th entry for i-th layer.\n Deafult is nn.Tanh().\n xavier_gains : float or list, optional\n For the weight initialization a Xavier/Glorot algorithm will be used.\n The gain can be specified over this value.\n Default is 5/3. \n\n Notes\n -----\n .. [1] Jie Bu and Anuj Karpatne, \"Quadratic Residual Networks: \n A New Class of Neural Networks for Solving Forward and Inverse Problems \n in Physics Involving PDEs\", 2021\n \"\"\"\n def __init__(self,\n input_space,\n output_space,\n hidden=(20,20,20),\n activations=nn.Tanh(),\n xavier_gains=5/3):\n super().__init__(input_space, output_space)\n\n if not isinstance(activations, (list, tuple)):\n activations = len(hidden) * [activations]\n if not isinstance(xavier_gains, (list, tuple)):\n xavier_gains = len(hidden) * [xavier_gains]\n\n layers = []\n layers.append(Quadratic(self.input_space.dim, hidden[0], xavier_gains[0]))\n layers.append(activations[0])\n for i in range(len(hidden)-1):\n layers.append(Quadratic(hidden[i], hidden[i+1], xavier_gains[i+1]))\n layers.append(activations[i+1])\n layers.append(Quadratic(hidden[-1], self.output_space.dim, 1.0))\n\n self.sequential = nn.Sequential(*layers)\n\n def forward(self, points):\n return Points(self.sequential(points), self.output_space)",
"import torch\nimport pytest\nimport numpy as np\n\nfrom torchphysics.problem.spaces import R1, R2, Points\n\n\ndef test_create_points():\n p = Points(torch.ones((3, 1)), R1('x'))\n assert p.space.dim == 1\n assert isinstance(p._t, torch.Tensor)\n\n\ndef test_get_tensor_from_point():\n p = Points(torch.ones((3, 1)), R1('x'))\n assert isinstance(p.as_tensor, torch.Tensor) \n assert torch.equal(p.as_tensor, torch.ones((3, 1)))\n\n\ndef test_length_of_points():\n p = Points(torch.ones((33, 2)), R2('x'))\n assert len(p) == 33 \n\n\ndef test_check_device():\n p = Points(torch.ones((33, 2)), R2('x'))\n assert p.device.type == 'cpu'\n\n\ndef test_create_points_space_has_to_fit_points():\n with pytest.raises(AssertionError):\n Points(torch.ones((3, 2)), R1('x'))\n\n\ndef test_create_points_data_has_to_have_batch_dim():\n with pytest.raises(AssertionError):\n Points(torch.ones(3), R1('x'))\n\n\ndef test_create_empty_points():\n p = Points.empty()\n assert p.space.dim == 0\n\n\ndef test_join_points():\n p1 = Points(torch.ones((2, 1)), R1('x'))\n p2 = Points(torch.zeros((2, 2)), R2('y'))\n p = Points.joined(p1, p2)\n assert p.space.dim == 3\n assert torch.equal(p._t, torch.tensor([[1.0, 0, 0], [1, 0, 0]]))\n\n\ndef test_join_points_with_empty_point():\n p1 = Points(torch.ones((2, 1)), R1('x'))\n p2 = Points.empty()\n p = Points.joined(p1, p2)\n assert p.space.dim == 1\n assert torch.equal(p._t, torch.tensor([[1.0], [1]]))\n\n\ndef test_create_points_from_dict():\n inp_dict = {'x': torch.ones((2, 1)), 'y': 2*torch.ones((2, 2))}\n p = Points.from_coordinates(inp_dict)\n assert p.space.dim == 3\n assert 'x' in p.space\n assert 'y' in p.space\n assert torch.equal(p._t, torch.tensor([[1.0, 2, 2], [1, 2, 2]]))\n\n\ndef test_create_points_from_empty_dict():\n p = Points.from_coordinates({})\n assert p.space.dim == 0\n\n\ndef test_check_dim_of_points():\n p = Points(torch.ones((3, 1)), R1('x'))\n assert p.dim == 1\n\n\ndef test_check_variables_of_points():\n r = R1('x')\n p = Points(torch.ones((3, 1)), r)\n assert p.variables == r.variables\n\n\ndef test_points_to_coordinate_dict():\n p = Points(torch.ones((3, 3)), R1('x')*R2('u'))\n coords = p.coordinates\n assert isinstance(coords, dict)\n assert 'x' in coords.keys()\n assert 'u' in coords.keys()\n assert torch.equal(coords['x'], torch.ones((3, 1)))\n assert torch.equal(coords['u'], torch.ones((3, 2)))\n\n\ndef test_check_points_empty():\n p = Points(torch.ones((3, 3)), R1('x')*R2('u'))\n assert not p.isempty\n p = Points.empty()\n assert p.isempty \n\n\ndef test_check_points_equal():\n p1 = Points(torch.ones((3, 1)), R1('x'))\n p2 = Points(torch.ones((3, 1)), R1('y'))\n p3 = Points(torch.ones((2, 1)), R1('x'))\n assert p1 == p1\n assert not p1 == p2\n assert not p1 == p3\n\n\ndef test_points_get_item():\n X = R2('x')\n T = R1('t')\n p = Points(torch.tensor([[2.0,1.0,2.5], [1.0,3.0,1.0],\n [1.0,1.0,4.0], [1.0,5.0,1.0],\n [6.0,1.0,1.0]]), X*T)\n\n assert torch.all(p[1,'x'].as_tensor == torch.tensor([1.0, 3.0]))\n assert torch.all(p[1:3,'x'].as_tensor == torch.tensor([[1.0, 3.0],\n [1.0, 1.0]]))\n assert p[2:5,:] == p[2:5]\n assert p[2:5,:] == Points(torch.tensor([[1., 1., 4.], [1., 5., 1.],\n [6., 1., 1.]]), X*T)\n expected_coords = {'x': torch.tensor([[1., 1.], [1., 5.], [6., 1.]]),\n 't': torch.tensor([[4.], [1.], [1.]])}\n computed_coords = p[2:5,:].coordinates \n assert torch.equal(computed_coords['x'], expected_coords['x'])\n assert torch.equal(computed_coords['t'], expected_coords['t'])\n\n\ndef test_points_tensor_slice():\n p = Points(torch.tensor([[1, 2], [3.0, 4.0]]), R1('x')*R1('t'))\n slc = (p.as_tensor > 2)\n assert p[slc[:,0]] == Points(torch.tensor([[3.0, 4.0]]), R1('x')*R1('t'))\n with pytest.raises(IndexError):\n p[slc]\n\n\ndef test_slice_with_ellipsis():\n p = Points(torch.tensor([[1, 0.0], [2, 4.0], [9, 4]]), R1('x')*R1('t'))\n assert p == p[..., ]\n\n\ndef test_slice_with_ellipsis_and_picking_space():\n p = Points(torch.tensor([[1, 0.0], [2, 4.0], [9, 4]]), R1('x')*R1('t'))\n p_sliced = Points(torch.tensor([[1], [2], [9.0]]), R1('x'))\n assert p_sliced == p[..., 'x'] \n p_sliced = Points(torch.tensor([[0.0], [4], [4]]), R1('t'))\n assert p_sliced == p[..., 't'] \n\n\ndef test_extract_given_indices_with_tensor():\n p = Points(torch.tensor([[1, 0.0], [2, 4.0], [9, 4]]), R2('x'))\n p_sliced = Points(torch.tensor([[1, 0.0], [9, 4]]), R2('x'))\n assert p[torch.tensor([0, 2]),] == p_sliced\n\n\ndef test_extract_given_indices_with_list():\n p = Points(torch.tensor([[1, 4.0], [2, 4.0], [9, 4]]), R2('x'))\n p_sliced = Points(torch.tensor([[1, 4.0], [9, 4]]), R2('x'))\n assert p[[0, 2],] == p_sliced\n\n\ndef test_extract_given_indices_with_np_array():\n p = Points(torch.tensor([[1, 4.0], [2, 4.0], [23, 4]]), R2('x'))\n p_sliced = Points(torch.tensor([[2, 4.0], [23, 4]]), R2('x'))\n assert p[np.array([1, 2]),] == p_sliced\n\n\ndef test_iterate_over_points():\n p = Points(torch.tensor([[2], [2.0]]), R1('x'))\n iter_p = iter(p)\n for p in iter_p:\n assert isinstance(p, Points)\n assert p.as_tensor == 2.0\n\n\ndef test_add_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1 + p1\n assert isinstance(p, Points)\n assert torch.equal(torch.tensor([[4.0], [2.0]]), p.as_tensor)\n\n\ndef test_cant_add_points_of_different_spaces():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n with pytest.raises(AssertionError):\n p1 + p2\n\n\ndef test_substract_points():\n p1 = Points(torch.tensor([[2, 1], [1.0, 0]]), R2('x'))\n p = p1 - p1\n assert isinstance(p, Points)\n assert torch.equal(torch.tensor([[0.0, 0], [0.0, 0]]), p.as_tensor)\n\n\ndef test_cant_substract_points_of_different_spaces():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n with pytest.raises(AssertionError):\n p1 + p2\n\n\ndef test_multiply_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1 * p1\n assert isinstance(p, Points)\n assert torch.equal(torch.tensor([[4.0], [1.0]]), p.as_tensor)\n\n\ndef test_cant_multiply_points_of_different_spaces():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n with pytest.raises(AssertionError):\n p1 * p2\n\n\ndef test_divide_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1 / p1\n assert isinstance(p, Points)\n assert torch.equal(torch.tensor([[1.0], [1.0]]), p.as_tensor)\n\n\ndef test_cant_divide_points_of_different_spaces():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n with pytest.raises(AssertionError):\n p1 / p2\n\n\ndef test_raise_power_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1**p1\n assert isinstance(p, Points)\n assert torch.equal(torch.tensor([[4.0], [1.0]]), p.as_tensor)\n\n\ndef test_cant_raise_power_points_of_different_spaces():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n with pytest.raises(AssertionError):\n p1**p2\n\n\ndef test_or_for_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1 | p2\n assert isinstance(p, Points)\n assert 'x' in p.space\n assert len(p) == 4\n\n\ndef test_or_for_empty_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points.empty()\n p = p1 | p2\n assert p == p1\n p = p2 | p1\n assert p == p1\n\n\ndef test_join_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n p = p1.join(p2)\n assert isinstance(p, Points)\n assert 'x' in p.space\n assert 'y' in p.space\n assert len(p) == 2\n\n\ndef test_points_setitem():\n p1 = Points(torch.tensor([[2, 3], [1.0, 4]]), R1('x')*R1('y'))\n p2 = Points(torch.tensor([[2], [1.0]]), R1('y'))\n p1[..., 'y'] = p2\n assert p1 == Points(torch.tensor([[2, 2], [1.0, 1]]), R1('x')*R1('y'))\n\n\ndef test_join_empty_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p2 = Points.empty()\n p = p1.join(p2)\n assert p == p1\n p = p2.join(p1)\n assert p == p1\n\n\ndef test_repeat_points():\n p1 = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p = p1.repeat(4)\n assert isinstance(p, Points)\n assert len(p) == 8\n assert 'x' in p.space\n assert p._t[0] == p._t[2]\n assert not p._t[0] == p._t[1]\n assert p._t[5] == p._t[7]\n\n\ndef test_requires_grad_points():\n p = Points(torch.tensor([[2], [1.0]]), R1('x'))\n assert not p.requires_grad\n\n\ndef test_set_requires_grad_points():\n p = Points(torch.tensor([[2], [1.0]]), R1('x'))\n assert not p.requires_grad\n p.requires_grad = True\n assert p.requires_grad\n\n\ndef test_torch_function_for_points():\n p = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p_repeat = torch.repeat_interleave(p, 10, dim=0)\n assert isinstance(p_repeat, torch.Tensor)\n assert len(p_repeat) == 20\n assert p_repeat[0] == p_repeat[1]\n assert p_repeat[10] == p_repeat[11]\n\n\ndef test_torch_function_for_points_2():\n p = Points(torch.tensor([[2], [1.0]]), R1('x'))\n p_repeat = torch.neg(p)\n assert isinstance(p_repeat, torch.Tensor)\n assert len(p_repeat) == 2\n assert p_repeat[0] == -2.0\n assert p_repeat[1] == -1.0\n\n\ndef test_unsqueeze():\n p = Points(torch.tensor([[1, 0.0], [2, 4.0], [9, 4]]), R1('x')*R1('t'))\n tensor_0 = torch.tensor([[[1., 0.], [2., 4.], [9., 4.]]]) \n assert torch.allclose(p.unsqueeze(0)._t, tensor_0)\n tensor_1 = torch.tensor([[[1., 0.]], [[2., 4.]], [[9., 4.]]]) \n assert torch.allclose(p.unsqueeze(1)._t, tensor_1)\n assert torch.allclose(p.unsqueeze(-1)._t, tensor_1)"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Parameter",
"torch.zeros",
"torch.nn.init.xavier_normal_",
"torch.nn.Tanh",
"torch.nn.Linear"
],
[
"torch.ones",
"torch.zeros",
"torch.neg",
"torch.equal",
"torch.tensor",
"torch.repeat_interleave",
"numpy.array"
]
] |
hammerlab/stanity
|
[
"6c36abc207c4ce94f78968501dab839a56f35a41"
] |
[
"stanity/psis.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"Pareto smoothed importance sampling (PSIS)\n\nThis module implements Pareto smoothed importance sampling (PSIS) and PSIS\nleave-one-out (LOO) cross-validation for Python (Numpy).\n\nIncluded functions\n------------------\npsisloo\n Pareto smoothed importance sampling leave-one-out log predictive densities.\n\npsislw\n Pareto smoothed importance sampling.\n\ngpdfitnew\n Estimate the paramaters for the Generalized Pareto Distribution (GPD).\n\ngpinv\n Inverse Generalised Pareto distribution function.\n\nsumlogs\n Sum of vector where numbers are represented by their logarithms.\n\nReferences\n----------\nAki Vehtari, Andrew Gelman and Jonah Gabry (2017). Practical\nBayesian model evaluation using leave-one-out cross-validation\nand WAIC. Statistics and Computing, 27(5):1413–1432.\ndoi:10.1007/s11222-016-9696-4. https://arxiv.org/abs/1507.04544\n\nAki Vehtari, Andrew Gelman and Jonah Gabry (2017). Pareto\nsmoothed importance sampling. https://arxiv.org/abs/arXiv:1507.02646v5\n\n\"\"\"\n\nfrom __future__ import division # For Python 2 compatibility\nimport numpy as np\n\n# 3-Clause BSD License\n\"\"\"\nCopyright 2017 Aki Vehtari, Tuomas Sivula\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"\n\n\ndef psisloo(log_lik, **kwargs):\n r\"\"\"PSIS leave-one-out log predictive densities.\n\n Computes the log predictive densities given posterior samples of the log\n likelihood terms :math:`p(y_i|\\theta^s)` in input parameter `log_lik`.\n Returns a sum of the leave-one-out log predictive densities `loo`,\n individual leave-one-out log predictive density terms `loos` and an estimate\n of Pareto tail indeces `ks`. The estimates are unreliable if tail index\n ``k > 0.7`` (see more in the references listed in the module docstring).\n\n Additional keyword arguments are passed to the :meth:`psislw()` function\n (see the corresponding documentation).\n\n Parameters\n ----------\n log_lik : ndarray\n Array of size n x m containing n posterior samples of the log likelihood\n terms :math:`p(y_i|\\theta^s)`.\n\n Returns\n -------\n loo : scalar\n sum of the leave-one-out log predictive densities\n\n loos : ndarray\n individual leave-one-out log predictive density terms\n\n ks : ndarray\n estimated Pareto tail indeces\n\n \"\"\"\n # ensure overwrite flag in passed arguments\n kwargs['overwrite_lw'] = True\n # log raw weights from log_lik\n lw = -log_lik\n # compute Pareto smoothed log weights given raw log weights\n lw, ks = psislw(lw, **kwargs)\n # compute\n lw += log_lik\n loos = sumlogs(lw, axis=0)\n loo = loos.sum()\n return loo, loos, ks\n\n\ndef psislw(lw, Reff=1.0, overwrite_lw=False):\n \"\"\"Pareto smoothed importance sampling (PSIS).\n\n Parameters\n ----------\n lw : ndarray\n Array of size n x m containing m sets of n log weights. It is also\n possible to provide one dimensional array of length n.\n\n Reff : scalar, optional\n relative MCMC efficiency ``N_eff / N``\n\n overwrite_lw : bool, optional\n If True, the input array `lw` is smoothed in-place, assuming the array\n is F-contiguous. By default, a new array is allocated.\n\n Returns\n -------\n lw_out : ndarray\n smoothed log weights\n kss : ndarray\n Pareto tail indices\n\n \"\"\"\n if lw.ndim == 2:\n n, m = lw.shape\n elif lw.ndim == 1:\n n = len(lw)\n m = 1\n else:\n raise ValueError(\"Argument `lw` must be 1 or 2 dimensional.\")\n if n <= 1:\n raise ValueError(\"More than one log-weight needed.\")\n\n if overwrite_lw and lw.flags.f_contiguous:\n # in-place operation\n lw_out = lw\n else:\n # allocate new array for output\n lw_out = np.copy(lw, order='F')\n\n # allocate output array for kss\n kss = np.empty(m)\n\n # precalculate constants\n cutoff_ind = - int(np.ceil(min(0.2 * n, 3 * np.sqrt(n / Reff)))) - 1\n cutoffmin = np.log(np.finfo(float).tiny)\n logn = np.log(n)\n k_min = 1/3\n\n # loop over sets of log weights\n for i, x in enumerate(lw_out.T if lw_out.ndim == 2 else lw_out[None, :]):\n # improve numerical accuracy\n x -= np.max(x)\n # sort the array\n x_sort_ind = np.argsort(x)\n # divide log weights into body and right tail\n xcutoff = max(\n x[x_sort_ind[cutoff_ind]],\n cutoffmin\n )\n expxcutoff = np.exp(xcutoff)\n tailinds, = np.where(x > xcutoff)\n x2 = x[tailinds]\n n2 = len(x2)\n if n2 <= 4:\n # not enough tail samples for gpdfitnew\n k = np.inf\n else:\n # order of tail samples\n x2si = np.argsort(x2)\n # fit generalized Pareto distribution to the right tail samples\n np.exp(x2, out=x2)\n x2 -= expxcutoff\n k, sigma = gpdfitnew(x2, sort=x2si)\n if k >= k_min and not np.isinf(k):\n # no smoothing if short tail or GPD fit failed\n # compute ordered statistic for the fit\n sti = np.arange(0.5, n2)\n sti /= n2\n qq = gpinv(sti, k, sigma)\n qq += expxcutoff\n np.log(qq, out=qq)\n # place the smoothed tail into the output array\n x[tailinds[x2si]] = qq\n # truncate smoothed values to the largest raw weight 0\n x[x > 0] = 0\n # renormalize weights\n x -= sumlogs(x)\n # store tail index k\n kss[i] = k\n\n # If the provided input array is one dimensional, return kss as scalar.\n if lw_out.ndim == 1:\n kss = kss[0]\n\n return lw_out, kss\n\n\ndef gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False):\n \"\"\"Estimate the paramaters for the Generalized Pareto Distribution (GPD)\n\n Returns empirical Bayes estimate for the parameters of the two-parameter\n generalized Parato distribution given the data.\n\n Parameters\n ----------\n x : ndarray\n One dimensional data array\n\n sort : bool or ndarray, optional\n If known in advance, one can provide an array of indices that would\n sort the input array `x`. If the input array is already sorted, provide\n False. If True (default behaviour), the array is sorted internally.\n\n sort_in_place : bool, optional\n If `sort` is True and `sort_in_place` is True, the array is sorted\n in-place (False by default).\n\n return_quadrature : bool, optional\n If True, quadrature points and weight `ks` and `w` of the marginal posterior distribution of k are also calculated and returned. False by\n default.\n\n Returns\n -------\n k, sigma : float\n estimated parameter values\n\n ks, w : ndarray\n Quadrature points and weights of the marginal posterior distribution\n of `k`. Returned only if `return_quadrature` is True.\n\n Notes\n -----\n This function returns a negative of Zhang and Stephens's k, because it is\n more common parameterisation.\n\n \"\"\"\n if x.ndim != 1 or len(x) <= 1:\n raise ValueError(\"Invalid input array.\")\n\n # check if x should be sorted\n if sort is True:\n if sort_in_place:\n x.sort()\n xsorted = True\n else:\n sort = np.argsort(x)\n xsorted = False\n elif sort is False:\n xsorted = True\n else:\n xsorted = False\n\n n = len(x)\n PRIOR = 3\n m = 30 + int(np.sqrt(n))\n\n bs = np.arange(1, m + 1, dtype=float)\n bs -= 0.5\n np.divide(m, bs, out=bs)\n np.sqrt(bs, out=bs)\n np.subtract(1, bs, out=bs)\n if xsorted:\n bs /= PRIOR * x[int(n/4 + 0.5) - 1]\n bs += 1 / x[-1]\n else:\n bs /= PRIOR * x[sort[int(n/4 + 0.5) - 1]]\n bs += 1 / x[sort[-1]]\n\n ks = np.negative(bs)\n temp = ks[:,None] * x\n np.log1p(temp, out=temp)\n np.mean(temp, axis=1, out=ks)\n\n L = bs / ks\n np.negative(L, out=L)\n np.log(L, out=L)\n L -= ks\n L -= 1\n L *= n\n\n temp = L - L[:,None]\n np.exp(temp, out=temp)\n w = np.sum(temp, axis=1)\n np.divide(1, w, out=w)\n\n # remove negligible weights\n dii = w >= 10 * np.finfo(float).eps\n if not np.all(dii):\n w = w[dii]\n bs = bs[dii]\n # normalise w\n w /= w.sum()\n\n # posterior mean for b\n b = np.sum(bs * w)\n # Estimate for k, note that we return a negative of Zhang and\n # Stephens's k, because it is more common parameterisation.\n temp = (-b) * x # pylint: disable=invalid-unary-operand-type\n np.log1p(temp, out=temp)\n k = np.mean(temp)\n if return_quadrature:\n np.negative(x, out=temp)\n temp = bs[:, None] * temp\n np.log1p(temp, out=temp)\n ks = np.mean(temp, axis=1)\n # estimate for sigma\n sigma = -k / b * n / (n - 0)\n # weakly informative prior for k\n a = 10\n k = k * n / (n+a) + a * 0.5 / (n+a)\n if return_quadrature:\n ks *= n / (n+a)\n ks += a * 0.5 / (n+a)\n\n if return_quadrature:\n return k, sigma, ks, w\n else:\n return k, sigma\n\n\ndef gpinv(p, k, sigma):\n \"\"\"Inverse Generalised Pareto distribution function.\"\"\"\n x = np.empty(p.shape)\n x.fill(np.nan)\n if sigma <= 0:\n return x\n ok = (p > 0) & (p < 1)\n if np.all(ok):\n if np.abs(k) < np.finfo(float).eps:\n np.negative(p, out=x)\n np.log1p(x, out=x)\n np.negative(x, out=x)\n else:\n np.negative(p, out=x)\n np.log1p(x, out=x)\n x *= -k\n np.expm1(x, out=x)\n x /= k\n x *= sigma\n else:\n if np.abs(k) < np.finfo(float).eps:\n # x[ok] = - np.log1p(-p[ok])\n temp = p[ok]\n np.negative(temp, out=temp)\n np.log1p(temp, out=temp)\n np.negative(temp, out=temp)\n x[ok] = temp\n else:\n # x[ok] = np.expm1(-k * np.log1p(-p[ok])) / k\n temp = p[ok]\n np.negative(temp, out=temp)\n np.log1p(temp, out=temp)\n temp *= -k\n np.expm1(temp, out=temp)\n temp /= k\n x[ok] = temp\n x *= sigma\n x[p == 0] = 0\n if k >= 0:\n x[p == 1] = np.inf\n else:\n x[p == 1] = -sigma / k\n return x\n\n\ndef sumlogs(x, axis=None, out=None):\n \"\"\"Sum of vector where numbers are represented by their logarithms.\n\n Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that\n it works even when elements have large magnitude.\n\n \"\"\"\n maxx = x.max(axis=axis, keepdims=True)\n xnorm = x - maxx\n np.exp(xnorm, out=xnorm)\n out = np.sum(xnorm, axis=axis, out=out)\n if isinstance(out, np.ndarray):\n np.log(out, out=out)\n else:\n out = np.log(out)\n out += np.squeeze(maxx)\n return out\n"
] |
[
[
"numpy.sqrt",
"numpy.squeeze",
"numpy.all",
"numpy.max",
"numpy.mean",
"numpy.negative",
"numpy.exp",
"numpy.where",
"numpy.divide",
"numpy.arange",
"numpy.subtract",
"numpy.finfo",
"numpy.copy",
"numpy.log1p",
"numpy.log",
"numpy.argsort",
"numpy.sum",
"numpy.abs",
"numpy.expm1",
"numpy.isinf",
"numpy.empty"
]
] |
hash-ir/Facial-Keypoints-Detection
|
[
"7d1bf3559ec4d6283b7f07dec16327862e084a8d"
] |
[
"data_loader.py"
] |
[
"from torch.utils.data import Dataset, DataLoader\nimport matplotlib.image as mpimg\nimport pandas as pd\nimport os\nimport numpy as np\n\nclass FacialKeypointsDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, transform=None):\n self.key_pts_frame = pd.read_csv(csv_file)\n self.key_pts_frame.dropna(inplace=True)\n self.key_pts_frame.reset_index(drop=True, inplace=True)\n self.transform = transform\n\n def __len__(self):\n return len(self.key_pts_frame)\n\n def __getitem__(self, idx):\n image_string = self.key_pts_frame.loc[idx]['Image']\n image_array = np.array([int(item) for item in image_string.split()]).reshape(-1, 96, 96).astype(np.float32)\n# print(image_array.shape)\n sample = {}\n sample['image'] = image_array\n sample['keypoints'] = self.key_pts_frame.loc[idx].values[:-1].reshape(15, 2).astype(np.float32)\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n\n"
] |
[
[
"pandas.read_csv"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.