repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
aquinquenel/scikit-learn-mooc
|
[
"edb91f1669ffad65038f5bf48a6771299be4c09d",
"edb91f1669ffad65038f5bf48a6771299be4c09d"
] |
[
"python_scripts/ensemble_ex_04.py",
"python_scripts/parameter_tuning_manual.py"
] |
[
"# ---\n# jupyter:\n# kernelspec:\n# display_name: Python 3\n# name: python3\n# ---\n\n# %% [markdown]\n# # 📝 Exercise M6.04\n#\n# The aim of the exercise is to get familiar with the histogram\n# gradient-boosting in scikit-learn. Besides, we will use this model within\n# a cross-validation framework in order to inspect internal parameters found\n# via grid-search.\n#\n# We will use the California housing dataset.\n\n# %%\nfrom sklearn.datasets import fetch_california_housing\n\ndata, target = fetch_california_housing(return_X_y=True, as_frame=True)\ntarget *= 100 # rescale the target in k$\n\n# %% [markdown]\n# First, create a histogram gradient boosting regressor. You can set the\n# trees number to be large, and configure the model to use early-stopping.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# We will use a grid-search to find some optimal parameter for this model.\n# In this grid-search, you should search for the following parameters:\n#\n# * `max_depth: [3, 8]`;\n# * `max_leaf_nodes: [15, 31]`;\n# * `learning_rate: [0.1, 1]`.\n#\n# Feel free to explore the space with additional values. Create the\n# grid-search providing the previous gradient boosting instance as the model.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Finally, we will run our experiment through cross-validation. In this regard,\n# define a 5-fold cross-validation. Besides, be sure to shuffle the data.\n# Subsequently, use the function `sklearn.model_selection.cross_validate`\n# to run the cross-validation. You should also set `return_estimator=True`,\n# so that we can investigate the inner model trained via cross-validation.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Now that we got the cross-validation results, print out the mean and\n# standard deviation score.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Then inspect the `estimator` entry of the results and check the best\n# parameters values. Besides, check the number of trees used by the model.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Inspect the results of the inner CV for each estimator of the outer CV.\n# Aggregate the mean test score for each parameter combination and make a box\n# plot of these scores.\n\n# %%\n# Write your code here.\n",
"# ---\n# jupyter:\n# kernelspec:\n# display_name: Python 3\n# name: python3\n# ---\n\n# %% [markdown]\n# # Set and get hyperparameters in scikit-learn\n#\n# The process of learning a predictive model is driven by a set of internal\n# parameters and a set of training data. These internal parameters are called\n# hyperparameters and are specific for each family of models. In addition, a\n# specific set of hyperparameters are optimal for a specific dataset and thus\n# they need to be optimized.\n#\n# ```{note}\n# In this notebook we will use the words \"hyperparameters\" and \"parameters\"\n# interchangeably.\n# ```\n#\n# This notebook shows how one can get and set the value of a hyperparameter in\n# a scikit-learn estimator. We recall that hyperparameters refer to the\n# parameter that will control the learning process.\n#\n# They should not be confused with the fitted parameters, resulting from the\n# training. These fitted parameters are recognizable in scikit-learn because\n# they are spelled with a final underscore `_`, for instance `model.coef_`.\n#\n# We will start by loading the adult census dataset and only use the numerical\n# features.\n\n# %%\nimport pandas as pd\n\nadult_census = pd.read_csv(\"../datasets/adult-census.csv\")\n\ntarget_name = \"class\"\nnumerical_columns = [\n \"age\", \"capital-gain\", \"capital-loss\", \"hours-per-week\"]\n\ntarget = adult_census[target_name]\ndata = adult_census[numerical_columns]\n\n# %% [markdown]\n# Our data is only numerical.\n\n# %%\ndata.head()\n\n# %% [markdown]\n# Let's create a simple predictive model made of a scaler followed by a\n# logistic regression classifier.\n#\n# As mentioned in previous notebooks, many models, including linear ones,\n# work better if all features have a similar scaling. For this purpose,\n# we use a `StandardScaler`, which transforms the data by rescaling features.\n\n# %%\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = Pipeline(steps=[\n (\"preprocessor\", StandardScaler()),\n (\"classifier\", LogisticRegression())\n])\n\n# %% [markdown]\n# We can evaluate the generalization performance of the model via\n# cross-validation.\n\n# %%\nfrom sklearn.model_selection import cross_validate\n\ncv_results = cross_validate(model, data, target)\nscores = cv_results[\"test_score\"]\nprint(f\"Accuracy score via cross-validation:\\n\"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown]\n# We created a model with the default `C` value that is equal to 1. If we\n# wanted to use a different `C` parameter we could have done so when we created\n# the `LogisticRegression` object with something like `LogisticRegression(C=1e-3)`.\n#\n# ```{note}\n# For more information on the model hyperparameter `C`, refer to the\n# [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html).\n# Be aware that we will focus on linear models in an upcoming module.\n# ```\n#\n# We can also change the parameter of a model after it has been created with\n# the `set_params` method, which is available for all scikit-learn estimators.\n# For example, we can set `C=1e-3`, fit and evaluate the model:\n\n# %%\nmodel.set_params(classifier__C=1e-3)\ncv_results = cross_validate(model, data, target)\nscores = cv_results[\"test_score\"]\nprint(f\"Accuracy score via cross-validation:\\n\"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown]\n# When the model of interest is a `Pipeline`, the parameter names are of the\n# form `<model_name>__<parameter_name>` (note the double underscore in the\n# middle). In our case, `classifier` comes from the `Pipeline` definition and\n# `C` is the parameter name of `LogisticRegression`.\n#\n# In general, you can use the `get_params` method on scikit-learn models to\n# list all the parameters with their values. For example, if you want to\n# get all the parameter names, you can use:\n\n# %%\nfor parameter in model.get_params():\n print(parameter)\n\n# %% [markdown]\n# `.get_params()` returns a `dict` whose keys are the parameter names and whose\n# values are the parameter values. If you want to get the value of a single\n# parameter, for example `classifier__C`, you can use:\n\n# %%\nmodel.get_params()['classifier__C']\n\n# %% [markdown]\n# We can systematically vary the value of C to see if there is an optimal\n# value.\n\n# %%\nfor C in [1e-3, 1e-2, 1e-1, 1, 10]:\n model.set_params(classifier__C=C)\n cv_results = cross_validate(model, data, target)\n scores = cv_results[\"test_score\"]\n print(f\"Accuracy score via cross-validation with C={C}:\\n\"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown]\n# We can see that as long as C is high enough, the model seems to perform\n# well.\n#\n# What we did here is very manual: it involves scanning the values for C\n# and picking the best one manually. In the next lesson, we will see how\n# to do this automatically.\n#\n# ```{warning}\n# When we evaluate a family of models on test data and pick the best\n# performer, we can not trust the corresponding prediction accuracy, and\n# we need to apply the selected model to new data. Indeed, the test data\n# has been used to select the model, and it is thus no longer independent\n# from this model.\n# ```\n\n# %% [markdown]\n# In this notebook we have seen:\n#\n# - how to use `get_params` and `set_params` to get the parameters of a model\n# and set them.\n"
] |
[
[
"sklearn.datasets.fetch_california_housing"
],
[
"sklearn.model_selection.cross_validate",
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression"
]
] |
adrianmatias/ml4grownups
|
[
"2ead636d99acc1e67e48789514fc87691f799ebc"
] |
[
"src/dataset.py"
] |
[
"import os\n\nimport pandas as pd\nimport numpy as np\nfrom conf import Conf\nfrom typing import List\nfrom sklearn.model_selection import train_test_split\n\nCONF = Conf()\n\n\ndef main():\n dataset = Dataset(\n data_user=get_data(\"users_onboarding_paywall.tsv\"),\n data_activity=get_data(\"activities_per_day.tsv\"),\n )\n\n print(dataset.data_user.head())\n print(dataset.data_activity.head())\n\n dataset.make_dataset()\n\n print(dataset.df.head())\n\n dataset.write_mlflow_data_request()\n\n\nclass Dataset:\n def __init__(self, data_user: pd.DataFrame, data_activity: pd.DataFrame):\n self.data_user = data_user\n self.data_activity = data_activity\n self.data_user_processed = pd.DataFrame\n self.data_activity_processed = pd.DataFrame\n self.df = pd.DataFrame\n\n def make_dataset(self):\n self.process_data_user()\n self.process_data_activity()\n self.join()\n\n def process_data_user(self):\n self.data_user_processed = (\n self.data_user.copy()\n .drop_duplicates(CONF.col_user)\n .set_index(CONF.col_user)\n )\n\n def split(self):\n train, test = train_test_split(self.df, test_size=0.2)\n train, valid = train_test_split(train, test_size=0.2)\n return train, valid, test\n\n @staticmethod\n def drop_label(df: pd.DataFrame):\n return df.drop(columns=CONF.col_label)\n\n def process_data_activity(self):\n cols_key = [CONF.col_user, CONF.col_days_in_trial]\n\n agg_total = dict(\n (col, sum) for col in self.data_activity.columns if \"total_\" in col\n )\n agg_mean = dict(\n (col, np.mean) for col in self.data_activity.columns if \"mean_\" in col\n )\n\n self.data_activity_processed = (\n self.data_activity.copy()\n .groupby(cols_key)\n .agg({**agg_total, **agg_mean})\n # TODO: apply rolling aggregation features\n # TODO: add record count\n .reset_index()\n .set_index(CONF.col_user)\n )\n\n def join(self):\n self.df = pd.merge(\n left=self.data_user_processed,\n right=self.data_activity_processed,\n on=CONF.col_user,\n how=\"left\",\n ).reset_index()\n\n @staticmethod\n def get_feat_list_cat(df: pd.DataFrame) -> List[str]:\n return list(\n df.drop(columns=[CONF.col_label] + CONF.feats_not)\n .select_dtypes(include=[\"object\"])\n .columns\n )\n\n @staticmethod\n def get_feat_list_num(df: pd.DataFrame) -> List[str]:\n return list(\n df.drop(columns=[CONF.col_label] + CONF.feats_not)\n .select_dtypes(exclude=[\"object\"])\n .columns\n )\n\n @staticmethod\n def get_feat_list(df: pd.DataFrame) -> List[str]:\n return list(df.drop(columns=[CONF.col_label] + CONF.feats_not).columns)\n\n def write_mlflow_data_request(self):\n self.df.head(2).to_json(\n os.path.join(CONF.path_data_interim, \"user_0.json\"), orient=\"split\"\n )\n\n def write_mlflow_data_request(self):\n self.df.head(2).to_json(\n os.path.join(CONF.path_data_interim, \"user_0.json\"), orient=\"split\"\n )\n\n\ndef get_data(filename: str) -> pd.DataFrame:\n path_filename = os.path.join(CONF.path_data_raw, filename)\n\n return pd.read_csv(filepath_or_buffer=path_filename, sep=\"\\t\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.merge",
"pandas.read_csv",
"sklearn.model_selection.train_test_split"
]
] |
google-research/crafty
|
[
"a232e66c245f4b7d67fe0443cdc094ca61dd7484"
] |
[
"util.py"
] |
[
"\n # Copyright 2021 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # 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\"\"\"Helper functions for craftgen.\"\"\"\n\nimport abc\nimport collections\nimport itertools\nimport json\nfrom typing import Dict, Sequence\n\nfrom crafty import data\nimport scipy.stats\nimport tensorflow as tf\n\n\nclass MagnitudeNormalizer(metaclass=abc.ABCMeta):\n \"\"\"Base class for magnitude normalizer.\"\"\"\n\n def __init__(self, scale: float):\n \"\"\"Initializer.\n\n Args:\n scale: scale parameter for a given distribution (e.g. std for Gaussian).\n \"\"\"\n assert scale > 0.0\n self.scale = scale\n\n @abc.abstractmethod\n def __call__(self, magnitude: float) -> float:\n \"\"\"Calculates probability of a given magnitude for a given distribution.\"\"\"\n return\n\n @abc.abstractmethod\n def cdf(self, magnitude: float) -> float:\n \"\"\"Calculates the cumulative probability for a given magnitude.\"\"\"\n return\n\n @classmethod\n def create(cls, magnitude_normalization: str, loc: float, scale: float):\n if magnitude_normalization == 'normal':\n return GaussianMagnitudeNormalizer(loc, scale)\n elif magnitude_normalization.startswith('gamma'):\n return GammaMagnitudeNormalizer(loc, scale)\n else:\n raise ValueError('Available types are `gamma`, `gamma` and `normal`'\n ', but got %s.' % magnitude_normalization)\n\n\nclass GaussianMagnitudeNormalizer(MagnitudeNormalizer):\n \"\"\"Normalizer based on Normal Distribution.\"\"\"\n\n def __init__(self, mean: float, std: float):\n \"\"\"Initializer.\n\n Args:\n mean: mean param for Gaussian.\n std: std param for Gaussian.\n \"\"\"\n super().__init__(scale=std)\n self.normal_dist = scipy.stats.norm(mean, self.scale)\n\n def __call__(self, magnitude: float) -> float:\n \"\"\"Calculates probability of a given magnitude for a normal distribution.\"\"\"\n # Get cumulative probability from -infinity to magnitude.\n assert magnitude >= 0.0\n return 2 * (1 - self.cdf(magnitude))\n\n def cdf(self, magnitude: float) -> float:\n \"\"\"Calculates the cumulative probability for a given magnitude.\"\"\"\n assert magnitude >= 0.0\n return self.normal_dist.cdf(magnitude)\n\n\nclass GammaMagnitudeNormalizer(MagnitudeNormalizer):\n \"\"\"Normalizer based on Gamma Distribution.\"\"\"\n\n def __init__(self, gamma_shape: float, scale: float):\n \"\"\"Initializer.\n\n Args:\n gamma_shape: Gamma shape param for Gamma.\n scale: scale param for Gamma.\n \"\"\"\n super().__init__(scale=scale)\n self.gamma_dist = scipy.stats.gamma(gamma_shape)\n\n def __call__(self, magnitude: float) -> float:\n \"\"\"Calculates probability of a given magnitude for a gamma distribution.\"\"\"\n assert magnitude >= 0.0\n return self.gamma_dist.pdf(magnitude / self.scale)\n\n def cdf(self, magnitude: float) -> float:\n \"\"\"Calculates the cumulative probability for a given magnitude.\"\"\"\n assert magnitude >= 0.0\n return self.gamma_dist.cdf(magnitude / self.scale)\n\n\ndef pairwise(iterable):\n \"\"\"From itertools: iterates pairwise over an iterable.\n\n Args:\n iterable: An iterable containing a sequence of items.\n\n Returns:\n An iterable containing pairs from the input iterable, e.g.\n s0,s1,s2,s3... -> (s0,s1), (s1,s2), (s2, s3), ...\n \"\"\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef get_scan_to_path_and_heading_dict(\n source_json_path: str) -> Dict[str, Sequence[data.Path]]:\n \"\"\"Gets `scan` -> [data.Path(path, heading), ...] mapping.\n\n Helper function to collection transition stats house-wise.\n\n Args:\n source_json_path: Path to training R2R json.\n\n Returns:\n Mapping of scan -> [data.Path(path, heading), ...].\n \"\"\"\n with tf.io.gfile.GFile(source_json_path, 'r') as fp:\n dataset = json.load(fp)\n scan_to_path_and_heading = collections.defaultdict(list)\n for item in dataset:\n path_container = data.Path(path=item['path'], heading=item['heading'])\n scan_to_path_and_heading[item['scan']].append(path_container)\n return scan_to_path_and_heading\n"
] |
[
[
"tensorflow.io.gfile.GFile"
]
] |
jzh800/DREAMPlace
|
[
"1ddae063d7b78f4b66e371eec9c33d2c633c3c09",
"1ddae063d7b78f4b66e371eec9c33d2c633c3c09"
] |
[
"dreamplace/PlaceDB.py",
"dreamplace/ops/density_overflow/density_overflow.py"
] |
[
"##\n# @file PlaceDB.py\n# @author Yibo Lin\n# @date Apr 2018\n# @brief placement database \n#\n\nimport sys\nimport os\nimport re\nimport time \nimport numpy as np \nimport logging\nimport Params\nimport dreamplace \nimport dreamplace.ops.place_io.place_io as place_io \nimport pdb \n\ndatatypes = {\n 'float32' : np.float32, \n 'float64' : np.float64\n }\n\nclass PlaceDB (object):\n \"\"\"\n @brief placement database \n \"\"\"\n def __init__(self):\n \"\"\"\n initialization\n To avoid the usage of list, I flatten everything. \n \"\"\"\n self.rawdb = None # raw placement database, a C++ object \n\n self.num_physical_nodes = 0 # number of real nodes, including movable nodes, terminals, and terminal_NIs\n self.num_terminals = 0 # number of terminals, essentially fixed macros \n self.num_terminal_NIs = 0 # number of terminal_NIs that can be overlapped, essentially IO pins\n self.node_name2id_map = {} # node name to id map, cell name \n self.node_names = None # 1D array, cell name \n self.node_x = None # 1D array, cell position x \n self.node_y = None # 1D array, cell position y \n self.node_orient = None # 1D array, cell orientation \n self.node_size_x = None # 1D array, cell width \n self.node_size_y = None # 1D array, cell height\n\n self.pin_direct = None # 1D array, pin direction IO \n self.pin_offset_x = None # 1D array, pin offset x to its node \n self.pin_offset_y = None # 1D array, pin offset y to its node \n\n self.net_name2id_map = {} # net name to id map\n self.net_names = None # net name \n self.net2pin_map = None # array of 1D array, each row stores pin id\n self.flat_net2pin_map = None # flatten version of net2pin_map \n self.flat_net2pin_start_map = None # starting index of each net in flat_net2pin_map\n self.net_weights = None # weights for each net\n\n self.node2pin_map = None # array of 1D array, contains pin id of each node \n self.pin2node_map = None # 1D array, contain parent node id of each pin \n self.pin2net_map = None # 1D array, contain parent net id of each pin \n\n self.rows = None # NumRows x 4 array, stores xl, yl, xh, yh of each row \n\n self.regions = None # array of 1D array, placement regions like FENCE and GUIDE \n self.flat_region_boxes = None # flat version of regions \n self.flat_region_boxes_start = None # start indices of regions, length of num regions + 1\n self.node2fence_region_map = None # map cell to a region, maximum integer if no fence region \n\n self.xl = None \n self.yl = None \n self.xh = None \n self.yh = None \n\n self.row_height = None\n self.site_width = None\n\n self.bin_size_x = None \n self.bin_size_y = None\n self.num_bins_x = None\n self.num_bins_y = None\n self.bin_center_x = None \n self.bin_center_y = None\n\n self.num_movable_pins = None \n\n self.total_movable_node_area = None\n self.total_fixed_node_area = None\n\n # enable filler cells \n # the Idea from e-place and RePlace \n self.total_filler_node_area = None \n self.num_filler_nodes = None\n\n self.dtype = None \n\n def scale_pl(self, scale_factor):\n \"\"\"\n @brief scale placement solution only\n @param scale_factor scale factor \n \"\"\"\n self.node_x *= scale_factor\n self.node_y *= scale_factor \n\n def scale(self, scale_factor):\n \"\"\"\n @brief scale distances\n @param scale_factor scale factor \n \"\"\"\n logging.info(\"scale coordinate system by %g\" % (scale_factor))\n self.scale_pl(scale_factor)\n self.node_size_x *= scale_factor\n self.node_size_y *= scale_factor\n self.pin_offset_x *= scale_factor\n self.pin_offset_y *= scale_factor\n self.xl *= scale_factor \n self.yl *= scale_factor\n self.xh *= scale_factor\n self.yh *= scale_factor\n self.row_height *= scale_factor\n self.site_width *= scale_factor\n self.rows *= scale_factor \n self.flat_region_boxes *= scale_factor\n # may have performance issue \n # I assume there are not many boxes \n for i in range(len(self.regions)): \n self.regions[i] *= scale_factor \n\n def sort(self):\n \"\"\"\n @brief Sort net by degree. \n Sort pin array such that pins belonging to the same net is abutting each other\n \"\"\"\n logging.info(\"sort nets by degree and pins by net\")\n\n # sort nets by degree \n net_degrees = np.array([len(pins) for pins in self.net2pin_map])\n net_order = net_degrees.argsort() # indexed by new net_id, content is old net_id\n self.net_names = self.net_names[net_order]\n self.net2pin_map = self.net2pin_map[net_order]\n for net_id, net_name in enumerate(self.net_names):\n self.net_name2id_map[net_name] = net_id\n for new_net_id in range(len(net_order)):\n for pin_id in self.net2pin_map[new_net_id]:\n self.pin2net_map[pin_id] = new_net_id\n ## check \n #for net_id in range(len(self.net2pin_map)):\n # for j in range(len(self.net2pin_map[net_id])):\n # assert self.pin2net_map[self.net2pin_map[net_id][j]] == net_id\n\n # sort pins such that pins belonging to the same net is abutting each other\n pin_order = self.pin2net_map.argsort() # indexed new pin_id, content is old pin_id \n self.pin2net_map = self.pin2net_map[pin_order]\n self.pin2node_map = self.pin2node_map[pin_order]\n self.pin_direct = self.pin_direct[pin_order]\n self.pin_offset_x = self.pin_offset_x[pin_order]\n self.pin_offset_y = self.pin_offset_y[pin_order]\n old2new_pin_id_map = np.zeros(len(pin_order), dtype=np.int32)\n for new_pin_id in range(len(pin_order)):\n old2new_pin_id_map[pin_order[new_pin_id]] = new_pin_id\n for i in range(len(self.net2pin_map)):\n for j in range(len(self.net2pin_map[i])):\n self.net2pin_map[i][j] = old2new_pin_id_map[self.net2pin_map[i][j]]\n for i in range(len(self.node2pin_map)):\n for j in range(len(self.node2pin_map[i])):\n self.node2pin_map[i][j] = old2new_pin_id_map[self.node2pin_map[i][j]]\n ## check \n #for net_id in range(len(self.net2pin_map)):\n # for j in range(len(self.net2pin_map[net_id])):\n # assert self.pin2net_map[self.net2pin_map[net_id][j]] == net_id\n #for node_id in range(len(self.node2pin_map)):\n # for j in range(len(self.node2pin_map[node_id])):\n # assert self.pin2node_map[self.node2pin_map[node_id][j]] == node_id\n\n @property\n def num_movable_nodes(self):\n \"\"\"\n @return number of movable nodes \n \"\"\"\n return self.num_physical_nodes - self.num_terminals - self.num_terminal_NIs\n\n @property \n def num_nodes(self):\n \"\"\"\n @return number of movable nodes, terminals, terminal_NIs, and fillers\n \"\"\"\n return self.num_physical_nodes + self.num_filler_nodes\n\n @property\n def num_nets(self):\n \"\"\"\n @return number of nets\n \"\"\"\n return len(self.net2pin_map)\n\n @property\n def num_pins(self):\n \"\"\"\n @return number of pins\n \"\"\"\n return len(self.pin2net_map)\n\n @property\n def width(self):\n \"\"\"\n @return width of layout \n \"\"\"\n return self.xh-self.xl\n\n @property\n def height(self):\n \"\"\"\n @return height of layout \n \"\"\"\n return self.yh-self.yl\n\n @property\n def area(self):\n \"\"\"\n @return area of layout \n \"\"\"\n return self.width*self.height\n\n def bin_index_x(self, x): \n \"\"\"\n @param x horizontal location \n @return bin index in x direction \n \"\"\"\n if x < self.xl:\n return 0 \n elif x > self.xh:\n return int(np.floor((self.xh-self.xl)/self.bin_size_x))\n else:\n return int(np.floor((x-self.xl)/self.bin_size_x))\n\n def bin_index_y(self, y): \n \"\"\"\n @param y vertical location \n @return bin index in y direction \n \"\"\"\n if y < self.yl:\n return 0 \n elif y > self.yh:\n return int(np.floor((self.yh-self.yl)/self.bin_size_y))\n else:\n return int(np.floor((y-self.yl)/self.bin_size_y))\n\n def bin_xl(self, id_x):\n \"\"\"\n @param id_x horizontal index \n @return bin xl\n \"\"\"\n return self.xl+id_x*self.bin_size_x\n\n def bin_xh(self, id_x):\n \"\"\"\n @param id_x horizontal index \n @return bin xh\n \"\"\"\n return min(self.bin_xl(id_x)+self.bin_size_x, self.xh)\n\n def bin_yl(self, id_y):\n \"\"\"\n @param id_y vertical index \n @return bin yl\n \"\"\"\n return self.yl+id_y*self.bin_size_y\n\n def bin_yh(self, id_y):\n \"\"\"\n @param id_y vertical index \n @return bin yh\n \"\"\"\n return min(self.bin_yl(id_y)+self.bin_size_y, self.yh)\n\n def num_bins(self, l, h, bin_size):\n \"\"\"\n @brief compute number of bins \n @param l lower bound \n @param h upper bound \n @param bin_size bin size \n @return number of bins \n \"\"\"\n return int(np.ceil((h-l)/bin_size))\n\n def bin_centers(self, l, h, bin_size):\n \"\"\"\n @brief compute bin centers \n @param l lower bound \n @param h upper bound \n @param bin_size bin size \n @return array of bin centers \n \"\"\"\n num_bins = self.num_bins(l, h, bin_size)\n centers = np.zeros(num_bins, dtype=self.dtype)\n for id_x in range(num_bins): \n bin_l = l+id_x*bin_size\n bin_h = min(bin_l+bin_size, h)\n centers[id_x] = (bin_l+bin_h)/2\n return centers \n\n def net_hpwl(self, x, y, net_id): \n \"\"\"\n @brief compute HPWL of a net \n @param x horizontal cell locations \n @param y vertical cell locations\n @return hpwl of a net \n \"\"\"\n pins = self.net2pin_map[net_id]\n nodes = self.pin2node_map[pins]\n hpwl_x = np.amax(x[nodes]+self.pin_offset_x[pins]) - np.amin(x[nodes]+self.pin_offset_x[pins])\n hpwl_y = np.amax(y[nodes]+self.pin_offset_y[pins]) - np.amin(y[nodes]+self.pin_offset_y[pins])\n\n return (hpwl_x+hpwl_y)*self.net_weights[net_id]\n\n def hpwl(self, x, y):\n \"\"\"\n @brief compute total HPWL \n @param x horizontal cell locations \n @param y vertical cell locations \n @return hpwl of all nets\n \"\"\"\n wl = 0\n for net_id in range(len(self.net2pin_map)):\n wl += self.net_hpwl(x, y, net_id)\n return wl \n\n def overlap(self, xl1, yl1, xh1, yh1, xl2, yl2, xh2, yh2):\n \"\"\"\n @brief compute overlap between two boxes \n @return overlap area between two rectangles\n \"\"\"\n return max(min(xh1, xh2)-max(xl1, xl2), 0.0) * max(min(yh1, yh2)-max(yl1, yl2), 0.0)\n\n def density_map(self, x, y):\n \"\"\"\n @brief this density map evaluates the overlap between cell and bins \n @param x horizontal cell locations \n @param y vertical cell locations \n @return density map \n \"\"\"\n bin_index_xl = np.maximum(np.floor(x/self.bin_size_x).astype(np.int32), 0)\n bin_index_xh = np.minimum(np.ceil((x+self.node_size_x)/self.bin_size_x).astype(np.int32), self.num_bins_x-1)\n bin_index_yl = np.maximum(np.floor(y/self.bin_size_y).astype(np.int32), 0)\n bin_index_yh = np.minimum(np.ceil((y+self.node_size_y)/self.bin_size_y).astype(np.int32), self.num_bins_y-1)\n\n density_map = np.zeros([self.num_bins_x, self.num_bins_y])\n\n for node_id in range(self.num_physical_nodes):\n for ix in range(bin_index_xl[node_id], bin_index_xh[node_id]+1):\n for iy in range(bin_index_yl[node_id], bin_index_yh[node_id]+1):\n density_map[ix, iy] += self.overlap(\n self.bin_xl(ix), self.bin_yl(iy), self.bin_xh(ix), self.bin_yh(iy), \n x[node_id], y[node_id], x[node_id]+self.node_size_x[node_id], y[node_id]+self.node_size_y[node_id]\n )\n\n for ix in range(self.num_bins_x):\n for iy in range(self.num_bins_y):\n density_map[ix, iy] /= (self.bin_xh(ix)-self.bin_xl(ix))*(self.bin_yh(iy)-self.bin_yl(iy))\n\n return density_map\n\n def density_overflow(self, x, y, target_density):\n \"\"\"\n @brief if density of a bin is larger than target_density, consider as overflow bin \n @param x horizontal cell locations \n @param y vertical cell locations \n @param target_density target density \n @return density overflow cost \n \"\"\"\n density_map = self.density_map(x, y)\n return np.sum(np.square(np.maximum(density_map-target_density, 0.0)))\n\n def print_node(self, node_id): \n \"\"\"\n @brief print node information \n @param node_id cell index \n \"\"\"\n logging.debug(\"node %s(%d), size (%g, %g), pos (%g, %g)\" % (self.node_names[node_id], node_id, self.node_size_x[node_id], self.node_size_y[node_id], self.node_x[node_id], self.node_y[node_id]))\n pins = \"pins \"\n for pin_id in self.node2pin_map[node_id]:\n pins += \"%s(%s, %d) \" % (self.node_names[self.pin2node_map[pin_id]], self.net_names[self.pin2net_map[pin_id]], pin_id)\n logging.debug(pins)\n\n def print_net(self, net_id):\n \"\"\"\n @brief print net information\n @param net_id net index \n \"\"\"\n logging.debug(\"net %s(%d)\" % (self.net_names[net_id], net_id))\n pins = \"pins \"\n for pin_id in self.net2pin_map[net_id]:\n pins += \"%s(%s, %d) \" % (self.node_names[self.pin2node_map[pin_id]], self.net_names[self.pin2net_map[pin_id]], pin_id)\n logging.debug(pins)\n\n def print_row(self, row_id):\n \"\"\"\n @brief print row information \n @param row_id row index \n \"\"\"\n logging.debug(\"row %d %s\" % (row_id, self.rows[row_id]))\n\n def flatten_nested_map(self, net2pin_map): \n \"\"\"\n @brief flatten an array of array to two arrays like CSV format \n @param net2pin_map array of array \n @return a pair of (elements, cumulative column indices of the beginning element of each row)\n \"\"\"\n # flat netpin map, length of #pins\n flat_net2pin_map = np.zeros(len(pin2net_map), dtype=np.int32)\n # starting index in netpin map for each net, length of #nets+1, the last entry is #pins \n flat_net2pin_start_map = np.zeros(len(net2pin_map)+1, dtype=np.int32)\n count = 0\n for i in range(len(net2pin_map)):\n flat_net2pin_map[count:count+len(net2pin_map[i])] = net2pin_map[i]\n flat_net2pin_start_map[i] = count \n count += len(net2pin_map[i])\n assert flat_net2pin_map[-1] != 0\n flat_net2pin_start_map[len(net2pin_map)] = len(pin2net_map)\n\n return flat_net2pin_map, flat_net2pin_start_map\n\n def read(self, params): \n \"\"\"\n @brief read using c++ \n @param params parameters \n \"\"\"\n self.dtype = datatypes[params.dtype]\n self.rawdb = place_io.PlaceIOFunction.read(params)\n self.initialize_from_rawdb(params)\n\n def initialize_from_rawdb(self, params):\n \"\"\"\n @brief initialize data members from raw database \n @param params parameters \n \"\"\"\n pydb = place_io.PlaceIOFunction.pydb(self.rawdb)\n\n self.num_physical_nodes = pydb.num_nodes\n self.num_terminals = pydb.num_terminals\n self.num_terminal_NIs = pydb.num_terminal_NIs\n self.node_name2id_map = pydb.node_name2id_map\n self.node_names = np.array(pydb.node_names, dtype=np.string_)\n # If the placer directly takes a global placement solution, \n # the cell positions may still be floating point numbers. \n # It is not good to use the place_io OP to round the positions. \n # Currently we only support BOOKSHELF format. \n use_read_pl_flag = False \n if (not params.global_place_flag) and os.path.exists(params.aux_input): \n filename = None \n with open(params.aux_input, \"r\") as f:\n for line in f:\n line = line.strip()\n if \".pl\" in line: \n tokens = line.split()\n for token in tokens:\n if token.endswith(\".pl\"):\n filename = token\n break\n filename = os.path.join(os.path.dirname(params.aux_input), filename)\n if filename is not None and os.path.exists(filename):\n self.node_x = np.zeros(self.num_physical_nodes, dtype=self.dtype)\n self.node_y = np.zeros(self.num_physical_nodes, dtype=self.dtype)\n self.node_orient = np.zeros(self.num_physical_nodes, dtype=np.string_)\n self.read_pl(params, filename)\n use_read_pl_flag = True\n if not use_read_pl_flag:\n self.node_x = np.array(pydb.node_x, dtype=self.dtype)\n self.node_y = np.array(pydb.node_y, dtype=self.dtype)\n self.node_orient = np.array(pydb.node_orient, dtype=np.string_)\n self.node_size_x = np.array(pydb.node_size_x, dtype=self.dtype)\n self.node_size_y = np.array(pydb.node_size_y, dtype=self.dtype)\n self.pin_direct = np.array(pydb.pin_direct, dtype=np.string_)\n self.pin_offset_x = np.array(pydb.pin_offset_x, dtype=self.dtype)\n self.pin_offset_y = np.array(pydb.pin_offset_y, dtype=self.dtype)\n self.net_name2id_map = pydb.net_name2id_map\n self.net_names = np.array(pydb.net_names, dtype=np.string_)\n self.net2pin_map = pydb.net2pin_map\n self.flat_net2pin_map = np.array(pydb.flat_net2pin_map, dtype=np.int32)\n self.flat_net2pin_start_map = np.array(pydb.flat_net2pin_start_map, dtype=np.int32)\n self.net_weights = np.array(pydb.net_weights, dtype=self.dtype)\n self.node2pin_map = pydb.node2pin_map\n self.flat_node2pin_map = np.array(pydb.flat_node2pin_map, dtype=np.int32)\n self.flat_node2pin_start_map = np.array(pydb.flat_node2pin_start_map, dtype=np.int32)\n self.pin2node_map = np.array(pydb.pin2node_map, dtype=np.int32)\n self.pin2net_map = np.array(pydb.pin2net_map, dtype=np.int32)\n self.rows = np.array(pydb.rows, dtype=self.dtype)\n self.regions = pydb.regions \n for i in range(len(self.regions)):\n self.regions[i] = np.array(self.regions[i], dtype=self.dtype)\n self.flat_region_boxes = np.array(pydb.flat_region_boxes, dtype=self.dtype)\n self.flat_region_boxes_start = np.array(pydb.flat_region_boxes_start, dtype=np.int32)\n self.node2fence_region_map = np.array(pydb.node2fence_region_map, dtype=np.int32)\n self.xl = float(pydb.xl)\n self.yl = float(pydb.yl)\n self.xh = float(pydb.xh)\n self.yh = float(pydb.yh)\n self.row_height = float(pydb.row_height)\n self.site_width = float(pydb.site_width)\n self.num_movable_pins = pydb.num_movable_pins\n\n # convert node2pin_map to array of array \n for i in range(len(self.node2pin_map)):\n self.node2pin_map[i] = np.array(self.node2pin_map[i], dtype=np.int32)\n self.node2pin_map = np.array(self.node2pin_map)\n\n # convert net2pin_map to array of array \n for i in range(len(self.net2pin_map)):\n self.net2pin_map[i] = np.array(self.net2pin_map[i], dtype=np.int32)\n self.net2pin_map = np.array(self.net2pin_map)\n\n def __call__(self, params):\n \"\"\"\n @brief top API to read placement files \n @param params parameters \n \"\"\"\n tt = time.time()\n\n self.read(params)\n self.initialize(params)\n\n logging.info(\"reading benchmark takes %g seconds\" % (time.time()-tt))\n\n def initialize(self, params):\n \"\"\"\n @brief initialize data members after reading \n @param params parameters \n \"\"\"\n\n # scale \n # adjust scale_factor if not set \n if params.scale_factor == 0:\n params.scale_factor = 1.0 / self.site_width\n logging.info(\"set scale_factor = %g, as site_width = %g\" % (params.scale_factor, self.site_width))\n self.scale(params.scale_factor)\n\n content = \"\"\"\n=============== Benchmark Statistics ===============\n#nodes = %d, #terminals = %d, # terminal_NIs = %d, #movable = %d, #nets = %d\ndie area = (%g, %g, %g, %g) %g\nrow height = %g, site width = %g\n\"\"\" % (\n self.num_physical_nodes, self.num_terminals, self.num_terminal_NIs, self.num_movable_nodes, len(self.net_names), \n self.xl, self.yl, self.xh, self.yh, self.area, \n self.row_height, self.site_width\n )\n\n # set number of bins \n self.num_bins_x = params.num_bins_x #self.num_bins(self.xl, self.xh, self.bin_size_x)\n self.num_bins_y = params.num_bins_y #self.num_bins(self.yl, self.yh, self.bin_size_y)\n # set bin size \n self.bin_size_x = (self.xh-self.xl)/params.num_bins_x \n self.bin_size_y = (self.yh-self.yl)/params.num_bins_y \n\n # bin center array \n self.bin_center_x = self.bin_centers(self.xl, self.xh, self.bin_size_x)\n self.bin_center_y = self.bin_centers(self.yl, self.yh, self.bin_size_y)\n\n content += \"num_bins = %dx%d, bin sizes = %gx%g\\n\" % (self.num_bins_x, self.num_bins_y, self.bin_size_x/self.row_height, self.bin_size_y/self.row_height)\n\n # set num_movable_pins \n if self.num_movable_pins is None:\n self.num_movable_pins = 0 \n for node_id in self.pin2node_map:\n if node_id < self.num_movable_nodes:\n self.num_movable_pins += 1\n content += \"#pins = %d, #movable_pins = %d\\n\" % (self.num_pins, self.num_movable_pins)\n # set total cell area \n self.total_movable_node_area = float(np.sum(self.node_size_x[:self.num_movable_nodes]*self.node_size_y[:self.num_movable_nodes]))\n # total fixed node area should exclude the area outside the layout and the area of terminal_NIs \n self.total_fixed_node_area = float(np.sum(\n np.maximum(\n np.minimum(self.node_x[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs] + self.node_size_x[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs], self.xh)\n - np.maximum(self.node_x[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs], self.xl), \n 0.0) * np.maximum(\n np.minimum(self.node_y[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs] + self.node_size_y[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs], self.yh)\n - np.maximum(self.node_y[self.num_movable_nodes:self.num_physical_nodes - self.num_terminal_NIs], self.yl), \n 0.0)\n ))\n content += \"total_movable_node_area = %g, total_fixed_node_area = %g\\n\" % (self.total_movable_node_area, self.total_fixed_node_area)\n\n # insert filler nodes \n if params.enable_fillers: \n self.total_filler_node_area = max((self.area-self.total_fixed_node_area)*params.target_density-self.total_movable_node_area, 0.0)\n node_size_order = np.argsort(self.node_size_x[:self.num_movable_nodes])\n filler_size_x = np.mean(self.node_size_x[node_size_order[int(self.num_movable_nodes*0.05):int(self.num_movable_nodes*0.95)]])\n filler_size_y = self.row_height\n self.num_filler_nodes = int(round(self.total_filler_node_area/(filler_size_x*filler_size_y)))\n self.node_size_x = np.concatenate([self.node_size_x, np.full(self.num_filler_nodes, fill_value=filler_size_x, dtype=self.node_size_x.dtype)])\n self.node_size_y = np.concatenate([self.node_size_y, np.full(self.num_filler_nodes, fill_value=filler_size_y, dtype=self.node_size_y.dtype)])\n else:\n self.total_filler_node_area = 0 \n self.num_filler_nodes = 0\n content += \"total_filler_node_area = %g, #fillers = %g, filler sizes = %gx%g\\n\" % (self.total_filler_node_area, self.num_filler_nodes, filler_size_x, filler_size_y)\n content += \"====================================================\"\n\n logging.info(content)\n\n def write(self, params, filename, sol_file_format=None):\n \"\"\"\n @brief write placement solution\n @param filename output file name \n @param sol_file_format solution file format, DEF|DEFSIMPLE|BOOKSHELF|BOOKSHELFALL\n \"\"\"\n tt = time.time()\n logging.info(\"writing to %s\" % (filename))\n if sol_file_format is None: \n if filename.endswith(\".def\"): \n sol_file_format = place_io.SolutionFileFormat.DEF \n else:\n sol_file_format = place_io.SolutionFileFormat.BOOKSHELF\n\n # unscale locations \n unscale_factor = 1.0/params.scale_factor\n if unscale_factor == 1.0:\n node_x = self.node_x\n node_y = self.node_y\n else:\n node_x = self.node_x * unscale_factor\n node_y = self.node_y * unscale_factor\n\n # Global placement may have floating point positions. \n # Currently only support BOOKSHELF format. \n # This is mainly for debug. \n if not params.legalize_flag and not params.detailed_place_flag and sol_file_format == place_io.SolutionFileFormat.BOOKSHELF:\n self.write_pl(params, filename, node_x, node_y)\n else:\n place_io.PlaceIOFunction.write(self.rawdb, filename, sol_file_format, node_x, node_y)\n logging.info(\"write %s takes %.3f seconds\" % (str(sol_file_format), time.time()-tt))\n\n def read_pl(self, params, pl_file):\n \"\"\"\n @brief read .pl file\n @param pl_file .pl file\n \"\"\"\n tt = time.time()\n logging.info(\"reading %s\" % (pl_file))\n count = 0\n with open(pl_file, \"r\") as f:\n for line in f:\n line = line.strip()\n if line.startswith(\"UCLA\"):\n continue\n # node positions\n pos = re.search(r\"(\\w+)\\s+([+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?)\\s+([+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?)\\s*:\\s*(\\w+)\", line)\n if pos:\n node_id = self.node_name2id_map[pos.group(1)]\n self.node_x[node_id] = float(pos.group(2))\n self.node_y[node_id] = float(pos.group(6))\n self.node_orient[node_id] = pos.group(10)\n orient = pos.group(4)\n if params.scale_factor != 1.0:\n self.scale_pl(params.scale_factor)\n logging.info(\"read_pl takes %.3f seconds\" % (time.time()-tt))\n\n def write_pl(self, params, pl_file, node_x, node_y):\n \"\"\"\n @brief write .pl file\n @param pl_file .pl file \n \"\"\"\n tt = time.time()\n logging.info(\"writing to %s\" % (pl_file))\n content = \"UCLA pl 1.0\\n\"\n str_node_names = np.array(self.node_names).astype(np.str)\n str_node_orient = np.array(self.node_orient).astype(np.str)\n for i in range(self.num_physical_nodes):\n content += \"\\n%s %g %g : %s\" % (\n str_node_names[i],\n node_x[i], \n node_y[i], \n str_node_orient[i]\n )\n if i >= self.num_movable_nodes:\n content += \" /FIXED\"\n if i >= self.num_movable_nodes + self.num_terminals:\n content += \"_NI\"\n with open(pl_file, \"w\") as f:\n f.write(content)\n logging.info(\"write_pl takes %.3f seconds\" % (time.time()-tt))\n\n def write_nets(self, params, net_file):\n \"\"\"\n @brief write .net file\n @param params parameters \n @param net_file .net file \n \"\"\"\n tt = time.time()\n logging.info(\"writing to %s\" % (net_file))\n content = \"UCLA nets 1.0\\n\"\n content += \"\\nNumNets : %d\" % (len(self.net2pin_map))\n content += \"\\nNumPins : %d\" % (len(self.pin2net_map))\n content += \"\\n\"\n\n for net_id in range(len(self.net2pin_map)):\n pins = self.net2pin_map[net_id]\n content += \"\\nNetDegree : %d %s\" % (len(pins), self.net_names[net_id])\n for pin_id in pins: \n content += \"\\n\\t%s %s : %d %d\" % (self.node_names[self.pin2node_map[pin_id]], self.pin_direct[pin_id], self.pin_offset_x[pin_id]/params.scale_factor, self.pin_offset_y[pin_id]/params.scale_factor)\n\n with open(net_file, \"w\") as f:\n f.write(content)\n logging.info(\"write_nets takes %.3f seconds\" % (time.time()-tt))\n\n def apply(self, params, node_x, node_y):\n \"\"\"\n @brief apply placement solution and update database \n \"\"\"\n # assign solution \n self.node_x[:self.num_movable_nodes] = node_x[:self.num_movable_nodes]\n self.node_y[:self.num_movable_nodes] = node_y[:self.num_movable_nodes]\n\n # unscale locations \n unscale_factor = 1.0/params.scale_factor\n if unscale_factor == 1.0:\n node_x = self.node_x\n node_y = self.node_y\n else:\n node_x = self.node_x * unscale_factor\n node_y = self.node_y * unscale_factor\n\n # update raw database \n place_io.PlaceIOFunction.apply(self.rawdb, node_x, node_y)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n logging.error(\"One input parameters in json format in required\")\n\n params = Params.Params()\n params.load(sys.argv[sys.argv[1]])\n logging.info(\"parameters = %s\" % (params))\n\n db = PlaceDB()\n db(params)\n\n db.print_node(1)\n db.print_net(1)\n db.print_row(1)\n",
"##\n# @file density_overflow.py\n# @author Yibo Lin\n# @date Jun 2018\n# @brief Compute density overflow \n#\n\nimport math \nimport torch\nfrom torch import nn\nfrom torch.autograd import Function\n\nimport dreamplace.ops.density_overflow.density_overflow_cpp as density_overflow_cpp\nimport dreamplace.configure as configure\nif configure.compile_configurations[\"CUDA_FOUND\"] == \"TRUE\": \n import dreamplace.ops.density_overflow.density_overflow_cuda_thread_map as density_overflow_cuda_thread_map\n import dreamplace.ops.density_overflow.density_overflow_cuda_by_node as density_overflow_cuda_by_node\n\nimport numpy as np \nimport matplotlib\nmatplotlib.use('Agg')\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt \n\nimport pdb \n\nclass DensityOverflowFunction(Function):\n \"\"\"\n @brief compute density overflow.\n \"\"\"\n @staticmethod\n def forward(\n pos,\n node_size_x,\n node_size_y,\n bin_center_x, \n bin_center_y, \n initial_density_map, \n thread2node_map, \n thread2bin_x_map,\n thread2bin_y_map, \n target_density, \n xl, \n yl, \n xh, \n yh, \n bin_size_x, \n bin_size_y, \n num_movable_nodes, \n num_filler_nodes, \n algorithm, \n num_threads\n ):\n if pos.is_cuda:\n if algorithm == 'threadmap': \n output = density_overflow_cuda_thread_map.forward(\n pos.view(pos.numel()), \n node_size_x,\n node_size_y,\n bin_center_x, \n bin_center_y, \n initial_density_map, \n thread2node_map, \n thread2bin_x_map,\n thread2bin_y_map, \n target_density, \n xl, \n yl, \n xh, \n yh, \n bin_size_x, \n bin_size_y,\n num_movable_nodes, \n num_filler_nodes)\n elif algorithm == 'by-node': \n output = density_overflow_cuda_by_node.forward(\n pos.view(pos.numel()), \n node_size_x,\n node_size_y,\n bin_center_x, \n bin_center_y, \n initial_density_map, \n target_density, \n xl, \n yl, \n xh, \n yh, \n bin_size_x, \n bin_size_y,\n num_movable_nodes, \n num_filler_nodes)\n else:\n output = density_overflow_cpp.forward(\n pos.view(pos.numel()), \n node_size_x,\n node_size_y,\n bin_center_x, \n bin_center_y, \n initial_density_map, \n target_density, \n xl, \n yl, \n xh, \n yh, \n bin_size_x, \n bin_size_y, \n num_movable_nodes, \n num_filler_nodes, \n num_threads\n )\n # logger.debug(\"overflow initial_density_map\")\n # logger.debug(initial_density_map/(bin_size_x*bin_size_y))\n # logger.debug(\"overflow density_map\")\n # logger.debug(output[1]/(bin_size_x*bin_size_y))\n # plot(output[1].clone().div(bin_size_x*bin_size_y).cpu().numpy(), 'density_map')\n # output consists of (overflow, density_map, max_density)\n return output[0], output[2]\n\nclass DensityOverflow(object):\n \"\"\"\n @brief Compute density overflow for both movable and fixed cells.\n The density map for fixed cells is pre-computed. \n Each call will only compute the density map for movable cells. \n \"\"\"\n def __init__(self, node_size_x, node_size_y, bin_center_x, bin_center_y, target_density, xl, yl, xh, yh, bin_size_x, bin_size_y, num_movable_nodes, num_terminals, num_filler_nodes, algorithm='by-node', num_threads=8):\n \"\"\"\n @brief initialization \n @param node_size_x cell width array consisting of movable cells, fixed cells, and filler cells in order \n @param node_size_y cell height array consisting of movable cells, fixed cells, and filler cells in order \n @param bin_center_x bin center x locations \n @param bin_center_y bin center y locations \n @param target_density target density \n @param xl left boundary \n @param yl bottom boundary \n @param xh right boundary \n @param yh top boundary \n @param bin_size_x bin width \n @param bin_size_y bin height \n @param num_movable_nodes number of movable cells \n @param num_terminals number of fixed cells \n @param num_filler_nodes number of filler cells \n @param algorithm must be by-node | threadmap\n \"\"\"\n super(DensityOverflow, self).__init__()\n self.node_size_x = node_size_x\n self.node_size_y = node_size_y\n self.bin_center_x = bin_center_x\n self.bin_center_y = bin_center_y\n self.target_density = target_density\n self.xl = xl \n self.yl = yl\n self.xh = xh \n self.yh = yh \n self.bin_size_x = bin_size_x\n self.bin_size_y = bin_size_y\n self.num_movable_nodes = num_movable_nodes\n self.num_terminals = num_terminals\n self.num_filler_nodes = num_filler_nodes\n self.algorithm = algorithm \n # compute maximum impacted bins \n if algorithm == 'threadmap' and node_size_x.is_cuda: \n thread2node_map = torch.empty(1, dtype=torch.int32)\n thread2bin_x_map = torch.empty(1, dtype=torch.int32)\n thread2bin_y_map = torch.empty(1, dtype=torch.int32)\n density_overflow_cuda_thread_map.thread_map(\n self.node_size_x.cpu(), \n self.node_size_y.cpu(), \n self.xl, self.yl, self.xh, self.yh, \n self.bin_size_x, self.bin_size_y, \n self.num_movable_nodes, self.num_filler_nodes, \n thread2node_map, \n thread2bin_x_map, \n thread2bin_y_map\n )\n self.thread2node_map = thread2node_map.cuda()\n self.thread2bin_x_map = thread2bin_x_map.cuda()\n self.thread2bin_y_map = thread2bin_y_map.cuda()\n else:\n self.thread2node_map = None\n self.thread2bin_x_map = None\n self.thread2bin_y_map = None\n self.initial_density_map = None\n self.num_threads = num_threads\n def __call__(self, pos): \n \"\"\"\n @brief API \n @param pos cell locations. The array consists of x locations of movable cells, fixed cells, and filler cells, then y locations of them \n \"\"\"\n if self.initial_density_map is None:\n if self.num_terminals == 0:\n num_impacted_bins_x = 0 \n num_impacted_bins_y = 0 \n else:\n num_bins_x = int(math.ceil((self.xh-self.xl)/self.bin_size_x))\n num_bins_y = int(math.ceil((self.yh-self.yl)/self.bin_size_y))\n num_impacted_bins_x = ((self.node_size_x[self.num_movable_nodes:self.num_movable_nodes+self.num_terminals].max()+self.bin_size_x)/self.bin_size_x).ceil().clamp(max=num_bins_x)\n num_impacted_bins_y = ((self.node_size_y[self.num_movable_nodes:self.num_movable_nodes+self.num_terminals].max()+self.bin_size_y)/self.bin_size_y).ceil().clamp(max=num_bins_y)\n if pos.is_cuda:\n self.initial_density_map = density_overflow_cuda_thread_map.fixed_density_map(\n pos.view(pos.numel()), \n self.node_size_x,\n self.node_size_y,\n self.bin_center_x, \n self.bin_center_y, \n self.xl, \n self.yl, \n self.xh, \n self.yh, \n self.bin_size_x, \n self.bin_size_y,\n self.num_movable_nodes, \n self.num_terminals, \n num_impacted_bins_x, num_impacted_bins_y)\n else:\n self.initial_density_map = density_overflow_cpp.fixed_density_map(\n pos.view(pos.numel()), \n self.node_size_x,\n self.node_size_y,\n self.bin_center_x, \n self.bin_center_y, \n self.xl, \n self.yl, \n self.xh, \n self.yh, \n self.bin_size_x, \n self.bin_size_y, \n self.num_movable_nodes, \n self.num_terminals, \n self.num_threads\n )\n #plot(self.initial_density_map.clone().div(self.bin_size_x*self.bin_size_y).cpu().numpy(), 'initial_density_map')\n\n return DensityOverflowFunction.forward(\n pos,\n node_size_x=self.node_size_x,\n node_size_y=self.node_size_y,\n bin_center_x=self.bin_center_x, \n bin_center_y=self.bin_center_y, \n initial_density_map=self.initial_density_map, \n thread2node_map=self.thread2node_map, \n thread2bin_x_map=self.thread2bin_x_map, \n thread2bin_y_map=self.thread2bin_y_map, \n target_density=self.target_density, \n xl=self.xl, \n yl=self.yl, \n xh=self.xh, \n yh=self.yh, \n bin_size_x=self.bin_size_x, \n bin_size_y=self.bin_size_y, \n num_movable_nodes=self.num_movable_nodes, \n num_filler_nodes=self.num_filler_nodes, \n algorithm=self.algorithm, \n num_threads=self.num_threads\n )\n\ndef plot(density_map, name):\n \"\"\"\n @brief density map contour and heat map \n \"\"\"\n print(np.amax(density_map))\n print(np.mean(density_map))\n fig = plt.figure(figsize=(4, 3))\n ax = fig.gca(projection='3d')\n\n x = np.arange(density_map.shape[0])\n y = np.arange(density_map.shape[1])\n\n x, y = np.meshgrid(x, y)\n ax.plot_surface(x, y, density_map, alpha=0.8)\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('density')\n\n #plt.tight_layout()\n plt.savefig(name+\".3d.png\")\n\n plt.clf()\n\n fig, ax = plt.subplots()\n\n ax.pcolor(density_map)\n\n # Loop over data dimensions and create text annotations.\n #for i in range(density_map.shape[0]):\n # for j in range(density_map.shape[1]):\n # text = ax.text(j, i, density_map[i, j],\n # ha=\"center\", va=\"center\", color=\"w\")\n fig.tight_layout()\n plt.savefig(name+\".2d.png\")\n"
] |
[
[
"numpy.amax",
"numpy.maximum",
"numpy.minimum",
"numpy.amin",
"numpy.full",
"numpy.ceil",
"numpy.floor",
"numpy.argsort",
"numpy.array",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.amax",
"torch.empty",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf",
"numpy.mean",
"numpy.meshgrid",
"matplotlib.pyplot.figure"
]
] |
KathCYM/ParlAI
|
[
"2ec2ad365b008d28347cbbd459ba29eb41657034"
] |
[
"parlai/agents/rag/retrievers.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"\nRetrievers for RAG.\n\"\"\"\nfrom abc import ABC, abstractmethod\nimport copy\nimport csv\nimport gzip\nimport numpy as np\nimport os\nfrom parlai.core.message import Message\nimport torch\nimport torch.cuda\nimport torch.nn\nimport transformers\nfrom tqdm import tqdm\n\ntry:\n from transformers import BertTokenizerFast as BertTokenizer\nexcept ImportError:\n from transformers import BertTokenizer\nfrom typing import Tuple, List, Dict, Union, Optional, Any\nfrom typing_extensions import final\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom parlai.agents.tfidf_retriever.tfidf_retriever import TfidfRetrieverAgent\nfrom parlai.core.agents import create_agent, create_agent_from_model_file\nfrom parlai.core.build_data import modelzoo_path\nfrom parlai.core.dict import DictionaryAgent\nfrom parlai.core.loader import register_agent\nfrom parlai.core.opt import Opt\nfrom parlai.core.torch_generator_agent import TorchGeneratorAgent\nfrom parlai.core.torch_ranker_agent import TorchRankerAgent\nimport parlai.utils.logging as logging\nfrom parlai.utils.torch import padded_tensor\nfrom parlai.utils.typing import TShared\nfrom parlai.utils.io import PathManager\n\nfrom parlai.agents.rag.dpr import DprQueryEncoder\nfrom parlai.agents.rag.polyfaiss import RagDropoutPolyWrapper\nfrom parlai.agents.rag.indexers import DenseHNSWFlatIndexer, indexer_factory\nfrom parlai.agents.rag.args import (\n RetrieverType,\n WOW_INDEX_PATH,\n WOW_PASSAGES_PATH,\n POLYENCODER_OPT_KEYS,\n TRANSFORMER_RANKER_BASE_OPT,\n WOW_COMPRESSED_INDEX_PATH,\n)\nfrom parlai.agents.rag.retrieve_api import SearchEngineRetriever\n\n\ndef load_passage_reader(\n ctx_file: str, return_dict: bool = True\n) -> Union[Dict[str, Tuple[str, str]], List[Tuple[str, str, str]]]:\n \"\"\"\n Load passages from file, corresponding to a FAISS index.\n\n We attempt to read the passages with a csv reader.\n\n If passage files are not saved correctly with a csv reader,\n reads can fail.\n\n :param ctxt_file:\n file to read\n\n :return reader:\n return a reader over the passages\n \"\"\"\n logging.info(f'Reading data from: {ctx_file}')\n f_open = gzip.open if ctx_file.endswith(\".gz\") else open\n try:\n passages = {} if return_dict else []\n with f_open(ctx_file) as tsvfile:\n _reader = csv.reader(tsvfile, delimiter='\\t') # type: ignore\n ids = []\n for idx, row in tqdm(enumerate(_reader)):\n if idx == 0:\n assert row[0] == 'id'\n ids.append(-1)\n elif idx <= 1:\n ids.append(row[0])\n if return_dict:\n passages[row[0]] = (row[1], row[2]) # type: ignore\n else:\n passages.append((row[0], row[1], row[2])) # type: ignore\n continue\n else:\n assert int(row[0]) == int(ids[idx - 1]) + 1, \"invalid load\"\n if return_dict:\n passages[row[0]] = (row[1], row[2]) # type: ignore\n else:\n passages.append((row[0], row[1], row[2])) # type: ignore\n ids.append(row[0])\n\n del ids\n except (csv.Error, AssertionError) as e:\n passages = {} if return_dict else []\n logging.error(f'Exception: {e}')\n logging.warning('Error in loading csv; loading via readlines')\n with f_open(ctx_file) as tsvfile:\n for idx, l in tqdm(enumerate(tsvfile.readlines())):\n line = l.replace('\\n', '').split('\\t') # type: ignore\n assert len(line) == 3\n if idx == 0:\n assert line[0] == 'id'\n if line[0] != 'id':\n if return_dict:\n passages[row[0]] = (row[1], row[2]) # type: ignore\n else:\n passages.append((row[0], row[1], row[2])) # type: ignore\n return passages\n\n\ndef load_passages_dict(ctx_file: str) -> Dict[str, Tuple[str, str]]:\n \"\"\"\n Load passages as a dict.\n\n :param ctx_file:\n file to read\n\n :return passages_dict:\n return a dict mapping passage id to a tuple of (text, title)\n \"\"\"\n psgs_dict = load_passage_reader(ctx_file, return_dict=True)\n assert isinstance(psgs_dict, dict)\n return psgs_dict\n\n\ndef load_passages_list(ctx_file: str) -> List[Tuple[str, str, str]]:\n \"\"\"\n Load passages as a list.\n\n :param ctx_file:\n file to read\n\n :return passages_dict:\n return a list of 3-tuples (id, text, title)\n \"\"\"\n psgs_list = load_passage_reader(ctx_file, return_dict=False)\n assert isinstance(psgs_list, list)\n return psgs_list\n\n\nclass Document:\n \"\"\"\n A Document used in retrieval.\n \"\"\"\n\n TITLE_DELIM = ' / '\n PASSAGE_DELIM = ' // '\n\n def __init__(self, title: str, text: str, docid: Union[int, str]):\n assert all(isinstance(t, str) for t in [title, text])\n self._title = title\n self._text = text\n self._id = str(docid)\n\n def get_title(self) -> str:\n return self._title\n\n def get_text(self) -> str:\n return self._text\n\n def get_id(self) -> str:\n return self._id\n\n def __repr__(self):\n return f\"ID: {self._id}\\nTitle: {self._title}\\nText: {self._text}\"\n\n def __str__(self):\n return f\"{self._title} | {self._text}\"\n\n def get_passage_str(self):\n return f\"{self._title.strip()}{self.TITLE_DELIM}{self._text.strip()}{self.PASSAGE_DELIM}\"\n\n def get_tokenization_str(self):\n return f\"{self._title.strip()}{self.TITLE_DELIM}{self._text.strip()}\"\n\n\nBLANK_DOC = Document('', '', '')\n\n\ndef argsort_scores_and_docs(\n scores: torch.Tensor, docs: List[Document], n_docs: int\n) -> Tuple[List[Document], torch.Tensor]:\n \"\"\"\n Sort scores and documents by score, return n_docs ranked docs/scores.\n\n :param scores:\n scores with which to rank\n :param docs:\n docs to argsort\n :param n_docs:\n number of docs to return\n\n :return:\n (docs, scores) --> sorted documents, according to scores.\n \"\"\"\n scores_sorter = scores.sort(descending=True)\n ranked_docs = [docs[idx] for idx in scores_sorter.indices[:n_docs]]\n ranked_scores = scores_sorter.values[:n_docs]\n return ranked_docs, ranked_scores\n\n\ndef clean_vec(\n vec: torch.LongTensor, end_idx: int, special_toks: List[int] = None\n) -> List[int]:\n \"\"\"\n Remove special tokens from a tensor prior to text conversion.\n \"\"\"\n new_vec = []\n for i in vec:\n if i == end_idx:\n break\n elif special_toks and i in special_toks:\n continue\n new_vec.append(i)\n return new_vec\n\n\nclass RagRetrieverTokenizer:\n \"\"\"\n Wrapper for various tokenizers used by RAG Query Model.\n \"\"\"\n\n VOCAB_PATH = 'vocab.txt'\n\n def __init__(\n self,\n datapath: str,\n query_model: str,\n dictionary: DictionaryAgent,\n max_length: int = 256,\n delimiter='\\n',\n ):\n \"\"\"\n :param query_model:\n query model type (e.g. bert)\n :param dictionary:\n ParlAI dictionary agent\n :param fast:\n whether to instantiate fast BertTokenizer\n :param max_length:\n maximum length of encoding.\n \"\"\"\n self.datapath = datapath\n self.query_model = query_model\n self.tokenizer = self._init_tokenizer(dictionary)\n self.max_length = max_length\n self._delimiter = delimiter\n\n def _init_tokenizer(\n self, dictionary: DictionaryAgent\n ) -> Union[BertTokenizer, DictionaryAgent]:\n \"\"\"\n If a regular parlai model, use the regular dictionary.\n\n Otherwise, build as necessary\n\n :param dictionary:\n ParlAI dictionary agent\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n try:\n return BertTokenizer.from_pretrained('bert-base-uncased')\n except (ImportError, OSError):\n vocab_path = PathManager.get_local_path(\n os.path.join(self.datapath, \"bert_base_uncased\", self.VOCAB_PATH)\n )\n return transformers.BertTokenizer.from_pretrained(vocab_path)\n else:\n return dictionary\n\n def get_pad_idx(self) -> int:\n \"\"\"\n Return pad token idx.\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n return self.tokenizer.pad_token_id\n else:\n return self.tokenizer[self.tokenizer.null_token]\n\n def get_delimiter(self) -> str:\n \"\"\"\n Return delimiter.\n \"\"\"\n return self._delimiter\n\n def get_bos_idx(self) -> int:\n \"\"\"\n Return start token idx.\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n return self.tokenizer.bos_token_id or 1\n else:\n return self.tokenizer[self.tokenizer.start_token]\n\n def get_eos_idx(self) -> int:\n \"\"\"\n Return start token idx.\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n return self.tokenizer.eos_token_id or 2\n else:\n return self.tokenizer[self.tokenizer.end_token]\n\n def encode(self, txt: str, txt_pair: Optional[str] = None) -> List[int]:\n \"\"\"\n Encode text.\n\n :param txt:\n text to encode\n :param txt_pair:\n Optional additional text to encode.\n Useful if encoding two parts of a text, e.g. title & text.\n\n :return encoding:\n return encoded text.\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n txt = txt.lower().strip()\n if txt_pair:\n txt_pair = txt_pair.lower().strip()\n return self.tokenizer.encode(\n txt,\n text_pair=txt_pair,\n add_special_tokens=True,\n max_length=self.max_length,\n pad_to_max_length=False,\n truncation='longest_first',\n )\n else:\n return self.tokenizer.txt2vec(txt)\n\n def decode(self, vec: torch.LongTensor) -> str:\n \"\"\"\n Decode a token vector into a string.\n \"\"\"\n if self.query_model in ['bert', 'bert_from_parlai_rag']:\n return self.tokenizer.decode(\n clean_vec(vec, self.get_eos_idx()), skip_special_tokens=True\n )\n else:\n return self.tokenizer.vec2txt(\n clean_vec(\n vec,\n self.get_eos_idx(),\n special_toks=[\n self.get_pad_idx(),\n self.get_bos_idx(),\n self.get_eos_idx(),\n ],\n )\n )\n\n\nclass RagRetriever(torch.nn.Module, ABC):\n \"\"\"\n RAG Retriever.\n\n Provides an interface to the RagModel for retrieving documents.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n super().__init__()\n self.retriever_type = RetrieverType(opt['rag_retriever_type'])\n if not (\n (self.retriever_type == RetrieverType.SEARCH_ENGINE)\n or (opt.get('retriever_debug_index') in [None, 'none'])\n ):\n if opt.get('retriever_debug_index') == 'exact':\n opt['path_to_index'] = WOW_INDEX_PATH\n else:\n opt['path_to_index'] = WOW_COMPRESSED_INDEX_PATH\n opt['path_to_dpr_passages'] = WOW_PASSAGES_PATH\n self.opt = opt\n self.print_docs = opt.get('print_docs', False)\n self.max_doc_len = opt['max_doc_token_length']\n self.max_query_len = opt['rag_query_truncate'] or 1024\n self.end_idx = dictionary[dictionary.end_token]\n self._tokenizer = RagRetrieverTokenizer(\n datapath=opt['datapath'],\n query_model=opt['query_model'],\n dictionary=dictionary,\n delimiter=opt.get('delimiter', '\\n') or '\\n',\n )\n self.fp16 = (\n not opt['no_cuda']\n and torch.cuda.is_available()\n and self.opt.get('fp16', False)\n )\n\n @final\n def retrieve(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Retrieve documents, given a query vector.\n\n :param query:\n tokenized query\n\n :return (docs, scores):\n docs: list of Documents for each batch example.\n scores: [bsz, n_docs] document scores\n \"\"\"\n docs, scores = self.retrieve_and_score(query)\n if self.print_docs:\n self.display_docs(docs)\n self.top_docs = [[str(d) for d in ds] for ds in docs]\n return docs, scores\n\n @abstractmethod\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Retrieve documents for a given query.\n\n :param query:\n tokenized query\n\n :return (docs, scores):\n docs: list of Documents for each batch example.\n scores: [bsz, n_docs] document scores\n \"\"\"\n\n def tokenize_query(self, query: str) -> List[int]:\n \"\"\"\n Tokenize the query.\n\n :param query:\n query to tokenize\n\n :return tokenized_query:\n return list of tokens\n \"\"\"\n return self._tokenizer.encode(query)\n\n def vectorize_texts(\n self,\n input_text: List[str],\n tokenizer: RagRetrieverTokenizer,\n max_len: Optional[int] = None,\n ) -> torch.LongTensor:\n \"\"\"\n Vectorize a set of input texts with an arbitrary RagRetrieverTokenizer.\n\n :param input_text:\n list of input strings\n :param tokenizer:\n tokenizer that encodes the input strings\n :param max_len:\n max length to tokenize\n\n :return vecs:\n returns a stacked padded tensor of tokens.\n \"\"\"\n vecs = [tokenizer.encode(q) for q in input_text]\n if max_len:\n vecs = [v[:max_len] for v in vecs]\n vecs, _ = padded_tensor(\n vecs,\n fp16friendly=self.fp16,\n pad_idx=tokenizer.get_pad_idx(),\n max_len=max_len,\n )\n return vecs\n\n def get_delimiter(self) -> str:\n \"\"\"\n Return the tokenizer's delimiter.\n \"\"\"\n return self._tokenizer.get_delimiter()\n\n def display_docs(self, top_docs: List[List[Document]]):\n \"\"\"\n Prints documents.\n\n :param top_docs:\n list of documents for each batch item\n \"\"\"\n for docs in top_docs:\n for rank, doc in enumerate(docs):\n print(f\"Rank: {rank}\\n{doc}\")\n\n def share(self) -> TShared:\n \"\"\"\n Share retriever stuff.\n\n Share anything that can be handily used by other retrievers.\n\n This is primarily to share things that take up substantial RAM\n (indices, passages)\n \"\"\"\n return {}\n\n\nclass RagRetrieverReranker(RagRetriever, ABC):\n \"\"\"\n Trait that carries methods for Reranker-based retrievers.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n super().__init__(opt, dictionary, shared=shared)\n self.n_final_docs = opt['n_docs']\n\n @final\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Perform two-stage retrieval; rescore initial set of docs.\n\n :param query:\n query tokens\n\n :return (docs, scores):\n docs: list of Documents for each batch example\n scores: doc scores\n \"\"\"\n # 1. Get Initial documents\n initial_docs, initial_scores = self._retrieve_initial(query)\n new_scores = self._rescore(query, initial_docs)\n\n # 2. Get new scores\n final_docs: List[List[Document]] = []\n final_scores: List[torch.Tensor] = []\n new_score_lambda = self._get_new_score_lambda()\n\n for i in range(len(initial_docs)):\n docs_i = initial_docs[i]\n initial_scores_i = initial_scores[i]\n scores_i = torch.mul(initial_scores_i, (1 - new_score_lambda)) + torch.mul(\n new_scores[i], new_score_lambda\n )\n docs_i, scores_i = argsort_scores_and_docs(\n scores_i, docs_i, self.n_final_docs\n )\n final_docs.append(docs_i)\n final_scores.append(scores_i)\n\n return final_docs, torch.stack(final_scores)\n\n @abstractmethod\n def _retrieve_initial(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Perform initial stage of retrieval.\n\n :param query:\n tokenized query\n\n :return (docs, scores):\n docs: list of Documents for each batch example\n scores: doc scores\n \"\"\"\n\n @abstractmethod\n def _rescore(\n self, query: torch.LongTensor, docs: List[List[Document]]\n ) -> torch.Tensor:\n \"\"\"\n Rescore retrieved documents.\n\n :param query:\n tokenized query\n :param docs:\n List of initially retrieved top docs for each batch example\n\n :return scores:\n return new doc scores.\n \"\"\"\n\n @abstractmethod\n def _get_new_score_lambda(self) -> torch.nn.Parameter:\n \"\"\"\n Return the lambda used for computing the new score.\n \"\"\"\n\n\nclass DPRRetriever(RagRetriever):\n \"\"\"\n DPR Retriever.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared=None):\n \"\"\"\n Initialize DPR Retriever.\n \"\"\"\n super().__init__(opt, dictionary, shared=shared)\n self.load_index(opt, shared)\n self.n_docs = opt['n_docs']\n self.query_encoder = DprQueryEncoder(\n opt, dpr_model=opt['query_model'], pretrained_path=opt['dpr_model_file']\n )\n\n def load_index(self, opt, shared):\n if not shared:\n self.indexer = indexer_factory(opt)\n index_path = modelzoo_path(opt['datapath'], opt['path_to_index'])\n passages_path = modelzoo_path(opt['datapath'], opt['path_to_dpr_passages'])\n embeddings_path = None\n if opt['path_to_dense_embeddings'] is not None:\n embeddings_path = modelzoo_path(\n opt['datapath'], opt['path_to_dense_embeddings']\n )\n self.indexer.deserialize_from(index_path, embeddings_path)\n self.passages = load_passages_dict(passages_path)\n elif shared:\n self.indexer = shared['indexer']\n self.passages = shared['passages']\n\n def share(self) -> TShared:\n \"\"\"\n Share FAISS retriever and passages.\n \"\"\"\n shared = super().share()\n shared['indexer'] = self.indexer\n shared['passages'] = self.passages\n return shared\n\n def index_retrieve(\n self, query: torch.Tensor, n_docs: int\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Retrieve over FAISS index.\n\n :param query:\n bsz x embed_dim query tensor\n :param n_docs:\n number of docs to retrieve\n\n :return (ids, scores):\n ids: [bsz, n_docs] tensor of document IDs\n scores: [bsz, n_docs] tensor of document scores\n \"\"\"\n # retrieve docs and scores, reconstruct document embeddings & scores\n # NOTE: important that detach occurs _for retrieval only_, as we use the\n # query encodings to compute scores later in this function; if detached,\n # gradient will not flow to the query encoder.\n top_docs_and_scores = self.indexer.search(\n query.cpu().detach().to(torch.float32).numpy(), n_docs\n )\n ids, np_vectors = zip(*top_docs_and_scores)\n vectors = torch.tensor(np_vectors).to(query)\n if isinstance(self.indexer, DenseHNSWFlatIndexer):\n vectors = vectors[:, :, :-1]\n # recompute exact FAISS scores\n scores = torch.bmm(query.unsqueeze(1), vectors.transpose(1, 2)).squeeze(1)\n if torch.isnan(scores).sum().item():\n raise RuntimeError(\n '\\n[ Document scores are NaN; please look into the built index. ]\\n'\n '[ This generally happens if FAISS cannot separate vectors appropriately. ]\\n'\n '[ If using a compressed index, try building an exact index: ]\\n'\n '[ $ python index_dense_embeddings --indexer-type exact... ]'\n )\n ids = torch.tensor([[int(s) for s in ss] for ss in ids])\n\n return ids, scores\n\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Retrieve and score.\n\n For DPR, we encode query tokens and retrieve from FAISS index.\n\n :param query:\n query tokens\n\n :return (docs, scores):\n docs: list of (text, title) tuples for each batch example\n scores: doc scores\n \"\"\"\n query_enc = self.query_encoder(query)\n top_doc_ids_tensor, top_doc_scores = self.index_retrieve(query_enc, self.n_docs)\n top_docs, top_doc_ids = [], []\n for i in range(query.size(0)):\n ids_i = []\n docs_i = []\n for int_id in top_doc_ids_tensor[i]:\n doc_id = str(int_id.item())\n passage = self.passages[doc_id]\n\n ids_i.append(doc_id)\n docs_i.append(Document(title=passage[1], text=passage[0], docid=doc_id))\n top_docs.append(docs_i)\n top_doc_ids.append(ids_i)\n return top_docs, top_doc_scores\n\n\nclass TFIDFRetriever(RagRetriever):\n \"\"\"\n Use TFIDF to retrieve wikipedia documents.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n \"\"\"\n Init a TFIDFRetrieverAgent.\n \"\"\"\n opt['query_model'] = 'tfidf'\n super().__init__(opt, dictionary, shared=shared)\n tfidf_opt = {\n 'model': 'rag_tfidf_retriever',\n 'model_file': (opt['tfidf_model_path']),\n 'tfidf_model_path': opt['tfidf_model_path'],\n 'retriever_num_retrieved': opt['n_docs'],\n 'retriever_mode': 'keys',\n 'override': {'model': 'rag_tfidf_retriever', 'remove_title': False},\n }\n self.n_docs = opt['n_docs']\n self.max_doc_paragraphs = opt['tfidf_max_doc_paragraphs']\n assert self.max_doc_paragraphs != 0\n if not shared:\n self.tfidf_retriever = create_agent(tfidf_opt)\n else:\n self.tfidf_retriever = shared['tfidf_retriever']\n\n def share(self) -> TShared:\n shared = super().share()\n shared['tfidf_retriever'] = self.tfidf_retriever\n return shared\n\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], Union[torch.Tensor, List[torch.Tensor]]]:\n \"\"\"\n Retrieve and score using TFIDF.\n\n :param query:\n query tokens\n\n :return (docs, scores):\n docs: list of (text, title) tuples for each batch example\n scores: doc scores\n \"\"\"\n\n def _build_doc(idx, cand):\n title = cand.split('\\n\\n')[0]\n paragraphs = cand.split('\\n\\n')[1:]\n if self.max_doc_paragraphs > 0:\n paragraphs = paragraphs[: self.max_doc_paragraphs]\n return Document(title=title, text=' '.join(paragraphs), docid=ids_i[idx])\n\n docs = []\n scores = []\n\n for q in query:\n query_text = self._tokenizer.decode(q)\n self.tfidf_retriever.observe({'text': query_text, 'episode_done': True})\n act = self.tfidf_retriever.act()\n if 'candidate_scores' not in act:\n scores_i = [0] * self.n_docs\n docs_i = [BLANK_DOC] * self.n_docs\n else:\n scores_i = act['candidate_scores']\n candidate_docs = act['text_candidates']\n ids_i = act['candidate_ids']\n candidate_docs = [\n _build_doc(j, c) for j, c in enumerate(act['text_candidates'])\n ]\n docs_i = candidate_docs[: self.n_docs]\n scores_i = scores_i[: self.n_docs]\n if len(docs_i) < self.n_docs:\n # Something went wrong with TFIDF here; need to add null docs\n logging.warning(\n f'Ex has less than {self.n_docs} TFIDF docs: {len(docs_i)}'\n )\n num_null = self.n_docs - len(docs_i)\n docs_i += [BLANK_DOC] * num_null\n scores_i = np.append(scores_i, [0] * num_null)\n docs.append(docs_i)\n scores.append(torch.FloatTensor(scores_i).to(query.device))\n\n scores = torch.stack(scores)\n return docs, scores\n\n\nclass DPRThenTorchReranker(RagRetrieverReranker, DPRRetriever, ABC):\n \"\"\"\n Base Class for DPR --> TorchRanker Retrievers.\n\n Handles some shared functionality.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n \"\"\"\n Initialize DPR model.\n\n It is up to subclasses to initialize rerankers.\n \"\"\"\n RagRetrieverReranker.__init__(self, opt, dictionary, shared=shared)\n self.dpr_num_docs = opt['dpr_num_docs']\n assert self.dpr_num_docs\n dpr_opt = copy.deepcopy(opt)\n dpr_opt['n_docs'] = self.dpr_num_docs\n DPRRetriever.__init__(self, dpr_opt, dictionary, shared=shared)\n\n def get_reranker_opts(self, opt: Opt) -> Dict[str, Any]:\n \"\"\"\n Provide options used when building the rerankers.\n\n Base class ensures that various optimizations (cuda, fp16, parallel)\n are accounted for.\n\n :param opt:\n base opt\n\n :return options_dict:\n return a dictionary mapping options to values.\n \"\"\"\n return {\n 'no_cuda': opt['no_cuda'],\n 'fp16': opt['fp16'],\n 'model_parallel': opt['model_parallel'],\n 'data_parallel': opt['data_parallel'],\n }\n\n def _build_reranker(\n self, opt: Opt\n ) -> Tuple[torch.nn.Module, RagRetrieverTokenizer]:\n \"\"\"\n Builds reranker.\n\n :param opt:\n original opt\n\n :return (module, dict)\n module: the model from the agent created via the options\n dict: A RagRetrieverTokenizer, dictionary for the created model.\n \"\"\"\n rerank_opt = copy.deepcopy(opt)\n rerank_opt = {**TRANSFORMER_RANKER_BASE_OPT, **self.get_reranker_opts(opt)}\n logging.disable()\n agent = create_agent(rerank_opt)\n logging.enable()\n assert isinstance(agent, TorchRankerAgent)\n\n return (\n agent.model,\n RagRetrieverTokenizer(opt['datapath'], '', agent.dict, max_length=360),\n )\n\n def _retrieve_initial(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Initial DPR retrieval.\n\n Just call superclass to retrieve first stage.\n\n :param query:\n encoding of query\n :param mask:\n optional query mask\n\n :return (docs, scores):\n docs: list of (text, title) tuples for each batch example\n scores: doc scores\n \"\"\"\n return DPRRetriever.retrieve_and_score(self, query)\n\n\nclass DPRThenPolyRetriever(DPRThenTorchReranker):\n \"\"\"\n 2 Stage Retrieval with DPR and Poly-encoder.\n\n 1. Retrieve N Docs with DPR\n 2. Rescore docs with polyencoder\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n \"\"\"\n Initialize a Poly-Encoder Agent.\n \"\"\"\n # 1. Call super to init DPR\n super().__init__(opt, dictionary, shared=shared)\n\n # 2. Poly-encoder\n self.polyencoder, self.poly_tokenizer = self._build_reranker(opt)\n self.register_parameter(\n \"poly_score_lambda\",\n torch.nn.Parameter(torch.tensor([float(opt['poly_score_initial_lambda'])])),\n )\n\n def _get_new_score_lambda(self) -> torch.nn.Parameter:\n \"\"\"\n Return the lambda used for computing the new score.\n \"\"\"\n return self.poly_score_lambda # type: ignore\n\n def get_reranker_opts(self, opt: Opt) -> Dict[str, Any]:\n \"\"\"\n Provide options used when building the polyencoder.\n\n :param opt:\n base opt\n\n :return options_dict:\n return a dictionary mapping options to values.\n \"\"\"\n from parlai.agents.rag.args import PRETRAINED_RANKER_TYPES\n\n init_path = opt['polyencoder_init_model']\n if init_path in PRETRAINED_RANKER_TYPES:\n init_model = f\"zoo:pretrained_transformers/poly_model_huge_{opt['polyencoder_init_model']}/model\"\n dict_file = f\"zoo:pretrained_transformers/poly_model_huge_{opt['polyencoder_init_model']}/model.dict\"\n else:\n assert os.path.exists(init_path)\n init_model = init_path\n dict_file = f'{init_path}.dict'\n\n return {\n 'model': 'transformer/polyencoder',\n 'init_model': init_model,\n 'dict_file': dict_file,\n # necessary opt args\n 'multitask_weights': [1],\n **{k: opt[k] for k in POLYENCODER_OPT_KEYS},\n **super().get_reranker_opts(opt),\n }\n\n def _rescore(\n self, query: torch.LongTensor, docs: List[List[Document]]\n ) -> torch.Tensor:\n \"\"\"\n Compute Poly-encoder score with initial set of Documents.\n\n Scoring taken from PolyencoderAgent.score_candidates\n\n :param query:\n query tokens, used in DPR retrieval.\n :param docs:\n List of initially retrieved top docs for each batch example\n\n :return new_scores:\n return scored documents.\n \"\"\"\n poly_query_vec = self.vectorize_texts(\n [self._tokenizer.decode(q) for q in query],\n self.poly_tokenizer,\n self.max_query_len,\n ).to(query.device)\n\n doc_vecs = torch.stack(\n [\n self.vectorize_texts(\n [d.get_tokenization_str() for d in docs_i],\n self.poly_tokenizer,\n self.max_doc_len,\n )\n for docs_i in docs\n ]\n ).to(query.device)\n\n ctxt_rep, ctxt_rep_mask, _ = self.polyencoder(ctxt_tokens=poly_query_vec)\n _, _, cand_rep = self.polyencoder(cand_tokens=doc_vecs)\n scores = self.polyencoder(\n ctxt_rep=ctxt_rep, ctxt_rep_mask=ctxt_rep_mask, cand_rep=cand_rep\n )\n return scores\n\n\nclass PolyFaissRetriever(DPRThenPolyRetriever):\n \"\"\"\n Poly-encoder Retriever, using FAISS.\n\n Performs FAISS retrieval to retrieve N initial docs; re-ranks according to Poly-\n encoder score to narrow down to K docs.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared = None):\n assert opt['query_model'] == 'dropout_poly'\n super().__init__(opt, dictionary, shared=shared)\n self.dropout_poly = RagDropoutPolyWrapper(opt)\n self.polyencoder = self.dropout_poly.model\n\n self.poly_tokenizer = RagRetrieverTokenizer(\n opt['datapath'], opt['query_model'], self.dropout_poly.dict, max_length=360\n )\n\n model = (\n self.polyencoder.module\n if hasattr(self.polyencoder, 'module')\n else self.polyencoder\n )\n for param in model.encoder_cand.parameters(): # type: ignore\n # freeze document encoding for PolyFAISS.\n param.requires_grad = False\n\n\n@register_agent(\"rag_tfidf_retriever\")\nclass RagTfidfRetrieverAgent(TfidfRetrieverAgent):\n \"\"\"\n Wrapper around TFIDF Retriever to cache retrieved documents.\n \"\"\"\n\n def __init__(self, opt: Opt, shared: TShared = None):\n super().__init__(opt, shared)\n if not shared:\n self.docid_to_text = {}\n else:\n self.docid_to_text = shared.get('docid_to_text', {})\n\n def share(self) -> TShared:\n shared = super().share()\n shared['docid_to_text'] = self.docid_to_text\n return shared\n\n def doc2txt(self, docid):\n \"\"\"\n Cache document texts during train/eval.\n \"\"\"\n if docid not in self.docid_to_text:\n text = super().doc2txt(docid)\n self.docid_to_text[docid] = text\n else:\n text = self.docid_to_text[docid]\n return text\n\n\nBLANK_SEARCH_DOC = {'url': None, 'content': '', 'title': ''}\nNO_SEARCH_QUERY = 'no_passages_used'\n\n\nclass SearchQueryRetriever(RagRetriever):\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared):\n RagRetriever.__init__(self, opt, dictionary, shared=shared)\n opt['skip_retrieval_token'] = NO_SEARCH_QUERY\n self.n_docs = opt['n_docs']\n self.len_chunk = opt['splitted_chunk_length']\n self.doc_chunk_split_mode = opt['doc_chunk_split_mode']\n n_doc_chunks = opt['n_ranked_doc_chunks']\n chunk_ranker_type = opt['doc_chunks_ranker']\n if chunk_ranker_type == 'tfidf':\n self.chunk_reranker = TfidfChunkRanker(n_doc_chunks)\n else:\n self.chunk_reranker = HeadChunkRanker(n_doc_chunks)\n\n if not shared:\n self.query_generator = self.init_search_query_generator(opt)\n else:\n self.query_generator = shared['query_generator']\n self.dict = dictionary\n self.init_query_encoder(opt)\n\n def share(self) -> TShared:\n shared = super().share()\n shared['query_generator'] = self.query_generator\n return shared\n\n def init_search_query_generator(self, opt) -> TorchGeneratorAgent:\n model_file = opt['search_query_generator_model_file']\n logging.info('Loading search generator model')\n logging.disable()\n search_query_gen_agent = create_agent_from_model_file(\n model_file,\n opt_overrides={\n 'skip_generation': False,\n 'inference': opt['search_query_generator_inference'],\n 'beam_min_length': opt['search_query_generator_beam_min_length'],\n 'beam_size': opt['search_query_generator_beam_size'],\n 'text_truncate': opt['search_query_generator_text_truncate'],\n },\n )\n logging.enable()\n logging.info('Search query generator model loading completed!')\n return search_query_gen_agent\n\n def generate_search_query(self, query: torch.LongTensor) -> List[str]:\n \"\"\"\n Generates a list of queries for the encoded query (context) tensor.\n \"\"\"\n texts = [self._tokenizer.decode(q) for q in query]\n obs_list = []\n for t in texts:\n msg = Message({'text': t, 'episode_done': True})\n obs_list.append(self.query_generator.observe(msg))\n self.query_generator.reset() # Erase the history\n search_quries = [r['text'] for r in self.query_generator.batch_act(obs_list)]\n logging.debug(f'Generated search queries {search_quries}')\n return search_quries\n\n def init_query_encoder(self, opt):\n if hasattr(self, 'query_encoder'):\n # It is already instantiated\n return\n self.query_encoder = DprQueryEncoder(\n opt, dpr_model=opt['query_model'], pretrained_path=opt['dpr_model_file']\n )\n\n def text2tokens(self, txt: str):\n if self.doc_chunk_split_mode == 'word':\n return txt.split(' ')\n else:\n return self.dict.txt2vec(txt)\n\n def tokens2text(self, tokens: List[int]):\n if self.doc_chunk_split_mode == 'word':\n return ' '.join(tokens)\n else:\n return self.dict.vec2txt(tokens)\n\n def pick_chunk(self, query, doc_text):\n \"\"\"\n Splits the document and returns the selected chunks.\n\n The number of returned chunks is controlled by `n_ranked_doc_chunks` in opt. The\n chunk selection is determined by `doc_chunks_ranker` in the opt.\n \"\"\"\n if not doc_text:\n # When there is no search query for the context\n return [(\"\", 0)]\n tokens = self.text2tokens(doc_text)\n doc_chunks = [\n self.tokens2text(tokens[i : i + self.len_chunk])\n for i in range(0, len(tokens), self.len_chunk)\n ]\n return self.chunk_reranker.get_top_chunks(query, doc_chunks)\n\n\nclass SearchQuerySearchEngineRetriever(SearchQueryRetriever):\n \"\"\"\n A retriever that uses a search engine server for retrieving documents.\n\n It instantiates a `SearchEngineRetriever` object that in turns send search queries\n to an external server for retrieving documents.\n \"\"\"\n\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared: TShared):\n super().__init__(opt, dictionary, shared)\n if not shared:\n self.search_client = self.initiate_retriever_api(opt)\n else:\n self.search_client = shared['search_client']\n\n def share(self) -> TShared:\n shared = super().share()\n shared['search_client'] = self.search_client\n return shared\n\n def initiate_retriever_api(self, opt) -> SearchEngineRetriever:\n logging.info('Creating the search engine retriever.')\n return SearchEngineRetriever(opt)\n\n def _empty_docs(self, num: int):\n \"\"\"\n Generates the requested number of empty documents.\n \"\"\"\n return [BLANK_SEARCH_DOC for _ in range(num)]\n\n def rank_score(self, rank_id: int):\n \"\"\"\n Scores the chunks of the retrieved document based on their rank.\n\n Note that this is the score for the retrieved document and applies to all its\n chunks.\n \"\"\"\n return 1 / (1 + rank_id)\n\n def _display_urls(self, search_results):\n \"\"\"\n Generates a string that lists retrieved URLs (document IDs).\n \"\"\"\n return '\\n'.join([d['url'] for d in search_results if d['url']])\n\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Retrieves relevant documents for the query (the conversation context).\n\n This method conducts three main steps that are flagged in the main code as well.\n step 1: generate search queries for the conversation context batch. This\n step uses the query generator model (self.query_generator). step 2: use the\n search client to retrieve documents. This step uses retrieval API agent\n (self.search_client) step 3: generate the list of Document objects from the\n retrieved content. Here if the documents too long, the code splits them and\n chooses a chunk based on the selected `doc_chunks_ranker` in the opt.\n \"\"\"\n # step 1\n search_queries = self.generate_search_query(query)\n\n # step 2\n search_results_batach = self.search_client.retrieve(search_queries, self.n_docs)\n\n # step 3\n top_docs = []\n top_doc_scores = []\n for sq, search_results in zip(search_queries, search_results_batach):\n if not search_results:\n search_results = self._empty_docs(self.n_docs)\n elif len(search_results) < self.n_docs:\n remain_docs = self.n_docs - len(search_results)\n search_results.extend(self._empty_docs(remain_docs))\n docs_i = []\n scors_i = []\n # Change this debug later\n logging.debug(f'URLS:\\n{self._display_urls(search_results)}')\n for i, doc in enumerate(search_results):\n url = doc['url']\n title = doc['title']\n dcontent = doc['content']\n assert type(dcontent) in (\n str,\n list,\n ), f'Unrecognized retrieved doc: {dcontent}'\n full_text = (\n dcontent if isinstance(dcontent, str) else '\\n'.join(doc['content'])\n )\n doc_chunks = [dc[0] for dc in self.pick_chunk(sq, full_text)]\n for splt_id, splt_content in enumerate(doc_chunks):\n docs_i.append(\n Document(\n docid=url, text=splt_content, title=f'{title}_{splt_id}'\n )\n )\n scors_i.append(self.rank_score(i))\n top_docs.append(docs_i)\n top_doc_scores.append(scors_i)\n self.top_docs = top_docs\n return top_docs, torch.Tensor(top_doc_scores).to(query.device)\n\n\nclass SearchQueryFAISSIndexRetriever(SearchQueryRetriever, DPRRetriever):\n def __init__(self, opt: Opt, dictionary: DictionaryAgent, shared):\n SearchQueryRetriever.__init__(self, opt, dictionary, shared=shared)\n self.load_index(opt, shared)\n\n def share(self) -> TShared:\n shared = SearchQueryRetriever.share(self)\n shared.update(DPRRetriever.share(self))\n return shared\n\n def retrieve_and_score(\n self, query: torch.LongTensor\n ) -> Tuple[List[List[Document]], torch.Tensor]:\n \"\"\"\n Retrieves from the FAISS index using a search query.\n\n This methods relies on the `retrieve_and_score` method in `RagRetriever`\n ancestor class. It receive the query (conversation context) and generatess the\n search term queries based on them. Then uses those search quries (instead of the\n the query text itself) to retrieve from the FAISS index.\n \"\"\"\n\n search_queries = self.generate_search_query(query)\n tokenized_search_queries, _ = padded_tensor(\n [self._tokenizer.encode(sq) for sq in search_queries]\n )\n top_docs, top_doc_scores = DPRRetriever.retrieve_and_score(\n self, tokenized_search_queries.to(query.device)\n )\n for query_id in range(len(top_docs)):\n if search_queries[query_id] == NO_SEARCH_QUERY:\n top_docs[query_id] = [BLANK_DOC for _ in range(self.n_docs)]\n return top_docs, top_doc_scores\n\n\nclass DocumentChunkRanker:\n \"\"\"\n Base class for controlling splitting long documents and selecting relevant chunks.\n \"\"\"\n\n def __init__(self, n_retrieved_chunks):\n self.n_ret_chunks = n_retrieved_chunks\n\n @abstractmethod\n def get_top_chunks(self, query, doc_chunks):\n \"\"\"\n Ranks documents (chunk) based on their relevance to `query`\n \"\"\"\n\n\nclass HeadChunkRanker(DocumentChunkRanker):\n \"\"\"\n Returns the head chunks only.\n \"\"\"\n\n def get_top_chunks(self, query, doc_chunks):\n \"\"\"\n Return chunks in doc-present order.\n \"\"\"\n return [(c,) for c in doc_chunks[: self.n_ret_chunks]]\n\n\nclass TfidfChunkRanker(DocumentChunkRanker):\n \"\"\"\n Uses TF-IDF to compare chunks to the original search query.\n \"\"\"\n\n def __init__(self, n_retrieved_chunks):\n super().__init__(n_retrieved_chunks)\n self._vectorizer = TfidfVectorizer()\n\n def get_top_chunks(self, query, doc_chunks):\n vectorized_corpus = self._vectorizer.fit_transform(doc_chunks + [query])\n docs_vec = vectorized_corpus[:-1, :]\n q_vec = vectorized_corpus[-1, :]\n scores = np.hstack((q_vec * docs_vec.transpose()).toarray())\n top_chunk_ids = np.argsort(-scores)[: self.n_ret_chunks]\n return [(doc_chunks[i], scores[i]) for i in top_chunk_ids]\n\n\ndef retriever_factory(\n opt: Opt, dictionary: DictionaryAgent, shared=None\n) -> Optional[RagRetriever]:\n \"\"\"\n Build retriever.\n\n :param opt:\n ParlAI Opt\n :param dictionary:\n dictionary agent\n :param shared:\n shared objects.\n\n :return retriever:\n return a retriever for RAG.\n \"\"\"\n if opt.get('converting'):\n return None\n # only build retriever when not converting a BART model\n retriever = RetrieverType(opt['rag_retriever_type'])\n if retriever is RetrieverType.DPR:\n return DPRRetriever(opt, dictionary, shared=shared)\n elif retriever is RetrieverType.TFIDF:\n return TFIDFRetriever(opt, dictionary, shared=shared)\n elif retriever is RetrieverType.DPR_THEN_POLY:\n return DPRThenPolyRetriever(opt, dictionary, shared=shared)\n elif retriever is RetrieverType.POLY_FAISS:\n return PolyFaissRetriever(opt, dictionary, shared=shared)\n elif retriever is RetrieverType.SEARCH_ENGINE:\n return SearchQuerySearchEngineRetriever(opt, dictionary, shared=shared)\n elif retriever is RetrieverType.SEARCH_TERM_FAISS:\n return SearchQueryFAISSIndexRetriever(opt, dictionary, shared=shared)\n"
] |
[
[
"torch.Tensor",
"torch.isnan",
"torch.tensor",
"numpy.append",
"torch.mul",
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.stack",
"numpy.argsort",
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] |
awesome-archive/character-based-cnn
|
[
"6a8910a49ce5d43b639d1da0320df8cfa88cb75b"
] |
[
"src/utils.py"
] |
[
"import json\r\nimport re\r\nimport numpy as np\r\nfrom sklearn import metrics\r\n\r\n# text-preprocessing\r\n\r\n\r\ndef lower(text):\r\n return text.lower()\r\n\r\n\r\ndef remove_hashtags(text):\r\n clean_text = re.sub(r'#[A-Za-z0-9_]+', \"\", text)\r\n return clean_text\r\n\r\n\r\ndef remove_user_mentions(text):\r\n clean_text = re.sub(r'@[A-Za-z0-9_]+', \"\", text)\r\n return clean_text\r\n\r\n\r\ndef remove_urls(text):\r\n clean_text = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)\r\n return clean_text\r\n\r\n\r\npreprocessing_setps = {\r\n 'remove_hashtags': remove_hashtags,\r\n 'remove_urls': remove_urls,\r\n 'remove_user_mentions': remove_user_mentions,\r\n 'lower': lower\r\n}\r\n\r\n\r\ndef process_text(steps, text):\r\n if steps is not None:\r\n for step in steps:\r\n text = preprocessing_setps[step](text)\r\n\r\n processed_text = \"\"\r\n for tx in text:\r\n processed_text += tx + \" \"\r\n return processed_text\r\n\r\n# metrics // model evaluations\r\n\r\n\r\ndef get_evaluation(y_true, y_prob, list_metrics):\r\n y_pred = np.argmax(y_prob, -1)\r\n output = {}\r\n if 'accuracy' in list_metrics:\r\n output['accuracy'] = metrics.accuracy_score(y_true, y_pred)\r\n if 'f1' in list_metrics:\r\n output['f1'] = metrics.f1_score(y_true, y_pred)\r\n\r\n return output\r\n\r\n\r\n# preprocess input for prediction\r\n\r\ndef preprocess_input(args):\r\n raw_text = args.text\r\n steps = args.steps\r\n for step in steps:\r\n raw_text = preprocessing_setps[step](raw_text)\r\n\r\n number_of_characters = args.number_of_characters + len(args.extra_characters)\r\n identity_mat = np.identity(number_of_characters)\r\n vocabulary = list(args.alphabet) + list(args.extra_characters)\r\n max_length = args.max_length\r\n\r\n processed_output = np.array([identity_mat[vocabulary.index(i)] for i in list(\r\n raw_text) if i in vocabulary], dtype=np.float32)\r\n if len(processed_output) > max_length:\r\n processed_output = processed_output[:max_length]\r\n elif 0 < len(processed_output) < max_length:\r\n processed_output = np.concatenate((processed_output, np.zeros(\r\n (max_length - len(processed_output), number_of_characters), dtype=np.float32)))\r\n elif len(processed_output) == 0:\r\n processed_output = np.zeros(\r\n (max_length, number_of_characters), dtype=np.float32)\r\n return processed_output\r\n"
] |
[
[
"numpy.argmax",
"numpy.identity",
"sklearn.metrics.f1_score",
"numpy.zeros",
"sklearn.metrics.accuracy_score"
]
] |
SithisSir/sr
|
[
"b87413f943b631511d22fca0796749e090a1f2e9"
] |
[
"models/model_espcn.py"
] |
[
"import tensorflow as tf\nfrom .model import Model\n\n\nclass ESPCN(Model):\n def __init__(self, args):\n super().__init__(args)\n self._prediction_offset = self._scale_factor * 4\n\n def get_data(self):\n data_batch, initializer = self.dataset.get_data()\n\n lr_batch = tf.cast(data_batch['lr1'], tf.float32) / 255.0\n hr_batch = tf.cast(data_batch['hr'], tf.float32) / 255.0\n\n return [lr_batch, hr_batch], initializer\n\n def get_placeholder(self):\n input_ph = tf.placeholder(tf.float32, shape=[1, None, None, 1], name=\"x\")\n\n return [input_ph]\n\n def load_model(self, data_batch):\n lr_batch = data_batch[0]\n\n with tf.variable_scope('espcn'):\n if not self._using_dataset:\n lr_batch = tf.pad(lr_batch, [[0, 0], [4, 4], [4, 4], [0, 0]], 'SYMMETRIC')\n net = tf.layers.conv2d(lr_batch, 64, 5, activation=tf.nn.tanh, padding='valid', name='conv1',\n kernel_initializer=tf.keras.initializers.he_normal())\n net = tf.layers.conv2d(net, 32, 3, activation=tf.nn.tanh, padding='valid', name='conv2',\n kernel_initializer=tf.keras.initializers.he_normal())\n net = tf.layers.conv2d(net, self._scale_factor ** 2, 3, activation=tf.nn.sigmoid, padding='valid',\n name='conv3', kernel_initializer=tf.keras.initializers.he_normal())\n predicted_batch = tf.depth_to_space(net, self._scale_factor, name='prediction')\n\n espcn_variables = tf.trainable_variables(scope='espcn')\n for variable in espcn_variables:\n if 'conv3' in variable.name:\n self.lr_multipliers[variable.name] = 0.1\n else:\n self.lr_multipliers[variable.name] = 1.0\n\n if self._using_dataset:\n tf.summary.image('Low_resolution', data_batch[0][:, 4:-4, 4:-4], max_outputs=self._save_num)\n tf.summary.image('High_resolution',\n data_batch[1][:, self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n max_outputs=self._save_num)\n tf.summary.image('High_resolution_prediction', predicted_batch, max_outputs=self._save_num)\n\n return predicted_batch\n\n def get_loss(self, data_batch, predicted_batch):\n loss = tf.losses.mean_squared_error(\n data_batch[1][:,\n self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n predicted_batch)\n\n tf.summary.scalar('MSE', loss)\n tf.summary.scalar('PSNR', tf.reduce_mean(tf.image.psnr(\n data_batch[1][:,\n self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n predicted_batch,\n max_val=1.0)))\n tf.summary.scalar('SSIM', tf.reduce_mean(tf.image.ssim(\n data_batch[1][:,\n self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n predicted_batch,\n max_val=1.0)))\n\n return loss\n\n def calculate_metrics(self, data_batch, predicted_batch):\n diff = data_batch[1][:, self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset] - predicted_batch\n diff_sqr = tf.square(diff)\n\n mse = ('MSE', tf.reduce_mean(diff_sqr, axis=[1, 2, 3]))\n psnr = ('PSNR', tf.squeeze(tf.image.psnr(\n data_batch[1][:,\n self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n predicted_batch,\n max_val=1.0)))\n ssim = ('SSIM', tf.squeeze(tf.image.ssim(\n data_batch[1][:,\n self._prediction_offset:-self._prediction_offset,\n self._prediction_offset:-self._prediction_offset],\n predicted_batch,\n max_val=1.0)))\n\n return [mse, psnr, ssim]\n"
] |
[
[
"tensorflow.losses.mean_squared_error",
"tensorflow.depth_to_space",
"tensorflow.image.psnr",
"tensorflow.reduce_mean",
"tensorflow.summary.image",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.variable_scope",
"tensorflow.square",
"tensorflow.pad",
"tensorflow.trainable_variables",
"tensorflow.image.ssim",
"tensorflow.keras.initializers.he_normal",
"tensorflow.summary.scalar"
]
] |
deven96/python
|
[
"46be8622fe58f004bdbd636a08a8904ef4134bcd"
] |
[
"bigml/laminar/numpy_ops.py"
] |
[
"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n#\n# Copyright 2017-2019 BigML\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Activation functions and helpers in numpy\n\nHere are most of the vector operations and helper functions we use in\nnumpy.\n\"\"\"\n\nimport numpy as np\n\nfrom scipy.special import expit\n\nfrom bigml.laminar.constants import LARGE_EXP, MATRIX_PARAMS, \\\n VEC_PARAMS\n\n\ndef to_numpy_array(xs):\n if isinstance(xs, np.ndarray):\n return np.copy(xs)\n else:\n return np.array(xs, dtype=np.float32)\n\n\ndef softplus(xs):\n x_cpy = to_numpy_array(xs)\n x_cpy[x_cpy < LARGE_EXP] = np.log(np.exp(x_cpy[x_cpy < LARGE_EXP]) + 1)\n return x_cpy\n\n\ndef relu(xs):\n x_cpy = to_numpy_array(xs)\n return x_cpy * (x_cpy > 0)\n\n\ndef softmax(xs):\n x_cpy = to_numpy_array(xs)\n\n shape0 = 1\n if len(x_cpy.shape) > 1:\n shape0 = x_cpy.shape[0]\n\n x_cpy = x_cpy.reshape(shape0, -1)\n\n maxes = np.amax(x_cpy, axis=1)\n maxes = maxes.reshape(maxes.shape[0], 1)\n\n exps = np.exp(x_cpy - maxes)\n dist = exps / np.sum(exps, axis=1).reshape((-1, 1))\n\n return dist\n\n\nACTIVATORS = {\n 'tanh': np.tanh,\n 'sigmoid': expit,\n 'softplus': softplus,\n 'relu': relu,\n 'softmax': softmax,\n 'identity': lambda x: x\n}\n\n\ndef plus(mat, vec):\n return mat + vec\n\n\ndef dot(mat1, mat2):\n output = []\n for row1 in mat1:\n new_row = []\n for row2 in mat2:\n new_row.append(np.dot(row1, row2).tolist())\n output.append(new_row)\n return output\n\ndef batch_norm(X, mean, stdev, shift, scale):\n return scale * (X - mean) / stdev + shift\n\n\ndef init_layer(layer, ftype=np.float64):\n out_layer = {}\n for key in layer:\n if layer[key] is not None:\n if key in MATRIX_PARAMS:\n out_layer[key] = np.array(layer[key], dtype=ftype)\n elif key in VEC_PARAMS:\n out_layer[key] = np.array(layer[key], dtype=ftype)\n else:\n out_layer[key] = layer[key]\n else:\n out_layer[key] = layer[key]\n\n return out_layer\n\n\ndef init_layers(layers):\n return [init_layer(layer) for layer in layers]\n\n\ndef destandardize(vec, v_mean, v_stdev):\n return vec * v_stdev + v_mean\n\n\ndef to_width(mat, width):\n if width > len(mat[0]):\n ntiles = int(np.ceil(width / float(len(mat[0]))))\n else:\n ntiles = 1\n\n return np.tile(mat, (1, ntiles))[:, :width]\n\n\ndef add_residuals(residuals, values):\n to_add = to_width(values, len(residuals[0]))\n return to_add + residuals\n\n\ndef sum_and_normalize(youts, is_regression):\n ysums = sum(youts)\n\n if is_regression:\n return ysums / len(youts)\n else:\n return ysums / np.sum(ysums, axis=1).reshape(-1, 1)\n\n\ndef propagate(x_in, layers):\n last_X = identities = to_numpy_array(x_in)\n for layer in layers:\n w = layer['weights']\n m = layer['mean']\n s = layer['stdev']\n b = layer['offset']\n g = layer['scale']\n\n afn = layer['activation_function']\n\n X_dot_w = dot(last_X, w)\n if m is not None and s is not None:\n next_in = batch_norm(X_dot_w, m, s, b, g)\n else:\n next_in = plus(X_dot_w, b)\n\n if layer['residuals']:\n next_in = add_residuals(next_in, identities)\n last_X = ACTIVATORS[afn](next_in)\n identities = last_X\n else:\n last_X = ACTIVATORS[afn](next_in)\n\n return last_X\n"
] |
[
[
"numpy.dot",
"numpy.amax",
"numpy.tile",
"numpy.copy",
"numpy.array",
"numpy.exp",
"numpy.sum"
]
] |
FindDefinition/cumm
|
[
"3d58e85b660afa05c20514afe65b8aa3a4995953"
] |
[
"cumm/gemm/turing_my_iters.py"
] |
[
"# Copyright 2021 Yan Yan\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\nfrom typing import List\n\nimport numpy as np\nimport pccm\n\nfrom cumm import dtypes\nfrom cumm import tensorview as tv\nfrom cumm.common import GemmBasic, GemmBasicKernel, TensorView\nfrom cumm.core_cc.csrc.arrayref import ArrayPtr\nfrom cumm.cudasim import checkers\nfrom cumm.gemm import arch, bases, constants, layout_tensorop, thread_map\nfrom cumm.gemm.core import MetaArray, metaseq, seq\nfrom cumm.gemm.thread_map import PitchLinearWarpRaked\n\n# def seq(*vals) -> np.ndarray:\n# return np.array([*vals], dtype=np.int64)\n\n\ndef div_up(a, b):\n return (a + b - 1) // b\n\n\ndef count_set_bits(n):\n count = 0\n while (n):\n n &= (n - 1)\n count += 1\n return count\n\n\ndef swizzle_increment(index: int, width: int):\n assert count_set_bits(width) == 1, \"width must be power of 2\"\n if index & 0b1 == 0:\n # bit 0 advance\n return 1 * width\n elif index == 0b1:\n # bit 1 advance\n return 0b11 * width\n elif index == 0b11:\n # bit 2 advance\n return 0b111 * width\n elif index == 0b111:\n # bit 3 advance\n return 0b1111 * width\n else:\n raise NotImplementedError\n\n\ndef swizzle_increment_code(code: pccm.FunctionCode, offset_var: str,\n index_var: str, width: int):\n assert count_set_bits(width) == 1, \"width must be power of 2\"\n with code.if_(f\"(({index_var}) & 0b1) == 0\"):\n code.raw(f\"{offset_var} ^= 1 * {width};\")\n with code.else_if_(f\"({index_var}) == 0b1\"):\n code.raw(f\"{offset_var} ^= 0b11 * {width};\")\n with code.else_if_(f\"({index_var}) == 0b11\"):\n code.raw(f\"{offset_var} ^= 0b111 * {width};\")\n with code.else_if_(f\"({index_var}) == 0b111\"):\n code.raw(f\"{offset_var} ^= 0b1111 * {width};\")\n\n\nclass MyTensorOpLayout(pccm.ParameterizedClass):\n def __init__(self, dtype: dtypes.DType, warp_shape: MetaArray[int],\n base_stride: int, stage_axis: int,\n stage_count: MetaArray[int], is_permute_m: bool):\n \"\"\"sw subsw\n Swizzle: multi-level switch system.\n 2: 01 -> 10\n 4: 01 -> 10\n 8: 01 -> 10\n stride = base_stride * interleave * stage_count[1]\n \"\"\"\n\n super().__init__()\n self.dtype = dtype\n self.is_permute_m = is_permute_m\n self.is_spec_32 = dtype.bitsize() == 32 and is_permute_m\n self.warp_shape = warp_shape\n interleave = 1\n smem_bank_size = 128\n self.base_stride = base_stride\n self.stage_axis = stage_axis\n self.stage_count = stage_count\n\n smem_access_size_bits = 128\n smem_access_size = 128 // 8\n store_access_size = dtype.bitsize()\n warp_access_size = dtype.bitsize()\n self.element_per_acc = smem_access_size // dtype.itemsize()\n store_num_access_bf = smem_bank_size // smem_access_size\n warp_num_access_bf = smem_bank_size // smem_access_size\n assert store_num_access_bf == 8\n warp_bank_free_length = 8\n if not self.is_spec_32:\n warp_bfa_access_shape = metaseq(warp_num_access_bf, 1)\n if warp_shape[1] < store_num_access_bf:\n # if a QP access a shape with stride > 1\n # we must use interleaved layout to ensure\n # bank free store\n # interleave: every kInterleave lines put in contiguous line in smem\n # interleave == 1, warp_bfa_access_shape=[8, 1]:\n # 0\n # 1\n # 2\n # 3\n # 4\n # 5\n # 6\n # 7\n # interleave == 2 (input stride=0-7, warp_bfa_access_shape=[4, 2]):\n # 0 1\n # 2 3\n # 4 5\n # 6 7\n # interleave == 4 (input stride=0-7, warp_bfa_access_shape=[2, 4]):\n # 0 1 2 3\n # 4 5 6 7\n # interleave == 8 (input stride=0-7, warp_bfa_access_shape=[1, 8]):\n # 01234567\n\n interleave = store_num_access_bf // warp_shape[1]\n warp_bfa_access_shape = metaseq(\n warp_num_access_bf // interleave, interleave)\n\n self.interleave = interleave\n self.warp_bfa_access_shape = warp_bfa_access_shape\n # num pointers:\n # when a swizzle part can't be handled in ONE iteration for ONE warp,\n # we need multiple pointers to handle different part of a swizzle part.\n\n # 1. SmemStoreIter\n # during store, if warp shape is [4, 8] and swizzle part is [8, 8], then we\n # need multiple pointers.\n\n # 2. WarpReadIter\n # for PermuteK iters (Crosswise in cutlass), the permute is done in k axis,\n # the min stride of tensor op is 8, which is the maximum size of swizzle part stride\n # so PermuteK iters don't need multiple pointers. (LDSM count is always 1 in k axis)\n #\n # for PermuteM iters (Congruous in cutlass), the permute is done in m|n axis,\n # ldm shape contig may smaller than swizzle part contig.\n # so one swizzle part may contains multiple iterations.\n\n # for PermuteK iters, if the tensor op stride is smaller than maximum swizzle part stride,\n # we still need multiple pointers.\n self.num_smem_pointers = max(\n warp_bfa_access_shape[0] // warp_shape[0], 1)\n\n self.subsw_length = 4\n if interleave != 1:\n self.subsw_length = min(warp_bfa_access_shape[0], 4)\n self.subsw_shape = metaseq(self.subsw_length, self.subsw_length)\n\n self.sw_shape = metaseq(warp_bfa_access_shape[0],\n store_num_access_bf)\n self.tile_shape = self.sw_shape\n self.part_shape = self.subsw_shape\n self.subsw_count = self.sw_shape // self.subsw_shape\n\n self.num_swizzle_part = warp_bfa_access_shape[\n 0] // self.subsw_length\n else:\n self.sw_shape = metaseq(4, 8)\n self.subsw_shape = metaseq(4, 8)\n self.tile_shape = self.sw_shape\n self.part_shape = self.subsw_shape\n self.interleave = 1\n self.num_smem_pointers = 1\n\n self.static_stride = base_stride * self.interleave * stage_count[1]\n self.static_stride_vec = self.static_stride // self.element_per_acc\n\n self.index_t = str(dtypes.int32)\n self.long_index_t = str(dtypes.int64)\n # cudasim mmebers\n self.stride = 0\n\n def __repr__(self):\n return f\"TensorOpLayout[sw={self.sw_shape}|il={self.interleave}]\"\n\n @pccm.cuda.constructor(host=True,\n device=True,\n forceinline=True,\n constexpr=True)\n def ctor(self):\n code = pccm.code()\n return code\n\n def python_ctor(self, stride):\n new_obj = MyTensorOpLayout(self.dtype, self.warp_shape,\n self.base_stride, self.stage_axis,\n self.stage_count, self.is_permute_m)\n new_obj.stride = stride\n return new_obj\n\n def from_shape_python(self, shape):\n l = MyTensorOpLayout(self.dtype, self.warp_shape, self.base_stride,\n self.stage_axis, self.stage_count,\n self.is_permute_m)\n l.stride = shape[0]\n return l\n\n @pccm.cuda.static_function(host=True,\n device=True,\n forceinline=True,\n constexpr=True)\n def from_shape(self):\n code = pccm.FunctionCode(f\"return {self.class_name}();\")\n code.arg(\"shape\", \"const tv::array<int, 2> &\")\n code.ret(self.class_name)\n return code\n\n @pccm.cuda.member_function(name=\"operator()\",\n host=True,\n device=True,\n forceinline=True,\n constexpr=True,\n const=True)\n def call_operator(self):\n code = pccm.code()\n shape_before_interleave = self.sw_shape[1] // self.interleave\n assert self.subsw_count[0] == 1 or self.subsw_count[0] == 2\n code.raw(f\"\"\"\n int vc = ec / {self.element_per_acc};\n int interleaved_s = s / {self.interleave};\n int idx_in_interleave_s = s % {self.interleave};\n // shape_before_interleave = {self.sw_shape[1]} // {self.interleave}\n // int sw_idx_s = interleaved_s / {self.sw_shape[0]};\n int sw_idx_c = vc / {shape_before_interleave};\n int idx_in_sw_c = vc % {shape_before_interleave} + idx_in_interleave_s * {shape_before_interleave};\n int idx_in_sw_s = interleaved_s % {self.sw_shape[0]};\n\n int subsw_idx_s = idx_in_sw_s / {self.subsw_shape[0]};\n int subsw_idx_c = idx_in_sw_c / {self.subsw_shape[1]};\n int idx_in_subsw_s = idx_in_sw_s % {self.subsw_shape[0]};\n int idx_in_subsw_c = idx_in_sw_c % {self.subsw_shape[1]};\n \n // if subsw_idx_s == 0, permuted_subsw_idx_c = 0/1 = subsw_idx_c\n // else permuted_subsw_idx_c = 1/0\n int permuted_subsw_idx_c = subsw_idx_c;\n if ({self.subsw_count[0]} > 1){{\n permuted_subsw_idx_c = subsw_idx_c ^ (subsw_idx_s % 2);\n }}\n int premuted_idx_in_subsw_c = idx_in_subsw_c ^ (idx_in_subsw_s % {self.subsw_length});\n int final_c = sw_idx_c * {self.sw_shape[1]} + permuted_subsw_idx_c * {self.subsw_shape[1]} + premuted_idx_in_subsw_c;\n // if ec % epa != 0\n int final_ec = final_c * {self.element_per_acc} + ec % {self.element_per_acc};\n int final_s = interleaved_s * {self.static_stride};\n return final_ec + final_s;\n \"\"\")\n code.arg(\"s,ec\", self.index_t)\n return code.ret(self.long_index_t)\n\n def __call__(self, s: int, ec: int):\n if self.is_spec_32:\n tc = ec // 32\n ts = s // 4\n\n c = (ec % 32) // self.element_per_acc\n s = s % 4\n offset = ((c ^ (2 * s)) * self.element_per_acc +\n s * self.static_stride + tc * 32 +\n ts * self.static_stride * 4 + ec % 4)\n return offset\n\n vc = ec // self.element_per_acc\n interleaved_s = s // self.interleave\n idx_in_interleave_s = s % self.interleave\n # shape_before_interleave = self.warp_shape[1]\n shape_before_interleave = self.sw_shape[1] // self.interleave\n sw_idx_s = interleaved_s // self.sw_shape[0]\n sw_idx_c = vc // shape_before_interleave\n idx_in_sw_c = vc % shape_before_interleave + idx_in_interleave_s * shape_before_interleave\n idx_in_sw_s = interleaved_s % self.sw_shape[0]\n subsw_idx_s = idx_in_sw_s // self.subsw_shape[0]\n subsw_idx_c = idx_in_sw_c // self.subsw_shape[1]\n idx_in_subsw_s = idx_in_sw_s % self.subsw_shape[0]\n idx_in_subsw_c = idx_in_sw_c % self.subsw_shape[1]\n permuted_subsw_idx_c = subsw_idx_c\n # if subsw_idx_s == 0, permuted_subsw_idx_c = 0/1 = subsw_idx_c\n # else permuted_subsw_idx_c = 1/0\n if self.subsw_count[0] == 2:\n permuted_subsw_idx_c = subsw_idx_c ^ (subsw_idx_s % 2)\n elif self.subsw_count[0] != 1:\n raise NotImplementedError\n if self.subsw_length == 4:\n premuted_idx_in_subsw_c = idx_in_subsw_c ^ (idx_in_subsw_s % 4)\n elif self.subsw_length == 2:\n premuted_idx_in_subsw_c = idx_in_subsw_c ^ (idx_in_subsw_s % 2)\n else:\n raise NotImplementedError\n # print(\"self.subsw_shape\", self.subsw_shape, self.sw_shape, self.interleave, self.subsw_count, self.element_per_acc)\n final_c = sw_idx_c * self.sw_shape[\n 1] + permuted_subsw_idx_c * self.subsw_shape[1]\n final_c += premuted_idx_in_subsw_c\n # if ec % epa != 0\n final_ec = final_c * self.element_per_acc + ec % self.element_per_acc\n final_s = interleaved_s * self.static_stride\n return final_ec + final_s\n\n def get_ldm_initial_offset_ref(self,\n lane_idx: int,\n ldm_count: MetaArray[int],\n transpose: bool = False,\n permute_m_pointer_idx: int = 0):\n \"\"\" transpose (not operend A)\n if transpose:\n Q0 Q1\n Q2 Q3\n else:\n Q0 Q2\n Q1 Q3\n \"\"\"\n if ldm_count[0] == 1:\n # Q0 Q1 Q2 Q3\n # stride: 01234567 01234567 ....\n # contig: 00000000 11111111 22222222 ....\n stride = lane_idx & 0b111\n contig_vec = lane_idx >> 3\n elif ldm_count[1] == 1:\n # Q0\n # Q1\n # Q2\n # Q3\n # stride: lane_id\n # contig: 0\n stride = lane_idx\n contig_vec = 0\n elif ldm_count == (2, 2):\n if transpose: # operand B\n # Q0 Q1\n # Q2 Q3\n # stride: 01234567 01234567 89ABCDEF 89ABCDEF\n # contig: 00000000 11111111 00000000 11111111\n stride = (lane_idx & 0b111) + ((lane_idx >> 4) << 3)\n contig_vec = (lane_idx & 0b1111) >> 3\n else: # operand A\n # Q0 Q2\n # Q1 Q3\n # stride: 01234567 89ABCDEF 01234567 89ABCDEF\n # contig: 00000000 00000000 11111111 11111111\n stride = lane_idx & 0b1111\n contig_vec = lane_idx >> 4\n else:\n raise NotImplementedError\n return self(\n stride, contig_vec * self.element_per_acc +\n permute_m_pointer_idx * ldm_count[1] * self.element_per_acc)\n\n def get_ldm_initial_index_fast(self,\n lane_idx: int,\n ldm_count: MetaArray[int],\n transpose: bool = False,\n permute_m_pointer_idx: int = 0):\n \"\"\" transpose (not operend A)\n if transpose:\n Q0 Q1\n Q2 Q3\n else:\n Q0 Q2\n Q1 Q3\n\n common bit seq rules:\n add is slower than xor\n x & 0b100 == 0000 1111 0000 1111\n x & 0b11 == 0123 0123 0123 0123\n x + 8 == x ^ 0b1000 when x < 8\n 0000 1111 0000 1111 == (x & 0b111) >> 2 == (x & 0b100) >> 2\n\n for PermuteM iters, permute_m_pointer_idx may larger than 0, and \n interleave must be 1 (TODO actually interleave can > 1).\n \"\"\"\n if permute_m_pointer_idx > 0:\n assert self.interleave == 1\n if self.interleave == 4:\n # 0 1 2 3 0 1 2 3\n # 4 5 6 7 4 5 6 7\n if ldm_count[1] == 1:\n # Q0\n # Q1\n # Q2\n # Q3\n # stride: 0000 1111 2222 3333 ....\n # contig_vec: 0246 1357 0246 1357 ... = 0246[...] ^ (stride & 1)\n # 0246[...] = (lane_idx & 3) << 1)\n stride = lane_idx >> 2\n contig_vec = ((lane_idx & 3) << 1) ^ (stride & 1)\n elif ldm_count == (2, 2):\n if transpose: # operand B\n # Q0 Q1\n # Q2 Q3\n # stride: 00001111 00001111 22223333 22223333 = 00001111[...] + 0[16] 1[16]\n # = (lane & 0b111) >> 2\n # contig: 02461357 13570246 02461357 13570246\n # = 0246... + 0000 1111 1111 0000\n # = ((lane_idx & 3) << 1) + (stride & 1) ^ ((lane_idx & 8) >> 3))\n # 0000 1111 0000 1111 ^ 0000 0000 1111 1111 = 0000 1111 1111 0000\n # = 02461357[] + 00000000 88888888 ...\n # also 0246.... ^ 0000 1111 8888 9999 0000 1111 8888 9999\n stride = ((lane_idx & 0b111) >> 2) + (lane_idx >> 4 << 1)\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ (\n (lane_idx & 0b1000) >> 3)\n else: # operand A\n # Q0 Q2\n # Q1 Q3\n # stride: 0000 1111 2222 3333 0000 1111 2222 3333\n # contig: 02461357 02461357 13570246 13570246, 0101 1010\n # also 0246.... ^ 0000 1111 0000 1111 8888 9999 8888 9999\n\n stride = (lane_idx & 0b1111) >> 2\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ (\n (lane_idx & 0b10000) >> 4)\n else:\n # Q0 Q1 Q2 Q3\n # stride: 0000 1111 0000 1111 ...\n # contig: 02461357 13570246 +8 +8\n stride = (lane_idx & 0b111) >> 2\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ (\n (lane_idx & 0b1000) >> 3) + (lane_idx >> 4 << 3)\n elif self.interleave == 2:\n # 0 1\n # 2 3\n # 4 5\n # 6 7\n # 0 1\n # 2 3\n # 4 5\n # 6 7\n if ldm_count[1] == 1:\n # Q0\n # Q1\n # Q2\n # Q3\n # stride: 0011 2233 4455 6677 .... = lane_idx >> 1\n # contig_vec: 04152637 ... = 00112233 + 04040404 = (lane_idx >> 1) & 0b11 + (lane_idx & 1) << 2\n # 0246[...] = (lane_idx & 3) << 1)\n stride = lane_idx >> 1\n contig_vec = ((lane_idx >> 1) & 0b11) + ((lane_idx & 1) << 2)\n elif ldm_count == (2, 2):\n if transpose: # operand B\n # Q0 Q1\n # Q2 Q3\n # stride: 00112233 00112233 44556677 44556677 = ((lane_idx >> 1) & 0b11) + (lane_idx >> 4 << 2)\n # contig: 04152637 15043726 04152637 15043726 = 04152637[] ^ 00000000 11111111 00000000 11111111 ((lane_idx >> 3) & 1)\n _00112233 = ((lane_idx >> 1) & 0b11)\n stride = _00112233 + (lane_idx >> 4 << 2)\n contig_vec = (_00112233 + ((lane_idx & 1) << 2)) ^ (\n (lane_idx >> 3) & 1)\n else: # operand A\n # Q0 Q2\n # Q1 Q3\n # stride: 00112233 44556677 00112233 44556677 = (lane_idx & 0b1111) >> 1\n # contig: 04152637 04152637 15043726 15043726\n # 0[8] 1[8] = lane_idx >> 4\n stride = (lane_idx & 0b1111) >> 1\n contig_vec = (((lane_idx >> 1) & 0b11) +\n ((lane_idx & 1) << 2)) ^ (lane_idx >> 4)\n else:\n # Q0 Q1 Q2 Q3\n # stride: 00112233 00112233 00112233 00112233\n # contig: 04152637 15043726 26370415 37261504 = 04152637 ^ 00000000 11111111 22222222 33333333\n stride = (lane_idx & 0b111) >> 1\n contig_vec = (((lane_idx >> 1) & 0b11) +\n ((lane_idx & 1) << 2)) ^ (lane_idx >> 3)\n elif self.interleave == 1:\n # 0\n # 1\n # 2\n # 3\n # 4\n # 5\n # 6\n # 7\n if ldm_count[1] == 1:\n # Q0\n # Q1\n # Q2\n # Q3\n # stride: 01234567 89... = lane_idx & 0b111\n # contig_vec: 01234567 01... = stride\n # if permute_m_pointer_idx > 0, contig_vec = 01234567 ^ permute_m_pointer_idx\n # 0246[...] = (lane_idx & 3) << 1)\n stride = lane_idx\n contig_vec = (lane_idx & 0b111) ^ permute_m_pointer_idx\n assert permute_m_pointer_idx < 8\n elif ldm_count == (2, 2):\n if transpose: # operand B\n # Q0 Q1\n # Q2 Q3\n # stride: 01234567 01234567 89ABCDEF 89ABCDEF = lane_idx & 0b111 + lane_idx >> 4 << 3\n # contig: 01234567 10325476 01234567 10325476 = stride ^ (0[8] 1[8] 0[8] 1[8])\n # if permute_m_pointer_idx > 0, contig_vec = stride ^ (permute_m_pointer_idx * 2[8], permute_m_pointer_idx * 2 + 1[8])\n _01234567 = (lane_idx & 0b111)\n stride = _01234567 + (lane_idx >> 4 << 3)\n contig_vec = _01234567 ^ (((lane_idx >> 3) & 1) +\n (permute_m_pointer_idx << 1))\n else: # operand A\n # Q0 Q2\n # Q1 Q3\n # stride: 01234567 89ABCDEF 01234567 89ABCDEF = lane_idx & 0b1111\n # contig: 01234567 01234567 10325476 10325476 = _01234567 ^ (lane_idx >> 4)\n # 0[8] 1[8] = lane_idx >> 4\n _01234567 = (lane_idx & 0b111)\n stride = lane_idx & 0b1111\n contig_vec = _01234567 ^ ((lane_idx >> 4) +\n (permute_m_pointer_idx << 1))\n assert permute_m_pointer_idx < 4\n else:\n # Q0 Q1 Q2 Q3\n # stride: 01234567 01234567 01234567 01234567\n # contig: 01234567 10325476 23016745 32107654 = 01234567 ^ 00000000 11111111 22222222 33333333\n stride = lane_idx & 0b111\n contig_vec = stride ^ ((lane_idx >> 3) +\n (permute_m_pointer_idx << 2))\n assert permute_m_pointer_idx < 2\n else:\n raise NotImplementedError\n return stride, contig_vec\n\n def get_ldm_initial_offset_fast(self,\n lane_idx: int,\n ldm_count: MetaArray[int],\n transpose: bool = False,\n permute_m_pointer_idx: int = 0):\n stride, contig_vec = self.get_ldm_initial_index_fast(\n lane_idx, ldm_count, transpose, permute_m_pointer_idx)\n res = stride * self.static_stride + contig_vec * self.element_per_acc\n ref = self.get_ldm_initial_offset_ref(lane_idx, ldm_count, transpose,\n permute_m_pointer_idx)\n if res != ref:\n print(self.sw_shape, self.subsw_shape)\n print(\n f\"{lane_idx, ldm_count, transpose, permute_m_pointer_idx, self.interleave, self.is_spec_32}, {res, ref}\"\n )\n assert res == ref\n return res\n\n @pccm.cuda.static_function(host=True,\n device=True,\n forceinline=True,\n constexpr=True)\n def get_ldm_initial_offset(self):\n code = pccm.code()\n code.arg(\"lane_idx,permute_m_pointer_idx\", self.index_t)\n code.arg(\"transpose\", \"bool\")\n # is hard to get ldm count here even if it's a static constexpr variable,\n # so we use template instead.\n code.nontype_targ(\"LdmCountStride,LdmCountContig\", \"int\")\n code.raw(f\"\"\"\n int stride = -1;\n int contig_vec = -1;\n \"\"\")\n if self.interleave == 4:\n code.raw(f\"\"\"\n if (LdmCountContig == 1){{\n stride = lane_idx >> 2;\n contig_vec = ((lane_idx & 3) << 1) ^ (stride & 1);\n }} else if (LdmCountContig == 2 && LdmCountStride == 2){{\n if (transpose){{\n stride = ((lane_idx & 0b111) >> 2) + (lane_idx >> 4 << 1);\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ ((lane_idx & 0b1000) >> 3);\n }}else{{\n stride = (lane_idx & 0b1111) >> 2;\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ ((lane_idx & 0b10000) >> 4);\n }}\n }}else{{\n stride = (lane_idx & 0b111) >> 2;\n contig_vec = ((lane_idx & 3) << 1) + (stride & 1) ^ ((lane_idx & 0b1000) >> 3) + (lane_idx >> 4 << 3);\n }}\n \"\"\")\n elif self.interleave == 2:\n code.raw(f\"\"\"\n if (LdmCountContig == 1){{\n stride = lane_idx >> 1;\n contig_vec = ((lane_idx >> 1) & 0b11) + ((lane_idx & 1) << 2);\n }} else if (LdmCountContig == 2 && LdmCountStride == 2){{\n if (transpose){{\n int _00112233 = ((lane_idx >> 1) & 0b11);\n stride = _00112233 + (lane_idx >> 4 << 2);\n contig_vec = (_00112233 + ((lane_idx & 1) << 2)) ^ ((lane_idx >> 3) & 1);\n }}else{{\n stride = (lane_idx & 0b1111) >> 1;\n contig_vec = (((lane_idx >> 1) & 0b11) + ((lane_idx & 1) << 2)) ^ (lane_idx >> 4);\n }}\n }}else{{\n stride = (lane_idx & 0b111) >> 1;\n contig_vec = (((lane_idx >> 1) & 0b11) + ((lane_idx & 1) << 2)) ^ (lane_idx >> 3);\n }}\n \"\"\")\n elif self.interleave == 1:\n code.raw(f\"\"\"\n if (LdmCountContig == 1){{\n stride = lane_idx;\n contig_vec = (lane_idx & 0b111) ^ permute_m_pointer_idx;\n }} else if (LdmCountContig == 2 && LdmCountStride == 2){{\n if (transpose){{\n int _01234567 = (lane_idx & 0b111);\n stride = _01234567 + (lane_idx >> 4 << 3);\n contig_vec = _01234567 ^ (((lane_idx >> 3) & 1) + (permute_m_pointer_idx << 1));\n }}else{{\n int _01234567 = (lane_idx & 0b111);\n stride = lane_idx & 0b1111;\n contig_vec = _01234567 ^ ((lane_idx >> 4) + (permute_m_pointer_idx << 1));\n }}\n }}else{{\n stride = lane_idx & 0b111;\n contig_vec = stride ^ ((lane_idx >> 3) + (permute_m_pointer_idx << 2));\n }}\n \"\"\")\n else:\n raise NotImplementedError\n code.raw(f\"\"\"\n return stride * {self.static_stride} + contig_vec * {self.element_per_acc};\n \"\"\")\n return code.ret(self.long_index_t)\n\n @pccm.cuda.member_function(host=True,\n device=True,\n forceinline=True,\n constexpr=True)\n def get_ldm_initial_offset_ref_cpp(self):\n code = pccm.code()\n code.arg(\"lane_idx,permute_m_pointer_idx\", self.index_t)\n code.arg(\"transpose\", \"bool\")\n # is hard to get ldm count here even if it's a static constexpr variable,\n # so we use template instead.\n code.nontype_targ(\"LdmCountStride,LdmCountContig\", \"int\")\n code.raw(f\"\"\"\n int stride = -1;\n int contig_vec = -1;\n \"\"\")\n code.raw(f\"\"\"\n if (LdmCountStride == 1){{\n stride = lane_idx & 0b111;\n contig_vec = lane_idx >> 3;\n }} else if (LdmCountContig == 2 && LdmCountStride == 2){{\n if (transpose){{\n stride = (lane_idx & 0b111) + ((lane_idx >> 4) << 3);\n contig_vec = (lane_idx & 0b1111) >> 3;\n }}else{{\n stride = lane_idx & 0b1111;\n contig_vec = lane_idx >> 4;\n }}\n }}else{{\n stride = lane_idx;\n contig_vec = 0;\n }}\n \"\"\")\n code.raw(f\"\"\"\n return (*this)(stride, contig_vec * {self.element_per_acc} + LdmCountContig * permute_m_pointer_idx * {self.element_per_acc});\n \"\"\")\n return code.ret(self.long_index_t)\n\n\ndef _ci_dev_layout_dev():\n msg = \"\"\n msg_contig = \"\"\n permute_m_pointer_idx = 0\n for lane_idx in range(32):\n stride = (lane_idx & 0b111) + ((lane_idx >> 4) << 3)\n contig_vec = (lane_idx & 0b1111) >> 3\n msg += f\"{stride:01x}\"\n msg_contig += f\"{contig_vec:01x}\"\n\n if (lane_idx + 1) % 8 == 0:\n msg += \" \"\n msg_contig += \" \"\n print(msg)\n print(msg_contig)\n\n\nclass SmemTileIterator(bases.GemmSmemIterator):\n def __init__(self,\n is_crosswise: bool,\n dtype: dtypes.DType,\n tile_shape_km: MetaArray[int],\n my_layout: MyTensorOpLayout,\n smem_layout: layout_tensorop.TensorOpMultiplicand,\n tmap: PitchLinearWarpRaked,\n alignment: int = -1,\n crosswise: int = 0,\n num_stage: int = 2):\n super().__init__(dtype,\n tmap.iterations.prod() * my_layout.element_per_acc,\n my_layout.element_per_acc)\n # cultass shape: mk\n # our shape: km\n # A crosswise: [64, 32], congruous: [32, 64]\n # , congruous: [32, 128]\n self.transposed_smem = is_crosswise\n self.ref_layout = smem_layout\n # if crosswise, A is mk, B is nk, so k_axis == 1\n # else A is km, B is kn, so k_axis == 0\n self.k_axis = 0 if not is_crosswise else 1\n self.is_crosswise = is_crosswise\n self.smem_layout = my_layout\n self.tile_shape_km = tile_shape_km\n self.num_stage = num_stage\n self.smem_vis_shape = [tile_shape_km[0] * num_stage, tile_shape_km[1]]\n self.layout = my_layout\n ss = tile_shape_km[1] * self.smem_layout.interleave\n self.smem_vis_shape = [\n tile_shape_km[0] * num_stage * tile_shape_km[1] // ss, ss\n ]\n self.stride_with_stage = self.smem_layout.base_stride * self.smem_layout.stage_count[\n 1]\n self.static_stride_vec = self.smem_layout.static_stride_vec\n\n self.tmap = tmap\n if alignment == -1:\n alignment = dtype.bitsize() * tmap.element_per_acc // 8\n self.alignment = alignment\n self.add_param_class(\"tmap\", tmap, \"ThreadMap\")\n self.crosswise = crosswise\n\n self.add_param_class(\"layout\", self.layout, \"Layout\")\n # if is_crosswise:\n # print(self.pointer_count, self.my_layout)\n self.iterations = tmap.iterations # same as tmap iterations\n if self.smem_layout.interleave != 1:\n self.interleaved_delta = metaseq(\n tmap.delta[0] // self.smem_layout.interleave,\n tmap.delta[1] * self.smem_layout.interleave)\n else:\n self.interleaved_delta = tmap.delta\n\n # num pointers:\n self.pointer_count = self.smem_layout.num_smem_pointers\n # print(self.smem_layout.interleave, self.static_stride, self.pointer_count, self.stage_axis)\n\n # self.add_member(\"stride_\", self.index_t)\n self.add_member(\"pointer_\",\n self.access_pointer,\n array=f\"[{self.pointer_count}]\")\n\n self.add_member(\"byte_offset_\", self.index_t)\n # self.add_member(\"iteration_contiguous_, iteration_strided_\", \"int\")\n # cudasim members\n self.pointer_: List[ArrayPtr] = [None] * self.pointer_count\n self.byte_offset_ = 0\n\n def get_smem_vis_shape(self) -> MetaArray[int]:\n return seq(self.smem_vis_shape[0], self.smem_vis_shape[1])\n\n def __repr__(self):\n return f\"SmemIter[id={self.interleaved_delta}|it={self.iterations}]\"\n\n @pccm.cuda.constructor(device=True, forceinline=True)\n def ctor(self):\n code = pccm.code()\n # TODO remove this argument\n code.arg(\"stride\", \"int\")\n code.arg(\"ptr\", self.pointer)\n code.arg(\"thread_id\", \"int\")\n code.ctor_init(\"byte_offset_\", \"0\")\n\n code.raw(f\"\"\"\n auto thread_offset_base = ThreadMap::initial_offset(thread_id);\n auto layout = Layout();\n TV_PRAGMA_UNROLL\n for (int i = 0; i < {self.pointer_count}; ++i) {{\n pointer_[i] = reinterpret_cast<{self.access_pointer}>(\n ptr + layout(thread_offset_base[0] + i * {self.tmap.warp_shape[0]},\n thread_offset_base[1]));\n }}\n \"\"\")\n return code\n\n def python_ctor(self, stride: int, ptr: ArrayPtr, thread_id: int):\n new_obj = SmemTileIterator(self.is_crosswise, self.dtype,\n self.tile_shape_km, self.smem_layout,\n self.ref_layout, self.tmap, self.alignment,\n self.crosswise, self.num_stage)\n l = new_obj.layout.python_ctor(self.stride_with_stage)\n thread_offset_base = new_obj.tmap.initial_offset_python(thread_id)\n refl = new_obj.ref_layout.python_ctor(new_obj.stride_with_stage)\n\n # for smem store iters, only stride axis may insufficient\n for i in range(new_obj.pointer_count):\n off = l(thread_offset_base[0] + i * new_obj.tmap.warp_shape[0],\n thread_offset_base[1])\n # refoff = refl(\n # thread_offset_base[0] + i * new_obj.tmap.warp_shape[0],\n # thread_offset_base[1])\n # if refoff != off:\n # print(off, refoff)\n new_obj.pointer_[i] = (ptr + off).change_access_size(\n new_obj.element_per_acc)\n return new_obj\n\n @pccm.cuda.member_function(device=True, forceinline=True, const=True)\n def get(self):\n code = pccm.FunctionCode(f\"\"\"\n {self.access_pointer} access_ptr = pointer_[s & {self.pointer_count - 1}];\n int external_stride_idx = (s & ~{self.pointer_count - 1});\n int access_offset = (external_stride_idx * {self.interleaved_delta[0]} *\n {self.static_stride_vec} + c * {self.interleaved_delta[1] // self.element_per_acc});\n \n char *access_byte_ptr =\n reinterpret_cast<char *>(access_ptr + access_offset);\n return reinterpret_cast<{self.access_pointer}>(access_byte_ptr + byte_offset_);\n \"\"\").arg(\"s, c\", \"int\")\n return code.ret(f\"{self.access_pointer}\")\n\n def get_python(self, s: int, c: int):\n access_ptr = self.pointer_[s & (self.pointer_count - 1)]\n # for other ptrs in same swizzle part,\n # we have already added the stride offset, so we remove\n # stride offset for all subsequence ptrs.\n external_stride_idx = s & (~((self.pointer_count - 1)))\n access_offset = (external_stride_idx * self.interleaved_delta[0] *\n self.static_stride_vec +\n c * self.interleaved_delta[1] // self.element_per_acc)\n ptr = ((access_ptr + access_offset).change_access_byte_size(1) +\n self.byte_offset_)\n return ptr.change_access_size(self.element_per_acc)\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def add_pointer_offset(self):\n code = pccm.FunctionCode(\n f\"byte_offset_ += offset * sizeof({self.dtype});\")\n code.arg(\"offset\", self.long_index_t)\n return code\n\n def add_pointer_offset_python(self, offset: int):\n self.byte_offset_ += offset * self.dtype.itemsize()\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def add_tile_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n add_pointer_offset(c * {self.layout.static_stride // self.layout.stage_count[1]} +\n s * {self.tile_shape_km[0] * self.tile_shape_km[1] *\n self.layout.stage_count[1]});\n \"\"\").arg(\"s, c\", \"int\")\n return code\n\n def add_tile_offset_python(self, s: int, c: int):\n # print(s, c, self.stage_count[1], self.tile_shape_km[0], self.tile_shape_km[1])\n self.add_pointer_offset_python(\n c * self.layout.static_stride // self.layout.stage_count[1] +\n s * self.tile_shape_km[0] * self.tile_shape_km[1] *\n self.layout.stage_count[1])\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def tile_increment(self):\n if self.layout.stage_axis == 1:\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(0, num_tile);\n \"\"\")\n else:\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(num_tile, 0);\n \"\"\")\n\n return code.arg(\"num_tile\", \"int\")\n\n def tile_increment_python(self, num: int):\n if self.layout.stage_axis == 1:\n self.add_tile_offset_python(0, num)\n else:\n self.add_tile_offset_python(num, 0)\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def store_with_pointer_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n store_with_byte_offset(frag, pointer_offset * {self.dtype.bitsize()} / 8);\n \"\"\")\n code.arg(\"frag\",\n f\"{self.fragment_t} const&\").arg(\"pointer_offset\",\n str(self.index_t))\n return code\n\n async def store_with_pointer_offset_python(self, frag: ArrayPtr,\n offset: int):\n return await self.store_with_byte_offset_python(\n frag, offset * self.dtype.itemsize())\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def store_with_byte_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n {self.const_access_pointer} frag_ptr = reinterpret_cast<{self.const_access_pointer}>(&frag);\n\n TV_PRAGMA_UNROLL\n for (int s = 0; s < {self.tmap.iterations[0]}; ++s) {{\n TV_PRAGMA_UNROLL\n for (int c = 0; c < {self.tmap.iterations[1]}; ++c) {{\n int access_idx = c + s * {self.tmap.iterations[1]};\n char *byte_ptr = reinterpret_cast<char *>(get(s, c)) + byte_offset;\n {self.access_pointer} access_ptr = reinterpret_cast<{self.access_pointer}>(byte_ptr);\n *access_ptr = frag_ptr[access_idx];\n }}\n }}\n \"\"\")\n\n code.arg(\"frag\",\n f\"{self.fragment_t} const&\").arg(\"byte_offset\",\n str(self.index_t))\n return code\n\n async def store_with_byte_offset_python(self, frag: ArrayPtr,\n byte_offset: int):\n ptr_addrs = np.zeros((frag.length, ), dtype=np.int32)\n frag_ptr = frag.change_access_size(self.element_per_acc)\n for s in range(self.tmap.iterations[0]):\n for c in range(self.tmap.iterations[1]):\n access_idx = c + s * self.tmap.iterations[1]\n byte_ptr = self.get_python(\n s, c).change_access_byte_size(1) + byte_offset\n access_ptr = byte_ptr.change_access_size(self.element_per_acc)\n await checkers.smem_bank_conflicit_check(access_ptr, 0)\n if access_ptr.length <= 0:\n continue\n\n access_ptr[0] = frag_ptr[access_idx]\n ptr_addrs[access_idx * frag_ptr.access_size:(access_idx + 1) *\n frag_ptr.access_size] = np.arange(\n access_ptr.offset,\n access_ptr.offset + frag_ptr.access_size)\n return ptr_addrs\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def store(self):\n code = pccm.FunctionCode(f\"\"\"\n store_with_pointer_offset(frag, 0);\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t} const&\")\n return code\n\n async def store_python(self, frag: ArrayPtr):\n return await self.store_with_pointer_offset_python(frag, 0)\n\n @pccm.cuda.member_function(name=\"operator++\",\n device=True,\n forceinline=True)\n def operator_pp(self):\n if self.layout.stage_axis == 1:\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(0, 1);\n return *this;\n \"\"\")\n else:\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(1, 0);\n return *this;\n \"\"\")\n\n return code.ret(f\"{self.class_name} &\")\n\n def increment_python(self):\n if self.layout.stage_axis == 1:\n self.add_tile_offset_python(0, 1)\n return self\n else:\n self.add_tile_offset_python(1, 0)\n return self\n\n\nclass WarpIteratorCrosswise(bases.GemmWarpIterator):\n \"\"\"PermuteK: the smem permute is done in k axis,\n which means when warp gemm increment (k increment), next location isn't trivial, \n we need to handle it carefully. \n\n Layout: LDM group -> WarpTileK\n \"\"\"\n def __init__(self, dtype: dtypes.DType, tile_shape_km: MetaArray[int],\n my_layout: MyTensorOpLayout,\n smem_layout: layout_tensorop.TensorOpMultiplicand,\n warp_tile_shape_km: MetaArray[int], operand_a: bool,\n inst_shape_km: MetaArray[int], mma_inst_delta: int,\n partk: int):\n self.threads = 32\n tile_shape_mk = tile_shape_km[::-1]\n inst_shape_mk = inst_shape_km[::-1]\n warp_tile_shape_mk = warp_tile_shape_km[::-1]\n element_count = warp_tile_shape_mk[0] * inst_shape_mk[1] // self.threads\n\n super().__init__(dtype, element_count, my_layout.element_per_acc)\n self.tile_shape_km = tile_shape_km\n self.inst_shape_km = inst_shape_km\n self.warp_tile_shape_km = warp_tile_shape_km\n self.warp_tile_shape_mk = warp_tile_shape_mk\n self.inst_shape_mk = inst_shape_mk\n self.tile_shape_mk = tile_shape_mk\n\n self.ref_layout = smem_layout\n self.layout = my_layout\n self.num_warp_gemm_iters = warp_tile_shape_mk[1] // inst_shape_mk[1]\n self.stride_with_stage = self.layout.base_stride * self.layout.stage_count[\n 1]\n self.add_param_class(\"layout\", self.layout, \"TensorOpLayout\")\n\n self.operand_a = operand_a\n self.mma_inst_delta = mma_inst_delta\n self.partk = partk\n self.crosswise = smem_layout.crosswise\n self.static_stride_vec = my_layout.static_stride // my_layout.element_per_acc\n assert self.layout.element_per_acc * self.dtype.itemsize(\n ) == arch.ldmatrix.LdMatrix.LineByteSize\n self.lds_op_outer = self.layout.element_per_acc\n self.ldm_line_size = self.layout.element_per_acc\n self.ldm_num_line = arch.ldmatrix.LdMatrix.NumLinePerMatrix\n self.lds_op_inner = arch.ldmatrix.LdMatrix.NumLinePerMatrix\n assert warp_tile_shape_mk[0] % self.lds_op_outer == 0\n assert warp_tile_shape_mk[1] % self.lds_op_inner == 0\n # ldm_count: number of sub matrix in ldmatrix inst\n # inst shape is mk ([16, 8]), so we need to load [16, 8]\n # so self.lds_op_outer * sizeof(T) must be 8 x f16?\n self.ldm_count = seq(1, inst_shape_mk[1] // self.ldm_line_size)\n self.ldm_count[0] = arch.ldmatrix.LdMatrix.MaxNum // self.ldm_count[1]\n if (self.ldm_count[0] * self.ldm_num_line) > warp_tile_shape_mk[0]:\n # ldm too many lines (at most 32 line), just use warp_tile_shape_km[0] // self.ldm_num_line\n self.ldm_count[0] = warp_tile_shape_mk[0] // self.ldm_num_line\n\n self.ldm_iters = seq(\n warp_tile_shape_mk[0] // self.ldm_num_line // self.ldm_count[0], 1)\n # number of k per tile?\n self.k_groups_per_tile = self.layout.sw_shape[\n 1] // self.layout.interleave // self.ldm_count[1]\n self.k_group_inc_mask = 0\n if self.k_groups_per_tile // self.partk > 1:\n # k_group_inc_mask: for maximum swizzle length limit\n self.k_group_inc_mask = (1 << int(\n np.log2(self.k_groups_per_tile // self.partk)) - 1) - 1\n # k inc width: when warp gemm increment, the length of byte increment (when no swizzle)\n self.k_inc_byte_width = self.ldm_count[1] * self.dtype.bitsize(\n ) * self.layout.element_per_acc // 8\n # self.add_member(\"sections_\", \"int\")\n # self.add_member(\"stride_\", self.index_t)\n self.add_member(\"pointer_\", self.const_access_pointer)\n # self.add_member(\"pointer_bkp_\", self.const_access_pointer)\n\n self.add_member(\"byte_offset_\", self.index_t)\n self.add_member(\"wmma_k_index_\", \"int\")\n\n self.ldmatrix = arch.ldmatrix.LdMatrix(True, self.ldm_count.prod())\n self.add_param_class(\"ldsm\", self.ldmatrix, \"LdMatrix\")\n # cudasim members\n self.pointer_: ArrayPtr = None\n self.byte_offset_ = -1\n self.wmma_k_index_ = -1\n\n def __repr__(self):\n return (f\"WarpIterPK[ldss={self.ldm_count}|\"\n f\"ldsi={self.ldm_iters}|g={self.k_groups_per_tile}]\")\n\n @pccm.cuda.constructor(device=True, forceinline=True)\n def ctor(self):\n code = pccm.code()\n code.arg(\"ptr\", self.pointer)\n code.arg(\"warp_idx_k, warp_idx_mn, lane_idx\", \"int\")\n code.ctor_init(\"pointer_\",\n f\"reinterpret_cast<{self.const_access_pointer}>(ptr)\")\n # code.ctor_init(\"pointer_bkp_\",\n # f\"reinterpret_cast<{self.const_access_pointer}>(ptr)\")\n code.ctor_init(\"wmma_k_index_\", \"0\")\n code.ctor_init(\"byte_offset_\", \"0\")\n code.raw(f\"\"\"\n #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ == 750))\n lane_idx = lane_idx % ({self.ldm_count.prod()} * {self.ldm_num_line});\n #endif\n int offset_e = TensorOpLayout::get_ldm_initial_offset<{self.ldm_count[0]}, {self.ldm_count[1]}>(\n lane_idx, 0, {pccm.boolean(self.operand_a)});\n byte_offset_ = offset_e * {self.dtype.bitsize()} / 8;\n add_tile_offset({self.num_warp_gemm_iters} * warp_idx_k, warp_idx_mn);\n \"\"\")\n return code\n\n async def python_ctor(self, ptr: ArrayPtr, warp_idx_k: int,\n warp_idx_mn: int, lane_idx: int):\n new_obj = WarpIteratorCrosswise(self.dtype, self.tile_shape_km,\n self.layout, self.ref_layout,\n self.warp_tile_shape_km,\n self.operand_a, self.inst_shape_km,\n self.mma_inst_delta, self.partk)\n new_obj.pointer_ = ptr.change_access_size(new_obj.element_per_acc)\n new_obj.wmma_k_index_ = 0\n new_obj.byte_offset_ = 0\n layout = new_obj.layout.python_ctor(new_obj.layout.static_stride //\n new_obj.layout.stage_count[1])\n # turing ldmatrix don't support invalid addr.\n # the number of lane needed is ldmatrix.count * 8\n lane_idx = lane_idx % (new_obj.ldm_count.prod() * new_obj.lds_op_inner)\n ref_offset = layout.get_ldm_initial_offset_fast(\n lane_idx, self.ldm_count, not self.operand_a)\n new_obj.byte_offset_ = (ref_offset * new_obj.dtype.bitsize() // 8)\n new_obj.add_tile_offset_python(\n new_obj.num_warp_gemm_iters * warp_idx_k, warp_idx_mn)\n return new_obj\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def add_tile_offset(self):\n interleaved_warp_tile_stride = self.warp_tile_shape_mk[\n 0] // self.layout.interleave\n code = pccm.FunctionCode(f\"\"\"\n int mn_offset = warp_idx_mn;\n int k_offset = warp_idx_k;\n int sw_part_idx = k_offset / {self.k_groups_per_tile};\n int idx_in_sw_part = k_offset % {self.k_groups_per_tile};\n\n byte_offset_ ^= (idx_in_sw_part * {self.k_inc_byte_width});\n // tv::printf2_block_once(threadIdx.x, \"premuteK\", byte_offset_);\n\n pointer_ +=\n mn_offset * {interleaved_warp_tile_stride * self.static_stride_vec} +\n sw_part_idx * {self.layout.sw_shape[1]};\n \"\"\")\n return code.arg(\"warp_idx_k, warp_idx_mn\", \"int\")\n\n def add_tile_offset_python(self, warp_idx_k: int, warp_idx_mn: int):\n mn_offset = warp_idx_mn\n k_offset = warp_idx_k\n sw_part_idx = k_offset // self.k_groups_per_tile\n idx_in_sw_part = k_offset % self.k_groups_per_tile\n # swizzle inside a swizzle part\n self.byte_offset_ ^= int(idx_in_sw_part * self.k_inc_byte_width)\n interleaved_warp_tile_stride = self.warp_tile_shape_mk[\n 0] // self.layout.interleave\n self.pointer_ += (\n mn_offset * interleaved_warp_tile_stride * self.static_stride_vec +\n sw_part_idx * self.layout.sw_shape[1])\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def tile_increment(self):\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(num_tile, 0);\n \"\"\")\n return code.arg(\"num_tile\", \"int\")\n\n def tile_increment_python(self, num: int):\n return self.add_tile_offset_python(num, 0)\n\n @pccm.cuda.member_function(name=\"operator++\",\n device=True,\n forceinline=True)\n def operator_pp(self):\n num_k_inc = (self.k_groups_per_tile // self.partk)\n code = pccm.code()\n\n if num_k_inc > 1:\n assert count_set_bits(\n self.k_inc_byte_width) == 1, \"width must be power of 2\"\n # precedence of c++ bit operators is lower than logical operators.\n # so we need brackets here, python code don't need them.\n code.raw(f\"\"\"\n if (((wmma_k_index_ & {self.k_group_inc_mask}) & 1) == 0){{\n // bit 0 advance\n byte_offset_ ^= 0b1 * {self.k_inc_byte_width};\n }}\n else if ((wmma_k_index_ & {self.k_group_inc_mask}) == 0b1){{\n // bit 1 advance\n byte_offset_ ^= 0b11 * {self.k_inc_byte_width};\n }}\n else if ((wmma_k_index_ & {self.k_group_inc_mask}) == 0b11){{\n // bit 2 advance\n byte_offset_ ^= 0b111 * {self.k_inc_byte_width};\n }}\n \"\"\")\n code.raw(f\"\"\"\n wmma_k_index_++;\n if (wmma_k_index_ == {num_k_inc}) {{\n wmma_k_index_ = 0;\n // k group increment\n add_tile_offset({self.k_groups_per_tile}, 0);\n }}\n return *this;\n \"\"\")\n return code.ret(f\"{self.class_name} &\")\n\n def increment_python(self):\n \"\"\"warps in k handle divided swizzle tile, then jump to next swizzle tile if exists.\n --swizzle0-- --swizzle1--\n w0 w1 w2 w3 w0 w1 w2 w3\n \"\"\"\n num_k_inc = (self.k_groups_per_tile // self.partk)\n if (num_k_inc > 1):\n # mask: largest number of bit during increment\n mask = self.k_group_inc_mask\n\n self.byte_offset_ ^= layout_tensorop.swizzle_increment(\n self.wmma_k_index_ & mask, self.k_inc_byte_width)\n self.wmma_k_index_ += 1\n if (self.wmma_k_index_ == num_k_inc):\n self.wmma_k_index_ = 0\n # increase sw part\n self.add_tile_offset_python(self.k_groups_per_tile, 0)\n return self\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load_with_byte_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n tv::array<unsigned, {self.ldm_count.prod()}> *fetch_ptr =\n reinterpret_cast<tv::array<unsigned, {self.ldm_count.prod()}> *>(&frag);\n TV_PRAGMA_UNROLL\n for (int s = 0; s < {self.ldm_iters[0]}; ++s) {{\n TV_PRAGMA_UNROLL\n for (int c = 0; c < {self.ldm_iters[1]}; ++c) {{\n int access_idx = c + s * {self.ldm_iters[1]};\n {self.const_access_pointer} source_ptr =\n pointer_ + {self.ldm_count[1]} * c +\n {self.ldm_num_line} * {self.ldm_count[0]} * s * \n {self.static_stride_vec // self.layout.interleave};\n char const *source_byte_ptr =\n reinterpret_cast<char const *>(source_ptr) + byte_offset +\n byte_offset_;\n LdMatrix::run(fetch_ptr[access_idx], source_byte_ptr);\n }}\n }}\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t}&\").arg(\"byte_offset\",\n str(self.index_t))\n return code\n\n async def load_with_byte_offset_python(self, frag: ArrayPtr,\n byte_offset: int):\n fetch_ptr = frag.change_access_byte_size(self.ldm_count.prod() * 4)\n ptr_addrs = np.zeros((frag.length, ), dtype=np.int32)\n\n for s in range(self.ldm_iters[0]):\n for c in range(self.ldm_iters[1]):\n access_idx = c + s * self.ldm_iters[1]\n\n source_ptr = (self.pointer_ + self.ldm_count[1] * c +\n self.ldm_num_line // self.layout.interleave *\n self.ldm_count[0] * s * self.static_stride_vec\n ).change_access_size(self.element_per_acc)\n\n source_byte_ptr = source_ptr.change_access_byte_size(\n 1) + byte_offset + self.byte_offset_\n await checkers.smem_bank_conflicit_check(fetch_ptr, access_idx)\n await self.ldmatrix(fetch_ptr[access_idx], source_byte_ptr)\n ptr_addrs[access_idx * fetch_ptr.access_size:(access_idx + 1) *\n fetch_ptr.access_size] = np.arange(\n source_byte_ptr.offset,\n source_byte_ptr.offset + fetch_ptr.access_size)\n return ptr_addrs\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load_with_pointer_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n load_with_byte_offset(frag, pointer_offset * sizeof({self.dtype}));\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t}&\").arg(\"pointer_offset\",\n str(self.index_t))\n return code\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load(self):\n code = pccm.FunctionCode(f\"\"\"\n load_with_byte_offset(frag, 0);\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t}&\")\n return code\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def set_kgroup_index(self):\n code = pccm.FunctionCode(\n f\"wmma_k_index_ = wmma_k % ({self.k_groups_per_tile // self.partk});\"\n )\n code.arg(\"wmma_k\", \"int\")\n return code\n\n async def load_python(self, frag: ArrayPtr):\n return await self.load_with_byte_offset_python(frag, 0)\n\n def set_wmma_k_index_python(self, wmma_k):\n self.wmma_k_index_ = wmma_k % (self.k_groups_per_tile // self.partk)\n\n\nclass WarpIteratorCongruous(bases.GemmWarpIterator):\n def __init__(self, dtype: dtypes.DType, tile_shape_km: MetaArray[int],\n my_layout: MyTensorOpLayout,\n smem_layout: layout_tensorop.TensorOpMultiplicand,\n warp_tile_shape_km: MetaArray[int], operand_a: bool,\n inst_shape_km: MetaArray[int], mma_inst_delta: int,\n partk: int):\n self.threads = 32\n\n self.is_spec_32 = dtype.bitsize() == 32\n element_count = warp_tile_shape_km[1] * inst_shape_km[0] // self.threads\n\n if self.is_spec_32:\n super().__init__(dtype, element_count, 1)\n else:\n super().__init__(dtype, element_count, my_layout.element_per_acc)\n # cultass shape: mk\n # our shape: km\n self.ref_layout = smem_layout\n self.my_layout = my_layout\n self.num_warp_gemm_iters = warp_tile_shape_km[0] // inst_shape_km[0]\n self.tile_shape_km = tile_shape_km\n self.warp_tile_shape_km = warp_tile_shape_km\n self.operand_a = operand_a\n self.inst_shape_km = inst_shape_km\n\n self.mma_inst_delta = mma_inst_delta\n self.partk = partk\n\n self.layout = my_layout\n self.static_stride_vec = my_layout.static_stride // my_layout.element_per_acc\n self.ldm_line_size = self.layout.element_per_acc\n self.ldm_num_line = arch.ldmatrix.LdMatrix.NumLinePerMatrix\n self.add_param_class(\"layout\", self.layout, \"TensorOpLayout\")\n\n if self.is_spec_32:\n # 32bit mma (tf32) don't support ldmatrix.trans.\n\n self.ldm_num_line = self.layout.sw_shape[0]\n self.ldm_line_size = self.threads // self.ldm_num_line\n self.ldm_count = metaseq(inst_shape_km[0] // self.ldm_num_line,\n inst_shape_km[1] // self.ldm_line_size)\n # tf32 iter can't use element per acc > 1 because it need transposed load.\n # so we need more pointers here.\n self.pointer_count = self.layout.sw_shape[\n 1] * self.layout.element_per_acc // self.ldm_line_size\n self.ldm_iters = metaseq(\n 1, warp_tile_shape_km[1] // self.ldm_line_size //\n self.ldm_count[1])\n else:\n\n self.lds_op_outer = self.layout.element_per_acc\n self.lds_op_inner = 8\n self.ldm_count = metaseq(inst_shape_km[0] // self.ldm_num_line, 1)\n self.ldm_count[\n 1] = arch.ldmatrix.LdMatrix.MaxNum // self.ldm_count[0]\n self.ldm_iters = metaseq(\n 1, warp_tile_shape_km[1] // self.layout.element_per_acc //\n self.ldm_count[1])\n self.pointer_count = self.layout.sw_shape[1] // self.ldm_count[1]\n assert warp_tile_shape_km[1] % self.ldm_line_size == 0\n assert warp_tile_shape_km[0] % self.ldm_num_line == 0\n\n self.k_groups_per_tile = self.warp_tile_shape_km[0] // inst_shape_km[\n 0] # type: int\n # print(self.layout.tile_shape)\n # print(self.class_name, self.ldm_count, self.ldm_iters,\n # self.k_groups_per_tile)\n\n self.add_member(\"wmma_k_index_\", \"int\")\n self.add_member(\"pointer_\",\n self.const_access_pointer,\n array=f\"[{self.pointer_count}]\")\n self.add_member(\"byte_offset_\", self.index_t)\n self.ldmatrix = arch.ldmatrix.LdMatrix(False, self.ldm_count.prod())\n\n self.add_param_class(\"ldsm\", self.ldmatrix, \"LdMatrix\")\n\n # cudasim members\n self.pointer_: List[ArrayPtr] = [None] * self.pointer_count\n self.byte_offset_ = -1\n self.wmma_k_index_ = -1\n\n def __repr__(self):\n return (f\"WarpIterPM[ldss={self.ldm_count}|\"\n f\"ldsi={self.ldm_iters}|g={self.k_groups_per_tile}]\")\n\n @pccm.cuda.constructor(device=True, forceinline=True)\n def ctor(self):\n code = pccm.code()\n code.arg(\"ptr\", self.pointer)\n code.arg(\"warp_idx_k, warp_idx_mn, lane_idx\", \"int\")\n code.ctor_init(\"wmma_k_index_\", \"0\")\n code.ctor_init(\"byte_offset_\", \"0\")\n if not self.is_spec_32:\n code.raw(f\"\"\"\n TV_PRAGMA_UNROLL\n for (int i = 0; i < {self.pointer_count}; ++i) {{\n int offset = TensorOpLayout::get_ldm_initial_offset<{self.ldm_count[0]}, {self.ldm_count[1]}>(\n lane_idx, i, {pccm.boolean(not self.operand_a)});\n pointer_[i] = reinterpret_cast<{self.const_access_pointer} >(ptr + offset);\n }}\n add_tile_offset({self.num_warp_gemm_iters} * warp_idx_k, warp_idx_mn);\n \"\"\")\n else:\n code.raw(f\"\"\"\n for (int i = 0; i < {self.pointer_count}; ++i) {{\n int access_strided = lane_idx % {self.ldm_num_line};\n int access_contiguous = (lane_idx / {self.ldm_num_line}) +\n (access_strided ^ i) * {self.lds_op_outer};\n pointer_[i] = reinterpret_cast<{self.const_access_pointer} >(ptr) +\n access_contiguous + access_strided * {self.static_stride_vec};\n }}\n add_tile_offset({self.num_warp_gemm_iters} * warp_idx_k, warp_idx_mn);\n \"\"\")\n return code\n\n async def python_ctor(self, ptr: ArrayPtr, warp_idx_k: int,\n warp_idx_mn: int, lane_idx: int):\n new_obj = WarpIteratorCongruous(self.dtype, self.tile_shape_km,\n self.my_layout, self.ref_layout,\n self.warp_tile_shape_km,\n self.operand_a, self.inst_shape_km,\n self.mma_inst_delta, self.partk)\n new_obj.wmma_k_index_ = 0\n new_obj.byte_offset_ = 0\n if not self.is_spec_32:\n layout = new_obj.layout.python_ctor(new_obj.layout.static_stride)\n for i in range(self.pointer_count):\n ref_offset = layout.get_ldm_initial_offset_fast(\n lane_idx,\n self.ldm_count,\n self.operand_a,\n permute_m_pointer_idx=i)\n new_obj.pointer_[i] = (\n ptr.change_access_size(self.element_per_acc) +\n ref_offset // self.element_per_acc)\n else:\n for i in range(self.pointer_count):\n access_strided = lane_idx % self.ldm_num_line\n access_contiguous = lane_idx // self.ldm_num_line + (\n access_strided ^ i) * self.ldm_line_size\n new_obj.pointer_[i] = (\n ptr.change_access_size(self.element_per_acc) +\n access_contiguous +\n access_strided * self.static_stride_vec)\n\n new_obj.add_tile_offset_python(self.num_warp_gemm_iters * warp_idx_k,\n warp_idx_mn)\n\n return new_obj\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def add_pointer_offset(self):\n code = pccm.FunctionCode(\n f\"byte_offset_ += offset * sizeof({self.dtype});\")\n code.arg(\"offset\", self.long_index_t)\n return code\n\n def add_pointer_offset_python(self, offset: int):\n self.byte_offset_ += offset * self.dtype.itemsize()\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def add_tile_offset(self):\n code = pccm.code()\n if self.is_spec_32:\n code.raw(f\"\"\"\n constexpr int kContigEqual = {self.layout.tile_shape[1]} * {self.layout.element_per_acc} / 2;\n // Matrix multiply 1688 pointer_[0] <=> pointer_[4] pointer_[1] <=> pointer_[5]\n // pointer_[2] <=> pointer_[6] pointer_[3] <=> pointer_[7]\n\n \"\"\")\n else:\n code.raw(f\"\"\"\n constexpr int kContigEqual = {self.layout.part_shape[1]} * {self.layout.element_per_acc};\n \"\"\")\n\n code.raw(f\"\"\"\n int mn_offset = warp_idx_mn;\n int k_offset = warp_idx_k;\n\n if ({self.warp_tile_shape_km[1]} == kContigEqual) {{\n if (warp_idx_mn % 2) {{\n TV_PRAGMA_UNROLL\n for (int i = 0; i < {self.pointer_count} / 2; ++i) {{\n {self.const_access_pointer} tmp_pointer = pointer_[i];\n pointer_[i] = pointer_[i + {self.pointer_count} / 2];\n pointer_[i + {self.pointer_count} / 2] = tmp_pointer;\n }}\n }}\n mn_offset = (warp_idx_mn >> 1) << 1;\n }}\n \"\"\")\n if self.is_spec_32:\n code.raw(f\"\"\"\n int offset = (k_offset * {self.inst_shape_km[0]}) *\n {self.static_stride_vec} +\n mn_offset * {self.warp_tile_shape_km[1]});\n \"\"\")\n else:\n code.raw(f\"\"\"\n int offset = (k_offset * {self.ldm_count[0] * self.ldm_num_line *\n self.static_stride_vec *\n self.layout.element_per_acc} +\n mn_offset * {self.warp_tile_shape_km[1]});\n \"\"\")\n code.raw(f\"\"\"\n add_pointer_offset(offset);\n \"\"\")\n return code.arg(\"warp_idx_k, warp_idx_mn\", \"int\")\n\n def add_tile_offset_python(self, warp_idx_k: int, warp_idx_mn: int):\n mn_offset = warp_idx_mn\n k_offset = warp_idx_k\n # two warp handle one swizzle part.\n # for second warp, we need to swap pointers (swizzle part for second warp)\n if (self.warp_tile_shape_km[1] == self.layout.part_shape[1] *\n self.layout.element_per_acc):\n if (warp_idx_mn % 2):\n for i in range(self.pointer_count // 2):\n tmp_pointer = self.pointer_[i]\n self.pointer_[i] = self.pointer_[i +\n self.pointer_count // 2]\n self.pointer_[i + self.pointer_count // 2] = tmp_pointer\n # mn_offset: 00 22 44 66\n # this stmt is exists because we have add offset in init function.\n # so we skip second warp.\n mn_offset = (warp_idx_mn >> 1) << 1\n self.add_pointer_offset_python(\n (k_offset * self.ldm_count[0] * self.ldm_num_line) *\n self.static_stride_vec * self.layout.element_per_acc +\n mn_offset * self.warp_tile_shape_km[1])\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def tile_increment(self):\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(num_tile, 0);\n \"\"\")\n return code.arg(\"num_tile\", \"int\")\n\n def tile_increment_python(self, num: int):\n return self.add_tile_offset_python(num, 0)\n\n @pccm.cuda.member_function(name=\"operator++\",\n device=True,\n forceinline=True)\n def operator_pp(self):\n code = pccm.FunctionCode(f\"\"\"\n add_tile_offset(1, 0); // strided, contig\n // tv::printf2_block_once(threadIdx.x, \"byte_offset_=\", byte_offset_);\n if ({self.partk} > 1) {{\n ++wmma_k_index_;\n // Jump to next stage\n if (wmma_k_index_ == {self.k_groups_per_tile}) {{\n wmma_k_index_ = 0;\n add_tile_offset((({self.partk} - 1) * {self.k_groups_per_tile}), 0);\n }}\n }}\n return *this;\n \"\"\")\n return code.ret(f\"{self.class_name} &\")\n\n def increment_python(self):\n self.add_tile_offset_python(1, 0)\n if (self.partk > 1):\n self.wmma_k_index_ += 1\n # Jump to next stage\n if (self.wmma_k_index_ == self.k_groups_per_tile):\n self.wmma_k_index_ = 0\n self.add_tile_offset_python(\n ((self.partk - 1) * self.k_groups_per_tile), 0)\n return self\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load_with_byte_offset(self):\n if not self.is_spec_32:\n code = pccm.FunctionCode(f\"\"\"\n tv::array<unsigned, {self.ldm_count.prod()}> *fetch_ptr = \n reinterpret_cast<tv::array<unsigned, {self.ldm_count.prod()}> *>(&frag);\n\n TV_PRAGMA_UNROLL\n for (int s = 0; s < {self.ldm_iters[0]}; ++s) {{\n TV_PRAGMA_UNROLL\n for (int c = 0; c < {self.ldm_iters[1]}; ++c) {{\n\n int access_idx = c + s * {self.ldm_iters[1]};\n\n {self.const_access_pointer} source_ptr =\n pointer_[c % {self.pointer_count}] +\n {self.layout.tile_shape[1]} * (c / {self.pointer_count}) +\n {self.ldm_count[0]} * s * {self.static_stride_vec};\n\n char const *source_byte_ptr = reinterpret_cast<char const *>(source_ptr) + byte_offset + byte_offset_;\n\n LdMatrix::run(fetch_ptr[access_idx], source_byte_ptr);\n }}\n }}\n \"\"\")\n else:\n code = pccm.FunctionCode(f\"\"\"\n {self.dtype} *fetch_ptr = reinterpret_cast<{self.dtype} *>(&frag);\n\n TV_PRAGMA_UNROLL\n for (int s = 0; s < {self.ldm_iters[0]}; ++s) {{\n TV_PRAGMA_UNROLL\n for (int c = 0; c < {self.ldm_iters[1]}; ++c) {{\n TV_PRAGMA_UNROLL\n for (int ss = 0; ss < {self.ldm_count[0]}; ++ss) {{\n TV_PRAGMA_UNROLL\n for (int cc = 0; cc < {self.ldm_count[1]}; ++cc) {{\n int access_idx =\n cc + (ss + (c + s * {self.ldm_iters[1]}) *\n {self.ldm_count[0]}) *\n {self.ldm_count[1]};\n int access_idx_contiguous = cc + c * {self.ldm_count[1]};\n int access_idx_strided =\n (ss + s * {self.ldm_count[0]}) * {self.ldm_num_line};\n\n {self.const_access_pointer} source_ptr =\n pointer_[access_idx_contiguous % {self.pointer_count}] +\n {self.layout.tile_shape[1]} * {self.layout.element_per_acc} *\n (access_idx_contiguous / {self.pointer_count}) +\n access_idx_strided * {self.static_stride_vec};\n\n char const *source_byte_ptr =\n reinterpret_cast<char const *>(source_ptr) + byte_offset +\n byte_offset_;\n\n fetch_ptr[access_idx] =\n *reinterpret_cast<{self.dtype} const *>(source_byte_ptr);\n }}\n }}\n }}\n }}\n \"\"\")\n\n code.arg(\"frag\", f\"{self.fragment_t}&\").arg(\"byte_offset\",\n str(self.index_t))\n return code\n\n async def load_with_byte_offset_python(self, frag: ArrayPtr,\n byte_offset: int):\n ptr_addrs = np.zeros((frag.length, ), dtype=np.int32)\n if not self.is_spec_32:\n fetch_ptr = frag.change_access_byte_size(self.ldm_count.prod() * 4)\n for s in range(self.ldm_iters[0]):\n for c in range(self.ldm_iters[1]):\n access_idx = c + s * self.ldm_iters[1]\n sw_part_idx = c // self.pointer_count\n pointer_part = self.pointer_[c % self.pointer_count]\n source_ptr = (pointer_part +\n self.layout.sw_shape[1] * sw_part_idx +\n self.ldm_count[0] * self.ldm_num_line * s *\n self.static_stride_vec)\n source_byte_ptr = source_ptr.change_access_byte_size(\n 1) + byte_offset + self.byte_offset_\n await checkers.smem_bank_conflicit_check(\n fetch_ptr, access_idx)\n await self.ldmatrix(fetch_ptr[access_idx], source_byte_ptr)\n ptr_addrs[access_idx *\n fetch_ptr.access_size:(access_idx + 1) *\n fetch_ptr.access_size] = np.arange(\n source_byte_ptr.offset,\n source_byte_ptr.offset +\n fetch_ptr.access_size)\n else:\n fetch_ptr = frag.change_access_size(1)\n for s in range(self.ldm_iters[0]):\n for c in range(self.ldm_iters[1]):\n for ss in range(self.ldm_count[0]):\n for cc in range(self.ldm_count[1]):\n access_idx = cc + (\n ss + (c + s * self.ldm_iters[1]) *\n self.ldm_count[0]) * self.ldm_count[1]\n access_contig = cc + c * self.ldm_count[1]\n access_stride = (\n ss + s * self.ldm_count[0]) * self.ldm_num_line\n pointer_part = self.pointer_[access_contig %\n self.pointer_count]\n\n source_ptr = (\n pointer_part + self.layout.sw_shape[1] *\n self.layout.element_per_acc * access_contig //\n self.pointer_count +\n access_stride * self.static_stride_vec)\n source_byte_ptr = source_ptr.change_access_byte_size(\n 1) + byte_offset + self.byte_offset_\n fetch_ptr[\n access_idx] = source_byte_ptr.change_access_size(\n 1)[0]\n\n return ptr_addrs\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load_with_pointer_offset(self):\n code = pccm.FunctionCode(f\"\"\"\n load_with_byte_offset(frag, pointer_offset * sizeof({self.dtype}));\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t}&\").arg(\"pointer_offset\",\n str(self.index_t))\n return code\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def load(self):\n code = pccm.FunctionCode(f\"\"\"\n load_with_byte_offset(frag, 0);\n \"\"\")\n code.arg(\"frag\", f\"{self.fragment_t}&\")\n return code\n\n @pccm.cuda.member_function(device=True, forceinline=True)\n def set_kgroup_index(self):\n code = pccm.code()\n code.arg(\"wmma_k\", \"int\")\n return code\n\n async def load_python(self, frag: ArrayPtr):\n return await self.load_with_byte_offset_python(frag, 0)\n\n def set_wmma_k_index_python(self, wmma_k):\n return\n"
] |
[
[
"numpy.arange",
"numpy.log2",
"numpy.zeros"
]
] |
MuellerSeb/ogs5py
|
[
"752e7bd2298fbd476406d168f6b7d1a85863dccd"
] |
[
"ogs5py/tools/output.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"Tools for ogs5py output files (independent from VTK package).\"\"\"\nimport glob\nimport os\nimport re\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\n\nfrom ogs5py.tools.types import PCS_TYP\n\n###############################################################################\n# retrieve infos from ogs-filenames\n###############################################################################\n\n\ndef split_pnt_path(\n infile,\n task_id=None,\n pnt_name=None,\n PCS_name=None,\n split_extra=False,\n guess_PCS=False,\n):\n \"\"\"\n Retrive ogs-infos from filename for tecplot-polyline output.\n\n {id}_time_{pnt}[_{PCS+extra}].tec\n \"\"\"\n # create a workaround for empty PCS string (which is valid)\n if PCS_name == \"\":\n temp_id, temp_pnt, temp_PCS, __ = split_pnt_path(\n infile=infile,\n task_id=task_id,\n pnt_name=None,\n PCS_name=None,\n split_extra=False,\n guess_PCS=False,\n )\n if temp_id is None:\n return 4 * (None,)\n endstring = temp_pnt + temp_PCS\n PCS = \"\"\n if pnt_name is None:\n if split_extra:\n # here we have to guess the POINT name and maybe an extra suf\n # POINT name is guessed as a name without \"_\"\n # the rest will be set as extra\n split_pnt = endstring.find(\"_\")\n if split_pnt > -1:\n pnt = endstring[: endstring.find(\"_\")]\n extra = endstring[endstring.find(\"_\") + 1 :]\n else:\n pnt = endstring\n extra = \"\"\n else:\n pnt = endstring\n extra = \"\"\n else:\n if endstring.startswith(pnt_name):\n pnt = pnt_name\n extra = endstring[len(pnt) :]\n if not split_extra and extra != \"\":\n return 4 * (None,)\n return temp_id, pnt, PCS, extra\n\n # remove the directory-part from the filepath to get the basename\n name = os.path.basename(infile)\n # search for the suffix (aka file ending)\n suffix_pat = re.compile(r\"\\.tec$\")\n suffix_match = suffix_pat.search(name)\n # check for the task_id\n if task_id is None:\n prefix_pat = re.compile(\"_time_\")\n prefix_match = prefix_pat.search(name)\n if prefix_match is None:\n return 4 * (None,)\n id_name = name[: prefix_match.span()[0]]\n else:\n prefix_pat = re.compile(\"^\" + re.escape(task_id) + \"_time_\")\n id_name = task_id\n prefix_match = prefix_pat.search(name)\n if prefix_match is None:\n return 4 * (None,)\n\n if pnt_name is not None:\n midtrm_pat = re.compile(\n \"^\"\n + re.escape(id_name)\n + \"_time_\"\n + re.escape(pnt_name)\n + r\"+[\\._]\"\n )\n midtrm_match = midtrm_pat.search(name)\n if midtrm_match is None:\n return 4 * (None,)\n PCS = name[midtrm_match.span()[1] : suffix_match.span()[0]]\n # check PCS\n if PCS_name is None:\n pcs_found = False\n for pcs_sgl in PCS_TYP[1:]:\n if PCS.startswith(pcs_sgl):\n pcs_found = True\n extra = PCS[len(pcs_sgl) :]\n PCS = pcs_sgl\n break\n if not pcs_found:\n extra = \"\"\n else:\n if PCS.startswith(PCS_name):\n extra = PCS[len(PCS_name) :]\n PCS = PCS_name\n if not split_extra and extra != \"\":\n return 4 * (None,)\n else:\n return 4 * (None,)\n else:\n # serch for the PCS\n if PCS_name is None:\n pcs_found = False\n for pcs_sgl in PCS_TYP[1:]:\n # create a pattern to search the actual pcs_type\n midtrm_pat = re.compile(\n \"^\"\n + re.escape(id_name)\n + \"_time_[^_]+.*_\"\n + re.escape(pcs_sgl)\n )\n midtrm_match = midtrm_pat.search(name)\n # if found retrive the PCS name\n if midtrm_match is not None:\n pcs_found = True\n PCS = name[\n midtrm_match.span()[1]\n - len(pcs_sgl) : suffix_match.span()[0]\n ]\n # cut off extra suffix from PCS\n extra = PCS[len(pcs_sgl) :]\n PCS = PCS[: len(pcs_sgl)]\n # retrive the pnt name from the file-path\n PCS_pat = re.compile(\n \"_\" + re.escape(PCS + extra) + r\"\\.tec$\"\n )\n PCS_match = PCS_pat.search(name)\n pnt = name[prefix_match.span()[1] : PCS_match.span()[0]]\n break\n if not pcs_found:\n if guess_PCS:\n # here we have to guess the POINT name and maybe a PCS type\n # POINT name is guessed as a name without \"_\"\n # the rest will be set as PCS\n midtrm_pat = re.compile(\n \"^\" + re.escape(id_name) + r\"_time_[^_]+[\\._]\"\n )\n midtrm_match = midtrm_pat.search(name)\n if midtrm_match is None:\n return 4 * (None,)\n pnt = name[\n prefix_match.span()[1] : midtrm_match.span()[1] - 1\n ]\n PCS = name[midtrm_match.span()[1] : suffix_match.span()[0]]\n extra = \"\"\n else:\n pnt = name[prefix_match.span()[1] : suffix_match.span()[0]]\n PCS = \"\"\n extra = \"\"\n else:\n PCS_pat = re.compile(\"_\" + re.escape(PCS_name)) # +\".*\\.tec$\")\n PCS_match = PCS_pat.search(name)\n if PCS_match is None:\n return 4 * (None,)\n pnt = name[prefix_match.span()[1] : PCS_match.span()[0]]\n extra = name[PCS_match.span()[1] : suffix_match.span()[0]]\n # PCS was given, extras should not be split and extra != \"\"\n # thus we get a contradiction\n if (not split_extra) and extra != \"\":\n return 4 * (None,)\n\n if not split_extra:\n PCS = PCS + extra\n extra = \"\"\n elif extra.startswith(\"_\"):\n extra = extra[1:]\n elif extra != \"\":\n # if PCS starts with given PCS but there's an extra suffix not\n # separated by an \"_\" return None\n return 4 * (None,)\n\n return id_name, pnt, PCS, extra\n\n\ndef split_ply_path(\n infile, task_id=None, line_name=None, PCS_name=None, split_extra=False\n):\n \"\"\"\n Retrive ogs-infos from filename for tecplot-polyline output.\n\n {id}_ply_{line}_t{n}[_{PCS+extra}].tec\n \"\"\"\n # remove the directory-part from the filepath to get the basename\n name = os.path.basename(infile)\n # check for the task_id\n if task_id is None:\n prefix_pat = re.compile(\"_ply_\")\n id_name = name[: prefix_pat.search(name).span()[0]]\n else:\n prefix_pat = re.compile(\"^\" + re.escape(task_id) + \"_ply_\")\n id_name = task_id\n # search for different parts in the string\n midtrm_pat = re.compile(r\"_t\\d+[\\._]\")\n suffix_pat = re.compile(r\"\\.tec$\")\n prefix_match = prefix_pat.search(name)\n midtrm_match = midtrm_pat.search(name)\n suffix_match = suffix_pat.search(name)\n\n # if anything was not found, return None for everything\n if prefix_match is None or midtrm_match is None or suffix_match is None:\n return 5 * (None,)\n\n # get the infos from the file-name\n line = name[prefix_match.span()[1] : midtrm_match.span()[0]]\n step = int(name[midtrm_match.span()[0] + 2 : midtrm_match.span()[1] - 1])\n PCS = name[midtrm_match.span()[1] : suffix_match.span()[0]]\n\n if line_name is not None and line_name != line:\n return 5 * (None,)\n\n if PCS_name is None:\n pcs_found = False\n for pcs_sgl in PCS_TYP[1:]:\n if PCS.startswith(pcs_sgl):\n pcs_found = True\n extra = PCS[len(pcs_sgl) :]\n PCS = pcs_sgl\n break\n if not pcs_found:\n extra = \"\"\n else:\n if PCS.startswith(PCS_name):\n extra = PCS[len(PCS_name) :]\n PCS = PCS_name\n if not split_extra and extra != \"\":\n return 5 * (None,)\n else:\n return 5 * (None,)\n if not split_extra:\n PCS = PCS + extra\n if PCS_name is not None and extra != \"\":\n return 5 * (None,)\n extra = \"\"\n elif extra.startswith(\"_\"):\n extra = extra[1:]\n elif extra != \"\" and PCS_name != \"\":\n # if PCS starts with given PCS (not \"\") but there's an extra suffix not\n # separated by an \"_\" return None\n return 5 * (None,)\n\n return id_name, line, step, PCS, extra\n\n\ndef readpvd_single(infile):\n \"\"\"\n Read a paraview pvd file.\n\n Convert all concerned files to a dictionary containing their data.\n \"\"\"\n output = {}\n # read the pvd file as XML and extract the needed file infos\n if not os.path.isfile(infile):\n return output\n info_root = ET.parse(infile).getroot()\n pvd_info = info_root.attrib\n files = []\n infos = []\n # iterate through the data collection\n for dataset in info_root[0]:\n files.append(dataset.attrib[\"file\"])\n infos.append(dataset.attrib)\n del infos[-1][\"file\"]\n if \"timestep\" in infos[-1]:\n infos[-1][\"timestep\"] = float(infos[-1][\"timestep\"])\n if \"part\" in infos[-1]:\n infos[-1][\"part\"] = int(infos[-1][\"part\"])\n output[\"pvd_info\"] = pvd_info\n output[\"files\"] = files\n output[\"infos\"] = infos\n return output\n\n\ndef get_output_files(task_root, task_id, pcs=None, typ=\"VTK\", element=None):\n \"\"\"\n Get a list of output file paths.\n\n Parameters\n ----------\n task_root : string\n string containing the path to the directory containing the ogs output\n task_id : string\n string containing the file name of the ogs task without extension\n pcs : string or None, optional\n specify the PCS type that should be collected\n Possible values are:\n\n - None/\"\" (no PCS_TYPE specified in *.out)\n - \"NO_PCS\"\n - \"GROUNDWATER_FLOW\"\n - \"LIQUID_FLOW\"\n - \"RICHARDS_FLOW\"\n - \"AIR_FLOW\"\n - \"MULTI_PHASE_FLOW\"\n - \"PS_GLOBAL\"\n - \"HEAT_TRANSPORT\"\n - \"DEFORMATION\"\n - \"MASS_TRANSPORT\"\n - \"OVERLAND_FLOW\"\n - \"FLUID_MOMENTUM\"\n - \"RANDOM_WALK\"\n\n Default : None\n typ : string, optional\n Type of the output (\"VTK\", \"PVD\", \"TEC_POINT\" or \"TEC_POLYLINE\").\n Default : \"VTK\"\n element : string or None, optional\n For tecplot output you can specify the name of the output element.\n (Point-name of Line-name from GLI file)\n Default: None\n \"\"\"\n typ = typ.upper()\n if pcs is None:\n pcs = \"\"\n # if pcs is \"ALL\" iterate over all known PCS types\n if pcs == \"ALL\":\n raise ValueError(\"get_output_files: specifiy a single PCS not 'ALL'.\")\n # format task_root proper as directory path\n task_root = os.path.normpath(task_root)\n if typ == \"VTK\":\n # in the filename, there is a underscore before the PCS-type\n if pcs != \"\":\n pcs = \"_\" + pcs\n # YEAHAA.. inconsistency\n if pcs == \"_RANDOM_WALK\":\n pcs = \"_RWPT\"\n # get a list of all output files \"{id}0000.vtk\" ... \"{id}999[...]9.vtk\"\n # if pcs is RWPT the name-sheme is different\n if pcs == \"_RWPT\":\n files = glob.glob(\n os.path.join(\n task_root, task_id + pcs + \"_[0-9]*.particles.vtk\"\n )\n )\n else:\n files = glob.glob(\n os.path.join(\n task_root, task_id + pcs + \"[0-9][0-9][0-9]*[0-9].vtk\"\n )\n )\n files.sort()\n elif typ == \"PVD\":\n # in the filename, there is a underscore before the PCS-type\n if pcs != \"\":\n pcs = \"_\" + pcs\n infile = os.path.join(task_root, task_id + pcs + \".pvd\")\n # get the pvd information about the concerned files\n pvd_info = readpvd_single(infile)\n # if pvd is empty: return\n if not pvd_info:\n return []\n # initialize output-time\n time = []\n for info in pvd_info[\"infos\"]:\n time.append(info[\"timestep\"])\n time = np.array(time)\n time_sort = np.argsort(time)\n files = []\n for new_pos in time_sort:\n files.append(pvd_info[\"files\"][new_pos])\n elif typ == \"TEC_POINT\":\n # find point output by keyword \"time\"\n infiles = glob.glob(\n os.path.join(task_root, task_id + \"_time_*.\" + \"tec\")\n )\n infiles.sort()\n files = []\n for infile in infiles:\n # get the information from the file-name\n _, pnt_name, file_pcs, _ = split_pnt_path(infile, task_id)\n # check if the given PCS type matches, else skip the file\n if file_pcs == pcs and (element is None or element == pnt_name):\n files.append(infile)\n elif typ == \"TEC_POLYLINE\":\n infiles = glob.glob(\n os.path.join(task_root, task_id + \"_ply_?*_t[0-9]*.tec\")\n )\n # sort the infiles by name to sort it by timestep (pitfall!!!)\n infiles.sort()\n files = []\n for infile in infiles:\n # get the information from the file-name\n _, line_name, _, file_pcs, _ = split_ply_path(infile, task_id)\n # check if the given PCS type matches, else skip the file\n if file_pcs == pcs and (element is None or element == line_name):\n files.append(infile)\n else:\n raise ValueError(f\"Unknown output typ: '{typ}'\")\n return files\n"
] |
[
[
"numpy.argsort",
"numpy.array"
]
] |
shaheerakber67/PPEMonitoringSystem
|
[
"93b9d78bcd93ba48a1ed6d0730d10d469e737d67"
] |
[
"core/utils.py"
] |
[
"import cv2\nimport random\nimport colorsys\nimport numpy as np\nimport tensorflow as tf\nimport pytesseract\nfrom core.config import cfg\nimport re\n\n# If you don't have tesseract executable in your PATH, include the following:\n# pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'\n# Example tesseract_cmd = r'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'\n\n\n\ndef load_freeze_layer(model='yolov4', tiny=False):\n if tiny:\n if model == 'yolov3':\n freeze_layouts = ['conv2d_9', 'conv2d_12']\n else:\n freeze_layouts = ['conv2d_17', 'conv2d_20']\n else:\n if model == 'yolov3':\n freeze_layouts = ['conv2d_58', 'conv2d_66', 'conv2d_74']\n else:\n freeze_layouts = ['conv2d_93', 'conv2d_101', 'conv2d_109']\n return freeze_layouts\n\ndef load_weights(model, weights_file, model_name='yolov4', is_tiny=False):\n if is_tiny:\n if model_name == 'yolov3':\n layer_size = 13\n output_pos = [9, 12]\n else:\n layer_size = 21\n output_pos = [17, 20]\n else:\n if model_name == 'yolov3':\n layer_size = 75\n output_pos = [58, 66, 74]\n else:\n layer_size = 110\n output_pos = [93, 101, 109]\n wf = open(weights_file, 'rb')\n major, minor, revision, seen, _ = np.fromfile(wf, dtype=np.int32, count=5)\n\n j = 0\n for i in range(layer_size):\n conv_layer_name = 'conv2d_%d' %i if i > 0 else 'conv2d'\n bn_layer_name = 'batch_normalization_%d' %j if j > 0 else 'batch_normalization'\n\n conv_layer = model.get_layer(conv_layer_name)\n filters = conv_layer.filters\n k_size = conv_layer.kernel_size[0]\n in_dim = conv_layer.input_shape[-1]\n\n if i not in output_pos:\n # darknet weights: [beta, gamma, mean, variance]\n bn_weights = np.fromfile(wf, dtype=np.float32, count=4 * filters)\n # tf weights: [gamma, beta, mean, variance]\n bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]]\n bn_layer = model.get_layer(bn_layer_name)\n j += 1\n else:\n conv_bias = np.fromfile(wf, dtype=np.float32, count=filters)\n\n # darknet shape (out_dim, in_dim, height, width)\n conv_shape = (filters, in_dim, k_size, k_size)\n conv_weights = np.fromfile(wf, dtype=np.float32, count=np.product(conv_shape))\n # tf shape (height, width, in_dim, out_dim)\n conv_weights = conv_weights.reshape(conv_shape).transpose([2, 3, 1, 0])\n\n if i not in output_pos:\n conv_layer.set_weights([conv_weights])\n bn_layer.set_weights(bn_weights)\n else:\n conv_layer.set_weights([conv_weights, conv_bias])\n\n # assert len(wf.read()) == 0, 'failed to read all data'\n wf.close()\n\n\ndef read_class_names(class_file_name):\n names = {}\n with open(class_file_name, 'r') as data:\n for ID, name in enumerate(data):\n names[ID] = name.strip('\\n')\n return names\n\ndef read_violence_class_names(class_file_name):\n names = {}\n with open(class_file_name, 'r') as data:\n for ID, name in enumerate(data):\n if ID % 2 != 0:\n names[ID] = name.strip('\\n')\n return names\n\ndef load_config(tiny=False):\n if tiny:\n STRIDES = np.array(cfg.YOLO.STRIDES_TINY)\n ANCHORS = get_anchors(cfg.YOLO.ANCHORS_TINY, tiny)\n XYSCALE = cfg.YOLO.XYSCALE_TINY\n else:\n STRIDES = np.array(cfg.YOLO.STRIDES)\n ANCHORS = get_anchors(cfg.YOLO.ANCHORS, tiny)\n XYSCALE = cfg.YOLO.XYSCALE\n\n NUM_CLASS = len(read_class_names(cfg.YOLO.CLASSES))\n\n return STRIDES, ANCHORS, NUM_CLASS, XYSCALE\n\n\ndef get_anchors(anchors_path, tiny=False):\n anchors = np.array(anchors_path)\n if tiny:\n return anchors.reshape(2, 3, 2)\n else:\n return anchors.reshape(3, 3, 2)\n\ndef image_preprocess(image, target_size, gt_boxes=None):\n ih, iw = target_size\n h, w, _ = image.shape\n\n scale = min(iw/w, ih/h)\n nw, nh = int(scale * w), int(scale * h)\n image_resized = cv2.resize(image, (nw, nh))\n\n image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)\n dw, dh = (iw - nw) // 2, (ih-nh) // 2\n image_paded[dh:nh+dh, dw:nw+dw, :] = image_resized\n image_paded = image_paded / 255.\n\n if gt_boxes is None:\n return image_paded\n\n else:\n gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw\n gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh\n return image_paded, gt_boxes\n\n# helper function to convert bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, xmax, ymax\ndef format_boxes(bboxes, image_height, image_width):\n for box in bboxes:\n ymin = int(box[0] * image_height)\n xmin = int(box[1] * image_width)\n ymax = int(box[2] * image_height)\n xmax = int(box[3] * image_width)\n box[0], box[1], box[2], box[3] = xmin, ymin, xmax, ymax\n return bboxes\n\ndef draw_bbox(image, bboxes, info = False, counted_classes = None, show_label=True, allowed_classes=list(read_class_names(cfg.YOLO.CLASSES).values()), read_plate = False):\n classes = read_class_names(cfg.YOLO.CLASSES)\n num_classes = len(classes)\n image_h, image_w, _ = image.shape\n hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))\n\n random.seed(0)\n random.shuffle(colors)\n random.seed(None)\n\n out_boxes, out_scores, out_classes, num_boxes = bboxes\n for i in range(num_boxes):\n if int(out_classes[i]) < 0 or int(out_classes[i]) > num_classes: continue\n coor = out_boxes[i]\n fontScale = 0.5\n score = out_scores[i]\n class_ind = int(out_classes[i])\n class_name = classes[class_ind]\n if class_name not in allowed_classes:\n continue\n else:\n if read_plate:\n height_ratio = int(image_h / 25)\n plate_number = recognize_plate(image, coor)\n if plate_number != None:\n cv2.putText(image, plate_number, (int(coor[0]), int(coor[1]-height_ratio)), \n cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255,255,0), 2)\n\n bbox_color = colors[class_ind]\n bbox_thick = int(0.6 * (image_h + image_w) / 600)\n c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])\n cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)\n\n if info:\n print(\"Object found: {}, Confidence: {:.2f}, BBox Coords (xmin, ymin, xmax, ymax): {}, {}, {}, {} \".format(class_name, score, coor[0], coor[1], coor[2], coor[3]))\n\n if show_label:\n bbox_mess = '%s: %.2f' % (class_name, score)\n t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick // 2)[0]\n c3 = (c1[0] + t_size[0], c1[1] - t_size[1] - 3)\n cv2.rectangle(image, c1, (np.float32(c3[0]), np.float32(c3[1])), bbox_color, -1) #filled\n\n cv2.putText(image, bbox_mess, (c1[0], np.float32(c1[1] - 2)), cv2.FONT_HERSHEY_SIMPLEX,\n fontScale, (0, 0, 0), bbox_thick // 2, lineType=cv2.LINE_AA)\n\n if counted_classes != None:\n height_ratio = int(image_h / 25)\n offset = 15\n for key, value in counted_classes.items():\n cv2.putText(image, \"{}s detected: {}\".format(key, value), (5, offset),\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2)\n offset += height_ratio\n return image\n\ndef bbox_iou(bboxes1, bboxes2):\n \"\"\"\n @param bboxes1: (a, b, ..., 4)\n @param bboxes2: (A, B, ..., 4)\n x:X is 1:n or n:n or n:1\n @return (max(a,A), max(b,B), ...)\n ex) (4,):(3,4) -> (3,)\n (2,1,4):(2,3,4) -> (2,3)\n \"\"\"\n bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]\n bboxes2_area = bboxes2[..., 2] * bboxes2[..., 3]\n\n bboxes1_coor = tf.concat(\n [\n bboxes1[..., :2] - bboxes1[..., 2:] * 0.5,\n bboxes1[..., :2] + bboxes1[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n bboxes2_coor = tf.concat(\n [\n bboxes2[..., :2] - bboxes2[..., 2:] * 0.5,\n bboxes2[..., :2] + bboxes2[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n\n left_up = tf.maximum(bboxes1_coor[..., :2], bboxes2_coor[..., :2])\n right_down = tf.minimum(bboxes1_coor[..., 2:], bboxes2_coor[..., 2:])\n\n inter_section = tf.maximum(right_down - left_up, 0.0)\n inter_area = inter_section[..., 0] * inter_section[..., 1]\n\n union_area = bboxes1_area + bboxes2_area - inter_area\n\n iou = tf.math.divide_no_nan(inter_area, union_area)\n\n return iou\n\n\ndef bbox_giou(bboxes1, bboxes2):\n \"\"\"\n Generalized IoU\n @param bboxes1: (a, b, ..., 4)\n @param bboxes2: (A, B, ..., 4)\n x:X is 1:n or n:n or n:1\n @return (max(a,A), max(b,B), ...)\n ex) (4,):(3,4) -> (3,)\n (2,1,4):(2,3,4) -> (2,3)\n \"\"\"\n bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]\n bboxes2_area = bboxes2[..., 2] * bboxes2[..., 3]\n\n bboxes1_coor = tf.concat(\n [\n bboxes1[..., :2] - bboxes1[..., 2:] * 0.5,\n bboxes1[..., :2] + bboxes1[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n bboxes2_coor = tf.concat(\n [\n bboxes2[..., :2] - bboxes2[..., 2:] * 0.5,\n bboxes2[..., :2] + bboxes2[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n\n left_up = tf.maximum(bboxes1_coor[..., :2], bboxes2_coor[..., :2])\n right_down = tf.minimum(bboxes1_coor[..., 2:], bboxes2_coor[..., 2:])\n\n inter_section = tf.maximum(right_down - left_up, 0.0)\n inter_area = inter_section[..., 0] * inter_section[..., 1]\n\n union_area = bboxes1_area + bboxes2_area - inter_area\n\n iou = tf.math.divide_no_nan(inter_area, union_area)\n\n enclose_left_up = tf.minimum(bboxes1_coor[..., :2], bboxes2_coor[..., :2])\n enclose_right_down = tf.maximum(\n bboxes1_coor[..., 2:], bboxes2_coor[..., 2:]\n )\n\n enclose_section = enclose_right_down - enclose_left_up\n enclose_area = enclose_section[..., 0] * enclose_section[..., 1]\n\n giou = iou - tf.math.divide_no_nan(enclose_area - union_area, enclose_area)\n\n return giou\n\n\ndef bbox_ciou(bboxes1, bboxes2):\n \"\"\"\n Complete IoU\n @param bboxes1: (a, b, ..., 4)\n @param bboxes2: (A, B, ..., 4)\n x:X is 1:n or n:n or n:1\n @return (max(a,A), max(b,B), ...)\n ex) (4,):(3,4) -> (3,)\n (2,1,4):(2,3,4) -> (2,3)\n \"\"\"\n bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]\n bboxes2_area = bboxes2[..., 2] * bboxes2[..., 3]\n\n bboxes1_coor = tf.concat(\n [\n bboxes1[..., :2] - bboxes1[..., 2:] * 0.5,\n bboxes1[..., :2] + bboxes1[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n bboxes2_coor = tf.concat(\n [\n bboxes2[..., :2] - bboxes2[..., 2:] * 0.5,\n bboxes2[..., :2] + bboxes2[..., 2:] * 0.5,\n ],\n axis=-1,\n )\n\n left_up = tf.maximum(bboxes1_coor[..., :2], bboxes2_coor[..., :2])\n right_down = tf.minimum(bboxes1_coor[..., 2:], bboxes2_coor[..., 2:])\n\n inter_section = tf.maximum(right_down - left_up, 0.0)\n inter_area = inter_section[..., 0] * inter_section[..., 1]\n\n union_area = bboxes1_area + bboxes2_area - inter_area\n\n iou = tf.math.divide_no_nan(inter_area, union_area)\n\n enclose_left_up = tf.minimum(bboxes1_coor[..., :2], bboxes2_coor[..., :2])\n enclose_right_down = tf.maximum(\n bboxes1_coor[..., 2:], bboxes2_coor[..., 2:]\n )\n\n enclose_section = enclose_right_down - enclose_left_up\n\n c_2 = enclose_section[..., 0] ** 2 + enclose_section[..., 1] ** 2\n\n center_diagonal = bboxes2[..., :2] - bboxes1[..., :2]\n\n rho_2 = center_diagonal[..., 0] ** 2 + center_diagonal[..., 1] ** 2\n\n diou = iou - tf.math.divide_no_nan(rho_2, c_2)\n\n v = (\n (\n tf.math.atan(\n tf.math.divide_no_nan(bboxes1[..., 2], bboxes1[..., 3])\n )\n - tf.math.atan(\n tf.math.divide_no_nan(bboxes2[..., 2], bboxes2[..., 3])\n )\n )\n * 2\n / np.pi\n ) ** 2\n\n alpha = tf.math.divide_no_nan(v, 1 - iou + v)\n\n ciou = diou - alpha * v\n\n return ciou\n\ndef nms(bboxes, iou_threshold, sigma=0.3, method='nms'):\n \"\"\"\n :param bboxes: (xmin, ymin, xmax, ymax, score, class)\n\n Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf\n https://github.com/bharatsingh430/soft-nms\n \"\"\"\n classes_in_img = list(set(bboxes[:, 5]))\n best_bboxes = []\n\n for cls in classes_in_img:\n cls_mask = (bboxes[:, 5] == cls)\n cls_bboxes = bboxes[cls_mask]\n\n while len(cls_bboxes) > 0:\n max_ind = np.argmax(cls_bboxes[:, 4])\n best_bbox = cls_bboxes[max_ind]\n best_bboxes.append(best_bbox)\n cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])\n iou = bbox_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])\n weight = np.ones((len(iou),), dtype=np.float32)\n\n assert method in ['nms', 'soft-nms']\n\n if method == 'nms':\n iou_mask = iou > iou_threshold\n weight[iou_mask] = 0.0\n\n if method == 'soft-nms':\n weight = np.exp(-(1.0 * iou ** 2 / sigma))\n\n cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight\n score_mask = cls_bboxes[:, 4] > 0.\n cls_bboxes = cls_bboxes[score_mask]\n\n return best_bboxes\n\ndef freeze_all(model, frozen=True):\n model.trainable = not frozen\n if isinstance(model, tf.keras.Model):\n for l in model.layers:\n freeze_all(l, frozen)\ndef unfreeze_all(model, frozen=False):\n model.trainable = not frozen\n if isinstance(model, tf.keras.Model):\n for l in model.layers:\n unfreeze_all(l, frozen)\n\n"
] |
[
[
"numpy.fromfile",
"tensorflow.concat",
"numpy.product",
"tensorflow.maximum",
"tensorflow.minimum",
"numpy.full",
"numpy.concatenate",
"numpy.argmax",
"numpy.float32",
"numpy.exp",
"numpy.array",
"tensorflow.math.divide_no_nan"
]
] |
yy-YangYi/shrinkbench
|
[
"42c6abb640aa37a6c9da098fe136a26c96a4ce0c"
] |
[
"experiment/train.py"
] |
[
"import pathlib\nimport time\n\nimport torch\nimport torchvision.models\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom torch.backends import cudnn\nfrom tqdm import tqdm\n\nfrom .base import Experiment\nfrom .. import datasets\nfrom .. import models\nfrom ..metrics import correct\nfrom ..models.head import mark_classifier\nfrom ..util import printc, OnlineStats\n\n\nclass TrainingExperiment(Experiment):\n\n default_dl_kwargs = {'batch_size': 128,\n 'pin_memory': False,\n 'num_workers': 8\n }\n\n default_train_kwargs = {'optim': 'SGD',\n 'epochs': 200,\n 'lr': 1e-3,\n }\n\n def __init__(self,\n dataset,\n model,\n seed=42,\n path=None,\n dl_kwargs=dict(),\n train_kwargs=dict(),\n debug=False,\n pretrained=False,\n resume=None,\n resume_optim=False,\n save_freq=10):\n\n # Default children kwargs\n super(TrainingExperiment, self).__init__(seed)\n dl_kwargs = {**self.default_dl_kwargs, **dl_kwargs}\n train_kwargs = {**self.default_train_kwargs, **train_kwargs}\n\n params = locals()\n params['dl_kwargs'] = dl_kwargs\n params['train_kwargs'] = train_kwargs\n self.add_params(**params)\n # Save params\n\n self.build_dataloader(dataset, **dl_kwargs)\n\n self.build_model(model, pretrained, resume)\n\n self.build_train(resume_optim=resume_optim, **train_kwargs)\n\n self.path = path\n self.save_freq = save_freq\n\n def run(self):\n self.freeze()\n printc(f\"Running {repr(self)}\", color='YELLOW')\n self.to_device()\n self.build_logging(self.train_metrics, self.path)\n self.run_epochs()\n\n def build_dataloader(self, dataset, **dl_kwargs):\n constructor = getattr(datasets, dataset)\n self.train_dataset = constructor(train=True)\n self.val_dataset = constructor(train=False)\n self.train_dl = DataLoader(self.train_dataset, shuffle=True, **dl_kwargs)\n self.val_dl = DataLoader(self.val_dataset, shuffle=False, **dl_kwargs)\n\n def build_model(self, model, pretrained=True, resume=None):\n if isinstance(model, str):\n if hasattr(models, model):\n model = getattr(models, model)(pretrained=pretrained)\n\n elif hasattr(torchvision.models, model):\n # https://pytorch.org/docs/stable/torchvision/models.html\n model = getattr(torchvision.models, model)(pretrained=pretrained)\n mark_classifier(model) # add is_classifier attribute\n else:\n raise ValueError(f\"Model {model} not available in custom models or torchvision models\")\n\n self.model = model\n\n if resume is not None:\n self.resume = pathlib.Path(self.resume)\n assert self.resume.exists(), \"Resume path does not exist\"\n previous = torch.load(self.resume)\n self.model.load_state_dict(previous['model_state_dict'])\n\n def build_train(self, optim, epochs, resume_optim=False, **optim_kwargs):\n default_optim_kwargs = {\n 'SGD': {'momentum': 0.9, 'nesterov': True, 'lr': 1e-3},\n 'Adam': {'momentum': 0.9, 'betas': (.9, .99), 'lr': 1e-4}\n }\n\n self.epochs = epochs\n\n # Optim\n if isinstance(optim, str):\n constructor = getattr(torch.optim, optim)\n if optim in default_optim_kwargs:\n optim_kwargs = {**default_optim_kwargs[optim], **optim_kwargs}\n optim = constructor(self.model.parameters(), **optim_kwargs)\n\n self.optim = optim\n\n if resume_optim:\n assert hasattr(self, \"resume\"), \"Resume must be given for resume_optim\"\n previous = torch.load(self.resume)\n self.optim.load_state_dict(previous['optim_state_dict'])\n\n # Assume classification experiment\n self.loss_func = nn.CrossEntropyLoss()\n\n def to_device(self):\n # Torch CUDA config\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n if not torch.cuda.is_available():\n printc(\"GPU NOT AVAILABLE, USING CPU!\", color=\"ORANGE\")\n self.model.to(self.device)\n cudnn.benchmark = True # For fast training.\n\n def checkpoint(self):\n checkpoint_path = self.path / 'checkpoints'\n checkpoint_path.mkdir(exist_ok=True, parents=True)\n epoch = self.log_epoch_n\n torch.save({\n 'model_state_dict': self.model.state_dict(),\n 'optim_state_dict': self.optim.state_dict()\n }, checkpoint_path / f'checkpoint-{epoch}.pt')\n\n def run_epochs(self):\n\n since = time.time()\n try:\n for epoch in range(self.epochs):\n printc(f\"Start epoch {epoch}\", color='YELLOW')\n self.train(epoch)\n self.eval(epoch)\n # Checkpoint epochs\n # TODO Model checkpointing based on best val loss/acc\n if epoch % self.save_freq == 0:\n self.checkpoint()\n # TODO Early stopping\n # TODO ReduceLR on plateau?\n self.log(timestamp=time.time()-since)\n self.log_epoch(epoch)\n\n\n except KeyboardInterrupt:\n printc(f\"\\nInterrupted at epoch {epoch}. Tearing Down\", color='RED')\n\n def run_epoch(self, train, epoch=0):\n if train:\n self.model.train()\n prefix = 'train'\n dl = self.train_dl\n else:\n prefix = 'val'\n dl = self.val_dl\n self.model.eval()\n\n total_loss = OnlineStats()\n acc1 = OnlineStats()\n acc5 = OnlineStats()\n\n epoch_iter = tqdm(dl)\n epoch_iter.set_description(f\"{prefix.capitalize()} Epoch {epoch}/{self.epochs}\")\n\n with torch.set_grad_enabled(train):\n for i, (x, y) in enumerate(epoch_iter, start=1):\n x, y = x.to(self.device), y.to(self.device)\n yhat = self.model(x)\n loss = self.loss_func(yhat, y)\n if train:\n loss.backward()\n\n self.optim.step()\n self.optim.zero_grad()\n\n c1, c5 = correct(yhat, y, (1, 5))\n total_loss.add(loss.item() / dl.batch_size)\n acc1.add(c1 / dl.batch_size)\n acc5.add(c5 / dl.batch_size)\n\n epoch_iter.set_postfix(loss=total_loss.mean, top1=acc1.mean, top5=acc5.mean)\n\n self.log(**{\n f'{prefix}_loss': total_loss.mean,\n f'{prefix}_acc1': acc1.mean,\n f'{prefix}_acc5': acc5.mean,\n })\n\n return total_loss.mean, acc1.mean, acc5.mean\n\n def train(self, epoch=0):\n return self.run_epoch(True, epoch)\n\n def eval(self, epoch=0):\n return self.run_epoch(False, epoch)\n\n @property\n def train_metrics(self):\n return ['epoch', 'timestamp',\n 'train_loss', 'train_acc1', 'train_acc5',\n 'val_loss', 'val_acc1', 'val_acc5',\n ]\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.utils.data.DataLoader",
"torch.set_grad_enabled",
"torch.cuda.is_available"
]
] |
lhz1029/pixel-cnn
|
[
"f759b8d9a6b3f4b15144ef3f6d3bf18ac31dacc4"
] |
[
"plot_unifs.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nfrom functools import partial\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", type=str, default='',\n help=\"Location of checkpoint to restore\")\n parser.add_argument(\"-n\", type=str, default='',\n help=\"Location of checkpoint to restore\")\n args = parser.parse_args()\n unifs = np.load(args.f)\n fig, axes = plt.subplots(5, 5)\n for i, el in enumerate(unifs[:25]):\n axes[i//5, i%5].hist(el.flatten())\n plt.savefig(args.n)\n # plt.show()"
] |
[
[
"numpy.load",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
]
] |
robertogyn19/incubator-superset
|
[
"14c3488c79f8f3cdbd1123e8f7a92f8746c2db09"
] |
[
"superset/views/core.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=C,R,W\nfrom datetime import datetime, timedelta\nimport inspect\nimport logging\nimport os\nimport re\nimport time\nimport traceback\nfrom urllib import parse\n\nfrom flask import (\n abort, flash, g, Markup, redirect, render_template, request, Response, url_for,\n)\nfrom flask_appbuilder import expose, Model, SimpleFormView\nfrom flask_appbuilder.actions import action\nfrom flask_appbuilder.models.sqla.interface import SQLAInterface\nfrom flask_appbuilder.security.decorators import has_access, has_access_api\nfrom flask_babel import gettext as __\nfrom flask_babel import lazy_gettext as _\nimport pandas as pd\nimport simplejson as json\nimport sqlalchemy as sqla\nfrom sqlalchemy import (\n and_, Column, create_engine, ForeignKey, Integer, MetaData, or_, Table, update)\nfrom sqlalchemy.engine.url import make_url\nfrom sqlalchemy.exc import IntegrityError\nfrom werkzeug.routing import BaseConverter\nfrom werkzeug.utils import secure_filename\n\nfrom superset import (\n app, appbuilder, cache, db, results_backend,\n security_manager, sql_lab, viz)\nfrom superset.connectors.connector_registry import ConnectorRegistry\nfrom superset.connectors.sqla.models import AnnotationDatasource, SqlaTable\nfrom superset.exceptions import SupersetException\nfrom superset.forms import CsvToDatabaseForm\nfrom superset.jinja_context import get_template_processor\nfrom superset.legacy import cast_form_data, update_time_range\nimport superset.models.core as models\nfrom superset.models.sql_lab import Query\nfrom superset.models.user_attributes import UserAttribute\nfrom superset.sql_parse import ParsedQuery\nfrom superset.utils import core as utils\nfrom superset.utils import dashboard_import_export\nfrom superset.utils.dates import now_as_float\nfrom .base import (\n api, BaseSupersetView,\n check_ownership,\n CsvResponse, data_payload_response, DeleteMixin, generate_download_headers,\n get_error_msg, handle_api_exception, json_error_response, json_success,\n SupersetFilter, SupersetModelView, YamlExportMixin,\n)\nfrom .utils import bootstrap_user_data\n\nconfig = app.config\nstats_logger = config.get('STATS_LOGGER')\nlog_this = models.Log.log_this\nDAR = models.DatasourceAccessRequest\nQueryStatus = utils.QueryStatus\n\n\nALL_DATASOURCE_ACCESS_ERR = __(\n 'This endpoint requires the `all_datasource_access` permission')\nDATASOURCE_MISSING_ERR = __('The data source seems to have been deleted')\nACCESS_REQUEST_MISSING_ERR = __(\n 'The access requests seem to have been deleted')\nUSER_MISSING_ERR = __('The user seems to have been deleted')\n\nFORM_DATA_KEY_BLACKLIST = []\nif not config.get('ENABLE_JAVASCRIPT_CONTROLS'):\n FORM_DATA_KEY_BLACKLIST = [\n 'js_tooltip',\n 'js_onclick_href',\n 'js_data_mutator',\n ]\n\n\ndef get_database_access_error_msg(database_name):\n return __('This view requires the database %(name)s or '\n '`all_datasource_access` permission', name=database_name)\n\n\ndef is_owner(obj, user):\n \"\"\" Check if user is owner of the slice \"\"\"\n return obj and user in obj.owners\n\n\nSQLTable = Table(\n 'tables',\n Model.metadata, # pylint: disable=no-member\n Column('id', Integer, primary_key=True),\n Column('database_id', Integer, ForeignKey('dbs.id')),\n extend_existing=True)\n\n\nclass SliceFilter(SupersetFilter):\n def apply(self, query, func): # noqa\n if security_manager.all_datasource_access():\n return query\n\n # TODO(bogdan): add `schema_access` support here\n datasource_perms = self.get_view_menus('datasource_access')\n query = (\n query.outerjoin(SQLTable, self.model.datasource_id == SQLTable.c.id)\n .outerjoin(models.Database, models.Database.id == SQLTable.c.database_id)\n .filter(or_(\n models.Database.perm.in_(datasource_perms),\n self.model.perm.in_(datasource_perms),\n ))\n )\n return query\n\n\nclass DashboardFilter(SupersetFilter):\n\n \"\"\"List dashboards for which users have access to at least one slice or are owners\"\"\"\n\n def apply(self, query, func): # noqa\n if security_manager.all_datasource_access():\n return query\n Slice = models.Slice # noqa\n Dash = models.Dashboard # noqa\n User = security_manager.user_model\n # TODO(bogdan): add `schema_access` support here\n datasource_perms = self.get_view_menus('datasource_access')\n slice_ids_qry = (\n db.session\n .query(Slice.id)\n .outerjoin(SQLTable, Slice.datasource_id == SQLTable.c.id)\n .outerjoin(models.Database, models.Database.id == SQLTable.c.database_id)\n .filter(or_(\n models.Database.perm.in_(datasource_perms),\n Slice.perm.in_(datasource_perms),\n ))\n )\n owner_ids_qry = (\n db.session\n .query(Dash.id)\n .join(Dash.owners)\n .filter(User.id == User.get_user_id())\n )\n query = query.filter(\n or_(Dash.id.in_(\n db.session.query(Dash.id)\n .distinct()\n .join(Dash.slices)\n .filter(Slice.id.in_(slice_ids_qry)),\n ), Dash.id.in_(owner_ids_qry)),\n )\n return query\n\n\nclass DatabaseView(SupersetModelView, DeleteMixin, YamlExportMixin): # noqa\n datamodel = SQLAInterface(models.Database)\n\n list_title = _('Databases')\n show_title = _('Show Database')\n add_title = _('Add Database')\n edit_title = _('Edit Database')\n\n list_columns = [\n 'database_name', 'backend', 'allow_run_async',\n 'allow_dml', 'allow_csv_upload', 'expose_in_sqllab', 'creator', 'modified']\n order_columns = [\n 'database_name', 'allow_run_async', 'allow_dml',\n 'modified', 'allow_csv_upload', 'expose_in_sqllab',\n ]\n add_columns = [\n 'database_name', 'sqlalchemy_uri', 'cache_timeout', 'expose_in_sqllab',\n 'allow_run_async', 'allow_csv_upload',\n 'allow_ctas', 'allow_dml', 'force_ctas_schema', 'impersonate_user',\n 'allow_multi_schema_metadata_fetch', 'extra',\n ]\n search_exclude_columns = (\n 'password', 'tables', 'created_by', 'changed_by', 'queries',\n 'saved_queries')\n edit_columns = add_columns\n show_columns = [\n 'tables',\n 'cache_timeout',\n 'extra',\n 'database_name',\n 'sqlalchemy_uri',\n 'perm',\n 'created_by',\n 'created_on',\n 'changed_by',\n 'changed_on',\n ]\n add_template = 'superset/models/database/add.html'\n edit_template = 'superset/models/database/edit.html'\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'sqlalchemy_uri': utils.markdown(\n 'Refer to the '\n '[SqlAlchemy docs]'\n '(http://docs.sqlalchemy.org/en/rel_1_2/core/engines.html#'\n 'database-urls) '\n 'for more information on how to structure your URI.', True),\n 'expose_in_sqllab': _('Expose this DB in SQL Lab'),\n 'allow_run_async': _(\n 'Operate the database in asynchronous mode, meaning '\n 'that the queries are executed on remote workers as opposed '\n 'to on the web server itself. '\n 'This assumes that you have a Celery worker setup as well '\n 'as a results backend. Refer to the installation docs '\n 'for more information.'),\n 'allow_ctas': _('Allow CREATE TABLE AS option in SQL Lab'),\n 'allow_dml': _(\n 'Allow users to run non-SELECT statements '\n '(UPDATE, DELETE, CREATE, ...) '\n 'in SQL Lab'),\n 'force_ctas_schema': _(\n 'When allowing CREATE TABLE AS option in SQL Lab, '\n 'this option forces the table to be created in this schema'),\n 'extra': utils.markdown(\n 'JSON string containing extra configuration elements.<br/>'\n '1. The ``engine_params`` object gets unpacked into the '\n '[sqlalchemy.create_engine]'\n '(http://docs.sqlalchemy.org/en/latest/core/engines.html#'\n 'sqlalchemy.create_engine) call, while the ``metadata_params`` '\n 'gets unpacked into the [sqlalchemy.MetaData]'\n '(http://docs.sqlalchemy.org/en/rel_1_0/core/metadata.html'\n '#sqlalchemy.schema.MetaData) call.<br/>'\n '2. The ``metadata_cache_timeout`` is a cache timeout setting '\n 'in seconds for metadata fetch of this database. Specify it as '\n '**\"metadata_cache_timeout\": {\"schema_cache_timeout\": 600, '\n '\"table_cache_timeout\": 600}**. '\n 'If unset, cache will not be enabled for the functionality. '\n 'A timeout of 0 indicates that the cache never expires.<br/>'\n '3. The ``schemas_allowed_for_csv_upload`` is a comma separated list '\n 'of schemas that CSVs are allowed to upload to. '\n 'Specify it as **\"schemas_allowed_for_csv_upload\": '\n '[\"public\", \"csv_upload\"]**. '\n 'If database flavor does not support schema or any schema is allowed '\n 'to be accessed, just leave the list empty', True),\n 'impersonate_user': _(\n 'If Presto, all the queries in SQL Lab are going to be executed as the '\n 'currently logged on user who must have permission to run them.<br/>'\n 'If Hive and hive.server2.enable.doAs is enabled, will run the queries as '\n 'service account, but impersonate the currently logged on user '\n 'via hive.server2.proxy.user property.'),\n 'allow_multi_schema_metadata_fetch': _(\n 'Allow SQL Lab to fetch a list of all tables and all views across '\n 'all database schemas. For large data warehouse with thousands of '\n 'tables, this can be expensive and put strain on the system.'),\n 'cache_timeout': _(\n 'Duration (in seconds) of the caching timeout for charts of this database. '\n 'A timeout of 0 indicates that the cache never expires. '\n 'Note this defaults to the global timeout if undefined.'),\n 'allow_csv_upload': _(\n 'If selected, please set the schemas allowed for csv upload in Extra.'),\n }\n label_columns = {\n 'expose_in_sqllab': _('Expose in SQL Lab'),\n 'allow_ctas': _('Allow CREATE TABLE AS'),\n 'allow_dml': _('Allow DML'),\n 'force_ctas_schema': _('CTAS Schema'),\n 'database_name': _('Database'),\n 'creator': _('Creator'),\n 'changed_on_': _('Last Changed'),\n 'sqlalchemy_uri': _('SQLAlchemy URI'),\n 'cache_timeout': _('Chart Cache Timeout'),\n 'extra': _('Extra'),\n 'allow_run_async': _('Asynchronous Query Execution'),\n 'impersonate_user': _('Impersonate the logged on user'),\n 'allow_csv_upload': _('Allow Csv Upload'),\n 'modified': _('Modified'),\n 'allow_multi_schema_metadata_fetch': _('Allow Multi Schema Metadata Fetch'),\n 'backend': _('Backend'),\n }\n\n def pre_add(self, db):\n self.check_extra(db)\n db.set_sqlalchemy_uri(db.sqlalchemy_uri)\n security_manager.merge_perm('database_access', db.perm)\n # adding a new database we always want to force refresh schema list\n for schema in db.all_schema_names():\n security_manager.merge_perm(\n 'schema_access', security_manager.get_schema_perm(db, schema))\n\n def pre_update(self, db):\n self.pre_add(db)\n\n def pre_delete(self, obj):\n if obj.tables:\n raise SupersetException(Markup(\n 'Cannot delete a database that has tables attached. '\n \"Here's the list of associated tables: \" +\n ', '.join('{}'.format(o) for o in obj.tables)))\n\n def _delete(self, pk):\n DeleteMixin._delete(self, pk)\n\n def check_extra(self, db):\n # this will check whether json.loads(extra) can succeed\n try:\n extra = db.get_extra()\n except Exception as e:\n raise Exception('Extra field cannot be decoded by JSON. {}'.format(str(e)))\n\n # this will check whether 'metadata_params' is configured correctly\n metadata_signature = inspect.signature(MetaData)\n for key in extra.get('metadata_params', {}):\n if key not in metadata_signature.parameters:\n raise Exception('The metadata_params in Extra field '\n 'is not configured correctly. The key '\n '{} is invalid.'.format(key))\n\n\nappbuilder.add_link(\n 'Import Dashboards',\n label=__('Import Dashboards'),\n href='/superset/import_dashboards',\n icon='fa-cloud-upload',\n category='Manage',\n category_label=__('Manage'),\n category_icon='fa-wrench')\n\n\nappbuilder.add_view(\n DatabaseView,\n 'Databases',\n label=__('Databases'),\n icon='fa-database',\n category='Sources',\n category_label=__('Sources'),\n category_icon='fa-database')\n\n\nclass DatabaseAsync(DatabaseView):\n list_columns = [\n 'id', 'database_name',\n 'expose_in_sqllab', 'allow_ctas', 'force_ctas_schema',\n 'allow_run_async', 'allow_dml',\n 'allow_multi_schema_metadata_fetch', 'allow_csv_upload',\n 'allows_subquery', 'backend',\n ]\n\n\nappbuilder.add_view_no_menu(DatabaseAsync)\n\n\nclass CsvToDatabaseView(SimpleFormView):\n form = CsvToDatabaseForm\n form_template = 'superset/form_view/csv_to_database_view/edit.html'\n form_title = _('CSV to Database configuration')\n add_columns = ['database', 'schema', 'table_name']\n\n def form_get(self, form):\n form.sep.data = ','\n form.header.data = 0\n form.mangle_dupe_cols.data = True\n form.skipinitialspace.data = False\n form.skip_blank_lines.data = True\n form.infer_datetime_format.data = True\n form.decimal.data = '.'\n form.if_exists.data = 'fail'\n\n def form_post(self, form):\n database = form.con.data\n schema_name = form.schema.data or ''\n\n if not self.is_schema_allowed(database, schema_name):\n message = _('Database \"{0}\" Schema \"{1}\" is not allowed for csv uploads. '\n 'Please contact Superset Admin'.format(database.database_name,\n schema_name))\n flash(message, 'danger')\n return redirect('/csvtodatabaseview/form')\n\n csv_file = form.csv_file.data\n form.csv_file.data.filename = secure_filename(form.csv_file.data.filename)\n csv_filename = form.csv_file.data.filename\n path = os.path.join(config['UPLOAD_FOLDER'], csv_filename)\n try:\n utils.ensure_path_exists(config['UPLOAD_FOLDER'])\n csv_file.save(path)\n table = SqlaTable(table_name=form.name.data)\n table.database = form.data.get('con')\n table.database_id = table.database.id\n table.database.db_engine_spec.create_table_from_csv(form, table)\n except Exception as e:\n try:\n os.remove(path)\n except OSError:\n pass\n message = 'Table name {} already exists. Please pick another'.format(\n form.name.data) if isinstance(e, IntegrityError) else str(e)\n flash(\n message,\n 'danger')\n stats_logger.incr('failed_csv_upload')\n return redirect('/csvtodatabaseview/form')\n\n os.remove(path)\n # Go back to welcome page / splash screen\n db_name = table.database.database_name\n message = _('CSV file \"{0}\" uploaded to table \"{1}\" in '\n 'database \"{2}\"'.format(csv_filename,\n form.name.data,\n db_name))\n flash(message, 'info')\n stats_logger.incr('successful_csv_upload')\n return redirect('/tablemodelview/list/')\n\n def is_schema_allowed(self, database, schema):\n if not database.allow_csv_upload:\n return False\n schemas = database.get_schema_access_for_csv_upload()\n if schemas:\n return schema in schemas\n return (security_manager.database_access(database) or\n security_manager.all_datasource_access())\n\n\nappbuilder.add_view_no_menu(CsvToDatabaseView)\n\n\nclass DatabaseTablesAsync(DatabaseView):\n list_columns = ['id', 'all_table_names_in_database', 'all_schema_names']\n\n\nappbuilder.add_view_no_menu(DatabaseTablesAsync)\n\n\nif config.get('ENABLE_ACCESS_REQUEST'):\n class AccessRequestsModelView(SupersetModelView, DeleteMixin):\n datamodel = SQLAInterface(DAR)\n list_columns = [\n 'username', 'user_roles', 'datasource_link',\n 'roles_with_datasource', 'created_on']\n order_columns = ['created_on']\n base_order = ('changed_on', 'desc')\n label_columns = {\n 'username': _('User'),\n 'user_roles': _('User Roles'),\n 'database': _('Database URL'),\n 'datasource_link': _('Datasource'),\n 'roles_with_datasource': _('Roles to grant'),\n 'created_on': _('Created On'),\n }\n\n appbuilder.add_view(\n AccessRequestsModelView,\n 'Access requests',\n label=__('Access requests'),\n category='Security',\n category_label=__('Security'),\n icon='fa-table')\n\n\nclass SliceModelView(SupersetModelView, DeleteMixin): # noqa\n route_base = '/chart'\n datamodel = SQLAInterface(models.Slice)\n\n list_title = _('Charts')\n show_title = _('Show Chart')\n add_title = _('Add Chart')\n edit_title = _('Edit Chart')\n\n can_add = False\n label_columns = {\n 'datasource_link': _('Datasource'),\n }\n search_columns = (\n 'slice_name', 'description', 'viz_type', 'datasource_name', 'owners',\n )\n list_columns = [\n 'slice_link', 'viz_type', 'datasource_link', 'creator', 'modified']\n order_columns = ['viz_type', 'datasource_link', 'modified']\n edit_columns = [\n 'slice_name', 'description', 'viz_type', 'owners', 'dashboards',\n 'params', 'cache_timeout']\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'description': Markup(\n 'The content here can be displayed as widget headers in the '\n 'dashboard view. Supports '\n '<a href=\"https://daringfireball.net/projects/markdown/\"\">'\n 'markdown</a>'),\n 'params': _(\n 'These parameters are generated dynamically when clicking '\n 'the save or overwrite button in the explore view. This JSON '\n 'object is exposed here for reference and for power users who may '\n 'want to alter specific parameters.',\n ),\n 'cache_timeout': _(\n 'Duration (in seconds) of the caching timeout for this chart. '\n 'Note this defaults to the datasource/table timeout if undefined.'),\n }\n base_filters = [['id', SliceFilter, lambda: []]]\n label_columns = {\n 'cache_timeout': _('Cache Timeout'),\n 'creator': _('Creator'),\n 'dashboards': _('Dashboards'),\n 'datasource_link': _('Datasource'),\n 'description': _('Description'),\n 'modified': _('Last Modified'),\n 'owners': _('Owners'),\n 'params': _('Parameters'),\n 'slice_link': _('Chart'),\n 'slice_name': _('Name'),\n 'table': _('Table'),\n 'viz_type': _('Visualization Type'),\n }\n\n def pre_add(self, obj):\n utils.validate_json(obj.params)\n\n def pre_update(self, obj):\n utils.validate_json(obj.params)\n check_ownership(obj)\n\n def pre_delete(self, obj):\n check_ownership(obj)\n\n @expose('/add', methods=['GET', 'POST'])\n @has_access\n def add(self):\n datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [\n {'value': str(d.id) + '__' + d.type, 'label': repr(d)}\n for d in datasources\n ]\n return self.render_template(\n 'superset/add_slice.html',\n bootstrap_data=json.dumps({\n 'datasources': sorted(datasources, key=lambda d: d['label']),\n }),\n )\n\n\nappbuilder.add_view(\n SliceModelView,\n 'Charts',\n label=__('Charts'),\n icon='fa-bar-chart',\n category='',\n category_icon='')\n\n\nclass SliceAsync(SliceModelView): # noqa\n route_base = '/sliceasync'\n list_columns = [\n 'id', 'slice_link', 'viz_type', 'slice_name',\n 'creator', 'modified', 'icons']\n label_columns = {\n 'icons': ' ',\n 'slice_link': _('Chart'),\n }\n\n\nappbuilder.add_view_no_menu(SliceAsync)\n\n\nclass SliceAddView(SliceModelView): # noqa\n route_base = '/sliceaddview'\n list_columns = [\n 'id', 'slice_name', 'slice_url', 'edit_url', 'viz_type', 'params',\n 'description', 'description_markeddown', 'datasource_id', 'datasource_type',\n 'datasource_name_text', 'datasource_link',\n 'owners', 'modified', 'changed_on']\n\n\nappbuilder.add_view_no_menu(SliceAddView)\n\n\nclass DashboardModelView(SupersetModelView, DeleteMixin): # noqa\n route_base = '/dashboard'\n datamodel = SQLAInterface(models.Dashboard)\n\n list_title = _('Dashboards')\n show_title = _('Show Dashboard')\n add_title = _('Add Dashboard')\n edit_title = _('Edit Dashboard')\n\n list_columns = ['dashboard_link', 'creator', 'modified']\n order_columns = ['modified']\n edit_columns = [\n 'dashboard_title', 'slug', 'owners', 'position_json', 'css',\n 'json_metadata']\n show_columns = edit_columns + ['table_names', 'slices']\n search_columns = ('dashboard_title', 'slug', 'owners')\n add_columns = edit_columns\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'position_json': _(\n 'This json object describes the positioning of the widgets in '\n 'the dashboard. It is dynamically generated when adjusting '\n 'the widgets size and positions by using drag & drop in '\n 'the dashboard view'),\n 'css': _(\n 'The CSS for individual dashboards can be altered here, or '\n 'in the dashboard view where changes are immediately '\n 'visible'),\n 'slug': _('To get a readable URL for your dashboard'),\n 'json_metadata': _(\n 'This JSON object is generated dynamically when clicking '\n 'the save or overwrite button in the dashboard view. It '\n 'is exposed here for reference and for power users who may '\n 'want to alter specific parameters.'),\n 'owners': _('Owners is a list of users who can alter the dashboard.'),\n }\n base_filters = [['slice', DashboardFilter, lambda: []]]\n label_columns = {\n 'dashboard_link': _('Dashboard'),\n 'dashboard_title': _('Title'),\n 'slug': _('Slug'),\n 'slices': _('Charts'),\n 'owners': _('Owners'),\n 'creator': _('Creator'),\n 'modified': _('Modified'),\n 'position_json': _('Position JSON'),\n 'css': _('CSS'),\n 'json_metadata': _('JSON Metadata'),\n 'table_names': _('Underlying Tables'),\n }\n\n def pre_add(self, obj):\n obj.slug = obj.slug.strip() or None\n if obj.slug:\n obj.slug = obj.slug.replace(' ', '-')\n obj.slug = re.sub(r'[^\\w\\-]+', '', obj.slug)\n if g.user not in obj.owners:\n obj.owners.append(g.user)\n utils.validate_json(obj.json_metadata)\n utils.validate_json(obj.position_json)\n owners = [o for o in obj.owners]\n for slc in obj.slices:\n slc.owners = list(set(owners) | set(slc.owners))\n\n def pre_update(self, obj):\n check_ownership(obj)\n self.pre_add(obj)\n\n def pre_delete(self, obj):\n check_ownership(obj)\n\n @action('mulexport', __('Export'), __('Export dashboards?'), 'fa-database')\n def mulexport(self, items):\n if not isinstance(items, list):\n items = [items]\n ids = ''.join('&id={}'.format(d.id) for d in items)\n return redirect(\n '/dashboard/export_dashboards_form?{}'.format(ids[1:]))\n\n @log_this\n @has_access\n @expose('/export_dashboards_form')\n def download_dashboards(self):\n if request.args.get('action') == 'go':\n ids = request.args.getlist('id')\n return Response(\n models.Dashboard.export_dashboards(ids),\n headers=generate_download_headers('json'),\n mimetype='application/text')\n return self.render_template(\n 'superset/export_dashboards.html',\n dashboards_url='/dashboard/list',\n )\n\n\nappbuilder.add_view(\n DashboardModelView,\n 'Dashboards',\n label=__('Dashboards'),\n icon='fa-dashboard',\n category='',\n category_icon='')\n\n\nclass DashboardModelViewAsync(DashboardModelView): # noqa\n route_base = '/dashboardasync'\n list_columns = [\n 'id', 'dashboard_link', 'creator', 'modified', 'dashboard_title',\n 'changed_on', 'url', 'changed_by_name',\n ]\n label_columns = {\n 'dashboard_link': _('Dashboard'),\n 'dashboard_title': _('Title'),\n 'creator': _('Creator'),\n 'modified': _('Modified'),\n }\n\n\nappbuilder.add_view_no_menu(DashboardModelViewAsync)\n\n\nclass DashboardAddView(DashboardModelView): # noqa\n route_base = '/dashboardaddview'\n list_columns = [\n 'id', 'dashboard_link', 'creator', 'modified', 'dashboard_title',\n 'changed_on', 'url', 'changed_by_name',\n ]\n show_columns = list(set(DashboardModelView.edit_columns + list_columns))\n\n\nappbuilder.add_view_no_menu(DashboardAddView)\n\n\nclass LogModelView(SupersetModelView):\n datamodel = SQLAInterface(models.Log)\n\n list_title = _('Logs')\n show_title = _('Show Log')\n add_title = _('Add Log')\n edit_title = _('Edit Log')\n\n list_columns = ('user', 'action', 'dttm')\n edit_columns = ('user', 'action', 'dttm', 'json')\n base_order = ('dttm', 'desc')\n label_columns = {\n 'user': _('User'),\n 'action': _('Action'),\n 'dttm': _('dttm'),\n 'json': _('JSON'),\n }\n\n\nappbuilder.add_view(\n LogModelView,\n 'Action Log',\n label=__('Action Log'),\n category='Security',\n category_label=__('Security'),\n icon='fa-list-ol')\n\n\[email protected]('/health')\ndef health():\n return 'OK'\n\n\[email protected]('/healthcheck')\ndef healthcheck():\n return 'OK'\n\n\[email protected]('/ping')\ndef ping():\n return 'OK'\n\n\nclass KV(BaseSupersetView):\n\n \"\"\"Used for storing and retrieving key value pairs\"\"\"\n\n @log_this\n @has_access_api\n @expose('/store/', methods=['POST'])\n def store(self):\n try:\n value = request.form.get('data')\n obj = models.KeyValue(value=value)\n db.session.add(obj)\n db.session.commit()\n except Exception as e:\n return json_error_response(e)\n return Response(\n json.dumps({'id': obj.id}),\n status=200)\n\n @log_this\n @has_access_api\n @expose('/<key_id>/', methods=['GET'])\n def get_value(self, key_id):\n kv = None\n try:\n kv = db.session.query(models.KeyValue).filter_by(id=key_id).one()\n except Exception as e:\n return json_error_response(e)\n return Response(kv.value, status=200)\n\n\nappbuilder.add_view_no_menu(KV)\n\n\nclass R(BaseSupersetView):\n\n \"\"\"used for short urls\"\"\"\n\n @log_this\n @expose('/<url_id>')\n def index(self, url_id):\n url = db.session.query(models.Url).filter_by(id=url_id).first()\n if url and url.url:\n explore_url = '//superset/explore/?'\n if url.url.startswith(explore_url):\n explore_url += f'r={url_id}'\n return redirect(explore_url[1:])\n else:\n return redirect(url.url[1:])\n else:\n flash('URL to nowhere...', 'danger')\n return redirect('/')\n\n @log_this\n @has_access_api\n @expose('/shortner/', methods=['POST'])\n def shortner(self):\n url = request.form.get('data')\n obj = models.Url(url=url)\n db.session.add(obj)\n db.session.commit()\n return Response(\n '{scheme}://{request.headers[Host]}/r/{obj.id}'.format(\n scheme=request.scheme, request=request, obj=obj),\n mimetype='text/plain')\n\n\nappbuilder.add_view_no_menu(R)\n\n\nclass Superset(BaseSupersetView):\n \"\"\"The base views for Superset!\"\"\"\n @has_access_api\n @expose('/datasources/')\n def datasources(self):\n datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [o.short_data for o in datasources if o.short_data.get('name')]\n datasources = sorted(datasources, key=lambda o: o['name'])\n return self.json_response(datasources)\n\n @has_access_api\n @expose('/override_role_permissions/', methods=['POST'])\n def override_role_permissions(self):\n \"\"\"Updates the role with the give datasource permissions.\n\n Permissions not in the request will be revoked. This endpoint should\n be available to admins only. Expects JSON in the format:\n {\n 'role_name': '{role_name}',\n 'database': [{\n 'datasource_type': '{table|druid}',\n 'name': '{database_name}',\n 'schema': [{\n 'name': '{schema_name}',\n 'datasources': ['{datasource name}, {datasource name}']\n }]\n }]\n }\n \"\"\"\n data = request.get_json(force=True)\n role_name = data['role_name']\n databases = data['database']\n\n db_ds_names = set()\n for dbs in databases:\n for schema in dbs['schema']:\n for ds_name in schema['datasources']:\n fullname = utils.get_datasource_full_name(\n dbs['name'], ds_name, schema=schema['name'])\n db_ds_names.add(fullname)\n\n existing_datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [\n d for d in existing_datasources if d.full_name in db_ds_names]\n role = security_manager.find_role(role_name)\n # remove all permissions\n role.permissions = []\n # grant permissions to the list of datasources\n granted_perms = []\n for datasource in datasources:\n view_menu_perm = security_manager.find_permission_view_menu(\n view_menu_name=datasource.perm,\n permission_name='datasource_access')\n # prevent creating empty permissions\n if view_menu_perm and view_menu_perm.view_menu:\n role.permissions.append(view_menu_perm)\n granted_perms.append(view_menu_perm.view_menu.name)\n db.session.commit()\n return self.json_response({\n 'granted': granted_perms,\n 'requested': list(db_ds_names),\n }, status=201)\n\n @log_this\n @has_access\n @expose('/request_access/')\n def request_access(self):\n datasources = set()\n dashboard_id = request.args.get('dashboard_id')\n if dashboard_id:\n dash = (\n db.session.query(models.Dashboard)\n .filter_by(id=int(dashboard_id))\n .one()\n )\n datasources |= dash.datasources\n datasource_id = request.args.get('datasource_id')\n datasource_type = request.args.get('datasource_type')\n if datasource_id:\n ds_class = ConnectorRegistry.sources.get(datasource_type)\n datasource = (\n db.session.query(ds_class)\n .filter_by(id=int(datasource_id))\n .one()\n )\n datasources.add(datasource)\n\n has_access = all(\n (\n datasource and security_manager.datasource_access(datasource)\n for datasource in datasources\n ))\n if has_access:\n return redirect('/superset/dashboard/{}'.format(dashboard_id))\n\n if request.args.get('action') == 'go':\n for datasource in datasources:\n access_request = DAR(\n datasource_id=datasource.id,\n datasource_type=datasource.type)\n db.session.add(access_request)\n db.session.commit()\n flash(__('Access was requested'), 'info')\n return redirect('/')\n\n return self.render_template(\n 'superset/request_access.html',\n datasources=datasources,\n datasource_names=', '.join([o.name for o in datasources]),\n )\n\n @log_this\n @has_access\n @expose('/approve')\n def approve(self):\n def clean_fulfilled_requests(session):\n for r in session.query(DAR).all():\n datasource = ConnectorRegistry.get_datasource(\n r.datasource_type, r.datasource_id, session)\n if not datasource or \\\n security_manager.datasource_access(datasource):\n # datasource does not exist anymore\n session.delete(r)\n session.commit()\n datasource_type = request.args.get('datasource_type')\n datasource_id = request.args.get('datasource_id')\n created_by_username = request.args.get('created_by')\n role_to_grant = request.args.get('role_to_grant')\n role_to_extend = request.args.get('role_to_extend')\n\n session = db.session\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, session)\n\n if not datasource:\n flash(DATASOURCE_MISSING_ERR, 'alert')\n return json_error_response(DATASOURCE_MISSING_ERR)\n\n requested_by = security_manager.find_user(username=created_by_username)\n if not requested_by:\n flash(USER_MISSING_ERR, 'alert')\n return json_error_response(USER_MISSING_ERR)\n\n requests = (\n session.query(DAR)\n .filter(\n DAR.datasource_id == datasource_id,\n DAR.datasource_type == datasource_type,\n DAR.created_by_fk == requested_by.id)\n .all()\n )\n\n if not requests:\n flash(ACCESS_REQUEST_MISSING_ERR, 'alert')\n return json_error_response(ACCESS_REQUEST_MISSING_ERR)\n\n # check if you can approve\n if (\n security_manager.all_datasource_access() or\n check_ownership(datasource, raise_if_false=False)\n ):\n # can by done by admin only\n if role_to_grant:\n role = security_manager.find_role(role_to_grant)\n requested_by.roles.append(role)\n msg = __(\n '%(user)s was granted the role %(role)s that gives access '\n 'to the %(datasource)s',\n user=requested_by.username,\n role=role_to_grant,\n datasource=datasource.full_name)\n utils.notify_user_about_perm_udate(\n g.user, requested_by, role, datasource,\n 'email/role_granted.txt', app.config)\n flash(msg, 'info')\n\n if role_to_extend:\n perm_view = security_manager.find_permission_view_menu(\n 'email/datasource_access', datasource.perm)\n role = security_manager.find_role(role_to_extend)\n security_manager.add_permission_role(role, perm_view)\n msg = __('Role %(r)s was extended to provide the access to '\n 'the datasource %(ds)s', r=role_to_extend,\n ds=datasource.full_name)\n utils.notify_user_about_perm_udate(\n g.user, requested_by, role, datasource,\n 'email/role_extended.txt', app.config)\n flash(msg, 'info')\n clean_fulfilled_requests(session)\n else:\n flash(__('You have no permission to approve this request'),\n 'danger')\n return redirect('/accessrequestsmodelview/list/')\n for r in requests:\n session.delete(r)\n session.commit()\n return redirect('/accessrequestsmodelview/list/')\n\n def get_form_data(self, slice_id=None, use_slice_data=False):\n form_data = {}\n post_data = request.form.get('form_data')\n request_args_data = request.args.get('form_data')\n # Supporting POST\n if post_data:\n form_data.update(json.loads(post_data))\n # request params can overwrite post body\n if request_args_data:\n form_data.update(json.loads(request_args_data))\n\n url_id = request.args.get('r')\n if url_id:\n saved_url = db.session.query(models.Url).filter_by(id=url_id).first()\n if saved_url:\n url_str = parse.unquote_plus(\n saved_url.url.split('?')[1][10:], encoding='utf-8', errors=None)\n url_form_data = json.loads(url_str)\n # allow form_date in request override saved url\n url_form_data.update(form_data)\n form_data = url_form_data\n\n if request.args.get('viz_type'):\n # Converting old URLs\n form_data = cast_form_data(form_data)\n\n form_data = {\n k: v\n for k, v in form_data.items()\n if k not in FORM_DATA_KEY_BLACKLIST\n }\n\n # When a slice_id is present, load from DB and override\n # the form_data from the DB with the other form_data provided\n slice_id = form_data.get('slice_id') or slice_id\n slc = None\n\n # Check if form data only contains slice_id\n contains_only_slc_id = not any(key != 'slice_id' for key in form_data)\n\n # Include the slice_form_data if request from explore or slice calls\n # or if form_data only contains slice_id\n if slice_id and (use_slice_data or contains_only_slc_id):\n slc = db.session.query(models.Slice).filter_by(id=slice_id).one_or_none()\n if slc:\n slice_form_data = slc.form_data.copy()\n slice_form_data.update(form_data)\n form_data = slice_form_data\n\n update_time_range(form_data)\n\n return form_data, slc\n\n def get_viz(\n self,\n slice_id=None,\n form_data=None,\n datasource_type=None,\n datasource_id=None,\n force=False,\n ):\n if slice_id:\n slc = (\n db.session.query(models.Slice)\n .filter_by(id=slice_id)\n .one()\n )\n return slc.get_viz()\n else:\n viz_type = form_data.get('viz_type', 'table')\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n viz_obj = viz.viz_types[viz_type](\n datasource,\n form_data=form_data,\n force=force,\n )\n return viz_obj\n\n @has_access\n @expose('/slice/<slice_id>/')\n def slice(self, slice_id):\n form_data, slc = self.get_form_data(slice_id, use_slice_data=True)\n if not slc:\n abort(404)\n endpoint = '/superset/explore/?form_data={}'.format(\n parse.quote(json.dumps({'slice_id': slice_id})),\n )\n if request.args.get('standalone') == 'true':\n endpoint += '&standalone=true'\n return redirect(endpoint)\n\n def get_query_string_response(self, viz_obj):\n query = None\n try:\n query_obj = viz_obj.query_obj()\n if query_obj:\n query = viz_obj.datasource.get_query_str(query_obj)\n except Exception as e:\n logging.exception(e)\n return json_error_response(e)\n\n if query_obj and query_obj['prequeries']:\n query_obj['prequeries'].append(query)\n query = ';\\n\\n'.join(query_obj['prequeries'])\n if query:\n query += ';'\n else:\n query = 'No query.'\n\n return self.json_response({\n 'query': query,\n 'language': viz_obj.datasource.query_language,\n })\n\n def get_raw_results(self, viz_obj):\n return self.json_response({\n 'data': viz_obj.get_df_payload()['df'].to_dict('records'),\n })\n\n def get_samples(self, viz_obj):\n return self.json_response({\n 'data': viz_obj.get_samples(),\n })\n\n def generate_json(\n self, datasource_type, datasource_id, form_data,\n csv=False, query=False, force=False, results=False,\n samples=False,\n ):\n viz_obj = self.get_viz(\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data,\n force=force,\n )\n security_manager.assert_datasource_permission(viz_obj.datasource)\n\n if csv:\n return CsvResponse(\n viz_obj.get_csv(),\n status=200,\n headers=generate_download_headers('csv'),\n mimetype='application/csv')\n\n if query:\n return self.get_query_string_response(viz_obj)\n\n if results:\n return self.get_raw_results(viz_obj)\n\n if samples:\n return self.get_samples(viz_obj)\n\n payload = viz_obj.get_payload()\n return data_payload_response(*viz_obj.payload_json_and_has_error(payload))\n\n @log_this\n @api\n @has_access_api\n @expose('/slice_json/<slice_id>')\n def slice_json(self, slice_id):\n form_data, slc = self.get_form_data(slice_id, use_slice_data=True)\n datasource_type = slc.datasource.type\n datasource_id = slc.datasource.id\n\n return self.generate_json(datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data)\n\n @log_this\n @api\n @has_access_api\n @expose('/annotation_json/<layer_id>')\n def annotation_json(self, layer_id):\n form_data = self.get_form_data()[0]\n form_data['layer_id'] = layer_id\n form_data['filters'] = [{'col': 'layer_id',\n 'op': '==',\n 'val': layer_id}]\n datasource = AnnotationDatasource()\n viz_obj = viz.viz_types['table'](\n datasource,\n form_data=form_data,\n force=False,\n )\n payload = viz_obj.get_payload()\n return data_payload_response(*viz_obj.payload_json_and_has_error(payload))\n\n @log_this\n @api\n @has_access_api\n @handle_api_exception\n @expose('/explore_json/<datasource_type>/<datasource_id>/', methods=['GET', 'POST'])\n @expose('/explore_json/', methods=['GET', 'POST'])\n def explore_json(self, datasource_type=None, datasource_id=None):\n \"\"\"Serves all request that GET or POST form_data\n\n This endpoint evolved to be the entry point of many different\n requests that GETs or POSTs a form_data.\n\n `self.generate_json` receives this input and returns different\n payloads based on the request args in the first block\n\n TODO: break into one endpoint for each return shape\"\"\"\n csv = request.args.get('csv') == 'true'\n query = request.args.get('query') == 'true'\n results = request.args.get('results') == 'true'\n samples = request.args.get('samples') == 'true'\n force = request.args.get('force') == 'true'\n\n form_data = self.get_form_data()[0]\n datasource_id, datasource_type = self.datasource_info(\n datasource_id, datasource_type, form_data)\n\n return self.generate_json(\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data,\n csv=csv,\n query=query,\n results=results,\n force=force,\n samples=samples,\n )\n\n @log_this\n @has_access\n @expose('/import_dashboards', methods=['GET', 'POST'])\n def import_dashboards(self):\n \"\"\"Overrides the dashboards using json instances from the file.\"\"\"\n f = request.files.get('file')\n if request.method == 'POST' and f:\n dashboard_import_export.import_dashboards(db.session, f.stream)\n return redirect('/dashboard/list/')\n return self.render_template('superset/import_dashboards.html')\n\n @log_this\n @has_access\n @expose('/explorev2/<datasource_type>/<datasource_id>/')\n def explorev2(self, datasource_type, datasource_id):\n \"\"\"Deprecated endpoint, here for backward compatibility of urls\"\"\"\n return redirect(url_for(\n 'Superset.explore',\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n **request.args))\n\n @staticmethod\n def datasource_info(datasource_id, datasource_type, form_data):\n \"\"\"Compatibility layer for handling of datasource info\n\n datasource_id & datasource_type used to be passed in the URL\n directory, now they should come as part of the form_data,\n This function allows supporting both without duplicating code\"\"\"\n datasource = form_data.get('datasource', '')\n if '__' in datasource:\n datasource_id, datasource_type = datasource.split('__')\n # The case where the datasource has been deleted\n datasource_id = None if datasource_id == 'None' else datasource_id\n\n if not datasource_id:\n raise Exception(\n 'The datasource associated with this chart no longer exists')\n datasource_id = int(datasource_id)\n return datasource_id, datasource_type\n\n @log_this\n @has_access\n @expose('/explore/<datasource_type>/<datasource_id>/', methods=['GET', 'POST'])\n @expose('/explore/', methods=['GET', 'POST'])\n def explore(self, datasource_type=None, datasource_id=None):\n user_id = g.user.get_id() if g.user else None\n form_data, slc = self.get_form_data(use_slice_data=True)\n\n datasource_id, datasource_type = self.datasource_info(\n datasource_id, datasource_type, form_data)\n\n error_redirect = '/chart/list/'\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n if not datasource:\n flash(DATASOURCE_MISSING_ERR, 'danger')\n return redirect(error_redirect)\n\n if config.get('ENABLE_ACCESS_REQUEST') and (\n not security_manager.datasource_access(datasource)\n ):\n flash(\n __(security_manager.get_datasource_access_error_msg(datasource)),\n 'danger')\n return redirect(\n 'superset/request_access/?'\n f'datasource_type={datasource_type}&'\n f'datasource_id={datasource_id}&')\n\n viz_type = form_data.get('viz_type')\n if not viz_type and datasource.default_endpoint:\n return redirect(datasource.default_endpoint)\n\n # slc perms\n slice_add_perm = security_manager.can_access('can_add', 'SliceModelView')\n slice_overwrite_perm = is_owner(slc, g.user)\n slice_download_perm = security_manager.can_access(\n 'can_download', 'SliceModelView')\n\n form_data['datasource'] = str(datasource_id) + '__' + datasource_type\n\n # On explore, merge legacy and extra filters into the form data\n utils.convert_legacy_filters_into_adhoc(form_data)\n utils.merge_extra_filters(form_data)\n\n # merge request url params\n if request.method == 'GET':\n utils.merge_request_params(form_data, request.args)\n\n # handle save or overwrite\n action = request.args.get('action')\n\n if action == 'overwrite' and not slice_overwrite_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('alter this ') + _('chart'),\n status=400)\n\n if action == 'saveas' and not slice_add_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('create a ') + _('chart'),\n status=400)\n\n if action in ('saveas', 'overwrite'):\n return self.save_or_overwrite_slice(\n request.args,\n slc, slice_add_perm,\n slice_overwrite_perm,\n slice_download_perm,\n datasource_id,\n datasource_type,\n datasource.name)\n\n standalone = request.args.get('standalone') == 'true'\n bootstrap_data = {\n 'can_add': slice_add_perm,\n 'can_download': slice_download_perm,\n 'can_overwrite': slice_overwrite_perm,\n 'datasource': datasource.data,\n 'form_data': form_data,\n 'datasource_id': datasource_id,\n 'datasource_type': datasource_type,\n 'slice': slc.data if slc else None,\n 'standalone': standalone,\n 'user_id': user_id,\n 'forced_height': request.args.get('height'),\n 'common': self.common_bootsrap_payload(),\n }\n table_name = datasource.table_name \\\n if datasource_type == 'table' \\\n else datasource.datasource_name\n if slc:\n title = slc.slice_name\n else:\n title = _('Explore - %(table)s', table=table_name)\n return self.render_template(\n 'superset/basic.html',\n bootstrap_data=json.dumps(bootstrap_data),\n entry='explore',\n title=title,\n standalone_mode=standalone)\n\n @api\n @handle_api_exception\n @has_access_api\n @expose('/filter/<datasource_type>/<datasource_id>/<column>/')\n def filter(self, datasource_type, datasource_id, column):\n \"\"\"\n Endpoint to retrieve values for specified column.\n\n :param datasource_type: Type of datasource e.g. table\n :param datasource_id: Datasource id\n :param column: Column name to retrieve values for\n :return:\n \"\"\"\n # TODO: Cache endpoint by user, datasource and column\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n if not datasource:\n return json_error_response(DATASOURCE_MISSING_ERR)\n security_manager.assert_datasource_permission(datasource)\n payload = json.dumps(\n datasource.values_for_column(\n column,\n config.get('FILTER_SELECT_ROW_LIMIT', 10000),\n ),\n default=utils.json_int_dttm_ser)\n return json_success(payload)\n\n def save_or_overwrite_slice(\n self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,\n datasource_id, datasource_type, datasource_name):\n \"\"\"Save or overwrite a slice\"\"\"\n slice_name = args.get('slice_name')\n action = args.get('action')\n form_data, _ = self.get_form_data()\n\n if action in ('saveas'):\n if 'slice_id' in form_data:\n form_data.pop('slice_id') # don't save old slice_id\n slc = models.Slice(owners=[g.user] if g.user else [])\n\n slc.params = json.dumps(form_data, indent=2, sort_keys=True)\n slc.datasource_name = datasource_name\n slc.viz_type = form_data['viz_type']\n slc.datasource_type = datasource_type\n slc.datasource_id = datasource_id\n slc.slice_name = slice_name\n\n if action in ('saveas') and slice_add_perm:\n self.save_slice(slc)\n elif action == 'overwrite' and slice_overwrite_perm:\n self.overwrite_slice(slc)\n\n # Adding slice to a dashboard if requested\n dash = None\n if request.args.get('add_to_dash') == 'existing':\n dash = (\n db.session.query(models.Dashboard)\n .filter_by(id=int(request.args.get('save_to_dashboard_id')))\n .one()\n )\n\n # check edit dashboard permissions\n dash_overwrite_perm = check_ownership(dash, raise_if_false=False)\n if not dash_overwrite_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('alter this ') +\n _('dashboard'),\n status=400)\n\n flash(\n 'Slice [{}] was added to dashboard [{}]'.format(\n slc.slice_name,\n dash.dashboard_title),\n 'info')\n elif request.args.get('add_to_dash') == 'new':\n # check create dashboard permissions\n dash_add_perm = security_manager.can_access('can_add', 'DashboardModelView')\n if not dash_add_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('create a ') + _('dashboard'),\n status=400)\n\n dash = models.Dashboard(\n dashboard_title=request.args.get('new_dashboard_name'),\n owners=[g.user] if g.user else [])\n flash(\n 'Dashboard [{}] just got created and slice [{}] was added '\n 'to it'.format(\n dash.dashboard_title,\n slc.slice_name),\n 'info')\n\n if dash and slc not in dash.slices:\n dash.slices.append(slc)\n db.session.commit()\n\n response = {\n 'can_add': slice_add_perm,\n 'can_download': slice_download_perm,\n 'can_overwrite': is_owner(slc, g.user),\n 'form_data': slc.form_data,\n 'slice': slc.data,\n }\n\n if request.args.get('goto_dash') == 'true':\n response.update({'dashboard': dash.url})\n\n return json_success(json.dumps(response))\n\n def save_slice(self, slc):\n session = db.session()\n msg = _('Chart [{}] has been saved').format(slc.slice_name)\n session.add(slc)\n session.commit()\n flash(msg, 'info')\n\n def overwrite_slice(self, slc):\n session = db.session()\n session.merge(slc)\n session.commit()\n msg = _('Chart [{}] has been overwritten').format(slc.slice_name)\n flash(msg, 'info')\n\n @api\n @has_access_api\n @expose('/checkbox/<model_view>/<id_>/<attr>/<value>', methods=['GET'])\n def checkbox(self, model_view, id_, attr, value):\n \"\"\"endpoint for checking/unchecking any boolean in a sqla model\"\"\"\n modelview_to_model = {\n '{}ColumnInlineView'.format(name.capitalize()): source.column_class\n for name, source in ConnectorRegistry.sources.items()\n }\n model = modelview_to_model[model_view]\n col = db.session.query(model).filter_by(id=id_).first()\n checked = value == 'true'\n if col:\n setattr(col, attr, checked)\n if checked:\n metrics = col.get_metrics().values()\n col.datasource.add_missing_metrics(metrics)\n db.session.commit()\n return json_success('OK')\n\n @api\n @has_access_api\n @expose('/schemas/<db_id>/')\n @expose('/schemas/<db_id>/<force_refresh>/')\n def schemas(self, db_id, force_refresh='false'):\n db_id = int(db_id)\n force_refresh = force_refresh.lower() == 'true'\n database = (\n db.session\n .query(models.Database)\n .filter_by(id=db_id)\n .first()\n )\n if database:\n schemas = database.all_schema_names(\n cache=database.schema_cache_enabled,\n cache_timeout=database.schema_cache_timeout,\n force=force_refresh)\n schemas = security_manager.schemas_accessible_by_user(database, schemas)\n else:\n schemas = []\n\n return Response(\n json.dumps({'schemas': schemas}),\n mimetype='application/json')\n\n @api\n @has_access_api\n @expose('/tables/<db_id>/<schema>/<substr>/')\n @expose('/tables/<db_id>/<schema>/<substr>/<force_refresh>/')\n def tables(self, db_id, schema, substr, force_refresh='false'):\n \"\"\"Endpoint to fetch the list of tables for given database\"\"\"\n db_id = int(db_id)\n force_refresh = force_refresh.lower() == 'true'\n schema = utils.js_string_to_python(schema)\n substr = utils.js_string_to_python(substr)\n database = db.session.query(models.Database).filter_by(id=db_id).one()\n\n if schema:\n table_names = database.all_table_names_in_schema(\n schema=schema, force=force_refresh,\n cache=database.table_cache_enabled,\n cache_timeout=database.table_cache_timeout)\n view_names = database.all_view_names_in_schema(\n schema=schema, force=force_refresh,\n cache=database.table_cache_enabled,\n cache_timeout=database.table_cache_timeout)\n else:\n table_names = database.all_table_names_in_database(\n cache=True, force=False, cache_timeout=24 * 60 * 60)\n view_names = database.all_view_names_in_database(\n cache=True, force=False, cache_timeout=24 * 60 * 60)\n table_names = security_manager.accessible_by_user(database, table_names, schema)\n view_names = security_manager.accessible_by_user(database, view_names, schema)\n\n if substr:\n table_names = [tn for tn in table_names if substr in tn]\n view_names = [vn for vn in view_names if substr in vn]\n\n max_items = config.get('MAX_TABLE_NAMES') or len(table_names)\n total_items = len(table_names) + len(view_names)\n max_tables = len(table_names)\n max_views = len(view_names)\n if total_items and substr:\n max_tables = max_items * len(table_names) // total_items\n max_views = max_items * len(view_names) // total_items\n\n table_options = [{'value': tn, 'label': tn}\n for tn in table_names[:max_tables]]\n table_options.extend([{'value': vn, 'label': '[view] {}'.format(vn)}\n for vn in view_names[:max_views]])\n payload = {\n 'tableLength': len(table_names) + len(view_names),\n 'options': table_options,\n }\n return json_success(json.dumps(payload))\n\n @api\n @has_access_api\n @expose('/copy_dash/<dashboard_id>/', methods=['GET', 'POST'])\n def copy_dash(self, dashboard_id):\n \"\"\"Copy dashboard\"\"\"\n session = db.session()\n data = json.loads(request.form.get('data'))\n dash = models.Dashboard()\n original_dash = (\n session\n .query(models.Dashboard)\n .filter_by(id=dashboard_id).first())\n\n dash.owners = [g.user] if g.user else []\n dash.dashboard_title = data['dashboard_title']\n\n if data['duplicate_slices']:\n # Duplicating slices as well, mapping old ids to new ones\n old_to_new_sliceids = {}\n for slc in original_dash.slices:\n new_slice = slc.clone()\n new_slice.owners = [g.user] if g.user else []\n session.add(new_slice)\n session.flush()\n new_slice.dashboards.append(dash)\n old_to_new_sliceids['{}'.format(slc.id)] = \\\n '{}'.format(new_slice.id)\n\n # update chartId of layout entities\n # in v2_dash positions json data, chartId should be integer,\n # while in older version slice_id is string type\n for value in data['positions'].values():\n if (\n isinstance(value, dict) and value.get('meta') and\n value.get('meta').get('chartId')\n ):\n old_id = '{}'.format(value.get('meta').get('chartId'))\n new_id = int(old_to_new_sliceids[old_id])\n value['meta']['chartId'] = new_id\n else:\n dash.slices = original_dash.slices\n dash.params = original_dash.params\n\n self._set_dash_metadata(dash, data)\n session.add(dash)\n session.commit()\n dash_json = json.dumps(dash.data)\n session.close()\n return json_success(dash_json)\n\n @api\n @has_access_api\n @expose('/save_dash/<dashboard_id>/', methods=['GET', 'POST'])\n def save_dash(self, dashboard_id):\n \"\"\"Save a dashboard's metadata\"\"\"\n session = db.session()\n dash = (session\n .query(models.Dashboard)\n .filter_by(id=dashboard_id).first())\n check_ownership(dash, raise_if_false=True)\n data = json.loads(request.form.get('data'))\n self._set_dash_metadata(dash, data)\n session.merge(dash)\n session.commit()\n session.close()\n return json_success(json.dumps({'status': 'SUCCESS'}))\n\n @staticmethod\n def _set_dash_metadata(dashboard, data):\n positions = data['positions']\n # find slices in the position data\n slice_ids = []\n slice_id_to_name = {}\n for value in positions.values():\n if (\n isinstance(value, dict) and value.get('meta') and\n value.get('meta').get('chartId')\n ):\n slice_id = value.get('meta').get('chartId')\n slice_ids.append(slice_id)\n slice_id_to_name[slice_id] = value.get('meta').get('sliceName')\n\n session = db.session()\n Slice = models.Slice # noqa\n current_slices = session.query(Slice).filter(\n Slice.id.in_(slice_ids)).all()\n\n dashboard.slices = current_slices\n\n # update slice names. this assumes user has permissions to update the slice\n for slc in dashboard.slices:\n new_name = slice_id_to_name[slc.id]\n if slc.slice_name != new_name:\n slc.slice_name = new_name\n session.merge(slc)\n session.flush()\n\n # remove leading and trailing white spaces in the dumped json\n dashboard.position_json = json.dumps(\n positions, indent=None, separators=(',', ':'), sort_keys=True)\n md = dashboard.params_dict\n dashboard.css = data.get('css')\n dashboard.dashboard_title = data['dashboard_title']\n\n if 'filter_immune_slices' not in md:\n md['filter_immune_slices'] = []\n if 'timed_refresh_immune_slices' not in md:\n md['timed_refresh_immune_slices'] = []\n if 'filter_immune_slice_fields' not in md:\n md['filter_immune_slice_fields'] = {}\n md['expanded_slices'] = data['expanded_slices']\n default_filters_data = json.loads(data.get('default_filters', '{}'))\n applicable_filters = \\\n {key: v for key, v in default_filters_data.items()\n if int(key) in slice_ids}\n md['default_filters'] = json.dumps(applicable_filters)\n dashboard.json_metadata = json.dumps(md)\n\n @api\n @has_access_api\n @expose('/add_slices/<dashboard_id>/', methods=['POST'])\n def add_slices(self, dashboard_id):\n \"\"\"Add and save slices to a dashboard\"\"\"\n data = json.loads(request.form.get('data'))\n session = db.session()\n Slice = models.Slice # noqa\n dash = (\n session.query(models.Dashboard).filter_by(id=dashboard_id).first())\n check_ownership(dash, raise_if_false=True)\n new_slices = session.query(Slice).filter(\n Slice.id.in_(data['slice_ids']))\n dash.slices += new_slices\n session.merge(dash)\n session.commit()\n session.close()\n return 'SLICES ADDED'\n\n @api\n @has_access_api\n @expose('/testconn', methods=['POST', 'GET'])\n def testconn(self):\n \"\"\"Tests a sqla connection\"\"\"\n try:\n username = g.user.username if g.user is not None else None\n uri = request.json.get('uri')\n db_name = request.json.get('name')\n impersonate_user = request.json.get('impersonate_user')\n database = None\n if db_name:\n database = (\n db.session\n .query(models.Database)\n .filter_by(database_name=db_name)\n .first()\n )\n if database and uri == database.safe_sqlalchemy_uri():\n # the password-masked uri was passed\n # use the URI associated with this database\n uri = database.sqlalchemy_uri_decrypted\n\n configuration = {}\n\n if database and uri:\n url = make_url(uri)\n db_engine = models.Database.get_db_engine_spec_for_backend(\n url.get_backend_name())\n db_engine.patch()\n\n masked_url = database.get_password_masked_url_from_uri(uri)\n logging.info('Superset.testconn(). Masked URL: {0}'.format(masked_url))\n\n configuration.update(\n db_engine.get_configuration_for_impersonation(uri,\n impersonate_user,\n username),\n )\n\n engine_params = (\n request.json\n .get('extras', {})\n .get('engine_params', {}))\n connect_args = engine_params.get('connect_args')\n\n if configuration and connect_args is not None:\n connect_args['configuration'] = configuration\n\n engine = create_engine(uri, **engine_params)\n engine.connect()\n return json_success(json.dumps(engine.table_names(), indent=4))\n except Exception as e:\n logging.exception(e)\n return json_error_response((\n 'Connection failed!\\n\\n'\n 'The error message returned was:\\n{}').format(e))\n\n @api\n @has_access_api\n @expose('/recent_activity/<user_id>/', methods=['GET'])\n def recent_activity(self, user_id):\n \"\"\"Recent activity (actions) for a given user\"\"\"\n M = models # noqa\n\n if request.args.get('limit'):\n limit = int(request.args.get('limit'))\n else:\n limit = 1000\n\n qry = (\n db.session.query(M.Log, M.Dashboard, M.Slice)\n .outerjoin(\n M.Dashboard,\n M.Dashboard.id == M.Log.dashboard_id,\n )\n .outerjoin(\n M.Slice,\n M.Slice.id == M.Log.slice_id,\n )\n .filter(\n sqla.and_(\n ~M.Log.action.in_(('queries', 'shortner', 'sql_json')),\n M.Log.user_id == user_id,\n ),\n )\n .order_by(M.Log.dttm.desc())\n .limit(limit)\n )\n payload = []\n for log in qry.all():\n item_url = None\n item_title = None\n if log.Dashboard:\n item_url = log.Dashboard.url\n item_title = log.Dashboard.dashboard_title\n elif log.Slice:\n item_url = log.Slice.slice_url\n item_title = log.Slice.slice_name\n\n payload.append({\n 'action': log.Log.action,\n 'item_url': item_url,\n 'item_title': item_title,\n 'time': log.Log.dttm,\n })\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/csrf_token/', methods=['GET'])\n def csrf_token(self):\n return Response(\n self.render_template('superset/csrf_token.json'),\n mimetype='text/json',\n )\n\n @api\n @has_access_api\n @expose('/fave_dashboards_by_username/<username>/', methods=['GET'])\n def fave_dashboards_by_username(self, username):\n \"\"\"This lets us use a user's username to pull favourite dashboards\"\"\"\n user = security_manager.find_user(username=username)\n return self.fave_dashboards(user.get_id())\n\n @api\n @has_access_api\n @expose('/fave_dashboards/<user_id>/', methods=['GET'])\n def fave_dashboards(self, user_id):\n qry = (\n db.session.query(\n models.Dashboard,\n models.FavStar.dttm,\n )\n .join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'Dashboard',\n models.Dashboard.id == models.FavStar.obj_id,\n ),\n )\n .order_by(\n models.FavStar.dttm.desc(),\n )\n )\n payload = []\n for o in qry.all():\n d = {\n 'id': o.Dashboard.id,\n 'dashboard': o.Dashboard.dashboard_link(),\n 'title': o.Dashboard.dashboard_title,\n 'url': o.Dashboard.url,\n 'dttm': o.dttm,\n }\n if o.Dashboard.created_by:\n user = o.Dashboard.created_by\n d['creator'] = str(user)\n d['creator_url'] = '/superset/profile/{}/'.format(\n user.username)\n payload.append(d)\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/created_dashboards/<user_id>/', methods=['GET'])\n def created_dashboards(self, user_id):\n Dash = models.Dashboard # noqa\n qry = (\n db.session.query(\n Dash,\n )\n .filter(\n sqla.or_(\n Dash.created_by_fk == user_id,\n Dash.changed_by_fk == user_id,\n ),\n )\n .order_by(\n Dash.changed_on.desc(),\n )\n )\n payload = [{\n 'id': o.id,\n 'dashboard': o.dashboard_link(),\n 'title': o.dashboard_title,\n 'url': o.url,\n 'dttm': o.changed_on,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/user_slices', methods=['GET'])\n @expose('/user_slices/<user_id>/', methods=['GET'])\n def user_slices(self, user_id=None):\n \"\"\"List of slices a user created, or faved\"\"\"\n if not user_id:\n user_id = g.user.id\n Slice = models.Slice # noqa\n FavStar = models.FavStar # noqa\n qry = (\n db.session.query(Slice,\n FavStar.dttm).join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'slice',\n models.Slice.id == models.FavStar.obj_id,\n ),\n isouter=True).filter(\n sqla.or_(\n Slice.created_by_fk == user_id,\n Slice.changed_by_fk == user_id,\n FavStar.user_id == user_id,\n ),\n )\n .order_by(Slice.slice_name.asc())\n )\n payload = [{\n 'id': o.Slice.id,\n 'title': o.Slice.slice_name,\n 'url': o.Slice.slice_url,\n 'data': o.Slice.form_data,\n 'dttm': o.dttm if o.dttm else o.Slice.changed_on,\n 'viz_type': o.Slice.viz_type,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/created_slices', methods=['GET'])\n @expose('/created_slices/<user_id>/', methods=['GET'])\n def created_slices(self, user_id=None):\n \"\"\"List of slices created by this user\"\"\"\n if not user_id:\n user_id = g.user.id\n Slice = models.Slice # noqa\n qry = (\n db.session.query(Slice)\n .filter(\n sqla.or_(\n Slice.created_by_fk == user_id,\n Slice.changed_by_fk == user_id,\n ),\n )\n .order_by(Slice.changed_on.desc())\n )\n payload = [{\n 'id': o.id,\n 'title': o.slice_name,\n 'url': o.slice_url,\n 'dttm': o.changed_on,\n 'viz_type': o.viz_type,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/fave_slices', methods=['GET'])\n @expose('/fave_slices/<user_id>/', methods=['GET'])\n def fave_slices(self, user_id=None):\n \"\"\"Favorite slices for a user\"\"\"\n if not user_id:\n user_id = g.user.id\n qry = (\n db.session.query(\n models.Slice,\n models.FavStar.dttm,\n )\n .join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'slice',\n models.Slice.id == models.FavStar.obj_id,\n ),\n )\n .order_by(\n models.FavStar.dttm.desc(),\n )\n )\n payload = []\n for o in qry.all():\n d = {\n 'id': o.Slice.id,\n 'title': o.Slice.slice_name,\n 'url': o.Slice.slice_url,\n 'dttm': o.dttm,\n 'viz_type': o.Slice.viz_type,\n }\n if o.Slice.created_by:\n user = o.Slice.created_by\n d['creator'] = str(user)\n d['creator_url'] = '/superset/profile/{}/'.format(\n user.username)\n payload.append(d)\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/warm_up_cache/', methods=['GET'])\n def warm_up_cache(self):\n \"\"\"Warms up the cache for the slice or table.\n\n Note for slices a force refresh occurs.\n \"\"\"\n slices = None\n session = db.session()\n slice_id = request.args.get('slice_id')\n table_name = request.args.get('table_name')\n db_name = request.args.get('db_name')\n\n if not slice_id and not (table_name and db_name):\n return json_error_response(__(\n 'Malformed request. slice_id or table_name and db_name '\n 'arguments are expected'), status=400)\n if slice_id:\n slices = session.query(models.Slice).filter_by(id=slice_id).all()\n if not slices:\n return json_error_response(__(\n 'Chart %(id)s not found', id=slice_id), status=404)\n elif table_name and db_name:\n SqlaTable = ConnectorRegistry.sources['table']\n table = (\n session.query(SqlaTable)\n .join(models.Database)\n .filter(\n models.Database.database_name == db_name or\n SqlaTable.table_name == table_name)\n ).first()\n if not table:\n return json_error_response(__(\n \"Table %(t)s wasn't found in the database %(d)s\",\n t=table_name, s=db_name), status=404)\n slices = session.query(models.Slice).filter_by(\n datasource_id=table.id,\n datasource_type=table.type).all()\n\n for slc in slices:\n try:\n form_data = self.get_form_data(slc.id, use_slice_data=True)[0]\n obj = self.get_viz(\n datasource_type=slc.datasource.type,\n datasource_id=slc.datasource.id,\n form_data=form_data,\n force=True,\n )\n obj.get_json()\n except Exception as e:\n return json_error_response(utils.error_msg_from_exception(e))\n return json_success(json.dumps(\n [{'slice_id': slc.id, 'slice_name': slc.slice_name}\n for slc in slices]))\n\n @has_access_api\n @expose('/favstar/<class_name>/<obj_id>/<action>/')\n def favstar(self, class_name, obj_id, action):\n \"\"\"Toggle favorite stars on Slices and Dashboard\"\"\"\n session = db.session()\n FavStar = models.FavStar # noqa\n count = 0\n favs = session.query(FavStar).filter_by(\n class_name=class_name, obj_id=obj_id,\n user_id=g.user.get_id()).all()\n if action == 'select':\n if not favs:\n session.add(\n FavStar(\n class_name=class_name,\n obj_id=obj_id,\n user_id=g.user.get_id(),\n dttm=datetime.now(),\n ),\n )\n count = 1\n elif action == 'unselect':\n for fav in favs:\n session.delete(fav)\n else:\n count = len(favs)\n session.commit()\n return json_success(json.dumps({'count': count}))\n\n @has_access\n @expose('/dashboard/<dashboard_id>/')\n def dashboard(self, dashboard_id):\n \"\"\"Server side rendering for a dashboard\"\"\"\n session = db.session()\n qry = session.query(models.Dashboard)\n if dashboard_id.isdigit():\n qry = qry.filter_by(id=int(dashboard_id))\n else:\n qry = qry.filter_by(slug=dashboard_id)\n\n dash = qry.one_or_none()\n if not dash:\n abort(404)\n datasources = set()\n for slc in dash.slices:\n datasource = slc.datasource\n if datasource:\n datasources.add(datasource)\n\n if config.get('ENABLE_ACCESS_REQUEST'):\n for datasource in datasources:\n if datasource and not security_manager.datasource_access(datasource):\n flash(\n __(security_manager.get_datasource_access_error_msg(datasource)),\n 'danger')\n return redirect(\n 'superset/request_access/?'\n f'dashboard_id={dash.id}&')\n\n dash_edit_perm = check_ownership(dash, raise_if_false=False) and \\\n security_manager.can_access('can_save_dash', 'Superset')\n dash_save_perm = security_manager.can_access('can_save_dash', 'Superset')\n superset_can_explore = security_manager.can_access('can_explore', 'Superset')\n slice_can_edit = security_manager.can_access('can_edit', 'SliceModelView')\n\n standalone_mode = request.args.get('standalone') == 'true'\n edit_mode = request.args.get('edit') == 'true'\n\n # Hack to log the dashboard_id properly, even when getting a slug\n @log_this\n def dashboard(**kwargs): # noqa\n pass\n dashboard(\n dashboard_id=dash.id,\n dashboard_version='v2',\n dash_edit_perm=dash_edit_perm,\n edit_mode=edit_mode)\n\n dashboard_data = dash.data\n dashboard_data.update({\n 'standalone_mode': standalone_mode,\n 'dash_save_perm': dash_save_perm,\n 'dash_edit_perm': dash_edit_perm,\n 'superset_can_explore': superset_can_explore,\n 'slice_can_edit': slice_can_edit,\n })\n\n bootstrap_data = {\n 'user_id': g.user.get_id(),\n 'dashboard_data': dashboard_data,\n 'datasources': {ds.uid: ds.data for ds in datasources},\n 'common': self.common_bootsrap_payload(),\n 'editMode': edit_mode,\n }\n\n if request.args.get('json') == 'true':\n return json_success(json.dumps(bootstrap_data))\n\n return self.render_template(\n 'superset/dashboard.html',\n entry='dashboard',\n standalone_mode=standalone_mode,\n title=dash.dashboard_title,\n bootstrap_data=json.dumps(bootstrap_data),\n )\n\n @api\n @log_this\n @expose('/log/', methods=['POST'])\n def log(self):\n return Response(status=200)\n\n @has_access\n @expose('/sync_druid/', methods=['POST'])\n @log_this\n def sync_druid_source(self):\n \"\"\"Syncs the druid datasource in main db with the provided config.\n\n The endpoint takes 3 arguments:\n user - user name to perform the operation as\n cluster - name of the druid cluster\n config - configuration stored in json that contains:\n name: druid datasource name\n dimensions: list of the dimensions, they become druid columns\n with the type STRING\n metrics_spec: list of metrics (dictionary). Metric consists of\n 2 attributes: type and name. Type can be count,\n etc. `count` type is stored internally as longSum\n other fields will be ignored.\n\n Example: {\n 'name': 'test_click',\n 'metrics_spec': [{'type': 'count', 'name': 'count'}],\n 'dimensions': ['affiliate_id', 'campaign', 'first_seen']\n }\n \"\"\"\n payload = request.get_json(force=True)\n druid_config = payload['config']\n user_name = payload['user']\n cluster_name = payload['cluster']\n\n user = security_manager.find_user(username=user_name)\n DruidDatasource = ConnectorRegistry.sources['druid']\n DruidCluster = DruidDatasource.cluster_class\n if not user:\n err_msg = __(\"Can't find User '%(name)s', please ask your admin \"\n 'to create one.', name=user_name)\n logging.error(err_msg)\n return json_error_response(err_msg)\n cluster = db.session.query(DruidCluster).filter_by(\n cluster_name=cluster_name).first()\n if not cluster:\n err_msg = __(\"Can't find DruidCluster with cluster_name = \"\n \"'%(name)s'\", name=cluster_name)\n logging.error(err_msg)\n return json_error_response(err_msg)\n try:\n DruidDatasource.sync_to_db_from_config(\n druid_config, user, cluster)\n except Exception as e:\n logging.exception(utils.error_msg_from_exception(e))\n return json_error_response(utils.error_msg_from_exception(e))\n return Response(status=201)\n\n @has_access\n @expose('/sqllab_viz/', methods=['POST'])\n @log_this\n def sqllab_viz(self):\n SqlaTable = ConnectorRegistry.sources['table']\n data = json.loads(request.form.get('data'))\n table_name = data.get('datasourceName')\n table = (\n db.session.query(SqlaTable)\n .filter_by(table_name=table_name)\n .first()\n )\n if not table:\n table = SqlaTable(table_name=table_name)\n table.database_id = data.get('dbId')\n table.schema = data.get('schema')\n table.template_params = data.get('templateParams')\n table.is_sqllab_view = True\n q = ParsedQuery(data.get('sql'))\n table.sql = q.stripped()\n db.session.add(table)\n cols = []\n for config in data.get('columns'):\n column_name = config.get('name')\n SqlaTable = ConnectorRegistry.sources['table']\n TableColumn = SqlaTable.column_class\n SqlMetric = SqlaTable.metric_class\n col = TableColumn(\n column_name=column_name,\n filterable=True,\n groupby=True,\n is_dttm=config.get('is_date', False),\n type=config.get('type', False),\n )\n cols.append(col)\n\n table.columns = cols\n table.metrics = [\n SqlMetric(metric_name='count', expression='count(*)'),\n ]\n db.session.commit()\n return self.json_response(json.dumps({\n 'table_id': table.id,\n }))\n\n @has_access\n @expose('/table/<database_id>/<path:table_name>/<schema>/')\n @log_this\n def table(self, database_id, table_name, schema):\n schema = utils.js_string_to_python(schema)\n table_name = parse.unquote_plus(table_name)\n mydb = db.session.query(models.Database).filter_by(id=database_id).one()\n payload_columns = []\n indexes = []\n primary_key = []\n foreign_keys = []\n try:\n columns = mydb.get_columns(table_name, schema)\n indexes = mydb.get_indexes(table_name, schema)\n primary_key = mydb.get_pk_constraint(table_name, schema)\n foreign_keys = mydb.get_foreign_keys(table_name, schema)\n except Exception as e:\n return json_error_response(utils.error_msg_from_exception(e))\n keys = []\n if primary_key and primary_key.get('constrained_columns'):\n primary_key['column_names'] = primary_key.pop('constrained_columns')\n primary_key['type'] = 'pk'\n keys += [primary_key]\n for fk in foreign_keys:\n fk['column_names'] = fk.pop('constrained_columns')\n fk['type'] = 'fk'\n keys += foreign_keys\n for idx in indexes:\n idx['type'] = 'index'\n keys += indexes\n\n for col in columns:\n dtype = ''\n try:\n dtype = '{}'.format(col['type'])\n except Exception:\n # sqla.types.JSON __str__ has a bug, so using __class__.\n dtype = col['type'].__class__.__name__\n pass\n payload_columns.append({\n 'name': col['name'],\n 'type': dtype.split('(')[0] if '(' in dtype else dtype,\n 'longType': dtype,\n 'keys': [\n k for k in keys\n if col['name'] in k.get('column_names')\n ],\n })\n tbl = {\n 'name': table_name,\n 'columns': payload_columns,\n 'selectStar': mydb.select_star(\n table_name, schema=schema, show_cols=True, indent=True,\n cols=columns, latest_partition=True),\n 'primaryKey': primary_key,\n 'foreignKeys': foreign_keys,\n 'indexes': keys,\n }\n return json_success(json.dumps(tbl))\n\n @has_access\n @expose('/extra_table_metadata/<database_id>/<path:table_name>/<schema>/')\n @log_this\n def extra_table_metadata(self, database_id, table_name, schema):\n schema = utils.js_string_to_python(schema)\n table_name = parse.unquote_plus(table_name)\n mydb = db.session.query(models.Database).filter_by(id=database_id).one()\n payload = mydb.db_engine_spec.extra_table_metadata(\n mydb, table_name, schema)\n return json_success(json.dumps(payload))\n\n @has_access\n @expose('/select_star/<database_id>/<table_name>')\n @expose('/select_star/<database_id>/<table_name>/<schema>')\n @log_this\n def select_star(self, database_id, table_name, schema=None):\n mydb = db.session.query(\n models.Database).filter_by(id=database_id).first()\n return json_success(\n mydb.select_star(\n table_name,\n schema,\n latest_partition=True,\n show_cols=True,\n ),\n )\n\n @expose('/theme/')\n def theme(self):\n return self.render_template('superset/theme.html')\n\n @has_access_api\n @expose('/cached_key/<key>/')\n @log_this\n def cached_key(self, key):\n \"\"\"Returns a key from the cache\"\"\"\n resp = cache.get(key)\n if resp:\n return resp\n return 'nope'\n\n @has_access_api\n @expose('/cache_key_exist/<key>/')\n @log_this\n def cache_key_exist(self, key):\n \"\"\"Returns if a key from cache exist\"\"\"\n key_exist = True if cache.get(key) else False\n status = 200 if key_exist else 404\n return json_success(json.dumps({'key_exist': key_exist}),\n status=status)\n\n @has_access_api\n @expose('/results/<key>/')\n @log_this\n def results(self, key):\n \"\"\"Serves a key off of the results backend\"\"\"\n if not results_backend:\n return json_error_response(\"Results backend isn't configured\")\n\n read_from_results_backend_start = now_as_float()\n blob = results_backend.get(key)\n stats_logger.timing(\n 'sqllab.query.results_backend_read',\n now_as_float() - read_from_results_backend_start,\n )\n if not blob:\n return json_error_response(\n 'Data could not be retrieved. '\n 'You may want to re-run the query.',\n status=410,\n )\n\n query = db.session.query(Query).filter_by(results_key=key).one()\n rejected_tables = security_manager.rejected_datasources(\n query.sql, query.database, query.schema)\n if rejected_tables:\n return json_error_response(security_manager.get_table_access_error_msg(\n '{}'.format(rejected_tables)), status=403)\n\n payload = utils.zlib_decompress_to_string(blob)\n display_limit = app.config.get('DEFAULT_SQLLAB_LIMIT', None)\n if display_limit:\n payload_json = json.loads(payload)\n payload_json['data'] = payload_json['data'][:display_limit]\n return json_success(\n json.dumps(\n payload_json,\n default=utils.json_iso_dttm_ser,\n ignore_nan=True,\n ),\n )\n\n @has_access_api\n @expose('/stop_query/', methods=['POST'])\n @log_this\n def stop_query(self):\n client_id = request.form.get('client_id')\n try:\n query = (\n db.session.query(Query)\n .filter_by(client_id=client_id).one()\n )\n query.status = QueryStatus.STOPPED\n db.session.commit()\n except Exception:\n pass\n return self.json_response('OK')\n\n @has_access_api\n @expose('/sql_json/', methods=['POST', 'GET'])\n @log_this\n def sql_json(self):\n \"\"\"Runs arbitrary sql and returns and json\"\"\"\n async_ = request.form.get('runAsync') == 'true'\n sql = request.form.get('sql')\n database_id = request.form.get('database_id')\n schema = request.form.get('schema') or None\n template_params = json.loads(\n request.form.get('templateParams') or '{}')\n limit = int(request.form.get('queryLimit', 0))\n if limit < 0:\n logging.warning(\n 'Invalid limit of {} specified. Defaulting to max limit.'.format(limit))\n limit = 0\n limit = limit or app.config.get('SQL_MAX_ROW')\n\n session = db.session()\n mydb = session.query(models.Database).filter_by(id=database_id).first()\n\n if not mydb:\n json_error_response(\n 'Database with id {} is missing.'.format(database_id))\n\n rejected_tables = security_manager.rejected_datasources(sql, mydb, schema)\n if rejected_tables:\n return json_error_response(\n security_manager.get_table_access_error_msg(rejected_tables),\n link=security_manager.get_table_access_link(rejected_tables),\n status=403)\n session.commit()\n\n select_as_cta = request.form.get('select_as_cta') == 'true'\n tmp_table_name = request.form.get('tmp_table_name')\n if select_as_cta and mydb.force_ctas_schema:\n tmp_table_name = '{}.{}'.format(\n mydb.force_ctas_schema,\n tmp_table_name,\n )\n\n client_id = request.form.get('client_id') or utils.shortid()[:10]\n limits = [mydb.db_engine_spec.get_limit_from_sql(sql), limit]\n query = Query(\n database_id=int(database_id),\n limit=min(lim for lim in limits if lim is not None),\n sql=sql,\n schema=schema,\n select_as_cta=request.form.get('select_as_cta') == 'true',\n start_time=now_as_float(),\n tab_name=request.form.get('tab'),\n status=QueryStatus.PENDING if async_ else QueryStatus.RUNNING,\n sql_editor_id=request.form.get('sql_editor_id'),\n tmp_table_name=tmp_table_name,\n user_id=g.user.get_id() if g.user else None,\n client_id=client_id,\n )\n session.add(query)\n session.flush()\n query_id = query.id\n session.commit() # shouldn't be necessary\n if not query_id:\n raise Exception(_('Query record was not created as expected.'))\n logging.info('Triggering query_id: {}'.format(query_id))\n\n try:\n template_processor = get_template_processor(\n database=query.database, query=query)\n rendered_query = template_processor.process_template(\n query.sql,\n **template_params)\n except Exception as e:\n return json_error_response(\n 'Template rendering failed: {}'.format(utils.error_msg_from_exception(e)))\n\n # Async request.\n if async_:\n logging.info('Running query on a Celery worker')\n # Ignore the celery future object and the request may time out.\n try:\n sql_lab.get_sql_results.delay(\n query_id,\n rendered_query,\n return_results=False,\n store_results=not query.select_as_cta,\n user_name=g.user.username if g.user else None,\n start_time=now_as_float())\n except Exception as e:\n logging.exception(e)\n msg = _(\n 'Failed to start remote query on a worker. '\n 'Tell your administrator to verify the availability of '\n 'the message queue.')\n query.status = QueryStatus.FAILED\n query.error_message = msg\n session.commit()\n return json_error_response('{}'.format(msg))\n\n resp = json_success(json.dumps(\n {'query': query.to_dict()}, default=utils.json_int_dttm_ser,\n ignore_nan=True), status=202)\n session.commit()\n return resp\n\n # Sync request.\n try:\n timeout = config.get('SQLLAB_TIMEOUT')\n timeout_msg = (\n f'The query exceeded the {timeout} seconds timeout.')\n with utils.timeout(seconds=timeout,\n error_message=timeout_msg):\n # pylint: disable=no-value-for-parameter\n data = sql_lab.get_sql_results(\n query_id,\n rendered_query,\n return_results=True,\n user_name=g.user.username if g.user else None)\n payload = json.dumps(\n data,\n default=utils.pessimistic_json_iso_dttm_ser,\n ignore_nan=True,\n encoding=None,\n )\n except Exception as e:\n logging.exception(e)\n return json_error_response('{}'.format(e))\n if data.get('status') == QueryStatus.FAILED:\n return json_error_response(payload=data)\n return json_success(payload)\n\n @has_access\n @expose('/csv/<client_id>')\n @log_this\n def csv(self, client_id):\n \"\"\"Download the query results as csv.\"\"\"\n logging.info('Exporting CSV file [{}]'.format(client_id))\n query = (\n db.session.query(Query)\n .filter_by(client_id=client_id)\n .one()\n )\n\n rejected_tables = security_manager.rejected_datasources(\n query.sql, query.database, query.schema)\n if rejected_tables:\n flash(\n security_manager.get_table_access_error_msg('{}'.format(rejected_tables)))\n return redirect('/')\n blob = None\n if results_backend and query.results_key:\n logging.info(\n 'Fetching CSV from results backend '\n '[{}]'.format(query.results_key))\n blob = results_backend.get(query.results_key)\n if blob:\n logging.info('Decompressing')\n json_payload = utils.zlib_decompress_to_string(blob)\n obj = json.loads(json_payload)\n columns = [c['name'] for c in obj['columns']]\n df = pd.DataFrame.from_records(obj['data'], columns=columns)\n logging.info('Using pandas to convert to CSV')\n csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))\n else:\n logging.info('Running a query to turn into CSV')\n sql = query.select_sql or query.executed_sql\n df = query.database.get_df(sql, query.schema)\n # TODO(bkyryliuk): add compression=gzip for big files.\n csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))\n response = Response(csv, mimetype='text/csv')\n response.headers['Content-Disposition'] = f'attachment; filename={query.name}.csv'\n logging.info('Ready to return response')\n return response\n\n @api\n @handle_api_exception\n @has_access\n @expose('/fetch_datasource_metadata')\n @log_this\n def fetch_datasource_metadata(self):\n datasource_id, datasource_type = (\n request.args.get('datasourceKey').split('__'))\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n # Check if datasource exists\n if not datasource:\n return json_error_response(DATASOURCE_MISSING_ERR)\n\n # Check permission for datasource\n security_manager.assert_datasource_permission(datasource)\n return json_success(json.dumps(datasource.data))\n\n @has_access_api\n @expose('/queries/<last_updated_ms>')\n def queries(self, last_updated_ms):\n \"\"\"Get the updated queries.\"\"\"\n stats_logger.incr('queries')\n if not g.user.get_id():\n return json_error_response(\n 'Please login to access the queries.', status=403)\n\n # Unix time, milliseconds.\n last_updated_ms_int = int(float(last_updated_ms)) if last_updated_ms else 0\n\n # UTC date time, same that is stored in the DB.\n last_updated_dt = utils.EPOCH + timedelta(seconds=last_updated_ms_int / 1000)\n\n sql_queries = (\n db.session.query(Query)\n .filter(\n Query.user_id == g.user.get_id(),\n Query.changed_on >= last_updated_dt,\n )\n .all()\n )\n dict_queries = {q.client_id: q.to_dict() for q in sql_queries}\n\n now = int(round(time.time() * 1000))\n\n unfinished_states = [\n QueryStatus.PENDING,\n QueryStatus.RUNNING,\n ]\n\n queries_to_timeout = [\n client_id for client_id, query_dict in dict_queries.items()\n if (\n query_dict['state'] in unfinished_states and (\n now - query_dict['startDttm'] >\n config.get('SQLLAB_ASYNC_TIME_LIMIT_SEC') * 1000\n )\n )\n ]\n\n if queries_to_timeout:\n update(Query).where(\n and_(\n Query.user_id == g.user.get_id(),\n Query.client_id in queries_to_timeout,\n ),\n ).values(state=QueryStatus.TIMED_OUT)\n\n for client_id in queries_to_timeout:\n dict_queries[client_id]['status'] = QueryStatus.TIMED_OUT\n\n return json_success(\n json.dumps(dict_queries, default=utils.json_int_dttm_ser))\n\n @has_access\n @expose('/search_queries')\n @log_this\n def search_queries(self):\n \"\"\"Search for queries.\"\"\"\n query = db.session.query(Query)\n search_user_id = request.args.get('user_id')\n database_id = request.args.get('database_id')\n search_text = request.args.get('search_text')\n status = request.args.get('status')\n # From and To time stamp should be Epoch timestamp in seconds\n from_time = request.args.get('from')\n to_time = request.args.get('to')\n\n if search_user_id:\n # Filter on db Id\n query = query.filter(Query.user_id == search_user_id)\n\n if database_id:\n # Filter on db Id\n query = query.filter(Query.database_id == database_id)\n\n if status:\n # Filter on status\n query = query.filter(Query.status == status)\n\n if search_text:\n # Filter on search text\n query = query \\\n .filter(Query.sql.like('%{}%'.format(search_text)))\n\n if from_time:\n query = query.filter(Query.start_time > int(from_time))\n\n if to_time:\n query = query.filter(Query.start_time < int(to_time))\n\n query_limit = config.get('QUERY_SEARCH_LIMIT', 1000)\n sql_queries = (\n query.order_by(Query.start_time.asc())\n .limit(query_limit)\n .all()\n )\n\n dict_queries = [q.to_dict() for q in sql_queries]\n\n return Response(\n json.dumps(dict_queries, default=utils.json_int_dttm_ser),\n status=200,\n mimetype='application/json')\n\n @app.errorhandler(500)\n def show_traceback(self):\n return render_template(\n 'superset/traceback.html',\n error_msg=get_error_msg(),\n ), 500\n\n @expose('/welcome')\n def welcome(self):\n \"\"\"Personalized welcome page\"\"\"\n if not g.user or not g.user.get_id():\n return redirect(appbuilder.get_url_for_login)\n\n welcome_dashboard_id = (\n db.session\n .query(UserAttribute.welcome_dashboard_id)\n .filter_by(user_id=g.user.get_id())\n .scalar()\n )\n if welcome_dashboard_id:\n return self.dashboard(str(welcome_dashboard_id))\n\n payload = {\n 'user': bootstrap_user_data(),\n 'common': self.common_bootsrap_payload(),\n }\n\n return self.render_template(\n 'superset/basic.html',\n entry='welcome',\n title='Superset',\n bootstrap_data=json.dumps(payload, default=utils.json_iso_dttm_ser),\n )\n\n @has_access\n @expose('/profile/<username>/')\n def profile(self, username):\n \"\"\"User profile page\"\"\"\n if not username and g.user:\n username = g.user.username\n\n payload = {\n 'user': bootstrap_user_data(username, include_perms=True),\n 'common': self.common_bootsrap_payload(),\n }\n\n return self.render_template(\n 'superset/basic.html',\n title=_(\"%(user)s's profile\", user=username),\n entry='profile',\n bootstrap_data=json.dumps(payload, default=utils.json_iso_dttm_ser),\n )\n\n @has_access\n @expose('/sqllab')\n def sqllab(self):\n \"\"\"SQL Editor\"\"\"\n d = {\n 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'),\n 'common': self.common_bootsrap_payload(),\n }\n return self.render_template(\n 'superset/basic.html',\n entry='sqllab',\n bootstrap_data=json.dumps(d, default=utils.json_iso_dttm_ser),\n )\n\n @api\n @handle_api_exception\n @has_access_api\n @expose('/slice_query/<slice_id>/')\n def slice_query(self, slice_id):\n \"\"\"\n This method exposes an API endpoint to\n get the database query string for this slice\n \"\"\"\n viz_obj = self.get_viz(slice_id)\n security_manager.assert_datasource_permission(viz_obj.datasource)\n return self.get_query_string_response(viz_obj)\n\n @api\n @has_access_api\n @expose('/schemas_access_for_csv_upload')\n def schemas_access_for_csv_upload(self):\n \"\"\"\n This method exposes an API endpoint to\n get the schema access control settings for csv upload in this database\n \"\"\"\n if not request.args.get('db_id'):\n return json_error_response(\n 'No database is allowed for your csv upload')\n\n db_id = int(request.args.get('db_id'))\n database = (\n db.session\n .query(models.Database)\n .filter_by(id=db_id)\n .one()\n )\n try:\n schemas_allowed = database.get_schema_access_for_csv_upload()\n if (security_manager.database_access(database) or\n security_manager.all_datasource_access()):\n return self.json_response(schemas_allowed)\n # the list schemas_allowed should not be empty here\n # and the list schemas_allowed_processed returned from security_manager\n # should not be empty either,\n # otherwise the database should have been filtered out\n # in CsvToDatabaseForm\n schemas_allowed_processed = security_manager.schemas_accessible_by_user(\n database, schemas_allowed, False)\n return self.json_response(schemas_allowed_processed)\n except Exception:\n return json_error_response((\n 'Failed to fetch schemas allowed for csv upload in this database! '\n 'Please contact Superset Admin!\\n\\n'\n 'The error message returned was:\\n{}').format(traceback.format_exc()))\n\n\nappbuilder.add_view_no_menu(Superset)\n\n\nclass CssTemplateModelView(SupersetModelView, DeleteMixin):\n datamodel = SQLAInterface(models.CssTemplate)\n\n list_title = _('CSS Templates')\n show_title = _('Show CSS Template')\n add_title = _('Add CSS Template')\n edit_title = _('Edit CSS Template')\n\n list_columns = ['template_name']\n edit_columns = ['template_name', 'css']\n add_columns = edit_columns\n label_columns = {\n 'template_name': _('Template Name'),\n }\n\n\nclass CssTemplateAsyncModelView(CssTemplateModelView):\n list_columns = ['template_name', 'css']\n\n\nappbuilder.add_separator('Sources')\nappbuilder.add_view(\n CssTemplateModelView,\n 'CSS Templates',\n label=__('CSS Templates'),\n icon='fa-css3',\n category='Manage',\n category_label=__('Manage'),\n category_icon='')\n\n\nappbuilder.add_view_no_menu(CssTemplateAsyncModelView)\n\nappbuilder.add_link(\n 'SQL Editor',\n label=_('SQL Editor'),\n href='/superset/sqllab',\n category_icon='fa-flask',\n icon='fa-flask',\n category='SQL Lab',\n category_label=__('SQL Lab'),\n)\n\nappbuilder.add_link(\n 'Query Search',\n label=_('Query Search'),\n href='/superset/sqllab#search',\n icon='fa-search',\n category_icon='fa-flask',\n category='SQL Lab',\n category_label=__('SQL Lab'),\n)\n\nappbuilder.add_link(\n 'Upload a CSV',\n label=__('Upload a CSV'),\n href='/csvtodatabaseview/form',\n icon='fa-upload',\n category='Sources',\n category_label=__('Sources'),\n category_icon='fa-wrench')\nappbuilder.add_separator('Sources')\n\n\[email protected]_request\ndef apply_caching(response):\n \"\"\"Applies the configuration's http headers to all responses\"\"\"\n for k, v in config.get('HTTP_HEADERS').items():\n response.headers[k] = v\n return response\n\n\n# ---------------------------------------------------------------------\n# Redirecting URL from previous names\nclass RegexConverter(BaseConverter):\n def __init__(self, url_map, *items):\n super(RegexConverter, self).__init__(url_map)\n self.regex = items[0]\n\n\napp.url_map.converters['regex'] = RegexConverter\n\n\[email protected]('/<regex(\"panoramix\\/.*\"):url>')\ndef panoramix(url): # noqa\n return redirect(request.full_path.replace('panoramix', 'superset'))\n\n\[email protected]('/<regex(\"caravel\\/.*\"):url>')\ndef caravel(url): # noqa\n return redirect(request.full_path.replace('caravel', 'superset'))\n\n\n# ---------------------------------------------------------------------\n"
] |
[
[
"pandas.DataFrame.from_records"
]
] |
dstahlke/qitensor
|
[
"2b430e01e3f0d3c8488e35f417faaca27f930af3"
] |
[
"qitensor/experimental/noncommgraph.py"
] |
[
"# Noncommutative graphs as defined by Duan, Severini, Winter in arXiv:1002.2514.\n\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport scipy.linalg as linalg\nimport itertools\nimport collections\nimport cvxopt.base\nimport cvxopt.solvers\n\nfrom qitensor import qudit, HilbertSpace, HilbertArray\nfrom qitensor.space import _shape_product\nfrom qitensor.superop import CP_Map\nfrom qitensor.subspace import TensorSubspace\n\n__all__ = [\n 'from_adjmat',\n 'from_graph6',\n 'pentagon',\n 'make_channel',\n 'from_channel',\n 'lovasz_theta',\n 'szegedy',\n 'schrijver',\n 'qthperp',\n 'qthmperp',\n 'qthpperp',\n 'get_many_values',\n]\n\n# Adapted from\n# https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties\nclass cached_property(object):\n def __init__(self, fget, doc=None):\n self.fget = fget\n self.__doc__ = doc or fget.__doc__\n self.__name__ = fget.__name__\n self.__module__ = fget.__module__\n\n def __get__(self, obj, objtype):\n # For Sphinx:\n if obj is None:\n return self.fget\n\n try:\n cache = obj._cache\n except AttributeError:\n cache = obj._cache = {}\n if not self.__name__ in cache:\n cache[self.__name__] = self.fget(obj)\n return cache[self.__name__]\n\n### Some helper functions for cvxopt ###\n\ndef mat_cplx_to_real(cmat):\n return np.bmat([[cmat.real, -cmat.imag], [cmat.imag, cmat.real]]) / np.sqrt(2)\n\ndef mat_real_to_cplx(rmat):\n w = rmat.shape[0] // 2\n h = rmat.shape[1] // 2\n return (rmat[:w,:h] + rmat[w:,h:] + 1j*rmat[w:,:h] - 1j*rmat[:w,h:]) / np.sqrt(2)\n\ndef make_F_real(Fx_list, F0_list):\n '''\n Convert F0, Fx arrays to real if needed, by considering C as a vector space\n over R. This is needed because cvxopt cannot handle complex inputs.\n '''\n\n F0_list_real = []\n Fx_list_real = []\n for (F0, Fx) in zip(F0_list, Fx_list):\n if F0.dtype.kind == 'c' or Fx.dtype.kind == 'c':\n F0_list_real.append(mat_cplx_to_real(F0))\n\n mr = np.zeros((Fx.shape[0]*2, Fx.shape[1]*2, Fx.shape[2]))\n for i in range(Fx.shape[2]):\n mr[:, :, i] = mat_cplx_to_real(Fx[:, :, i])\n Fx_list_real.append(mr)\n else:\n F0_list_real.append(F0)\n Fx_list_real.append(Fx)\n\n assert len(F0_list_real) == len(F0_list)\n assert len(Fx_list_real) == len(Fx_list)\n return (Fx_list_real, F0_list_real)\n\ndef call_sdp(c, Fx_list, F0_list):\n '''\n Solve the SDP which minimizes $c^T x$ under the constraint\n $\\sum_i Fx_i x_i - F0 \\ge 0$ for all (Fx, F0) in (Fx_list, F0_list).\n '''\n\n for (k, (F0, Fx)) in enumerate(zip(F0_list, Fx_list)):\n assert linalg.norm(F0 - F0.conj().T) < 1e-10\n for i in range(Fx.shape[2]):\n assert linalg.norm(Fx[:,:,i] - Fx[:,:,i].conj().T) < 1e-10\n\n (Fx_list, F0_list) = make_F_real(Fx_list, F0_list)\n Gs = [cvxopt.base.matrix(Fx.reshape(Fx.shape[0]**2, Fx.shape[2])) for Fx in Fx_list]\n hs = [cvxopt.base.matrix(F0) for F0 in F0_list]\n\n sol = cvxopt.solvers.sdp(cvxopt.base.matrix(c), Gs=Gs, hs=hs)\n xvec = np.array(sol['x']).flatten()\n\n sol['Gs'] = Gs\n sol['hs'] = hs\n\n if sol['status'] == 'optimal':\n for (G, h) in zip(Gs, hs):\n G = np.array(G)\n h = np.array(h)\n M = np.dot(G, xvec).reshape(h.shape)\n assert linalg.eigvalsh(h-M)[0] > -1e-7\n\n return (xvec, sol)\n\ndef tensor_to_matrix(M):\n assert (len(M.shape) % 2 == 0)\n l = len(M.shape) // 2\n nr = _shape_product(M.shape[:l])\n nc = _shape_product(M.shape[l:])\n assert nr == nc\n return M.reshape(nr, nc)\n\ndef check_psd(M):\n \"\"\"\n By how much does M fail to be PSD?\n \"\"\"\n\n if isinstance(M, HilbertArray):\n M = M.nparray\n\n M = tensor_to_matrix(M)\n\n err_H = linalg.norm(M - M.T.conj())\n err_P = linalg.eigvalsh(M + M.T.conj())[0]\n err_P = 0 if err_P > 0 else -err_P\n\n return err_H + err_P\n\ndef project_dh(M):\n \"\"\"\n Get doubly Hermitian component.\n \"\"\"\n M = (M + M.transpose(1,0,3,2).conj()) / 2\n M = (M + M.transpose(2,3,0,1).conj()) / 2\n return M\n\n### Helper class, for private use ######################\n\nclass GraphProperties(object):\n \"\"\"Non-commutative graphs as described in arXiv:1002.2514.\"\"\"\n\n def __init__(self, S):\n \"\"\"\n Create a non-commutative graph from provided TensorSubspace.\n \"\"\"\n\n assert S.is_hermitian()\n\n self.S = S\n\n # Make it a space over rank-2 tensors.\n S_flat = self.S_flat = S._op_flatten()\n assert S_flat._col_shp[0] == S_flat._col_shp[1]\n n = self.n = S_flat._col_shp[0]\n\n assert np.eye(n) in S_flat\n\n self.cond_psd = {\n 'name': 'psd',\n 'R': lambda Z: Z.transpose((0,2,1,3)).reshape(n**2, n**2),\n 'R*': lambda Z: Z.reshape(n,n,n,n).transpose((0,2,1,3)),\n }\n\n self.cond_ppt = {\n 'name': 'ppt',\n 'R': lambda Z: Z.transpose((1,2,0,3)).reshape(n**2, n**2),\n 'R*': lambda Z: Z.reshape(n,n,n,n).transpose((2,0,1,3)),\n }\n\n for c in [self.cond_psd, self.cond_ppt]:\n m = np.random.random((n**2, n**2))\n m2 = c['R'](c['R*'](m))\n assert linalg.norm(m-m2) < 1e-10\n\n @cached_property\n def S_basis(self):\n ret = np.array(self.S_flat.hermitian_basis()) \\\n if self.S_flat.dim() else np.zeros((0, self.n, self.n), dtype=complex)\n assert len(ret.shape) == 3\n return ret\n\n @cached_property\n def Sp_basis(self):\n ret = np.array(self.S_flat.perp().hermitian_basis()) \\\n if self.S_flat.perp().dim() else np.zeros((0, self.n, self.n), dtype=complex)\n assert len(ret.shape) == 3\n return ret\n\n @cached_property\n def Y_basis(self):\n return self.get_S_ot_L_basis(self.S_basis)\n\n @cached_property\n def Y_basis_dh(self):\n return self.basis_doubly_hermit(self.S_basis)\n\n @cached_property\n def T_basis(self):\n return self.get_S_ot_L_basis(self.Sp_basis)\n\n @cached_property\n def T_basis_dh(self):\n return self.basis_doubly_hermit(self.Sp_basis)\n\n @cached_property\n def full_basis_dh(self):\n return self.basis_doubly_hermit(TensorSubspace.full((self.n, self.n)).hermitian_basis())\n\n @cached_property\n def top_space(self):\n return self.S._hilb_space.ket_space()\n\n @cached_property\n def bottom_space(self):\n ret = self.top_space\n while not ret.isdisjoint(self.top_space):\n ret = ret.prime\n return ret\n\n def R(self, x):\n ha = self.top_space\n hb = self.bottom_space\n return x.relabel({ hb: ha.H, ha.H: hb })\n\n def ddag(self, x):\n ha = self.top_space\n hb = self.bottom_space\n ret = x.relabel({ ha: hb, hb: ha, ha.H: hb.H, hb.H: ha.H }).conj()\n assert (ret - self.R(self.R(x).H)).norm() < 1e-12\n return ret\n\n def make_ab_array(self, M):\n ha = self.top_space\n hb = self.bottom_space\n return (ha*hb).O.array(M, reshape=True, input_axes=ha.axes+hb.axes+ha.H.axes+hb.H.axes)\n\n def __str__(self):\n return '<GraphProperties of '+self.S._str_inner()+'>'\n\n def __repr__(self):\n return str(self)\n\n def get_S_ot_L_basis(self, Sb):\n \"\"\"\n Compute a basis for the allowed Y operators for Theorem 9 of\n arXiv:1002.2514. These are the operators which are Hermitian and are\n in S*L(A'). Note that this basis is intended to map real vectors to\n complex Y operators.\n \"\"\"\n\n (nS, n, _n) = Sb.shape\n assert n == _n\n\n Lb = TensorSubspace.full((n, n)).hermitian_basis()\n\n baz = np.zeros((nS*n*n, n, n, n, n), dtype=complex)\n i = 0\n for x in Sb:\n for y in Lb:\n baz[i] = np.tensordot(x, y, axes=([],[])).transpose((0, 2, 1, 3))\n i += 1\n assert i == baz.shape[0]\n\n ret = baz.transpose((1, 2, 3, 4, 0))\n\n # [ |a>, |a'>, <a|, <a'| ; idx ]\n return ret\n\n def basis_doubly_hermit(self, Sb):\n \"\"\"\n Returns a basis of elements of spc \\ot spc that are Hermitian and also have Hermitian\n images under R().\n\n Sb must be a Hermitian basis.\n \"\"\"\n\n (nS, n, _n) = Sb.shape\n assert n == _n\n\n if nS == 0:\n return np.zeros((0, n, n, n, n), dtype=complex)\n\n out = []\n for (i, x) in enumerate(Sb):\n out.append( np.tensordot(x, x.conj(), axes=([],[])).transpose((0, 2, 1, 3)) )\n for (j, y) in enumerate(Sb):\n if j >= i:\n continue\n xy = np.tensordot(x, y.conj(), axes=([],[])).transpose((0, 2, 1, 3))\n yx = np.tensordot(y, x.conj(), axes=([],[])).transpose((0, 2, 1, 3))\n out.append(xy+yx)\n\n out = [ x / linalg.norm(x) for x in out ]\n\n ret = np.array(out).transpose((1, 2, 3, 4, 0))\n\n # [ |a>, |a'>, <a|, <a'| ; idx ]\n return ret\n\n def test_get_Y_basis_doubly_hermit(self):\n n = self.n\n Yb = self.Y_basis\n Hb = self.full_basis_dh\n A = TensorSubspace.from_span([ mat_cplx_to_real(Yb[:,:,:,:,i].reshape((n*n, n*n))) for i in range(Yb.shape[4]) ])\n B = TensorSubspace.from_span([ mat_cplx_to_real(Hb[:,:,:,:,i].reshape((n*n, n*n))) for i in range(Hb.shape[4]) ])\n C = A & B\n print(A,B,C)\n out = np.array([ mat_real_to_cplx(x).reshape((n,n,n,n)) for x in C ])\n for (i,c) in enumerate(np.rollaxis(Hb, -1)):\n x = c.reshape((n*n, n*n))\n y = mat_real_to_cplx(mat_cplx_to_real(x))\n assert linalg.norm(x - x.conj().T) < 1e-10\n assert np.allclose(x, y)\n for (i,c) in enumerate(B):\n x = mat_real_to_cplx(c)\n assert linalg.norm(x - x.conj().T) < 1e-10\n for (i,c) in enumerate(C):\n x = mat_real_to_cplx(c)\n assert linalg.norm(x - x.conj().T) < 1e-10\n a = TensorSubspace.from_span([ mat_cplx_to_real(x.reshape(n*n,n*n)) for x in\n np.rollaxis(self.Y_basis_dh, -1) ])\n b = TensorSubspace.from_span([ mat_cplx_to_real(x.reshape(n*n,n*n)) for x in out ])\n print(a)\n print(b)\n print(a.equiv(b))\n assert a.equiv(b)\n\n def test_doubly_hermitian_basis(self):\n n = self.n\n\n def perms(i,j,k,l):\n return [(i,j,k,l), (j,i,l,k), (l,k,j,i), (k,l,i,j)]\n\n inds = set()\n for (i,j,k,l) in itertools.product(list(range(n)), repeat=4):\n p = perms(i,j,k,l)\n if not np.any([ x in inds for x in p ]):\n inds.add((i,j,k,l))\n\n ops = []\n for (i,j,k,l) in inds:\n a = np.zeros((n,n,n,n), dtype=complex)\n a[i,j,k,l] = 1\n a += a.transpose((1,0,3,2))\n a += a.transpose((2,3,0,1))\n ops.append(a)\n\n a = np.zeros((n,n,n,n), dtype=complex)\n a[i,j,k,l] = 1j\n a += a.transpose((1,0,3,2)).conj()\n a += a.transpose((2,3,0,1)).conj()\n if np.sum(np.abs(a)) > 1e-6:\n ops.append(a)\n\n a = TensorSubspace.from_span([ mat_cplx_to_real(x.reshape(n*n,n*n)) for x in\n np.rollaxis(self.full_basis_dh, -1) ])\n b = TensorSubspace.from_span([ mat_cplx_to_real(x.reshape(n*n,n*n)) for x in ops ])\n print(a)\n print(b)\n print(a.equiv(b))\n assert a.equiv(b)\n\n def get_cone_set(self, cones):\n if isinstance(cones, list):\n return cones\n else:\n assert isinstance(cones, str)\n return {\n 'hermit': [],\n 'psd': [self.cond_psd],\n 'psd&ppt': [self.cond_psd, self.cond_ppt],\n 'ppt': [self.cond_ppt],\n }[cones]\n\n### End of GraphProperties #################################\n\ndef from_adjmat(adj_mat, loops=False):\n \"\"\"\n Create a non-commutative graph from the adjacency matrix of a classical graph.\n\n The given adjacency matrix must be symmetric.\n\n >>> import numpy\n >>> # 5-cycle graph\n >>> adj_mat = np.array([\n ... [0, 1, 0, 0, 1],\n ... [1, 0, 1, 0, 0],\n ... [0, 1, 0, 1, 0],\n ... [0, 0, 1, 0, 1],\n ... [1, 0, 0, 1, 0]\n ... ])\n >>> S = from_adjmat(adj_mat)\n >>> S\n <TensorSubspace of dim 10 over space (5, 5)>\n >>> theta = lovasz_theta(~S)\n >>> abs(theta - numpy.sqrt(5)) < 1e-8\n True\n >>> T = from_adjmat(adj_mat, loops=True)\n >>> T\n <TensorSubspace of dim 15 over space (5, 5)>\n >>> theta = lovasz_theta(T)\n >>> abs(theta - numpy.sqrt(5)) < 1e-8\n True\n \"\"\"\n\n assert len(adj_mat.shape) == 2\n assert adj_mat.shape[0] == adj_mat.shape[1]\n assert np.all(adj_mat == adj_mat.transpose())\n n = adj_mat.shape[0]\n basis = []\n\n # copy and cast to numpy\n adj_mat = np.array(adj_mat)\n\n for (i, j) in np.transpose(adj_mat.nonzero()):\n m = np.zeros((n, n), dtype=complex)\n m[i, j] = 1\n basis.append(m)\n\n ret = TensorSubspace.from_span(basis)\n\n if loops:\n ret |= TensorSubspace.diagonals((n, n))\n\n return ret\n\ndef from_graph6(g6, loops=False):\n \"\"\"\n Create a non-commutative graph corresponding to the classical graph with the given\n graph6 code.\n\n >>> from_graph6('GRddY{')\n <TensorSubspace of dim 32 over space (8, 8)>\n >>> from_graph6('GRddY{', loops=True)\n <TensorSubspace of dim 40 over space (8, 8)>\n \"\"\"\n\n import networkx as nx\n G = nx.parse_graph6(g6)\n n = len(G)\n basis = []\n\n for (i, j) in G.edges():\n m = np.zeros((n, n), dtype=complex)\n m[i, j] = 1\n basis.append(m)\n basis += [ x.transpose() for x in basis ]\n\n ret = TensorSubspace.from_span(basis)\n\n if loops:\n ret |= TensorSubspace.diagonals((n, n))\n\n return ret\n\ndef pentagon():\n \"\"\"\n Create the 5-cycle graph. Useful for testing.\n\n >>> import numpy\n >>> # 5-cycle graph\n >>> adj_mat = np.array([\n ... [0, 1, 0, 0, 1],\n ... [1, 0, 1, 0, 0],\n ... [0, 1, 0, 1, 0],\n ... [0, 0, 1, 0, 1],\n ... [1, 0, 0, 1, 0]\n ... ])\n >>> S = from_adjmat(adj_mat)\n >>> T = pentagon()\n >>> S.equiv(T)\n True\n \"\"\"\n\n # Adjacency matric for the 5-cycle graph.\n adj_mat = np.array([\n [0, 1, 0, 0, 1],\n [1, 0, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [0, 0, 1, 0, 1],\n [1, 0, 0, 1, 0]\n ])\n return from_adjmat(adj_mat)\n\ndef make_channel(S):\n \"\"\"\n Makes a CPTP map whose confusibility graph is equal to ``S``.\n\n >>> ha = qudit('a', 3)\n >>> S = TensorSubspace.create_random_hermitian(ha, 5, tracefree=True).perp()\n >>> S\n <TensorSubspace of dim 4 over space (|a><a|)>\n >>> N = make_channel(S)\n >>> N\n CP_Map( |a><a| to |a,k><a,k| )\n >>> T = from_channel(N)\n >>> T\n <TensorSubspace of dim 4 over space (|a><a|)>\n >>> T.equiv(S)\n True\n \"\"\"\n\n assert S._hilb_space is not None\n spc = S._hilb_space\n assert S.is_hermitian()\n assert spc.eye() in S\n\n if S.dim() == 1:\n return CP_Map.identity(spc)\n\n # Hermitian basis for all but identity\n B = (S - spc.eye().span()).hermitian_basis()\n # Add identity to make a PSD basis\n B = [ b - spc.eye() * b.eigvalsh()[0] for b in B ]\n # Make everything in the basis sum to a bounded operator\n m = np.sum(B).eigvalsh()[-1]\n B = [ b/m for b in B ]\n # Add a final element to make a complete POVM\n B += [ spc.eye() - np.sum(B) ]\n # Make Kraus operators\n J = [ b.sqrt() for b in B ]\n # Remove a unitary degree of freedom\n # Is this needed or just here to make a nicer answer?\n J = [ j.svd()[0].H * j for j in J ]\n\n # Add basis index to channel output (eliminates interference between different basis\n # elements).\n hk = qudit('k', len(J))\n J = [ hk.ket(k) * j for (k,j) in enumerate(J) ]\n\n Kspc = TensorSubspace.from_span(J)\n assert S.equiv(Kspc.H * Kspc)\n\n chan = CP_Map.from_kraus(J)\n assert chan.is_cptp()\n\n return chan\n\ndef from_channel(N):\n \"\"\"\n Returns the confusibility graph for a ``CP_Map``.\n\n >>> ha = qudit('a', 3)\n >>> N = CP_Map.decohere(ha)\n >>> N\n CP_Map( |a><a| to |a><a| )\n >>> S = from_channel(N)\n >>> S\n <TensorSubspace of dim 3 over space (|a><a|)>\n >>> theta = lovasz_theta(S)\n >>> abs(theta - 3.0) < 1e-8\n True\n \"\"\"\n\n assert N.is_cptp()\n K = TensorSubspace.from_span(N.krauses())\n return K.H * K\n\n### Main SDP routines =============\n\ndef lovasz_theta(S, long_return=False, verify_tol=1e-7):\n \"\"\"\n Compute the non-commutative generalization of the Lovasz function,\n using Theorem 9 of arXiv:1002.2514.\n\n If the long_return option is True, then the optimal solution (T, Y, etc.) is returned.\n \"\"\"\n\n if S.perp().dim() == 0:\n return 1.0\n\n ncg = GraphProperties(S)\n n = ncg.n\n\n Yb_len = ncg.Y_basis.shape[4]\n\n # x = [t, Y.A:Si * Y.A':i * Y.A':j]\n xvec_len = 1 + Yb_len\n\n idx = 1\n x_to_Y = np.zeros((n,n,n,n,xvec_len), dtype=complex)\n x_to_Y[:,:,:,:,idx:idx+Yb_len] = ncg.Y_basis\n idx += Yb_len\n\n assert idx == xvec_len\n\n phi_phi = np.zeros((n,n, n,n), dtype=complex)\n for (i, j) in itertools.product(list(range(n)), repeat=2):\n phi_phi[i, i, j, j] = 1\n phi_phi = phi_phi.reshape(n**2, n**2)\n\n # Cost vector.\n # x = [t, Y.A:Si * Y.A':i * Y.A':j]\n c = np.zeros(xvec_len)\n c[0] = 1\n\n # tI - tr_A(Y) >= 0\n Fx_1 = np.trace(x_to_Y, axis1=0, axis2=2)\n for i in range(n):\n Fx_1[i, i, 0] = -1\n F0_1 = np.zeros((n, n))\n\n # Y >= |Phi><Phi|\n Fx_2 = -x_to_Y.reshape(n**2, n**2, xvec_len).copy()\n F0_2 = -phi_phi\n\n (xvec, sdp_stats) = call_sdp(c, [Fx_1, Fx_2], [F0_1, F0_2])\n\n if sdp_stats['status'] == 'optimal':\n rho = mat_real_to_cplx(np.array(sdp_stats['zs'][0]))\n I_ot_rho = np.tensordot(np.eye(n), rho, axes=0).transpose(0,2,1,3)\n zs1 = mat_real_to_cplx(np.array(sdp_stats['zs'][1])).reshape(n,n,n,n)\n T = zs1 - I_ot_rho\n\n t = xvec[0]\n Y = np.dot(x_to_Y, xvec)\n\n # Verify primal/dual solution\n if verify_tol:\n err = collections.defaultdict(float)\n\n # Test the primal solution\n for mat in np.rollaxis(ncg.Y_basis, -1):\n dp = np.tensordot(T, mat.conj(), axes=4)\n err[r'T in Ybas.perp()'] += linalg.norm(dp)\n T_plus_Irho = T + I_ot_rho\n err[r'T_plus_Irho pos'] = check_psd(T_plus_Irho.reshape(n**2, n**2))\n err[r'Tr(rho)'] = abs(np.trace(rho) - 1)\n err[r'rho pos'] = check_psd(rho)\n\n err[r'primal value'] = abs(T.trace().trace() + 1 - t)\n\n err[r'Y - phi_phi PSD'] = check_psd(Y.reshape(n**2, n**2) - phi_phi)\n\n maxeig = linalg.eigvalsh(np.trace(Y, axis1=0, axis2=2))[-1].real\n err[r'dual value'] = abs(t - maxeig)\n\n for mat in ncg.Sp_basis:\n dp = np.tensordot(Y, mat.conj(), axes=[[0, 2], [0, 1]])\n err[r'Y in S \\ot \\bar{S}'] += linalg.norm(dp)\n\n assert min(err.values()) >= 0\n for (k, v) in err.items():\n if v > verify_tol:\n print('WARNING: err[%s] = %g' % (k, v))\n\n if long_return:\n if ncg.S._hilb_space is not None:\n ha = ncg.top_space\n hb = ncg.bottom_space\n rho = hb.O.array(rho, reshape=True)\n T = ncg.make_ab_array(T)\n Y = ncg.make_ab_array(Y)\n else:\n ha = None\n hb = None\n to_ret = [ 't', 'T', 'rho', 'Y', 'ha', 'hb', 'sdp_stats' ]\n _locals = locals()\n return { key: _locals[key] for key in to_ret }\n else:\n return t\n else:\n raise Exception('cvxopt.sdp returned error: '+sdp_stats['status'])\n\ndef szegedy(S, cones, long_return=False, verify_tol=1e-7):\n r\"\"\"\n My non-commutative generalization of Szegedy's number.\n\n .. math::\n \\max &\\left<\\Phi|T + I \\otimes \\rho|\\Phi\\right> \\textrm{ s.t.} \\\\\n &\\rho \\succeq 0, \\Tr(\\rho)=1 \\\\\n &T + I \\otimes \\rho \\succeq 0 \\\\\n &T+\\sum_i (L_i+L_i^\\dag) \\in S^\\perp * \\overline{S}^\\perp \\\\\n &R(L_i)+R(L_i)^\\dag \\in \\mathcal{C}_i^* \\quad \\forall i \\\\\n \\min &\\opnorm{Tr_A(Y)} \\textrm{ s.t.} \\\\\n &Y \\succeq \\ket{\\Phi}\\bra{\\Phi} \\\\\n &Y \\in S \\otimes \\overline{S} \\\\\n &R(Y) \\in \\mathcal{C}_i \\quad \\forall i \\\\\n &Y = Y^\\ddag \\textrm{ (redundant with above)}\n\n ``cones`` can be ``hermit``, ``psd``, ``ppt``, or ``psd&ppt``.\n\n If the long_return option is True, then the optimal solution (T, Y, etc.) is returned.\n It is possible for the value to be ``inf``, in which case the primal solution will be\n a certificate of infeasibility, with :math:`\\Tr(\\rho)=0`.\n \"\"\"\n\n if S.perp().dim() == 0:\n return 1.0\n\n ncg = GraphProperties(S)\n cones = ncg.get_cone_set(cones)\n\n for C in cones:\n assert 'R' in C\n\n n = ncg.n\n\n Ybas = ncg.Y_basis_dh\n Yb_len = Ybas.shape[4]\n\n # x = [t, Y.A:Si * Y.A':i * Y.A':j]\n xvec_len = 1 + Yb_len\n\n idx = 1\n x_to_Y = np.zeros((n,n,n,n,xvec_len), dtype=complex)\n x_to_Y[:,:,:,:,idx:idx+Yb_len] = Ybas\n idx += Yb_len\n\n assert idx == xvec_len\n\n phi_phi = np.zeros((n,n, n,n), dtype=complex)\n for (i, j) in itertools.product(list(range(n)), repeat=2):\n phi_phi[i, i, j, j] = 1\n phi_phi = phi_phi.reshape(n**2, n**2)\n\n # Cost vector.\n # x = [t, Y.A:Si * Y.A':i * Y.A':j]\n c = np.zeros(xvec_len)\n c[0] = 1\n\n # tI - tr_A(Y) >= 0\n Fx_1 = np.trace(x_to_Y, axis1=0, axis2=2)\n for i in range(n):\n Fx_1[i, i, 0] = -1\n F0_1 = np.zeros((n, n))\n\n # Y >= |Phi><Phi|\n Fx_2 = -x_to_Y.reshape(n**2, n**2, xvec_len).copy()\n F0_2 = -phi_phi\n\n Fx_econs = []\n F0_econs = []\n for v in cones:\n Fx = -np.array([ v['R'](y) for y in np.rollaxis(x_to_Y, -1) ], dtype=complex)\n Fx = np.rollaxis(Fx, 0, len(Fx.shape))\n F0 = -np.zeros((n**2, n**2), dtype=complex)\n Fx_econs.append(Fx)\n F0_econs.append(F0)\n\n Fx_list = [Fx_1, Fx_2] + Fx_econs\n F0_list = [F0_1, F0_2] + F0_econs\n\n (xvec, sdp_stats) = call_sdp(c, Fx_list, F0_list)\n\n err = collections.defaultdict(float)\n\n if sdp_stats['status'] in ['optimal', 'primal infeasible']:\n rho = mat_real_to_cplx(np.array(sdp_stats['zs'][0]))\n I_ot_rho = np.tensordot(np.eye(n), rho, axes=0).transpose(0,2,1,3)\n zs1 = mat_real_to_cplx(np.array(sdp_stats['zs'][1])).reshape(n,n,n,n)\n L_list = []\n for (i,v) in enumerate(cones):\n zsi = mat_real_to_cplx(np.array(sdp_stats['zs'][2+i]))\n # over 2 because we will later do L_i+L_i^\\dag\n L_i = v['R*'](zsi) / 2\n L_list.append(L_i)\n T = zs1 - I_ot_rho\n\n # Copy rot-antihermit portion of T to X.\n X = T - project_dh(T)\n if len(cones):\n L_list[0] -= X/2\n else:\n L_list.append(-X/2)\n X = None\n\n if sdp_stats['status'] == 'primal infeasible':\n # Rescale certificate of infeasibility so that <Phi|T|Phi>=1 exactly.\n s = T.trace().trace()\n T /= s\n rho /= s\n L_list = [ L_i/s for L_i in L_list ]\n\n # Verify dual solution (or part of it; more is done below)\n if verify_tol:\n # Test the primal solution\n L = np.sum(L_list, axis=0)\n LH = L.transpose(2,3,0,1).conj()\n TLL = T+L+LH\n\n for mat in np.rollaxis(Ybas, -1):\n dp = np.tensordot(TLL, mat.conj(), axes=4)\n err[r'T+L+L^\\dag in Ybas.perp()'] += linalg.norm(dp)\n\n if len(cones):\n for (i, (v, L_i)) in enumerate(zip(cones, L_list)):\n M = v['R'](L_i).copy()\n M += M.T.conj()\n err['R(L_i)+R(L_i)^\\dag in '+v['name']] = check_psd(M)\n\n T_plus_Irho = T + I_ot_rho\n err[r'T_plus_Irho pos'] = check_psd(T_plus_Irho.reshape(n**2, n**2))\n if sdp_stats['status'] == 'optimal':\n err[r'Tr(rho)'] = abs(np.trace(rho) - 1)\n else:\n err[r'Tr(rho)'] = abs(np.trace(rho))\n err[r'rho pos'] = check_psd(rho)\n\n # not mandatory, but we can get this condtion anyway\n TLLddag = TLL.transpose((1,0,3,2)).conj()\n err[r'R(T+L+L^\\dag) \\in Herm'] = linalg.norm(TLL-TLLddag)\n\n TH = T.transpose((2,3,0,1)).conj()\n err[r'T-T^\\dag'] = linalg.norm(T-TH)\n\n if sdp_stats['status'] == 'optimal':\n t = xvec[0]\n Y = np.dot(x_to_Y, xvec)\n\n # Verify primal/dual solution\n if verify_tol:\n err[r'primal value'] = abs(T.trace().trace() + 1 - t)\n\n err[r'Y - phi_phi PSD'] = check_psd(Y.reshape(n**2, n**2) - phi_phi)\n\n for v in cones:\n M = v['R'](Y)\n err[r'R(Y) in '+v['name']] = check_psd(M)\n\n Yddag = Y.transpose((1,0,3,2)).conj()\n err[r'Y-Y^\\ddag'] = linalg.norm(Y-Yddag)\n\n maxeig = linalg.eigvalsh(np.trace(Y, axis1=0, axis2=2))[-1].real\n err[r'dual value'] = abs(t - maxeig)\n\n if err:\n assert min(err.values()) >= 0\n for (k, v) in err.items():\n if v > verify_tol:\n print('WARNING: err[%s] = %g' % (k, v))\n\n if sdp_stats['status'] in ['optimal', 'primal infeasible']:\n if sdp_stats['status'] == 'primal infeasible':\n t = np.inf\n if long_return:\n if len(cones):\n L_map = { C['name']: L_i for (C, L_i) in zip(cones, L_list) }\n else:\n assert len(L_list)==1\n L_map = { 'hermit': L_list[0] }\n if ncg.S._hilb_space is not None:\n ha = ncg.top_space\n hb = ncg.bottom_space\n rho = hb.O.array(rho, reshape=True)\n T = ncg.make_ab_array(T)\n if sdp_stats['status'] == 'optimal':\n Y = ncg.make_ab_array(Y)\n L_map = { k: ncg.make_ab_array(L_map[k]) for k in L_map.keys() }\n else:\n ha = None\n hb = None\n to_ret = [ 't', 'T', 'rho', 'L_map', 'ha', 'hb', 'sdp_stats' ]\n if sdp_stats['status'] == 'optimal':\n to_ret += 'Y'\n _locals = locals()\n return { key: _locals[key] for key in to_ret }\n else:\n return t\n else:\n raise Exception('cvxopt.sdp returned error: '+sdp_stats['status'])\n\ndef schrijver(S, cones, long_return=False, verify_tol=1e-7):\n r\"\"\"\n My non-commutative generalization of Schrijver's number.\n\n .. math::\n \\max &\\left<\\Phi|T + I \\otimes \\rho|\\Phi\\right> \\textrm{ s.t.} \\\\\n &\\rho \\succeq 0, \\Tr(\\rho)=1 \\\\\n &T + I \\otimes \\rho \\succeq 0 \\\\\n &T \\in S^\\perp \\otimes \\overline{S}^\\perp \\\\\n &R(T) \\in \\mathcal{C}_i \\quad \\forall i \\\\\n &T = T^\\ddag \\textrm{ (redundant with above)} \\\\\n \\min &\\opnorm{Tr_A(Y)} \\textrm{ s.t.} \\\\\n &Y \\succeq \\ket{\\Phi}\\bra{\\Phi} \\\\\n &Y+\\sum_i (L_i+L_i^\\dag) \\in S * \\overline{S} \\\\\n &R(L_i)+R(L_i)^\\dag \\in \\mathcal{C}_i^* \\quad \\forall i\n\n ``cones`` can be ``hermit``, ``psd``, ``ppt``, or ``psd&ppt``.\n\n If the long_return option is True, then the optimal solution (T, Y, etc.) is returned.\n \"\"\"\n\n if S.perp().dim() == 0:\n return 1.0\n\n ncg = GraphProperties(S)\n cones = ncg.get_cone_set(cones)\n\n for C in cones:\n assert 'R' in C\n\n n = ncg.n\n\n Tbas = ncg.T_basis_dh\n Tb_len = Tbas.shape[4]\n\n # rhotf is the trace-free component of the actual rho\n rhotf_basis = TensorSubspace.from_span([np.eye(n)]).perp(). \\\n hermitian_basis().transpose((1,2,0))\n rb_len = rhotf_basis.shape[2]\n assert rb_len == n*n-1\n\n xvec_len = Tb_len + rb_len\n\n idx = 0\n x_to_T = np.zeros((n,n,n,n,xvec_len), dtype=complex)\n x_to_T[:,:,:,:,idx:idx+Tb_len] = Tbas\n idx += Tb_len\n\n x_to_rhotf = np.zeros((n,n,xvec_len), dtype=complex)\n x_to_rhotf[:,:,idx:idx+rb_len] = rhotf_basis\n idx += rb_len\n\n assert idx == xvec_len\n\n # T + I \\ot rhotf\n x_to_sum = x_to_T + \\\n np.tensordot(np.eye(n), x_to_rhotf, axes=0).transpose((0,2,1,3,4))\n\n # rho \\succeq 0\n Fx_1 = -x_to_rhotf\n F0_1 = np.eye(n)/n\n\n # T + I \\ot rho \\succeq 0\n Fx_2 = -x_to_sum.reshape(n**2, n**2, xvec_len)\n for i in range(Fx_2.shape[2]):\n assert linalg.norm(Fx_2[:,:,i] - Fx_2[:,:,i].conj().T) < 1e-10\n F0_2 = np.eye(n**2)/n\n\n c = -np.trace(np.trace(x_to_sum)).real\n\n Fx_econs = []\n F0_econs = []\n for v in cones:\n Fx = -np.array([ v['R'](y) for y in np.rollaxis(x_to_T, -1) ], dtype=complex)\n Fx = np.rollaxis(Fx, 0, len(Fx.shape))\n F0 = -np.zeros((n**2, n**2), dtype=complex)\n Fx_econs.append(Fx)\n F0_econs.append(F0)\n\n Fx_list = [Fx_1, Fx_2] + Fx_econs\n F0_list = [F0_1, F0_2] + F0_econs\n\n (xvec, sdp_stats) = call_sdp(c, Fx_list, F0_list)\n\n if sdp_stats['status'] == 'optimal':\n t = -np.dot(c, xvec) + 1\n T = np.dot(x_to_T, xvec)\n rho = np.dot(x_to_rhotf, xvec) + np.eye(n)/n\n I_rho = np.tensordot(np.eye(n), rho, axes=0).transpose(0,2,1,3)\n T_plus_Irho = np.dot(x_to_sum, xvec) + np.eye(n*n).reshape(n,n,n,n) / n\n\n J = np.zeros((n,n, n,n), dtype=complex)\n for (i, j) in itertools.product(list(range(n)), repeat=2):\n J[i, i, j, j] = 1\n\n Y = J + mat_real_to_cplx(np.array(sdp_stats['zs'][1])).reshape(n,n,n,n)\n\n L_list = []\n zs_idx = 2\n for (i,v) in enumerate(cones):\n zsi = mat_real_to_cplx(np.array(sdp_stats['zs'][2+i]))\n zs_idx += 1\n # over 2 because we will later do L+L^\\dag\n L = v['R*'](zsi) / 2\n L_list.append(L)\n assert zs_idx == len(sdp_stats['zs'])\n\n # Copy rot-antihermit portion of Y to X.\n X = Y - project_dh(Y)\n if len(cones):\n L_list[0] -= X/2\n else:\n L_list.append(-X/2)\n X = None\n\n if verify_tol:\n err = collections.defaultdict(float)\n\n # Test the primal solution\n err[r'T + I \\ot rho'] = linalg.norm(T + I_rho - T_plus_Irho)\n err['primal value'] = abs(t - T_plus_Irho.trace(axis1=0, axis2=1).trace(axis1=0, axis2=1))\n\n err['T_plus_Irho PSD'] = check_psd(T_plus_Irho.reshape(n**2, n**2))\n err['Tr(rho)'] = abs(np.trace(rho) - 1)\n err['rho PSD'] = check_psd(rho)\n\n for v in cones:\n M = v['R'](T)\n err['R(T) in '+v['name']] = check_psd(M)\n\n Tddag = T.transpose((1,0,3,2)).conj()\n err[r'T-T^\\ddag'] = linalg.norm(T-Tddag)\n\n # Test the dual solution\n err['dual value'] = abs(t - linalg.eigvalsh(Y.trace(axis1=0, axis2=2))[-1])\n\n L = np.sum(L_list, axis=0)\n LH = L.transpose(2,3,0,1).conj()\n YLL = Y+L+LH\n\n err_Y_space = 0\n for matA in ncg.Sp_basis:\n for matB in ncg.Sp_basis:\n xy = np.tensordot(matA, matB.conj(), axes=([],[])).transpose((0, 2, 1, 3))\n dp = np.tensordot(YLL, xy.conj(), axes=4)\n err_Y_space += abs(dp)\n err[r'Y+L+L^\\dag in S \\djp \\bar{S}'] = err_Y_space\n\n if len(cones):\n for (i, (v, L_i)) in enumerate(zip(cones, L_list)):\n M = v['R'](L_i).copy()\n M += M.T.conj()\n err['R(L_i) in '+v['name']] = check_psd(M)\n\n # not mandatory, but we can get this condtion anyway\n YLLddag = YLL.transpose((1,0,3,2)).conj()\n err[r'R(Y+L+L^\\dag) \\in Herm'] = linalg.norm(YLL-YLLddag)\n\n YH = Y.transpose((2,3,0,1)).conj()\n err[r'Y-Y^\\dag'] = linalg.norm(Y-YH)\n\n err['Y-J PSD'] = check_psd((Y-J).reshape(n*n, n*n))\n\n assert min(err.values()) >= 0\n for (k, v) in err.items():\n if v > verify_tol:\n print('WARNING: err[%s] = %g' % (k, v))\n\n if long_return:\n if len(cones):\n L_map = { C['name']: L_i for (C, L_i) in zip(cones, L_list) }\n else:\n assert len(L_list)==1\n L_map = { 'hermit': L_list[0] }\n if ncg.S._hilb_space is not None:\n ha = ncg.top_space\n hb = ncg.bottom_space\n rho = hb.O.array(rho, reshape=True)\n T = ncg.make_ab_array(T)\n Y = ncg.make_ab_array(Y)\n L_map = { k: ncg.make_ab_array(L_map[k]) for k in L_map.keys() }\n else:\n ha = None\n hb = None\n to_ret = [ 't', 'T', 'rho', 'Y', 'L_map', 'ha', 'hb', 'sdp_stats' ]\n _locals = locals()\n return { key: _locals[key] for key in to_ret }\n else:\n return t\n else:\n raise Exception('cvxopt.sdp returned error: '+sdp_stats['status'])\n\n### Convenience functions ================\n\ndef qthperp(S, long_return=False):\n '''\n Returns ``lovasz_theta(S.perp())``.\n ``S`` should be trace-free.\n '''\n\n return lovasz_theta(~S, long_return)\n\ndef qthmperp(S, cones, long_return=False):\n '''\n Returns ``schrijver(S.perp())``.\n ``S`` should be trace-free.\n '''\n\n return schrijver(~S, cones, long_return)\n\ndef qthpperp(S, cones, long_return=False):\n '''\n Returns ``szegedy(S.perp())``.\n ``S`` should be trace-free.\n '''\n\n return szegedy(~S, cones, long_return)\n\ndef get_many_values(S, which_ones=None):\n \"\"\"\n >>> np.random.seed(1)\n >>> S = TensorSubspace.create_random_hermitian(3, 5, tracefree=True).perp()\n >>> cvxopt.solvers.options['abstol'] = float(1e-7)\n >>> cvxopt.solvers.options['reltol'] = float(1e-7)\n >>> vals = get_many_values(S)\n >>> ', '.join([ '%s: %.5f' % (k, vals[k]) for k in sorted(vals.keys()) ])\n 'lovasz: 3.80697, schrijver(hermit): 3.31461, schrijver(ppt): 2.42820, schrijver(psd&ppt): 2.42820, schrijver(psd): 3.31461, szegedy(hermit): 4.55314, szegedy(ppt): inf, szegedy(psd&ppt): inf, szegedy(psd): 4.55314'\n \"\"\"\n\n if which_ones is None:\n which_ones = [\n 'lovasz',\n 'schrijver(hermit)',\n 'schrijver(ppt)',\n 'schrijver(psd&ppt)',\n 'schrijver(psd)',\n 'szegedy(hermit)',\n 'szegedy(ppt)',\n 'szegedy(psd&ppt)',\n 'szegedy(psd)',\n ]\n\n ret = {}\n if 'lovasz' in which_ones:\n ret['lovasz'] = lovasz_theta(S)\n for cone in ('hermit', 'ppt', 'psd', 'psd&ppt'):\n if 'schrijver('+cone+')' in which_ones:\n ret['schrijver('+cone+')'] = schrijver(S, cone)\n if 'szegedy('+cone+')' in which_ones:\n ret['szegedy('+cone+')'] = szegedy(S, cone)\n return ret\n\n### Validation code ####################\n\ndef test_lovasz(S):\n \"\"\"\n >>> ha = qudit('a', 3)\n >>> np.random.seed(1)\n >>> S = TensorSubspace.create_random_hermitian(ha, 5, tracefree=True).perp()\n >>> test_lovasz(S)\n t: 3.8069736\n total err: 0.0000000\n total err: 0.0000000\n duality gap: 0.0000000\n \"\"\"\n\n cvxopt.solvers.options['show_progress'] = False\n cvxopt.solvers.options['abstol'] = float(1e-8)\n cvxopt.solvers.options['reltol'] = float(1e-8)\n\n info = lovasz_theta(S, True)\n assert info['sdp_stats']['status'] == 'optimal'\n print('t: %.7f' % info['t'])\n (tp, errp) = check_lovasz_primal(S, *[ info[x] for x in 'rho,T'.split(',') ])\n (td, errd) = check_lovasz_dual(S, *[ info[x] for x in 'Y'.split(',') ])\n print('duality gap: %.7f' % (td-tp))\n\ndef test_schrijver(S, cones=('hermit', 'psd', 'ppt', 'psd&ppt')):\n \"\"\"\n >>> ha = qudit('a', 3)\n >>> np.random.seed(1)\n >>> S = TensorSubspace.create_random_hermitian(ha, 5, tracefree=True).perp()\n >>> test_schrijver(S)\n --- Schrijver with hermit\n t: 3.3146051\n total err: 0.0000000\n total err: 0.0000000\n duality gap: 0.0000000\n --- Schrijver with psd\n t: 3.3146051\n total err: 0.0000000\n total err: 0.0000000\n duality gap: 0.0000000\n --- Schrijver with ppt\n t: 2.4281982\n total err: 0.0000000\n total err: 0.0000000\n duality gap: -0.0000000\n --- Schrijver with psd&ppt\n t: 2.4281982\n total err: 0.0000000\n total err: 0.0000000\n duality gap: -0.0000000\n \"\"\"\n\n cvxopt.solvers.options['show_progress'] = False\n cvxopt.solvers.options['abstol'] = float(1e-8)\n cvxopt.solvers.options['reltol'] = float(1e-8)\n\n # FIXME - are 'ppt' and 'psd&ppt' always the same value?\n for cone in cones:\n print('--- Schrijver with', cone)\n info = schrijver(S, cone, True)\n assert info['sdp_stats']['status'] == 'optimal'\n print('t: %.7f' % info['t'])\n (tp, errp) = check_schrijver_primal(S, cone, *[ info[x] for x in 'rho,T'.split(',') ])\n (td, errd) = check_schrijver_dual(S, cone, *[ info[x] for x in 'Y,L_map'.split(',') ])\n print('duality gap: %.7f' % (td-tp))\n\ndef test_szegedy(S):\n \"\"\"\n >>> ha = qudit('a', 3)\n >>> np.random.seed(1)\n >>> S = TensorSubspace.create_random_hermitian(ha, 5, tracefree=True).perp()\n >>> test_szegedy(S)\n --- Szegedy with hermit\n t: 4.5531383\n total err: 0.0000000\n total err: 0.0000000\n duality gap: 0.0000000\n --- Szegedy with psd\n t: 4.5531383\n total err: 0.0000000\n total err: 0.0000000\n duality gap: -0.0000000\n --- Szegedy with ppt\n t: inf\n total err: 0.0000000\n --- Szegedy with psd&ppt\n t: inf\n total err: 0.0000000\n \"\"\"\n\n cvxopt.solvers.options['show_progress'] = False\n cvxopt.solvers.options['abstol'] = float(1e-8)\n cvxopt.solvers.options['reltol'] = float(1e-8)\n\n # FIXME - are 'ppt' and 'psd&ppt' always the same value?\n for cone in ('hermit', 'psd', 'ppt', 'psd&ppt'):\n print('--- Szegedy with', cone)\n info = szegedy(S, cone, True)\n assert info['sdp_stats']['status'] in ['optimal', 'primal infeasible']\n print('t: %.7f' % info['t'])\n is_opt = (info['sdp_stats']['status'] == 'optimal')\n info['is_opt'] = is_opt\n (tp, errp) = check_szegedy_primal(S, cone, *[ info[x] for x in 'rho,T,L_map,is_opt'.split(',') ])\n if is_opt:\n (td, errd) = check_szegedy_dual(S, cone, *[ info[x] for x in 'Y'.split(',') ])\n print('duality gap: %.7f' % (td-tp))\n\ndef check_lovasz_primal(S, rho, T, report=True):\n r\"\"\"\n Verify Lovasz primal solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, None, { 'lovasz_primal': (rho, T) }, report)\n\ndef check_lovasz_dual(S, Y, report=True):\n r\"\"\"\n Verify Lovasz dual solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, None, { 'lovasz_dual': (Y,) }, report)\n\ndef check_schrijver_primal(S, cones, rho, T, report=True):\n r\"\"\"\n Verify Schrijver primal solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, cones, { 'schrijver_primal': (rho, T) }, report)\n\ndef check_schrijver_dual(S, cones, Y, L_map, report=True):\n r\"\"\"\n Verify Schrijver dual solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, cones, { 'schrijver_dual': (Y, L_map) }, report)\n\ndef check_szegedy_primal(S, cones, rho, T, L_map, is_opt, report=True):\n r\"\"\"\n Verify Schrijver primal solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, cones, { 'szegedy_primal': (rho, T, L_map, is_opt) }, report)\n\ndef check_szegedy_dual(S, cones, Y, report=True):\n r\"\"\"\n Verify Szegedy dual solution.\n Returns ``(t, err)`` where ``t`` is the value and ``err`` is the amount by which\n feasibility constrains are violated.\n \"\"\"\n\n return checking_routine(S, cones, { 'szegedy_dual': Y }, report)\n\ndef checking_routine(S, cones, task, report):\n ncg = GraphProperties(S)\n\n if cones is not None:\n cones = ncg.get_cone_set(cones)\n cone_names = frozenset(C['name'] for C in cones)\n\n ha = ncg.top_space\n hb = ncg.bottom_space\n R = ncg.R\n ddag = ncg.ddag\n\n Sb = S.map(lambda x: x.relabel({ ha: hb, ha.H: hb.H }).conj())\n\n Phi = ha.eye().relabel({ ha.H: hb })\n J = Phi.O\n\n def proj_Sp_ot_all(x):\n ret = (ha*hb).O.array()\n for pa in S.perp():\n ret += pa * (x * pa.H).trace(ha)\n return ret\n\n def proj_Sp_ot_Sp(x):\n ret = (ha*hb).O.array()\n for pa in S.perp():\n foo = (x * pa.H).trace(ha)\n ret += pa * Sb.perp().project(foo)\n return ret\n\n def proj_S_ot_S(x):\n ret = (ha*hb).O.array()\n for pa in S:\n foo = (x * pa.H).trace(ha)\n ret += pa * Sb.project(foo)\n return ret\n\n err = {}\n\n if 'lovasz_primal' in task:\n (rho, T) = task['lovasz_primal']\n\n assert rho.space == hb.O\n assert T.space == (ha*hb).O\n val = 1 + (Phi.H * T * Phi).real\n err[r'trace(rho)'] = abs(1 - rho.trace())\n err[r'rho PSD'] = check_psd(rho)\n err[r'T + I \\ot rho PSD'] = check_psd(T + ha.eye()*rho)\n\n err[r\"T \\in S^\\perp \\ot \\linop{A'}\"] = (T - proj_Sp_ot_all(T)).norm()\n\n if 'lovasz_dual' in task:\n (Y,) = task['lovasz_dual']\n\n val = Y.trace(ha).eigvalsh()[-1]\n\n err[r'Y \\succeq J'] = check_psd(Y - J)\n\n err[r\"Y \\perp S^\\perp \\ot \\linop{A'}\"] = proj_Sp_ot_all(Y).norm()\n\n if 'schrijver_primal' in task:\n (rho, T) = task['schrijver_primal']\n\n assert rho.space == hb.O\n assert T.space == (ha*hb).O\n val = 1 + (Phi.H * T * Phi).real\n err[r'trace(rho)'] = abs(1 - rho.trace())\n err[r'rho PSD'] = check_psd(rho)\n err[r'T + I \\ot rho PSD'] = check_psd(T + ha.eye()*rho)\n err[r'T^\\ddag - T'] = (T - ddag(T)).norm()\n\n for C in cone_names:\n if C == 'psd':\n err[r'T_PSD'] = check_psd(R(T))\n elif C == 'ppt':\n err[r'T_PPT'] = check_psd(R(T).transpose(ha))\n else:\n assert 0\n\n err[r'T \\in S^\\perp \\ot \\bar{S}^\\perp'] = (T - proj_Sp_ot_Sp(T)).norm()\n\n if 'schrijver_dual' in task:\n (Y, L_map) = task['schrijver_dual']\n\n val = Y.trace(ha).eigvalsh()[-1]\n\n err[r'Y \\succeq J'] = check_psd(Y - J)\n\n L = np.sum(list(L_map.values()))\n\n err[r'Y+L+L^\\dag \\perp S^\\perp \\ot \\bar{S}^\\perp'] = proj_Sp_ot_Sp(Y+L+L.H).norm()\n\n for C in cone_names:\n L = L_map[C]\n M = R(L) + R(L).H\n if C == 'psd':\n err[r'L_PSD'] = check_psd(M)\n elif C == 'ppt':\n err[r'L_PPT'] = check_psd(M.transpose(ha))\n else:\n assert 0\n\n if 'szegedy_primal' in task:\n (rho, T, L_map, is_opt) = task['szegedy_primal']\n\n assert rho.space == hb.O\n assert T.space == (ha*hb).O\n\n if is_opt:\n val = 1 + (Phi.H * T * Phi).real\n err[r'trace(rho)'] = abs(1 - rho.trace())\n else:\n # Certificate of primal infeasibility\n val = np.inf\n err[r'trace(rho)'] = abs(rho.trace())\n err[r'<Phi|T|Phi>=1'] = abs(1-(Phi.H * T * Phi).real)\n\n err[r'rho PSD'] = check_psd(rho)\n err[r'T + I \\ot rho PSD'] = check_psd(T + ha.eye()*rho)\n\n L = np.sum(list(L_map.values()))\n\n err[r'T+L+L^\\dag \\perp S \\ot \\bar{S}'] = proj_S_ot_S(T+L+L.H).norm()\n\n for C in cone_names:\n L = L_map[C]\n M = R(L) + R(L).H\n if C == 'psd':\n err[r'L_PSD'] = check_psd(M)\n elif C == 'ppt':\n err[r'L_PPT'] = check_psd(M.transpose(ha))\n else:\n assert 0\n\n if 'szegedy_dual' in task:\n Y = task['szegedy_dual']\n\n val = Y.trace(ha).eigvalsh()[-1]\n err[r'Y \\succeq J'] = check_psd(Y - J)\n err[r'Y^\\ddag - Y'] = (Y - ddag(Y)).norm()\n\n for C in cone_names:\n if C == 'psd':\n err[r'T_PSD'] = check_psd(R(Y))\n elif C == 'ppt':\n err[r'T_PPT'] = check_psd(R(Y).transpose(ha))\n else:\n assert 0\n\n err[r'Y \\in S \\ot \\bar{S}'] = (Y - proj_S_ot_S(Y)).norm()\n\n ### Tally and report\n\n assert min(err.values()) >= 0\n\n if report:\n for (k, v) in err.items():\n if v > 1e-7:\n print('err[%s] = %g' % (k, v))\n\n print('total err: %.7f' % sum(err.values()))\n\n return (val, err)\n\n# If this module is run from the command line, run the doctests.\nif __name__ == \"__main__\":\n # Doctests require not getting progress messages from SDP solver.\n cvxopt.solvers.options['show_progress'] = False\n\n print(\"Running doctests.\")\n import doctest\n doctest.testmod()\n"
] |
[
[
"numpy.rollaxis",
"numpy.dot",
"numpy.random.random",
"numpy.sqrt",
"numpy.allclose",
"numpy.sum",
"numpy.abs",
"numpy.eye",
"numpy.bmat",
"numpy.any",
"scipy.linalg.norm",
"scipy.linalg.eigvalsh",
"numpy.tensordot",
"numpy.array",
"numpy.zeros",
"numpy.trace"
]
] |
shijh/HeadPoseEstimation-WHENet
|
[
"6e0b4bc5cfe86e9d78c0514a963dae6792b11c35"
] |
[
"whenet.py"
] |
[
"import efficientnet as efn\nimport keras\nimport numpy as np\nfrom utils import softmax\n\nclass WHENet:\n def __init__(self, snapshot=None):\n base_model = efn.EfficientNetB0(include_top=False, input_shape=(224, 224, 3))\n out = base_model.output\n out = keras.layers.GlobalAveragePooling2D()(out)\n fc_yaw = keras.layers.Dense(name='yaw_new', units=120)(out) # 3 * 120 = 360 degrees in yaw\n fc_pitch = keras.layers.Dense(name='pitch_new', units=66)(out)\n fc_roll = keras.layers.Dense(name='roll_new', units=66)(out)\n self.model = keras.models.Model(inputs=base_model.input, outputs=[fc_yaw, fc_pitch, fc_roll])\n if snapshot!=None:\n self.model.load_weights(snapshot)\n self.idx_tensor = [idx for idx in range(66)]\n self.idx_tensor = np.array(self.idx_tensor, dtype=np.float32)\n self.idx_tensor_yaw = [idx for idx in range(120)]\n self.idx_tensor_yaw = np.array(self.idx_tensor_yaw, dtype=np.float32)\n\n def get_angle(self, img):\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n img = img/255\n img = (img - mean) / std\n predictions = self.model.predict(img, batch_size=8)\n # print(\"h5 predict: \\n\", predictions)\n yaw_predicted = softmax(predictions[0])\n pitch_predicted = softmax(predictions[1])\n roll_predicted = softmax(predictions[2])\n yaw_predicted = np.sum(yaw_predicted*self.idx_tensor_yaw, axis=1)*3-180\n pitch_predicted = np.sum(pitch_predicted * self.idx_tensor, axis=1) * 3 - 99\n roll_predicted = np.sum(roll_predicted * self.idx_tensor, axis=1) * 3 - 99\n return yaw_predicted, pitch_predicted, roll_predicted"
] |
[
[
"numpy.array",
"numpy.sum"
]
] |
Code-Cornelius/python_libraries
|
[
"71c388da60e2aeb94369c3813faca93bf6a18ebf",
"71c388da60e2aeb94369c3813faca93bf6a18ebf",
"71c388da60e2aeb94369c3813faca93bf6a18ebf"
] |
[
"corai/src/data_processing_fct.py",
"corai_util/finance/src/implied_vol.py",
"corai_util/calculus/tests/test_diff_eq.py"
] |
[
"import os\n\nimport numpy as np\nfrom corai_util.tools.src.function_writer import list_of_dicts_to_json\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\n\ndef pipeline_scaling_minimax(df):\n minimax = MinMaxScaler(feature_range=(0, 1))\n minimax.fit(df)\n return minimax, minimax.transform(df)\n\n\ndef pipeline_scaling_normal(df):\n standar_normalis = StandardScaler() # norm l2 and gives a N_0,1, on each column.\n standar_normalis.fit(df.values.reshape(-1, 1))\n return standar_normalis, standar_normalis.transform(df.values.reshape(-1, 1)).reshape(-1)\n\n\ndef add_column_cyclical_features(df, col_name_time, period, start_num=0):\n \"\"\"\n Semantics:\n In order to incorporate cyclicity in input data, one can add the sin/cos of the time data (e.g.).\n\n Args:\n df: pandas dataframe.\n col_name_time (str): name of the column where the cyclicity is computed from.\n period: period in terms of values from the col_name_time.\n start_num (float): starting value of the cyclicity. Default = 0.\n\n Pre-condition:\n df's col_name_time exists.\n\n Post-condition:\n df's col_name_time is removed.\n df's 'sin_{col_name_time}' and 'cos_{col_name_time}' are created.\n\n Returns:\n The new dataframe that needs to be reassigned.\n \"\"\"\n values = 2 * np.pi * (df[col_name_time] - start_num) / period\n kwargs = {f'sin_{col_name_time}': lambda x: np.sin(values),\n f'cos_{col_name_time}': lambda x: np.cos(values)}\n return df.assign(**kwargs).drop(columns=[col_name_time])\n",
"# normal libraries\nimport warnings\n\nimport numpy as np\nfrom scipy.optimize import bisect\nfrom scipy.stats import norm\n\n# priv_libraries\nfrom corai_util.finance.src.bs_model import BlackScholes, BlackScholesVegaCore\nfrom corai_util.calculus.src.optimization import newtons_method_vectorised\n\n\n\n# section ######################################################################\n# #############################################################################\n# IV\n\n\n\ndef implied_vol_bisect(CallPutFlag, s0, K, T, R, d, experimented_price):\n \"\"\"\n\n Args:\n CallPutFlag:\n s0: starting point of the S's,\n K: strike price\n T:\n R:\n d:\n experimented_price:\n\n Returns:\n\n \"\"\"\n\n # Bisection algorithm when the Lee-Li algorithm breaks down\n def _smileMin(vol, *args):\n K, s0, T, r, price = args\n return price - BlackScholes(CallPutFlag, s0, K, T, r, d, sigma=vol)\n\n vMin, vMax = 0.00001, 20.\n # in order to find the implied volatility, one has to find the value at which smileMin crosses zero.\n try:\n return bisect(_smileMin, vMin, vMax, args=(K, s0, T, R, experimented_price),\n xtol=1e-20,\n rtol=1e-15,\n full_output=False, disp=True)\n except ValueError:\n warnings.warn(\"Bisect didn't find the implied volatility \\sigma_{IMP}, returned NaN.\")\n return np.NaN\n\n\ndef implied_volatility_newton(CallPutFlag, s0, K, T, R, d, experimented_price):\n \"\"\"\n Compute Implied Volatility by newton's method.\n The function is vectorised regarding K.\n\n Args:\n CallPutFlag:\n d: dividends\n K: strike price\n s0: initial price\n T: maturity\n R: rate of interest rates\n experimented_price: price of the underlying\n\n Returns: the Implied Volatility \\sigma_imp\n\n \"\"\"\n assert len(K) == len(experimented_price)\n\n fx = lambda varSIGMA, indices: BlackScholes(CallPutFlag, s0, K[indices],\n T, R, d, sigma=varSIGMA[indices]) - experimented_price[indices]\n dfx = lambda varSIGMA, indices: BlackScholesVegaCore(np.exp(-R * T), np.exp((R - d) * T) * s0,\n K[indices], T, varSIGMA[indices])\n try:\n x = np.full(len(experimented_price), 1.)\n newtons_method_vectorised(fx, dfx, x)\n return x\n except ValueError:\n warnings.warn(\"Bisect did not find the $\\sigma_{IMP}$, returned NaN.\")\n return np.NaN\n\n\n# section ######################################################################\n# #############################################################################\n# Total IV\n\ndef total_implied_vol_bisect(CallPutFlag, s0, K, R, d, experimented_price):\n sigma = implied_vol_bisect(CallPutFlag, s0, K, 1, R, d, experimented_price)\n return sigma * sigma\n\n\ndef total_implied_vol_newton(CallPutFlag, s0, K, R, d, experimented_price):\n sigma = implied_volatility_newton(CallPutFlag, s0, K, 1, R, d, experimented_price)\n return sigma * sigma\n\n",
"from unittest import TestCase\n\nimport numpy as np\nfrom scipy.stats import norm, uniform, lognorm\n\nfrom corai_util.calculus import diff_eq\nfrom corai_util.tools import function_iterable\n\n\nclass Test_diff_eq(TestCase):\n def test_fractional_adams(self):\n pass\n\n def test_system_ode_solver(self):\n # example taken from the paper Hobson Klimmek 2015\n\n UNIFORM_SUPP = [[-1., 1.],\n [-2.,\n 2.]] # UNIFORM_SUPP[0][0] <= UNIFORM_SUPP[1][0] <= UNIFORM_SUPP[1][1] <= UNIFORM_SUPP[1][0]\n\n density_1 = lambda tt: uniform.pdf(tt,\n loc=UNIFORM_SUPP[0][0],\n scale=UNIFORM_SUPP[0][1] - UNIFORM_SUPP[0][0])\n density_2 = lambda tt: uniform.pdf(tt,\n loc=UNIFORM_SUPP[1][0],\n scale=UNIFORM_SUPP[1][1] - UNIFORM_SUPP[1][0])\n\n def density_mu(tt):\n return density_1(tt)\n\n def density_nu(tt):\n return density_2(tt)\n\n def density_eta(tt):\n return np.maximum(density_mu(tt) - density_nu(tt), 0)\n\n def density_gamma(tt):\n return np.maximum(density_nu(tt) - density_mu(tt), 0)\n\n def p_dash_open_formula(tt, xx, yy):\n return (tt - yy) / (yy - xx) * density_eta(tt) / density_gamma(xx)\n\n def q_dash_open_formula(tt, xx, yy):\n return (xx - tt) / (yy - xx) * density_eta(tt) / density_gamma(yy)\n\n tt = np.linspace(-1 * 0.999, 0.5, 1000)\n starting_points = [[1.99, -1.01], [1.01, -1.99]]\n # forward equation\n empirical = diff_eq.system_ODE_solver(tt, starting_points[0],\n [p_dash_open_formula, q_dash_open_formula],\n left_or_right=\"left\")\n q, p = zip(*empirical)\n p = function_iterable.replace_nans_numpy(np.array(p))\n q = function_iterable.replace_nans_numpy(np.array(q))\n\n true_p = lambda tt: -1 / 2 * (np.sqrt(12. - 3. * tt * tt) + tt)\n true_q = lambda tt: 1 / 2 * (np.sqrt(12. - 3. * tt * tt) - tt)\n error = np.mean(np.abs(function_iterable.replace_nans_numpy(p) - true_p(tt)))\n error += np.mean(np.abs(function_iterable.replace_nans_numpy(q) - true_q(tt)))\n\n # backward equation\n tt = np.linspace(-0.5, 1 * 0.999, 2000)\n # forward equation\n empirical = diff_eq.system_ODE_solver(tt, starting_points[1],\n [p_dash_open_formula, q_dash_open_formula],\n left_or_right=\"left\")\n q, p = zip(*empirical)\n p = function_iterable.replace_nans_numpy(np.array(p))\n q = function_iterable.replace_nans_numpy(np.array(q))\n error += np.mean(function_iterable.replace_nans_numpy(p) - true_p(tt))\n error += np.mean(function_iterable.replace_nans_numpy(q) - true_q(tt))\n\n assert error < 0.1\n"
] |
[
[
"sklearn.preprocessing.StandardScaler",
"numpy.cos",
"sklearn.preprocessing.MinMaxScaler",
"numpy.sin"
],
[
"scipy.optimize.bisect",
"numpy.exp"
],
[
"scipy.stats.uniform.pdf",
"numpy.array",
"numpy.sqrt",
"numpy.linspace"
]
] |
isl-org/faiss
|
[
"908812266c4472b0ab07ac46a5a65635cdad8bb5"
] |
[
"contrib/exhaustive_search.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport faiss\nimport time\nimport numpy as np\n\nimport logging\n\nLOG = logging.getLogger(__name__)\n\ndef knn_ground_truth(xq, db_iterator, k, metric_type=faiss.METRIC_L2):\n \"\"\"Computes the exact KNN search results for a dataset that possibly\n does not fit in RAM but for which we have an iterator that\n returns it block by block.\n \"\"\"\n LOG.info(\"knn_ground_truth queries size %s k=%d\" % (xq.shape, k))\n t0 = time.time()\n nq, d = xq.shape\n rh = faiss.ResultHeap(nq, k)\n\n index = faiss.IndexFlat(d, metric_type)\n if faiss.get_num_gpus():\n LOG.info('running on %d GPUs' % faiss.get_num_gpus())\n index = faiss.index_cpu_to_all_gpus(index)\n\n # compute ground-truth by blocks, and add to heaps\n i0 = 0\n for xbi in db_iterator:\n ni = xbi.shape[0]\n index.add(xbi)\n D, I = index.search(xq, k)\n I += i0\n rh.add_result(D, I)\n index.reset()\n i0 += ni\n LOG.info(\"%d db elements, %.3f s\" % (i0, time.time() - t0))\n\n rh.finalize()\n LOG.info(\"GT time: %.3f s (%d vectors)\" % (time.time() - t0, i0))\n\n return rh.D, rh.I\n\n# knn function used to be here\nknn = faiss.knn\n\n\n\n\ndef range_search_gpu(xq, r2, index_gpu, index_cpu):\n \"\"\"GPU does not support range search, so we emulate it with\n knn search + fallback to CPU index.\n\n The index_cpu can either be a CPU index or a numpy table that will\n be used to construct a Flat index if needed.\n \"\"\"\n nq, d = xq.shape\n LOG.debug(\"GPU search %d queries\" % nq)\n k = min(index_gpu.ntotal, 1024)\n D, I = index_gpu.search(xq, k)\n if index_gpu.metric_type == faiss.METRIC_L2:\n mask = D[:, k - 1] < r2\n else:\n mask = D[:, k - 1] > r2\n if mask.sum() > 0:\n LOG.debug(\"CPU search remain %d\" % mask.sum())\n if isinstance(index_cpu, np.ndarray):\n # then it in fact an array that we have to make flat\n xb = index_cpu\n index_cpu = faiss.IndexFlat(d, index_gpu.metric_type)\n index_cpu.add(xb)\n lim_remain, D_remain, I_remain = index_cpu.range_search(xq[mask], r2)\n LOG.debug(\"combine\")\n D_res, I_res = [], []\n nr = 0\n for i in range(nq):\n if not mask[i]:\n if index_gpu.metric_type == faiss.METRIC_L2:\n nv = (D[i, :] < r2).sum()\n else:\n nv = (D[i, :] > r2).sum()\n D_res.append(D[i, :nv])\n I_res.append(I[i, :nv])\n else:\n l0, l1 = lim_remain[nr], lim_remain[nr + 1]\n D_res.append(D_remain[l0:l1])\n I_res.append(I_remain[l0:l1])\n nr += 1\n lims = np.cumsum([0] + [len(di) for di in D_res])\n return lims, np.hstack(D_res), np.hstack(I_res)\n\n\ndef range_ground_truth(xq, db_iterator, threshold, metric_type=faiss.METRIC_L2,\n shard=False, ngpu=-1):\n \"\"\"Computes the range-search search results for a dataset that possibly\n does not fit in RAM but for which we have an iterator that\n returns it block by block.\n \"\"\"\n nq, d = xq.shape\n t0 = time.time()\n xq = np.ascontiguousarray(xq, dtype='float32')\n\n index = faiss.IndexFlat(d, metric_type)\n if ngpu == -1:\n ngpu = faiss.get_num_gpus()\n if ngpu:\n LOG.info('running on %d GPUs' % ngpu)\n co = faiss.GpuMultipleClonerOptions()\n co.shard = shard\n index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)\n\n # compute ground-truth by blocks\n i0 = 0\n D = [[] for _i in range(nq)]\n I = [[] for _i in range(nq)]\n all_lims = []\n for xbi in db_iterator:\n ni = xbi.shape[0]\n if ngpu > 0:\n index_gpu.add(xbi)\n lims_i, Di, Ii = range_search_gpu(xq, threshold, index_gpu, xbi)\n index_gpu.reset()\n else:\n index.add(xbi)\n lims_i, Di, Ii = index.range_search(xq, threshold)\n index.reset()\n Ii += i0\n for j in range(nq):\n l0, l1 = lims_i[j], lims_i[j + 1]\n if l1 > l0:\n D[j].append(Di[l0:l1])\n I[j].append(Ii[l0:l1])\n i0 += ni\n LOG.info(\"%d db elements, %.3f s\" % (i0, time.time() - t0))\n\n empty_I = np.zeros(0, dtype='int64')\n empty_D = np.zeros(0, dtype='float32')\n # import pdb; pdb.set_trace()\n D = [(np.hstack(i) if i != [] else empty_D) for i in D]\n I = [(np.hstack(i) if i != [] else empty_I) for i in I]\n sizes = [len(i) for i in I]\n assert len(sizes) == nq\n lims = np.zeros(nq + 1, dtype=\"uint64\")\n lims[1:] = np.cumsum(sizes)\n return lims, np.hstack(D), np.hstack(I)\n\n\ndef threshold_radius_nres(nres, dis, ids, thresh):\n \"\"\" select a set of results \"\"\"\n mask = dis < thresh\n new_nres = np.zeros_like(nres)\n o = 0\n for i, nr in enumerate(nres):\n nr = int(nr) # avoid issues with int64 + uint64\n new_nres[i] = mask[o : o + nr].sum()\n o += nr\n return new_nres, dis[mask], ids[mask]\n\n\ndef threshold_radius(lims, dis, ids, thresh):\n \"\"\" restrict range-search results to those below a given radius \"\"\"\n mask = dis < thresh\n new_lims = np.zeros_like(lims)\n n = len(lims) - 1\n for i in range(n):\n l0, l1 = lims[i], lims[i + 1]\n new_lims[i + 1] = new_lims[i] + mask[l0:l1].sum()\n return new_lims, dis[mask], ids[mask]\n\n\ndef apply_maxres(res_batches, target_nres):\n \"\"\"find radius that reduces number of results to target_nres, and\n applies it in-place to the result batches used in range_search_max_results\"\"\"\n alldis = np.hstack([dis for _, dis, _ in res_batches])\n alldis.partition(target_nres)\n radius = alldis[target_nres]\n\n if alldis.dtype == 'float32':\n radius = float(radius)\n else:\n radius = int(radius)\n LOG.debug(' setting radius to %s' % radius)\n totres = 0\n for i, (nres, dis, ids) in enumerate(res_batches):\n nres, dis, ids = threshold_radius_nres(nres, dis, ids, radius)\n totres += len(dis)\n res_batches[i] = nres, dis, ids\n LOG.debug(' updated previous results, new nb results %d' % totres)\n return radius, totres\n\n\ndef range_search_max_results(index, query_iterator, radius,\n max_results=None, min_results=None,\n shard=False, ngpu=0):\n \"\"\"Performs a range search with many queries (given by an iterator)\n and adjusts the threshold on-the-fly so that the total results\n table does not grow larger than max_results.\n\n If ngpu != 0, the function moves the index to this many GPUs to\n speed up search.\n \"\"\"\n\n if max_results is not None:\n if min_results is None:\n min_results = int(0.8 * max_results)\n\n if ngpu == -1:\n ngpu = faiss.get_num_gpus()\n\n if ngpu:\n LOG.info('running on %d GPUs' % ngpu)\n co = faiss.GpuMultipleClonerOptions()\n co.shard = shard\n index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)\n\n t_start = time.time()\n t_search = t_post_process = 0\n qtot = totres = raw_totres = 0\n res_batches = []\n\n for xqi in query_iterator:\n t0 = time.time()\n if ngpu > 0:\n lims_i, Di, Ii = range_search_gpu(xqi, radius, index_gpu, index)\n else:\n lims_i, Di, Ii = index.range_search(xqi, radius)\n\n nres_i = lims_i[1:] - lims_i[:-1]\n raw_totres += len(Di)\n qtot += len(xqi)\n\n t1 = time.time()\n if xqi.dtype != np.float32:\n # for binary indexes\n # weird Faiss quirk that returns floats for Hamming distances\n Di = Di.astype('int16')\n\n totres += len(Di)\n res_batches.append((nres_i, Di, Ii))\n\n if max_results is not None and totres > max_results:\n LOG.info('too many results %d > %d, scaling back radius' %\n (totres, max_results))\n radius, totres = apply_maxres(res_batches, min_results)\n t2 = time.time()\n t_search += t1 - t0\n t_post_process += t2 - t1\n LOG.debug(' [%.3f s] %d queries done, %d results' % (\n time.time() - t_start, qtot, totres))\n\n LOG.info(' search done in %.3f s + %.3f s, total %d results, end threshold %g' % (\n t_search, t_post_process, totres, radius))\n\n nres = np.hstack([nres_i for nres_i, dis_i, ids_i in res_batches])\n dis = np.hstack([dis_i for nres_i, dis_i, ids_i in res_batches])\n ids = np.hstack([ids_i for nres_i, dis_i, ids_i in res_batches])\n\n lims = np.zeros(len(nres) + 1, dtype='uint64')\n lims[1:] = np.cumsum(nres)\n\n return radius, lims, dis, ids\n"
] |
[
[
"numpy.hstack",
"numpy.ascontiguousarray",
"numpy.cumsum",
"numpy.zeros_like",
"numpy.zeros"
]
] |
NatalieHanzhina/bayesian_retinanet_tf2
|
[
"a34290cb3e837ff67de73fc74a9a1899f14fa46c"
] |
[
"keras_retinanet/utils/tf_version.py"
] |
[
"\"\"\"\nCopyright 2017-2019 Fizyr (https://fizyr.com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport sys\n\nMINIMUM_TF_VERSION = 2, 2, 0\nBLACKLISTED_TF_VERSIONS = []\n\n\ndef tf_version():\n \"\"\" Get the Tensorflow version.\n Returns\n tuple of (major, minor, patch).\n \"\"\"\n return tuple(map(int, tf.version.VERSION.split('-')[0].split('.')))\n\n\ndef tf_version_ok(minimum_tf_version=MINIMUM_TF_VERSION, blacklisted=BLACKLISTED_TF_VERSIONS):\n \"\"\" Check if the current Tensorflow version is higher than the minimum version.\n \"\"\"\n return tf_version() >= minimum_tf_version and tf_version() not in blacklisted\n\n\ndef assert_tf_version(minimum_tf_version=MINIMUM_TF_VERSION, blacklisted=BLACKLISTED_TF_VERSIONS):\n \"\"\" Assert that the Tensorflow version is up to date.\n \"\"\"\n detected = tf.version.VERSION\n required = '.'.join(map(str, minimum_tf_version))\n assert(tf_version_ok(minimum_tf_version, blacklisted)), 'You are using tensorflow version {}. The minimum required version is {} (blacklisted: {}).'.format(detected, required, blacklisted)\n\n\ndef check_tf_version():\n \"\"\" Check that the Tensorflow version is up to date. If it isn't, print an error message and exit the script.\n \"\"\"\n try:\n assert_tf_version()\n except AssertionError as e:\n print(e, file=sys.stderr)\n sys.exit(1)\n"
] |
[
[
"tensorflow.version.VERSION.split"
]
] |
Indy4G/Web-Design-Challenge
|
[
"3e540217268b98b2874992c87836912791053484"
] |
[
"docs/csv_to_html.py"
] |
[
"import pandas as pd\ndf = pd.read_csv(\"Resources/cities.csv\")\ndf.to_html('raw_data.html',classes=[\"table-bordered\", \"table-striped\", \"table-hover\"])\n"
] |
[
[
"pandas.read_csv"
]
] |
dingdian110/alpha-ml
|
[
"d6a7a8a8a3452a7e3362bf0ef32b9ac5fe215fde",
"d6a7a8a8a3452a7e3362bf0ef32b9ac5fe215fde",
"d6a7a8a8a3452a7e3362bf0ef32b9ac5fe215fde"
] |
[
"alphaml/datasets/rgs_dataset/dataset_loader.py",
"alphaml/datasets/cls_dataset/mammography.py",
"alphaml/engine/components/models/regression/libsvm_svr.py"
] |
[
"data_dir_template = 'data/rgs_data/%s/'\n\n\ndef load_data(dataset_name):\n if dataset_name == 'boston':\n from sklearn.datasets import load_boston\n boston=load_boston()\n X, y = boston.data, boston.target\n else:\n raise ValueError('Invalid dataset name: %s!' % dataset_name)\n print(X.shape, y.shape)\n print(min(y), max(y))\n return X, y, None\n",
"import pandas as pd\nfrom alphaml.datasets.utils import trans_label\n\ndef load_mammography(data_folder):\n file_path = data_folder + 'mammography.csv'\n data = pd.read_csv(file_path, delimiter=',').values\n return data[:, :-1], trans_label(data[:, -1])\n",
"from ConfigSpace.configuration_space import ConfigurationSpace\nfrom ConfigSpace.conditions import EqualsCondition, InCondition\nfrom ConfigSpace.hyperparameters import UniformFloatHyperparameter, \\\n UniformIntegerHyperparameter, CategoricalHyperparameter, \\\n UnParametrizedHyperparameter\nfrom alphaml.utils.constants import *\nfrom alphaml.utils.model_util import softmax\nfrom alphaml.utils.common import check_none, check_for_bool\nfrom alphaml.engine.components.models.base_model import BaseRegressionModel\n\n\nclass LibSVM_SVR(BaseRegressionModel):\n def __init__(self, C, kernel, gamma, shrinking, tol, max_iter,\n degree=3, coef0=0, random_state=None):\n self.C = C\n self.kernel = kernel\n self.degree = degree\n self.gamma = gamma\n self.coef0 = coef0\n self.shrinking = shrinking\n self.tol = tol\n self.max_iter = max_iter\n self.random_state = random_state\n self.estimator = None\n\n def fit(self, X, Y):\n from sklearn.svm import SVR\n\n self.C = float(self.C)\n if self.degree is None:\n self.degree = 3\n else:\n self.degree = int(self.degree)\n if self.gamma is None:\n self.gamma = 0.0\n else:\n self.gamma = float(self.gamma)\n if self.coef0 is None:\n self.coef0 = 0.0\n else:\n self.coef0 = float(self.coef0)\n self.tol = float(self.tol)\n self.max_iter = float(self.max_iter)\n\n self.shrinking = check_for_bool(self.shrinking)\n\n self.estimator = SVR(C=self.C,\n kernel=self.kernel,\n degree=self.degree,\n gamma=self.gamma,\n coef0=self.coef0,\n shrinking=self.shrinking,\n tol=self.tol,\n max_iter=self.max_iter)\n self.estimator.fit(X, Y)\n return self\n\n def predict(self, X):\n if self.estimator is None:\n raise NotImplementedError\n return self.estimator.predict(X)\n\n @staticmethod\n def get_properties(dataset_properties=None):\n return {'shortname': 'LibSVM-SVR',\n 'name': 'LibSVM Support Vector Regression',\n 'handles_regression': True,\n 'handles_classification': False,\n 'handles_multiclass': False,\n 'handles_multilabel': False,\n 'is_deterministic': True,\n 'input': (DENSE, SPARSE, UNSIGNED_DATA),\n 'output': (PREDICTIONS,)}\n\n @staticmethod\n def get_hyperparameter_search_space(dataset_properties=None):\n C = UniformFloatHyperparameter(\"C\", 0.03125, 32768, log=True,\n default_value=1.0)\n # No linear kernel here, because we have liblinear\n kernel = CategoricalHyperparameter(name=\"kernel\",\n choices=[\"rbf\", \"poly\", \"sigmoid\"],\n default_value=\"rbf\")\n degree = UniformIntegerHyperparameter(\"degree\", 2, 5, default_value=3)\n gamma = UniformFloatHyperparameter(\"gamma\", 3.0517578125e-05, 8,\n log=True, default_value=0.1)\n # TODO this is totally ad-hoc\n coef0 = UniformFloatHyperparameter(\"coef0\", -1, 1, default_value=0)\n # probability is no hyperparameter, but an argument to the SVM algo\n shrinking = CategoricalHyperparameter(\"shrinking\", [\"True\", \"False\"],\n default_value=\"True\")\n tol = UniformFloatHyperparameter(\"tol\", 1e-5, 1e-1, default_value=1e-3,\n log=True)\n # cache size is not a hyperparameter, but an argument to the program!\n max_iter = UnParametrizedHyperparameter(\"max_iter\", 2000)\n\n cs = ConfigurationSpace()\n cs.add_hyperparameters([C, kernel, degree, gamma, coef0, shrinking,\n tol, max_iter])\n\n degree_depends_on_poly = EqualsCondition(degree, kernel, \"poly\")\n coef0_condition = InCondition(coef0, kernel, [\"poly\", \"sigmoid\"])\n cs.add_condition(degree_depends_on_poly)\n cs.add_condition(coef0_condition)\n\n return cs\n"
] |
[
[
"sklearn.datasets.load_boston"
],
[
"pandas.read_csv"
],
[
"sklearn.svm.SVR"
]
] |
boryana-ilieva/respy
|
[
"c3f600eefbb54d4f34ae2cc1e52d4d32c03ba0dc"
] |
[
"doc/graphs/_modules/auxiliary_samples.py"
] |
[
"\"\"\" This module contains auxiliary functions to plot some information on the\nRESTUD economy.\n\"\"\"\n\n# standard library\nimport matplotlib.pylab as plt\nimport numpy as np\nimport shutil\nimport shlex\nimport os\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.ticker import FuncFormatter\nfrom matplotlib import cm\n\n# Evaluation points\nEDU, EXP_A, EXP_B = 10.00, 5, 5\n\n\"\"\" Auxiliary function\n\"\"\"\n\ndef prepare_directories(SPECS):\n\n for spec in SPECS:\n dirname = 'data_' + spec\n try:\n shutil.rmtree(dirname)\n except OSError:\n pass\n\n os.mkdir(dirname)\n\n\ndef wage_function(edu, exp_A, exp_B, coeffs):\n \"\"\" This function calculates the expected wage based on an agent's\n covariates for a given parameterization.\n \"\"\"\n\n # Intercept\n wage = coeffs[0]\n\n # Schooling\n wage += coeffs[1] * edu\n\n # Experience A\n wage += coeffs[2] * exp_A\n wage += coeffs[3] * exp_A ** 2\n\n # Experience B\n wage += coeffs[4] * exp_B\n wage += coeffs[5] * exp_B ** 2\n\n # Transformation\n wage = np.exp(wage)\n\n # Finishing\n return wage\n\n\ndef return_to_experience(exp_A, exp_B, coeffs, which):\n \"\"\" Wrapper to evaluate the wage function for varying levels of experience.\n \"\"\"\n # Get wage\n wage = wage_function(EDU, exp_A, exp_B, coeffs[which])\n\n # Finishing\n return wage\n\n\n# Auxiliary function\ndef return_to_education(edu, coeffs, which):\n \"\"\" Wrapper to evaluate the wage function for varying levels of education\n \"\"\"\n # Get wage\n wage = wage_function(edu, EXP_A, EXP_B, coeffs[which])\n\n # Finishing\n return wage\n\n\"\"\" Plotting functions\n\"\"\"\n\n\ndef get_choice_probabilities(fname):\n \"\"\" Get the choice probabilities.\n \"\"\"\n # Initialize container.\n stats = np.tile(np.nan, (0, 4))\n\n with open(fname) as in_file:\n\n for line in in_file.readlines():\n\n # Split line\n list_ = shlex.split(line)\n\n # Skip empty lines\n if not list_:\n continue\n\n # If OUTCOMES is reached, then we are done for good.\n if list_[0] == 'Outcomes':\n break\n\n # Any lines that do not have an integer as their first element\n # are not of interest.\n try:\n int(list_[0])\n except ValueError:\n continue\n\n # All lines that make it down here are relevant.\n stats = np.vstack((stats, [float(x) for x in list_[1:]]))\n\n # Finishing\n return stats\n\n\ndef plot_return_experience(x, y, z, spec):\n \"\"\" Function to produce plot for the return to experience.\n \"\"\"\n def _beautify_subplot(subplot, zlim):\n subplot.view_init(azim=180 + 40)\n\n subplot.set_ylabel('Experience A')\n subplot.set_xlabel('Experience B')\n subplot.set_zlabel('Wages')\n\n subplot.zaxis.set_rotate_label(False)\n subplot.set_zlabel(r'Wages (in \\$1,000)', rotation=90)\n\n subplot.zaxis.get_major_ticks()[0].set_visible(False)\n\n # Background Color (higher numbers are lighter)\n subplot.w_xaxis.set_pane_color((0.8, 0.8, 0.8, 1.0))\n subplot.w_yaxis.set_pane_color((0.6, 0.6, 0.6, 1.0))\n subplot.w_zaxis.set_pane_color((0.68, 0.68, 0.68, 1.0))\n\n ax.set_zlim(zlim)\n\n # Scaling\n z['a'] = z['a'] / 1000\n z['b'] = z['b'] / 1000\n if spec == 'one':\n zlim = [10, 35]\n elif spec == 'two':\n zlim = [0, 55]\n elif spec == 'three':\n zlim = [0, 55]\n\n fig = plt.figure(figsize=(16, 8))\n\n\n ax = fig.add_subplot(121, projection='3d')\n ax.plot_surface(x, y, z['a'], rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False, alpha=0.8)\n _beautify_subplot(ax, zlim)\n\n\n\n ax = fig.add_subplot(122, projection='3d')\n ax.plot_surface(x, y, z['b'], rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False, alpha=0.8)\n _beautify_subplot(ax, zlim)\n\n # Write out to\n plt.savefig('data_' + spec.lower() + '/returns_experience.png', bbox_inches='tight', format='png')\n\n\ndef plot_return_education(xvals, yvals, spec):\n \"\"\" Function to produce plot for the return to education.\n \"\"\"\n\n labels = ['Occupation A', 'Occupation B']\n\n # Initialize plot\n ax = plt.figure(figsize=(12, 8)).add_subplot(111)\n\n # Scaling\n for occu in ['a', 'b']:\n for i, _ in enumerate(xvals):\n yvals[occu][i] = yvals[occu][i] / 1000\n\n # Draw lines\n ax.plot(xvals, yvals['a'], '-k', label='Occupation A', linewidth=5,\n color='red', alpha=0.8)\n ax.plot(xvals, yvals['b'], '-k', label='Occupation B', linewidth=5,\n color='orange', alpha=0.8)\n\n # Both axes\n ax.tick_params(labelsize=16, direction='out', axis='both', top='off',\n right='off')\n\n # x-axis\n ax.set_xticklabels(ax.get_xticks().astype(int))\n ax.set_xlabel('Years of Schooling', fontsize=16)\n\n # y-axis\n yticks = ['{:,.0f}'.format(y) for y in ax.get_yticks().astype(int)]\n ax.set_yticklabels(yticks, fontsize=16)\n\n ax.set_ylabel(r'Wages (in \\$1,000)', fontsize=16)\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n\n # Set up legend\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10),\n fancybox=False, frameon=False, shadow=False, ncol=2, fontsize=20)\n\n # Write out to\n plt.savefig('data_' + spec.lower() + '/returns_schooling.png',\n bbox_inches='tight', format='png')\n\n\ndef plot_choice_patterns(choice_probabilities, task):\n \"\"\" Function to produce plot for choice patterns.\n \"\"\"\n\n deciles = range(40)\n colors = ['blue', 'yellow', 'orange', 'red']\n width = 0.9\n\n # Plotting\n bottom = [0] * 40\n\n # Initialize plot\n ax = plt.figure(figsize=(12, 8)).add_subplot(111)\n labels = ['Home', 'School', 'Occupation A', 'Occupation B']\n for j, i in enumerate([3, 2, 0, 1]):\n heights = choice_probabilities[:, i]\n plt.bar(deciles, heights, width, bottom=bottom, color=colors[j],\n alpha=0.70)\n bottom = [heights[i] + bottom[i] for i in range(40)]\n\n # Both Axes\n ax.tick_params(labelsize=16, direction='out', axis='both',\n top='off',\n right='off')\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n # X axis\n ax.set_xlabel('Period', fontsize=16)\n ax.set_xlim([0, 40])\n\n # Y axis\n ax.set_ylabel('Share of Population', fontsize=16)\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n\n # Legend\n plt.legend(labels, loc='upper center', bbox_to_anchor=(0.5, -0.10),\n fancybox=False, frameon=False, shadow=False, ncol=4,\n fontsize=20)\n\n # Write out to\n plt.savefig('choices_' + task + '.png', bbox_inches='tight',\n format='png')\n"
] |
[
[
"matplotlib.pylab.bar",
"numpy.tile",
"matplotlib.pylab.figure",
"matplotlib.pylab.legend",
"matplotlib.pylab.savefig",
"numpy.exp"
]
] |
caymansimpson/reuniclusVGC
|
[
"d30522f4d2eb2fc2d6aa9ed71905b9e6aab87c37"
] |
[
"tests/rl_with_open_ai_gym_wrapper.py"
] |
[
"# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\n\nimport sys\n\nsys.path.append(\".\") # will make \"bots\" callable from root\nsys.path.append(\"..\") # will make \"bots\" callable from simulators\nsys.path.append('/Users/cayman/Repositories/poke-env/src')\n\nfrom poke_env.player.env_player import Gen8EnvSinglePlayer\nfrom poke_env.player.random_player import RandomPlayer\n\nfrom rl.agents.dqn import DQNAgent\nfrom rl.policy import LinearAnnealedPolicy, EpsGreedyQPolicy\nfrom rl.memory import SequentialMemory\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\n\n\n# We define our RL player\n# It needs a state embedder and a reward computer, hence these two methods\nclass SimpleRLPlayer(Gen8EnvSinglePlayer):\n def embed_battle(self, battle):\n # -1 indicates that the move does not have a base power\n # or is not available\n moves_base_power = -np.ones(4)\n moves_dmg_multiplier = np.ones(4)\n for i, move in enumerate(battle.available_moves):\n moves_base_power[i] = (\n move.base_power / 100\n ) # Simple rescaling to facilitate learning\n if move.type:\n moves_dmg_multiplier[i] = move.type.damage_multiplier(\n battle.opponent_active_pokemon.type_1,\n battle.opponent_active_pokemon.type_2,\n )\n\n # We count how many pokemons have not fainted in each team\n remaining_mon_team = (\n len([mon for mon in battle.team.values() if mon.fainted]) / 6\n )\n remaining_mon_opponent = (\n len([mon for mon in battle.opponent_team.values() if mon.fainted]) / 6\n )\n\n # Final vector with 10 components\n return np.concatenate(\n [\n moves_base_power,\n moves_dmg_multiplier,\n [remaining_mon_team, remaining_mon_opponent],\n ]\n )\n\n def compute_reward(self, battle) -> float:\n return self.reward_computing_helper(\n battle, fainted_value=2, hp_value=1, victory_value=30\n )\n\n\nclass MaxDamagePlayer(RandomPlayer):\n def choose_move(self, battle):\n # If the player can attack, it will\n if battle.available_moves:\n # Finds the best move among available ones\n best_move = max(battle.available_moves, key=lambda move: move.base_power)\n return self.create_order(best_move)\n\n # If no attack is available, a random switch will be made\n else:\n return self.choose_random_move(battle)\n\n\nNB_TRAINING_STEPS = 10000\nNB_EVALUATION_EPISODES = 100\n\ntf.random.set_seed(0)\nnp.random.seed(0)\n\n\n# This is the function that will be used to train the dqn\ndef dqn_training(player, dqn, nb_steps):\n dqn.fit(player, nb_steps=nb_steps)\n player.complete_current_battle()\n\n\ndef dqn_evaluation(player, dqn, nb_episodes):\n # Reset battle statistics\n player.reset_battles()\n dqn.test(player, nb_episodes=nb_episodes, visualize=False, verbose=False)\n\n print(\n \"DQN Evaluation: %d victories out of %d episodes\"\n % (player.n_won_battles, nb_episodes)\n )\n\n\nif __name__ == \"__main__\":\n env_player = SimpleRLPlayer(battle_format=\"gen8randombattle\")\n\n opponent = RandomPlayer(battle_format=\"gen8randombattle\")\n second_opponent = MaxDamagePlayer(battle_format=\"gen8randombattle\")\n\n # Output dimension\n n_action = len(env_player.action_space)\n\n model = Sequential()\n model.add(Dense(128, activation=\"elu\", input_shape=(1, 10)))\n\n # Our embedding have shape (1, 10), which affects our hidden layer\n # dimension and output dimension\n # Flattening resolve potential issues that would arise otherwise\n model.add(Flatten())\n model.add(Dense(64, activation=\"elu\"))\n model.add(Dense(n_action, activation=\"linear\"))\n\n memory = SequentialMemory(limit=10000, window_length=1)\n\n # Ssimple epsilon greedy\n policy = LinearAnnealedPolicy(\n EpsGreedyQPolicy(),\n attr=\"eps\",\n value_max=1.0,\n value_min=0.05,\n value_test=0,\n nb_steps=10000,\n )\n\n # Defining our DQN\n dqn = DQNAgent(\n model=model,\n nb_actions=len(env_player.action_space),\n policy=policy,\n memory=memory,\n nb_steps_warmup=1000,\n gamma=0.5,\n target_model_update=1,\n delta_clip=0.01,\n enable_double_dqn=True,\n )\n\n dqn.compile(Adam(lr=0.00025), metrics=[\"mae\"])\n\n # Training\n env_player.play_against(\n env_algorithm=dqn_training,\n opponent=opponent,\n env_algorithm_kwargs={\"dqn\": dqn, \"nb_steps\": NB_TRAINING_STEPS},\n )\n model.save(\"model_%d\" % NB_TRAINING_STEPS)\n\n # Evaluation\n print(\"Results against random player:\")\n env_player.play_against(\n env_algorithm=dqn_evaluation,\n opponent=opponent,\n env_algorithm_kwargs={\"dqn\": dqn, \"nb_episodes\": NB_EVALUATION_EPISODES},\n )\n\n print(\"\\nResults against max player:\")\n env_player.play_against(\n env_algorithm=dqn_evaluation,\n opponent=second_opponent,\n env_algorithm_kwargs={\"dqn\": dqn, \"nb_episodes\": NB_EVALUATION_EPISODES},\n )\n"
] |
[
[
"numpy.random.seed",
"tensorflow.keras.layers.Dense",
"numpy.ones",
"numpy.concatenate",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.models.Sequential",
"tensorflow.random.set_seed"
]
] |
woojeongjin/vokenization
|
[
"1acd3baa23d08cea43ac2e56b2faad1a805bc457",
"1acd3baa23d08cea43ac2e56b2faad1a805bc457"
] |
[
"vokenization/evaluate_diversity.py",
"vlm/run_glue_epochs.py"
] |
[
"import argparse\nfrom collections import defaultdict\nimport json\nimport os\nimport sys\n\nimport numpy as np\nimport tqdm\n\nfrom vokenization import Vokenizer, load_model_and_tokenizer\nimport common\n\nimgset2fname = {\n 'coco_train': 'mscoco_train.json',\n 'coco_nominival': 'mscoco_nominival.json',\n 'coco_minival': 'mscoco_minival.json',\n 'vg_nococo': 'vgnococo.json',\n 'cc_train': 'training.tsv',\n 'cc_valid': 'validation.tsv',\n}\n\ntokenizer_name = 'bert-base-uncased'\n\n\ndef load_lang_data(corpus_name, topk=10000):\n \"\"\"\n Load {topk} sentences from the corpus named by {corpus_name}.\n \"\"\"\n fpath = corpus_name + '.' + tokenizer_name\n tokens = []\n with open(fpath) as f:\n for i, line in enumerate(f):\n tokens.append(list(map(int, line.split(' '))))\n if (i + 1) == topk:\n break\n print(\"Read %d sentences from the corpus %s located at %s.\" % (\n len(tokens), corpus_name, fpath\n ))\n return tokens\n\n\ndef load_cc_data(img_set):\n fname = os.path.join(common.CC_ROOT, imgset2fname[img_set])\n sents = []\n with open(fname) as f:\n for line in f:\n sent, _ = line.split('\\t')\n sents.append(sent)\n print(\"Load the %d sentences for image set %s from %s\" % (\n len(sents), img_set, fname))\n return sents\n\n\ndef load_lxrt_data(img_set):\n fname = os.path.join(common.LXRT_ROOT, imgset2fname[img_set])\n sents = []\n with open(fname) as f:\n data = json.load(f)\n for datum in data:\n sents.extend(datum['sentf']['mscoco'])\n print(\"Load the %d sentences for image set %s from %s\" % (\n len(sents), img_set, fname))\n return sents\n\n\ndef analyze(token2info):\n \"\"\"\n :param token2info: token2info: token --> (img_id --> cnt)\n :return:\n \"\"\"\n names = ['Num Images', 'Max Cnt', 'Avg Cnt', 'Std Cnt']\n results = np.zeros(4)\n num_tokens = 0\n for token in token2info:\n img2cnt = token2info[token]\n cnts = np.array(list(img2cnt.values()))\n num_imgs = len(cnts)\n max_cnt = cnts.max()\n avg_cnt = cnts.mean()\n std_cnt = cnts.std()\n results += (num_imgs, max_cnt, avg_cnt, std_cnt)\n num_tokens += 1\n print(\"With %d tokens, \" % num_tokens)\n results /= num_tokens\n for name, result in zip(names, results):\n print(\"Average of %s is %0.2f\" % (name, result))\n\n corpus_info = defaultdict(lambda: 0)\n for info in token2info.values():\n for img, cnt in info.items():\n corpus_info[img] += cnt\n print(\"Cover %d images\" % len(corpus_info))\n\n# load = '/ssd-playpen/home/hTan/CoL/CoX/snap/pretrain/coco_hinge05_dim64_resxt101_bertl4'\nparser = argparse.ArgumentParser()\nparser.add_argument('--load', type=str, default='/ssd-playpen/home/hTan/CoL/CoX/snap/pretrain/coco_hinge05_dim64_resxt101_robertal4',\n help='The directory saved the model (containing'\n 'BEST.pth.model).')\nparser.add_argument('--image-sets', type=str, default='coco_minival',\n help='The splits of images to be extracted')\nparser.add_argument('--corpus', type=str, default='wiki103',\n help='Evaluated corpus')\nparser.add_argument('--maxsents', type=int, default=10000,\n help='The maximum sentences to be evaluated in the corpus')\nargs = parser.parse_args()\n\nkeys_path = os.path.join(args.load, 'keys')\n\nprint(\"Evaluate for model %s on image sets %s\" % (args.load, args.image_sets))\nmodel, tokenizer = load_model_and_tokenizer(args.load)\nimg_sets = args.image_sets.split(',')\nvokenizer = Vokenizer(model, tokenizer, keys_path, img_sets)\n\ncorpus_list = args.corpus.split(',')\nfor corpus in corpus_list:\n corpus = corpus.strip()\n print(\"\\nProcessing corpus %s for diversity test:\" % corpus)\n # token2info: token --> (img_id --> cnt)\n token2info = defaultdict(lambda: defaultdict(lambda: 0))\n\n if corpus in imgset2fname:\n if 'cc' in corpus:\n sents = load_cc_data(corpus)\n else:\n sents = load_lxrt_data(corpus)\n batch_size = 32\n for start_id in tqdm.tqdm(range(0, len(sents), batch_size)):\n batch_sents = sents[start_id: start_id + batch_size]\n scores, ids, tokens, paths = vokenizer.vokenize_sents(batch_sents, topk=None)\n for i in range(len(paths)):\n for token, path in zip(tokens[i][1:-1], paths[i][1:-1]):\n token2info[token][path] += 1\n else:\n tokens_list = load_lang_data(corpus, args.maxsents)\n batch_size = 16\n for start_id in tqdm.tqdm(range(0, len(tokens_list), batch_size)):\n batch_tokens = tokens_list[start_id: start_id + batch_size]\n scores, ids, tokens, paths = vokenizer.vokenize_ids(batch_tokens, topk=None)\n for i in range(len(paths)):\n for token, path in zip(tokens[i][1:-1], paths[i][1:-1]):\n token2info[token][path] += 1\n\n analyze(token2info)\n\n\n\n\n",
"import argparse\nimport math\nimport os\nfrom pathlib import Path\nfrom pprint import pprint\nimport subprocess\nimport threading\nimport time\n\nimport torch\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--load\", default=None, type=str,\n help=\"The model loaded, e.g., snap/vlm/wiki103_small\"\n)\nparser.add_argument(\n \"--gpus\", default=None, type=str,\n help=\"The list of GPU ids, separated by comma, e.g., '2,3'\"\n)\nparser.add_argument(\n \"--snaps\", default=1, type=int,\n help=\"The number of snaps evaluated with GLUE benchmark. \"\n \"-1 means all.\"\n)\nparser.add_argument(\n \"--start-from\", default=0, type=int\n)\nargs = parser.parse_args()\n\nif args.gpus is None:\n # Get all gpus available in this server.\n num_gpus = torch.cuda.device_count()\n # The device id are labeled from 0 to num_gpus-1.\n available_gpus = list(range(num_gpus))\nelse:\n available_gpus = [int(gpu_id) for gpu_id in args.gpus.split(\",\")]\n num_gpus = len(available_gpus)\n\nresource = threading.Semaphore(num_gpus)\n\n\ndef get_snap_paths(load):\n load_path = Path(load)\n paths = []\n for dir_path in load_path.iterdir():\n if dir_path.name.startswith(\"checkpoint-\"):\n paths.append(dir_path)\n return paths\n\n\ndef sorted_paths(paths):\n pathXkey = []\n for path in paths:\n name = path.name\n identifier = name[len(\"checkpoint-\"):]\n if identifier == 'last':\n continue\n if 'epoch' in identifier:\n key = identifier\n else:\n key = int(identifier)\n pathXkey.append((path, key))\n pathXkey = sorted(pathXkey, key=lambda x: x[1])\n paths = list(map(lambda x: x[0], pathXkey))\n return paths\n\n\ndef get_test_paths(paths, snaps):\n \"\"\"\n Return $snaps paths to be tested on GLUE\n \"\"\"\n if snaps == -1:\n return paths\n interval = len(paths) * 1. / snaps\n test_paths = []\n for i in range(1, snaps+1):\n idx = int(math.ceil(interval * i)) - 1\n test_paths.append(paths[idx])\n return test_paths\n\n\n# Get all paths needs to be processed\npaths = get_snap_paths(args.load)\npaths = sorted_paths(paths)\npaths = paths[args.start_from:]\npaths = get_test_paths(paths, args.snaps)\npaths = paths[::-1] # Run the last epochs first.\npath_lock = threading.Lock()\n\n\ndef run_glue():\n while True:\n # Only have one atomic operation (list.pop) here, do not need lock.\n # A Semaphore is enough to control the resources.\n resource.acquire()\n gpu_id = available_gpus.pop(0)\n\n # Involve multiple atomic operations (list.__len__, list.pop),\n # thus introduce a lock here.\n path_lock.acquire()\n if len(paths) > 0:\n path = paths.pop(0)\n else:\n path_lock.release()\n break\n path_lock.release()\n\n model = path.parent\n ckpt = path.name\n print(gpu_id, model, ckpt)\n process = subprocess.Popen(\n ['bash',\n 'scripts/run_glue_at_epoch.bash',\n str(gpu_id), # Use GPU\n '3', # Number of epochs\n model,\n ckpt\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n\n available_gpus.append(gpu_id)\n resource.release()\n\n # Sleep here allows the script (run_glue_at_epoch.bash) to finish\n # thus all memory in GPU will be cleared.\n time.sleep(5)\n return\n\n\n# Allocate #threads which equals to #GPUs\nthreads = []\nfor _ in range(num_gpus):\n threads.append(\n threading.Thread(target=run_glue)\n )\nfor thread in threads:\n thread.start()\n\n# Join to the main thread, thus the main thread will wait for all the threads.\nfor thread in threads:\n thread.join()\n"
] |
[
[
"numpy.zeros"
],
[
"torch.cuda.device_count"
]
] |
LautaroEst/cs231n-Computer-Vision
|
[
"f353a3d376d452dd1f9ef8979ddc96de91a45605"
] |
[
"Utils/Pruebas-Pytorch/pytorch_utils/MNISTdataloader.py"
] |
[
"import torch\nfrom torchvision import datasets as dset\nfrom torch.utils.data import DataLoader, sampler\nfrom torchvision.transforms import Compose, ToTensor\n\n\nclass Reshape(object):\n \n def __call__(self, sample):\n return sample[0,:,:]\n \n\n\ndef GetMNISTDataLoaders(NUM_TRAIN, NUM_VAL, batch_size=64):\n \n \n transform = Compose([ToTensor(),\n Reshape()])\n \n mnist_train_val = dset.MNIST('./MNIST/train', train=True, download=True, transform=transform)\n mnist_test = dset.MNIST('./MNIST/test', train=False, download=True, transform=transform)\n \n print('La base de datos MNIST contiene', len(mnist_train_val) + len(mnist_test), 'muestras')\n print('Cantidad de muestras para entrenamiento: ', NUM_TRAIN)\n print('Cantidad de muestras para validación: ', NUM_VAL)\n print('Cantidad de muestras para test: ', len(mnist_test))\n \n mnist_train_dataloader = DataLoader(mnist_train_val, \n batch_size=batch_size, \n sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN)))\n mnist_val_dataloader = DataLoader(mnist_train_val, \n batch_size=batch_size, \n sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN,NUM_TRAIN+NUM_VAL)))\n mnist_test_dataloader = DataLoader(mnist_test, \n batch_size=batch_size) \n \n return mnist_train_dataloader, mnist_val_dataloader, mnist_test_dataloader\n\n\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
cyrusneary/multi-agent-comms
|
[
"d88ebfa3d1adb4da55283472c95d8a094f42df43"
] |
[
"optimization_problems/total_corr2.py"
] |
[
"from ntpath import join\nimport cvxpy as cp\nfrom cvxpy.lin_ops.lin_utils import conv\nfrom cvxpy.settings import NONNEG\nimport numpy as np\nfrom scipy.special import rel_entr\n\nimport sys, os, time\nsys.path.append('../')\nfrom markov_decision_process.mdp import MDP\n\ndef build_linearized_program(mdp: MDP, \n N_agents : int,\n agent_state_size_list : list,\n agent_action_size_list : list,\n check_agent_state_action,\n check_agent_state,\n reachability_coef : float = 1.0,\n exp_len_coef : float = 0.1,\n total_corr_coef : float = 0.1,\n max_length_constr : int = 100):\n \"\"\"\n Construct a convex program to solve for a set of occupancy measures \n that respect the MDP dynamics while maximizing the probability of\n reaching the target set.\n\n Parameters\n ----------\n mdp :\n An object representing the MDP on which the reachability problem\n is to be solved.\n N_agents :\n The number of agents involved in the problem.\n agent_state_size_list :\n A list of integers specifying the number of local states for\n each agent.\n agent_action_size_list :\n A list of integers specifying the number of local actions for\n each agent.\n check_agent_state_action :\n A function indicating whether or not the state-action pair of\n a particular agent agrees with a given joint state-action pair.\n check_agent_state :\n A function indicating whether or not the state pair of\n a particular agent agrees with a given joint state pair.\n exp_len_coef :\n Coefficient on the expected length term in the definition of\n the optimization objective.\n total_corr_coef :\n Coefficient on the total correlation term in the definition of \n the optimization objective.\n max_length_constr : \n Hard constraint on the maximum expected length of the \n trajectories. This constraint is necessary to ensure that the \n optimization algorithm terminates.\n\n Returns\n -------\n prob : cvxpy Problem\n The linear program to be solved.\n vars : list of cvxpy Variables\n vars[0] is a (Ns,Na) variable x, where x[s,a] represents the \n occupancy measure of state-action pair (s,a).\n params : list of cvxpy Parameters\n params[0] is the expected length coefficient used to define\n the optimization objective.\n params[1] is the total correlation coefficient used to define\n the optimization objective.\n params[2] is the last guess at a solution.\n \"\"\"\n\n # Define index matrices that will be very helpful for computing\n # the gradients of the entropy terms of the mixed processes for each\n # agent.\n\n f_grad = {}\n g_grad = {}\n\n print('Building gradient vectors.')\n t_start = time.time()\n for i in range(N_agents):\n f_grad[i] = {}\n g_grad[i] = {}\n for s in range(agent_state_size_list[i]):\n\n g_grad[i][s] = np.zeros((mdp.Ns, mdp.Na))\n for s_joint in range(mdp.Ns):\n for a_joint in range(mdp.Na):\n if check_agent_state(i, s, s_joint):\n g_grad[i][s][s_joint, a_joint] = 1.0\n\n f_grad[i][s] = {}\n for a in range(agent_action_size_list[i]):\n f_grad[i][s][a] = np.zeros((mdp.Ns, mdp.Na))\n for s_joint in range(mdp.Ns):\n for a_joint in range(mdp.Na):\n if check_agent_state_action(i, \n s, s_joint, \n a, a_joint):\n f_grad[i][s][a][s_joint, a_joint] = 1.0\n print('Finished building gradients in {} seconds.'.format(time.time() \n - t_start))\n\n ##### Define the problem variables\n x = cp.Variable(shape=(mdp.Ns, mdp.Na),\n name='x',\n nonneg=True)\n reachability_coef = cp.Parameter(name='reachabilityCoef',\n value=reachability_coef,\n nonneg=True)\n exp_len_coef = cp.Parameter(name='expLenCoef', \n value=exp_len_coef,\n nonneg=True)\n total_corr_coef = cp.Parameter(name='entropyCoef', \n value=total_corr_coef,\n nonneg=True)\n x_last = cp.Parameter(shape=(mdp.Ns, mdp.Na),\n name='x_last',\n value=np.zeros((mdp.Ns, mdp.Na)),\n nonneg=True)\n\n vars = [x]\n params = [reachability_coef, exp_len_coef, total_corr_coef, x_last]\n\n ##### Define the problem constraints\n constraints = []\n\n # All occupancy measures are positive\n constraints.append(x[mdp.active_states, :] >= 0.0)\n\n # Absorbing states are set to have no occupancy measure\n constraints.append(x[mdp.absorbing_states, :] == 0.0)\n\n constraints.append(cp.sum(x) <= max_length_constr)\n\n # The remaining states satisfy the balance equations\n occupancy_out = cp.sum(x[mdp.active_states, :], axis=1)\n\n occupancy_init = np.zeros((mdp.Ns,))\n occupancy_init[mdp.initial_state] = 1.0\n occupancy_init = occupancy_init[mdp.active_states]\n\n occupancy_in = cp.hstack(\n [cp.sum(cp.multiply(x[mdp.active_states, :], \n mdp.T[mdp.active_states, :, i])) \n for i in mdp.active_states]\n )\n\n constraints.append(occupancy_out \n - occupancy_init \n - occupancy_in == 0)\n\n ##### Define the problem objective\n target_set_in = cp.sum(cp.hstack(\n [cp.sum(cp.multiply(x[mdp.active_states, :], \n mdp.T[mdp.active_states, :, i])) \n for i in mdp.target_set]\n )\n )\n\n expected_length = cp.sum(x)\n\n y = cp.sum(x[mdp.active_states, :], axis=1)\n y = cp.vstack([y for i in range(mdp.Na)]).T\n\n joint_entropy = -cp.sum(cp.rel_entr(x[mdp.active_states, :], y))\n\n grad = 0.0\n convex_term = 0.0\n for i in range(N_agents):\n for s_local in range(agent_state_size_list[i]):\n for a_local in range(agent_action_size_list[i]):\n numerator = cp.sum(x_last[np.where(f_grad[i][s_local][a_local])])\n denominator = cp.sum(x_last[np.where(g_grad[i][s_local])])\n ratio_term = numerator / denominator\n log_term = cp.log(ratio_term)\n\n grad = grad + log_term * f_grad[i][s_local][a_local]\n\n convex_term = convex_term + numerator * log_term\n\n linearized_term = - convex_term - cp.sum(cp.multiply(grad, (x - x_last)))\n\n total_corr = linearized_term - joint_entropy\n\n obj = cp.Maximize(reachability_coef * target_set_in \n - exp_len_coef * expected_length\n - total_corr_coef * total_corr)\n\n ##### Create the problem\n prob = cp.Problem(obj, constraints)\n\n return prob, vars, params, f_grad, g_grad"
] |
[
[
"numpy.zeros",
"numpy.where"
]
] |
YIWANGFAN/RetinaFace-
|
[
"99f54ebca356053a987ed3c616dbb2cd06070c89"
] |
[
"wyfRetinaFace/data/data_augment.py"
] |
[
"import cv2\nimport numpy as np\nimport random\nfrom utils.box_utils import matrix_iof\n\n\ndef _crop(image, boxes, labels, landm, img_dim):\n height, width, _ = image.shape\n pad_image_flag = True\n\n for _ in range(250):\n \"\"\"\n if random.uniform(0, 1) <= 0.2:\n scale = 1.0\n else:\n scale = random.uniform(0.3, 1.0)\n \"\"\"\n PRE_SCALES = [0.3, 0.45, 0.6, 0.8, 1.0]\n scale = random.choice(PRE_SCALES)\n short_side = min(width, height)\n w = int(scale * short_side)\n h = w\n\n if width == w:\n l = 0\n else:\n l = random.randrange(width - w)\n if height == h:\n t = 0\n else:\n t = random.randrange(height - h)\n roi = np.array((l, t, l + w, t + h))\n\n value = matrix_iof(boxes, roi[np.newaxis])\n flag = (value >= 1)\n if not flag.any():\n continue\n\n centers = (boxes[:, :2] + boxes[:, 2:]) / 2\n print(\"boxes:\",boxes)\n mask_a = np.logical_and(roi[:2] < centers, centers < roi[2:]).all(axis=1)\n boxes_t = boxes[mask_a].copy()\n labels_t = labels[mask_a].copy()\n landms_t = landm[mask_a].copy()\n landms_t = landms_t.reshape([-1, 5, 2])\n\n if boxes_t.shape[0] == 0:\n continue\n\n image_t = image[roi[1]:roi[3], roi[0]:roi[2]]\n\n boxes_t[:, :2] = np.maximum(boxes_t[:, :2], roi[:2])\n boxes_t[:, :2] -= roi[:2]\n boxes_t[:, 2:] = np.minimum(boxes_t[:, 2:], roi[2:])\n boxes_t[:, 2:] -= roi[:2]\n\n # landm\n landms_t[:, :, :2] = landms_t[:, :, :2] - roi[:2]\n landms_t[:, :, :2] = np.maximum(landms_t[:, :, :2], np.array([0, 0]))\n landms_t[:, :, :2] = np.minimum(landms_t[:, :, :2], roi[2:] - roi[:2])\n landms_t = landms_t.reshape([-1, 10])\n\n\n\t# make sure that the cropped image contains at least one face > 16 pixel at training image scale\n b_w_t = (boxes_t[:, 2] - boxes_t[:, 0] + 1) / w * img_dim\n b_h_t = (boxes_t[:, 3] - boxes_t[:, 1] + 1) / h * img_dim\n mask_b = np.minimum(b_w_t, b_h_t) > 0.0\n boxes_t = boxes_t[mask_b]\n labels_t = labels_t[mask_b]\n landms_t = landms_t[mask_b]\n\n if boxes_t.shape[0] == 0:\n continue\n\n pad_image_flag = False\n\n return image_t, boxes_t, labels_t, landms_t, pad_image_flag\n return image, boxes, labels, landm, pad_image_flag\n\n\ndef _distort(image):\n\n def _convert(image, alpha=1, beta=0):\n tmp = image.astype(float) * alpha + beta\n tmp[tmp < 0] = 0\n tmp[tmp > 255] = 255\n image[:] = tmp\n\n image = image.copy()\n\n if random.randrange(2):\n\n #brightness distortion\n if random.randrange(2):\n _convert(image, beta=random.uniform(-32, 32))\n\n #contrast distortion\n if random.randrange(2):\n _convert(image, alpha=random.uniform(0.5, 1.5))\n\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n #saturation distortion\n if random.randrange(2):\n _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\n\n #hue distortion\n if random.randrange(2):\n tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\n tmp %= 180\n image[:, :, 0] = tmp\n\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n else:\n\n #brightness distortion\n if random.randrange(2):\n _convert(image, beta=random.uniform(-32, 32))\n\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n #saturation distortion\n if random.randrange(2):\n _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\n\n #hue distortion\n if random.randrange(2):\n tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\n tmp %= 180\n image[:, :, 0] = tmp\n\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n #contrast distortion\n if random.randrange(2):\n _convert(image, alpha=random.uniform(0.5, 1.5))\n\n return image\n\n\ndef _expand(image, boxes, fill, p):\n if random.randrange(2):\n return image, boxes\n\n height, width, depth = image.shape\n\n scale = random.uniform(1, p)\n w = int(scale * width)\n h = int(scale * height)\n\n left = random.randint(0, w - width)\n top = random.randint(0, h - height)\n\n boxes_t = boxes.copy()\n boxes_t[:, :2] += (left, top)\n boxes_t[:, 2:] += (left, top)\n expand_image = np.empty(\n (h, w, depth),\n dtype=image.dtype)\n expand_image[:, :] = fill\n expand_image[top:top + height, left:left + width] = image\n image = expand_image\n\n return image, boxes_t\n\n\ndef _mirror(image, boxes, landms):\n _, width, _ = image.shape\n if random.randrange(2):\n image = image[:, ::-1]\n boxes = boxes.copy()\n boxes[:, 0::2] = width - boxes[:, 2::-2]\n\n # landm\n landms = landms.copy()\n landms = landms.reshape([-1, 5, 2])\n landms[:, :, 0] = width - landms[:, :, 0]\n tmp = landms[:, 1, :].copy()\n landms[:, 1, :] = landms[:, 0, :]\n landms[:, 0, :] = tmp\n tmp1 = landms[:, 4, :].copy()\n landms[:, 4, :] = landms[:, 3, :]\n landms[:, 3, :] = tmp1\n landms = landms.reshape([-1, 10])\n\n return image, boxes, landms\n\n\ndef _pad_to_square(image, rgb_mean, pad_image_flag):\n if not pad_image_flag:\n return image\n height, width, _ = image.shape\n long_side = max(width, height)\n image_t = np.empty((long_side, long_side, 3), dtype=image.dtype)\n image_t[:, :] = rgb_mean\n image_t[0:0 + height, 0:0 + width] = image\n return image_t\n\n\ndef _resize_subtract_mean(image, insize, rgb_mean):\n interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]\n interp_method = interp_methods[random.randrange(5)]\n image = cv2.resize(image, (insize, insize), interpolation=interp_method)\n image = image.astype(np.float32)\n image -= rgb_mean\n return image.transpose(2, 0, 1)\n\n\nclass preproc(object):\n\n def __init__(self, img_dim, rgb_means):\n self.img_dim = img_dim\n self.rgb_means = rgb_means\n\n def __call__(self, image, targets):\n assert targets.shape[0] > 0, \"this image does not have gt\"\n\n boxes = targets[:, :4].copy()\n labels = targets[:, -1].copy()\n landm = targets[:, 4:-1].copy()\n\n image_t, boxes_t, labels_t, landm_t, pad_image_flag = _crop(image, boxes, labels, landm, self.img_dim)\n image_t = _distort(image_t)\n image_t = _pad_to_square(image_t,self.rgb_means, pad_image_flag)\n image_t, boxes_t, landm_t = _mirror(image_t, boxes_t, landm_t)\n height, width, _ = image_t.shape\n image_t = _resize_subtract_mean(image_t, self.img_dim, self.rgb_means)\n boxes_t[:, 0::2] /= width\n boxes_t[:, 1::2] /= height\n\n landm_t[:, 0::2] /= width\n landm_t[:, 1::2] /= height\n\n labels_t = np.expand_dims(labels_t, 1)\n targets_t = np.hstack((boxes_t, landm_t, labels_t))\n\n return image_t, targets_t\n"
] |
[
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.maximum",
"numpy.minimum",
"numpy.logical_and",
"numpy.array",
"numpy.empty"
]
] |
albertoivo/chicago-bikeshare-mlnd
|
[
"fccb797a5cec1a527e160ca5377f6912078d9f49"
] |
[
"chicago_bikeshare_pt.py"
] |
[
"#!/usr/bin/env python3\n# coding: utf-8\n\nimport csv\nimport matplotlib.pyplot as plt\nimport zipfile\nimport os.path\n\ncsv_name = 'chicago.csv'\ncsv_zip_name = 'chicago.csv.zip'\n\nis_csv = os.path.isfile(csv_name)\nis_csv_zip_name = os.path.isfile(csv_zip_name)\n\nif is_csv_zip_name and not is_csv:\n print(\"Descompactando CSV file...\")\n with zipfile.ZipFile('./chicago.csv.zip', 'r') as zip_ref:\n zip_ref.extractall('./')\n\n# Vamos ler os dados como uma lista\nprint(\"Lendo o documento...\")\nwith open(\"chicago.csv\", \"r\") as file_read:\n reader = csv.reader(file_read)\n data_list = list(reader)\nprint(\"Ok!\")\n\n# Vamos verificar quantas linhas nós temos\nprint(\"Número de linhas:\")\nprint(len(data_list))\n\n# Imprimindo a primeira linha de data_list para verificar se funcionou.\nprint(\"Linha 0: \")\nprint(data_list[0])\n# É o cabeçalho dos dados, para que possamos identificar as colunas.\n\n# Imprimindo a segunda linha de data_list, ela deveria conter alguns dados\nprint(\"Linha 1: \")\nprint(data_list[1])\n\ninput(\"Aperte Enter para continuar...\")\n\n# TAREFA 1\nprint(\"\\n\\nTAREFA 1: Imprimindo as primeiras 20 amostras\")\nprint(\"\\n\")\nfor data in data_list[1:20]:\n print(data)\n\n# Vamos mudar o data_list para remover o cabeçalho dele.\ndata_list = data_list[1:]\n\n# Nós podemos acessar as features pelo índice\n# Por exemplo: sample[6] para imprimir gênero, ou sample[-2]\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 2\n\n\nprint(\"\\nTAREFA 2: Imprimindo o gênero das primeiras 20 amostras\")\nprint(\"\\n\")\nfor data in data_list[0:19]:\n print(data[6])\n\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 3\n\n\ndef column_to_list(_data, _index):\n _column_list = []\n\n for d in _data:\n _column_list.append(d[_index])\n return _column_list\n\n\n# Vamos checar com os gêneros se isso está funcionando para os primeiros 20\nprint(\"\\nTAREFA 3: Imprimindo a lista de gêneros das primeiras 20 amostras\")\nprint(column_to_list(data_list, -2)[:20])\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert type(column_to_list(\n data_list,\n -2)) is list, \"TAREFA 3: Tipo incorreto retornado. Deveria ser uma lista.\"\nassert len(column_to_list(\n data_list, -2)) == 1551505, \"TAREFA 3: Tamanho incorreto retornado.\"\nassert column_to_list(data_list, -2)[0] == \"\" and \\\n column_to_list(data_list, -2)[1] == \"Male\",\\\n \"TAREFA 3: A lista não coincide.\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 4\n\n\nmale = len(\n list(\n filter(lambda gender: gender == 'Male', column_to_list(data_list,\n -2))))\nfemale = len(\n list(\n filter(lambda gender: gender == 'Female', column_to_list(\n data_list, -2))))\n\n# Verificando o resultado\nprint(\"\\nTAREFA 4: Imprimindo quantos masculinos e femininos nós encontramos\")\nprint(\"Masculinos: \", male, \"\\nFemininos: \", female)\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert male == 935854 and female == 298784, \"TAREFA 4: A conta não bate.\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 5\n\n\ndef count_gender(_data_list):\n _male = len(\n list(\n filter(lambda gender: gender == 'Male',\n column_to_list(_data_list, -2))))\n _female = len(\n list(\n filter(lambda gender: gender == 'Female',\n column_to_list(_data_list, -2))))\n return [_male, _female]\n\n\nprint(\"\\nTAREFA 5: Imprimindo o resultado de count_gender\")\nprint(count_gender(data_list))\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert type(\n count_gender(data_list)\n) is list, \"TAREFA 5: Tipo incorreto retornado. Deveria retornar uma lista.\"\nassert len(\n count_gender(data_list)) == 2, \"TAREFA 5: Tamanho incorreto retornado.\"\nassert count_gender(data_list)[0] == 935854 and \\\n count_gender(data_list)[1] == 298784, \\\n \"TAREFA 5: Resultado incorreto no retorno!\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 6\n\n\ndef most_popular_gender(_data_list):\n _male, _female = count_gender(_data_list)\n _answer = \"\"\n if _male == _female:\n _answer = \"Equal\"\n elif _male > _female:\n _answer = \"Male\"\n else:\n _answer = \"Female\"\n return _answer\n\n\nprint(\"\\nTAREFA 6: Qual é o gênero mais popular na lista?\")\nprint(\"O gênero mais popular na lista é: \", most_popular_gender(data_list))\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert type(\n most_popular_gender(data_list)\n) is str, \"TAREFA 6: Tipo incorreto no retorno. Deveria retornar uma string.\"\nassert most_popular_gender(\n data_list) == \"Male\", \"TAREFA 6: Resultado de retorno incorreto!\"\n# -----------------------------------------------------\n\n# Se tudo está rodando como esperado, verifique este gráfico!\n# gender_list = column_to_list(data_list, -2)\ntypes = [\"Male\", \"Female\"]\nquantity = count_gender(data_list)\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantidade')\nplt.xlabel('Gênero')\nplt.xticks(y_pos, types)\nplt.title('Quantidade por Gênero')\nplt.show(block=True)\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 7\n\n\nprint(\"\\nTAREFA 7: Verifique o gráfico!\")\nuser_types = set(column_to_list(data_list, -3))\nuser_types_dict = {}\nfor utype in user_types:\n length = len(\n list(\n filter(lambda user: user == utype, column_to_list(data_list, -3))))\n user_types_dict[utype] = length\n\nprint(user_types_dict)\n\ntypes = list(user_types_dict.keys())\nquantity = list(user_types_dict.values())\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantidade')\nplt.xlabel('User Type')\nplt.xticks(y_pos, types)\nplt.title('Quantidade por User Type')\nplt.show(block=True)\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 8\n\n\nmale, female = count_gender(data_list)\nprint(\"\\nTAREFA 8: Por que a condição a seguir é Falsa?\")\nprint(\"male + female == len(data_list):\", male + female == len(data_list))\nanswer = \"Porque há vários registros em branco. \" \\\n \"Então a soma correta seria: male + female + branco. \"\nprint(\"resposta:\", answer)\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert answer != \"Escreva sua resposta aqui.\", \\\n \"TAREFA 8: Escreva sua própria resposta!\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 9\n\n\n# Você não deve usar funções prontas para isso, como max() e min().\ntrip_duration_list = column_to_list(data_list, 2)\nsorted_int_list = sorted(list(map(int, trip_duration_list)))\nlist_len = len(sorted_int_list)\nindex = (list_len - 1) // 2\n\nmin_trip = sorted_int_list[0]\nmax_trip = sorted_int_list[-1]\nmean_trip = sum(sorted_int_list) / len(sorted_int_list)\nmedian_trip = sorted_int_list[index] if list_len % 2 else (\n sorted_int_list[index] + sorted_int_list[index + 1]) / 2\n\nprint(\"\\nTAREFA 9: Imprimindo o mínimo, máximo, média, e mediana\")\nprint(\"Min: \", min_trip, \"Max: \", max_trip, \"Média: \", mean_trip, \"Mediana: \",\n median_trip)\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert round(min_trip) == 60, \"TAREFA 9: min_trip com resultado errado!\"\nassert round(max_trip) == 86338, \"TAREFA 9: max_trip com resultado errado!\"\nassert round(mean_trip) == 940, \"TAREFA 9: mean_trip com resultado errado!\"\nassert round(median_trip) == 670, \"TAREFA 9: median_trip com resultado errado!\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 10\n\n\nstart_stations = set(column_to_list(data_list, 3))\n\nprint(\"\\nTAREFA 10: Imprimindo as start stations:\")\nprint(len(start_stations))\nprint(start_stations)\n\n# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\nassert len(\n start_stations) == 582, \"TAREFA 10: Comprimento errado de start stations.\"\n# -----------------------------------------------------\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 11\n\n\ndef new_function(param1: int, param2: str) -> list:\n \"\"\"\n Função de exemplo com anotações.\n Argumentos:\n param1: O primeiro parâmetro.\n param2: O segundo parâmetro.\n Retorna:\n Uma lista de valores x.\n \"\"\"\n print(param1, param2) # apenas para fins de PEP8\n return [] # apenas para fins de PEP8\n\n\ninput(\"Aperte Enter para continuar...\")\n\n\n# TAREFA 12\n\n\n# para que nós possamos usar essa função com outra categoria de dados.\nprint(\"Você vai encarar o desafio? (yes ou no)\")\nanswer = \"yes\"\n\n\ndef count_items(_column_list):\n _data_types = set(_column_list)\n _data_types_dict = {}\n for _utype in _data_types:\n _length = len(list(filter(lambda user: user == _utype, _column_list)))\n _data_types_dict[_utype] = _length\n _item_types = user_types_dict.keys()\n _count_items = user_types_dict.values()\n return _item_types, _count_items\n\n\nif answer == \"yes\":\n # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------\n column_list = column_to_list(data_list, -2)\n types, counts = count_items(column_list)\n print(\"\\nTAREFA 12: Imprimindo resultados para count_items()\")\n print(\"Tipos:\", types, \"Counts:\", counts)\n assert len(types) == 3, \"TAREFA 12: Há 3 tipos de gênero!\"\n assert sum(counts) == 1551505, \"TAREFA 12: Resultado de retorno incorreto!\"\n # -----------------------------------------------------\n"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
bbboming/inc_via_bay
|
[
"0a339a866e8f83ff8fbda99909a58d24514ca3d1"
] |
[
"train_70_30.py"
] |
[
"# train.py\n#!/usr/bin/env\tpython3\n\nimport os\nimport sys\nimport argparse\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\n\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nfrom tqdm import tqdm\nfrom tensorboardX import SummaryWriter\n\nfrom conf import settings\nfrom utils import get_network, WarmUpLR\n\ndef train(epoch):\n net.train()\n pbar = tqdm(cifar100_training_loader)\n for batch_index, (images, labels) in enumerate(pbar):\n images = Variable(images)\n labels = Variable(labels)\n\n labels = labels.cuda()\n images = images.cuda()\n\n optimizer.zero_grad()\n outputs = net(images)\n loss = loss_function(outputs, labels)\n loss.backward()\n optimizer.step()\n\n if epoch <= args.warm:\n warmup_scheduler.step()\n\n n_iter = (epoch - 1) * len(cifar100_training_loader) + batch_index + 1\n pbar.set_description(\"[ EPOCH {epoch} ]\".format(epoch=epoch))\n pbar.set_postfix( \n loss=loss.item(),\n lr= optimizer.param_groups[0]['lr']\n )\n #update training loss for each iteration\n writer.add_scalar('Train/loss', loss.item(), n_iter)\n for name, param in net.named_parameters():\n layer, attr = os.path.splitext(name)\n attr = attr[1:]\n writer.add_histogram(\"{}/{}\".format(layer, attr), param, epoch)\n\ndef eval_training(epoch):\n net.eval()\n\n test_loss = 0.0 # cost function error\n correct = 0.0\n\n for (images, labels) in cifar100_test_loader:\n images = Variable(images)\n labels = Variable(labels)\n\n images = images.cuda()\n labels = labels.cuda()\n\n outputs = net(images)\n loss = loss_function(outputs, labels)\n test_loss += loss.item()\n _, preds = outputs.max(1)\n correct += preds.eq(labels).sum()\n\n test_loss = test_loss / len(cifar100_test_loader.dataset)\n test_acc = correct.float() / len(cifar100_test_loader.dataset)\n\n print(\"[ EPOCH {epoch} ] Loss {loss}, Acc {acc}\".format(\n epoch=epoch,\n loss=test_loss / len(cifar100_test_loader.dataset),\n acc=correct.float() / len(cifar100_test_loader.dataset)\n ))\n print()\n\n #add informations to tensorboard\n writer.add_scalar('Test/Average loss', test_loss / len(cifar100_test_loader.dataset), epoch)\n writer.add_scalar('Test/Accuracy', correct.float() / len(cifar100_test_loader.dataset), epoch)\n\n return test_loss, test_acc\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-net', type=str, default='resnet50', help='net type')\n parser.add_argument('-gpu', type=bool, default=True, help='use gpu or not')\n parser.add_argument('-w', type=int, default=2, help='number of workers for dataloader')\n parser.add_argument('-b', type=int, default=128, help='batch size for dataloader')\n parser.add_argument('-s', type=bool, default=True, help='whether shuffle the dataset')\n parser.add_argument('-warm', type=int, default=1, help='warm up training phase')\n parser.add_argument('-lr', type=float, default=0.1, help='initial learning rate')\n parser.add_argument('-resume', type=bool, default=False, help='resume training')\n args = parser.parse_args()\n\n net = get_network(args, use_gpu=args.gpu)\n if args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load('./checkpoint/ckpt.pth')\n net.load_state_dict(checkpoint)\n\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n if device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n \n #data preprocessing:\n DATA_ROOT = '/home/bbboming/HDD/Paper/datasets_object/ICIFAR100_70_30/BASE/'\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(settings.CIFAR100_TRAIN_MEAN, settings.CIFAR100_TRAIN_STD),\n ])\n trainset = datasets.ImageFolder(os.path.join(DATA_ROOT, 'train'), train_transform)\n cifar100_training_loader = torch.utils.data.DataLoader(\n trainset, batch_size = args.b, pin_memory = True,\n num_workers = args.w, shuffle=args.s\n )\n\n test_transform = transforms.Compose([ \n transforms.ToTensor(),\n transforms.Normalize(settings.CIFAR100_TRAIN_MEAN, settings.CIFAR100_TRAIN_STD),\n ])\n\n testset = datasets.ImageFolder(os.path.join(DATA_ROOT, 'test'), test_transform)\n cifar100_test_loader = torch.utils.data.DataLoader(\n testset, batch_size = args.b, pin_memory = True,\n num_workers = args.w, shuffle=False\n )\n \n loss_function = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n train_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,'min', threshold=1e-7)\n iter_per_epoch = len(cifar100_training_loader)\n warmup_scheduler = WarmUpLR(optimizer, iter_per_epoch * args.warm)\n checkpoint_path = os.path.join(settings.CHECKPOINT_PATH, args.net, settings.TIME_NOW)\n\n #use tensorboard\n if not os.path.exists(settings.LOG_DIR):\n os.mkdir(settings.LOG_DIR)\n writer = SummaryWriter(log_dir=os.path.join(\n settings.LOG_DIR, args.net, settings.TIME_NOW))\n\n #create checkpoint folder to save model\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n checkpoint_path = os.path.join(checkpoint_path, '{net}-{epoch}-{type}.pth')\n\n best_acc = 0.0\n for epoch in range(1, settings.EPOCH):\n\n train(epoch)\n test_loss, test_acc = eval_training(epoch)\n\n #Write Lr Log\n writer.add_scalars(\"Lr\", {'lr': get_lr(optimizer)}, epoch+1)\n\n #Train Scheduler\n train_scheduler.step(test_loss)\n\n #start to save best performance model after learning rate decay to 0.01 \n if epoch > settings.MILESTONES[1] and best_acc < test_acc:\n torch.save(net.state_dict(), checkpoint_path.format(net=args.net, epoch=epoch, type='best'))\n best_acc = test_acc\n continue\n\n if not epoch % settings.SAVE_EPOCH:\n torch.save(net.state_dict(), checkpoint_path.format(net=args.net, epoch=epoch, type='regular'))\n\n writer.close()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.load",
"torch.utils.data.DataLoader",
"torch.cuda.is_available",
"torch.nn.DataParallel",
"torch.autograd.Variable"
]
] |
GuodongZhu/nevergrad
|
[
"446bc2ef0c7ef318578013721843f7701507fd67"
] |
[
"nevergrad/optimization/test_base.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport warnings\nfrom unittest import TestCase\nfrom typing import List, Tuple, Any\nimport genty\nimport numpy as np\nfrom ..common import testing\nfrom ..instrumentation import variables as var\nfrom . import optimizerlib\nfrom . import base\n\n\nclass CounterFunction:\n\n def __init__(self) -> None:\n self.count = 0\n\n def __call__(self, value: base.ArrayLike) -> float:\n assert len(value) == 1\n self.count += 1\n return float(value[0] - 1)**2\n\n\nclass LoggingOptimizer(base.Optimizer):\n\n def __init__(self, num_workers: int = 1) -> None:\n super().__init__(dimension=1, budget=5, num_workers=num_workers)\n self.logs: List[str] = []\n\n def _internal_ask(self) -> base.ArrayLike:\n self.logs.append(f\"s{self._num_suggestions}\") # s for suggest\n return np.array((self._num_suggestions,))\n\n def _internal_tell(self, x: base.ArrayLike, value: float) -> None:\n self.logs.append(f\"u{x[0]}\") # u for update\n\n\[email protected]\nclass OptimizationTests(TestCase):\n\n @genty.genty_dataset( # type: ignore\n w1_batch=(1, True, ['s0', 'u0', 's1', 'u1', 's2', 'u2', 's3', 'u3', 's4', 'u4']),\n w1_steady=(1, False, ['s0', 'u0', 's1', 'u1', 's2', 'u2', 's3', 'u3', 's4', 'u4']), # no difference (normal, since worker=1)\n w3_batch=(3, True, ['s0', 's1', 's2', 'u0', 'u1', 'u2', 's3', 's4', 'u3', 'u4']),\n w3_steady=(3, False, ['s0', 's1', 's2', 'u0', 'u1', 'u2', 's3', 's4', 'u3', 'u4']), # not really steady TODO change this behavior\n # w3_steady=(3, False, ['s0', 's1', 's2', 'u0', 's3', 'u1', 's4', 'u2', 'u3', 'u4']), # This is what we would like\n )\n def test_batch_and_steady_optimization(self, num_workers: int, batch_mode: bool, expected: List[Tuple[str, float]]) -> None:\n # tests the suggestion (s) and update (u) patterns\n # the w3_steady is unexpected. It is designed to be efficient with a non-sequential executor, but because\n # of it, it is acting like batch mode when sequential...\n optim = LoggingOptimizer(num_workers=num_workers)\n func = CounterFunction()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n optim.optimize(func, verbosity=2, batch_mode=batch_mode)\n testing.printed_assert_equal(optim.logs, expected)\n\n @genty.genty_dataset( # type: ignore\n int_val=(3, False),\n bool_val=(True, False),\n int32_val=(np.int32(3), False),\n int64_val=(np.int64(3), False),\n float64_val=(np.float64(3), False),\n float32_val=(np.float32(3), False),\n list_val=([3, 5], True),\n complex_val=(1j, True),\n object_val=(object(), True),\n )\n def test_tell_types(self, value: Any, error: bool) -> None:\n optim = LoggingOptimizer(num_workers=1)\n x = optim.ask()\n if error:\n np.testing.assert_raises(TypeError, optim.tell, x, value)\n else:\n optim.tell(x, value)\n\n\ndef test_base_optimizer() -> None:\n zeroptim = optimizerlib.Zero(dimension=2, budget=4, num_workers=1)\n representation = repr(zeroptim)\n assert \"dimension=2\" in representation, f\"Unexpected representation: {representation}\"\n np.testing.assert_equal(zeroptim.ask(), [0, 0])\n zeroptim.tell([0, 0], 0)\n zeroptim.tell([1, 1], 1)\n np.testing.assert_equal(zeroptim.provide_recommendation(), [0, 0])\n # check that the best value is updated if a second evaluation is not as good\n zeroptim.tell([0, 0], 10)\n zeroptim.tell([1, 1], 1)\n np.testing.assert_equal(zeroptim.provide_recommendation(), [1, 1])\n np.testing.assert_equal(zeroptim._num_suggestions, 1)\n\n\ndef test_optimize() -> None:\n optimizer = optimizerlib.OnePlusOne(dimension=1, budget=100, num_workers=5)\n optimizer.register_callback(\"tell\", base.OptimizationPrinter(num_eval=10, num_sec=.1))\n func = CounterFunction()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n result = optimizer.optimize(func, verbosity=2)\n np.testing.assert_almost_equal(result[0], 1, decimal=2)\n np.testing.assert_equal(func.count, 100)\n\n\ndef test_instrumented_optimizer() -> None:\n instru = var.Instrumentation(var.Gaussian(0, 1), var.SoftmaxCategorical([0, 1]))\n opt = optimizerlib.registry[\"RandomSearch\"](dimension=instru.dimension, budget=10)\n iopt = base.IntrumentedOptimizer(opt, instru)\n output = iopt.optimize(lambda x, y: x**2 + y) # type: ignore\n assert isinstance(output, base.ArgPoint)\n"
] |
[
[
"numpy.testing.assert_equal",
"numpy.int32",
"numpy.testing.assert_almost_equal",
"numpy.int64",
"numpy.testing.assert_raises",
"numpy.float64",
"numpy.float32",
"numpy.array"
]
] |
salem-devloper/Lung-Segmentation-Non-Covid
|
[
"11eb87e46014aefaf034239bf68b65c5eb55711d"
] |
[
"QataCovDataset.py"
] |
[
"import torch\nimport torchvision\nimport numpy as np\nfrom torch.utils.data import DataLoader,Dataset\nimport os\nimport random\nimport cv2\nfrom PIL import Image\n\nfrom skimage import io\n\n\n# torch.utils.data.Dataset is an abstract class representing a dataset\nclass QataCovDataset(Dataset): # inherit from torch.utils.data.Dataset\n \"Lung sengmentation dataset.\"\n def __init__(self,root_dir = os.path.join(os.getcwd(),\"data/Lung Segmentation\"),split=None, transforms = None , shuffle = True):\n \"\"\"\n Args:\n :param root_dir (str):\n :param split (str):\n :param transforms (callable, optional) :\n \"\"\"\n self.root_dir = root_dir\n self.split = split # train / val / test\n self.transforms = transforms\n\n self.image_path = self.root_dir + '/Images/'\n\n # target\n self.mask_path = os.path.join(self.root_dir,'Ground-truths')\n \n\n def __len__(self):\n return len(self.split)\n\n def __getitem__(self, idx):\n img_name = self.split[idx]\n # set index\n #for fName in self.data_file[self.split][\"image\"]:\n # file_idx = int(fName.split('_')[1])\n # if idx == file_idx:\n # img_fName = fName\n img_path = os.path.join(self.image_path, img_name)\n img = Image.open(img_path).convert('L') # open as PIL Image and set Channel = 1\n # img = cv2.imread(img_path)\n\n #for fName in self.data_file[self.split][\"mask\"]:\n # file_idx = int(fName.split('_')[1])\n # if idx == file_idx:\n # mask_fName = fName\n mask_path = os.path.join(self.mask_path, img_name+'_mask')\n\n img_size = np.array(img).shape\n\n if os.path.exists(mask_path):\n mask = Image.open(mask_path).convert('L') # PIL Image\n else:\n mask = Image.fromarray(np.zeros(img_size,dtype=np.uint8))\n\n sample = {'image': img, 'mask': mask}\n\n if self.transforms:\n sample = self.transforms(sample)\n\n if isinstance(img,torch.Tensor) and isinstance(mask, torch.Tensor):\n assert img.size == mask.size\n return sample\n\nif __name__ == \"__main__\":\n \"\"\"Visualization\"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n import torchvision.transforms as transforms\n from my_transforms import Resize, ToTensor, GrayScale\n from torch.utils.data import DataLoader\n # set img size\n img_size = 512\n\n scale = Resize(512)\n composed = transforms.Compose([Resize(600),\n GrayScale()])\n\n data = LungSegDataset(split='val')\n\n def show(img, mask):\n combined = np.hstack((img, mask))\n plt.imshow(combined)\n fig = plt.figure(figsize=(30,30))\n cnt = 0\n for i in range(len(data)):\n sample = data[i]\n\n # for i in range(len(data)):\n # if i == 3:\n # break\n # sample = data[i]\n # for tsfrm in [composed]:\n # transformed_sample = tsfrm(sample)\n #\n # ax = plt.subplot(1, 3, i + 1)\n # plt.tight_layout()\n # ax.set_title(type(tsfrm).__name__)\n # show(transformed_sample['image'],transformed_sample['mask'])\n #\n #\n #\n # plt.show()\n # print(data.train_image_idx)\n # print(data.train_mask_idx)\n # print(data.train_idx)\n # # print(data.train_mask_file[1].split(\"_\"))\n # sample = []\n # for i in range(6):\n # i += 100\n # combined = np.hstack((data[i]['image'],data[i]['mask']))\n # sample.append(combined)\n #\n # plt.figure(figsize=(25, 10))\n #\n # for i in [0,3]:\n # for j in [1,2,3]:\n # plt.subplot(2, 3, i + j)\n # plt.imshow(sample[i + j - 1])\n # plt.show()\n\n"
] |
[
[
"numpy.hstack",
"matplotlib.pyplot.imshow",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
SHITIANYU-hue/flow
|
[
"6fb5697868517fea7098a81b78c1be8e925f09f7",
"6fb5697868517fea7098a81b78c1be8e925f09f7"
] |
[
"tests/setup_scripts.py",
"flow/benchmarks/baselines/bottleneck0.py"
] |
[
"\"\"\"Specifies several methods for creating networks and environments.\n\nThis allows us to reduce the number of times these features are specified when\ncreating new tests, as all tests follow approximately the same format.\n\"\"\"\n\nimport logging\n\nfrom numpy import pi, sin, cos, linspace\n\nfrom flow.controllers.car_following_models import IDMController\nfrom flow.controllers.routing_controllers import ContinuousRouter, GridRouter\nfrom flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams, \\\n SumoCarFollowingParams\nfrom flow.core.params import TrafficLightParams\nfrom flow.core.params import VehicleParams\nfrom flow.envs.traffic_light_grid import TrafficLightGridTestEnv\n\nfrom flow.networks.figure_eight import FigureEightNetwork\nfrom flow.networks.traffic_light_grid import TrafficLightGridNetwork\nfrom flow.networks.highway import HighwayNetwork\nfrom flow.networks.ring import RingNetwork\nfrom flow.envs.ring.accel import AccelEnv\n\n\ndef ring_road_exp_setup(sim_params=None,\n vehicles=None,\n env_params=None,\n net_params=None,\n initial_config=None,\n traffic_lights=None):\n \"\"\"\n Create an environment and network pair for ring road test experiments.\n\n Parameters\n ----------\n sim_params : flow.core.params.SumoParams\n sumo-related configuration parameters, defaults to a time step of 0.1s\n and no sumo-imposed failsafe on human or rl vehicles\n vehicles : Vehicles type\n vehicles to be placed in the network, default is one vehicles with an\n IDM acceleration controller and ContinuousRouter routing controller.\n env_params : flow.core.params.EnvParams\n environment-specific parameters, defaults to a environment with no\n failsafes, where other parameters do not matter for non-rl runs\n net_params : flow.core.params.NetParams\n network-specific configuration parameters, defaults to a single lane\n ring road of length 230 m\n initial_config : flow.core.params.InitialConfig\n specifies starting positions of vehicles, defaults to evenly\n distributed vehicles across the length of the network\n traffic_lights : flow.core.params.TrafficLightParams\n traffic light signals, defaults to no traffic lights in the network\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n if sim_params is None:\n # set default sim_params configuration\n sim_params = SumoParams(sim_step=0.1, render=False)\n\n if vehicles is None:\n # set default vehicles configuration\n vehicles = VehicleParams()\n vehicles.add(\n veh_id=\"idm\",\n acceleration_controller=(IDMController, {}),\n routing_controller=(ContinuousRouter, {}),\n car_following_params=SumoCarFollowingParams(\n speed_mode=\"aggressive\",\n ),\n num_vehicles=1)\n\n if env_params is None:\n # set default env_params configuration\n additional_env_params = {\n \"target_velocity\": 8,\n \"max_accel\": 1,\n \"max_decel\": 1,\n \"sort_vehicles\": False,\n }\n env_params = EnvParams(additional_params=additional_env_params)\n\n if net_params is None:\n # set default net_params configuration\n additional_net_params = {\n \"length\": 230,\n \"lanes\": 1,\n \"speed_limit\": 30,\n \"resolution\": 40\n }\n net_params = NetParams(additional_params=additional_net_params)\n\n if initial_config is None:\n # set default initial_config configuration\n initial_config = InitialConfig(lanes_distribution=1)\n\n if traffic_lights is None:\n # set default to no traffic lights\n traffic_lights = TrafficLightParams()\n\n flow_params = dict(\n # name of the experiment\n exp_tag=\"RingRoadTest\",\n\n # name of the flow environment the experiment is running on\n env_name=AccelEnv,\n\n # name of the network class the experiment is running on\n network=RingNetwork,\n\n # simulator that is used by the experiment\n simulator='traci',\n\n # sumo-related parameters (see flow.core.params.SumoParams)\n sim=sim_params,\n\n # environment related parameters (see flow.core.params.EnvParams)\n env=env_params,\n # network-related parameters (see flow.core.params.NetParams and the\n # network's documentation or ADDITIONAL_NET_PARAMS component)\n net=net_params,\n\n # vehicles to be placed in the network at the start of a rollout (see\n # flow.core.params.VehicleParams)\n veh=vehicles,\n\n # parameters specifying the positioning of vehicles upon initialization/\n # reset (see flow.core.params.InitialConfig)\n initial=initial_config,\n\n # traffic lights to be introduced to specific nodes (see\n # flow.core.params.TrafficLightParams)\n tls=traffic_lights,\n )\n\n # create the network\n network = RingNetwork(\n name=\"RingRoadTest\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config,\n traffic_lights=traffic_lights)\n\n # create the environment\n env = AccelEnv(\n env_params=env_params, sim_params=sim_params, network=network)\n\n # reset the environment\n env.reset()\n\n return env, network, flow_params\n\n\ndef figure_eight_exp_setup(sim_params=None,\n vehicles=None,\n env_params=None,\n net_params=None,\n initial_config=None,\n traffic_lights=None):\n \"\"\"\n Create an environment and network pair for figure eight test experiments.\n\n Parameters\n ----------\n sim_params : flow.core.params.SumoParams\n sumo-related configuration parameters, defaults to a time step of 0.1s\n and no sumo-imposed failsafe on human or rl vehicles\n vehicles : Vehicles type\n vehicles to be placed in the network, default is one vehicles with an\n IDM acceleration controller and ContinuousRouter routing controller.\n env_params : flow.core.params.EnvParams\n environment-specific parameters, defaults to a environment with no\n failsafes, where other parameters do not matter for non-rl runs\n net_params : flow.core.params.NetParams\n network-specific configuration parameters, defaults to a figure eight\n with a 30 m radius\n initial_config : flow.core.params.InitialConfig\n specifies starting positions of vehicles, defaults to evenly\n distributed vehicles across the length of the network\n traffic_lights: flow.core.params.TrafficLightParams\n traffic light signals, defaults to no traffic lights in the network\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n if sim_params is None:\n # set default sim_params configuration\n sim_params = SumoParams(sim_step=0.1, render=False)\n\n if vehicles is None:\n # set default vehicles configuration\n vehicles = VehicleParams()\n vehicles.add(\n veh_id=\"idm\",\n acceleration_controller=(IDMController, {}),\n car_following_params=SumoCarFollowingParams(\n speed_mode=\"aggressive\",\n ),\n routing_controller=(ContinuousRouter, {}),\n num_vehicles=1)\n\n if env_params is None:\n # set default env_params configuration\n additional_env_params = {\n \"target_velocity\": 8,\n \"max_accel\": 1,\n \"max_decel\": 1,\n \"sort_vehicles\": False\n }\n env_params = EnvParams(additional_params=additional_env_params)\n\n if net_params is None:\n # set default net_params configuration\n additional_net_params = {\n \"radius_ring\": 30,\n \"lanes\": 1,\n \"speed_limit\": 30,\n \"resolution\": 40\n }\n net_params = NetParams(additional_params=additional_net_params)\n\n if initial_config is None:\n # set default initial_config configuration\n initial_config = InitialConfig(lanes_distribution=1)\n\n if traffic_lights is None:\n # set default to no traffic lights\n traffic_lights = TrafficLightParams()\n\n flow_params = dict(\n # name of the experiment\n exp_tag=\"FigureEightTest\",\n\n # name of the flow environment the experiment is running on\n env_name=AccelEnv,\n\n # name of the network class the experiment is running on\n network=FigureEightNetwork,\n\n # simulator that is used by the experiment\n simulator='traci',\n\n # sumo-related parameters (see flow.core.params.SumoParams)\n sim=sim_params,\n\n # environment related parameters (see flow.core.params.EnvParams)\n env=env_params,\n # network-related parameters (see flow.core.params.NetParams and the\n # network's documentation or ADDITIONAL_NET_PARAMS component)\n net=net_params,\n\n # vehicles to be placed in the network at the start of a rollout (see\n # flow.core.params.VehicleParams)\n veh=vehicles,\n\n # parameters specifying the positioning of vehicles upon initialization/\n # reset (see flow.core.params.InitialConfig)\n initial=initial_config,\n\n # traffic lights to be introduced to specific nodes (see\n # flow.core.params.TrafficLightParams)\n tls=traffic_lights,\n )\n\n # create the network\n network = FigureEightNetwork(\n name=\"FigureEightTest\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config,\n traffic_lights=traffic_lights)\n\n # create the environment\n env = AccelEnv(\n env_params=env_params, sim_params=sim_params, network=network)\n\n # reset the environment\n env.reset()\n\n return env, network, flow_params\n\n\ndef highway_exp_setup(sim_params=None,\n vehicles=None,\n env_params=None,\n net_params=None,\n initial_config=None,\n traffic_lights=None):\n \"\"\"\n Create an environment and network pair for highway test experiments.\n\n Parameters\n ----------\n sim_params : flow.core.params.SumoParams\n sumo-related configuration parameters, defaults to a time step of 0.1s\n and no sumo-imposed failsafe on human or rl vehicles\n vehicles : Vehicles type\n vehicles to be placed in the network, default is one vehicles with an\n IDM acceleration controller and ContinuousRouter routing controller.\n env_params : flow.core.params.EnvParams\n environment-specific parameters, defaults to a environment with no\n failsafes, where other parameters do not matter for non-rl runs\n net_params : flow.core.params.NetParams\n network-specific configuration parameters, defaults to a single lane\n highway of length 100 m\n initial_config : flow.core.params.InitialConfig\n specifies starting positions of vehicles, defaults to evenly\n distributed vehicles across the length of the network\n traffic_lights: flow.core.params.TrafficLightParams\n traffic light signals, defaults to no traffic lights in the network\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n if sim_params is None:\n # set default sim_params configuration\n sim_params = SumoParams(sim_step=0.1, render=False)\n\n if vehicles is None:\n # set default vehicles configuration\n vehicles = VehicleParams()\n vehicles.add(\n veh_id=\"idm\",\n acceleration_controller=(IDMController, {}),\n car_following_params=SumoCarFollowingParams(\n speed_mode=\"aggressive\",\n ),\n routing_controller=(ContinuousRouter, {}),\n num_vehicles=1)\n\n if env_params is None:\n # set default env_params configuration\n additional_env_params = {\n \"target_velocity\": 8,\n \"max_accel\": 1,\n \"max_decel\": 1,\n \"sort_vehicles\": False\n }\n env_params = EnvParams(additional_params=additional_env_params)\n\n if net_params is None:\n # set default net_params configuration\n additional_net_params = {\n \"length\": 100,\n \"lanes\": 1,\n \"speed_limit\": 30,\n \"resolution\": 40,\n \"num_edges\": 1\n }\n net_params = NetParams(additional_params=additional_net_params)\n\n if initial_config is None:\n # set default initial_config configuration\n initial_config = InitialConfig()\n\n if traffic_lights is None:\n # set default to no traffic lights\n traffic_lights = TrafficLightParams()\n\n flow_params = dict(\n # name of the experiment\n exp_tag=\"RingRoadTest\",\n\n # name of the flow environment the experiment is running on\n env_name=AccelEnv,\n\n # name of the network class the experiment is running on\n network=HighwayNetwork,\n\n # simulator that is used by the experiment\n simulator='traci',\n\n # sumo-related parameters (see flow.core.params.SumoParams)\n sim=sim_params,\n\n # environment related parameters (see flow.core.params.EnvParams)\n env=env_params,\n # network-related parameters (see flow.core.params.NetParams and the\n # network's documentation or ADDITIONAL_NET_PARAMS component)\n net=net_params,\n\n # vehicles to be placed in the network at the start of a rollout (see\n # flow.core.params.VehicleParams)\n veh=vehicles,\n\n # parameters specifying the positioning of vehicles upon initialization/\n # reset (see flow.core.params.InitialConfig)\n initial=initial_config,\n\n # traffic lights to be introduced to specific nodes (see\n # flow.core.params.TrafficLightParams)\n tls=traffic_lights,\n )\n\n # create the network\n network = HighwayNetwork(\n name=\"RingRoadTest\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config,\n traffic_lights=traffic_lights)\n\n # create the environment\n env = AccelEnv(\n env_params=env_params, sim_params=sim_params, network=network)\n\n # reset the environment\n env.reset()\n\n return env, network, flow_params\n\n\ndef traffic_light_grid_mxn_exp_setup(row_num=1,\n col_num=1,\n sim_params=None,\n vehicles=None,\n env_params=None,\n net_params=None,\n initial_config=None,\n tl_logic=None):\n \"\"\"\n Create an environment and network pair for traffic light grid 1x1 test experiments.\n\n Parameters\n ----------\n row_num: int, optional\n number of horizontal rows of edges in the traffic light grid network\n col_num: int, optional\n number of vertical columns of edges in the traffic light grid network\n sim_params : flow.core.params.SumoParams\n sumo-related configuration parameters, defaults to a time step of 1s\n and no sumo-imposed failsafe on human or rl vehicles\n vehicles : Vehicles type\n vehicles to be placed in the network, default is 5 vehicles per edge\n for a total of 20 vehicles with an IDM acceleration controller and\n GridRouter routing controller.\n env_params : flow.core.params.EnvParams\n environment-specific parameters, defaults to a environment with\n failsafes, where other parameters do not matter for non-rl runs\n net_params : flow.core.params.NetParams\n network-specific configuration parameters, defaults to a 1x1 traffic\n light grid with traffic lights on\n initial_config : flow.core.params.InitialConfig\n specifies starting positions of vehicles, defaults to evenly\n distributed vehicles across the length of the network\n tl_logic: flow.core.params.TrafficLightParams\n specifies logic of any traffic lights added to the system\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n if tl_logic is None:\n tl_logic = TrafficLightParams(baseline=False)\n\n if sim_params is None:\n # set default sim_params configuration\n sim_params = SumoParams(sim_step=1, render=False)\n\n if vehicles is None:\n vehicles_per_edge = 5\n num_edges = 2 * (row_num + col_num)\n total_vehicles = num_edges * vehicles_per_edge\n vehicles = VehicleParams()\n vehicles.add(\n veh_id=\"idm\",\n acceleration_controller=(IDMController, {}),\n car_following_params=SumoCarFollowingParams(\n min_gap=2.5, tau=1.1, max_speed=30),\n routing_controller=(GridRouter, {}),\n num_vehicles=total_vehicles)\n\n if env_params is None:\n # set default env_params configuration\n additional_env_params = {\n \"target_velocity\": 50,\n \"switch_time\": 3.0,\n \"tl_type\": \"controlled\",\n \"discrete\": False\n }\n\n env_params = EnvParams(\n additional_params=additional_env_params, horizon=100)\n\n if net_params is None:\n # set default net_params configuration\n total_vehicles = vehicles.num_vehicles\n num_entries = 2 * row_num + 2 * col_num\n assert total_vehicles % num_entries == 0, \"{} total vehicles should \" \\\n \"be divisible by {\" \\\n \"}\".format(total_vehicles,\n num_entries)\n grid_array = {\n \"short_length\": 100,\n \"inner_length\": 300,\n \"long_length\": 3000,\n \"row_num\": row_num,\n \"col_num\": col_num,\n \"cars_left\": int(total_vehicles / num_entries),\n \"cars_right\": int(total_vehicles / num_entries),\n \"cars_top\": int(total_vehicles / num_entries),\n \"cars_bot\": int(total_vehicles / num_entries)\n }\n\n additional_net_params = {\n \"length\": 200,\n \"lanes\": 2,\n \"speed_limit\": 35,\n \"resolution\": 40,\n \"grid_array\": grid_array,\n \"horizontal_lanes\": 1,\n \"vertical_lanes\": 1\n }\n\n net_params = NetParams(additional_params=additional_net_params)\n\n if initial_config is None:\n # set default initial_config configuration\n initial_config = InitialConfig(\n spacing=\"custom\", additional_params={\"enter_speed\": 30})\n\n flow_params = dict(\n # name of the experiment\n exp_tag=\"Grid1x1Test\",\n\n # name of the flow environment the experiment is running on\n env_name=TrafficLightGridTestEnv,\n\n # name of the network class the experiment is running on\n network=TrafficLightGridNetwork,\n\n # simulator that is used by the experiment\n simulator='traci',\n\n # sumo-related parameters (see flow.core.params.SumoParams)\n sim=sim_params,\n\n # environment related parameters (see flow.core.params.EnvParams)\n env=env_params,\n # network-related parameters (see flow.core.params.NetParams and the\n # network's documentation or ADDITIONAL_NET_PARAMS component)\n net=net_params,\n\n # vehicles to be placed in the network at the start of a rollout (see\n # flow.core.params.VehicleParams)\n veh=vehicles,\n\n # parameters specifying the positioning of vehicles upon initialization/\n # reset (see flow.core.params.InitialConfig)\n initial=initial_config,\n\n # traffic lights to be introduced to specific nodes (see\n # flow.core.params.TrafficLightParams)\n tls=tl_logic\n )\n\n # create the network\n network = TrafficLightGridNetwork(\n name=\"Grid1x1Test\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config,\n traffic_lights=tl_logic)\n\n # create the environment\n env = TrafficLightGridTestEnv(\n env_params=env_params, sim_params=sim_params, network=network)\n\n # reset the environment\n env.reset()\n\n return env, network, flow_params\n\n\ndef variable_lanes_exp_setup(sim_params=None,\n vehicles=None,\n env_params=None,\n net_params=None,\n initial_config=None,\n traffic_lights=None):\n \"\"\"\n Create an environment and network variable-lane ring road.\n\n Each edge in this network can have a different number of lanes. Used for\n test purposes.\n\n Parameters\n ----------\n sim_params : flow.core.params.SumoParams\n sumo-related configuration parameters, defaults to a time step of 0.1s\n and no sumo-imposed failsafe on human or rl vehicles\n vehicles : Vehicles type\n vehicles to be placed in the network, default is one vehicles with an\n IDM acceleration controller and ContinuousRouter routing controller.\n env_params : flow.core.params.EnvParams\n environment-specific parameters, defaults to a environment with no\n failsafes, where other parameters do not matter for non-rl runs\n net_params : flow.core.params.NetParams\n network-specific configuration parameters, defaults to a figure eight\n with a 30 m radius\n initial_config : flow.core.params.InitialConfig\n specifies starting positions of vehicles, defaults to evenly\n distributed vehicles across the length of the network\n traffic_lights: flow.core.params.TrafficLightParams\n traffic light signals, defaults to no traffic lights in the network\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n if sim_params is None:\n # set default sim_params configuration\n sim_params = SumoParams(sim_step=0.1, render=False)\n\n if vehicles is None:\n # set default vehicles configuration\n vehicles = VehicleParams()\n vehicles.add(\n veh_id=\"idm\",\n acceleration_controller=(IDMController, {}),\n car_following_params=SumoCarFollowingParams(\n speed_mode=\"aggressive\",\n ),\n routing_controller=(ContinuousRouter, {}),\n num_vehicles=1)\n\n if env_params is None:\n # set default env_params configuration\n additional_env_params = {\n \"target_velocity\": 8,\n \"max_accel\": 1,\n \"max_decel\": 1,\n \"sort_vehicles\": False\n }\n env_params = EnvParams(additional_params=additional_env_params)\n\n if net_params is None:\n # set default net_params configuration\n additional_net_params = {\n \"length\": 230,\n \"lanes\": 1,\n \"speed_limit\": 30,\n \"resolution\": 40\n }\n net_params = NetParams(additional_params=additional_net_params)\n\n if initial_config is None:\n # set default initial_config configuration\n initial_config = InitialConfig()\n\n if traffic_lights is None:\n # set default to no traffic lights\n traffic_lights = TrafficLightParams()\n\n flow_params = dict(\n # name of the experiment\n exp_tag=\"VariableLaneRingRoadTest\",\n\n # name of the flow environment the experiment is running on\n env_name=AccelEnv,\n\n # name of the network class the experiment is running on\n network=VariableLanesNetwork,\n\n # simulator that is used by the experiment\n simulator='traci',\n\n # sumo-related parameters (see flow.core.params.SumoParams)\n sim=sim_params,\n\n # environment related parameters (see flow.core.params.EnvParams)\n env=env_params,\n # network-related parameters (see flow.core.params.NetParams and the\n # network's documentation or ADDITIONAL_NET_PARAMS component)\n net=net_params,\n\n # vehicles to be placed in the network at the start of a rollout (see\n # flow.core.params.VehicleParams)\n veh=vehicles,\n\n # parameters specifying the positioning of vehicles upon initialization/\n # reset (see flow.core.params.InitialConfig)\n initial=initial_config,\n\n # traffic lights to be introduced to specific nodes (see\n # flow.core.params.TrafficLightParams)\n tls=traffic_lights,\n )\n\n # create the network\n network = VariableLanesNetwork(\n name=\"VariableLaneRingRoadTest\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config,\n traffic_lights=traffic_lights)\n\n # create the environment\n env = AccelEnv(\n env_params=env_params, sim_params=sim_params, network=network)\n\n # reset the environment\n env.reset()\n\n return env, network, flow_params\n\n\nclass VariableLanesNetwork(RingNetwork):\n \"\"\"Instantiate a ring road with variable number of lanes per edge.\"\"\"\n\n def specify_edges(self, net_params):\n \"\"\"See parent class.\n\n Each edge can be provided with a separate number of lanes.\n \"\"\"\n length = net_params.additional_params[\"length\"]\n resolution = net_params.additional_params[\"resolution\"]\n v = net_params.additional_params[\"speed_limit\"]\n r = length / (2 * pi)\n edgelen = length / 4.\n\n edges = [{\n \"id\":\n \"bottom\",\n \"from\":\n \"bottom\",\n \"to\":\n \"right\",\n \"speed\":\n v,\n \"length\":\n edgelen,\n \"numLanes\":\n 1,\n \"shape\":\n [\n (r * cos(t), r * sin(t))\n for t in linspace(-pi / 2, 0, resolution)\n ]\n }, {\n \"id\":\n \"right\",\n \"from\":\n \"right\",\n \"to\":\n \"top\",\n \"speed\":\n v,\n \"length\":\n edgelen,\n \"numLanes\":\n 3,\n \"shape\":\n [\n (r * cos(t), r * sin(t))\n for t in linspace(0, pi / 2, resolution)\n ]\n }, {\n \"id\":\n \"top\",\n \"from\":\n \"top\",\n \"to\":\n \"left\",\n \"speed\":\n v,\n \"length\":\n edgelen,\n \"numLanes\":\n 2,\n \"shape\":\n [\n (r * cos(t), r * sin(t))\n for t in linspace(pi / 2, pi, resolution)\n ]\n }, {\n \"id\":\n \"left\",\n \"from\":\n \"left\",\n \"to\":\n \"bottom\",\n \"speed\":\n v,\n \"length\":\n edgelen,\n \"numLanes\":\n 4,\n \"shape\":\n [\n (r * cos(t), r * sin(t))\n for t in linspace(pi, 3 * pi / 2, resolution)\n ]\n }]\n\n return edges\n",
"\"\"\"Evaluates the baseline performance of bottleneck0 without RL control.\n\nBaseline is no AVs.\n\"\"\"\n\nimport numpy as np\nfrom flow.core.experiment import Experiment\nfrom flow.core.params import InFlows\nfrom flow.core.params import SumoLaneChangeParams\nfrom flow.core.params import SumoCarFollowingParams\nfrom flow.core.params import VehicleParams\nfrom flow.controllers import ContinuousRouter\nfrom flow.benchmarks.bottleneck0 import flow_params\nfrom flow.benchmarks.bottleneck0 import SCALING\n\n\ndef bottleneck0_baseline(num_runs, render=True):\n \"\"\"Run script for the bottleneck0 baseline.\n\n Parameters\n ----------\n num_runs : int\n number of rollouts the performance of the environment is evaluated\n over\n render : bool, optional\n specifies whether to use the gui during execution\n\n Returns\n -------\n flow.core.experiment.Experiment\n class needed to run simulations\n \"\"\"\n sim_params = flow_params['sim']\n env_params = flow_params['env']\n net_params = flow_params['net']\n\n # we want no autonomous vehicles in the simulation\n vehicles = VehicleParams()\n vehicles.add(veh_id='human',\n car_following_params=SumoCarFollowingParams(\n speed_mode=9,\n ),\n routing_controller=(ContinuousRouter, {}),\n lane_change_params=SumoLaneChangeParams(\n lane_change_mode=0,\n ),\n num_vehicles=1 * SCALING)\n\n # only include human vehicles in inflows\n flow_rate = 2300 * SCALING\n inflow = InFlows()\n inflow.add(veh_type='human', edge='1',\n vehs_per_hour=flow_rate,\n departLane='random', departSpeed=10)\n net_params.inflows = inflow\n\n # modify the rendering to match what is requested\n sim_params.render = render\n\n # set the evaluation flag to True\n env_params.evaluate = True\n\n flow_params['env'].horizon = env_params.horizon\n exp = Experiment(flow_params)\n\n results = exp.run(num_runs)\n return np.mean(results['returns']), np.std(results['returns'])\n\n\nif __name__ == '__main__':\n runs = 2 # number of simulations to average over\n mean, std = bottleneck0_baseline(num_runs=runs, render=True)\n\n print('---------')\n print('The average outflow, std. deviation over 500 seconds '\n 'across {} runs is {}, {}'.format(runs, mean, std))\n"
] |
[
[
"numpy.cos",
"numpy.linspace",
"numpy.sin"
],
[
"numpy.std",
"numpy.mean"
]
] |
sm7175/MLAI
|
[
"e33a8af0c67265f7ba9e00fb315e56aa78c82075"
] |
[
"RL-based system for assisting cab drivers/Env.py"
] |
[
"# Import routines\n\nimport numpy as np\nimport math\nimport random\nfrom itertools import permutations\n\n# Defining hyperparameters\nm = 5 # number of cities, ranges from 1 ..... m\nt = 24 # number of hours, ranges from 0 .... t-1\nd = 7 # number of days, ranges from 0 ... d-1\nC = 5 # Per hour fuel and other costs\nR = 9 # per hour revenue from a passenger\n\n\nclass CabDriver():\n\n def __init__(self):\n \"\"\"initialise your state and define your action space and state space\"\"\"\n self.action_space = list(permutations([i for i in range(m)], 2)) + [(0,0)]\n self.state_space = [[x, y, z] for x in range(m) for y in range(t) for z in range(d)]\n self.state_init = random.choice(self.state_space)\n\n # Start the first round\n self.reset()\n\n\n ## Encoding state (or state-action) for NN input\n\n def state_encod_arch1(self, state):\n \"\"\"convert the state into a vector so that it can be fed to the NN. This method converts a given state into a vector format. Hint: The vector is of size m + t + d.\"\"\"\n state_encod = [0 for x in range (m+t+d)] ## initialize vector state\n state_encod[state[0]] = 1 ## set the location value into vector\n state_encod[m+state[1]] = 1\n state_encod[m+t+state[2]] = 1## set time value into vector\n return state_encod\n\n def action_encod_arch1(self, action):\n \"\"\"convert the state into a vector so that it can be fed to the NN. This method converts a given state into a vector format. Hint: The vector is of size m + t + d.\"\"\"\n state_encod = [0 for x in range (m+m)] ## initialize vector state\n if action[0] != 0 and action[1] != 0:\n state_encod[action[0]] = 1 ## set pickup location:\n state_encod[m + action[1]] = 1 ## set drop location\n return state_encod\n\n # Use this function if you are using architecture-2 \n # def state_encod_arch2(self, state, action):\n # \"\"\"convert the (state-action) into a vector so that it can be fed to the NN. This method converts a given state-action pair into a vector format. Hint: The vector is of size m + t + d + m + m.\"\"\"\n\n \n # return state_encod\n\n\n ## Getting number of requests\n\n def requests(self, state):\n \"\"\"Determining the number of requests basis the location. \n Use the table specified in the MDP and complete for rest of the locations\"\"\"\n location = state[0]\n if location == 0:\n requests = np.random.poisson(2)\n if location == 1:\n requests = np.random.poisson(12)\n if location == 2:\n requests = np.random.poisson(4)\n if location == 3:\n requests = np.random.poisson(7)\n if location == 4:\n requests = np.random.poisson(8)\n\n if requests >15:\n requests =15\n\n possible_actions_index = random.sample(range(1, (m-1)*m +1), requests) # (0,0) is not considered as customer request\n actions = [self.action_space[i] for i in possible_actions_index]\n\n \n actions.append([0,0])\n possible_actions_index.append(self.action_space.index((0,0)))\n\n return possible_actions_index,actions \n\n\n\n def reward_func(self, state, action, Time_matrix):\n \"\"\"Takes in state, action and Time-matrix and returns the reward\"\"\"\n #find next state and calculating reward for next state\n next_state, wait_time, transit_time, ride_time = self.next_state_func(state, action, Time_matrix)\n\n revenue_time = ride_time\n idle_time = wait_time + transit_time\n reward = (R * revenue_time) - (C * (revenue_time + idle_time))\n\n return reward\n\n\n\n\n def next_state_func(self, state, action, Time_matrix):\n \"\"\"Takes state and action as input and returns next state\"\"\"\n # Find current state of driver\n curr_loc = state[0]\n curr_time = state[1]\n curr_day = state[2]\n pickup_loc = action[0]\n drop_loc = action[1]\n\n ## reward depends of time, lets initialize\n total_time = 0\n wait_time = 0\n ride_time = 0\n transit_time = 0\n\n ## next state depends on possible actions taken by cab driver\n ## There are 3 cases for the same\n ## 1. Cab driver refuse i.e. action (0,0)\n if (pickup_loc) == 0 and (drop_loc == 0):\n wait_time = 1\n next_loc = curr_loc\n\n ## 2. Driver wants to have pickup and is at same location\n elif pickup_loc == curr_loc:\n ride_time = Time_matrix[curr_loc][drop_loc][curr_time][curr_day]\n #print('ride time',ride_time)\n next_loc = drop_loc\n\n ## 3. Driver wants to pickup and is at different location\n else:\n transit_time = Time_matrix[curr_loc][pickup_loc][curr_time][curr_day]\n #print('transit time',transit_time)\n updated_time, updated_day = self.get_updated_day_time(curr_time, curr_day, transit_time)\n ride_time = Time_matrix[pickup_loc][drop_loc][updated_time][updated_day]\n #print('ride time',ride_time)\n next_loc = drop_loc\n curr_time = updated_time\n curr_day = updated_day\n\n total_time = ride_time + wait_time\n #print('total travel time',total_time)\n updated_time, updated_day = self.get_updated_day_time(curr_time, curr_day, total_time)\n #print('updated time',updated_time)\n #print('updated day',updated_day)\n next_state = [next_loc, updated_time, updated_day]\n\n return next_state, wait_time, transit_time, ride_time\n\n\n def get_updated_day_time(self, time, day, duration):\n if time + int(duration) < 24: ## no need to change day\n updated_time = time + int(duration)\n updated_day = day\n else:\n updated_time = (time + int(duration)) % 24\n days_passed = (time + int(duration)) // 24\n updated_day = (day + days_passed ) % 7\n return updated_time, updated_day\n\n def reset(self):\n return self.action_space, self.state_space, self.state_init\n \n#c = CabDriver()\n#print(c.requests([0, 1, 5]))\n"
] |
[
[
"numpy.random.poisson"
]
] |
is0280fp/Side-by-Side-Walking-Model
|
[
"c1bbed8c4ebd74f09729e77d1cbdf8772c038f36"
] |
[
"kubo_trajectory.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 6 19:27:32 2018\n\n@author: yume\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef load_default_trajectory():\n ps = np.array(([\n [-0.53173167, 1.00566862],\n [-0.64863302, 1.21137899],\n [-0.69358629, 1.37081578],\n [-0.56492492, 1.15327546],\n [-0.55600373, 1.20423396],\n [-0.49829951, 1.18146021],\n [-0.4876535 , 1.26848054],\n [-0.40688797, 1.17889313],\n [-0.36144606, 1.17268442],\n [-0.36301364, 1.16589986],\n [-0.26197483, 0.97310113],\n [-0.18595858, 0.84792744],\n [-0.15463059, 0.88581777],\n [-0.11882032, 0.88506996],\n [-0.07030252, 0.83651973],\n [-0.00437487, 0.71518041],\n [ 0.06212817, 0.6156811 ],\n [ 0.09516149, 0.58589172],\n [ 0.11530097, 0.49806781],\n [ 0.15681783, 0.41303067],\n [ 0.16868134, 0.31595739],\n [ 0.14577136, 0.21343067],\n [ 0.21918505, 0.09798281],\n [ 0.23124401, 0.08830546],\n [ 0.31372331, 0.0993604 ],\n [ 0.37089928, 0.0556672 ],\n [ 0.43012147, -0.01261747],\n [ 0.56015322, -0.15992731],\n [ 0.59530929, -0.18893619],\n [ 0.66607129, -0.21852342],\n [ 0.74119056, -0.2547459 ],\n [ 0.80317985, -0.29817707],\n [ 0.87592691, -0.32004919],\n [ 0.99646922, -0.35281576],\n [ 1.07824823, -0.33362457],\n [ 1.08384645, -0.31515728],\n [ 1.11101332, -0.3015165 ],\n [ 1.21916902, -0.30317703],\n [ 1.29680354, -0.26745176],\n [ 1.34889216, -0.22786973],\n [ 1.40211797, -0.27128178],\n [ 1.55955659, -0.26800284],\n [ 1.53856141, -0.21427955],\n [ 1.59283648, -0.23691401],\n [ 1.75731484, -0.22579062],\n [ 1.83461493, -0.15193576],\n [ 1.64913028, -0.12088702],\n [ 1.73514484, -0.11720822],\n [ 1.79714215, -0.10405228],\n [ 1.6275711 , -0.06806892],\n [ 1.41617776, -0.04095689],\n [ 1.33747574, -0.04594844],\n [ 1.76581281, -0.10071683]\n ]))\n ps_for_d = np.array(([\n [ 0.07360019, -0.11945583],\n [-0.11690135, 0.20571037],\n [-0.04495327, 0.15943679],\n [ 0.12866137, -0.21754032],\n [ 0.00892119, 0.0509585 ],\n [ 0.05770422, -0.02277375],\n [ 0.01064601, 0.08702033],\n [ 0.08076553, -0.08958741],\n [ 0.04544191, -0.00620871],\n [-0.00156758, -0.00678456],\n [ 0.10103881, -0.19279873],\n [ 0.07601625, -0.12517369],\n [ 0.03132799, 0.03789033],\n [ 0.03581027, -0.00074781],\n [ 0.0485178 , -0.04855023],\n [ 0.06592765, -0.12133932],\n [ 0.06650304, -0.09949931],\n [ 0.03303332, -0.02978938],\n [ 0.02013948, -0.08782391],\n [ 0.04151686, -0.08503714],\n [ 0.01186351, -0.09707328],\n [-0.02290998, -0.10252672],\n [ 0.07341369, -0.11544786],\n [ 0.01205896, -0.00967735],\n [ 0.0824793 , 0.01105494],\n [ 0.05717597, -0.0436932 ],\n [ 0.05922219, -0.06828467],\n [ 0.13003175, -0.14730984],\n [ 0.03515607, -0.02900888],\n [ 0.070762 , -0.02958723],\n [ 0.07511927, -0.03622248],\n [ 0.06198929, -0.04343117],\n [ 0.07274706, -0.02187212],\n [ 0.12054231, -0.03276657],\n [ 0.08177901, 0.01919119],\n [ 0.00559822, 0.01846729],\n [ 0.02716687, 0.01364078],\n [ 0.1081557 , -0.00166053],\n [ 0.07763452, 0.03572527],\n [ 0.05208862, 0.03958203],\n [ 0.05322581, -0.04341205],\n [ 0.15743862, 0.00327894],\n [-0.02099518, 0.05372329],\n [ 0.05427507, -0.02263446],\n [ 0.16447836, 0.01112339],\n [ 0.07730009, 0.07385486],\n [-0.18548465, 0.03104874],\n [ 0.08601456, 0.0036788 ],\n [ 0.06199731, 0.01315594],\n [-0.16957105, 0.03598336],\n [-0.21139334, 0.02711203],\n [-0.07870202, -0.00499155],\n [ 0.42833707, -0.05476839]\n ]))\n return (ps, ps_for_d)\n\n\nif __name__ == '__main__':\n ps, ds_for_d = load_default_trajectory()\n for p in ps:\n plt.plot(p[0], p[1], \"*\", color='#ff7f00')\n"
] |
[
[
"matplotlib.pyplot.plot",
"numpy.array"
]
] |
watate/spinningup
|
[
"f05f04f6319e3972212448ccec080d4cac426884"
] |
[
"spinup/utils/logx.py"
] |
[
"\"\"\"\n\nSome simple logging functionality, inspired by rllab's logging.\n\nLogs to a tab-separated-values file (path/to/output_directory/progress.txt)\n\n\"\"\"\nimport json\nimport joblib\nimport shutil\nimport numpy as np\nimport tensorflow as tf\nimport os.path as osp, time, atexit, os\nfrom spinup.utils.mpi_tools import proc_id, mpi_statistics_scalar\nfrom spinup.utils.serialization_utils import convert_json\n\ncolor2num = dict(\n gray=30,\n red=31,\n green=32,\n yellow=33,\n blue=34,\n magenta=35,\n cyan=36,\n white=37,\n crimson=38\n)\n\ndef colorize(string, color, bold=False, highlight=False):\n \"\"\"\n Colorize a string.\n\n This function was originally written by John Schulman.\n \"\"\"\n attr = []\n num = color2num[color]\n if highlight: num += 10\n attr.append(str(num))\n if bold: attr.append('1')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n\ndef restore_tf_graph(sess, fpath):\n \"\"\"\n Loads graphs saved by Logger.\n\n Will output a dictionary whose keys and values are from the 'inputs' \n and 'outputs' dict you specified with logger.setup_tf_saver().\n\n Args:\n sess: A Tensorflow session.\n fpath: Filepath to save directory.\n\n Returns:\n A dictionary mapping from keys to tensors in the computation graph\n loaded from ``fpath``. \n \"\"\"\n tf.saved_model.loader.load(\n sess,\n [tf.saved_model.tag_constants.SERVING],\n fpath\n )\n model_info = joblib.load(osp.join(fpath, 'model_info.pkl'))\n graph = tf.get_default_graph()\n model = dict()\n model.update({k: graph.get_tensor_by_name(v) for k,v in model_info['inputs'].items()})\n model.update({k: graph.get_tensor_by_name(v) for k,v in model_info['outputs'].items()})\n return model\n\nclass Logger:\n \"\"\"\n A general-purpose logger.\n\n Makes it easy to save diagnostics, hyperparameter configurations, the \n state of a training run, and the trained model.\n \"\"\"\n\n def __init__(self, output_dir=None, output_fname='progress.txt', exp_name=None):\n \"\"\"\n Initialize a Logger.\n\n Args:\n output_dir (string): A directory for saving results to. If \n ``None``, defaults to a temp directory of the form\n ``/tmp/experiments/somerandomnumber``.\n\n output_fname (string): Name for the tab-separated-value file \n containing metrics logged throughout a training run. \n Defaults to ``progress.txt``. \n\n exp_name (string): Experiment name. If you run multiple training\n runs and give them all the same ``exp_name``, the plotter\n will know to group them. (Use case: if you run the same\n hyperparameter configuration with multiple random seeds, you\n should give them all the same ``exp_name``.)\n \"\"\"\n if proc_id()==0:\n self.output_dir = output_dir or \"/tmp/experiments/%i\"%int(time.time())\n if osp.exists(self.output_dir):\n print(\"Warning: Log dir %s already exists! Storing info there anyway.\"%self.output_dir)\n else:\n os.makedirs(self.output_dir)\n self.output_file = open(osp.join(self.output_dir, output_fname), 'w')\n atexit.register(self.output_file.close)\n print(colorize(\"Logging data to %s\"%self.output_file.name, 'green', bold=True))\n else:\n self.output_dir = None\n self.output_file = None\n self.first_row=True\n self.log_headers = []\n self.log_current_row = {}\n self.exp_name = exp_name\n\n def log(self, msg, color='green'):\n \"\"\"Print a colorized message to stdout.\"\"\"\n if proc_id()==0:\n print(colorize(msg, color, bold=True))\n\n def log_tabular(self, key, val):\n \"\"\"\n Log a value of some diagnostic.\n\n Call this only once for each diagnostic quantity, each iteration.\n After using ``log_tabular`` to store values for each diagnostic,\n make sure to call ``dump_tabular`` to write them out to file and\n stdout (otherwise they will not get saved anywhere).\n \"\"\"\n if self.first_row:\n self.log_headers.append(key)\n else:\n assert key in self.log_headers, \"Trying to introduce a new key %s that you didn't include in the first iteration\"%key\n assert key not in self.log_current_row, \"You already set %s this iteration. Maybe you forgot to call dump_tabular()\"%key\n self.log_current_row[key] = val\n\n def save_config(self, config):\n \"\"\"\n Log an experiment configuration.\n\n Call this once at the top of your experiment, passing in all important\n config vars as a dict. This will serialize the config to JSON, while\n handling anything which can't be serialized in a graceful way (writing\n as informative a string as possible). \n\n Example use:\n\n .. code-block:: python\n\n logger = EpochLogger(**logger_kwargs)\n logger.save_config(locals())\n \"\"\"\n config_json = convert_json(config)\n if self.exp_name is not None:\n config_json['exp_name'] = self.exp_name\n if proc_id()==0:\n output = json.dumps(config_json, separators=(',',':\\t'), indent=4, sort_keys=True)\n print(colorize('Saving config:\\n', color='cyan', bold=True))\n print(output)\n with open(osp.join(self.output_dir, \"config.json\"), 'w') as out:\n out.write(output)\n\n def save_state(self, state_dict, itr=None):\n \"\"\"\n Saves the state of an experiment.\n\n To be clear: this is about saving *state*, not logging diagnostics.\n All diagnostic logging is separate from this function. This function\n will save whatever is in ``state_dict``---usually just a copy of the\n environment---and the most recent parameters for the model you \n previously set up saving for with ``setup_tf_saver``. \n\n Call with any frequency you prefer. If you only want to maintain a\n single state and overwrite it at each call with the most recent \n version, leave ``itr=None``. If you want to keep all of the states you\n save, provide unique (increasing) values for 'itr'.\n\n Args:\n state_dict (dict): Dictionary containing essential elements to\n describe the current state of training.\n\n itr: An int, or None. Current iteration of training.\n \"\"\"\n if proc_id()==0:\n fname = 'vars.pkl' if itr is None else 'vars%d.pkl'%itr\n try:\n joblib.dump(state_dict, osp.join(self.output_dir, fname))\n except:\n self.log('Warning: could not pickle state_dict.', color='red')\n if hasattr(self, 'tf_saver_elements'):\n self._tf_simple_save(itr)\n \n\n def setup_tf_saver(self, sess, inputs, outputs):\n \"\"\"\n Set up easy model saving for tensorflow.\n\n Call once, after defining your computation graph but before training.\n\n Args:\n sess: The Tensorflow session in which you train your computation\n graph.\n\n inputs (dict): A dictionary that maps from keys of your choice\n to the tensorflow placeholders that serve as inputs to the \n computation graph. Make sure that *all* of the placeholders\n needed for your outputs are included!\n\n outputs (dict): A dictionary that maps from keys of your choice\n to the outputs from your computation graph.\n \"\"\"\n self.tf_saver_elements = dict(session=sess, inputs=inputs, outputs=outputs)\n self.tf_saver_info = {'inputs': {k:v.name for k,v in inputs.items()},\n 'outputs': {k:v.name for k,v in outputs.items()}}\n\n def _tf_simple_save(self, itr=None):\n \"\"\"\n Uses simple_save to save a trained model, plus info to make it easy\n to associated tensors to variables after restore. \n \"\"\"\n if proc_id()==0:\n assert hasattr(self, 'tf_saver_elements'), \\\n \"First have to setup saving with self.setup_tf_saver\"\n fpath = 'simple_save' + ('%d'%itr if itr is not None else '')\n fpath = osp.join(self.output_dir, fpath)\n if osp.exists(fpath):\n # simple_save refuses to be useful if fpath already exists,\n # so just delete fpath if it's there.\n shutil.rmtree(fpath)\n \n tf.compat.v1.saved_model.simple_save(export_dir=fpath, **self.tf_saver_elements)\n joblib.dump(self.tf_saver_info, osp.join(fpath, 'model_info.pkl'))\n \n def dump_tabular(self):\n \"\"\"\n Write all of the diagnostics from the current iteration.\n\n Writes both to stdout, and to the output file.\n \"\"\"\n if proc_id()==0:\n vals = []\n key_lens = [len(key) for key in self.log_headers]\n max_key_len = max(15,max(key_lens))\n keystr = '%'+'%d'%max_key_len\n fmt = \"| \" + keystr + \"s | %15s |\"\n n_slashes = 22 + max_key_len\n print(\"-\"*n_slashes)\n for key in self.log_headers:\n val = self.log_current_row.get(key, \"\")\n valstr = \"%8.3g\"%val if hasattr(val, \"__float__\") else val\n print(fmt%(key, valstr))\n vals.append(val)\n print(\"-\"*n_slashes)\n if self.output_file is not None:\n if self.first_row:\n self.output_file.write(\"\\t\".join(self.log_headers)+\"\\n\")\n self.output_file.write(\"\\t\".join(map(str,vals))+\"\\n\")\n self.output_file.flush()\n self.log_current_row.clear()\n self.first_row=False\n\nclass EpochLogger(Logger):\n \"\"\"\n A variant of Logger tailored for tracking average values over epochs.\n\n Typical use case: there is some quantity which is calculated many times\n throughout an epoch, and at the end of the epoch, you would like to \n report the average / std / min / max value of that quantity.\n\n With an EpochLogger, each time the quantity is calculated, you would\n use \n\n .. code-block:: python\n\n epoch_logger.store(NameOfQuantity=quantity_value)\n\n to load it into the EpochLogger's state. Then at the end of the epoch, you \n would use \n\n .. code-block:: python\n\n epoch_logger.log_tabular(NameOfQuantity, **options)\n\n to record the desired values.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.epoch_dict = dict()\n\n def store(self, **kwargs):\n \"\"\"\n Save something into the epoch_logger's current state.\n\n Provide an arbitrary number of keyword arguments with numerical \n values.\n \"\"\"\n for k,v in kwargs.items():\n if not(k in self.epoch_dict.keys()):\n self.epoch_dict[k] = []\n self.epoch_dict[k].append(v)\n\n def log_tabular(self, key, val=None, with_min_and_max=False, average_only=False):\n \"\"\"\n Log a value or possibly the mean/std/min/max values of a diagnostic.\n\n Args:\n key (string): The name of the diagnostic. If you are logging a\n diagnostic whose state has previously been saved with \n ``store``, the key here has to match the key you used there.\n\n val: A value for the diagnostic. If you have previously saved\n values for this key via ``store``, do *not* provide a ``val``\n here.\n\n with_min_and_max (bool): If true, log min and max values of the \n diagnostic over the epoch.\n\n average_only (bool): If true, do not log the standard deviation\n of the diagnostic over the epoch.\n \"\"\"\n if val is not None:\n super().log_tabular(key,val)\n else:\n v = self.epoch_dict[key]\n vals = np.concatenate(v) if isinstance(v[0], np.ndarray) and len(v[0].shape)>0 else v\n stats = mpi_statistics_scalar(vals, with_min_and_max=with_min_and_max)\n super().log_tabular(key if average_only else 'Average' + key, stats[0])\n if not(average_only):\n super().log_tabular('Std'+key, stats[1])\n if with_min_and_max:\n super().log_tabular('Max'+key, stats[3])\n super().log_tabular('Min'+key, stats[2])\n self.epoch_dict[key] = []\n\n # I modified this to include argument with_min_and_max\n def get_stats(self, key, with_min_and_max=False):\n \"\"\"\n Lets an algorithm ask the logger for mean/std/min/max of a diagnostic.\n \"\"\"\n v = self.epoch_dict[key]\n vals = np.concatenate(v) if isinstance(v[0], np.ndarray) and len(v[0].shape)>0 else v\n return mpi_statistics_scalar(vals)"
] |
[
[
"numpy.concatenate",
"tensorflow.get_default_graph",
"tensorflow.compat.v1.saved_model.simple_save",
"tensorflow.saved_model.loader.load"
]
] |
jed057/wtpy
|
[
"4df1dff1dcee43c80701bb0edc1b3eaea385b77f"
] |
[
"wtpy/apps/WtBtAnalyst.py"
] |
[
"from pandas import DataFrame as df\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom dateutil.parser import parse\r\nfrom collections import Counter\r\nfrom datetime import datetime\r\n\r\nimport math\r\nimport json\r\nfrom xlsxwriter import Workbook\r\n\r\n\r\nclass Calculate():\r\n '''\r\n 绩效比率计算\r\n '''\r\n def __init__(self, ret, mar, rf, period, trade):\r\n \"\"\"\r\n :param ret: 收益率序列\r\n :param mar: 最低可接受回报\r\n :param rf: 无风险利率\r\n :param period: 年交易日(用来年化)240\r\n \"\"\"\r\n self.ret = ret\r\n self.mar = mar\r\n self.rf = rf\r\n self.trade = math.ceil(trade)\r\n self.period = period\r\n self.daily_rf = (self.rf + 1) ** (1 / self.period) - 1\r\n\r\n # 潜在上行比率\r\n def calculate_upside_ratio(self):\r\n acess_return = np.sum(self.ret - self.mar)\r\n downside_std = self.ret[self.ret.apply(lambda x: x < 0)].std()\r\n upside_ratio = acess_return / downside_std\r\n return upside_ratio\r\n\r\n # 夏普率\r\n def sharp_ratio(self):\r\n expect_return = self.ret.mean()\r\n std = self.ret.std()\r\n sharp_ratio = (expect_return - self.daily_rf) / std\r\n return sharp_ratio\r\n\r\n # 索提诺比率\r\n def sortion_ratio(self):\r\n expect_return = self.ret.mean()\r\n downside_std = self.ret[self.ret.apply(lambda x: x < 0)].std()\r\n sortion_ratio = (expect_return - self.daily_rf) / downside_std\r\n return sortion_ratio\r\n\r\n # 最大回撤\r\n def maxDrawdown(self):\r\n ret = (self.ret + 1).cumprod()\r\n i = np.argmax((np.maximum.accumulate(ret) - ret) / np.maximum.accumulate(ret))\r\n if i == 0:\r\n return 0\r\n j = np.argmax(ret[:i])\r\n return (ret[j] - ret[i]) / ret[j]\r\n\r\n def maxDrawdown_time(self):\r\n ret = (self.ret + 1).cumprod()\r\n i = np.argmax((np.maximum.accumulate(ret) - ret) / np.maximum.accumulate(ret))\r\n if i == 0:\r\n return 0\r\n j = np.argmax(ret[:i])\r\n return i, j\r\n\r\n # 卡尔马比率\r\n def calmar_ratio(self):\r\n maxdrawdown = Calculate.maxDrawdown(self)\r\n annual_return = Calculate.get_annual_return(self)\r\n calmar_ratio = annual_return / maxdrawdown\r\n return calmar_ratio\r\n\r\n # 斯特林比率\r\n def sterling_a_ratio(self):\r\n average_drawdown = abs(self.ret.where(self.ret < 0, 0).mean())\r\n annual_return = Calculate.get_annual_return(self)\r\n sterling_a_ratio = (annual_return - self.rf) / average_drawdown\r\n return sterling_a_ratio\r\n\r\n # 单笔最大回撤\r\n def single_largest_maxdrawdown(self):\r\n single_largest_mdd = self.ret[self.ret.apply(lambda x: x < 0)]\r\n if len(single_largest_mdd) == 0:\r\n single_largest_mxd = 0\r\n return single_largest_mxd\r\n single_largest_mxd = abs(single_largest_mdd.min())\r\n return single_largest_mxd\r\n\r\n # 单笔最大回撤索引\r\n def single_maxdrawdown_time(self):\r\n i = np.argmin(self.ret)\r\n return i\r\n\r\n # 年化收益率\r\n def get_annual_return(self):\r\n annual_return = 0 if self.trade==0 else ((1 + self.ret.sum()) ** (self.period / self.trade) - 1)\r\n return annual_return\r\n\r\n # 月化收益率\r\n def monthly_return(self):\r\n ann = Calculate.get_annual_return(self)\r\n monthly_return = (ann + 1) ** (1/12) - 1\r\n return monthly_return\r\n\r\n # 月平均收益\r\n def monthly_average_return(self):\r\n monthly = self.ret.mean() * (self.period / 12)\r\n return monthly\r\n\r\n # 衰落时间\r\n def decay_time(self):\r\n netvalue = (self.ret+1).cumprod()\r\n\r\n ser = []\r\n temp = netvalue[0]\r\n ss = 0\r\n for x in netvalue:\r\n if x >= temp:\r\n ss = 0\r\n ser.append(ss)\r\n temp = x\r\n\r\n else:\r\n ss = ss + 1\r\n ser.append(ss)\r\n ss = max(pd.Series(ser))\r\n return ss\r\n\r\ndef fmtNAN(val, defVal = 0):\r\n if math.isnan(val):\r\n return defVal\r\n\r\n return val\r\n\r\ndef continue_trading_analysis(data, x_value) -> dict:\r\n '''\r\n 连续交易分析\r\n '''\r\n mean = data['profit'].mean()\r\n std = data['profit'].std()\r\n z_score = (x_value - mean) / std\r\n times = 0\r\n win_time = 0\r\n ltimes = 0\r\n loss_time = 0\r\n for i in range(len(data)-1):\r\n sss = data['profit'][i]\r\n if sss > 0:\r\n times += 1\r\n ltimes = 0\r\n rem = i\r\n if times > win_time:\r\n win_time = times\r\n con_win_p_end = rem\r\n else:\r\n times = 0\r\n ltimes += 1\r\n rem = i\r\n if ltimes > loss_time:\r\n loss_time = ltimes\r\n con_loss_p_end = rem\r\n\r\n capital = 500000\r\n con_win_profit = (data['profit'].loc[con_win_p_end-win_time + 1:con_win_p_end]).sum()\r\n con_lose_loss = (data['profit'].loc[con_loss_p_end-loss_time + 1:con_loss_p_end]).sum()\r\n # con_win_p_end, win_time 连续盈利结束位置,连续盈利最大次数\r\n # con_loss_p_end,loss_time 连续亏损结束位置,连续亏损最大次数\r\n\r\n cot_profit_ratio = con_win_profit / capital\r\n loss_profit_ratio = con_lose_loss / capital\r\n\r\n result = {'z值': z_score,\r\n '最大连续盈利交易次数': win_time,\r\n '最大连续亏损交易次数': loss_time,\r\n '最大连续盈利额': con_win_profit,\r\n '最大连续亏损额': con_lose_loss,\r\n '最大连续盈利(%)': cot_profit_ratio,\r\n '最大连续亏损(%)': loss_profit_ratio}\r\n\r\n return result\r\n\r\ndef nomalize_val(val):\r\n if math.isnan(val):\r\n return 0\r\n else:\r\n return val\r\n\r\ndef extreme_trading(data, time_of_std=1):\r\n '''\r\n 极端交易分析\r\n '''\r\n std = data['profit'].std()\r\n df_wins = data[data[\"profit\"] > 0]\r\n df_loses = data[data[\"profit\"] <= 0]\r\n winamout = df_wins[\"profit\"].sum() # 毛盈利\r\n loseamount = df_loses[\"profit\"].sum() # 毛亏损\r\n trdnetprofit = winamout + loseamount # 交易净盈亏\r\n totaltimes = len(data) # 总交易次数\r\n avgprof = trdnetprofit / totaltimes if totaltimes > 0 else 0 # 单次平均盈亏\r\n\r\n # 单笔盈利 + 标准差\r\n sin_profit_plstd = avgprof + (std * time_of_std)\r\n # 单笔盈利 - 标准差\r\n sin_profit_mistd = avgprof - (std * time_of_std)\r\n\r\n # 极端交易数量\r\n extreme_result = data[data['profit'].apply(lambda x: x > sin_profit_plstd or x < sin_profit_mistd)]\r\n extreme_num = len(extreme_result)\r\n\r\n # 极端交易盈亏 1 Std. Deviation of Avg. Trade\r\n extreme_profit = 0 if extreme_num==0 else extreme_result['profit'].sum()\r\n\r\n result = {'1 Std. Deviation of Avg. Trade': nomalize_val(std),\r\n '单笔净利 +1倍标准差': nomalize_val(sin_profit_plstd),\r\n '单笔盈利 - 标准差': nomalize_val(sin_profit_mistd),\r\n '极端交易数量': extreme_num,\r\n '极端交易盈亏': extreme_profit\r\n }\r\n return result\r\n\r\n\r\ndef average_profit(data):\r\n '''\r\n 连续交易分析之平均收益\r\n '''\r\n data = data['profit']\r\n win = 0\r\n li = []\r\n lose = 0\r\n li_2 = []\r\n dic= []\r\n dicc = []\r\n for i in range(1, len(data) - 1):\r\n if (data[i] > 0) == (data[i - 1] > 0):\r\n if data[i] > 0:\r\n c = 1\r\n win = win + c\r\n else:\r\n c = 1\r\n lose = lose + c\r\n if (data[i] > 0) == ((data[i + 1]) > 0):\r\n pass\r\n else:\r\n if data[i] > 0:\r\n dis = {str(win): data[i-win:i+1].sum()}\r\n dic.append(dis)\r\n li.append(win)\r\n win = 0\r\n\r\n else:\r\n dis = {str(lose): data[i-lose:i+1].sum()}\r\n dicc.append(dis)\r\n li_2.append(lose)\r\n lose = 0\r\n else:\r\n win = 0\r\n lose = 0\r\n number_win = Counter(li)\r\n number_lose = Counter(li_2)\r\n ss = pd.DataFrame()\r\n for x in dic:\r\n df = pd.DataFrame([x])\r\n ss = pd.concat([ss, df.T])\r\n win_ss = ss.reset_index()\r\n win_ss = win_ss.groupby('index').mean()\r\n\r\n ss2 = pd.DataFrame()\r\n for y in dicc:\r\n df = pd.DataFrame([y])\r\n ss2 = pd.concat([ss2, df.T])\r\n lose_ss = ss2.reset_index()\r\n lose_ss = lose_ss.groupby('index').mean()\r\n result = {'连续盈利次数': number_win,\r\n '连续亏损次数': number_lose,\r\n '每个序列平均收益': win_ss,\r\n '每个序列平均亏损': lose_ss}\r\n return result\r\n\r\ndef stat_closes_by_day(df_closes:df, capital) -> df:\r\n '''\r\n 按天统计平仓数据\r\n '''\r\n df_closes['day'] = df_closes['opentime']\r\n df_closes['win'] = df_closes['profit'].apply(lambda x: 1 if x > 0 else 0)\r\n df_closes['times'] = 1\r\n df_closes['gross_profit'] = df_closes['profit'].apply(lambda x: x if x > 0 else 0)\r\n df_closes['gross_loss'] = df_closes['profit'].apply(lambda x: x if x < 0 else 0)\r\n profit = df_closes.groupby(df_closes['day']).sum()\r\n profit['win_rate'] = profit['win'] / profit['times']\r\n profit['profit_ratio'] = profit['profit']*100.0/capital\r\n res = profit[['profit', 'gross_profit', 'gross_loss', 'times', 'win_rate','profit_ratio']]\r\n return res.iloc[::-1]\r\n\r\ndef stat_closes_by_month(df_closes:df, capital) -> df:\r\n '''\r\n 按月统计平仓数据\r\n '''\r\n df_closes['month'] = df_closes['opentime'].apply(lambda x: x.strftime(\"%Y/%m\"))\r\n df_closes['win'] = df_closes['profit'].apply(lambda x: 1 if x > 0 else 0)\r\n df_closes['times'] = 1\r\n df_closes['gross_profit'] = df_closes['profit'].apply(lambda x: x if x > 0 else 0)\r\n df_closes['gross_loss'] = df_closes['profit'].apply(lambda x: x if x < 0 else 0)\r\n profit = df_closes.groupby(df_closes['month']).sum()\r\n profit['win_rate'] = profit['win'] / profit['times']\r\n profit['profit_ratio'] = profit['profit']*100.0/capital\r\n res = profit[['profit', 'gross_profit', 'gross_loss', 'times', 'win_rate','profit_ratio']]\r\n return res.iloc[::-1]\r\n\r\ndef stat_closes_by_year(df_closes:df, capital) -> df:\r\n '''\r\n 按年统计平仓数据\r\n '''\r\n df_closes['year'] = df_closes['opentime'].apply(lambda x: x.strftime(\"%Y\"))\r\n df_closes['win'] = df_closes['profit'].apply(lambda x: 1 if x > 0 else 0)\r\n df_closes['times'] = 1\r\n df_closes['gross_profit'] = df_closes['profit'].apply(lambda x: x if x > 0 else 0)\r\n df_closes['gross_loss'] = df_closes['profit'].apply(lambda x: x if x < 0 else 0)\r\n profit = df_closes.groupby(df_closes['year']).sum()\r\n profit['win_rate'] = profit['win'] / profit['times']\r\n profit['profit_ratio'] = profit['profit']*100.0/capital\r\n res = profit[['profit', 'gross_profit', 'gross_loss', 'times', 'win_rate','profit_ratio']]\r\n return res.iloc[::-1]\r\n\r\ndef time_analysis(df_closes:df) -> dict:\r\n '''\r\n 时间分析\r\n '''\r\n trading_time = df_closes['closebarno'][len(df_closes) - 1] * 5\r\n\r\n def time_trans(x):\r\n d = x // (24 * 60)\r\n h = x % (24 * 60) // 60\r\n m = x % (24 * 60) % 60\r\n return str(d), str(h), str(m)\r\n # 转化为日,时,分\r\n s_trading_time = time_trans(trading_time)\r\n\r\n # 策略运行时间\r\n str_time = (df_closes['closebarno'] - df_closes['openbarno']).sum() * 5\r\n s_str_time = time_trans(str_time)\r\n # 比率\r\n porition = str_time / trading_time * 100\r\n\r\n # 最大空仓时间\r\n empty_time = (df_closes['openbarno'].shift(-1) - df_closes['closebarno']).max() * 5\r\n s_empty_time = time_trans(empty_time)\r\n\r\n capital = 500000\r\n df_closes['principal'] = df_closes['totalprofit'] + capital\r\n df_closes['principal'] = df_closes['principal'].shift(1)\r\n input_data = df_closes.fillna(value=500000)\r\n ret = input_data['profit'] / input_data['principal']\r\n mar = 0\r\n rf = 0.02\r\n period = 240\r\n trade = input_data['closebarno'][len(input_data) - 1] / 47\r\n factors = Calculate(ret, mar, rf, period, trade)\r\n\r\n single_drawdown_date = factors.single_maxdrawdown_time()\r\n signe_drawdown_date = parse(str(input_data['opentime'][single_drawdown_date]))\r\n\r\n # 最大回撤区间\r\n maxdrawdown_time = factors.maxDrawdown_time()\r\n\r\n # 回撤开始日期\r\n start_time = maxdrawdown_time[1]\r\n start_time = parse(str(input_data['opentime'][start_time]))\r\n\r\n # 回撤结束日期\r\n end_time = maxdrawdown_time[0]\r\n end_time = parse(str(input_data['opentime'][end_time]))\r\n\r\n # 最大损失日期\r\n loss_time_index = np.argmin(input_data['profit'])\r\n loss_time = parse(str(input_data['opentime'][loss_time_index]))\r\n\r\n result = {'交易周期': '(%s)' % ','.join(s_trading_time),\r\n '策略运行时间': '(%s)' % ','.join(s_str_time),\r\n '策略运行时间%': porition,\r\n '最长空仓时间': '(%s)' % ','.join(s_empty_time),\r\n '策略最大回撤开始时间': start_time.strftime(\"%Y/%m/%d %H:%M\"),\r\n '策略最大回撤结束时间': end_time.strftime(\"%Y/%m/%d %H:%M\"),\r\n '单笔最大回撤时间': signe_drawdown_date.strftime(\"%Y/%m/%d %H:%M\"),\r\n '平仓交易最大损失日期': loss_time.strftime(\"%Y/%m/%d %H:%M\")}\r\n\r\n return result\r\n\r\ndef ratio_calculate(data, after_merge, capital = 500000, rf = 0, period = 240) -> dict:\r\n data['principal'] = data['totalprofit'] + capital\r\n data['principal'] = data['principal'].shift(1)\r\n input_data = data.fillna(value=capital)\r\n ret = input_data['profit'] / input_data['principal']\r\n mar = 0\r\n trade = input_data['closebarno'][len(input_data) - 1] / 47\r\n factors = Calculate(ret, mar, rf, period, trade)\r\n # 潜在上涨比率\r\n potential_upside_ratio = factors.calculate_upside_ratio()\r\n # 夏普比率\r\n sharpe_ratio = factors.sharp_ratio()\r\n # 索提诺比率\r\n sortino_ratio = factors.sortion_ratio()\r\n # 卡尔马比率(Calmar Ratio)\r\n calmar_ratio = factors.calmar_ratio()\r\n # 斯特林比率\r\n sterling_ratio = factors.sterling_a_ratio()\r\n result1 = performance_summary(data, after_merge)\r\n # 净利/单笔最大亏损\r\n net_s_loss = result1.get('净利') / result1.get('单笔最大亏损')\r\n # 净利/单笔最大回撤\r\n net_s_drawdown = result1.get('净利') / factors.single_largest_maxdrawdown()\r\n # 净利/ 策略最大回撤\r\n net_strategy_drawdown = result1.get('净利') / factors.maxDrawdown()\r\n # 调整净利/单笔最大亏损\r\n adjust_s_loss = result1.get('调整净利') / result1.get('单笔最大亏损')\r\n # 调整净利/单笔最大回撤\r\n adjust_s_drawdown = result1.get('调整净利') / factors.single_largest_maxdrawdown()\r\n # 调整净利/ 策略最大回撤\r\n adjust_strategy_drawdown = result1.get('调整净利') / factors.maxDrawdown()\r\n\r\n result = {'潜在上涨比率':potential_upside_ratio,\r\n '夏普比率':sharpe_ratio,\r\n '索提诺比率':sortino_ratio,\r\n '卡尔马比率':calmar_ratio,\r\n '斯特林比率':sterling_ratio,\r\n '净利/单笔最大亏损':net_s_loss,\r\n '净利/单笔最大回撤':net_s_drawdown,\r\n '净利/ 策略最大回撤':net_strategy_drawdown,\r\n '调整净利/单笔最大亏损':adjust_s_loss,\r\n '调整净利/单笔最大回撤':adjust_s_drawdown,\r\n '调整净利/ 策略最大回撤':adjust_strategy_drawdown}\r\n\r\n return result\r\n\r\ndef performance_summary(input_data, input_data1, capital = 500000, rf = 0.00, period = 240):\r\n '''\r\n 绩效统计\r\n '''\r\n # 指标计算准备\r\n input_data['principal'] = input_data['totalprofit'] + capital\r\n input_data['principal'] = input_data['principal'].shift(1)\r\n input_data = input_data.fillna(value=capital)\r\n ret = input_data['profit'] / input_data['principal']\r\n mar = 0\r\n trade = len(input_data)\r\n #trade = input_data['closebarno'][len(input_data)-1] / 47\r\n\r\n # 指标class\r\n factors = Calculate(ret, mar, rf, period, trade)\r\n # 毛利\r\n profit = input_data[input_data['profit'].apply(lambda x: x >= 0)]\r\n total_profit = 0 if len(profit)==0 else profit['profit'].sum()\r\n # 毛损\r\n loss = input_data[input_data['profit'].apply(lambda x: x < 0)]\r\n total_loss = 0 if len(loss)==0 else loss['profit'].sum()\r\n # 净利\r\n net_profit = total_profit + total_loss\r\n input_data1['adjust_profit'] = (input_data1['profit'] - input_data1['transaction_fee']) if len(input_data1)>0 else 0\r\n # 调整毛利\r\n adjust_profit = input_data1[input_data1['adjust_profit'].apply(lambda x: x >= 0)]\r\n total_adjust_profit = 0 if len(adjust_profit)==0 else adjust_profit['adjust_profit'].sum()\r\n # 调整毛损\r\n adjust_loss = input_data1[input_data1['adjust_profit'].apply((lambda x: x < 0))]\r\n total_adjust_loss = 0 if len(adjust_loss)==0 else adjust_loss['adjust_profit'].sum()\r\n # 调整净利\r\n adjust_net_profit = total_adjust_profit + total_adjust_loss\r\n # 盈利因子\r\n profit_factor = 0 if total_loss==0 else np.abs(total_profit / total_loss)\r\n # 调整盈利因子\r\n adjust_profit_factor = 0 if total_adjust_loss == 0 else np.abs(total_adjust_profit / total_adjust_loss)\r\n # 最大持有合约数量\r\n max_holding_number = 1\r\n # 已付手续费\r\n paid_trading_fee = input_data1['transaction_fee'].sum() if len(input_data1)>0 else 0\r\n # 单笔最大亏损\r\n single_loss = input_data[input_data['profit'].apply(lambda x: x < 0)]\r\n single_largest_loss = 0 if len(single_loss)==0 else abs(single_loss['profit'].min())\r\n # 平仓交易最大亏损\r\n trading_loss = single_largest_loss\r\n # 平仓交易最大亏损比\r\n trading_loss_rate = trading_loss / capital\r\n # 年化收益率\r\n annual_ret = factors.get_annual_return()\r\n # 月化收益率\r\n monthly_return = factors.monthly_return()\r\n # 月平均收益\r\n monthly_average_return = factors.monthly_average_return()\r\n\r\n # 结果封装字典\r\n result = {'毛利': total_profit,\r\n '毛损': total_loss,\r\n '净利': net_profit,\r\n '调整毛利': adjust_net_profit,\r\n '调整毛损': total_adjust_loss,\r\n '调整净利': adjust_net_profit,\r\n '盈利因子': profit_factor,\r\n '调整盈利因子': adjust_profit_factor,\r\n '最大持有合约数量': max_holding_number,\r\n '已付手续费': paid_trading_fee,\r\n '单笔最大亏损': single_largest_loss,\r\n '平仓交易最大亏损': trading_loss,\r\n '平仓交易最大亏损比': trading_loss_rate,\r\n '年化收益率': annual_ret,\r\n '月化收益率': monthly_return,\r\n '月平均收益': monthly_average_return}\r\n return result\r\n\r\ndef do_trading_analyze(df_closes, df_funds):\r\n \r\n df_wins = df_closes[df_closes[\"profit\"] > 0]\r\n df_loses = df_closes[df_closes[\"profit\"] <= 0]\r\n\r\n ay_WinnerBarCnts = df_wins[\"closebarno\"] - df_wins[\"openbarno\"]\r\n ay_LoserBarCnts = df_loses[\"closebarno\"] - df_loses[\"openbarno\"]\r\n\r\n total_winbarcnts = ay_WinnerBarCnts.sum()\r\n total_losebarcnts = ay_LoserBarCnts.sum()\r\n\r\n total_fee = df_funds.iloc[-1][\"fee\"]\r\n\r\n totaltimes = len(df_closes) # 总交易次数\r\n wintimes = len(df_wins) # 盈利次数\r\n losetimes = len(df_loses) # 亏损次数\r\n winamout = df_wins[\"profit\"].sum() # 毛盈利\r\n loseamount = df_loses[\"profit\"].sum() # 毛亏损\r\n trdnetprofit = winamout + loseamount # 交易净盈亏\r\n accnetprofit = trdnetprofit - total_fee # 账户净盈亏\r\n winrate = (wintimes / totaltimes) if totaltimes > 0 else 0 # 胜率\r\n avgprof = (trdnetprofit / totaltimes) if totaltimes > 0 else 0 # 单次平均盈亏\r\n avgprof_win = (winamout / wintimes) if wintimes > 0 else 0 # 单次盈利均值\r\n avgprof_lose = (loseamount / losetimes) if losetimes > 0 else 0 # 单次亏损均值\r\n winloseratio = abs(avgprof_win / avgprof_lose) if avgprof_lose != 0 else \"N/A\" # 单次盈亏均值比\r\n\r\n # 单笔最大盈利交易\r\n largest_profit = df_wins['profit'].max()\r\n # 单笔最大亏损交易\r\n largest_loss = df_loses['profit'].min()\r\n # 交易的平均持仓K线根数\r\n avgtrd_hold_bar = 0 if totaltimes==0 else ((df_closes['closebarno'] - df_closes['openbarno']).sum()) / totaltimes\r\n # 平均空仓K线根数\r\n avb = (df_closes['openbarno'].shift(-1) - df_closes['closebarno']).dropna()\r\n avgemphold_bar = 0 if len(df_closes)==0 else avb.sum() / len(df_closes)\r\n\r\n # 两笔盈利交易之间的平均空仓K线根数\r\n win_holdbar_situ = (df_wins['openbarno'].shift(-1) - df_wins['closebarno']).dropna()\r\n winempty_avgholdbar = 0 if len(df_wins)==0 else win_holdbar_situ.sum() / len(df_wins)\r\n # 两笔亏损交易之间的偶平均空仓K线根数\r\n loss_holdbar_situ = (df_loses['openbarno'].shift(-1) - df_loses['closebarno']).dropna()\r\n lossempty_avgholdbar = 0 if len(df_loses)==0 else loss_holdbar_situ.sum() / len(df_loses)\r\n\r\n max_consecutive_wins = 0 # 最大连续盈利次数\r\n max_consecutive_loses = 0 # 最大连续亏损次数\r\n\r\n avg_bars_in_winner = total_winbarcnts / wintimes if wintimes > 0 else \"N/A\"\r\n avg_bars_in_loser = total_losebarcnts / losetimes if losetimes > 0 else \"N/A\"\r\n\r\n consecutive_wins = 0\r\n consecutive_loses = 0\r\n\r\n for idx, row in df_closes.iterrows():\r\n profit = row[\"profit\"]\r\n if profit > 0:\r\n consecutive_wins += 1\r\n consecutive_loses = 0\r\n else:\r\n consecutive_wins = 0\r\n consecutive_loses += 1\r\n\r\n max_consecutive_wins = max(max_consecutive_wins, consecutive_wins)\r\n max_consecutive_loses = max(max_consecutive_loses, consecutive_loses)\r\n\r\n summary = dict()\r\n\r\n summary[\"交易总数量\"] = totaltimes\r\n summary[\"盈利交易次数\"] = wintimes\r\n summary[\"亏损交易次数\"] = losetimes\r\n summary[\"毛盈利\"] = float(winamout)\r\n summary[\"毛亏损\"] = float(loseamount)\r\n summary[\"交易净盈亏\"] = float(trdnetprofit)\r\n summary[\"% 胜率\"] = winrate * 100\r\n summary[\"单次平均盈亏\"] = avgprof\r\n summary[\"单次盈利均值\"] = avgprof_win\r\n summary[\"单次亏损均值\"] = avgprof_lose\r\n summary[\"% 单次盈亏均值比\"] = winloseratio\r\n summary[\"最大连续盈利次数\"] = max_consecutive_wins\r\n summary[\"最大连续亏损次数\"] = max_consecutive_loses\r\n summary[\"盈利交易的平均持仓K线根数\"] = avg_bars_in_winner\r\n summary[\"亏损交易的平均持仓K线根数\"] = avg_bars_in_loser\r\n summary[\"账户净盈亏\"] = 0 if totaltimes==0 else accnetprofit / totaltimes\r\n summary['单笔最大盈利交易'] = largest_profit\r\n summary['单笔最大亏损交易'] = largest_loss\r\n summary['交易的平均持仓K线根数'] = avgtrd_hold_bar\r\n summary['平均空仓K线根数'] = avgemphold_bar\r\n summary['两笔盈利交易之间的平均空仓K线根数'] = winempty_avgholdbar\r\n summary['两笔亏损交易之间的平均空仓K线根数'] = lossempty_avgholdbar\r\n summary = pd.DataFrame([summary]).T\r\n summary = summary.reset_index()\r\n return summary\r\n\r\ndef trading_analyze(workbook:Workbook, df_closes, df_funds, capital = 500000):\r\n '''\r\n 交易分析\r\n '''\r\n res = average_profit(df_closes)\r\n rr = res.get('连续盈利次数')\r\n df = pd.DataFrame([rr]).T\r\n df.columns = ['连续次数']\r\n df = df.reset_index()\r\n\r\n every_series_profit = res.get('每个序列平均收益')\r\n every_series_profit = every_series_profit.reset_index()\r\n df['index'] = df['index'].apply(lambda x: int(x))\r\n every_series_profit['index'] = every_series_profit['index'].apply(lambda x: int(x))\r\n f_result = df.merge(every_series_profit)\r\n f_result = f_result.sort_values('index')\r\n f_result.columns = ['连续次数', '出现次数', '每个序列平均收益']\r\n\r\n rr_2 = res.get('连续亏损次数')\r\n df_2 = pd.DataFrame([rr_2]).T\r\n df_2.columns = ['连续次数']\r\n df_2 = df_2.reset_index()\r\n\r\n every_series_loss = res.get('每个序列平均亏损')\r\n every_series_loss = every_series_loss.reset_index()\r\n df_2['index'] = df_2['index'].apply(lambda x: int(x))\r\n every_series_loss['index'] = every_series_loss['index'].apply(lambda x: int(x))\r\n f_2_result = df_2.merge(every_series_loss)\r\n f_2_result = f_2_result.sort_values('index')\r\n f_2_result.columns = ['连续次数', '出现次数', '每个序列平均亏损']\r\n\r\n ssaa = 1000\r\n # 连续交易系列分析\r\n s = continue_trading_analysis(df_closes, ssaa)\r\n # 极端交易\r\n ss = extreme_trading(df_closes)\r\n extre_pro = ss.get('单笔净利 +1倍标准差')\r\n extre_los = ss.get('单笔盈利 - 标准差')\r\n data1 = df_closes[df_closes['profit'].apply(lambda x: x > extre_pro)]\r\n data2 = df_closes[df_closes['profit'].apply(lambda x: x < extre_los)]\r\n ss_1 = extreme_trading(data1)\r\n ss_2 = extreme_trading(data2)\r\n ss_1 = pd.DataFrame([ss_1]).T\r\n ss_2 = pd.DataFrame([ss_2]).T\r\n sss = pd.concat([ss_1, ss_2], axis=1)\r\n ss = pd.DataFrame([ss]).T\r\n sss = pd.concat([ss, sss], axis=1)\r\n sss.columns = ['总计', '极端盈利', '极端亏损']\r\n\r\n title_format = workbook.add_format({\r\n 'font_size': 16,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n index_format = workbook.add_format({\r\n 'font_size': 12,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n value_format = workbook.add_format({\r\n 'align': 'right', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n date_format = workbook.add_format({\r\n 'num_format': 'yyyy/mm/dd',\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n worksheet = workbook.add_worksheet('交易分析')\r\n\r\n trade_s = do_trading_analyze(df_closes, df_funds)\r\n data_1 = df_closes[df_closes['direct'].apply(lambda x: 'LONG' in x)]\r\n trade_s_long = do_trading_analyze(data_1, df_funds)\r\n data_2 = df_closes[df_closes['direct'].apply(lambda x: 'SHORT' in x)]\r\n trade_s_short = do_trading_analyze(data_2, df_funds)\r\n trade_s = trade_s.merge(trade_s_long, how='inner', on='index')\r\n trade_s = trade_s.merge(trade_s_short,how='inner', on='index')\r\n trade_s.columns =['类别', '所有交易', '多头', '空头']\r\n trade_s.fillna(value=0, inplace=True)\r\n\r\n worksheet.write_row('A1', ['总体交易分析'], title_format)\r\n worksheet.write_row('B3', ['所有交易','多头交易','空头交易'], index_format)\r\n worksheet.write_column('A4', trade_s['类别'], index_format)\r\n worksheet.write_column('B4', trade_s['所有交易'], value_format)\r\n worksheet.write_column('C4', trade_s['多头'], value_format)\r\n worksheet.write_column('D4', trade_s['空头'], value_format)\r\n\r\n worksheet.write_row('A28', ['极端交易'], title_format)\r\n worksheet.write_row('B30', ['总计','极端盈利','极端亏损'], index_format)\r\n worksheet.write_column('A31', sss.index, index_format)\r\n worksheet.write_column('B31', sss['总计'], value_format)\r\n worksheet.write_column('C31', sss['极端盈利'], value_format)\r\n worksheet.write_column('D31', sss['极端亏损'], value_format)\r\n\r\n worksheet.write_row('A38', ['连续交易系列分析'], title_format)\r\n worksheet.write_column('A40', s.keys(), index_format)\r\n worksheet.write_column('B40', s.values(), value_format)\r\n\r\n worksheet.write_row('A49', ['连续交易系列统计'], title_format)\r\n worksheet.write_row('A51', ['连续盈利次数','出现次数','每个序列的平均收益'], index_format)\r\n worksheet.write_column('A52', f_result['连续次数'], value_format)\r\n worksheet.write_column('B52', f_result['出现次数'], value_format)\r\n worksheet.write_column('C52', f_result['每个序列平均收益'], value_format)\r\n\r\n win_cnt = len(f_result)\r\n next_row = win_cnt+52\r\n worksheet.write_row('A%d'%next_row, ['连续亏损次数','出现次数','每个序列的平均亏损'], index_format)\r\n worksheet.write_column('A%d'%(next_row+1), f_2_result['连续次数'], value_format)\r\n worksheet.write_column('B%d'%(next_row+1), f_2_result['出现次数'], value_format)\r\n worksheet.write_column('C%d'%(next_row+1), f_2_result['每个序列平均亏损'], value_format)\r\n\r\n # 这里开始画图\r\n next_row += len(f_2_result) + 3\r\n worksheet.write_row('A%d'%next_row, ['全部交易'], title_format)\r\n chart_col = workbook.add_chart({'type': 'scatter'})\r\n length = len(df_closes)\r\n sheetName = '交易列表'\r\n chart_col.add_series(\r\n {\r\n 'name': '收益分布',\r\n 'categories': '=%s!$A$4:$A$%s' % (sheetName, length+3),\r\n 'values': '=%s!$J$4:$J$%s' % (sheetName, length+3),\r\n 'marker': {\r\n 'type':\"circle\", \r\n 'size':3\r\n }\r\n }\r\n )\r\n chart_col.set_title({'name': '收益分布'})\r\n worksheet.insert_chart('A%d' % (next_row+2), chart_col)\r\n\r\n next_row += 30\r\n worksheet.write_row('A%d'%next_row, ['潜在盈利'], title_format)\r\n chart_col = workbook.add_chart({'type': 'scatter'})\r\n length = len(df_closes)\r\n sheetName = '交易列表'\r\n chart_col.add_series(\r\n {\r\n 'name': '潜在盈利',\r\n 'categories': '=%s!$A$4:$A$%s' % (sheetName, length+3),\r\n 'values': '=%s!$N$4:$N$%s' % (sheetName, length+3),\r\n 'marker': {\r\n 'type':\"diamond\", \r\n 'size':3, \r\n 'border': {'color': 'red'},\r\n 'fill': {'color': 'red'}\r\n }\r\n }\r\n )\r\n chart_col.set_title({'name': '潜在盈利'})\r\n worksheet.insert_chart('A%d' % (next_row+2), chart_col)\r\n\r\n next_row += 30\r\n worksheet.write_row('A%d'%next_row, ['潜在亏损'], title_format)\r\n chart_col = workbook.add_chart({'type': 'scatter'})\r\n length = len(df_closes)\r\n sheetName = '交易列表'\r\n chart_col.add_series(\r\n {\r\n 'name': '潜在亏损',\r\n 'categories': '=%s!$A$4:$A$%s' % (sheetName, length+3),\r\n 'values': '=%s!$P$4:$P$%s' % (sheetName, length+3),\r\n 'marker': {\r\n 'type':\"triangle\", \r\n 'size':3, \r\n 'border': {'color': 'green'},\r\n 'fill': {'color': 'green'}\r\n }\r\n }\r\n )\r\n chart_col.set_title({'name': '潜在亏损'})\r\n worksheet.insert_chart('A%d' % (next_row+2), chart_col)\r\n\r\n \r\n # 周期分析\r\n worksheet = workbook.add_worksheet('周期分析')\r\n\r\n df_closes['opentime'] = df_closes['opentime'].apply(lambda x: parse(str(int(x / 10000))))\r\n res = stat_closes_by_day(df_closes.copy(), capital) \r\n worksheet.write_row('A1', ['日度绩效分析'], title_format)\r\n worksheet.write_row('A3', ['期间','盈利(¤)','盈利(%)','毛利','毛损','交易次数','胜率(%)'], index_format)\r\n worksheet.write_column('A4', res.index, date_format)\r\n worksheet.write_column('B4', res[\"profit\"], value_format)\r\n worksheet.write_column('C4', res[\"profit_ratio\"], value_format)\r\n worksheet.write_column('D4', res[\"gross_profit\"], value_format)\r\n worksheet.write_column('E4', res[\"gross_loss\"], value_format)\r\n worksheet.write_column('F4', res[\"times\"], value_format)\r\n worksheet.write_column('G4', res[\"win_rate\"]*100, value_format)\r\n \r\n next_row = 5 + len(res)\r\n res = stat_closes_by_month(df_closes.copy(), capital)\r\n worksheet.write_row('A%d'%(next_row+1), ['月度绩效分析'], title_format)\r\n worksheet.write_row('A%d'%(next_row+3), ['期间','盈利(¤)','盈利(%)','毛利','毛损','交易次数','胜率(%)'], index_format)\r\n worksheet.write_column('A%d'%(next_row+4), res.index, index_format)\r\n worksheet.write_column('B%d'%(next_row+4), res[\"profit\"], value_format)\r\n worksheet.write_column('C%d'%(next_row+4), res[\"profit_ratio\"], value_format)\r\n worksheet.write_column('D%d'%(next_row+4), res[\"gross_profit\"], value_format)\r\n worksheet.write_column('E%d'%(next_row+4), res[\"gross_loss\"], value_format)\r\n worksheet.write_column('F%d'%(next_row+4), res[\"times\"], value_format)\r\n worksheet.write_column('G%d'%(next_row+4), res[\"win_rate\"]*100, value_format)\r\n\r\n next_row = next_row + 4 + len(res)\r\n res = stat_closes_by_year(df_closes.copy(), capital) \r\n worksheet.write_row('A%d'%(next_row+1), ['年度绩效分析'], title_format)\r\n worksheet.write_row('A%d'%(next_row+3), ['期间','盈利(¤)','盈利(%)','毛利','毛损','交易次数','胜率(%)'], index_format)\r\n worksheet.write_column('A%d'%(next_row+4), res.index, index_format)\r\n worksheet.write_column('B%d'%(next_row+4), res[\"profit\"], value_format)\r\n worksheet.write_column('C%d'%(next_row+4), res[\"profit_ratio\"], value_format)\r\n worksheet.write_column('D%d'%(next_row+4), res[\"gross_profit\"], value_format)\r\n worksheet.write_column('E%d'%(next_row+4), res[\"gross_loss\"], value_format)\r\n worksheet.write_column('F%d'%(next_row+4), res[\"times\"], value_format)\r\n worksheet.write_column('G%d'%(next_row+4), res[\"win_rate\"]*100, value_format)\r\n\r\ndef strategy_analyze(workbook:Workbook, df_closes, df_trades, capital, rf = 0.0, period = 240):\r\n '''\r\n 策略分析\r\n '''\r\n\r\n # 截取开仓明细\r\n data1_open = df_trades[df_trades['action'].apply(lambda x: 'OPEN' in x)].reset_index()\r\n data1_open = data1_open.drop(columns=['index'])\r\n # 截取平仓明细\r\n data1_close = df_trades[df_trades['action'].apply(lambda x: 'CLOSE' in x)].reset_index()\r\n data1_close = data1_close.drop(columns=['index'])\r\n\r\n # 将平仓明细字段重命名,并跟开仓明细合并成一个大表\r\n data1_close = data1_close.rename(columns={'code': 'code_1', 'time': 'time_1', 'direct': 'direct_1',\r\n 'action': 'action_1', 'price': 'price_1', 'qty': 'qty_1', 'tag': 'tag_1',\r\n 'fee': 'fee_1'})\r\n\r\n new_data = pd.concat([data1_open, data1_close], axis=1)\r\n new_data = new_data.dropna()\r\n new_data = new_data.drop(columns=['code_1', 'qty_1'])\r\n\r\n # 计算开仓平仓手续费\r\n new_data['transaction_fee'] = new_data['fee'] + new_data['fee_1']\r\n clean_data = new_data[['time', 'transaction_fee']]\r\n clean_data = clean_data.rename(columns={'time': 'opentime'})\r\n\r\n # 合并数据\r\n after_merge = pd.merge(df_closes, clean_data, how='inner', on='opentime')\r\n\r\n data_long = df_closes[df_closes['direct'].apply(lambda x:'LONG' in x )].reset_index()\r\n after_merge_long = after_merge[after_merge['direct'].apply(lambda x: 'LONG' in x)].reset_index()\r\n data_short = df_closes[df_closes['direct'].apply(lambda x: 'SHORT' in x)].reset_index()\r\n after_merge_short = after_merge[after_merge['direct'].apply(lambda x: 'SHORT' in x)].reset_index()\r\n\r\n # 全部平仓明细进行绩效分析\r\n result1 = performance_summary(df_closes, after_merge, capital=capital, rf=rf, period=period)\r\n # 做多平仓明细进行绩效分析\r\n result1_2 = performance_summary(data_long, after_merge_long, capital=capital, rf=rf, period=period)\r\n # 做空平仓明细进行绩效分析\r\n result1_3 = performance_summary(data_short,after_merge_short, capital=capital, rf=rf, period=period)\r\n # 绩效比率计算\r\n result2 = ratio_calculate(df_closes, after_merge, capital=capital, rf=rf, period=period)\r\n # 时间分析\r\n result3 = time_analysis(df_closes)\r\n\r\n result1 = pd.DataFrame(pd.Series(result1), columns=['所有交易'])\r\n result1 = result1.reset_index().rename(columns={'index': '策略绩效概要'})\r\n\r\n result1_2 = pd.DataFrame(pd.Series(result1_2), columns=['多头交易'])\r\n result1_2 = result1_2.reset_index().rename(columns={'index': '策略绩效概要'})\r\n\r\n result1_3 = pd.DataFrame(pd.Series(result1_3), columns=['空头交易'])\r\n result1_3 = result1_3.reset_index().rename(columns={'index': '策略绩效概要'})\r\n\r\n result1 = result1.merge(result1_2,how='inner',on='策略绩效概要')\r\n result1 = result1.merge(result1_3,how='inner',on='策略绩效概要')\r\n\r\n sheetName = '策略分析'\r\n worksheet = workbook.add_worksheet(sheetName)\r\n\r\n title_format = workbook.add_format({\r\n 'font_size': 16,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n index_format = workbook.add_format({\r\n 'font_size': 12,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n value_format = workbook.add_format({\r\n 'align': 'right', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n result1.fillna(value=0, inplace=True)\r\n worksheet.write_row('A1', ['策略绩效概要'], title_format) \r\n worksheet.write_row('B3', ['所有交易','多头交易','空头交易'], index_format)\r\n worksheet.write_column('A4', result1['策略绩效概要'], index_format)\r\n worksheet.write_column('B4', result1['所有交易'], value_format)\r\n worksheet.write_column('C4', result1['多头交易'], value_format)\r\n worksheet.write_column('D4', result1['空头交易'], value_format)\r\n\r\n worksheet.write_row('A22', ['绩效比率'], title_format) \r\n worksheet.write_column('A24', result2.keys(), index_format)\r\n worksheet.write_column('B24', result2.values(), value_format)\r\n\r\n worksheet.write_row('A37', ['时间分析'], title_format) \r\n worksheet.write_column('A39', result3.keys(), index_format)\r\n worksheet.write_column('B39', result3.values(), value_format)\r\n\r\n # 这里开始画图\r\n worksheet.write_row('A49', ['详细权益曲线'], title_format)\r\n chart_col = workbook.add_chart({'type': 'line'})\r\n length = len(df_closes)\r\n sheetName = '交易列表'\r\n chart_col.add_series(\r\n {\r\n 'name': '详细权益曲线',\r\n 'categories': '=%s!$G$4:$G$%s' % (sheetName, length+3),\r\n 'values': '=%s!$R$4:$R$%s' % (sheetName, length+3),\r\n 'line': {'color': 'red','width': 1}\r\n }\r\n )\r\n chart_col.set_title({'name': '详细权益曲线'})\r\n worksheet.insert_chart('A51', chart_col)\r\n\r\n worksheet.write_row('A79', ['详细权益曲线及潜在亏损'], title_format)\r\n chart_col = workbook.add_chart({'type': 'line'})\r\n chart_col.add_series(\r\n {\r\n 'name': '权益曲线',\r\n 'categories': '=%s!$G$4:$G$%s' % (sheetName, length+3),\r\n 'values': '=%s!$R$4:$R$%s' % (sheetName, length+3),\r\n 'line': {'color': 'red','width': 1}\r\n }\r\n )\r\n chart_col.add_series(\r\n {\r\n 'name': '潜在亏损',\r\n 'categories': '=%s!$G$4:$G$%s' % (sheetName, length+3),\r\n 'values': '=%s!$P$4:$P$%s' % (sheetName, length+3),\r\n 'line': {'color': 'green','width': 1}\r\n }\r\n )\r\n chart_col.set_title({'name': '详细权益曲线及潜在亏损'})\r\n worksheet.insert_chart('A81', chart_col)\r\n\r\n worksheet.write_row('A109', ['潜在盈利与亏损'], title_format)\r\n chart_col = workbook.add_chart({'type': 'line'})\r\n chart_col.add_series(\r\n {\r\n 'name': '潜在盈利',\r\n 'categories': '=%s!$G$4:$G$%s' % (sheetName, length+3),\r\n 'values': '=%s!$N$4:$N$%s' % (sheetName, length+3),\r\n 'line': {'color': 'red','width': 1}\r\n }\r\n )\r\n chart_col.add_series(\r\n {\r\n 'name': '潜在亏损',\r\n 'categories': '=%s!$G$4:$G$%s' % (sheetName, length+3),\r\n 'values': '=%s!$P$4:$P$%s' % (sheetName, length+3),\r\n 'line': {'color': 'green','width': 1}\r\n }\r\n )\r\n chart_col.set_title({'name': '潜在盈利与亏损'})\r\n worksheet.insert_chart('A111', chart_col)\r\n\r\ndef output_closes(workbook:Workbook, df_closes:df, capital = 500000):\r\n worksheet = workbook.add_worksheet('交易列表')\r\n title_format = workbook.add_format({\r\n 'font_size': 16,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n index_format = workbook.add_format({\r\n 'font_size': 12,\r\n 'bold': True,\r\n 'align': 'left', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n value_format = workbook.add_format({\r\n 'align': 'right', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n\r\n time_format = workbook.add_format({\r\n 'num_format': 'yyyy/mm/dd HH:MM',\r\n 'align': 'right', # 水平居中\r\n 'valign': 'vcenter' # 垂直居中\r\n })\r\n \r\n\r\n df_closes['entrytime'] = df_closes['opentime'].apply(lambda x: datetime.strptime(str(x), '%Y%m%d%H%M'))\r\n df_closes['exittime'] = df_closes['closetime'].apply(lambda x: datetime.strptime(str(x), '%Y%m%d%H%M'))\r\n\r\n worksheet.write_row('A1', ['交易列表'], title_format) \r\n worksheet.write_row('A3', ['编号', '代码','方向','进场时间','进场价格','进场标记','出场时间','出场价格','出场标记',\r\n '盈利¤','盈利%','累计盈利¤','累计盈利%','潜在盈利¤','潜在盈利%','潜在亏损¤','潜在亏损%','累计权益'], index_format)\r\n df_closes[\"profit_ratio\"] = df_closes[\"profit\"]*100/capital\r\n df_closes[\"total_profit_ratio\"] = df_closes[\"totalprofit\"]*100/capital\r\n df_closes[\"max_profit_ratio\"] = df_closes[\"maxprofit\"]*100/capital\r\n df_closes[\"max_loss_ratio\"] = df_closes[\"maxloss\"]*100/capital\r\n\r\n worksheet.write_column('A4', df_closes.index+1, value_format)\r\n worksheet.write_column('B4', df_closes['code'], value_format)\r\n worksheet.write_column('C4', df_closes['direct'], value_format)\r\n worksheet.write_column('D4', df_closes['entrytime'], time_format)\r\n worksheet.write_column('E4', df_closes['openprice'], value_format)\r\n ay = df_closes['entertag'].apply(lambda x: x if type(x)==str else '' if math.isnan(x) else x)\r\n worksheet.write_column('F4', ay, value_format)\r\n worksheet.write_column('G4', df_closes['exittime'], time_format)\r\n worksheet.write_column('H4', df_closes['closeprice'], value_format)\r\n ay = df_closes['exittag'].apply(lambda x: x if type(x)==str else '' if math.isnan(x) else x)\r\n worksheet.write_column('I4', ay, value_format)\r\n\r\n worksheet.write_column('J4', df_closes['profit'], value_format)\r\n worksheet.write_column('K4', df_closes['profit_ratio'], value_format)\r\n worksheet.write_column('L4', df_closes['totalprofit'], value_format)\r\n worksheet.write_column('M4', df_closes['total_profit_ratio'], value_format)\r\n worksheet.write_column('N4', df_closes['maxprofit'], value_format)\r\n worksheet.write_column('O4', df_closes['max_profit_ratio'], value_format)\r\n worksheet.write_column('P4', df_closes['maxloss'], value_format)\r\n worksheet.write_column('Q4', df_closes['max_loss_ratio'], value_format)\r\n worksheet.write_column('R4', df_closes['totalprofit']+capital, value_format)\r\n\r\ndef summary_analyze(df_funds:df, capital = 5000000, rf = 0, period = 240) -> dict:\r\n '''\r\n 概要分析\r\n '''\r\n init_capital = capital\r\n annual_days = period\r\n days = len(df_funds)\r\n\r\n #先做资金统计吧\r\n print(\"anayzing fund data……\")\r\n df_funds[\"dynbalance\"] += init_capital\r\n ayBal = df_funds[\"dynbalance\"] # 每日期末动态权益\r\n\r\n #生成每日期初动态权益\r\n ayPreBal = np.array(ayBal.tolist()[:-1]) \r\n ayPreBal = np.insert(ayPreBal, 0, init_capital) #每日期初权益\r\n df_funds[\"prebalance\"] = ayPreBal\r\n\r\n #统计期末权益大于期初权益的天数,即盈利天数\r\n windays = len(df_funds[df_funds[\"dynbalance\"]>df_funds[\"prebalance\"]])\r\n\r\n #每日净值\r\n ayNetVals = (ayBal/init_capital)\r\n \r\n ar = math.pow(ayNetVals.iloc[-1], annual_days/days) - 1 #年化收益率=总收益率^(年交易日天数/统计天数)\r\n ayDailyReturn = ayBal/ayPreBal-1 #每日收益率\r\n delta = fmtNAN(ayDailyReturn.std(axis=0)*math.pow(annual_days,0.5),0) #年化标准差=每日收益率标准差*根号下(年交易日天数)\r\n down_delta = fmtNAN(ayDailyReturn[ayDailyReturn<0].std(axis=0)*math.pow(annual_days,0.5), 0) #下行标准差=每日亏损收益率标准差*根号下(年交易日天数)\r\n\r\n #sharpe率\r\n if delta != 0.0:\r\n sr = (ar-rf)/delta\r\n else:\r\n sr = 9999.0\r\n\r\n #计算最大回撤和最大上涨\r\n maxub = ayNetVals[0]\r\n minub = maxub\r\n mdd = 0.0\r\n midd = 0.0\r\n mup = 0.0\r\n for idx in range(1,len(ayNetVals)):\r\n maxub = max(maxub, ayNetVals[idx])\r\n minub = min(minub, ayNetVals[idx])\r\n profit = (ayNetVals[idx] - ayNetVals[idx-1])/ayNetVals[idx-1]\r\n falldown = (ayNetVals[idx] - maxub)/maxub\r\n riseup = (ayNetVals[idx] - minub)/minub\r\n if profit <= 0:\r\n midd = max(midd, abs(profit))\r\n mdd = max(mdd, abs(falldown))\r\n else:\r\n mup = max(mup, abs(riseup))\r\n #索提诺比率\r\n if down_delta != 0.0:\r\n sortino = (ar-rf)/down_delta\r\n else:\r\n sortino = 0.0\r\n if mdd != 0.0:\r\n calmar = ar/mdd\r\n else:\r\n calmar = 999999.0\r\n\r\n\r\n # key_indicator = ['交易天数', '累积收益(%)', '年化收益率(%)', '胜率(%)', '最大回撤(%)', '最大上涨(%)', '标准差(%)',\r\n # '下行波动率(%)', 'Sharpe比率', 'Sortino比率', 'Calmar比率']\r\n return {\r\n \"days\": days,\r\n \"total_return\":(ayNetVals.iloc[-1]-1)*100, \r\n \"annual_return\":ar*100, \r\n \"win_rate\":(windays/days)*100, \r\n \"max_falldown\":mdd*100, \r\n \"max_profratio\":mup*100, \r\n \"std\":delta*100, \r\n \"down_std\":down_delta*100, \r\n \"sharpe_ratio\":sr, \r\n \"sortino_ratio\":sortino, \r\n \"calmar_ratio\":calmar\r\n }\r\n\r\n\r\ndef funds_analyze(workbook:Workbook, df_funds:df, capital = 5000000, rf = 0, period = 240):\r\n '''\r\n 逐日资金分析\r\n '''\r\n init_capital = capital\r\n annual_days = period\r\n days = len(df_funds)\r\n\r\n #先做资金统计吧\r\n print(\"anayzing fund data……\")\r\n df_funds[\"dynbalance\"] += init_capital\r\n ayBal = df_funds[\"dynbalance\"] # 每日期末动态权益\r\n\r\n #生成每日期初动态权益\r\n ayPreBal = np.array(ayBal.tolist()[:-1]) \r\n ayPreBal = np.insert(ayPreBal, 0, init_capital) #每日期初权益\r\n df_funds[\"prebalance\"] = ayPreBal\r\n\r\n #统计期末权益大于期初权益的天数,即盈利天数\r\n windays = len(df_funds[df_funds[\"dynbalance\"]>df_funds[\"prebalance\"]])\r\n\r\n #每日净值\r\n ayNetVals = (ayBal/init_capital)\r\n \r\n ar = math.pow(ayNetVals.iloc[-1], annual_days/days) - 1 #年化收益率=总收益率^(年交易日天数/统计天数)\r\n ayDailyReturn = ayBal/ayPreBal-1 #每日收益率\r\n delta = fmtNAN(ayDailyReturn.std(axis=0)*math.pow(annual_days,0.5),0) #年化标准差=每日收益率标准差*根号下(年交易日天数)\r\n down_delta = fmtNAN(ayDailyReturn[ayDailyReturn<0].std(axis=0)*math.pow(annual_days,0.5), 0) #下行标准差=每日亏损收益率标准差*根号下(年交易日天数)\r\n\r\n #sharpe率\r\n if delta != 0.0:\r\n sr = (ar-rf)/delta\r\n else:\r\n sr = 9999.0\r\n\r\n #计算最大回撤和最大上涨\r\n maxub = ayNetVals[0]\r\n minub = maxub\r\n mdd = 0.0\r\n midd = 0.0\r\n mup = 0.0\r\n for idx in range(1,len(ayNetVals)):\r\n maxub = max(maxub, ayNetVals[idx])\r\n minub = min(minub, ayNetVals[idx])\r\n profit = (ayNetVals[idx] - ayNetVals[idx-1])/ayNetVals[idx-1]\r\n falldown = (ayNetVals[idx] - maxub)/maxub\r\n riseup = (ayNetVals[idx] - minub)/minub\r\n if profit <= 0:\r\n midd = max(midd, abs(profit))\r\n mdd = max(mdd, abs(falldown))\r\n else:\r\n mup = max(mup, abs(riseup))\r\n #索提诺比率\r\n if down_delta != 0.0:\r\n sortino = (ar-rf)/down_delta\r\n else:\r\n sortino = 0.0\r\n if mdd != 0.0:\r\n calmar = ar/mdd\r\n else:\r\n calmar = 999999.0\r\n\r\n #输出到excel\r\n sheetName = '逐日绩效概览'\r\n worksheet = workbook.add_worksheet(sheetName)\r\n\r\n # 设置合并单元格及格式 #\r\n # ~~~~~~ 写入数据 ~~~~~~ #\r\n title_format = workbook.add_format({\r\n 'bold': True,\r\n 'border': 1,\r\n 'align': 'center', # 水平居中\r\n 'valign': 'vcenter', # 垂直居中\r\n 'fg_color': '#bcbcbc'\r\n })\r\n fund_data_format = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n })\r\n \r\n fund_data_format_2 = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n 'num_format': '0.00'\r\n })\r\n\r\n fund_data_format_3 = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n 'num_format': '0.000'\r\n })\r\n\r\n fund_data_format_4 = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n 'num_format': '0.0000'\r\n })\r\n\r\n\r\n merge_format = workbook.add_format({\r\n 'font_size': 16,\r\n 'bold': True,\r\n 'align': 'center', # 水平居中\r\n 'valign': 'vcenter', # 垂直居中\r\n })\r\n indicator_format = workbook.add_format({\r\n 'font_size': 12,\r\n 'bold': True,\r\n 'align': 'center', # 水平居中\r\n 'valign': 'vcenter', # 垂直居中\r\n })\r\n worksheet.merge_range('A1:D1', '收益率统计指标', merge_format)\r\n worksheet.merge_range('E1:H1', '风险统计指标', merge_format)\r\n worksheet.merge_range('I1:K1', '综合指标', merge_format)\r\n\r\n key_indicator = ['交易天数', '累积收益(%)', '年化收益率(%)', '胜率(%)', '最大回撤(%)', '最大上涨(%)', '标准差(%)',\r\n '下行波动率(%)', 'Sharpe比率', 'Sortino比率', 'Calmar比率']\r\n key_data = [(ayNetVals.iloc[-1]-1)*100, ar*100, (windays/days)*100, mdd*100, mup*100, delta*100, down_delta*100, sr, sortino, calmar]\r\n worksheet.write_row('A2', key_indicator, indicator_format)\r\n worksheet.write_column('A3', [days], fund_data_format)\r\n worksheet.write_row('B3', key_data, fund_data_format_3)\r\n\r\n # 画图 #\r\n chart_col = workbook.add_chart({'type': 'line'})\r\n length = days\r\n chart_col.add_series( # 给图表设置格式,填充内容\r\n {\r\n 'name': '=逐日绩效分析!$B$1',\r\n 'categories': '=逐日绩效分析!$A$3:$A$%d' % (length+2),\r\n 'values': '=逐日绩效分析!$G$3:$G$%d' % (length+2),\r\n 'line': {'color': 'blue', 'width':1},\r\n }\r\n )\r\n chart_col.set_title({'name': '累计净值'})\r\n worksheet.insert_chart('A8', chart_col)\r\n\r\n # 准备第二张表格 #\r\n sheetName = '逐日绩效分析'\r\n worksheet = workbook.add_worksheet(sheetName)\r\n title_format2 = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'center', # 水平居中\r\n 'valign': 'vcenter', # 垂直居中\r\n 'fg_color': '#D3D3D3',\r\n 'text_wrap': 1\r\n })\r\n worksheet.merge_range('A1:A2', '日期', title_format2)\r\n worksheet.merge_range('B1:B2', '统计时间', title_format2)\r\n worksheet.merge_range('C1:C2', '初始资金', title_format2)\r\n worksheet.merge_range('D1:D2', '出入金', title_format2)\r\n worksheet.merge_range('E1:E2', '当前权益', title_format2)\r\n worksheet.merge_range('F1:F2', '累计盈亏', title_format2)\r\n worksheet.merge_range('G1:G2', '累计净值', title_format2)\r\n worksheet.merge_range('H1:I1', '当日盈亏', title_format2)\r\n indicator = ['数值', '比例']\r\n worksheet.write_row('H2', indicator, title_format2)\r\n worksheet.merge_range('J1:J2', '峰值', title_format2)\r\n worksheet.merge_range('K1:K2', '当日累计回撤', title_format2)\r\n worksheet.merge_range('L1:L2', '历史最大累计回撤', title_format2)\r\n worksheet.merge_range('M1:M2', '最大单日回撤', title_format2)\r\n worksheet.merge_range('N1:N2', '衰落时间', title_format2)\r\n # worksheet.merge_range('O1:O2', 'IF指数', title_format2)\r\n # worksheet.merge_range('P1:P2', 'IF净值', title_format2)\r\n\r\n # 写入内容 #\r\n profit_format = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 靠右\r\n 'valign': 'vcenter', # 垂直居中\r\n 'fg_color': '#FAFAD2',\r\n 'num_format': '0.00'\r\n })\r\n\r\n percent_format = workbook.add_format({\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n 'num_format': '0.00%'\r\n })\r\n\r\n date_format = workbook.add_format({\r\n 'num_format': 'yyyy/mm/dd',\r\n 'border': 1,\r\n 'align': 'right', # 右对齐\r\n 'valign': 'vcenter', # 垂直居中\r\n })\r\n\r\n ayDates = df_funds['date'].apply(lambda x: str(x)[:4]+'/'+str(x)[4:6]+'/'+str(x)[6:8])\r\n worksheet.write_column('A3', ayDates, date_format)\r\n worksheet.write_column('B3', range(len(df_funds)), fund_data_format)\r\n initial = [init_capital]*len(df_funds)\r\n worksheet.write_column('C3', initial, fund_data_format)\r\n worksheet.write_column('D3', '/', fund_data_format)\r\n worksheet.write_column('E3', ayBal, fund_data_format)\r\n worksheet.write_column('F3', ayBal-init_capital, fund_data_format_2)\r\n worksheet.write_column('G3', ayNetVals, fund_data_format_4)\r\n worksheet.write_column('H3', ayBal-ayPreBal, profit_format)\r\n worksheet.write_column('I3', ayDailyReturn, percent_format)\r\n # 计算峰值\r\n upper = np.maximum.accumulate(ayNetVals)\r\n worksheet.write_column('J3', upper, fund_data_format_4)\r\n # 回撤指标\r\n temp = 1-(ayNetVals)/(np.maximum.accumulate(ayNetVals))\r\n worksheet.write_column('K3', temp, percent_format)\r\n worksheet.write_column('L3', np.maximum.accumulate(temp), percent_format)\r\n worksheet.write_column('M3', np.minimum.accumulate(ayDailyReturn), percent_format)\r\n # 计算衰落时间\r\n down_time = [0]\r\n for i in range(1, len(upper)):\r\n if upper[i] > upper[i-1]:\r\n down_time.append(0)\r\n else:\r\n l = down_time[i-1]\r\n down_time.append(l+1)\r\n worksheet.write_column('N3', down_time, fund_data_format)\r\n\r\nclass WtBtAnalyst:\r\n\r\n def __init__(self):\r\n self.__strategies__ = dict()\r\n return\r\n\r\n def add_strategy(self, sname:str, folder:str, init_capital:float, rf:float=0.02, annual_trading_days:int = 240):\r\n self.__strategies__[sname] = {\r\n \"folder\": folder,\r\n \"cap\":init_capital,\r\n \"rf\":rf,\r\n \"atd\":annual_trading_days\r\n }\r\n\r\n def run_new(self, outFileName:str = ''):\r\n if len(self.__strategies__.keys()) == 0:\r\n raise Exception(\"strategies is empty\")\r\n\r\n for sname in self.__strategies__:\r\n sInfo = self.__strategies__[sname]\r\n folder = sInfo[\"folder\"]\r\n print(\"start PnL analyzing for strategy %s……\" % (sname))\r\n\r\n df_funds = pd.read_csv(folder + \"funds.csv\")\r\n df_closes = pd.read_csv(folder + \"closes.csv\")\r\n df_trades = pd.read_csv(folder + \"trades.csv\")\r\n\r\n if len(outFileName) == 0:\r\n outFileName = 'Strategy[%s]_PnLAnalyzing_%s_%s.xlsx' % (sname, df_funds['date'][0], df_funds['date'].iloc[-1])\r\n\r\n workbook = Workbook(outFileName)\r\n init_capital = sInfo[\"cap\"]\r\n annual_days = sInfo[\"atd\"]\r\n rf = sInfo[\"rf\"]\r\n\r\n strategy_analyze(workbook, df_closes.copy(), df_trades.copy(), capital=init_capital, rf=rf, period=annual_days)\r\n output_closes(workbook, df_closes.copy(), capital=init_capital)\r\n trading_analyze(workbook, df_closes.copy(), df_funds.copy(), capital=init_capital)\r\n funds_analyze(workbook, df_funds.copy(), capital=init_capital, rf=rf, period=annual_days)\r\n workbook.close()\r\n\r\n print(\"PnL analyzing of strategy %s done\" % (sname))\r\n\r\n\r\n def run(self, outFileName:str = ''):\r\n if len(self.__strategies__.keys()) == 0:\r\n raise Exception(\"strategies is empty\")\r\n\r\n for sname in self.__strategies__:\r\n sInfo = self.__strategies__[sname]\r\n folder = sInfo[\"folder\"]\r\n print(\"start PnL analyzing for strategy %s……\" % (sname))\r\n\r\n df_funds = pd.read_csv(folder + \"funds.csv\")\r\n print(\"fund logs loaded……\")\r\n\r\n init_capital = sInfo[\"cap\"]\r\n annual_days = sInfo[\"atd\"]\r\n rf = sInfo[\"rf\"]\r\n \r\n if len(outFileName) == 0:\r\n outFileName = 'Strategy[%s]_PnLAnalyzing_%s_%s.xlsx' % (sname, df_funds['date'][0], df_funds['date'].iloc[-1])\r\n workbook = Workbook(outFileName)\r\n funds_analyze(workbook, df_funds, capital=init_capital, rf=rf, period=annual_days)\r\n workbook.close()\r\n\r\n print(\"PnL analyzing of strategy %s done\" % (sname))\r\n\r\n def run_simple(self):\r\n if len(self.__strategies__.keys()) == 0:\r\n raise Exception(\"strategies is empty\")\r\n\r\n for sname in self.__strategies__:\r\n sInfo = self.__strategies__[sname]\r\n folder = sInfo[\"folder\"]\r\n\r\n df_funds = pd.read_csv(folder + \"funds.csv\")\r\n\r\n init_capital = sInfo[\"cap\"]\r\n annual_days = sInfo[\"atd\"]\r\n rf = sInfo[\"rf\"]\r\n \r\n filename = folder + 'summary.json'\r\n sumObj = summary_analyze(df_funds, capital=init_capital, rf=rf, period=annual_days)\r\n sumObj[\"name\"] = sname\r\n f = open(filename,\"w\")\r\n f.write(json.dumps(sumObj, indent=4, ensure_ascii=True))\r\n f.close()"
] |
[
[
"pandas.concat",
"pandas.merge",
"pandas.read_csv",
"numpy.abs",
"pandas.Series",
"numpy.minimum.accumulate",
"pandas.DataFrame",
"numpy.argmax",
"numpy.argmin",
"numpy.insert",
"numpy.maximum.accumulate",
"numpy.sum"
]
] |
kunadawa/video-object-detection
|
[
"9e90f9d02b04b1052c596d857968e93d7c421366"
] |
[
"samples/conftest.py"
] |
[
"import pytest\nimport numpy\nfrom proto.generated import detection_handler_pb2\nimport datetime\n\n\[email protected]\ndef create_handle_detection_request():\n \"\"\"\n returns a detection_handler_pb2.handle_detection_request object if the input data is successfully serialized into protobuf types\n \"\"\"\n frame_array1 = [5, 2, 3]\n # not sure why the frame from opencv is nested this way\n frame = numpy.array([[frame_array1, [8.4, 7.9, 5.2], [59, 64, 64]]])\n class_id = 8.0\n detection_output = {'detection_scores': [0.54], 'detection_classes': [class_id],\n 'detection_boxes': numpy.array([[0.36190858, 0.11737314, 0.94603133, 0.3205647]])}\n detection_boxes = detection_handler_pb2.float_array(numbers=detection_output['detection_boxes'].ravel(),\n shape=detection_output['detection_boxes'].shape)\n string_map = {'color': 'blue', 'music': 'classical'}\n float_map = {'weight': 56.9, 'height': 85.4}\n category_index = {int(class_id): {'name': \"elephant\"}}\n return detection_handler_pb2.handle_detection_request(\n start_timestamp=datetime.datetime.now().timestamp(),\n detection_scores=detection_output['detection_scores'],\n detection_classes=detection_output['detection_classes'],\n detection_boxes=detection_boxes,\n instance_name=\"testing\",\n frame=detection_handler_pb2.float_array(numbers=frame.ravel(), shape=frame.shape),\n frame_count=1619,\n source=\"steam\",\n string_map=string_map,\n float_map=float_map,\n category_index={k: v['name'] for k, v in category_index.items()}), string_map, float_map, category_index\n"
] |
[
[
"numpy.array"
]
] |
ultimus11/Driverless-Need-For-Speed-MW
|
[
"b5181fb8727ab73f6c3c1c8460437f74de7c90fd"
] |
[
"parts/part3/nfs4.py"
] |
[
"import cv2\r\nimport numpy as np\r\nimport time\r\nfrom grabScreen import grab_screen\r\nfrom direct_key_inputs import PressKey, ReleaseKey, W, A, S, D\r\n\r\ndef forward():\r\n PressKey(W)\r\n ReleaseKey(A)\r\n ReleaseKey(D)\r\ndef process_roi_lanes(img,lines):\r\n try:\r\n for line in lines:\r\n coords = line[0]\r\n cv2.line(img, (coords[0],coords[1]), (coords[2],coords[3]), [255,255,255], 3)\r\n #print(coords[0],coords[1])\r\n #draw circle at the bottom of lane\r\n cv2.circle(img,(coords[0],coords[1]), 10, (255,0,255), 1)\r\n except:\r\n pass\r\ndef roi(img, vertices):\r\n #blank mask:\r\n mask = np.zeros_like(img)\r\n # fill the mask\r\n cv2.fillPoly(mask, vertices, 100)\r\n # now only show the area that is the mask\r\n masked = cv2.bitwise_and(img, mask)\r\n return masked\r\ndef Image_processing(origional_img):\r\n processed_img_1 = cv2.imshow('wondow',origional_img)\r\n processed_img = cv2.Canny(cv2.cvtColor(origional_img,cv2.COLOR_BGR2RGB), threshold1=50, threshold2=300)\r\n #get edges only from our region of interest\r\n vertices = np.array([[1,480],[1,280],[100,225],[540,225],[640,280],[640,470]], np.int32)\r\n #vertices = np.array([[bottomleft],left up],[middle left],[middle right],[right up],[right bottom])\r\n processed_img = roi(processed_img, [vertices])\r\n #process edges in roi\r\n lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, np.array([]), 55, 45)\r\n process_roi_lanes(processed_img,lines)\r\n return processed_img\r\ndef screen_capture():\r\n last_time=time.time()\r\n while(True):\r\n #grab_image\r\n capture_screen,image_1 = grab_screen(region=(100,100,740,580))\r\n #find edges or process image\r\n edges = Image_processing(image_1)\r\n print('heres our {} time '.format(time.time()-last_time))\r\n last_time=time.time()\r\n cv2.imshow('window', edges)\r\n #cv2.imshow('wondow',cv2.cvtColor(capture_screen,cv2.COLOR_BGR2RGB))\r\n if cv2.waitKey(25)&0xFF==('q'):\r\n cv2.destroyAllWindows()\r\n break\r\n\r\nscreen_capture()\r\n\r\n"
] |
[
[
"numpy.array",
"numpy.zeros_like"
]
] |
suddhu/MinkLoc3D
|
[
"11a2d2d3a96e74133b4aff635d456e22133babcd"
] |
[
"training/vizEpochs.py"
] |
[
"# Author: Jacek Komorowski\n# Warsaw University of Technology\n\nimport argparse\nfrom utils import MinkLocParams\nfrom tacto.utils.util3D import Util3D\nfrom shapeclosure.misc import plotTNSE3d, sampleSurfacePoses, renderInteractions\nimport gc \nimport os\nfrom os import path as osp\nfrom model_factory import model_factory\nimport torch\nfrom evaluate import getCloudEmbedding\nimport pickle\nimport numpy as np \nimport re \nimport trimesh\n\nfrom shapeclosure.benchmark_embeddings import evaluate_dataset, plot_violin, getRandomError, getNearestIndices\nfrom tacto.TactoRender import TactoRender\nfrom torch.utils.tensorboard import SummaryWriter\nimport torchvision \n\ntacrender = TactoRender()\n\ndef generateTactoTestData(obj_path : str, numSamples : int = 100):\n tacRender = TactoRender(obj_path, randomize = True, headless = True)\n # print(\"Generating {} random samples\".format(numSamples)) \n mesh = trimesh.load(obj_path)\n samplePoses = sampleSurfacePoses(mesh=mesh, num_samples=numSamples, edges = True) # general\n # remove nan quaternions from sampling \n nan_idxs = np.isnan(samplePoses).any(axis=1)\n while np.sum(nan_idxs) != 0:\n samplePoses[nan_idxs, :] = sampleSurfacePoses(mesh = mesh, num_samples = np.sum(nan_idxs), edges = True)\n nan_idxs = np.isnan(samplePoses).any(axis=1)\n\n sampleHeightmaps, sampleMasks, sampleImages, samplePoses, _ = renderInteractions(samplePoses, tacRender, num_depths = 1, no_contact_prob = 2)\n return sampleHeightmaps, sampleMasks, sampleImages, samplePoses\n\ndef getEvalData(obj_name: list, params: MinkLocParams, numSamples = 5):\n model = model_factory(params)\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n model.to(device)\n model.eval()\n\n heightmap_path = os.path.join(params.eval_folder, obj_name, \"gt_heightmaps\") \n image_path = os.path.join(params.eval_folder, obj_name, \"tactile_images\") \n contactmasks_path = os.path.join(params.eval_folder, obj_name, \"gt_contactmasks\") \n pose_path = os.path.join(params.eval_folder, obj_name, \"tactile_data.pkl\") \n obj_path = os.path.join(\"/mnt/sda/suddhu/YCBModels\", obj_name, \"google_512k/nontextured.stl\")\n u3d = Util3D(obj_path, off_screen = True, virtual_buff = True)\n\n images = u3d.loadImages(image_path)\n heightmaps, contactmasks = u3d.loadHeightmapsAndMasks(heightmap_path, contactmasks_path)\n with open(pose_path, 'rb') as pickle_file:\n gelposes = pickle.load(pickle_file)[\"gelposes\"]\n sampleHeightmaps, sampleMasks, sampleImages, samplePoses = generateTactoTestData(obj_path = obj_path, numSamples = numSamples)\n\n dataDict = { \"obj_name\" : obj_name, \n \"params\" : params, \n \"numSamples\" : numSamples, \n \"model\" : model, \n \"images\" : images, \n \"heightmaps\" : heightmaps, \n \"contactmasks\" : contactmasks, \n \"gelposes\" : gelposes, \n \"sampleHeightmaps\" : sampleHeightmaps, \n \"sampleMasks\" : sampleMasks, \n \"sampleImages\" : sampleImages,\n \"samplePoses\" : samplePoses\n }\n return dataDict\n\n# return top 10 embedding scores images, and pose score images \ndef testEvalSamples(epoch : int, weights_path: str, data : dict):\n savepath = os.path.join(\"/mnt/sda/suddhu/minkloc_training\", data[\"obj_name\"])\n if not os.path.exists(os.path.join(savepath, \"image_output\")):\n os.makedirs(os.path.join(savepath, \"image_output\"))\n\n model = data[\"model\"]\n device = next(model.parameters()).device\n\n checkpoint = torch.load(weights_path, map_location=device)\n if type(checkpoint) is dict:\n model.load_state_dict(checkpoint['state_dict'])\n else:\n model.load_state_dict(checkpoint)\n # print(\"=> loaded weights '{}' (epoch {})\"\n # .format(weights_path, checkpoint['epoch']))\n\n print(\"Viz. epoch {} embeddings for {}\".format(epoch, data[\"obj_name\"]))\n\n databaseEmbeddings = getCloudEmbedding(model, tacrender, data[\"heightmaps\"], data[\"contactmasks\"], data[\"params\"], batch_size=100)\n queryEmbeddings = getCloudEmbedding(model, tacrender, data[\"sampleHeightmaps\"], data[\"sampleMasks\"], data[\"params\"], batch_size = 100)\n gc.collect()\n\n nn = 5\n # get the nearest images from the embeddings and pose supervision to compare\n d, q = databaseEmbeddings, queryEmbeddings\n eval_idxs, pose_idxs = getNearestIndices(d, q, data[\"gelposes\"], data[\"samplePoses\"], num_neighbors = nn)\n\n grid = [None] * data[\"numSamples\"] \n\n for i in range(data[\"numSamples\"]):\n m_anchor = torch.tensor(data[\"sampleImages\"][i]).permute(2, 0, 1)\n eval_set, pose_set = [], [] \n for e in eval_idxs[i]:\n m_eval = torch.tensor(data[\"images\"][e]).permute(2, 0, 1)\n eval_set.append(m_eval)\n for p in pose_idxs[i]:\n m_pose = torch.tensor(data[\"images\"][p]).permute(2, 0, 1)\n pose_set.append(m_pose)\n \n all_set = eval_set + pose_set + [m_anchor]\n grid[i] = torchvision.utils.make_grid(all_set, nrow = nn, padding = 5, pad_value = 1)\n # grid[i] = torchvision.transforms.ToPILImage()(grid[i])\n full_grid = torchvision.utils.make_grid(grid, nrows = 1, padding = 5, pad_value = 1)\n full_grid = torchvision.transforms.ToPILImage()(full_grid)\n image_path = os.path.join(savepath, \"image_output\", f\"{epoch:03d}_cloud.png\")\n full_grid.save(image_path)\n\ndef evalViolinPlot(epoch: int, weights_path: str, data : dict, random_error : float = 1.0, k : int = 10):\n savepath = os.path.join(\"/mnt/sda/suddhu/minkloc_training\", data[\"obj_name\"])\n if not os.path.exists(os.path.join(savepath, \"violin\")):\n os.makedirs(os.path.join(savepath, \"violin\"))\n\n model = data[\"model\"]\n device = next(model.parameters()).device\n\n checkpoint = torch.load(weights_path, map_location=device)\n if type(checkpoint) is dict:\n model.load_state_dict(checkpoint['state_dict'])\n else:\n model.load_state_dict(checkpoint)\n\n # print(\"=> loaded weights '{}' (epoch {})\"\n # .format(weights_path, checkpoint['epoch']))\n\n print(f\"Viz. violin plot epoch: {epoch} embeddings for {data['obj_name']}\")\n\n databaseEmbeddings = getCloudEmbedding(model, tacrender, data[\"heightmaps\"], data[\"contactmasks\"], data[\"params\"], batch_size=100)\n queryEmbeddings = getCloudEmbedding(model, tacrender, data[\"sampleHeightmaps\"], data[\"sampleMasks\"], data[\"params\"], batch_size=100)\n gc.collect()\n\n recall, top_1_error, top_n_error = evaluate_dataset(databaseEmbeddings, queryEmbeddings, data[\"gelposes\"], data[\"samplePoses\"], n = k)\n top_1_error /= random_error\n top_n_error /= random_error\n # print recall and avg error\n rmse = {}\n print(f'Avg. norm. RMSE (Top 1): {np.mean(top_1_error):.4f}, Avg. norm. RMSE (Top {k}): {np.mean(top_n_error):.4f}, Random. RMSE: {1.0:.4f}')\n \n rmse[f'top_1'] = np.mean(top_1_error)\n rmse[f'top_{k}'] = np.mean(top_n_error)\n # rmse['random'] = 1.0\n\n image_path = os.path.join(savepath, \"violin\", f\"{epoch}.png\")\n plot_violin(top_1_error, top_n_error, 1.0, image_path, epoch)\n # print(f\"Saved violin @ {image_path}\")\n return rmse\n\ndef evalTSNE(obj_name: str, all_weights_path: str, params: MinkLocParams, valid_embeddings : list = ['image_embedding', 'cloud_embedding', 'embedding']):\n model = model_factory(params)\n # Move the model to the proper device before configuring the optimizer\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n model.to(device)\n model.eval()\n\n all_weights = os.listdir(all_weights_path)\n all_weights = sorted(all_weights, key=lambda x: int(x.partition('=')[2].partition('.')[0]))\n\n heightmap_path = os.path.join(params.eval_folder, obj_name, \"gt_heightmaps\") \n contactmasks_path = os.path.join(params.eval_folder, obj_name, \"gt_contactmasks\") \n pose_path = os.path.join(params.eval_folder, obj_name, \"tactile_data.pkl\") \n savepath = os.path.join(\"/mnt/sda/suddhu/minkloc_training\", obj_name)\n obj_path = os.path.join(\"/mnt/sda/suddhu/YCBModels\", obj_name, \"google_512k/nontextured.stl\")\n u3d = Util3D(obj_path, off_screen = True, virtual_buff = True)\n\n heightmaps, contactmasks = u3d.loadHeightmapsAndMasks(heightmap_path, contactmasks_path)\n\n if not os.path.exists(savepath):\n os.makedirs(savepath)\n\n with open(pose_path, 'rb') as pickle_file:\n poseDict = pickle.load(pickle_file)\n gelposes = poseDict[\"gelposes\"]\n TSNE_init = 'pca'\n\n for weights in all_weights:\n weights_path = osp.join(all_weights_path, weights)\n checkpoint = torch.load(weights_path, map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded weights '{}' (epoch {})\"\n .format(weights, checkpoint['epoch']))\n \n epoch = int(re.findall(r'\\d+', weights)[0])\n print(\"Viz. epoch {} embeddings for {}\".format(epoch, obj_name))\n\n embeddings = getCloudEmbedding(model, heightmaps, contactmasks, params, batch_size=100)\n\n # 1: TSNE plot\n gc.collect()\n for key in valid_embeddings:\n if np.all(embeddings[key]) is None:\n print(\"No {} exists\".format(key))\n continue\n if not os.path.exists(os.path.join(savepath, key)):\n os.makedirs(os.path.join(savepath, key))\n print(\"Generating {} TSNE\".format(key))\n # TSNE_init = np.load(os.path.join(savepath, \"tsne.npy\")) \n TSNE = plotTNSE3d(embeddings[key], TSNE_init)\n # if epoch == 0:\n # TSNE_init = TSNE\n # np.save(os.path.join(savepath, \"tsne.npy\"), TSNE)\n u3d.saveTSNEMesh(gelposes, TSNE, os.path.join(savepath, key, \"{}_tsne\".format(epoch)), nPoints=None)\n \n# training MinkLoc with pre-trained Lidar weights \n''' python projects/shape-closures/scripts/MinkLoc3D/training/vizEpochs.py --config ../config/config_tactile.txt \\\n --model_path /home/rpluser/Documents/suddhu/projects/shape-closures/scripts/MinkLoc3D/weights/MinkLocRGB_20220417_1120 --object 035_power_drill '''\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Evaluate each epoch of training as TSNE on objects')\n parser.add_argument('--config', type=str, required=True, help='Path to configuration file')\n parser.add_argument('--model_path', type=str, required=False, help='Path to training epoch weights')\n parser.add_argument('--object', type=str, required=False, default = None, help='Visualize tsne on object models at each iteration')\n\n abspath = osp.abspath(__file__)\n dname = osp.dirname(abspath)\n os.chdir(dname)\n\n args = parser.parse_args()\n print(\"\\n--------------------------------\")\n print('Config path: {}'.format(args.config))\n print('model path: {}'.format(args.model_path))\n print('Object: {}'.format(args.object))\n print(\"--------------------------------\")\n\n params = MinkLocParams(args.config)\n obj = args.object #[obj for obj in args.viz_tsne_objects[0].split()]\n\n # get all weight paths \n all_weights_paths = os.listdir(args.model_path)\n all_weights_paths = sorted(all_weights_paths, key=lambda x: int(x.partition('=')[2].partition('.')[0]))\n for i in range(len(all_weights_paths)):\n all_weights_paths[i] = osp.join(args.model_path, all_weights_paths[i])\n\n # get query and database data \n print(\"Generating query data for eval and violin\")\n evalData = getEvalData(obj_name = obj, params = params, numSamples = 10)\n violinData = getEvalData(obj_name = obj, params = params, numSamples = 5000)\n random_error = getRandomError(violinData[\"gelposes\"], violinData[\"samplePoses\"])\n\n logdir = os.path.join(\"/home/rpluser/Documents/suddhu/runs\", f\"epoch_rmse_{obj}\")\n writer = SummaryWriter(logdir)\n for i, weights_path in enumerate(all_weights_paths):\n testEvalSamples(weights_path = weights_path, data = evalData, valid_embeddings= ['image_embedding'])\n rmse = evalViolinPlot(weights_path = weights_path, data = violinData, valid_embeddings= ['image_embedding'], random_error = random_error, k = 10)\n writer.add_scalars('violin_rmse', rmse, i)\n # evalTSNE(obj_names = vizTSNEObjects, all_weights_path = args.model_path, params = params, valid_embeddings= ['image_embedding'])\n"
] |
[
[
"torch.load",
"numpy.isnan",
"torch.tensor",
"numpy.all",
"numpy.mean",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"torch.device",
"numpy.sum"
]
] |
Intelligent-Computing-Lab-Yale/Energy-Separation-Training
|
[
"9336862a10c915a482d427e8a36367f648e7dd40"
] |
[
"detector_net.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsize_1 = 64\nsize_2 = 64\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n # 3 input channels for CIFAR10, VGG11 calls for 64 output channels from\n # the first conv layer, a batchnorm, then a ReLU\n self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1,bias=True)# 3 8\n # self.norm1 = nn.BatchNorm2d(8)\n self.relu1 = nn.ReLU()\n\n self.mp1 = nn.MaxPool2d(2, stride=2)\n self.conv2 = nn.Conv2d(8, 16, kernel_size=3, padding=1,bias=True)# 8 16\n # self.norm2 = nn.BatchNorm2d(16)\n self.relu2 = nn.ReLU()\n self.mp2 = nn.MaxPool2d(2, stride=2)\n self.conv3 = nn.Conv2d(16, 32, kernel_size=3, padding=1,bias=True)# 16 32\n # self.norm3 = nn.BatchNorm2d(32)\n self.relu3 = nn.ReLU()\n\n self.conv4 = nn.Conv2d(32, 32, kernel_size=3, padding=1,bias=True)# 32 32\n # self.norm4 = nn.BatchNorm2d(32)\n self.relu4 = nn.ReLU()\n #\n self.conv5 = nn.Conv2d(32, 64, kernel_size=3, padding=1,bias=True)# 32 64\n # self.norm5 = nn.BatchNorm2d(64)\n self.relu5 = nn.ReLU()\n #\n # self.conv6 = nn.Conv2d(size_1, 64, kernel_size=3, padding=1)\n # self.norm6 = nn.BatchNorm2d(64)\n # self.relu6 = nn.ReLU()\n\n def forward(self, x0, stage):\n # print(x0.size())\n # self.conv1.weight = torch.nn.Parameter(self.conv1.weight.abs())\n x1 = self.conv1(x0)\n # feature = x1\n # x1,_ = BinActive2.apply(x1, 255)\n if stage == 0:\n\n soi = x1.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x1 = self.norm1(x1)\n # x1,_ = BinActive2.apply(x1, 255)\n x1 = self.relu1(x1)\n # x1,_ = BinActive2.apply(x1, 255)\n # x1 = self.mp1(x1)\n\n x2 = self.conv2(x1)\n # x2,_ = BinActive2.apply(x2, 255)\n if stage == 1:\n soi = x2.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x2 = self.norm2(x2)\n # x2,_ = BinActive2.apply(x2, 255)\n\n # soi = x2.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n\n x2 = self.relu2(x2)\n # x2,_ = BinActive2.apply(x2, 255)\n\n # x2 = self.mp2(x2)\n x3 = self.conv3(x2)\n # x3,_ = BinActive2.apply(x3, 255)\n if stage == 2:\n soi = x3.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x3 = self.norm3(x3)\n # x3,_ = BinActive2.apply(x3, 255)\n\n # soi = x3.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n x3 = self.relu3(x3)\n # x3,_ = BinActive2.apply(x3, 255)\n\n # x3 = self.mp2(x3)\n x4 = self.conv4(x3)\n # x4,_ = BinActive2.apply(x4, 255)\n\n # soi = x4.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x4 = self.norm4(x4)\n # x4,_ = BinActive2.apply(x4, 255)\n\n x4 = self.relu4(x4)\n # x4,_ = BinActive2.apply(x4, 255)\n\n #\n x5 = self.conv5(x4)\n # x5,_ = BinActive2.apply(x5, 255)\n\n # soi = x5.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x5 = self.norm5(x5)\n # x5,_ = BinActive2.apply(x5, 255)\n\n # x5 = self.relu5(x5)\n # x5,_ = BinActive2.apply(x5, 255)\n\n #\n # x6 = self.conv6(x5)\n # # soi = x6.abs().mean(dim=1).mean(dim=1).mean(dim=1)\n # x6 = self.norm6(x6)\n # x6 = self.relu6(x6)\n\n return soi\n\n\n"
] |
[
[
"torch.nn.MaxPool2d",
"torch.nn.ReLU",
"torch.nn.Conv2d"
]
] |
nismod/sim
|
[
"951e9356d95d114225a16ad24c74d531f7528057"
] |
[
"hh.py"
] |
[
"\nimport pandas as pd\n\nimport ukpopulation.snhpdata as SNHPData\nimport ukpopulation.utils #as utils\n\n\nsnhp_e = pd.read_csv(\"data/ons_hh_e_2016-2041.csv\").drop([str(y) for y in range(2001,2014)], axis=1)\nsnhp_w = pd.read_csv(\"data/hh_w_2014-2039.csv\").drop([\"Unnamed: 0\", \"Unnamed: 1\"], axis=1)\n\nsnhp_s = SNHPData.SNHPData(\"./data/cache\").data[ukpopulation.utils.SC]\n\nsnhp_e = snhp_e.groupby(\"CODE\").sum().reset_index().rename({\"CODE\": \"GEOGRAPHY_CODE\"}, axis=1)\nsnhp_e = snhp_e[snhp_e.GEOGRAPHY_CODE.str.startswith(\"E0\")]\n#print(snhp_e)\n\nsnhp_w = snhp_w.groupby(\"GEOGRAPHY_CODE\").sum().reset_index()\n#print(snhp_w)\n\n#print(snhp_s)\n\nsnhp = pd.concat([snhp_e, snhp_w, snhp_s], ignore_index=True, sort=False)\n\nsnhp.to_csv(\"./snhp.csv\")\n"
] |
[
[
"pandas.concat",
"pandas.read_csv"
]
] |
sophon-ai-algo/sophon-inference
|
[
"f923413b76615e265af28fd1dd2b43e5eb303dcd"
] |
[
"modules/auto_runner/external/tensorflow_functions.py"
] |
[
"\"\"\" Copyright 2016-2022 by Bitmain Technologies Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport os\nimport time\nimport tensorflow as tf\nimport numpy as np\nfrom google.protobuf import text_format\n\n\ndef load_graph_from_memory(serialized_graph):\n \"\"\" load a tf graph\n \"\"\"\n graph = tf.Graph()\n with graph.as_default():\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(graph_def, name='')\n return graph\n\ndef node_def_add_node(sss):\n \"\"\" add node{} to a string of an op.\n\n Args:\n sss: original string of an op.\n\n Returns:\n new string with node{} added.\n \"\"\"\n sss = sss.replace('\\n', '\\n\\t')\n sss = \"node {\\n\\t\" + sss\n sss = sss[0:len(sss)-1] + '}\\n'\n return sss\n\ndef node_def_remove_colocations(sss):\n \"\"\" remove colocations in a node_def.\n\n Args:\n sss: original node_def of an op.\n\n Returns:\n new string of node_def.\n \"\"\"\n idx = sss.find('loc:@')\n if idx < 0:\n return sss\n idx1 = sss.find('\"', idx)\n to_remove = sss[idx:idx1]\n sss = sss.replace(to_remove, '')\n return sss\n\ndef if_this_input_can_remove(tfgraph, iop):\n \"\"\" Judge if this op can remove,\n or, to say, an constant value\n \"\"\"\n operator = tfgraph.get_operation_by_name(iop)\n if operator.type == 'Const':\n return True, [iop]\n if operator.type == 'Identity':\n if len(operator.inputs) == 1:\n inputop = operator.inputs[0].op\n if inputop.type == 'Const':\n return True, [iop, inputop.name]\n return False, None\n\ndef node_def_remove_control_inputs(sss):\n \"\"\" remove controlinputs in a node_def.\n\n Args:\n sss: original node_def of an op.\n\n Returns:\n new string of node_def.\n \"\"\"\n idx = sss.find('input: \"^')\n while idx > 0:\n idx_e = sss.find('\"', idx + 10)\n tmpstr = sss[idx:(idx_e+1)]\n sss = sss.replace(tmpstr, '')\n idx = sss.find('input: \"^')\n return sss\n\ndef node_def_remove_inputs(sss):\n \"\"\" remove inputs in a node_def.\n\n Args:\n sss: original node_def of an op.\n\n Returns:\n new string of node_def.\n \"\"\"\n idx = sss.find('input: \"')\n while idx > 0:\n idx_e = sss.find('\"', idx + 9)\n tmpstr = sss[idx:(idx_e+1)]\n sss = sss.replace(tmpstr, '')\n idx = sss.find('input: \"')\n return sss\n\ndef just_write_text(sss, pb_path, pb_name):\n \"\"\" only for debug\n \"\"\"\n tid = sss.find('tensor_content:')\n while tid > 0:\n eid = sss.find('}', tid)\n sss = sss[:tid] + sss[eid:]\n tid = sss.find('tensor_content:')\n with open(os.path.join(pb_path, pb_name+'txt'), 'w+') as fff:\n fff.write(sss)\n\ndef save_str_to_pb(sss, pb_path, pb_name):\n \"\"\" Save node_def string to a model, ends with \".pb\".\n \"\"\"\n #just_write_text(sss, pb_path, pb_name)\n graph_def = tf.GraphDef()\n text_format.Merge(sss, graph_def)\n tf.train.write_graph(graph_def, pb_path, pb_name, as_text=False)\n\ndef infer_tensorflow_graph(graph_path, input_names, input_values, \\\n output_names, warm_loop=0, infer_loop=1, with_flops=False):\n \"\"\" infer a tensorflow graph.\n \"\"\"\n graph = tf.Graph()\n with graph.as_default():\n graph_def = tf.GraphDef()\n with tf.gfile.GFile(graph_path, 'rb') as fid:\n serialized_graph = fid.read()\n graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(graph_def, name='')\n with tf.Session() as sess:\n for _ in range(warm_loop):\n rets = sess.run(output_names, \\\n feed_dict=dict(zip(input_names, input_values)))\n time_1 = time.time()\n for _ in range(infer_loop):\n rets = sess.run(output_names, \\\n feed_dict=dict(zip(input_names, input_values)))\n time_2 = time.time()\n flop_value = None\n if with_flops:\n flops = tf.profiler.profile(graph, \\\n options=tf.profiler.ProfileOptionBuilder.float_operation())\n flop_value = flops.total_float_ops\n return rets, (time_2 - time_1)/infer_loop, flop_value\n\ndef get_all_ops_from_model_path(model_path):\n \"\"\" get all ops and the graph of a tensorflow model.\n \"\"\"\n assert model_path.endswith(\".pb\")\n graph = tf.Graph()\n with graph.as_default():\n graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_path, \"rb\") as fid:\n serialized_graph = fid.read()\n graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(graph_def, name='')\n ops = graph.get_operations()\n return ops, graph\n\ndef get_graph(model_path, device):\n \"\"\" get graph of a tensorflow model\n \"\"\"\n assert model_path.endswith(\".pb\")\n graph = tf.Graph()\n with graph.as_default():\n with tf.device(device):\n graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_path, \"rb\") as fid:\n serialized_graph = fid.read()\n graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(graph_def, name='')\n return graph\n\n\ndef tensorflow_infer_outputs(model, input_dict, output_names):\n \"\"\" infer tensorflow graph and get its result.\n \"\"\"\n if isinstance(model, str):\n #if type(model) == type(str()):\n _, graph = get_all_ops_from_model_path(model)\n else:\n graph = model\n with graph.as_default():\n with tf.Session() as sess:\n ret = sess.run(output_names, input_dict)\n return ret\n\ndef get_tensor_shape_in_graph(graph, start_tensors, \\\n start_shapes, out_tensor_name):\n \"\"\" infer a tensorflow graph, get the shape of the querying tensor.\n \"\"\"\n operator = graph.\\\n get_operation_by_name(out_tensor_name[:out_tensor_name.find(':')])\n if len(operator.outputs) < 1:\n return tuple([-1])\n inputs = []\n for s_tensor in start_tensors:\n inputs.append(graph.get_tensor_by_name(s_tensor))\n values = []\n for s_shape in start_shapes:\n values.append(np.ones(s_shape))\n with graph.as_default():\n with tf.Session() as sess:\n ret = sess.run(out_tensor_name, feed_dict=dict(zip(inputs, values)))\n # it's a tuple\n return ret.shape\n\ndef get_flops(model_path):\n \"\"\" get flops of a model\n\n Args:\n model_path: A string, path of the model.\n\n Returns:\n An integer, flops of this model\n\n \"\"\"\n _, graph = get_all_ops_from_model_path(model_path)\n flops = tf.profiler.profile(graph, \\\n options=tf.profiler.ProfileOptionBuilder.float_operation())\n return flops.total_float_ops\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.device",
"tensorflow.gfile.GFile",
"numpy.ones",
"tensorflow.Session",
"tensorflow.profiler.ProfileOptionBuilder.float_operation",
"tensorflow.GraphDef",
"tensorflow.train.write_graph"
]
] |
Dani-Mora/wide-deep-cnn
|
[
"16b74dd29fc3d97a86e8c65cc542306d59c00a9a"
] |
[
"code/widedeep/ops/variables.py"
] |
[
"\"\"\"\nHelper class to create variables in Tensorflow\n\"\"\"\n\nimport tensorflow as tf\n\nNON_SAVABLE_COL = 'not_saveable'\n\n\ndef variable(name,\n shape,\n dtype,\n initializer,\n collections=[],\n regularizer=None,\n trainable=True):\n \"\"\" Creates or retrieves existing variable to represent trainable weights\n Simplified version of the contrib convolution2d function extended for\n inference\n Args:\n name: Name of the variable\n shape: Shape (list) of the variable to create\n dtype: Type of the variable\n initializer: Initializer to compute.\n collections: Collections where variables should be added\n regularizer: Regularized function for the variable.\n trainable: Whether the value of the variable should be\n subject to training\n Returns\n Variable created/retrieved\n \"\"\"\n # All variables are added to the variable collection\n col_set = build_collections(collections)\n return tf.get_variable(name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n regularizer=regularizer,\n trainable=trainable,\n collections=col_set)\n\n\ndef auxiliar_variable(name,\n shape,\n dtype,\n initializer,\n collections=[],\n regularizer=None):\n \"\"\" Creates or retrieves an existing variable that won't be stored in\n the checkpoints. This variable is not trainable. Parameters are further\n described in variable method\"\"\"\n return variable(name=name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n collections=[NON_SAVABLE_COL] + collections,\n regularizer=regularizer,\n trainable=False)\n\n\ndef savable_variables():\n \"\"\" Returns the list of variables to save \"\"\"\n all = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n exclude = tf.get_collection(NON_SAVABLE_COL)\n excluded_names = [v.name for v in exclude]\n return [v for v in all if v.name not in excluded_names]\n\n\ndef build_collections(collections):\n \"\"\" Builds the input collections, adding the default collection graph\n ops.GraphKeys.VARIABLES and checks that collection names are unique \"\"\"\n inp_cols = [] if collections is None else list(collections)\n cols = [tf.GraphKeys.GLOBAL_VARIABLES] + inp_cols\n return set(cols) # Remove duplicates\n\n\ndef add_variable_summary(value, name):\n \"\"\" Sets summaries for the input variable \"\"\"\n tf.summary.scalar(name=\"%s:fraction_of_zero_values\" % name,\n tensor=tf.nn.zero_fraction(value))\n tf.summary.histogram(name=\"%s:activation\" % name, values=value)\n\n\ndef summarize_gradients(model_name, gradients):\n \"\"\" Adds histograms for gradients and gradient norms of the input\n gradients \"\"\"\n\n def get_prefix(var):\n return model_name + '/' + var.name\n\n for gradient, variable in gradients:\n if gradient is not None:\n tf.summary.histogram(get_prefix(variable) + \"/gradients\", gradient)\n tf.summary.histogram(get_prefix(variable) + \"/gradient_norm\",\n tf.global_norm([gradient]))\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.get_collection",
"tensorflow.nn.zero_fraction",
"tensorflow.global_norm",
"tensorflow.summary.histogram"
]
] |
ceykmc/detectron2
|
[
"0b500b4d7ed11e9728867298f5f168fb34908e2c"
] |
[
"tests/data/test_detection_utils.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport copy\nimport numpy as np\nimport unittest\nimport pycocotools.mask as mask_util\n\nfrom detectron2.data import detection_utils\nfrom detectron2.data import transforms as T\nfrom detectron2.structures import BitMasks, BoxMode\n\n\nclass TestTransformAnnotations(unittest.TestCase):\n def test_transform_simple_annotation(self):\n transforms = T.TransformList([T.HFlipTransform(400)])\n anno = {\n \"bbox\": np.asarray([10, 10, 200, 300]),\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"category_id\": 3,\n \"segmentation\": [[10, 10, 100, 100, 100, 10], [150, 150, 200, 150, 200, 200]],\n }\n\n output = detection_utils.transform_instance_annotations(anno, transforms, (400, 400))\n self.assertTrue(np.allclose(output[\"bbox\"], [200, 10, 390, 300]))\n self.assertEqual(len(output[\"segmentation\"]), len(anno[\"segmentation\"]))\n self.assertTrue(np.allclose(output[\"segmentation\"][0], [390, 10, 300, 100, 300, 10]))\n\n detection_utils.annotations_to_instances([output, output], (400, 400))\n\n def test_flip_keypoints(self):\n transforms = T.TransformList([T.HFlipTransform(400)])\n anno = {\n \"bbox\": np.asarray([10, 10, 200, 300]),\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"keypoints\": np.random.rand(17, 3) * 50 + 15,\n }\n\n output = detection_utils.transform_instance_annotations(\n copy.deepcopy(anno),\n transforms,\n (400, 400),\n keypoint_hflip_indices=detection_utils.create_keypoint_hflip_indices(\n [\"keypoints_coco_2017_train\"]\n ),\n )\n # The first keypoint is nose\n self.assertTrue(np.allclose(output[\"keypoints\"][0, 0], 400 - anno[\"keypoints\"][0, 0]))\n # The last 16 keypoints are 8 left-right pairs\n self.assertTrue(\n np.allclose(\n output[\"keypoints\"][1:, 0].reshape(-1, 2)[:, ::-1],\n 400 - anno[\"keypoints\"][1:, 0].reshape(-1, 2),\n )\n )\n self.assertTrue(\n np.allclose(\n output[\"keypoints\"][1:, 1:].reshape(-1, 2, 2)[:, ::-1, :],\n anno[\"keypoints\"][1:, 1:].reshape(-1, 2, 2),\n )\n )\n\n def test_transform_RLE(self):\n transforms = T.TransformList([T.HFlipTransform(400)])\n mask = np.zeros((300, 400), order=\"F\").astype(\"uint8\")\n mask[:, :200] = 1\n\n anno = {\n \"bbox\": np.asarray([10, 10, 200, 300]),\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"segmentation\": mask_util.encode(mask[:, :, None])[0],\n \"category_id\": 3,\n }\n output = detection_utils.transform_instance_annotations(\n copy.deepcopy(anno), transforms, (300, 400)\n )\n mask = output[\"segmentation\"]\n self.assertTrue((mask[:, 200:] == 1).all())\n self.assertTrue((mask[:, :200] == 0).all())\n\n inst = detection_utils.annotations_to_instances(\n [output, output], (400, 400), mask_format=\"bitmask\"\n )\n self.assertTrue(isinstance(inst.gt_masks, BitMasks))\n\n def test_transform_RLE_resize(self):\n transforms = T.TransformList(\n [T.HFlipTransform(400), T.ScaleTransform(300, 400, 400, 400, \"bilinear\")]\n )\n mask = np.zeros((300, 400), order=\"F\").astype(\"uint8\")\n mask[:, :200] = 1\n\n anno = {\n \"bbox\": np.asarray([10, 10, 200, 300]),\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"segmentation\": mask_util.encode(mask[:, :, None])[0],\n \"category_id\": 3,\n }\n output = detection_utils.transform_instance_annotations(\n copy.deepcopy(anno), transforms, (400, 400)\n )\n\n inst = detection_utils.annotations_to_instances(\n [output, output], (400, 400), mask_format=\"bitmask\"\n )\n self.assertTrue(isinstance(inst.gt_masks, BitMasks))\n\n def test_gen_crop(self):\n instance = {\"bbox\": [10, 10, 100, 100], \"bbox_mode\": BoxMode.XYXY_ABS}\n t = detection_utils.gen_crop_transform_with_instance((10, 10), (150, 150), instance)\n # the box center must fall into the cropped region\n self.assertTrue(t.x0 <= 55 <= t.x0 + t.w)\n\n def test_gen_crop_outside_boxes(self):\n instance = {\"bbox\": [10, 10, 100, 100], \"bbox_mode\": BoxMode.XYXY_ABS}\n with self.assertRaises(AssertionError):\n detection_utils.gen_crop_transform_with_instance((10, 10), (15, 15), instance)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.asarray",
"numpy.random.rand",
"numpy.zeros",
"numpy.allclose"
]
] |
nathanielfernandes/HamoodBot
|
[
"e22b321e0594360fb427080322ed8731b48cec16"
] |
[
"modules/math_functions.py"
] |
[
"#\nimport sys, re\nimport requests\nimport json\nimport io\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sqrt, sin, cos, tan, log\nfrom sympy import symbols, Eq, solve, parse_expr, integrate, diff\nfrom copy import copy\nimport time, math, random\n\nimport signal\nfrom contextlib import contextmanager\n\nimport pylab\n\nfrom utils.helpers import to_async\n\n\ndef flatten(l, condition=lambda e: True, switch=lambda e: e) -> list:\n return [switch(e) for t in l for e in t if condition(e)]\n\n\nCOLORS = (\"b\", \"g\", \"r\", \"c\", \"m\")\nRESTRICTED = (\n \"exit\",\n \"__\",\n \"_\",\n \"import\",\n \"eval\",\n \"exec\",\n \"open\",\n \"file\",\n \"input\",\n \"execfile\",\n \"stdin\",\n \"builtins\",\n \"globals\",\n \"locals\",\n \"try\",\n \"except\",\n \"calloc\",\n \"malloc\",\n \"sleep\",\n \"raise\",\n \"SystemExit\",\n \"quit\",\n)\n\n\nfolder = f\"{os.path.split(os.getcwd())[0]}/{os.path.split(os.getcwd())[1]}/temp\"\n\n\n# Implemented from https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python\n@contextmanager\ndef time_limit(seconds):\n def signal_handler(signum, frame):\n raise TimeoutError(\"Timed Out! Code execution surpassed 1 second!\")\n\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n\nEQF = re.compile(\n r\"(?:(\\)\\()|(\\)[a-zA-Z])[^a-z]|[^a-z]([a-zA-Z]\\()|(\\d\\()|(\\)\\d)|(\\)[a-z])|(\\d[a-zA-Z])|[^a-z]([a-zA-Z]\\d+))\"\n)\n\n\ndef format_eq(eq):\n eq = (\n eq.replace(\" \", \"\")\n .replace(\"\\n\", \"\")\n .replace(\"[\", \"(\")\n .replace(\"]\", \")\")\n .replace(\"^\", \"**\")\n .replace(\"mod\", \"%\")\n )\n for res in RESTRICTED:\n eq = eq.replace(res, \"\")\n\n stuff = EQF.findall(eq)\n to_replace = flatten(stuff, lambda e: e != \"\")\n\n for rep in to_replace:\n eq = eq.replace(rep, f\"{rep[0]}*{rep[-1]}\")\n\n return eq\n\n\ndef graph_eq(equations):\n plt.clf()\n equations = equations[:5]\n\n try:\n with time_limit(2):\n for equation in equations:\n eq = equation\n equation = format_eq(equation)\n\n x = np.array(np.arange(-100, 100, 0.1))\n\n y = eval(\n str(parse_expr(equation)),\n {\n \"sqrt\": sqrt,\n \"sin\": sin,\n \"cos\": cos,\n \"tan\": tan,\n \"log\": log,\n \"x\": x,\n },\n )\n\n # plt.title(title)\n\n plt.grid(alpha=0.5, linestyle=\"solid\")\n plt.axhline(y=0, color=\"k\", linewidth=0.5)\n plt.axvline(x=0, color=\"k\", linewidth=0.5)\n\n plt.plot(\n x,\n y,\n label=f\"y = {equation.replace('**', '^')}\",\n color=COLORS[equations.index(eq)],\n )\n plt.legend()\n buffer = io.BytesIO()\n plt.savefig(buffer, bbox_inches=\"tight\")\n plt.clf()\n buffer.seek(0)\n return buffer\n except Exception as e:\n if isinstance(e, TimeoutError):\n return \"Timed Out! Calculation exceeded 1 second!\"\n return \"Invalid Input\"\n\n\ndef calc_eq(equation):\n equation = format_eq(equation)\n try:\n with time_limit(1):\n solved = eval(\n str(parse_expr(equation)),\n {\"sqrt\": sqrt, \"sin\": sin, \"cos\": cos, \"tan\": tan, \"log\": log},\n )\n except Exception as e:\n if isinstance(e, TimeoutError):\n return \"Timed Out! Calculation exceeded 1 second!\"\n return \"Invalid Input\"\n\n return solved\n\n\ndef solve_eq(equation):\n equation = format_eq(equation)\n solved = []\n\n try:\n with time_limit(1):\n sol = solve(Eq(parse_expr(equation), 0), dict=True)\n for solution in sol:\n for k in solution.keys():\n if \"I\" not in str(solution[k]):\n solution[k] = round(\n eval(\n str(solution[k]),\n {\n \"sqrt\": sqrt,\n \"sin\": sin,\n \"cos\": cos,\n \"tan\": tan,\n \"log\": log,\n },\n ),\n 3,\n )\n solved.append(f\"{k} = {solution[k]}\")\n except Exception as e:\n if isinstance(e, TimeoutError):\n return \"Timed Out! Calculation exceeded 1 second!\"\n return \"Invalid Input\"\n\n return solved\n\n\ndef base_conversion(number, base1, base2):\n try:\n return np.base_repr(int(number, base=base1), base2)\n except ValueError:\n return \"Invalid Input\"\n\n\ndef get_derivative(equation, d):\n equation = format_eq(equation)\n try:\n with time_limit(1):\n for i in range(d):\n equation = diff(equation)\n return str(equation)\n except Exception as e:\n if isinstance(e, TimeoutError):\n return \"Timed Out! Calculation exceeded 1 second!\"\n return \"Invalid Input\"\n\n\n# implemented from https://stackoverflow.com/questions/14110709/creating-images-of-mathematical-expressions-from-tex-using-matplotlib\ndef latex_to_text(formula):\n formula = formula.replace(\"`\", \"\")\n\n if formula[0] != \"$\":\n formula = \"$\" + formula\n if formula[-1] != \"$\":\n formula += \"$\"\n\n try:\n buffer = io.BytesIO()\n formula = r\"{}\".format(formula)\n fig = pylab.figure()\n text = fig.text(0, 0, formula)\n\n # Saving the figure will render the text.\n dpi = 200\n fig.savefig(buffer, dpi=dpi)\n\n # Now we can work with text's bounding box.\n bbox = text.get_window_extent()\n width, height = bbox.size / float(dpi) + 0.005\n # Adjust the figure size so it can hold the entire text.\n fig.set_size_inches((width, height))\n\n # Adjust text's vertical position.\n dy = (bbox.ymin / float(dpi)) / height\n text.set_position((0, -dy))\n\n buffer = io.BytesIO()\n # Save the adjusted text.\n fig.savefig(buffer, dpi=dpi)\n\n buffer.seek(0)\n plt.clf()\n plt.close()\n return buffer\n\n except Exception as e:\n return e\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.axvline",
"numpy.arange",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.close",
"matplotlib.pyplot.grid"
]
] |
VITA-Group/Large_Scale_GCN_Benchmarking
|
[
"d4c85a899a22b5a982ae437eac037f3629454510"
] |
[
"Precomputing/base.py"
] |
[
"import torch\nimport torch.nn.functional as F\nfrom torch_geometric.transforms import SIGN\nfrom torch.utils.data import DataLoader\n\nimport torch\nfrom torch_sparse import SparseTensor\n\nfrom sklearn.metrics import f1_score\n\nfrom utils import get_memory_usage, compute_tensor_bytes, MB, GB\nimport time\nimport json\n\nclass PrecomputingBase(torch.nn.Module):\n def __init__(self, args, data, train_idx):\n super(PrecomputingBase, self).__init__()\n\n self.num_layers = args.num_layers\n self.dim_hidden = args.dim_hidden\n self.num_classes = args.num_classes\n self.num_feats = args.num_feats\n self.batch_size = args.batch_size\n self.dropout = args.dropout\n self.norm = args.norm\n self.multi_label = args.multi_label\n self.debug_mem_speed = args.debug_mem_speed\n self.precompute(data)\n self.saved_args = vars(args)\n\n def precompute(self, data):\n print('precomputing features, may take a while')\n data = SIGN(self.num_layers)(data)\n self.xs = [data.x] + [data[f'x{i}'] for i in range(1, self.num_layers + 1)]\n\n def forward(self, xs):\n raise NotImplementedError\n\n def mem_speed_bench(self, input_dict):\n split_idx = input_dict['split_masks']\n device = input_dict['device']\n optimizer = input_dict['optimizer']\n loss_op = input_dict['loss_op']\n torch.cuda.empty_cache()\n model_opt_usage = get_memory_usage(0, False)\n usage_dict = {'model_opt_usage': model_opt_usage, 'data_mem': [], 'act_mem': [], 'peak_mem': [], 'duration': []}\n print('model + optimizer only, mem: %.2f MB' % (usage_dict['model_opt_usage'] / MB))\n xs_train = torch.cat([x[split_idx['train']] for x in self.xs], -1)\n y_train = input_dict['y'][split_idx['train']]\n dim_feat = self.xs[0].shape[-1]\n train_set = torch.utils.data.TensorDataset(xs_train, y_train)\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=self.batch_size, \n num_workers=8, pin_memory=True)\n epoch_start_time = time.time()\n torch.cuda.synchronize()\n for xs, y in train_loader:\n iter_start_time = time.time()\n torch.cuda.synchronize()\n xs = [x.to(device) for x in torch.split(xs, dim_feat, -1)]\n y = y.to(device)\n init_mem = get_memory_usage(0, False)\n data_mem = init_mem - usage_dict['model_opt_usage']\n usage_dict['data_mem'].append(data_mem)\n print('data mem: %.2f MB' % (data_mem / MB))\n optimizer.zero_grad()\n out = self.forward(xs)\n if isinstance(loss_op, torch.nn.NLLLoss):\n out = F.log_softmax(out, dim=-1)\n elif isinstance(loss_op, torch.nn.BCEWithLogitsLoss):\n y = y.float()\n loss = loss_op(out, y)\n loss = loss.mean()\n before_backward = get_memory_usage(0, False)\n act_mem = before_backward - init_mem - compute_tensor_bytes([loss, out])\n usage_dict['act_mem'].append(act_mem)\n print('act mem: %.2f MB' % (act_mem / MB))\n loss.backward()\n optimizer.step()\n torch.cuda.synchronize()\n iter_end_time = time.time()\n duration = iter_end_time - iter_start_time\n print('duration: %.4f sec' % duration)\n usage_dict['duration'].append(duration)\n peak_usage = torch.cuda.max_memory_allocated(0)\n usage_dict['peak_mem'].append(peak_usage)\n print(f'peak mem usage: {peak_usage / MB}')\n with open('./%s_%s_mem_speed_log.json' % (self.saved_args['dataset'], self.__class__.__name__), 'w') as fp:\n info_dict = {**self.saved_args, **usage_dict}\n del info_dict['device']\n json.dump(info_dict, fp)\n exit()\n\n def train_net(self, input_dict):\n split_idx = input_dict['split_masks']\n device = input_dict['device']\n optimizer = input_dict['optimizer']\n loss_op = input_dict['loss_op']\n\n xs_train = torch.cat([x[split_idx['train']] for x in self.xs], -1)\n y_train = input_dict['y'][split_idx['train']]\n dim_feat = self.xs[0].shape[-1]\n\n train_set = torch.utils.data.TensorDataset(xs_train, y_train)\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=self.batch_size, \n num_workers=8, pin_memory=True)\n\n total_correct = 0\n y_true, y_preds = [], []\n\n for xs, y in train_loader:\n\n xs = [x.to(device) for x in torch.split(xs, dim_feat, -1)]\n y = y.to(device)\n\n optimizer.zero_grad()\n out = self.forward(xs)\n if isinstance(loss_op, torch.nn.NLLLoss):\n out = F.log_softmax(out, dim=-1)\n elif isinstance(loss_op, torch.nn.BCEWithLogitsLoss):\n y = y.float()\n loss = loss_op(out, y)\n\n loss = loss.mean()\n loss.backward()\n optimizer.step()\n\n if not self.multi_label:\n y_preds.append(out.argmax(dim=-1).detach().cpu())\n y_true.append(y.detach().cpu())\n # total_correct += int(out.argmax(dim=-1).eq(y).sum())\n else:\n y_preds.append(out.detach().cpu())\n y_true.append(y.detach().cpu())\n # train_acc = f1_score(y_true[self.split_masks['train']],\n # pred[self.split_masks['train']], average='micro') \\\n # if pred[self.split_masks['train']].sum() > 0 else 0\n # total_correct += int(out.eq(y).sum())\n\n y_true = torch.cat(y_true, 0)\n y_preds = torch.cat(y_preds, 0)\n if not self.multi_label:\n total_correct = y_preds.eq(y_true).sum().item()\n train_acc = float(total_correct / y_train.size(0))\n else:\n y_preds = (y_preds > 0).float().numpy()\n train_acc = f1_score(y_true, y_preds, average='micro')\n\n return float(loss.item()), train_acc\n\n @torch.no_grad()\n def inference(self, input_dict):\n x_all = input_dict['x']\n device = input_dict['device']\n y_preds = []\n loader = DataLoader(range(x_all.size(0)), batch_size=100000)\n for perm in loader:\n y_pred = self.forward([x[perm].to(device) for x in self.xs])\n y_preds.append(y_pred.cpu())\n y_preds = torch.cat(y_preds, dim=0)\n\n return y_preds\n"
] |
[
[
"torch.cuda.synchronize",
"torch.nn.functional.log_softmax",
"torch.cat",
"torch.utils.data.TensorDataset",
"torch.utils.data.DataLoader",
"torch.cuda.empty_cache",
"torch.cuda.max_memory_allocated",
"torch.no_grad",
"torch.split",
"sklearn.metrics.f1_score"
]
] |
Defra-Data-Science-Centre-of-Excellence/sdg-build
|
[
"716a7597e5cb7de248915b21fa1a9e4a5cd1e0e0"
] |
[
"sdg/DisaggregationReportService.py"
] |
[
"import os\nimport sdg\nimport pandas as pd\nfrom slugify import slugify\nfrom sdg.Loggable import Loggable\n\nclass DisaggregationReportService(Loggable):\n \"\"\"Report generation to document disaggregations in data.\"\"\"\n\n\n def __init__(self, outputs, languages=None, translation_helper=None,\n indicator_url=None, extra_disaggregations=None, logging=None):\n \"\"\"Constructor for the DisaggregationReportService class.\n\n Parameters\n ----------\n outputs : list\n Required list of objects inheriting from OutputBase. Each output\n will receive its own documentation page (or pages).\n languages : list\n Optional list of language codes. If languages are provided, these\n languages will display as translations in additional columns.\n Defaults to [].\n translation_helper : TranslationHelper\n Instance of TranslationHelper class to perform translations.\n indicator_url : string\n Optional URL pattern to use for linking to indicators. If provided,\n the \"[id]\" will be replaced with the indicator id (dash-delimited).\n For example, \"https://example.com/[id].html\" will be replaced with\n \"https://example.com/4-1-1.html\".\n extra_disaggregations : list\n Optional list of columns to include, which would not otherwise be\n included. Common choices are are units of measurement and series,\n which some users may prefer to see in the report.\n \"\"\"\n Loggable.__init__(self, logging=logging)\n self.outputs = outputs\n self.indicator_url = indicator_url\n self.slugs = []\n self.languages = [] if languages is None else languages\n self.translation_helper = translation_helper\n self.extra_disaggregations = [] if extra_disaggregations is None else extra_disaggregations\n self.disaggregation_store = None\n\n\n def get_disaggregation_store(self):\n \"\"\"Analyzes the data in and compiles information about disaggregations.\n\n Returns\n -------\n dict\n Dict with disaggregation names keyed to dicts containing:\n - values (dict of values keyed to number of instances)\n - indicators (dict with indicator ids as keys)\n - filename (string, suitable for writing to disk)\n - name (string, the name of the disaggregation)\n \"\"\"\n if self.disaggregation_store is not None:\n return self.disaggregation_store\n\n all_disaggregations = {}\n indicators = self.get_all_indicators()\n for indicator_id in indicators:\n if not indicators[indicator_id].is_statistical():\n continue\n if not indicators[indicator_id].is_complete():\n continue\n non_disaggregation_columns = indicators[indicator_id].options.get_non_disaggregation_columns()\n non_disaggregation_columns = [col for col in non_disaggregation_columns if col not in self.extra_disaggregations]\n for series in indicators[indicator_id].get_all_series():\n disaggregations = series.get_disaggregations()\n for disaggregation in disaggregations:\n if disaggregation in non_disaggregation_columns:\n continue\n if disaggregation not in all_disaggregations:\n all_disaggregations[disaggregation] = {\n 'values': {},\n 'indicators': {},\n 'filename': self.create_filename(disaggregation),\n 'name': disaggregation,\n }\n value = disaggregations[disaggregation]\n if pd.isna(value) or value == '':\n continue\n if value not in all_disaggregations[disaggregation]['values']:\n all_disaggregations[disaggregation]['values'][value] = {\n 'instances': 0,\n 'indicators': {},\n 'filename': self.create_filename(value, prefix='disaggregation-value--'),\n 'name': value,\n 'disaggregation': disaggregation,\n }\n all_disaggregations[disaggregation]['values'][value]['instances'] += 1\n if indicator_id not in all_disaggregations[disaggregation]['values'][value]['indicators']:\n all_disaggregations[disaggregation]['values'][value]['indicators'][indicator_id] = 0\n all_disaggregations[disaggregation]['values'][value]['indicators'][indicator_id] += 1\n\n all_disaggregations[disaggregation]['indicators'][indicator_id] = True\n self.disaggregation_store = all_disaggregations\n return self.disaggregation_store\n\n\n def get_all_indicators(self):\n indicators = {}\n for output in self.outputs:\n for indicator_id in output.get_indicator_ids():\n indicator = output.get_indicator_by_id(indicator_id)\n if not indicator.is_standalone():\n indicators[indicator_id] = indicator\n return indicators\n\n\n def create_filename(self, title, prefix='disaggregation--'):\n \"\"\"Convert a title into a unique filename.\n\n Parameters\n ----------\n title : string\n A title representing the output\n\n Returns\n -------\n string\n The title converted into a unique *.html filename\n \"\"\"\n slug = prefix + slugify(str(title))\n if slug in self.slugs:\n slug = slug + '_'\n if len(slug) > 100:\n slug = slug[0:100]\n self.slugs.append(slug)\n return slug + '.html'\n\n\n def group_disaggregation_store_by_indicator(self):\n store = self.get_disaggregation_store()\n grouped = {}\n for disaggregation in store:\n for indicator in store[disaggregation]['indicators']:\n if indicator not in grouped:\n grouped[indicator] = {}\n grouped[indicator][disaggregation] = store[disaggregation]\n return grouped\n\n\n def get_disaggregation_link(self, disaggregation_info):\n return '<a href=\"{}\">{}</a>'.format(\n disaggregation_info['filename'],\n disaggregation_info['name'],\n )\n\n\n def get_disaggregation_value_link(self, disaggregation_value_info):\n return '<a href=\"{}\">{}</a>'.format(\n disaggregation_value_info['filename'],\n disaggregation_value_info['name'],\n )\n\n\n def translate(self, text, language, group=None):\n if self.translation_helper is None:\n return text\n else:\n default_group = 'data' if group is None else [group, 'data']\n return self.translation_helper.translate(text, language, default_group)\n\n\n def get_disaggregations_dataframe(self):\n store = self.get_disaggregation_store()\n rows = []\n for disaggregation in store:\n\n num_indicators = len(store[disaggregation]['indicators'].keys())\n num_values = len(store[disaggregation]['values'].keys())\n\n # In some cases, a disaggregation may exist as a column but will have\n # no values. In these cases, we skip it.\n if num_values == 0:\n continue\n\n row = {\n 'Disaggregation': self.get_disaggregation_link(store[disaggregation]),\n 'Number of indicators': num_indicators,\n 'Number of values': num_values,\n }\n for language in self.get_languages():\n row[language] = self.translate(disaggregation, language, disaggregation)\n rows.append(row)\n\n columns = ['Disaggregation']\n columns.extend(self.get_languages())\n columns.extend(['Number of indicators', 'Number of values'])\n\n df = pd.DataFrame(rows, columns=columns)\n if not df.empty:\n df.sort_values(by=['Disaggregation'], inplace=True)\n return df\n\n\n def get_languages(self):\n return self.languages\n\n\n def get_indicators_dataframe(self):\n grouped = self.group_disaggregation_store_by_indicator()\n rows = []\n for indicator in grouped:\n disaggregation_links = [self.get_disaggregation_link(disaggregation) for disaggregation in grouped[indicator].values()]\n if len(disaggregation_links) == 0:\n continue\n rows.append({\n 'Indicator': self.get_indicator_link(indicator),\n 'Disaggregations': ', '.join(disaggregation_links),\n 'Number of disaggregations': len(disaggregation_links),\n })\n df = pd.DataFrame(rows, columns=['Indicator', 'Disaggregations', 'Number of disaggregations'])\n if not df.empty:\n df.sort_values(by=['Indicator'], inplace=True)\n return df\n\n\n def get_disaggregation_dataframe(self, info):\n rows = []\n for value in info['values']:\n row = {\n 'Value': self.get_disaggregation_value_link(info['values'][value]),\n 'Disaggregation combinations using this value': info['values'][value]['instances'],\n 'Number of indicators': len(info['values'][value]['indicators'].keys()),\n }\n for language in self.get_languages():\n row[language] = self.translate(value, language, info['name'])\n rows.append(row)\n\n columns = ['Value']\n columns.extend(self.get_languages())\n columns.extend(['Disaggregation combinations using this value', 'Number of indicators'])\n\n df = pd.DataFrame(rows, columns=columns)\n if not df.empty:\n df.sort_values(by=['Value'], inplace=True)\n return df\n\n\n def get_disaggregation_indicator_dataframe(self, info):\n rows = []\n for indicator_id in info['indicators']:\n rows.append({\n 'Indicator': self.get_indicator_link(indicator_id)\n })\n df = pd.DataFrame(rows)\n if not df.empty:\n df.sort_values(by=['Indicator'], inplace=True)\n return df\n\n\n def get_disaggregation_value_dataframe(self, info):\n rows = []\n for indicator_id in info['indicators']:\n rows.append({\n 'Indicator': self.get_indicator_link(indicator_id),\n 'Disaggregation combinations using this value': info['indicators'][indicator_id]\n })\n df = pd.DataFrame(rows, columns=['Indicator', 'Disaggregation combinations using this value'])\n if not df.empty:\n df.sort_values(by=['Indicator'], inplace=True)\n return df\n\n\n def get_disaggregation_report_template(self):\n return \"\"\"\n <div role=\"navigation\" aria-describedby=\"contents-heading\">\n <h2 id=\"contents-heading\">On this page</h2>\n <ul>\n <li><a href=\"#by-disaggregation\">By disaggregation</a></li>\n <li><a href=\"#by-indicator\">By indicator</a></li>\n </ul>\n </div>\n <div>\n <h2 id=\"by-disaggregation\" tabindex=\"-1\">By disaggregation</h2>\n {disaggregation_download}\n {disaggregation_table}\n </div>\n <div>\n <h2 id=\"by-indicator\" tabindex=\"-1\">By indicator</h2>\n {indicator_download}\n {indicator_table}\n </div>\n \"\"\"\n\n\n def get_disaggregation_detail_template(self):\n return \"\"\"\n <div role=\"navigation\" aria-describedby=\"contents-heading\">\n <h2 id=\"contents-heading\">On this page</h2>\n <ul>\n <li><a href=\"#values-used\">Values used in disaggregation</a></li>\n <li><a href=\"#indicators-using\">Indicators using disaggregation</a></li>\n </ul>\n </div>\n <div>\n <h2 id=\"values-used\" tabindex=\"-1\">Values used in disaggregation</h2>\n {values_download}\n {values_table}\n </div>\n <div>\n <h2 id=\"indicators-using\" tabindex=\"-1\">Indicators using disaggregation</h2>\n {indicators_download}\n {indicators_table}\n </div>\n \"\"\"\n\n\n def get_disaggregation_value_detail_template(self):\n return \"\"\"\n <div>\n {download}\n {table}\n </div>\n \"\"\"\n\n\n def get_indicator_link(self, indicator_id):\n indicator_label = '#' + indicator_id\n if self.indicator_url is None:\n return indicator_label\n link = '<a href=\"{href}\">{label}</a>'\n href = self.indicator_url.replace('[id]', indicator_id)\n return link.format(href=href, label=indicator_label)\n\n\n def remove_links_from_dataframe(self, df):\n return df.replace('<[^<]+?>', '', regex=True)\n"
] |
[
[
"pandas.isna",
"pandas.DataFrame"
]
] |
Alibaba-Gemini-Lab/tf-encrypted
|
[
"bf381b949c8860fbd97876e8275fdbc55987effe"
] |
[
"tf_encrypted/tensor/native.py"
] |
[
"\"\"\"Native tensors and their factory.\n\nThese use TensorFlow's native dtypes tf.int32 and tf.int64 for the given float\nencoding being used (fixed-point, etc.).\"\"\"\nfrom __future__ import absolute_import\n\nimport abc\nimport math\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ..operations import secure_random\nfrom ..operations import aby3_fixed_point as aby3_fp\nfrom .factory import AbstractConstant\nfrom .factory import AbstractFactory\nfrom .factory import AbstractPlaceholder\nfrom .factory import AbstractTensor\nfrom .factory import AbstractVariable\nfrom .helpers import inverse\nfrom .shared import binarize\nfrom .shared import conv2d\nfrom .shared import im2col\n\n\ndef native_factory(\n NATIVE_TYPE, EXPLICIT_MODULUS=None,\n): # pylint: disable=invalid-name\n \"\"\"Constructs the native tensor Factory.\"\"\"\n\n class Factory(AbstractFactory):\n \"\"\"Native tensor factory.\"\"\"\n\n def tensor(self, value):\n\n if isinstance(value, tf.Tensor):\n if value.dtype is not self.native_type:\n value = tf.cast(value, dtype=self.native_type)\n return DenseTensor(value)\n\n if isinstance(value, np.ndarray):\n value = tf.convert_to_tensor(value, dtype=self.native_type)\n return DenseTensor(value)\n\n raise TypeError(\"Don't know how to handle {}\".format(type(value)))\n\n def constant(self, value):\n\n if isinstance(value, np.ndarray):\n value = tf.constant(value, dtype=self.native_type)\n return Constant(value)\n\n raise TypeError(\"Don't know how to handle {}\".format(type(value)))\n\n def variable(self, initial_value):\n\n if isinstance(initial_value, (tf.Tensor, np.ndarray)):\n return Variable(initial_value)\n\n if isinstance(initial_value, Tensor):\n return Variable(initial_value.value)\n\n msg = \"Don't know how to handle {}\"\n raise TypeError(msg.format(type(initial_value)))\n\n def placeholder(self, shape):\n return Placeholder(shape)\n\n @property\n def min(self):\n if EXPLICIT_MODULUS is not None:\n return 0\n return NATIVE_TYPE.min\n\n @property\n def max(self):\n if EXPLICIT_MODULUS is not None:\n return EXPLICIT_MODULUS\n return NATIVE_TYPE.max\n\n @property\n def modulus(self) -> int:\n if EXPLICIT_MODULUS is not None:\n return EXPLICIT_MODULUS\n return NATIVE_TYPE.max - NATIVE_TYPE.min + 1\n\n @property\n def native_type(self):\n return NATIVE_TYPE\n\n @property\n def nbits(self):\n return NATIVE_TYPE.size * 8\n\n def sample_uniform(\n self, shape, minval: Optional[int] = None, maxval: Optional[int] = None\n ):\n minval = self.min if minval is None else minval\n # TODO(Morten) believe this should be native_type.max+1\n maxval = self.max if maxval is None else maxval\n\n if secure_random.supports_seeded_randomness():\n seed = secure_random.secure_seed()\n return UniformTensor(\n shape=shape, seed=seed, minval=minval, maxval=maxval\n )\n\n if secure_random.supports_secure_randomness():\n sampler = secure_random.random_uniform\n else:\n sampler = tf.random_uniform\n value = sampler(\n shape=shape, minval=minval, maxval=maxval, dtype=NATIVE_TYPE\n )\n return DenseTensor(value)\n\n def sample_seeded_uniform(\n self,\n shape,\n seed,\n minval: Optional[int] = None,\n maxval: Optional[int] = None,\n ):\n \"\"\"Seeded sample of a random tensor.\n\n Arguments:\n shape (tuple of ints), shape of the tensor to sample\n seed (int), seed for the sampler to use\n minval (int), the a in the interval [a,b]\n maxval (int), the b in the interval [a,b]\n\n Returns a tensor of shape `shape` drawn from a uniform distribution over\n the interval [minval,maxval].\n \"\"\"\n minval = self.min if minval is None else minval\n maxval = self.max if maxval is None else maxval\n\n if secure_random.supports_seeded_randomness():\n # Don't use UniformTensor for lazy sampling here, because the `seed`\n # might be something (e.g., key) we want to protect, and we cannot\n # send it to another party\n value = secure_random.seeded_random_uniform(\n shape=shape,\n dtype=NATIVE_TYPE,\n minval=minval,\n maxval=maxval,\n seed=seed,\n )\n return DenseTensor(value)\n\n raise NotImplementedError(\n \"Secure seeded randomness implementation is not available.\"\n )\n\n def sample_bounded(self, shape, bitlength: int):\n maxval = 2 ** bitlength\n assert maxval <= self.max\n\n if secure_random.supports_seeded_randomness():\n seed = secure_random.secure_seed()\n return UniformTensor(shape=shape, seed=seed, minval=0, maxval=maxval)\n\n if secure_random.supports_secure_randomness():\n sampler = secure_random.random_uniform\n else:\n sampler = tf.random_uniform\n value = sampler(shape=shape, minval=0, maxval=maxval, dtype=NATIVE_TYPE)\n return DenseTensor(value)\n\n def sample_bits(self, shape):\n return self.sample_bounded(shape, bitlength=1)\n\n def stack(self, xs: list, axis: int = 0):\n assert all(isinstance(x, Tensor) for x in xs)\n value = tf.stack([x.value for x in xs], axis=axis)\n return DenseTensor(value)\n\n def concat(self, xs: list, axis: int):\n assert all(isinstance(x, Tensor) for x in xs)\n value = tf.concat([x.value for x in xs], axis=axis)\n return DenseTensor(value)\n\n def where(self, condition, x, y, v2=False):\n if not isinstance(condition, tf.Tensor):\n msg = \"Don't know how to handle `condition` of type {}\"\n raise TypeError(msg.format(type(condition)))\n if not v2:\n value = tf.where(condition, x.value, y.value)\n else:\n value = tf.compat.v2.where(condition, x.value, y.value)\n return DenseTensor(value)\n\n FACTORY = Factory() # pylint: disable=invalid-name\n\n def _lift(x, y) -> Tuple[\"Tensor\", \"Tensor\"]:\n\n if isinstance(x, Tensor) and isinstance(y, Tensor):\n return x, y\n\n if isinstance(x, Tensor):\n\n if isinstance(y, int):\n return x, x.factory.tensor(np.array([y]))\n\n if isinstance(y, Tensor):\n\n if isinstance(x, int):\n return y.factory.tensor(np.array([x])), y\n\n raise TypeError(\"Don't know how to lift {} {}\".format(type(x), type(y)))\n\n class Tensor(AbstractTensor):\n \"\"\"Base class for other native tensor classes.\"\"\"\n\n @property\n @abc.abstractproperty\n def value(self):\n pass\n\n @property\n @abc.abstractproperty\n def shape(self):\n pass\n\n def identity(self):\n value = tf.identity(self.value)\n return DenseTensor(value)\n\n def to_native(self) -> tf.Tensor:\n return self.value\n\n def bits(self, factory=None) -> AbstractTensor:\n factory = factory or FACTORY\n if EXPLICIT_MODULUS is None:\n return factory.tensor(binarize(self.value))\n bitsize = bitsize = math.ceil(math.log2(EXPLICIT_MODULUS))\n return factory.tensor(binarize(self.value % EXPLICIT_MODULUS, bitsize))\n\n def __repr__(self) -> str:\n return \"{}(shape={})\".format(type(self), self.shape)\n\n @property\n def factory(self):\n return FACTORY\n\n def __add__(self, other):\n x, y = _lift(self, other)\n return x.add(y)\n\n def __radd__(self, other):\n x, y = _lift(self, other)\n return y.add(x)\n\n def __sub__(self, other):\n x, y = _lift(self, other)\n return x.sub(y)\n\n def __rsub__(self, other):\n x, y = _lift(self, other)\n return y.sub(x)\n\n def __mul__(self, other):\n x, y = _lift(self, other)\n return x.mul(y)\n\n def __rmul__(self, other):\n x, y = _lift(self, other)\n return x.mul(y)\n\n def __mod__(self, k: int):\n return self.mod(k)\n\n def __neg__(self):\n return self.mul(-1)\n\n def __getitem__(self, slc):\n return DenseTensor(self.value[slc])\n\n def add(self, other):\n x, y = _lift(self, other)\n value = x.value + y.value\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def sub(self, other):\n x, y = _lift(self, other)\n value = x.value - y.value\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def mul(self, other):\n x, y = _lift(self, other)\n value = x.value * y.value\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def matmul(self, other):\n x, y = _lift(self, other)\n value = tf.matmul(x.value, y.value)\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def bit_reverse(self):\n assert(self.factory.nbits == 64, \"bit_reverse works for native-64 only\")\n value = aby3_fp.i64_bit_reverse(self.value)\n return DenseTensor(value)\n\n def bit_gather(self, even: bool):\n assert(self.factory.nbits == 64, \"bit_gather works for native-64 only\")\n value = aby3_fp.i64_bit_gather(self.value, even)\n return DenseTensor(value)\n\n def xor_indices(self):\n assert(self.factory.nbits == 64, \"xor_indices works for native-64 only\")\n value = aby3_fp.i64_xor_indices(self.value)\n return DenseTensor(value)\n\n def im2col(self, h_filter, w_filter, padding, stride):\n i2c = im2col(self.value, h_filter, w_filter, padding, stride)\n return DenseTensor(i2c)\n\n def conv2d(self, other, stride: int, padding: str = \"SAME\"):\n if EXPLICIT_MODULUS is not None:\n # TODO(Morten) any good reason this wasn't implemented for PrimeTensor?\n raise NotImplementedError()\n x, y = _lift(self, other)\n return conv2d(x, y, stride, padding)\n\n def batch_to_space_nd(self, block_shape, crops):\n value = tf.batch_to_space_nd(self.value, block_shape, crops)\n return DenseTensor(value)\n\n def space_to_batch_nd(self, block_shape, paddings):\n value = tf.space_to_batch_nd(self.value, block_shape, paddings)\n return DenseTensor(value)\n\n def mod(self, k: int):\n value = self.value % k\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def transpose(self, perm):\n return DenseTensor(tf.transpose(self.value, perm))\n\n def strided_slice(self, args, kwargs):\n return DenseTensor(tf.strided_slice(self.value, *args, **kwargs))\n\n def gather(self, indices: list, axis: int = 0):\n return DenseTensor(tf.gather(self.value, indices, axis=axis))\n\n def split(self, num_split: Union[int, list], axis: int = 0):\n values = tf.split(self.value, num_split, axis=axis)\n return [DenseTensor(value) for value in values]\n\n def reshape(self, axes: Union[tf.Tensor, List[int]]):\n return DenseTensor(tf.reshape(self.value, axes))\n\n def negative(self):\n value = tf.negative(self.value)\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def reduce_sum(self, axis, keepdims=None):\n value = tf.reduce_sum(self.value, axis, keepdims)\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def cumsum(self, axis, exclusive, reverse):\n value = tf.cumsum(\n self.value, axis=axis, exclusive=exclusive, reverse=reverse\n )\n if EXPLICIT_MODULUS is not None:\n value %= EXPLICIT_MODULUS\n return DenseTensor(value)\n\n def equal_zero(self, factory=None):\n factory = factory or FACTORY\n return factory.tensor(\n tf.cast(tf.equal(self.value, 0), dtype=factory.native_type)\n )\n\n def equal(self, other, factory=None):\n x, y = _lift(self, other)\n factory = factory or FACTORY\n return factory.tensor(\n tf.cast(tf.equal(x.value, y.value), dtype=factory.native_type)\n )\n\n def truncate(self, amount, base=2):\n if base == 2:\n return self.right_shift(amount)\n factor = base ** amount\n factor_inverse = inverse(factor, self.factory.modulus)\n return (self - (self % factor)) * factor_inverse\n\n def right_shift(self, bitlength):\n return DenseTensor(tf.bitwise.right_shift(self.value, bitlength))\n\n def expand_dims(self, axis: Optional[int] = None):\n return DenseTensor(tf.expand_dims(self.value, axis))\n\n def squeeze(self, axis: Optional[List[int]] = None):\n return DenseTensor(tf.squeeze(self.value, axis=axis))\n\n def cast(self, factory):\n return factory.tensor(self.value)\n\n def __or__(self, other):\n return self.bitwise_or(other)\n\n def bitwise_or(self, other):\n x, y = _lift(self, other)\n value = tf.bitwise.bitwise_or(x.value, y.value)\n return DenseTensor(value)\n\n def __xor__(self, other):\n return self.bitwise_xor(other)\n\n def bitwise_xor(self, other):\n x, y = _lift(self, other)\n value = tf.bitwise.bitwise_xor(x.value, y.value)\n return DenseTensor(value)\n\n def __and__(self, other):\n return self.bitwise_and(other)\n\n def bitwise_and(self, other):\n x, y = _lift(self, other)\n value = tf.bitwise.bitwise_and(x.value, y.value)\n return DenseTensor(value)\n\n def __invert__(self):\n return self.invert()\n\n def invert(self):\n value = tf.bitwise.invert(self.value)\n return DenseTensor(value)\n\n def __lshift__(self, bitlength):\n return self.left_shift(bitlength)\n\n def left_shift(self, bitlength):\n return DenseTensor(tf.bitwise.left_shift(self.value, bitlength))\n\n def __rshift__(self, bitlength):\n \"\"\"\n Arithmetic shift.\n Please refer to `self.logical_rshift` for a logical right shift.\n \"\"\"\n return self.right_shift(bitlength)\n\n def logical_rshift(self, bitlength):\n \"\"\"Computes a bitshift to the right.\"\"\"\n # There is some bug in TF when casting from int to uint: the uint result\n # becomes 0 so the following code does not work.\n # Bug report: https://github.com/tensorflow/tensorflow/issues/30215\n #\n # cast_map = {tf.int8: tf.uint8, tf.int16: tf.uint16,\n # tf.int32: tf.uint32, tf.int64: tf.uint64}\n # x = tf.bitwise.right_shift(\n # tf.cast(self.value, dtype=cast_map[NATIVE_TYPE]), bitlength)\n # x = tf.cast(x, NATIVE_TYPE)\n #\n # Instead, we have to do the following slightly more sophisticated stuff.\n if bitlength < 0:\n raise ValueError(\"Unsupported shift steps.\")\n if bitlength == 0:\n return self\n total = NATIVE_TYPE.size * 8\n mask = ~((-1) << (total - bitlength))\n x = tf.bitwise.right_shift(self.value, bitlength)\n x = tf.bitwise.bitwise_and(x, mask)\n return DenseTensor(x)\n\n class DenseTensor(Tensor):\n \"\"\"Public native Tensor class.\"\"\"\n\n def __init__(self, value):\n self._value = value\n\n @property\n def shape(self):\n return self._value.shape\n\n @property\n def value(self):\n return self._value\n\n @property\n def support(self):\n return [self._value]\n\n class UniformTensor(Tensor):\n \"\"\"Class representing a uniform-random, lazily sampled tensor.\n\n Lazy sampling optimizes communication by sending seeds in place of\n fully-expanded tensors.\"\"\"\n\n def __init__(self, shape, seed, minval, maxval):\n self._seed = seed\n self._shape = shape\n self._minval = minval\n self._maxval = maxval\n\n @property\n def shape(self):\n return self._shape\n\n @property\n def value(self):\n with tf.name_scope(\"expand-seed\"):\n return secure_random.seeded_random_uniform(\n shape=self._shape,\n dtype=NATIVE_TYPE,\n minval=self._minval,\n maxval=self._maxval,\n seed=self._seed,\n )\n\n @property\n def support(self):\n return [self._seed]\n\n class Constant(DenseTensor, AbstractConstant):\n \"\"\"Native Constant class.\"\"\"\n\n def __init__(self, constant: tf.Tensor) -> None:\n assert isinstance(constant, tf.Tensor)\n super(Constant, self).__init__(constant)\n\n def __repr__(self) -> str:\n return \"Constant(shape={})\".format(self.shape)\n\n class Placeholder(DenseTensor, AbstractPlaceholder):\n \"\"\"Native Placeholder class.\"\"\"\n\n def __init__(self, shape: List[int]) -> None:\n self.placeholder = tf.placeholder(NATIVE_TYPE, shape=shape)\n super(Placeholder, self).__init__(self.placeholder)\n\n def __repr__(self) -> str:\n return \"Placeholder(shape={})\".format(self.shape)\n\n def feed(self, value: np.ndarray) -> Dict[tf.Tensor, np.ndarray]:\n assert isinstance(value, np.ndarray), type(value)\n return {self.placeholder: value}\n\n class Variable(DenseTensor, AbstractVariable):\n \"\"\"Native Variable class.\"\"\"\n\n def __init__(self, initial_value: Union[tf.Tensor, np.ndarray]) -> None:\n self.variable = tf.Variable(\n initial_value, dtype=NATIVE_TYPE, trainable=False\n )\n self.initializer = self.variable.initializer\n super(Variable, self).__init__(self.variable.read_value())\n\n def __repr__(self) -> str:\n return \"Variable(shape={})\".format(self.shape)\n\n def assign_from_native(self, value: np.ndarray) -> tf.Operation:\n assert isinstance(value, np.ndarray), type(value)\n return self.assign_from_same(FACTORY.tensor(value))\n\n def assign_from_same(self, value: Tensor) -> tf.Operation:\n assert isinstance(value, Tensor), type(value)\n return tf.assign(self.variable, value.value).op\n\n return FACTORY\n"
] |
[
[
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.reduce_sum",
"tensorflow.bitwise.bitwise_and",
"tensorflow.cast",
"tensorflow.space_to_batch_nd",
"tensorflow.equal",
"tensorflow.where",
"tensorflow.cumsum",
"tensorflow.strided_slice",
"tensorflow.bitwise.right_shift",
"tensorflow.Variable",
"tensorflow.bitwise.invert",
"tensorflow.batch_to_space_nd",
"tensorflow.squeeze",
"tensorflow.compat.v2.where",
"tensorflow.gather",
"tensorflow.name_scope",
"tensorflow.bitwise.bitwise_xor",
"tensorflow.negative",
"tensorflow.matmul",
"tensorflow.bitwise.left_shift",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.bitwise.bitwise_or",
"tensorflow.split",
"numpy.array",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.reshape",
"tensorflow.assign",
"tensorflow.expand_dims"
]
] |
beijing-penguin/pytorch-tutorial
|
[
"986aade6848ef4809975aa029ae83d8bb84fd26e"
] |
[
"my_pytoch/net/neural_networks.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n # 1 input image channel, 6 output channels, 5x5 square convolution\n # kernel\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n # an affine operation: y = Wx + b\n self.fc1 = nn.Linear(400, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n # Max pooling over a (2, 2) window\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n # If the size is a square you can only specify a single number\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\nnet = Net()\nprint(net)\n\nprint(net.parameters())\nparams = list(net.parameters())\nprint(len(params))\nprint(params[0].size()) # conv1's .weight\n\ninput = torch.randn(1, 1, 32, 32)\nout = net(input)\nprint(out)\n\nnet.zero_grad()\nout.backward(torch.randn(1, 10))\n"
] |
[
[
"torch.nn.Linear",
"torch.randn",
"torch.nn.Conv2d"
]
] |
Rahul-404/Handwritten-digit-recognition-MNIST
|
[
"c20fca30c2cfc26e15c64b45e3065111e9c5b974"
] |
[
"run.py"
] |
[
"from keras.models import load_model\nfrom tkinter import *\nimport tkinter as tk\nimport win32gui\nfrom PIL import ImageGrab, Image\nimport numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\n\nmodel = load_model('mnist.h5')\n\ndef predict_digit(img):\n # resize image to 28x28 pixels\n img = img.resize(1, 28, 28, 1)\n # convert rbg to gray\n img = img.convert('L')\n img = np.array(img)\n # reshaping to support our model input nd normalization\n img = img.reshape(1, -1)\n img = img/255.0\n # predicting the class\n res = model.predict(img)[0]\n return res\n\nclass App(tk.Tk):\n\n def __init__(self):\n tk.Tk.__init__(self)\n self.x = self.y = 0\n\n # creating elements\n self.canvas = tk.Canvas(self, width=300, height=300, bg='white',cursor='cross')\n self.label = tk.Label(self, text='Thinking..', font=('Helvetica', 48))\n self.classify_btn = tk.Button(self, text='Recognise', command=self.classify_handwriting)\n self.button_clear = tk.Button(self, text = 'Clear', command = self.clear_all)\n\n # Grid structure\n self.canvas.grid(row=0, column=0, pady=2, sticky=W,)\n self.label.grid(row=0, column=1, pady=2, padx=2)\n self.classify_btn.grid(row=1, column=1, pady=2, padx=2)\n self.button_clear.grid(row=1, column=0, pady=2)\n\n # self.canvas.bind(\"<Motion>\", self.start_pos)\n self.canvas.bind(\"<B1-Motion>\", self.draw_lines)\n\n def clear_all(self):\n self.canvas.delete(\"all\")\n\n def classify_handwriting(self):\n HWND = self.canvas.winfo_id()# get the handle of the canvas\n rect = win32gui.GetWindowRect(HWND)# get the coordinate of the canvas\n im = ImageGrab.grab(rect)\n digit, acc = predict_digit(im)\n self.label.configure(text= str(digit)+', '+ str(int(acc*100))+'%')\n\n\n def draw_lines(self, event):\n self.x = event.x\n self.y = event.y\n r = 8\n self.canvas.create_oval(self.x-r, self.y-r, self.x + r, self.y + r, fill='black')\n\napp = App()\nmainloop()"
] |
[
[
"numpy.array"
]
] |
MacDaddio/BigGAN-PyTorch
|
[
"cd47be41de43e8ba3679e144883560966aba3480"
] |
[
"train.py"
] |
[
"\"\"\" BigGAN: The Authorized Unofficial PyTorch release\n Code by A. Brock and A. Andonian\n This code is an unofficial reimplementation of\n by A. Brock, J. Donahue, and K. Simonyan (arXiv 1809.11096).\n\n Let's go.\n\"\"\"\n\nimport os\nimport functools\nimport math\nimport numpy as np\nfrom tqdm import tqdm, trange\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.nn import Parameter as P\nimport torchvision\n\n# Import my stuff\nimport inception_utils\nimport utils\nimport losses\nimport train_fns\nfrom sync_batchnorm import patch_replication_callback\n\n# The main training file. Config is a dictionary specifying the configuration\n# of this training run.\n\ndef get_current_lr(lr, decay, min_val, itr):\n if itr == 0:\n return np.max([lr, min_val])\n else:\n return np.max([lr / (decay ** itr ), min_val])\n\ndef run(config):\n \n #Make sure that the learning rate decay is >= 1\n assert config['G_lr_decay'] >= 1.0, 'Generator learning rate decay (G_lr_decay) must be greater than or equal to 1.0'\n assert config['D_lr_decay'] >= 1.0, 'Discriminator learning rate decay (D_lr_decay) must be greater than or equal to 1.0'\n\n #Make sure nDs is 1 if PS training\n# if config['which_train_fn'] == 'PS':\n# assert config['num_D_steps'] == 1, 'num_D_steps must be equal to 1 for PS training.'\n\n #Make sure nps is -1 or greater than 0\n assert config['nps'] == -1 or config['nps'] > 0, 'nps must be -1 (default) or positive.'\n\n # Update the config dict as necessary\n # This is for convenience, to add settings derived from the user-specified\n # configuration into the config-dict (e.g. inferring the number of classes\n # and size of the images from the dataset, passing in a pytorch object\n # for the activation specified as a string)\n config['resolution'] = utils.imsize_dict[config['dataset']]\n config['n_classes'] = utils.nclass_dict[config['dataset']]\n config['G_activation'] = utils.activation_dict[config['G_nl']]\n config['D_activation'] = utils.activation_dict[config['D_nl']]\n # By default, skip init if resuming training.\n if config['resume']:\n print('Skipping initialization for training resumption...')\n config['skip_init'] = True\n config = utils.update_config_roots(config)\n device = 'cuda'\n \n # Seed RNG\n utils.seed_rng(config['seed'])\n\n # Prepare root folders if necessary\n utils.prepare_root(config)\n\n # Setup cudnn.benchmark for free speed\n torch.backends.cudnn.benchmark = True\n\n # Import the model--this line allows us to dynamically select different files.\n model = __import__(config['model'])\n experiment_name = (config['experiment_name'] if config['experiment_name']\n else utils.name_from_config(config))\n print('Experiment name is %s' % experiment_name)\n\n # Next, build the model\n G = model.Generator(**config).to(device)\n D = model.Discriminator(**config).to(device)\n \n # If using EMA, prepare it\n if config['ema']:\n print('Preparing EMA for G with decay of {}'.format(config['ema_decay']))\n G_ema = model.Generator(**{**config, 'skip_init':True, \n 'no_optim': True}).to(device)\n ema = utils.ema(G, G_ema, config['ema_decay'], config['ema_start'])\n else:\n G_ema, ema = None, None\n \n # FP16?\n if config['G_fp16']:\n print('Casting G to float16...')\n G = G.half()\n if config['ema']:\n G_ema = G_ema.half()\n if config['D_fp16']:\n print('Casting D to fp16...')\n D = D.half()\n # Consider automatically reducing SN_eps?\n GD = model.G_D(G, D)\n print(G)\n print(D)\n print('Number of params in G: {} D: {}'.format(\n *[sum([p.data.nelement() for p in net.parameters()]) for net in [G,D]]))\n # Prepare state dict, which holds things like epoch # and itr #\n state_dict = {'itr': 0, 'epoch': 0, 'save_num': 0, 'save_best_num': 0,\n 'best_IS': 0, 'best_FID': 999999, 'config': config}\n\n # If loading from a pre-trained model, load weights\n if config['resume']:\n print('Loading weights...')\n utils.load_weights(G, D, state_dict,\n config['weights_root'], experiment_name, \n config['load_weights'] if config['load_weights'] else None,\n G_ema if config['ema'] else None)\n\n # If parallel, parallelize the GD module\n if config['parallel']:\n GD = nn.DataParallel(GD)\n if config['cross_replica']:\n patch_replication_callback(GD)\n\n # Prepare loggers for stats; metrics holds test metrics,\n # lmetrics holds any desired training metrics.\n test_metrics_fname = '%s/%s_log.jsonl' % (config['logs_root'],\n experiment_name)\n train_metrics_fname = '%s/%s' % (config['logs_root'], experiment_name)\n print('Inception Metrics will be saved to {}'.format(test_metrics_fname))\n test_log = utils.MetricsLogger(test_metrics_fname, \n reinitialize=(not config['resume']))\n print('Training Metrics will be saved to {}'.format(train_metrics_fname))\n train_log = utils.MyLogger(train_metrics_fname, \n reinitialize=(not config['resume']),\n logstyle=config['logstyle'])\n # Write metadata\n utils.write_metadata(config['logs_root'], experiment_name, config, state_dict)\n # Prepare data; the Discriminator's batch size is all that needs to be passed\n # to the dataloader, as G doesn't require dataloading.\n # Note that at every loader iteration we pass in enough data to complete\n # a full D iteration (regardless of number of D steps and accumulations)\n D_batch_size = (config['batch_size'] * config['num_D_steps']\n * config['num_D_accumulations'])\n loaders = utils.get_data_loaders(**{**config, 'batch_size': D_batch_size,\n 'start_itr': state_dict['itr']})\n \n # Set nps equal to the length of the data if\n if config['nps'] == -1:\n config['nps'] = len(loaders[0].dataset)\n\n # Prepare inception metrics: FID and IS\n get_inception_metrics = inception_utils.prepare_inception_metrics(config['dataset'], config['parallel'], config['no_fid'])\n\n # Prepare noise and randomly sampled label arrays\n # Allow for different batch sizes in G\n G_batch_size = max(config['G_batch_size'], config['batch_size'], config['inception_batchsize'])\n z_, y_ = utils.prepare_z_y(G_batch_size, G.dim_z, config['n_classes'],\n device=device, fp16=config['G_fp16'])\n # Prepare a fixed z & y to see individual sample evolution throghout training\n fixed_z, fixed_y = utils.prepare_z_y(G_batch_size, G.dim_z,\n config['n_classes'], device=device,\n fp16=config['G_fp16']) \n fixed_z.sample_()\n fixed_y.sample_()\n # Loaders are loaded, prepare the training function\n if config['which_train_fn'] == 'GAN':\n train = train_fns.GAN_training_function(G, D, GD, z_, y_, \n ema, state_dict, config)\n # If doing pseudosupervised training\n elif config['which_train_fn'] == 'PS':\n# train = train_fns.GAN_training_function_PS(G, config)\n train = train_fns.GAN_training_function_with_PS(G, D, GD, z_, y_, \n ema, state_dict, config)\n z_ps = torch.randn(config['dim_z'], len(loaders[0].dataset)).T.to(device) # The transpose part makes the z's consistent across experiments\n \n #Fill the z_ps variable with n-nps nans indicating which variables don't have nans\n if len(loaders[0].dataset) - config['nps'] > 0:\n ind = torch.randperm(len(loaders[0].dataset))[0:(len(loaders[0].dataset) - config['nps'])]\n z_ps[ind] = float('nan') \n \n # Else, assume debugging and use the dummy train fn\n else:\n train = train_fns.dummy_training_function()\n # Prepare Sample function for use with inception metrics\n sample = functools.partial(utils.sample,\n G=(G_ema if config['ema'] and config['use_ema']\n else G),\n z_=z_, y_=y_, config=config)\n\n print('Beginning training at epoch %d...' % state_dict['epoch'])\n # Train for specified number of epochs, although we mostly track G iterations.\n for epoch in range(state_dict['epoch'], config['num_epochs']): \n # Which progressbar to use? TQDM or my own?\n if config['pbar'] == 'mine':\n pbar = utils.progress(loaders[0],displaytype='s1k' if config['use_multiepoch_sampler'] else 'eta')\n else:\n pbar = tqdm(loaders[0])\n for i, (x, y) in enumerate(pbar):\n # Increment the iteration counter\n state_dict['itr'] += 1\n # Make sure G and D are in training mode, just in case they got set to eval\n # For D, which typically doesn't have BN, this shouldn't matter much.\n G.train()\n D.train()\n \n #Set the learning rate\n for temp in G.optim.param_groups:\n temp['lr'] = get_current_lr(config['G_lr'], config['G_lr_decay'], config['G_lr_min'], state_dict['itr'])\n for temp in D.optim.param_groups:\n temp['lr'] = get_current_lr(config['D_lr'], config['D_lr_decay'], config['D_lr_min'], state_dict['itr'])\n \n if config['ema']:\n G_ema.train()\n if config['D_fp16']:\n x, y = x.to(device).half(), y.to(device)\n else:\n x, y = x.to(device), y.to(device)\n if config['which_train_fn'] == 'PS':\n i_start = i * config['batch_size'] * config['num_G_accumulations']\n i_end = (i + 1) * config['batch_size'] * config['num_G_accumulations']\n# metrics = train(x,y,z_ps[i_start:i_end,:])\n metrics = train(x,y,z_ps)\n else:\n metrics = train(x, y)\n train_log.log(itr=int(state_dict['itr']), **metrics)\n \n # Every sv_log_interval, log singular values\n if (config['sv_log_interval'] > 0) and (not (state_dict['itr'] % config['sv_log_interval'])):\n train_log.log(itr=int(state_dict['itr']), \n **{**utils.get_SVs(G, 'G'), **utils.get_SVs(D, 'D')})\n\n # If using my progbar, print metrics.\n if config['pbar'] == 'mine':\n print(', '.join([' itr: %d' % state_dict['itr']] \n + ['%s : %+4.2f' % (key, metrics[key]) for key in metrics][0:3] \n + ['%s : %4.1e' % (key, metrics[key]) for key in metrics][3:5] ), end=' ')\n\n # Save weights and copies as configured at specified interval\n if not (state_dict['itr'] % config['save_every']):\n if config['G_eval_mode']:\n print('Switchin G to eval mode...')\n G.eval()\n if config['ema']:\n G_ema.eval()\n train_fns.save_and_sample(G, D, G_ema, z_, y_, fixed_z, fixed_y, \n state_dict, config, experiment_name)\n\n # Test every specified interval\n if not (state_dict['itr'] % config['test_every']):\n if config['G_eval_mode']:\n print('Switchin G to eval mode...')\n G.eval()\n train_fns.test(G, D, G_ema, z_, y_, state_dict, config, sample,\n get_inception_metrics, experiment_name, test_log)\n # Increment epoch counter at end of epoch\n state_dict['epoch'] += 1\n\n\ndef main():\n # parse command line and run\n parser = utils.prepare_parser()\n config = vars(parser.parse_args())\n print(config)\n run(config)\n\nif __name__ == '__main__':\n main()"
] |
[
[
"numpy.max",
"torch.nn.DataParallel"
]
] |
jglaser/pytorch-optimizer
|
[
"910b414565427f0a66e20040475e7e4385e066a5"
] |
[
"tests/test_optimizer_with_nn.py"
] |
[
"import numpy as np\nimport pytest\nimport torch\nfrom torch import nn\n\nimport torch_optimizer as optim\n\n\ndef make_dataset(seed=42):\n rng = np.random.RandomState(seed)\n N = 100\n D = 2\n\n X = rng.randn(N, D) * 2\n\n # center the first N/2 points at (-2,-2)\n mid = N // 2\n X[:mid, :] = X[:mid, :] - 2 * np.ones((mid, D))\n\n # center the last N/2 points at (2, 2)\n X[mid:, :] = X[mid:, :] + 2 * np.ones((mid, D))\n\n # labels: first N/2 are 0, last N/2 are 1\n Y = np.array([0] * mid + [1] * mid).reshape(100, 1)\n\n x = torch.Tensor(X)\n y = torch.Tensor(Y)\n return x, y\n\n\nclass LogisticRegression(nn.Module):\n def __init__(self):\n super(LogisticRegression, self).__init__()\n self.linear1 = nn.Linear(2, 4)\n self.linear2 = nn.Linear(4, 1)\n\n def forward(self, x):\n output = torch.relu(self.linear1(x))\n output = self.linear2(output)\n y_pred = torch.sigmoid(output)\n return y_pred\n\n\ndef ids(v):\n return '{} {}'.format(v[0].__name__, v[1:])\n\n\ndef build_lookahead(*a, **kw):\n base = optim.Yogi(*a, **kw)\n return optim.Lookahead(base)\n\n\noptimizers = [\n (build_lookahead, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.A2GradExp, {'lips': 2.0, 'beta': 1e-3}, 500),\n (optim.A2GradInc, {'lips': 5.0, 'beta': 1e-3}, 200),\n (optim.A2GradUni, {'lips': 5.0, 'beta': 1e-3}, 500),\n (optim.AccSGD, {'lr': 1.0, 'weight_decay': 1e-3}, 200),\n (optim.AdaBelief, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.AdaBound, {'lr': 1.5, 'gamma': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.AdaMod, {'lr': 2.0, 'weight_decay': 1e-3}, 200),\n (optim.Adafactor, {'lr': 0.004466, 'weight_decay': 1e-3}, 1500),\n (optim.AdamP, {'lr': 0.045, 'weight_decay': 1e-3}, 800),\n (optim.AggMo, {'lr': 0.17059, 'weight_decay': 1e-3}, 1000),\n (optim.Apollo, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.DiffGrad, {'lr': 0.5, 'weight_decay': 1e-3}, 200),\n (\n optim.LARS,\n {'lr': 1.0, 'weight_decay': 1e-3, 'trust_coefficient': 0.01},\n 200,\n ),\n (optim.Lamb, {'lr': 0.0151, 'weight_decay': 1e-3}, 1000),\n (optim.MADGRAD, {'lr': 1.0, 'weight_decay': 1e-3}, 200),\n (optim.NovoGrad, {'lr': 0.01, 'weight_decay': 1e-3}, 200),\n (optim.PID, {'lr': 0.01, 'weight_decay': 1e-3, 'momentum': 0.1}, 200),\n (optim.QHAdam, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.QHM, {'lr': 0.1, 'weight_decay': 1e-5, 'momentum': 0.2}, 200),\n (optim.RAdam, {'lr': 1.0, 'weight_decay': 1e-3}, 200),\n (optim.Ranger, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.RangerQH, {'lr': 0.0124, 'weight_decay': 1e-3}, 1100),\n (optim.RangerVA, {'lr': 0.2214, 'weight_decay': 1e-3}, 500),\n (optim.SGDP, {'lr': 1.0, 'weight_decay': 1e-3}, 200),\n (optim.SGDW, {'lr': 1.0, 'weight_decay': 1e-3}, 200),\n (optim.SWATS, {'lr': 0.703, 'weight_decay': 1e-3}, 600),\n (\n optim.Shampoo,\n {'lr': 0.279, 'weight_decay': 1e-3, 'momentum': 0.05},\n 1600,\n ),\n (optim.Yogi, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n (optim.Adahessian, {'lr': 0.1, 'weight_decay': 1e-3}, 200),\n]\n\n\[email protected]('optimizer_config', optimizers, ids=ids)\ndef test_basic_nn_modeloptimizer_config(optimizer_config):\n torch.manual_seed(42)\n x_data, y_data = make_dataset()\n model = LogisticRegression()\n\n loss_fn = nn.BCELoss()\n optimizer_class, config, iterations = optimizer_config\n optimizer = optimizer_class(model.parameters(), **config)\n init_loss = None\n for _ in range(iterations):\n y_pred = model(x_data)\n loss = loss_fn(y_pred, y_data)\n if init_loss is None:\n init_loss = loss\n optimizer.zero_grad()\n loss.backward(create_graph=True)\n optimizer.step()\n assert init_loss.item() > 2.0 * loss.item()\n"
] |
[
[
"torch.sigmoid",
"torch.Tensor",
"torch.manual_seed",
"torch.nn.BCELoss",
"numpy.ones",
"torch.nn.Linear",
"numpy.array",
"numpy.random.RandomState"
]
] |
startupcode001/payequity
|
[
"21432b36c77cd7cd0ebc263453302a01ec3b5170",
"21432b36c77cd7cd0ebc263453302a01ec3b5170"
] |
[
"Script/PE_Functions_1.py",
"Script/46/PE_Functions.py"
] |
[
"import pandas as pd\nimport numpy as np\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.graph_objects as go\n\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer,KNNImputer\n\nfrom patsy import dmatrices\nimport statsmodels.api as sm\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\n\nfrom math import pi\n\n# Helper Functions Starts here #\n\ndef rename_column(df):\n df.columns = [c.strip().upper().replace(' ', '_') for c in df.columns]\n df.columns = [c.strip().upper().replace('/', '_') for c in df.columns]\n df.columns = [c.strip().upper().replace('-', '_') for c in df.columns]\n df.columns = [c.strip().upper().replace('(', '') for c in df.columns]\n df.columns = [c.strip().upper().replace(')', '') for c in df.columns]\n df.columns = [c.strip().upper().replace('.', '') for c in df.columns]\n df.columns = [c.strip().upper().replace('___', '_') for c in df.columns]\n df.columns = [c.strip().upper().replace('__', '_') for c in df.columns]\n return df\n\ndef plot_gender_gap(coff):\n female_coff = coff\n bar_before = {'color': \"lightgrey\"}\n bar_after = {'color': \"green\"}\n bar_now = bar_before\n if female_coff>=0:\n bar_now = bar_after\n \n fig = go.Figure(go.Indicator(\n domain = {'x': [0, 1], 'y': [0, 1]},\n value = 1+round(female_coff,2),\n mode = \"gauge+number+delta\",\n title = {'text': \"Women earn {} dollar for every 1 dollar earn by Men\".format(1+round(female_coff,2))},\n delta = {'reference': 1},\n gauge = {'bar':bar_now,\n 'axis': {'range': [0.8,1.2]},\n 'steps' : [\n {'range': [0.95, 1.2], 'color': \"lightgreen\"},\n {'range': [0.8, 0.95], 'color': \"white\"}\n ],\n 'threshold' : {'line': {'color': \"blue\", 'width': 1}, 'thickness': 0.5, 'value': 1}\n }))\n return fig\n\ndef plot_pie_2(ratio):\n labels = ['','{}% of the drivers'.format(round(ratio*100,))]\n sizes = [1-ratio, ratio]\n pcts = labels\n width = 0.5\n\n fig_pie_1, ax1 = plt.subplots()\n ax1.axis('equal')\n\n pie, _ = ax1.pie(\n sizes,\n startangle=90,\n # labels=pcts,\n # labeldistance=.8,\n # rotatelabels=True,\n colors = [\"whitesmoke\", \"gold\"]\n )\n plt.text(0, -3, labels, ha='center', va='center', fontsize=12)\n\n plt.setp(pie, width=width, edgecolor='white')\n\n return fig_pie_1\n\ndef plot_pie(ratio):\n fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection':'polar'})\n data = round(ratio*100,0)\n startangle = 90\n x = (data * pi *2)/ 100\n left = (startangle * pi *2)/ 360 #this is to control where the bar starts\n plt.xticks([])\n plt.yticks([])\n ax.spines.clear()\n ax.barh(1, x, left=left, height=1, color='#5DADE2') \n plt.ylim(-3, 3)\n plt.text(0, -3, data, ha='center', va='center', fontsize=22)\n return fig\n\n\ndef clean_req_feature(data, feature, valid_feature_list, warning_message, data_type=\"string\", \n val_col = 'VALIDATION_MESSAGE',val_flag_col = 'VALIDATION_FLAG'):\n da = data.copy()\n # Check exclusion and remove invalid data\n if data_type == \"numeric\":\n # Numeric features, exclude nan, strings\n da[feature] = pd.to_numeric(da[feature], errors='coerce')\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n elif data_type == 'datetime':\n da[feature] = pd.to_datetime(da[feature], errors='coerce')\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n# da = da.dropna(subset=[feature])\n else:\n # String features, check for nan and valid list \n if len(valid_feature_list) == 0: \n # exclude nan only\n check_na_feature = sum(da[feature].isna()*1)/len(da[feature])\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n# da = da.dropna(subset=[feature])\n else:\n # exclude nan, and those not in valid_feature_list\n da[feature] = da[feature].str[0].str.upper()\n exclude_feature_num = sum(~(da[feature].isin(valid_feature_list))*1)\n da.loc[~da[feature].isin(valid_feature_list), val_flag_col] = 1\n# da = da[da[feature].isin(valid_feature_list)]\n\n # Record message\n if exclude_feature_num>0:\n warning_feature = feature+\": exclude \"+str(exclude_feature_num)+\" invalid records\"\n da.loc[da[val_flag_col]==1, val_col] = da[val_col]+\" | \"+ warning_feature\n else:\n warning_feature = feature+\": Successful Run\"\n warning_message[feature] = warning_feature\n# print(warning_message)\n da[val_flag_col]=0\n return da,warning_message\n\ndef clean_optional_feature(data, feature, valid_feature_list, warning_message, exclude_col, data_type=\"string\", \n val_col = 'VALIDATION_MESSAGE',val_flag_col = 'VALIDATION_FLAG'):\n da = data.copy()\n check_na_feature = sum(da[feature].isna()*1)/len(da[feature])\n \n # Step 1, determine if there is no input, if yes, then this is an optional factor and we should exclude from our model\n if check_na_feature == 1:\n # Step 1, determine if there is no input, if yes, then this is an optional factor and we should exclude from our model\n exclude_col.append(feature)\n warning_feature = feature + \": exclude this optional factor\"\n warning_message[feature] = warning_feature\n else:\n # Step 2, clean up data just like the required features\n da, warning_message = clean_req_feature(data = da,feature = feature,valid_feature_list=valid_feature_list,\n warning_message = warning_message, data_type=data_type,val_col = val_col,val_flag_col = val_flag_col)\n \n return da, warning_message, exclude_col\n\ndef set_dropped_category(series, dropped_category):\n '''\n Function to move one category to the top of a category column, such that\n it is the one that gets dropped for the OLS\n '''\n\n temp = list(series.cat.categories)\n temp.insert(0, temp.pop(temp.index(dropped_category)))\n series = series.cat.reorder_categories(temp)\n\n return series\n\n# Main Program Starts here #\n\ndef run(data=None):\n # 1.1 Setup ************************************\n # Use Starting Salary or not, Y/N\n company_name = 'Client Name'\n version = 'Base Pay'\n starting_salary_flag = 'N'\n target = 'SALARY'\n\n # Setup error message to display on UI\n error_message = {}\n warning_message = {}\n exclude_col = []\n \n # Read Data\n try:\n df = data\n except:\n error_file_read = \"Unable to read submission file, Please download and update data template again\"\n error_message['File_Read'] = error_file_read\n df.columns = [c.strip().upper().replace(' ', '_') for c in df.columns]\n df.columns = [c.strip().upper().replace('/', '_') for c in df.columns]\n \n # 2.1 Data Cleaning ****************************\n # Data Validation\n df['VALIDATION_MESSAGE']=\"\"\n df['VALIDATION_FLAG']=0\n # Snapshot Date\n try:\n df['SNAPSHOT_DATE'] = df['SNAPSHOT_DATE'].astype(\"string\")\n snapshot = df['SNAPSHOT_DATE'].mode().tolist()[0]\n except:\n error_snapshot = \"Invalid snapshot date, Please check submission format is mm/dd/yyyy in data template\"\n error_message['SNAPSHOT_DATE'] = error_snapshot\n df['NOW'] = pd.to_datetime(snapshot)\n \n # 2.2 Clean up All features ******************\n df,warning_message = clean_req_feature(data = df,feature = \"EEID\",valid_feature_list=[],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"GENDER\",valid_feature_list=[\"F\",\"M\",\"O\"],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"SALARY\",valid_feature_list=[],warning_message = warning_message, data_type='numeric')\n df,warning_message = clean_req_feature(data = df,feature = \"JOB_LEVEL_OR_COMP_GRADE\",valid_feature_list=[],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"JOB_FUNCTION\",valid_feature_list=[],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"STATE\",valid_feature_list=[],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"FULL_TIME\",valid_feature_list=[\"Y\",\"N\"],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"FLSA_EXEMPT\",valid_feature_list=[\"Y\",\"N\"],warning_message = warning_message,data_type=\"string\")\n\n # Clean up optional features\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"ETHNICITY\",valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=\"string\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"PEOPLE_MANAGER\",valid_feature_list=[\"Y\",\"N\"],warning_message = warning_message,exclude_col = exclude_col, data_type=\"string\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"EDUCATION\",valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=\"string\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"PROMOTION\",valid_feature_list=[\"Y\",\"N\"],warning_message = warning_message,exclude_col = exclude_col, data_type=\"string\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"PERFORMANCE\",valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=\"string\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"DATE_OF_BIRTH\",valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=\"datetime\")\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = \"DATE_OF_HIRE\",valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=\"datetime\")\n \n # Record Message\n df_org = df.copy()\n df_org.to_excel('Data\\data_validate.xlsx')\n before_clean_record = df_org.shape[0]\n \n df = df_org[df_org['VALIDATION_MESSAGE']==\"\"]\n after_clean_record=df.shape[0]\n\n warning_message['OVERVIEW'] = \"OVERVIEW:Successfully run \"+str(after_clean_record)+\" out of \"+str(before_clean_record)+\" records\"\n message = pd.DataFrame.from_dict(warning_message,orient='index')\n message.columns=['NAME']\n message = message['NAME'].str.split(\":\",expand = True)\n message.columns=['NAME','Message']\n message = message['Message']\n \n # 2.3 Feature Engineering ****************************\n df = df.set_index('EEID', drop=True)\n # col_list=df.columns.tolist()\n filter_list = [x for x in df.columns.tolist() if x not in exclude_col]\n df = df[filter_list]\n col_list=df.columns.tolist()\n \n # Calculate Age and Tenure\n try:\n df['AGE'] = np.ceil((df['NOW'] - df['DATE_OF_BIRTH']).dt.days/365)\n except:\n print('AGE: Calculation error')\n try:\n df['TENURE'] = np.ceil((df['NOW'] - df['DATE_OF_HIRE']).dt.days/365)\n except:\n print('TENURE: Calculation error')\n \n numeric_columns = ['SALARY','AGE', 'TENURE']\n if 'AGE' not in col_list:\n numeric_columns.remove('AGE')\n if 'TENURE' not in col_list:\n numeric_columns.remove('TENURE')\n \n for c in numeric_columns:\n df.loc[df[c]=='na', c] = np.nan\n df[c] = pd.to_numeric(df[c])\n \n df.to_excel('edu.xlsx')\n \n # %% Convert string columns to categories\n category_columns = [x for x in col_list if x not in numeric_columns]\n for c in category_columns:\n df[c] = df[c].astype(str).str.strip().astype('category')\n \n feature = []\n baseline = []\n \n df['LOG_SALARY'] = np.log(df['SALARY'])\n\n # Default to category level w/ highest n-count\n cat_cols = list(df.select_dtypes(['category']).columns)\n for x in cat_cols:\n drop_cate = df[x].value_counts().index.tolist()[0]\n #Set Manually\n if x=='GENDER':\n print('Override! Gender',\"level dropped:\",'M')\n drop_cate = 'M'\n df[x] = set_dropped_category(df[x], drop_cate)\n feature.append(x)\n baseline.append(drop_cate)\n\n df_baseline = pd.DataFrame({'Features': feature,'Baseline': baseline})\n print('\\n')\n print(df_baseline.to_markdown())\n \n # 3 Modeling - Linear Regression ****************************\n col_list = df.columns\n \n # Remove all excess columns\n add_exclude_col = ['SALARY','SNAPSHOT_DATE', 'VALIDATION_MESSAGE', 'VALIDATION_FLAG', 'NOW','DATE_OF_BIRTH','DATE_OF_HIRE']\n add_exclude_col_predict = add_exclude_col+['GENDER','ETHNICITY']\n exclude_col = exclude_col+add_exclude_col\n exclude_col_predict = exclude_col+add_exclude_col_predict\n\n model_col = [x for x in col_list if x not in exclude_col]\n model_col_predict = [x for x in col_list if x not in exclude_col_predict]\n \n # Factors\n f_raw = 'LOG_SALARY ~ GENDER'\n f_discover = model_col[-1] + ' ~ ' + ' + '.join(map(str, model_col[0:len(model_col)-1]))\n f_predict= model_col[-1] + ' ~ ' + ' + '.join(map(str, model_col_predict[0:len(model_col_predict)-1]))\n \n # Gender Raw Gap\n y_raw, x_raw = dmatrices(f_raw, df, return_type='dataframe')\n model_raw = sm.OLS(y_raw, x_raw)\n results = model_raw.fit()\n\n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n\n r2_raw = results.rsquared\n r2_adj = results.rsquared_adj\n\n female_coff_raw = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['Coef.'].tolist()[0]\n female_pvalue_raw = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['P>|t|'].tolist()[0]\n \n # Gender Net Gap\n y_dis, x_dis = dmatrices(f_discover, df, return_type='dataframe')\n model_dis = sm.OLS(y_dis, x_dis)\n results = model_dis.fit()\n\n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n\n r2 = results.rsquared\n r2_adj = results.rsquared_adj\n\n female_coff = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['Coef.'].tolist()[0]\n female_pvalue = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['P>|t|'].tolist()[0]\n \n # Gender Net Gap - Prediciton\n y_predict, x_predict = dmatrices(f_predict, df, return_type='dataframe')\n model_predict = sm.OLS(y_predict, x_predict)\n results_predict = model_predict.fit()\n\n y_pred = results_predict.predict(x_predict)\n std, lower, upper = wls_prediction_std(results_predict)\n\n # Graphs\n plot_gender = plot_gender_gap(female_coff)\n fig_pie = plot_pie(1+female_coff)\n \n # Statistics for output\n hc_female = df[(df['GENDER']=='F') | (df['GENDER']=='FEMALE')].shape[0]\n \n # print(message.loc[['OVERVIEW']]['Message'])\n \n return df, df_org, message, exclude_col, r2_raw, female_coff_raw, female_pvalue_raw, r2, female_coff, female_pvalue, fig_pie, before_clean_record, after_clean_record,hc_female",
"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom datetime import date\nimport operator\nimport copy \n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom streamlit_echarts import st_echarts\nimport hydralit_components as hc\nfrom pathlib import Path\n\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer,KNNImputer\n\nfrom patsy import dmatrices\nimport statsmodels.api as sm\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\n\nfrom math import pi\nimport base64\nimport os\n\nimport xlsxwriter\nfrom io import BytesIO\n\nimport locale\n\nimport pyrebase\n\nimport plost\n\nfrom PE_Parameter import *\n\n# Helper Functions Starts here #\n\n# def rename_column(df):\n# df.columns = [c.strip().upper().replace(' ', '_') for c in df.columns]\n# df.columns = [c.strip().upper().replace('/', '_') for c in df.columns]\n# df.columns = [c.strip().upper().replace('-', '_') for c in df.columns]\n# df.columns = [c.strip().upper().replace('(', '') for c in df.columns]\n# df.columns = [c.strip().upper().replace(')', '') for c in df.columns]\n# df.columns = [c.strip().upper().replace('.', '') for c in df.columns]\n# df.columns = [c.strip().upper().replace('___', '_') for c in df.columns]\n# df.columns = [c.strip().upper().replace('__', '_') for c in df.columns]\n# return df\n# st.set_page_config(layout=\"wide\")\n\n# Set Style\n# style_path = Path(__file__).parents[0].__str__()+'/Style/style.css'\n# with open(style_path) as f:\n# st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)\n\ndef rename_column(df):\n df.columns = [c.strip().replace(' ', '_') for c in df.columns]\n df.columns = [c.strip().replace('/', '_') for c in df.columns]\n df.columns = [c.strip().replace('-', '_') for c in df.columns]\n df.columns = [c.strip().replace('(', '') for c in df.columns]\n df.columns = [c.strip().replace(')', '') for c in df.columns]\n df.columns = [c.strip().replace('.', '') for c in df.columns]\n df.columns = [c.strip().replace('___', '_') for c in df.columns]\n df.columns = [c.strip().replace('__', '_') for c in df.columns]\n return df\n\ndef gender_name_replace(text):\n if ('F' in text):\n return 'Female'\n elif ('M' in text):\n return 'Male'\n elif ('N' in text):\n return 'Non-Binary'\n elif ('U' in text):\n return 'Unknown'\n else:\n return text\n\ndef plot_eth_donut(data):\n # explosion \n # plt.clf()\n n_exp = len(data['ETHNICITY_NAME'])\n explode = np.repeat(0.02, n_exp).tolist()\n explode = tuple(explode)\n \n centre_circle = plt.Circle((0, 0), 0.65, fc='white')\n # fig_eth = plt.subplots()\n # fig_eth = plt.gcf()\n fig_eth = plt.figure(num = 0,dpi=100)\n # fig_eth, ax_eth = plt.subplots()\n \n plt.pie(data['HC'], labels=data['ETHNICITY_NAME'],\n autopct='%1.1f%%', pctdistance=0.85,\n explode=explode)\n fig_eth.gca().add_artist(centre_circle)\n plt.tight_layout()\n # plt.title('Ethnicity by Headcount')\n # plt.figure(figsize=(500,500))\n return fig_eth\n\ndef plot_gender_donut(data):\n # explosion \n # plt.clf()\n n_exp = len(data['GENDER_NAME'])\n explode = np.repeat(0.02, n_exp).tolist()\n explode = tuple(explode)\n # data.to_excel('gender_check.xlsx')\n \n # Pie Chart\n plt.pie(data['HC'], labels=data['GENDER_NAME'],\n autopct='%1.1f%%', pctdistance=0.85,\n explode=explode)\n centre_circle = plt.Circle((0, 0), 0.65, fc='white')\n # fig_gender = plt.gcf()\n fig_gender = plt.figure(num = 1,dpi=100)\n # fig_gender, ax_gender = plt.subplots()\n fig_gender.gca().add_artist(centre_circle)\n plt.tight_layout()\n # plt.title('Ethnicity by Headcount')\n # plt.figure(figsize=(500,500))\n # plt.show()\n return fig_gender\n\ndef plot_bar(data,col): \n scale_max = round(data['COEF_DISPLAY'].max(),2)+0.02\n scale_min = round(data['COEF_DISPLAY'].min(),2)-0.02\n fig = px.bar(data, x=col, y=\"COEF_DISPLAY\", color='STAT', template='seaborn', text=[f'{round(100*j,1)}%' for i,j in zip(data[col],data['COEF_DISPLAY'])])\n \n fig.update_layout(showlegend=False,autosize=False, margin=dict(l=10, r=10, t=10, b=10),yaxis_range=[scale_min,scale_max],paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)')\n fig.update_yaxes(automargin=True, showticklabels=False, visible=False)\n fig.update_xaxes(automargin=True, showticklabels=True, visible=True)\n # fig.update_xaxes(automargin=True, showticklabels=True, visible=True)\n # fig['layout']['yaxis'].update(autorange = True)s\n # fig['layout']['xaxis'].update(autorange = True)\n fig.update_traces(textfont_size=10, textangle=0, textposition=\"outside\", cliponaxis=False)\n return fig\n\ndef clean_req_feature(data, feature, valid_feature_list, warning_message, data_type=\"string\", \n val_col = 'VALIDATION_MESSAGE',val_flag_col = 'VALIDATION_FLAG'):\n da = data.copy()\n # Check exclusion and remove invalid data\n if (data_type == \"numeric\") and (feature == 'SALARY'):\n da[feature] = pd.to_numeric(da[feature], errors='coerce')\n da.loc[(da[feature].isna()) | (da[feature]<=0), val_flag_col] = 1\n exclude_feature_num = sum(da[feature].isna()*1)+sum((da[feature]<=0)*1)\n elif data_type == \"numeric\":\n # Numeric features, exclude nan, strings\n da[feature] = pd.to_numeric(da[feature], errors='coerce')\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n elif data_type == 'datetime':\n da[feature] = pd.to_datetime(da[feature], errors='coerce')\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n# da = da.dropna(subset=[feature])\n else:\n # String features, check for nan and valid list \n if len(valid_feature_list) == 0: \n # exclude nan only\n check_na_feature = sum(da[feature].isna()*1)/len(da[feature])\n exclude_feature_num = sum(da[feature].isna()*1)\n da.loc[da[feature].isna(), val_flag_col] = 1\n# da = da.dropna(subset=[feature])\n else:\n # exclude nan, and those not in valid_feature_list\n da[feature] = da[feature].str[0].str.upper()\n exclude_feature_num = sum(~(da[feature].isin(valid_feature_list))*1)\n da.loc[~da[feature].isin(valid_feature_list), val_flag_col] = 1\n# da = da[da[feature].isin(valid_feature_list)]\n\n # Record message\n if exclude_feature_num>0:\n warning_feature = feature+\": exclude \"+str(exclude_feature_num)+\" invalid or blank records\"\n da.loc[da[val_flag_col]==1, val_col] = da[val_col]+\" | \"+ warning_feature\n else:\n warning_feature = feature+\": Successful Run\"\n warning_message[feature] = warning_feature\n# print(warning_message)\n da[val_flag_col]=0\n return da,warning_message\n\ndef clean_optional_feature(data, feature, valid_feature_list, warning_message, exclude_col, data_type=\"string\", \n val_col = 'VALIDATION_MESSAGE',val_flag_col = 'VALIDATION_FLAG'):\n da = data.copy()\n check_na_feature = sum(da[feature].isna()*1)/len(da[feature])\n \n # Step 1, determine if there is no input, if yes, then this is an optional factor and we should exclude from our model\n if check_na_feature == 1:\n # Step 1, determine if there is no input, if yes, then this is an optional factor and we should exclude from our model\n exclude_col.append(feature)\n warning_feature = feature + \": exclude this optional driver\"\n warning_message[feature] = warning_feature\n else:\n # Step 2, clean up data just like the required features\n da, warning_message = clean_req_feature(data = da,feature = feature,valid_feature_list=valid_feature_list,\n warning_message = warning_message, data_type=data_type,val_col = val_col,val_flag_col = val_flag_col)\n \n return da, warning_message, exclude_col\n\ndef set_dropped_category(series, dropped_category):\n '''\n Function to move one category to the top of a category column, such that\n it is the one that gets dropped for the OLS\n '''\n\n temp = list(series.cat.categories)\n temp.insert(0, temp.pop(temp.index(dropped_category)))\n series = series.cat.reorder_categories(temp)\n\n return series\n\n# Main Program Starts here #\n\n# Set functions\[email protected]_memo(show_spinner=False)\ndef convert_df(df):\n # IMPORTANT: Cache the conversion to prevent computation on every rerun\n return df.to_csv().encode('utf-8')\n\n# Function\[email protected]_memo(show_spinner=False)\n# Download Excel Template\ndef get_binary_file_downloader_html(bin_file, file_label='File'):\n with open(bin_file, 'rb') as f:\n data = f.read()\n bin_str = base64.b64encode(data).decode()\n # href = f'<a href=\"data:application/octet-stream;base64,{bin_str}\" download=\"{bin_file}\">{file_label}</a>'\n href = f'<a href=\"data:application/octet-stream;base64,{bin_str}\" download=\"{os.path.basename(bin_file)}\">{file_label}</a>'\n return href\n\n# Download Excel Files\ndef get_excel_file_downloader_html(data, file_label='File'):\n bin_str = base64.b64encode(data).decode()\n # bin_str = base64.b64encode(data)\n # href = f'<a href=\"data:application/octet-stream;base64,{bin_str}\" download=\"{bin_file}\">{file_label}</a>' \n # href = f'<a href=\"data:application/octet-stream;base64,{bin_str}\" download=\"{file_label}\">{file_label}</a>'\n href = f'<a href=\"data:file/xlsx;base64,{bin_str}\" download=\"{file_label}\">{file_label}</a>'\n # href = f'<a href=\"data:file/xlsx;base64,{b64}\" download=\"new_file.{extension}\">Download {extension}</a>'\n return href\n\ndef reme(df,budget_df,X_full,factor, project_group_feature, protect_group_class):\n budget_df['adj_lower'] = budget_df['predicted'] - factor * budget_df['pred_stderr']\n\n # Adjust protect group pay only, others set to original pay\n budget_df['adj_salary'] = budget_df['original']\n budget_df.loc[(budget_df[project_group_feature] == protect_group_class) & (budget_df['original'] < budget_df['adj_lower']),'adj_salary'] = budget_df['adj_lower']\n \n # Recalculate pay gap and p value with adjusted salary\n \n x_dis = copy.deepcopy(X_full)\n y_dis = copy.deepcopy(budget_df['adj_salary'])\n \n model = sm.OLS(y_dis, x_dis)\n results = model.fit()\n \n# budget_df['adj_salary'].to_excel('reme_y.xlsx')\n# X_full.to_excel('reme_x.xlsx')\n \n # df_result = results.summary2().tables[1]\n # df_result.reset_index(level=0, inplace=True)\n # df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n # df_result.to_excel('reme_result.xlsx')\n \n# asdf\n \n budget = np.sum(np.exp(budget_df['adj_salary']) - np.exp(budget_df['original']))\n budget_df['S_Salary'] = np.trunc(np.exp(budget_df['original']))\n budget_df['S_Budget'] = np.trunc(np.exp(budget_df['adj_salary']))-np.trunc(np.exp(budget_df['original']))\n budget_df['S_Adjusted'] = np.trunc(np.exp(budget_df['adj_salary']))\n budget_df['S_AdjInd'] = 0\n budget_df.loc[budget_df['S_Budget'] >0, 'S_AdjInd']=1\n\n # Reporting\n current_total_salary = np.sum(budget_df['S_Salary'])\n Budget_PCT = budget_df['S_Budget']/np.exp(budget_df['original'])\n \n # target_position = 1\n # resulting_gap = results.params[target_position]\n # resulting_pvalues = results.pvalues[target_position]\n \n df_result = process_run_result(results)\n resulting_gap = df_result[df_result['CONTENT'] == protect_group_class]['COEF'].values[0]\n resulting_pvalues = df_result[df_result['CONTENT'] == protect_group_class]['PVALUE'].values[0]\n \n adj_count = budget_df['S_AdjInd'].sum()\n adj_average = Budget_PCT[Budget_PCT>0].mean()\n adj_max = Budget_PCT[Budget_PCT>0].max()\n adj_budget_pct = budget/current_total_salary\n \n # df_result.to_excel('run_result.xlsx')\n \n # print(resulting_gap)\n # print(resulting_pvalues) \n \n # print(results.summary())\n # print(\"***\")\n # print(\"Factor: \"+str(factor))\n # print(resulting_gap)\n # print(resulting_pvalues)\n # print(adj_count)\n # print(adj_budget_pct)\n # budget_df.to_excel('check_final_budget.xlsx')\n # asdf\n\n return budget_df, budget, resulting_gap, resulting_pvalues, adj_count, adj_budget_pct, results, x_dis, y_dis\n\ndef process_run_result(results):\n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n \n df_result = df_result[(df_result['CONTENT'].str.contains(\"GENDER\")==True) | (df_result['CONTENT'].str.contains(\"ETHNICITY\")==True)]\n \n df_result = df_result[['CONTENT','Coef.','P>|t|']]\n df_result.columns = ['CONTENT','COEF','PVALUE']\n # df_result_gender['GENDER'] = df_result_gender['CONTENT']\n df_result['CONTENT'] = df_result['CONTENT'].str.replace(\"[\",\"\")\n df_result['CONTENT'] = df_result['CONTENT'].str.replace(\"]\",\"\")\n \n df_result['FEATURE'] = 'GENDER'\n df_result.loc[(df_result['CONTENT'].str.contains(\"ETHNICITY\")==True),'FEATURE'] = 'ETHNICITY'\n df_result['CONTENT'] = df_result['CONTENT'].str.split('.').str[-1]\n df_result['CONTENT_DISPLAY'] = df_result.apply(lambda x: gender_name_replace(text=x['CONTENT']),axis=1)\n df_result = df_result[~((df_result['CONTENT_DISPLAY']=='Unknown') | (df_result['CONTENT_DISPLAY']=='unknown'))]\n df_result[\"STAT_COUNT\"]=0\n df_result.loc[((df_result['PVALUE']<=0.05) & (df_result['COEF']<0)) ,\"STAT_COUNT\"] = 1\n \n # df_result.to_excel('run_result.xlsx')\n # asdf\n \n return df_result\n # df_result = df_result.drop(columns=['CONTENT'])\n # df_result['COEF_DISPLAY'] = df_result['COEF']\n # df_result.to_excel('run_result.xlsx')\n\[email protected]_memo(show_spinner=False)\n# Run Goal Seek for insignificant gap and 0 gap\ndef reme_gap_seek(df,budget_df,X_full, project_group_feature, protect_group_class, seek_goal, current_pvalue, current_gap, search_step = -0.001):\n factor_range = np.arange(2, -2,search_step)\n threshold = 0.0005\n \n # seek_budget_df = np.nan\n seek_budget_df = pd.DataFrame()\n seek_budget = np.nan\n seek_resulting_gap = np.nan\n seek_resulting_pvalues = np.nan\n seek_adj_count = np.nan\n seek_adj_budget_pct = np.nan\n seek_pass = False\n seek_success = False\n \n if current_gap>=0:\n print('current gap is already >= 0')\n seek_pass = False\n seek_success = False\n seek_resulting_gap = current_gap\n else:\n seek_pass = True\n for factor in factor_range:\n budget_df, budget, resulting_gap, resulting_pvalues, adj_count, adj_budget_pct, results, x_dis, y_dis = reme(df,budget_df,X_full,factor, project_group_feature, protect_group_class)\n\n if np.abs(resulting_gap-seek_goal)<=threshold:\n seek_budget_df = budget_df\n seek_budget = budget\n seek_resulting_gap = resulting_gap\n seek_resulting_pvalues = resulting_pvalues\n seek_adj_count = adj_count\n seek_adj_budget_pct = adj_budget_pct\n seek_success = True\n\n print('Found factor that close gap:' + str(factor))\n print('Final Gap is '+str(seek_resulting_gap))\n print('Final p_value is '+str(seek_resulting_pvalues))\n print('Final Budget is '+str(seek_budget))\n print('Final Budget % '+str(seek_adj_budget_pct))\n \n keep_list = ['EEID','S_Budget','S_Adjusted']\n seek_budget_df = seek_budget_df[keep_list]\n seek_budget_df.columns=['EEID','SCENARIO_B_ADJUSTMENT','SCENARIO_B_ADJUSTED_SALARY']\n # seek_budget_df = seek_budget_df.merge(df,on='EEID',how='inner')\n seek_budget_df.to_excel('budget_gap.xlsx')\n df_result = process_run_result(results)\n df_result.to_excel('zero_gap_result.xlsx')\n break\n\n if seek_budget == np.nan:\n print('no result found')\n seek_success = False\n \n return seek_budget_df,seek_budget,seek_resulting_gap,seek_resulting_pvalues,seek_adj_count, seek_adj_budget_pct,seek_pass,seek_success\n \[email protected]_memo(show_spinner=False)\n# Run Goal Seek for insignificant gap and 0 gap\ndef reme_pvalue_seek(df,budget_df,X_full, project_group_feature, protect_group_class, seek_goal, current_pvalue, current_gap, input_df_result, count_loop, search_step= -0.005):\n \n factor_range = np.arange(2, -2,search_step)\n threshold = 0.0005\n \n # seek_budget_df = np.nan\n seek_budget_df = pd.DataFrame()\n seek_budget = np.nan\n seek_resulting_gap = np.nan\n seek_resulting_pvalues = np.nan\n seek_adj_count = np.nan\n seek_adj_budget_pct = np.nan\n seek_pass = False\n seek_success = False\n \n if (current_pvalue>=0.05) | (current_gap>0):\n print('Current P value already greater than 5%: '+str(current_pvalue))\n print('Or Current gap already greater than 0%: '+str(current_gap))\n seek_pass = False\n seek_success = False\n seek_budget_df = copy.deepcopy(budget_df)\n seek_budget = 0\n seek_resulting_gap = current_gap\n seek_resulting_pvalues = current_pvalue\n seek_adj_count = 0\n seek_adj_budget_pct = 0\n df_result = copy.deepcopy(input_df_result)\n else:\n seek_pass = True\n for factor in factor_range:\n result_budget_df, result_budget, resulting_gap, resulting_pvalues, adj_count, adj_budget_pct, results, x_dis, y_dis = reme(df,budget_df,X_full,factor, project_group_feature, protect_group_class)\n\n # if np.abs(resulting_pvalues-seek_goal)<=threshold:\n if resulting_pvalues>=seek_goal:\n seek_budget_df = copy.deepcopy(result_budget_df)\n seek_budget = result_budget\n seek_resulting_gap = resulting_gap\n seek_resulting_pvalues = resulting_pvalues\n seek_adj_count = adj_count\n seek_adj_budget_pct = adj_budget_pct\n seek_success = True\n\n print('Found factor that close pvalue:' + str(factor))\n print('Final Gap is '+str(seek_resulting_gap))\n print('Final p_value is '+str(seek_resulting_pvalues))\n print('Final Budget is '+str(seek_budget))\n print('Final Budget % '+str(seek_adj_budget_pct))\n\n # keep_list = ['EEID','S_Budget','S_Adjusted']\n # seek_budget_df = seek_budget_df[keep_list]\n scenario_ind_name = 'SCENARIO_B_IND_'+str(count_loop)+\"_\"+protect_group_class\n scenario_increase_name = 'SCENARIO_B_BUDGET_'+str(count_loop)+\"_\"+protect_group_class\n scenario_adjusted_name = 'SCENARIO_B_ADJUSTED_SALARY_'+str(count_loop)+\"_\"+protect_group_class\n scenario_adjusted_log_name = 'LOG_SCENARIO_B_ADJUSTED_SALARY_'+str(count_loop)+\"_\"+protect_group_class\n \n seek_budget_df[scenario_ind_name]=seek_budget_df['S_AdjInd']\n seek_budget_df[scenario_increase_name]=seek_budget_df['S_Budget']\n seek_budget_df[scenario_adjusted_name]=seek_budget_df['S_Adjusted']\n seek_budget_df[scenario_adjusted_log_name]=seek_budget_df['adj_salary']\n # seek_budget_df.columns=['EEID','SCENARIO_A_ADJUSTMENT','SCENARIO_A_ADJUSTED_SALARY']\n \n seek_budget_df['original'] = seek_budget_df['adj_salary']\n # seek_budget_df = seek_budget_df.merge(df,on='EEID',how='inner')\n seek_budget_df.to_excel('budget_pv.xlsx')\n df_result = process_run_result(results)\n df_result.to_excel('pvalue_result.xlsx')\n \n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n df_result.to_excel('pv_result.xlsx')\n \n x_dis.to_excel('pv_x_dis.xlsx')\n y_dis.to_excel('pv_y_dis.xlsx')\n \n break\n\n if seek_budget == np.nan:\n print('no result found')\n seek_success = False\n \n return seek_budget_df,seek_budget,seek_resulting_gap,seek_resulting_pvalues,seek_adj_count, seek_adj_budget_pct,seek_pass,seek_success,df_result\n\n# def exam_col(file_path,display_path):\n# message = \"\"\n# df['Data2'].replace(r'^\\s*$', np.nan, regex=True).isna().all()\n\ndef run(data=None, df_gender_name=None, req_list=None, ci = 0.95):\n # 1.1 Setup ************************************\n company_name = 'Client Name'\n version = 'Base Pay'\n starting_salary_flag = 'N'\n target = 'SALARY'\n\n # Setup error message to display on UI\n error_message = {}\n warning_message = {}\n exclude_col = []\n \n # Read Data\n try:\n df = data\n except:\n error_file_read = \"Unable to read submission file, Please download and update data template again\"\n error_message['File_Read'] = error_file_read\n\n df = rename_column(df)\n \n df_type = df.iloc[0]\n df = df.iloc[1:]\n \n # 2.1 Data Cleaning ****************************\n # Data Validation\n df['VALIDATION_MESSAGE']=\"\"\n df['VALIDATION_FLAG']=0\n # Snapshot Date\n snapshot = np.nan\n try:\n df['SNAPSHOT_DATE'] = df['SNAPSHOT_DATE'].astype(\"string\")\n snapshot = df['SNAPSHOT_DATE'].mode().tolist()[0]\n except:\n print('date exception')\n snapshot = date.today()\n error_snapshot = \"Invalid snapshot date, Please check submission format is mm/dd/yyyy in data template\"\n error_message['SNAPSHOT_DATE'] = error_snapshot\n df['NOW'] = pd.to_datetime(snapshot)\n \n # 2.2 Clean up All features ******************\n df,warning_message = clean_req_feature(data = df,feature = \"EEID\",valid_feature_list=[],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"GENDER\",valid_feature_list=[\"F\",\"M\",\"N\",\"U\",\"O\"],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"SALARY\",valid_feature_list=[],warning_message = warning_message, data_type='numeric')\n df,warning_message = clean_req_feature(data = df,feature = \"JOB_LEVEL_OR_COMP_GRADE\",valid_feature_list=[],warning_message = warning_message, data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"JOB_FUNCTION\",valid_feature_list=[],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"COUNTRY\",valid_feature_list=[],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"LOCATION\",valid_feature_list=[],warning_message = warning_message,data_type=\"string\")\n df,warning_message = clean_req_feature(data = df,feature = \"FULL_TIME\",valid_feature_list=[\"Y\",\"N\"],warning_message = warning_message,data_type=\"string\")\n\n # Clean up customized features\n standard_col = req_list\n all_col = df.columns.tolist()\n cust_col = [x for x in all_col if x not in standard_col]\n df_type = pd.DataFrame(df_type).reset_index()\n df_type.columns = ['COL_NAME','TYPE']\n df_type = df_type[~df_type['COL_NAME'].isin(standard_col)]\n for i, row in df_type.iterrows():\n df,warning_message, exclude_col = clean_optional_feature(data = df,feature = row['COL_NAME'],valid_feature_list=[],warning_message = warning_message,exclude_col = exclude_col, data_type=row['TYPE'])\n \n # Record Message\n df_org = df.copy()\n # df_org.to_excel('Data\\data_validate.xlsx')\n before_clean_record = df_org.shape[0]\n \n df = df_org[df_org['VALIDATION_MESSAGE']==\"\"]\n after_clean_record=df.shape[0]\n \n df_validation = df_org[df_org['VALIDATION_MESSAGE']!=\"\"]\n list_validation = [x for x in df_validation.columns.tolist() if x not in ['VALIDATION_MESSAGE','VALIDATION_FLAG','NOW']]\n list_validation = ['VALIDATION_MESSAGE']+list_validation\n df_validation = df_validation[list_validation]\n \n warning_message['OVERVIEW'] = \"OVERVIEW:Successfully run \"+str(after_clean_record)+\" out of \"+str(before_clean_record)+\" records\"\n message = pd.DataFrame.from_dict(warning_message,orient='index')\n message.columns=['NAME']\n message = message['NAME'].str.split(\":\",expand = True)\n message.columns=['NAME','Message']\n message = message['Message']\n \n # 2.3 Feature Engineering ****************************\n # df_saveID = df['EEID']\n # df = df.set_index('EEID', drop=True)\n # col_list=df.columns.tolist()\n filter_list = [x for x in df.columns.tolist() if x not in exclude_col]\n df = df[filter_list]\n col_list=df.columns.tolist()\n \n print(exclude_col)\n print(filter_list)\n extra = ['VALIDATION_MESSAGE', 'VALIDATION_FLAG', 'NOW']\n exclude_feature = exclude_col \n include_feature = [x for x in filter_list if x not in extra]\n \n # Calculate Age and Tenure\n try:\n df['AGE'] = np.ceil((df['NOW'] - df['DATE_OF_BIRTH']).dt.days/365)\n except:\n print('AGE: Calculation error')\n try:\n df['TENURE'] = np.ceil((df['NOW'] - df['DATE_OF_HIRE']).dt.days/365)\n except:\n print('TENURE: Calculation error')\n \n numeric_columns = ['SALARY','AGE', 'TENURE']\n if 'AGE' not in col_list:\n numeric_columns.remove('AGE')\n if 'TENURE' not in col_list:\n numeric_columns.remove('TENURE')\n \n # Include customized columns\n numeric_columns_customized = []\n for i, row in df_type.iterrows():\n if row['TYPE'] == 'numeric':\n numeric_columns_customized.append(row['COL_NAME'])\n \n numeric_columns_customized_include = [x for x in numeric_columns_customized if x in include_feature]\n numeric_columns.extend(numeric_columns_customized_include)\n numeric_columns = list(set(numeric_columns))\n \n for c in numeric_columns:\n df.loc[df[c]=='na', c] = np.nan\n df[c] = pd.to_numeric(df[c])\n \n # df.to_excel('edu.xlsx')\n \n # %% Convert string columns to categories\n category_columns = [x for x in col_list if x not in numeric_columns]\n print(category_columns)\n for c in category_columns:\n df[c] = df[c].astype(str).str.strip().astype('category')\n \n feature = []\n baseline = []\n \n df['LOG_SALARY'] = np.log(df['SALARY'])\n\n # Default to category level w/ highest n-count\n cat_cols = list(df.select_dtypes(['category']).columns)\n for x in cat_cols:\n drop_cate = df[x].value_counts().index.tolist()[0]\n #Set Manually\n if x=='GENDER':\n print('Override! Gender',\"level dropped:\",'M')\n drop_cate = 'M'\n df[x] = set_dropped_category(df[x], drop_cate)\n feature.append(x)\n baseline.append(drop_cate)\n\n df_baseline = pd.DataFrame({'Features': feature,'Baseline': baseline})\n print('\\n')\n print(df_baseline.to_markdown())\n \n # 3 Gender Modeling - Linear Regression ****************************\n col_list = df.columns\n \n # Remove all excess columns\n add_exclude_col = ['EEID','SALARY','SNAPSHOT_DATE', 'VALIDATION_MESSAGE', 'VALIDATION_FLAG', 'NOW','DATE_OF_BIRTH','DATE_OF_HIRE']\n add_exclude_col_predict = add_exclude_col+['GENDER','ETHNICITY']\n exclude_col = exclude_col+add_exclude_col\n exclude_col_predict = exclude_col+add_exclude_col_predict\n\n model_col = [x for x in col_list if x not in exclude_col]\n model_col_predict = [x for x in col_list if x not in exclude_col_predict]\n \n # Factors\n f_raw = 'LOG_SALARY ~ GENDER'\n f_discover = model_col[-1] + ' ~ ' + ' + '.join(map(str, model_col[0:len(model_col)-1]))\n f_predict= model_col[-1] + ' ~ ' + ' + '.join(map(str, model_col_predict[0:len(model_col_predict)-1]))\n \n print(f_raw)\n print(f_discover)\n print(f_predict)\n \n # Gender Raw Gap\n y_raw, x_raw = dmatrices(f_raw, df, return_type='dataframe')\n model_raw = sm.OLS(y_raw, x_raw)\n results = model_raw.fit()\n\n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n\n r2_raw = results.rsquared\n r2_adj = results.rsquared_adj\n\n female_coff_raw = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['Coef.'].tolist()[0]\n female_pvalue_raw = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['P>|t|'].tolist()[0]\n \n # Gender Net Gap\n y_dis, x_dis = dmatrices(f_discover, df, return_type='dataframe')\n model_dis = sm.OLS(y_dis, x_dis)\n results = model_dis.fit()\n df_result = results.summary2().tables[1]\n df_result.reset_index(level=0, inplace=True)\n df_result = df_result.rename(columns={\"index\":\"CONTENT\"})\n y_dis.to_excel('y_dis.xlsx')\n x_dis.to_excel('x_dis.xlsx')\n df_result.to_excel('dis_model.xlsx')\n \n# temp_y = pd.read_excel(r'pv_y_dis.xlsx')\n# print(temp_y.head(3))\n# temp_y['EEID'] = temp_y['EEID'].astype(str)\n \n# df2 = copy.deepcopy(df)\n# df2 = df2.merge(temp_y, on = 'EEID', how = 'left')\n \n# # df2['LOG_SALARY_TEMPY'] = temp_y['adj_salary']\n# df2['LOG_SALARY_ORG'] = df2['LOG_SALARY']\n# df2['LOG_SALARY'] = df2['adj_salary']\n \n# # df2.loc[df2['GENDER']=='F','LOG_SALARY'] = df2['LOG_SALARY']-3\n# y_dis2, x_dis2 = dmatrices(f_discover, df2, return_type='dataframe')\n# model_dis2 = sm.OLS(y_dis2, x_dis2)\n# results2 = model_dis2.fit()\n# df_result2 = results2.summary2().tables[1]\n# df_result2.reset_index(level=0, inplace=True)\n# df_result2 = df_result2.rename(columns={\"index\":\"CONTENT\"})\n# y_dis2.to_excel('y_dis2.xlsx')\n# x_dis2.to_excel('x_dis2.xlsx')\n# df_result2.to_excel('dis_model2.xlsx')\n# df2.to_excel('df2.xlsx')\n \n# asdf\n \n r2 = results.rsquared\n r2_adj = results.rsquared_adj\n\n female_coff = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['Coef.'].tolist()[0]\n female_pvalue = df_result.loc[df_result['CONTENT']==\"GENDER[T.F]\"]['P>|t|'].tolist()[0]\n \n nonb_coff = df_result.loc[df_result['CONTENT']==\"GENDER[T.N]\"]['Coef.'].tolist()[0]\n nonb_pvalue = df_result.loc[df_result['CONTENT']==\"GENDER[T.N]\"]['P>|t|'].tolist()[0]\n \n # Gender Net Gap - Prediciton\n y_predict, x_predict = dmatrices(f_predict, df, return_type='dataframe')\n model_predict = sm.OLS(y_predict, x_predict)\n results_predict = model_predict.fit()\n\n y_pred = results_predict.predict(x_predict)\n std, lower, upper = wls_prediction_std(results_predict,alpha=0.05)\n std_view,lower_view, upper_view = wls_prediction_std(results_predict,alpha=1-ci)\n ci_view_lower = \"Lower_CI\"+str(int(ci*100))\n ci_view_upper = \"Upper_CI\"+str(int(ci*100))\n \n print(ci_view_upper)\n \n# std_90, lower_90, upper_90 = wls_prediction_std(results_predict,alpha=0.10)\n# std_85, lower_85, upper_85 = wls_prediction_std(results_predict,alpha=0.15)\n# std_80, lower_80, upper_80 = wls_prediction_std(results_predict,alpha=0.20)\n# std_75, lower_75, upper_75 = wls_prediction_std(results_predict,alpha=0.25)\n# std_70, lower_70, upper_70 = wls_prediction_std(results_predict,alpha=0.30)\n \n # Save budget file for prediction\n X_full = x_dis \n \n if 'ETHNICITY' in include_feature:\n budget_df = pd.DataFrame({'EEID':df['EEID'], 'original_before': df['LOG_SALARY'], 'original': df['LOG_SALARY'], 'GENDER': df['GENDER'],'ETHNICITY': df['ETHNICITY'], 'predicted':y_pred,'pred_lower': lower, 'pred_upper': upper, 'pred_stderr': std})\n else:\n budget_df = pd.DataFrame({'EEID':df['EEID'], 'original_before': df['LOG_SALARY'], 'original': df['LOG_SALARY'], 'GENDER': df['GENDER'],'predicted':y_pred,'pred_lower': lower, 'pred_upper': upper, 'pred_stderr': std})\n predict_df = pd.DataFrame({'EEID':df['EEID'] ,'Predicted Salary':np.trunc(np.exp(y_pred)), 'Lower_CI95': np.trunc(np.exp(lower)), 'Upper_CI95': np.trunc(np.exp(upper)), ci_view_lower: np.trunc(np.exp(lower_view)), ci_view_upper: np.trunc(np.exp(upper_view))})\n \n# X_full.to_excel('xfull.xlsx')\n# df.to_excel('check_final.xlsx')\n budget_df.to_excel('check_final_budget.xlsx')\n predict_df.to_excel('check_final_predict.xlsx')\n \n # r2 = 0.91\n # Graphs\n # fig_r2_gender_gap = plot_full_pie(r2,'r2')\n # fig_r2_gender_gap = plot_r2(r2)\n # fig_raw_gender_gap = plot_gender_gap(female_coff)\n # fig_net_gender_gap = plot_gender_gap(female_coff)\n \n # Statistics for output\n hc_female = df[(df['GENDER']=='F') | (df['GENDER']=='FEMALE')].shape[0]\n avg_pay = df['SALARY'].mean()\n \n # Result Table\n df_result.to_excel('result_regression.xlsx')\n \n # Result Gender Table\n df_result_gender = df_result[df_result['CONTENT'].str.contains(\"GENDER\")==True]\n df_result_gender = df_result_gender[['CONTENT','Coef.','P>|t|']]\n df_result_gender.columns = ['CONTENT','COEF','PVALUE']\n df_result_gender['GENDER'] = df_result_gender['CONTENT']\n df_result_gender['GENDER'] = df_result_gender['GENDER'].str.replace(\"[\",\"\")\n df_result_gender['GENDER'] = df_result_gender['GENDER'].str.replace(\"]\",\"\")\n df_result_gender['GENDER'] = df_result_gender['GENDER'].str.split('.').str[-1]\n df_result_gender = df_result_gender.drop(columns=['CONTENT'])\n df_result_gender['COEF_DISPLAY'] = df_result_gender['COEF']\n df_result_gender['STAT'] = \"No\"\n df_result_gender['STAT_COUNT'] = 0\n df_result_gender.loc[df_result_gender['PVALUE']<=0.05,\"STAT\"] = \"Yes\"\n df_result_gender.loc[((df_result_gender['PVALUE']<=0.05) & (df_result_gender['COEF']<0)) ,\"STAT_COUNT\"] = 1\n df_result_gender = df_result_gender.sort_values(by=['COEF_DISPLAY'], ascending=False)\n baseline_row = pd.DataFrame({'GENDER':'M', 'COEF':0, 'COEF_DISPLAY':0,'PVALUE':1,'STAT':\"No\",'STAT_COUNT':0},index =[0])\n df_result_gender = pd.concat([baseline_row, df_result_gender[:]]).reset_index(drop = True)\n df_result_gender['GENDER'] = df_result_gender.apply(lambda x: gender_name_replace(text=x['GENDER']),axis=1)\n df_result_gender = df_result_gender[~((df_result_gender['GENDER']=='Unknown') | (df_result_gender['GENDER']=='unknown'))]\n df_result_gender = df_result_gender.reset_index(drop=True)\n df_result_gender.to_excel('result_gender.xlsx')\n fig_gender_bar = plot_bar(df_result_gender,'GENDER')\n \n # Result Ethnicity Table\n df_result_eth = df_result[df_result['CONTENT'].str.contains(\"ETHNICITY\")==True]\n df_result_eth = df_result_eth[['CONTENT','Coef.','P>|t|']]\n df_result_eth.columns = ['CONTENT','COEF','PVALUE']\n df_result_eth['ETHNICITY'] = df_result_eth['CONTENT']\n df_result_eth['COEF_DISPLAY'] = df_result_eth['COEF']\n df_result_eth['STAT'] = \"No\"\n df_result_eth['STAT_COUNT'] = 0\n df_result_eth.loc[df_result_eth['PVALUE']<=0.05,\"STAT\"] = \"Yes\"\n df_result_eth.loc[((df_result_eth['PVALUE']<=0.05) & (df_result_eth['COEF']<0)),\"STAT_COUNT\"] = 1\n df_result_eth = df_result_eth.sort_values(by=['COEF_DISPLAY'], ascending=False)\n df_result_eth['ETHNICITY'] = df_result_eth['ETHNICITY'].str.replace(\"[\",\"\")\n df_result_eth['ETHNICITY'] = df_result_eth['ETHNICITY'].str.replace(\"]\",\"\")\n df_result_eth['ETHNICITY'] = df_result_eth['ETHNICITY'].str.split('.').str[-1]\n df_result_eth = df_result_eth.drop(columns=['CONTENT'])\n df_result_eth = df_result_eth.reset_index(drop=True)\n baseline_eth = df['ETHNICITY'].value_counts()\n # baseline_eth.to_excel('baseline_eth.xlsx')\n # print(baseline_eth.index[0])\n baseline_row = pd.DataFrame({'ETHNICITY':baseline_eth.index[0], 'COEF':0, 'COEF_DISPLAY':0,'PVALUE':1,'STAT':\"No\",'STAT_COUNT':0},index =[0])\n df_result_eth = pd.concat([baseline_row, df_result_eth[:]]).reset_index(drop = True)\n df_result_eth = df_result_eth[~((df_result_eth['ETHNICITY']=='Unknown') | (df_result_eth['ETHNICITY']=='unknown'))]\n eth_baseline = df_result_eth['ETHNICITY'][0]\n df_result_eth.to_excel('result_eth.xlsx')\n fig_eth_bar = plot_bar(df_result_eth,'ETHNICITY')\n \n # Result All Table\n df_initial_result = process_run_result(results)\n df_initial_result.to_excel('initial_result.xlsx')\n \n # Gender Table\n df_gender = df.pivot_table(index=['GENDER'],values=['EEID','SALARY'],aggfunc={'EEID':'count','SALARY':'mean'},fill_value=np.nan)\n df_gender.columns = ['_'.join(col).strip() for col in df_gender.columns.values]\n df_gender = df_gender.reset_index()\n df_gender.columns = ['GENDER','HC','AVG_PAY']\n df_gender = df_gender.merge(df_gender_name,on='GENDER',how='left')\n df_gender = df_gender.sort_values(by=['HC'],ascending=False)\n \n df_gender_female_pay = df[df['GENDER'] == 'F']\n df_gender_nonb_pay = df[df['GENDER'] == 'N']\n \n gender_female_pay = df_gender_female_pay['SALARY'].mean()\n gender_nonb_pay = df_gender_nonb_pay['SALARY'].mean()\n \n # df_gender_minor_pay.to_excel('gender.xlsx')\n fig_gender_hc = plot_gender_donut(df_gender)\n \n # Ethnicity Table\n # plt.clf()\n df_eth = None\n eth_minor_pay = None\n if 'ETHNICITY' in include_feature:\n df_eth = df.pivot_table(index=['ETHNICITY'],values=['EEID','SALARY'],aggfunc={'EEID':'count','SALARY':'mean'},fill_value=np.nan)\n df_eth.columns = ['_'.join(col).strip() for col in df_eth.columns.values]\n df_eth = df_eth.reset_index()\n df_eth.columns = ['ETHNICITY_NAME','HC','AVG_PAY']\n df_eth = df_eth.sort_values(by=['HC'],ascending=False)\n fig_eth_hc = plot_eth_donut(data = df_eth)\n df_eth_minor_pay = df[df['ETHNICITY'] != df_eth['ETHNICITY_NAME'][0]]\n eth_minor_pay = df_eth_minor_pay['SALARY'].mean()\n # df_eth_minor_pay.to_excel('eth.xlsx')\n \n # df_gender = df_gender.drop(columns=['GENDER'])\n # df_gender.to_excel('gender.xlsx')\n # df.to_excel('gender.xlsx')\n # print(message.loc[['OVERVIEW']]['Message'])\n \n return df, df_org, df_validation, message, exclude_col, r2_raw, female_coff_raw, female_pvalue_raw, r2, female_coff, female_pvalue, before_clean_record, after_clean_record,hc_female,X_full,budget_df,exclude_feature, include_feature,df_gender, df_eth, fig_gender_hc,fig_eth_hc, avg_pay, gender_female_pay, gender_nonb_pay, eth_minor_pay,fig_gender_bar, fig_eth_bar, df_result_gender, df_result_eth,eth_baseline, df_initial_result, predict_df, ci_view_lower, ci_view_upper\n\ndef display_rename(display_map,feature):\n return [display_map.get(item,item) for item in feature]\n\n# def analysis(df_submit, run_demo, file_path, display_path, main_page, main_page_info, ci):\ndef analysis(df_submit, run_demo, file_path, display_path, main_page, main_page_info):\n # Process df (not demo datafile) \n # with st.spinner('Running analysis, Please wait for it...'):\n m_info = main_page_info.success('Reading Data')\n if run_demo == True:\n # Demo Run\n df = pd.read_excel(file_path,sheet_name=\"Demo Data\")\n else:\n df = pd.read_excel(df_submit,sheet_name=\"Submission\") \n\n # Convert program column names to display\n df_name = pd.read_excel(display_path,sheet_name=\"Standard_Col\")\n df_cus_name = pd.read_excel(display_path,sheet_name=\"Custom_Col\")\n df_gender_name = pd.read_excel(display_path,sheet_name=\"Gender\")\n\n # Run Checking \n df_check = df.iloc[1:]\n full_list = df_name['PROGRAM_NAME'].tolist()\n full_list_display = df_name['DISPLAY_NAME'].tolist()\n\n req_list = df_name[df_name['REQUIRE']==1]['PROGRAM_NAME'].tolist()\n # req_list_display = df_name[df_name['REQUIRE']==1]['DISPLAY_NAME'].tolist()\n cus_list = df_cus_name['PROGRAM_NAME'].tolist()\n display_map = dict(zip(full_list, full_list_display))\n display_inv_map = dict(zip(full_list_display, full_list))\n\n inc_list = []\n exc_list = []\n\n for col in df_check.columns.tolist():\n if df_check[col].replace(r'^\\s*$', np.nan, regex=True).isna().all():\n # if df_check[col].isna():\n exc_list.append(col)\n else:\n inc_list.append(col)\n\n error_req_list = [x for x in req_list if x not in inc_list]\n error_req_message=\"\"\n if len(error_req_list) != 0:\n error_req_message = 'The requested data field below has not been provided: '+ ', '.join(error_req_list)+'. Please update and resubmit the template.'\n \n final_req_list = [x for x in req_list if x not in ['EEID','SALARY']]\n display_req_list = display_rename(display_map,final_req_list)\n\n final_optional_list = [x for x in inc_list if x not in (req_list+cus_list+['SNAPSHOT_DATE'])]\n display_optional_list = display_rename(display_map,final_optional_list)\n\n # Display selection Step 3\n config = main_page.form(\"Configuration\")\n with config:\n config.write(\"Step 3. Confirm Selected Configuration\")\n ci_select, optional_select, req_select, = config.columns((0.5, 1, 1)) \n ci = ci_select.slider(label = 'A: Choose fair pay confidence internal %', value = 95, min_value = 70, max_value = 99, step = 1, help='Setting at 95% means I want to have a pay range so that 95% of the time, the predicted pay falls inside.')\n ci = ci/100\n optional_col = optional_select.multiselect(label = 'C: Select Optional Pay Factors',options=display_optional_list,default=display_optional_list,disabled=False)\n req_col = req_select.multiselect(label = 'B: Required Pay Factors',options=display_req_list,default=display_req_list,disabled=True)\n submitted_form = config.form_submit_button(\"🚀 Confirm to Run Analysis'\")\n\n # Final Filter on pay driver selection\n optional_col_select = display_rename(display_inv_map,optional_col)\n req_list = ['SNAPSHOT_DATE'] + req_list\n final_col_select = req_list + optional_col_select\n df = df[final_col_select]\n \n print('inc: ')\n print(inc_list)\n print('exc: ')\n print(exc_list)\n print('req: ')\n print(req_list)\n print('cus: ')\n print(cus_list)\n print('error message req: ')\n print(error_req_message)\n print('display req')\n print(display_req_list)\n print('display optional')\n print(display_optional_list)\n print('display system run optional')\n print(optional_col_select)\n\n # st.stop()\n\n if submitted_form:\n # st.write(optional_col_select)\n # st.write(final_col_select)\n # st.write(df.columns.tolist())\n display_map = dict(zip(df_name['PROGRAM_NAME'], df_name['DISPLAY_NAME']))\n \n # Run discovery model:\n m_info = main_page_info.success('Running Gap Analysis')\n df, df_org, df_validation, message, exclude_col, r2_raw, female_coff_raw, female_pvalue_raw, r2, female_coff, female_pvalue, before_clean_record, after_clean_record,hc_female,X_full,budget_df,exclude_feature, include_feature,df_gender,df_eth,fig_gender_hc,fig_eth_hc,avg_pay, gender_female_pay, gender_nonb_pay, eth_minor_pay,fig_gender_bar, fig_eth_bar,df_result_gender, df_result_eth, eth_baseline, df_initial_result, predict_df, ci_view_lower, ci_view_upper = run(df,df_gender_name,req_list,ci) \n \n # st.write(df.columns.tolist())\n # , fig_gender_bar\n # ,fig_eth_hc\n print('pvalue'+str(female_pvalue))\n gender_gap_format = str(round(female_coff*100,0))+'%'\n gender_gap_stats = '**NOT** statistically significant'\n if female_pvalue<0.05:\n gender_gap_stats = 'statistically significant'\n\n # Run Reme Pvalue = 7%\n \n# df_result = copy.deepcopy(df_initial_result)\n# count_loop = 0\n# count_reme = 0\n# reme_exit = 0\n# seek_budget_df_pv = copy.deepcopy(budget_df)\n \n# while df_result['STAT_COUNT'].sum()>0:\n# # print('count_loop: '+str(count_loop))\n# df_result_loop = zip(df_result['CONTENT'].to_list(), df_result['FEATURE'].to_list(), df_result['COEF'].to_list(), df_result['PVALUE'].to_list())\n \n# for protect_group_class, project_group_feature,init_current_gap,init_current_pvalue in df_result_loop:\n# # print('count_reme: '+str(count_reme))\n# m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk - '+ project_group_feature + ' - '+ protect_group_class)\n# if count_reme == 0:\n# current_gap = init_current_gap\n# current_pvalue = init_current_pvalue\n# else:\n# current_gap = df_result[df_result['CONTENT']==protect_group_class]['COEF'].values[0]\n# current_pvalue = df_result[df_result['CONTENT']==protect_group_class]['PVALUE'].values[0]\n\n# seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature=project_group_feature, protect_group_class=protect_group_class, seek_goal=0.07, current_gap = current_gap, current_pvalue = current_pvalue, input_df_result = df_result, count_loop = count_loop, search_step = -0.001)\n \n# pv_budget_name = 'pv_budget_'+str(count_loop)+'_'+protect_group_class+'.xlsx'\n# pv_result_name = 'pv_result_'+str(count_loop)+'_'+protect_group_class+'.xlsx'\n \n# seek_budget_df_pv.to_excel(pv_budget_name)\n# df_result.to_excel(pv_result_name)\n \n# count_reme = count_reme + 1\n# print('count_reme: '+str(count_reme))\n# if df_result['STAT_COUNT'].sum()==0:\n# reme_exit = 1\n# break\n# if reme_exit == 1:\n# break\n# count_loop = count_loop +1\n# print('count_loop: '+str(count_loop))\n \n# df_result_loop = zip(df_initial_result['CONTENT'].to_list(), df_initial_result['FEATURE'].to_list(), df_initial_result['COEF'].to_list(), df_initial_result['PVALUE'].to_list()) \n# seek_budget_df_pv = copy.deepcopy(budget_df)\n \n# count_reme = 0\n \n# for protect_group_class, project_group_feature,init_current_gap,init_current_pvalue in df_result_loop:\n# m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk - '+ protect_group_class)\n# if count_reme == 0:\n# current_gap = init_current_gap\n# current_pvalue = init_current_pvalue\n# else:\n# current_gap = df_result[df_result['']==]['COEF'].values[0]\n# current_pvalue = df_result[df_result['']==]['PVALUE'].values[0]\n \n# seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature=project_group_feature, protect_group_class=protect_group_class, seek_goal=0.07, current_gap = current_gap, current_pvalue = current_pvalue, search_step = -0.001)\n \n \n # seek_budget_df_pv.to_excel('df_pv_n.xlsx')\n # df_result.to_excel('df_pv_n_result.xlsx')\n \n # asdf\n \n # for \n \n# # Run Reme Pvalue = 7%\n# m_info = main_page_info.success('Running Remediation Scenario A: Mitigate Legal Risk')\n# seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv = reme_pvalue_seek(df,budget_df,X_full, project_group_feature='GENDER', protect_group_class='F', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n# seek_budget_df_pv.to_excel('df_pv.xlsx')\n\n# # Run Reme Zero Gap\n# m_info = main_page_info.success('Running Remediation Scenario B: Close Gender Gap')\n# seek_budget_df_gap,seek_budget_gap,seek_resulting_gap_gap,seek_resulting_pvalues_gap,seek_adj_count_gap, seek_adj_budget_pct_gap,seek_pass_gap, seek_success_gap = reme_gap_seek(df,budget_df,X_full, project_group_feature='GENDER', protect_group_class='F', seek_goal=0, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001) \n# seek_budget_df_gap.to_excel('df_gap.xlsx')\n \n# # Run Reme Pvalue = 7%\n# m_info = main_page_info.success('Running Remediation Scenario A: Mitigate Legal Risk')\n# seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv = reme_pvalue_seek(df,budget_df,X_full, project_group_feature='GENDER', protect_group_class='N', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n# seek_budget_df_pv.to_excel('df_pv.xlsx')\n\n# # Run Reme Zero Gap\n# m_info = main_page_info.success('Running Remediation Scenario B: Close Gender Gap')\n# seek_budget_df_gap,seek_budget_gap,seek_resulting_gap_gap,seek_resulting_pvalues_gap,seek_adj_count_gap, seek_adj_budget_pct_gap,seek_pass_gap, seek_success_gap = reme_gap_seek(df,budget_df,X_full, project_group_feature='GENDER', protect_group_class='N', seek_goal=0, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001) \n# seek_budget_df_gap.to_excel('df_gap.xlsx')\n \n # Run Reme Pvalue = 7%\n \n # m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n # seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,budget_df,X_full, project_group_feature='GENDER', protect_group_class='N', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n # seek_budget_df_pv.to_excel('df_pv_n.xlsx')\n # df_result.to_excel('df_pv_n_result.xlsx')\n \n # asdf\n \n seek_budget_df_pv = copy.deepcopy(budget_df)\n df_result = copy.deepcopy(df_initial_result)\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='GENDER', protect_group_class='F', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, input_df_result = df_result, count_loop = 0, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_female.xlsx')\n df_result.to_excel('df_pv_female_result.xlsx')\n \n asdf\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='ETHNICITY', protect_group_class='Black', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_black.xlsx')\n df_result.to_excel('df_pv_black_result.xlsx')\n \n # asdf\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='ETHNICITY', protect_group_class='Asian', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_asian.xlsx')\n df_result.to_excel('df_pv_asian_result.xlsx')\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='GENDER', protect_group_class='F', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_female_2.xlsx')\n df_result.to_excel('df_pv_female_2_result.xlsx')\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='ETHNICITY', protect_group_class='Black', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_black2.xlsx')\n df_result.to_excel('df_pv_black2_result.xlsx')\n \n # asdf\n \n m_info = main_page_info.success('Running Remediation Scenario B: Mitigate Legal Risk')\n seek_budget_df_pv,seek_budget_pv,seek_resulting_gap_pv,seek_resulting_pvalues_pv,seek_adj_count_pv, seek_adj_budget_pct_pv,seek_pass_pv, seek_success_pv, df_result = reme_pvalue_seek(df,seek_budget_df_pv,X_full, project_group_feature='ETHNICITY', protect_group_class='Asian', seek_goal=0.07, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001)\n seek_budget_df_pv.to_excel('df_pv_asian2.xlsx')\n df_result.to_excel('df_pv_asian2_result.xlsx')\n \n asdf\n\n # Run Reme Zero Gap\n m_info = main_page_info.success('Running Remediation Scenario C: Close Gender Gap')\n seek_budget_df_gap,seek_budget_gap,seek_resulting_gap_gap,seek_resulting_pvalues_gap,seek_adj_count_gap, seek_adj_budget_pct_gap,seek_pass_gap, seek_success_gap = reme_gap_seek(df,budget_df,X_full, project_group_feature='ETHNICITY', protect_group_class='Black', seek_goal=0, current_gap = female_coff, current_pvalue = female_pvalue, search_step = -0.001) \n seek_budget_df_gap.to_excel('df_gap.xlsx')\n\n # Create download file for remediation\n reme_download_flag = 0\n df_reme_org = df.drop(columns=['VALIDATION_MESSAGE', 'VALIDATION_FLAG', 'NOW','LOG_SALARY'])\n if operator.not_(seek_budget_df_pv.empty):\n df_reme_ind = seek_budget_df_pv.merge(seek_budget_df_gap,on='EEID',how='inner').merge(df_reme_org,on = 'EEID',how='inner')\n list_reme = [x for x in df_reme_ind.columns.tolist() if x not in ['EEID','GENDER','SALARY']]\n list_reme = ['EEID','GENDER','SALARY']+list_reme\n df_reme_ind = df_reme_ind[list_reme]\n reme_download_flag = 1\n elif (seek_budget_df_pv.empty) and (operator.not_(seek_budget_df_gap.empty)):\n df_reme_ind = seek_budget_df_gap.merge(df_reme_org,on = 'EEID',how='inner')\n list_reme = [x for x in df_reme_ind.columns.tolist() if x not in ['EEID','GENDER','SALARY']]\n list_reme = ['EEID','GENDER','SALARY']+list_reme\n df_reme_ind = df_reme_ind[list_reme]\n reme_download_flag = 1\n # df_reme_ind.to_excel('df_reme_ind.xlsx')\n\n # Run Remediation Messages\n message_budget_pv = np.nan\n if seek_pass_pv == False:\n message_budget_pv = '0 - gender pay gap is currently not statistically significant.'\n message_budget_pv_overview = message_budget_pv\n elif (seek_pass_pv == True) and (seek_success_pv == False):\n message_budget_pv = 'No results found, please contact our consultant for more information.'\n message_budget_pv_overview = message_budget_pv\n else:\n if seek_budget_pv> 1000000:\n message_budget_pv = str(locale.format(\"%.2f\", round(seek_budget_pv/1000000,2), grouping=True))+' Million'+'\\n'+'('+str(round(seek_adj_budget_pct_pv*100,0))+'% of Pay)'\n else:\n message_budget_pv = str(locale.format(\"%d\", round(seek_budget_pv/1000,0), grouping=True))+' K'+'\\n'+'('+str(round(seek_adj_budget_pct_pv*100,0))+'% of Pay)'\n message_budget_pv_overview = \"Raising women's pay by $\"+message_budget_pv+' will reduce gap to ' + '-2.2%' + ' and become statistically insignificant.'\n\n message_budget_gap = np.nan\n if seek_pass_gap == False:\n message_budget_gap = '0 - Women earn more than men, so no adjustment is necessary.'\n elif (seek_pass_gap == True) and (seek_success_gap == False):\n message_budget_gap = 'No results found, please contact our consultant for more information.'\n else:\n if seek_budget_gap> 1000000:\n message_budget_gap = str(locale.format(\"%.2f\", round(seek_budget_gap/1000000,2), grouping=True))+' Million'+'\\n'+'('+str(round(seek_adj_budget_pct_gap*100,2))+'% of Pay)'\n else:\n message_budget_gap = str(locale.format(\"%d\", round(seek_budget_gap/1000,0), grouping=True))+' K'+'\\n'+'('+str(round(seek_adj_budget_pct_gap*100,2))+'% of Pay)'\n\n scenario = ['Current','A','B']\n action = ['🏁 No change','✔️ Mitigate legal risk \\n'+'✔️ Reduce the gender gap to a statistical insignificant level.','✔️ Mitigate legal risk \\n'+'✔️ Completely close gender gap \\n'+'✔️ Become a market leader (Top 1%)\\n']\n budget = ['0',message_budget_pv,message_budget_gap]\n\n if abs(seek_resulting_gap_gap)<0.0005:\n seek_resulting_gap_gap = 0\n net_gap = [female_coff,seek_resulting_gap_pv,seek_resulting_gap_gap]\n net_gap = [f'{i*100:.1f}%' for i in net_gap]\n\n df_reme = pd.DataFrame({'Scenario': scenario, 'How do I do this?': action, 'What is my budget?': budget, 'What is the gap after adjustment?': net_gap})\n\n cell_hover = { # for row hover use <tr> instead of <td>\n 'selector': 'td:hover',\n 'props': [('background-color', 'lightgrey')]\n }\n index_names = {\n 'selector': '.index_name',\n 'props': 'font-style: italic; color: darkgrey; font-weight:normal;'\n }\n headers = {\n 'selector': 'th:not(.index_name)',\n 'props': 'background-color: #3498DB; color: white; text-align: center; '\n }\n styler = df_reme.style.hide_index().set_table_styles([cell_hover, index_names, headers], overwrite=False).set_properties(**{\n 'white-space': 'pre-wrap'})\n \n # Show exclude and include features\n include_feature = [display_map.get(item,item) for item in include_feature]\n exclude_feature = [display_map.get(item,item) for item in exclude_feature]\n\n include_feature_text = ', '.join(include_feature)\n exclude_feature_text = ', '.join(exclude_feature)\n # st.sidebar.options = st.sidebar.markdown('Pay drivers included in model:' + include_feature_text)\n\n # Run data validation\n m_info = main_page_info.success('Output Data Validation')\n demo_validation = convert_df(df_validation)\n\n output = BytesIO()\n writer = pd.ExcelWriter(output, engine='xlsxwriter')\n df_validation.to_excel(writer, index=False, sheet_name='Sheet1')\n workbook = writer.book\n worksheet = writer.sheets['Sheet1']\n\n for column in df_validation:\n column_width = max(df_validation[column].astype(str).map(len).max(), len(column))+3\n col_idx = df_validation.columns.get_loc(column)\n writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_width)\n cell_format = workbook.add_format()\n\n cell_format.set_pattern(1) # This is optional when using a solid fill.\n cell_format.set_bg_color('yellow')\n worksheet.write('A1', 'Please see the instructions for a valid record.',cell_format)\n\n writer.save()\n processed_data = output.getvalue()\n\n# Start Streamlit ----------------------------------------------------------------------------------------------------------------------\n \n # Display run is successful message \n m_info = main_page_info.success('View Result: '+message.loc[['OVERVIEW']][0])\n\n main_page.markdown(\"\"\"---\"\"\")\n m_col1_but_col1, m_col1_but_col2, m_col1_but_col3, m_col1_but_col4 = main_page.columns((0.5, 0.5, 1 , 1))\n\n m_col1_but_col1.metric('Submitted Entry',before_clean_record)\n m_col1_but_col1.metric('Processed Entry',after_clean_record)\n m_col1_but_col1.metric('Invalid Entry',before_clean_record - after_clean_record)\n if operator.not_(df_validation.empty):\n m_col1_but_col1.markdown(get_excel_file_downloader_html(processed_data, 'Invalid Entry.xlsx'), unsafe_allow_html=True)\n m_col1_but_col1.markdown(\"🖱️ 'Save link as...'\")\n\n avg_pay_info = str(locale.format(\"%d\", round(avg_pay/1000,0), grouping=True))+'k'\n m_col1_but_col2.metric('Ave Overall Salary',avg_pay_info)\n\n gender_female_pay_info = str(locale.format(\"%d\", round(gender_female_pay/1000,0), grouping=True))+'k'\n gender_female_pay_delta = str(locale.format(\"%d\", round(gender_female_pay/1000,0) - round(avg_pay/1000,0), grouping=True))+'k'\n # m_col1_but_col2.metric('Avg Non-Male Salary',gender_minor_pay_info, delta=gender_minor_pay_delta)\n m_col1_but_col2.metric('Avg Female Salary',gender_female_pay_info)\n\n gender_nonb_pay_info = str(locale.format(\"%d\", round(gender_nonb_pay/1000,0), grouping=True))+'k'\n gender_nonb_pay_delta = str(locale.format(\"%d\", round(gender_nonb_pay/1000,0) - round(avg_pay/1000,0), grouping=True))+'k'\n # m_col1_but_col2.metric('Avg Non-Male Salary',gender_minor_pay_info, delta=gender_minor_pay_delta)\n m_col1_but_col2.metric('Avg Non-Binary Salary',gender_nonb_pay_info)\n\n eth_major_name = 'Avg Non-'+ df_eth['ETHNICITY_NAME'][0] + ' Salary'\n eth_minor_pay_info = str(locale.format(\"%d\", round(eth_minor_pay/1000,0), grouping=True))+'k'\n eth_minor_pay_delta = str(locale.format(\"%d\", round(eth_minor_pay/1000,0) - round(avg_pay/1000,0), grouping=True))+'k'\n # m_col1_but_col2.metric(eth_major_name,eth_minor_pay_info, delta = eth_minor_pay_delta)\n m_col1_but_col2.metric(eth_major_name,eth_minor_pay_info)\n\n # m_col1_but_col1_2.metric('Submission Record',before_clean_record)\n # m_col1_but_col1_2.metric('Successful Run',after_clean_record)\n\n m_col1_but_col3.markdown(\"<h1 style='text-align: center; vertical-align: top; font-size: 100%'>Gender Distribution</h1>\", unsafe_allow_html=True)\n m_col1_but_col3.pyplot(fig_gender_hc)\n\n m_col1_but_col4.markdown(\"<h1 style='text-align: center; vertical-align: top; font-size: 100%'>Ethnicity Distribution</h1>\", unsafe_allow_html=True)\n m_col1_but_col4.pyplot(fig_eth_hc)\n\n # main_page.markdown(\"\"\"---\"\"\")\n\n # main_page.pyplot(fig_gender_hc)\n# test1, test2, test3 = main_page.columns((1, 1, 1))\n\n# test1.plotly_chart(fig_gender_bar, use_container_width=True)\n\n # main_page.markdown(\"\"\"---\"\"\")\n\n # with st.expander(\"What pay drivers are supplied:\"):\n # inc_col, exc_col = st.columns((1, 1))\n # inc_col.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> ✔️ Pay drivers you supplied: </h1>\", unsafe_allow_html=True)\n # inc_col.markdown(include_feature_text, unsafe_allow_html=True) \n # exc_col.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Orange; font-size: 110%; opacity: 0.7'> ⚠️ Pay drivers you haven't supplied: </h1>\", unsafe_allow_html=True) \n # exc_col.markdown(exclude_feature_text, unsafe_allow_html=True)\n\n # r2= 0.9\n\n # Show R2\n main_page.markdown(\"\"\"---\"\"\")\n metric_R2_1, metric_R2_2, metric_R2_3 = main_page.columns((1, 1.2, 1.3)) \n metric_R2_1.markdown(\"<h1 style='text-align: left; vertical-align: bottom; font-size: 150%; color: #3498DB; opacity: 0.7'>Robustness</h1>\", unsafe_allow_html=True)\n # metric_R2_1.plotly_chart(fig_r2_gender_gap, use_container_width=True)\n with metric_R2_1:\n r2_options = get_r2_option(r2)\n st_echarts(options=r2_options,height=\"200px\") \n\n metric_R2_2.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Benchmark</h1>\", unsafe_allow_html=True)\n metric_R2_2.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> 🌐 70% ~ 100% </h1>\" \" \\n\" \"Robustness measures whether the standard model adequately explains compensation decisions. For instance, 80% means that the standard model explains 80% of the pay difference between employees.\", unsafe_allow_html=True)\n metric_R2_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Observation</h1>\", unsafe_allow_html=True)\n if r2>=0.7:\n metric_R2_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> ✔️ Align with market </h1>\", unsafe_allow_html=True)\n metric_R2_3.markdown(\"Great! Pay drivers are **sufficient** to account for the variation of wages between employees. Let us look at the pay gap.\", unsafe_allow_html=True)\n else:\n metric_R2_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Orange; font-size: 110%; opacity: 0.7'> ⚠️ Below market </h1>\" , unsafe_allow_html=True)\n metric_R2_3.markdown(\"The default compensation drivers are <font color=Orange> **not robust** </font> in drawing conclusions on the salary gap. In general, we can improve the model robustness by adding additional drivers such as talent potential, cost centre, skills and so on. Please contact us for an open consultation.\", unsafe_allow_html=True)\n st.stop()\n # metric_R2_3.markdown(\"<h1 style='text-align: center; vertical-align: bottom; color: Black; background-color: #3498DB; opacity: 0.7; border-style: dotted'>Observation</h1>\", unsafe_allow_html=True)\n\n # Show Gender Gap\n main_page.markdown(\"\"\"---\"\"\")\n metric_net_gap_1, metric_net_gap_2, metric_net_gap_3 = main_page.columns((1, 1.1, 1.4)) \n metric_net_gap_1.markdown(\"<h1 style='text-align: left; vertical-align: bottom; font-size: 150%; color: #3498DB; opacity: 0.7'> Gender Gap </h1>\", unsafe_allow_html=True)\n metric_net_gap_1.plotly_chart(fig_gender_bar, use_container_width=True)\n\n metric_net_gap_2.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Benchmark</h1>\", unsafe_allow_html=True)\n metric_net_gap_2.write(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> 🌐 -3% ~ 1% </h1>\" \"Pay gap measures for every dollar paid to male employees, how much (less) or more goes to non-male employees. For example pay gap at -10% means that on average women are paid 10% less compared to men all else equal. In US, gender gap typically ranges between -3% and +1%. \", unsafe_allow_html=True) \n\n num_gender_sig = df_result_gender['STAT_COUNT'].sum()\n # num_gender_sig = 0\n metric_net_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Observation</h1>\", unsafe_allow_html=True)\n if num_gender_sig>0:\n metric_net_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Orange; font-size: 110%; opacity: 0.7'> ⚠️ Legal Risk - High </h1>\", unsafe_allow_html=True)\n metric_net_gap_3.write('There is/are '+ str(num_gender_sig) + ' statistically significant gender pay gap shown with ' + '<font color=Orange> **Red** </font>' +' bar. A significant gender pay gap means - we are more than 95% certain that the gap exists after incorporates all of the legitimate determinants of pay (such as differences of skill, effort, and responsibility). From a legal perspective:',unsafe_allow_html=True) \n metric_net_gap_3.write('* Statistically significant gap - Strong evidence of gender pay discrimination' +'\\n'+'* Non statistically significant gap - No evidence of gender pay discrimination, the gap is likely due to random chance',unsafe_allow_html=True)\n metric_net_gap_3.write('You may consider reducing the pay gap to a statistically insignificant level to reduce legal risk.')\n else:\n metric_net_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> ✔️ Legal Risk - Low </h1>\", unsafe_allow_html=True)\n metric_net_gap_3.write('There is no negative statistically significant gender pay gap shown in the chart. A significant gender pay gap means - we are more than 95% certain that the gap exists after incorporates all of the legitimate determinants of pay (such as differences of skill, effort, and responsibility). From a legal perspective:',unsafe_allow_html=True) \n metric_net_gap_3.write('* Statistically significant gap - Strong evidence of gender pay discrimination' +'\\n'+'* Non statistically significant gap - No evidence of gender pay discrimination, the gap is likely due to random chance',unsafe_allow_html=True)\n metric_net_gap_3.write('As a precaution, you can routinely repeat this analysis to monitor the pay gap. An alternative is to consider completely closing the pay gap to zero.') \n\n # Show Ethnicity Gap\n main_page.markdown(\"\"\"---\"\"\")\n metric_eth_gap_1, metric_eth_gap_2, metric_eth_gap_3 = main_page.columns((1, 1.1, 1.4)) \n metric_eth_gap_1.markdown(\"<h1 style='text-align: left; vertical-align: bottom; font-size: 150%; color: #3498DB; opacity: 0.7'> Ethnicity Gap </h1>\", unsafe_allow_html=True)\n metric_eth_gap_1.plotly_chart(fig_eth_bar, use_container_width=True)\n\n metric_eth_gap_2.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Benchmark</h1>\", unsafe_allow_html=True)\n metric_eth_gap_2.write(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> 🌐 -10% ~ 5% </h1>\" \"Pay gap measures for every dollar paid to ethnic majority (\" + eth_baseline + \"), how much (less) or more goes to ethnicity minorities. For example pay gap at -10% means that on average black are paid 10% less compared to white all else equal. In US, ethnicity gap typically ranges between -10% and +5%. \", unsafe_allow_html=True) \n\n num_eth_sig = df_result_eth['STAT_COUNT'].sum()\n # num_gender_sig = 0\n metric_eth_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Observation</h1>\", unsafe_allow_html=True)\n if num_eth_sig>0:\n metric_eth_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Orange; font-size: 110%; opacity: 0.7'> ⚠️ Legal Risk - High </h1>\", unsafe_allow_html=True)\n metric_eth_gap_3.write('There is/are '+ str(num_eth_sig) + ' statistically significant ethnicity pay gap shown with ' + '<font color=Orange> **Red** </font>' +' bar. A significant ethnicity pay gap means - we are more than 95% certain that the gap exists after incorporates all of the legitimate determinants of pay (such as differences of skill, effort, and responsibility). From a legal perspective:',unsafe_allow_html=True) \n metric_eth_gap_3.write('* Statistically significant gap - Strong evidence of ethnicity pay discrimination' +'\\n'+'* Non statistically significant gap - No evidence of ethnicity pay discrimination, the gap is likely due to random chance',unsafe_allow_html=True)\n metric_eth_gap_3.write('You may consider reducing the pay gap to a statistically insignificant level to reduce legal risk.')\n else:\n metric_eth_gap_3.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: Green; font-size: 110%; opacity: 0.7'> ✔️ Legal Risk - Low </h1>\", unsafe_allow_html=True)\n metric_eth_gap_3.write('There is no negative statistically significant ethnicity pay gap shown in the chart. A significant ethnicity pay gap means - we are more than 95% certain that the gap exists after incorporates all of the legitimate determinants of pay (such as differences of skill, effort, and responsibility). From a legal perspective:',unsafe_allow_html=True) \n metric_eth_gap_3.write('* Statistically significant gap - Strong evidence of ethnicity pay discrimination' +'\\n'+'* Non statistically significant gap - No evidence of gender pay discrimination, the gap is likely due to random chance',unsafe_allow_html=True)\n metric_eth_gap_3.write('As a precaution, you can routinely repeat this analysis to monitor the pay gap. An alternative is to consider completely closing the pay gap to zero.') \n\n # Remediation Scenarios\n main_page.markdown(\"\"\"---\"\"\")\n # reme_col1, reme_col2 = main_page.columns((1, 1))\n # result_pvalue = [female_pvalue,seek_resulting_pvalues_pv,seek_resulting_pvalues_gap]\n\n df_reme = pd.DataFrame({'Scenario': scenario, 'How do I do this?': action, 'What is my budget?': budget, 'What is the gap after adjustment?': net_gap})\n\n cell_hover = { # for row hover use <tr> instead of <td>\n 'selector': 'td:hover',\n 'props': [('background-color', 'lightgrey')]\n }\n index_names = {\n 'selector': '.index_name',\n 'props': 'font-style: italic; color: darkgrey; font-weight:normal;'\n }\n headers = {\n 'selector': 'th:not(.index_name)',\n 'props': 'background-color: #3498DB; color: white; text-align: center; '\n }\n styler = df_reme.style.hide_index().set_table_styles([cell_hover, index_names, headers], overwrite=False).set_properties(**{\n 'white-space': 'pre-wrap'})\n\n main_page.markdown(\"<h1 style='text-align: left; vertical-align: bottom;color: #3498DB; font-size: 150%; opacity: 0.7'>Remediation Scenarios</h1>\", unsafe_allow_html=True)\n\n # Download individual employee recommendation\n if reme_download_flag == 1:\n output_reme = BytesIO()\n writer_reme = pd.ExcelWriter(output_reme, engine='xlsxwriter')\n df_reme_ind.to_excel(writer_reme, index=False, sheet_name='Sheet1')\n workbook_reme = writer_reme.book\n worksheet_reme = writer_reme.sheets['Sheet1']\n\n for column in df_reme_ind:\n column_width = max(df_reme_ind[column].astype(str).map(len).max(), len(column))+3\n col_idx = df_reme_ind.columns.get_loc(column)\n writer_reme.sheets['Sheet1'].set_column(col_idx, col_idx, column_width)\n cell_format = workbook_reme.add_format()\n\n cell_format.set_pattern(1) # This is optional when using a solid fill.\n cell_format.set_bg_color('yellow')\n worksheet_reme.write('A1', 'EEID',cell_format)\n\n writer_reme.save()\n processed_reme = output_reme.getvalue()\n\n # main_page.download_button(label='💰 Download Salary Adjustment',data = processed_reme,file_name= 'Salary Adjustment.xlsx')\n reme_col1, reme_col2 = main_page.columns((1, 4))\n reme_col1.markdown(\"🖱️ 'Save link as...'\")\n reme_col2.markdown(get_excel_file_downloader_html(processed_reme, 'Salary Adjustment.xlsx'), unsafe_allow_html=True)\n\n main_page.write(styler.to_html(), unsafe_allow_html=True)\n st.stop()\n"
] |
[
[
"matplotlib.pyplot.yticks",
"pandas.to_datetime",
"numpy.log",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"numpy.ceil",
"matplotlib.pyplot.setp",
"pandas.DataFrame.from_dict",
"matplotlib.pyplot.text",
"pandas.to_numeric",
"matplotlib.pyplot.xticks"
],
[
"numpy.log",
"matplotlib.pyplot.tight_layout",
"pandas.to_datetime",
"pandas.read_excel",
"pandas.concat",
"numpy.abs",
"numpy.arange",
"pandas.DataFrame",
"matplotlib.pyplot.Circle",
"numpy.ceil",
"pandas.DataFrame.from_dict",
"numpy.exp",
"numpy.repeat",
"matplotlib.pyplot.pie",
"pandas.to_numeric",
"numpy.sum",
"pandas.ExcelWriter",
"matplotlib.pyplot.figure"
]
] |
sidarth164/RecoEdge
|
[
"351d680a8878f8ab4917e9a96af7d34600a4a6f6"
] |
[
"fedrec/trainers/dlrm_trainer.py"
] |
[
"from typing import Dict\n\nimport attr\nimport numpy as np\nimport torch\nfrom fedrec.trainers.base_trainer import BaseTrainer, TrainConfig\nfrom fedrec.federated_worker import FederatedWorker, Neighbour\nfrom fedrec.preprocessor import PreProcessor\nfrom fedrec.utilities import registry\nfrom fedrec.utilities import saver_utils as saver_mod\nfrom fedrec.utilities.cuda_utils import map_to_cuda\nfrom fedrec.utilities.logger import BaseLogger\nfrom sklearn import metrics\nfrom tqdm import tqdm\n\n\[email protected]('train_config', 'dlrm_std')\[email protected]\nclass DLRMTrainConfig(TrainConfig):\n eval_every_n = attr.ib(default=10000)\n report_every_n = attr.ib(default=10)\n save_every_n = attr.ib(default=2000)\n keep_every_n = attr.ib(default=10000)\n\n batch_size = attr.ib(default=128)\n eval_batch_size = attr.ib(default=256)\n num_epochs = attr.ib(default=-1)\n\n num_batches = attr.ib(default=-1)\n\n @num_batches.validator\n def check_only_one_declaration(instance, _, value):\n if instance.num_epochs > 0 & value > 0:\n raise ValueError(\n \"only one out of num_epochs and num_batches must be declared!\")\n\n num_eval_batches = attr.ib(default=-1)\n eval_on_train = attr.ib(default=False)\n eval_on_val = attr.ib(default=True)\n\n num_workers = attr.ib(default=0)\n pin_memory = attr.ib(default=True)\n\n\[email protected]('trainer', 'dlrm')\nclass DLRMTrainer(BaseTrainer):\n\n def __init__(\n self,\n config_dict: Dict,\n train_config: DLRMTrainConfig,\n logger: BaseLogger, \n model_preproc: PreProcessor,) -> None:\n\n self.train_config = train_config\n super().__init__(config_dict, train_config, logger, model_preproc)\n\n @staticmethod\n def _yield_batches_from_epochs(loader, start_epoch):\n current_epoch = start_epoch\n while True:\n for batch in loader:\n yield batch, current_epoch\n current_epoch += 1\n\n @property\n def optimizer(self):\n if self._optimizer is None:\n with self.init_random:\n self._optimizer = registry.construct(\n 'optimizer', self.config_dict['train']['optimizer'],\n params=self.model.parameters())\n return self._optimizer\n\n def get_scheduler(self, optimizer, **kwargs):\n if self._scheduler is None:\n with self.init_random:\n self._scheduler = registry.construct(\n 'lr_scheduler',\n self.config_dict['train'].get(\n 'lr_scheduler', {'name': 'noop'}),\n optimizer=optimizer, **kwargs)\n return self._scheduler\n\n @property\n def saver(self):\n if self._saver is None:\n # 2. Restore model parameters\n self._saver = saver_mod.Saver(\n self.model, self.optimizer, keep_every_n=self.train_config.keep_every_n)\n return self._saver\n\n @property\n def data_loaders(self):\n if self._data_loaders:\n return self._data_loaders\n # 3. Get training data somewhere\n with self.data_random:\n train_data = self.model_preproc.dataset('train')\n train_data_loader = self.model_preproc.data_loader(\n train_data,\n batch_size=self.train_config.batch_size,\n num_workers=self.train_config.num_workers,\n pin_memory=self.train_config.pin_memory,\n persistent_workers=True,\n shuffle=True,\n drop_last=True)\n\n train_eval_data_loader = self.model_preproc.data_loader(\n train_data,\n pin_memory=self.train_config.pin_memory,\n num_workers=self.train_config.num_workers,\n persistent_workers=True,\n batch_size=self.train_config.eval_batch_size)\n\n val_data = self.model_preproc.dataset('val')\n val_data_loader = self.model_preproc.data_loader(\n val_data,\n num_workers=self.train_config.num_workers,\n pin_memory=self.train_config.pin_memory,\n persistent_workers=True,\n batch_size=self.train_config.eval_batch_size)\n self._data_loaders = {\n 'train': train_data_loader,\n 'train_eval': train_eval_data_loader,\n 'val': val_data_loader\n }\n\n @staticmethod\n def eval_model(\n model,\n loader,\n eval_section,\n logger,\n num_eval_batches=-1,\n best_acc_test=None,\n best_auc_test=None,\n step=-1):\n scores = []\n targets = []\n model.eval()\n total_len = num_eval_batches if num_eval_batches > 0 else len(loader)\n with torch.no_grad():\n t_loader = tqdm(enumerate(loader), unit=\"batch\", total=total_len)\n for i, testBatch in t_loader:\n # early exit if nbatches was set by the user and was exceeded\n if (num_eval_batches is not None) and (i >= num_eval_batches):\n break\n t_loader.set_description(f\"Running {eval_section}\")\n\n inputs, true_labels = map_to_cuda(testBatch, non_blocking=True)\n\n # forward pass\n Z_test = model.get_scores(model(*inputs))\n\n S_test = Z_test.detach().cpu().numpy() # numpy array\n T_test = true_labels.detach().cpu().numpy() # numpy array\n\n scores.append(S_test)\n targets.append(T_test)\n\n model.train()\n scores = np.concatenate(scores, axis=0)\n targets = np.concatenate(targets, axis=0)\n metrics_dict = {\n \"recall\": lambda y_true, y_score: metrics.recall_score(\n y_true=y_true, y_pred=np.round(y_score)\n ),\n \"precision\": lambda y_true, y_score: metrics.precision_score(\n y_true=y_true, y_pred=np.round(y_score), zero_division=0.0\n ),\n \"f1\": lambda y_true, y_score: metrics.f1_score(\n y_true=y_true, y_pred=np.round(y_score)\n ),\n \"ap\": metrics.average_precision_score,\n \"roc_auc\": metrics.roc_auc_score,\n \"accuracy\": lambda y_true, y_score: metrics.accuracy_score(\n y_true=y_true, y_pred=np.round(y_score)\n ),\n }\n\n results = {}\n for metric_name, metric_function in metrics_dict.items():\n results[metric_name] = metric_function(targets, scores)\n logger.add_scalar(\n eval_section + \"/\" + \"mlperf-metrics/\" + metric_name,\n results[metric_name],\n step,\n )\n\n if (best_auc_test is not None) and (results[\"roc_auc\"] > best_auc_test):\n best_auc_test = results[\"roc_auc\"]\n best_acc_test = results[\"accuracy\"]\n return True, results\n\n return False, results\n\n def test(self):\n results = {}\n if self.train_config.eval_on_train:\n _, results['train_metrics'] = self.eval_model(\n self.model,\n self.data_loaders['train_eval'],\n eval_section='train_eval',\n num_eval_batches=self.train_config.num_eval_batches,\n logger=self.logger, step=-1)\n\n if self.train_config.eval_on_val:\n _, results['test_metrics'] = self.eval_model(\n self.model,\n self.data_loaders['test'],\n eval_section='test',\n logger=self.logger,\n num_eval_batches=self.train_config.num_eval_batches,\n step=-1)\n return results\n\n def train(self, modeldir=None):\n last_step, current_epoch = self.saver.restore(modeldir)\n lr_scheduler = self.get_scheduler(\n self.optimizer, last_epoch=last_step)\n\n if self.train_config.num_batches > 0:\n total_train_len = self.train_config.num_batches\n else:\n total_train_len = len(self.data_loaders['train'])\n train_dl = self._yield_batches_from_epochs(\n self.data_loaders['train'], start_epoch=current_epoch)\n\n # 4. Start training loop\n with self.data_random:\n best_acc_test = 0\n best_auc_test = 0\n dummy_input = map_to_cuda(next(iter(train_dl))[0])\n self.logger.add_graph(self.model, dummy_input[0])\n t_loader = tqdm(train_dl, unit='batch',\n total=total_train_len)\n for batch, current_epoch in t_loader:\n t_loader.set_description(f\"Training Epoch {current_epoch}\")\n\n # Quit if too long\n if self.train_config.num_batches > 0 & last_step >= self.train_config.num_batches:\n break\n if self.train_config.num_epochs > 0 & current_epoch >= self.train_config.num_epochs:\n break\n\n # Evaluate model\n if last_step % self.train_config.eval_every_n == 0:\n if self.train_config.eval_on_train:\n self.eval_model(\n self.model,\n self.data_loaders['train_eval'],\n eval_section='train_eval',\n num_eval_batches=self.train_config.num_eval_batches,\n logger=self.logger, step=last_step)\n\n if self.train_config.eval_on_val:\n if self.eval_model(\n self.model,\n self.data_loaders['val'],\n eval_section='val',\n logger=self.logger,\n num_eval_batches=self.train_config.num_eval_batches,\n best_acc_test=best_acc_test, best_auc_test=best_auc_test,\n step=last_step)[1]:\n self.saver.save(modeldir, last_step,\n current_epoch, is_best=True)\n\n # Compute and apply gradient\n with self.model_random:\n input, true_label = map_to_cuda(\n batch, non_blocking=True)\n output = self.model(*input)\n loss = self.model.loss(output, true_label)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n lr_scheduler.step()\n\n # Report metrics\n if last_step % self.train_config.report_every_n == 0:\n t_loader.set_postfix({'loss': loss.item()})\n self.logger.add_scalar(\n 'train/loss', loss.item(), global_step=last_step)\n self.logger.add_scalar(\n 'train/lr', lr_scheduler.last_lr[0], global_step=last_step)\n if self.train_config.log_gradients:\n self.logger.log_gradients(self.model, last_step)\n\n last_step += 1\n # Run saver\n if last_step % self.train_config.save_every_n == 0:\n self.saver.save(modeldir, last_step, current_epoch)\n\n\[email protected]('trainer', 'dlrm_fl')\nclass DLRMWorker(FederatedWorker):\n def __init__(self,\n config,\n client_index: int,\n roles,\n in_neighbours: Dict[int, Neighbour],\n out_neighbours: Dict[int, Neighbour],\n base_trainer: BaseTrainer,\n train_data_num: int):\n super().__init__(config, client_index, roles, in_neighbours,\n out_neighbours, base_trainer, train_data_num)\n"
] |
[
[
"numpy.concatenate",
"numpy.round",
"torch.no_grad"
]
] |
kad99kev/pytorch_gan_trainer
|
[
"f9db1072f29485843be3008e25d64abac8a36e2b"
] |
[
"pytorch_gan_trainer/models/acgan/discriminator.py"
] |
[
"import torch.nn as nn\n\n\nclass Discriminator(nn.Module):\n \"\"\"Discriminator model for ACGAN.\n\n Arguments:\n target_size (int): Target size of input image.\n num_channels (int): Number of channels in images of dataset.\n num_classes (int): Number of classes in dataset.\n feature_size (int): Feature size of the model.\n \"\"\"\n\n def __init__(self, target_size, num_channels, num_classes, feature_size=64):\n super(Discriminator, self).__init__()\n self.target_size = target_size\n self.feature_size = feature_size\n self.num_classes = num_classes\n\n assert target_size in [\n 64,\n 128,\n 256,\n ], \"Target size can only be one of the following: [64, 128, 256]\"\n assert num_channels in [\n 1,\n 3,\n ], \"Number of channels can only be one of the following: [1, 3]\"\n assert feature_size // 8 > 0, \"Please enter a larger feature size\"\n\n feature_size = feature_size // 2\n\n self.conv_1 = nn.Sequential(\n nn.Conv2d(num_channels, feature_size, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n )\n # Shape [target_size / 2 x target_size / 2]\n\n self.conv_2 = nn.Sequential(\n nn.Conv2d(feature_size, feature_size, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n nn.BatchNorm2d(feature_size, 0.8),\n )\n # Shape [target_size / 4 x target_size / 4]\n\n self.conv_3 = nn.Sequential(\n nn.Conv2d(feature_size, feature_size * 2, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n nn.BatchNorm2d(feature_size * 2, 0.8),\n )\n # Shape [target_size / 8 x target_size / 8]\n\n feature_size = feature_size * 2\n\n if target_size >= 128:\n self.conv_4 = nn.Sequential(\n nn.Conv2d(feature_size, feature_size * 2, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n nn.BatchNorm2d(feature_size * 2, 0.8),\n )\n\n feature_size = feature_size * 2\n\n if target_size == 256:\n self.conv_5 = nn.Sequential(\n nn.Conv2d(feature_size, feature_size * 2, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n nn.BatchNorm2d(feature_size * 2, 0.8),\n )\n feature_size = feature_size * 2\n\n self.conv_final = nn.Sequential(\n nn.Conv2d(feature_size, feature_size * 2, 4, 2, 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.2),\n nn.BatchNorm2d(feature_size * 2, 0.8),\n )\n feature_size = feature_size * 2\n\n # Discriminator Layer\n self.discrim = nn.Sequential(nn.Linear(feature_size * 4 ** 2, 1), nn.Sigmoid())\n\n # Auxillary Layer\n self.aux = nn.Sequential(\n nn.Linear(feature_size * 4 ** 2, num_classes), nn.Softmax(dim=1)\n )\n\n def forward(self, inputs):\n \"\"\"Forward pass to the model.\n\n Arguments:\n input (torch.Tensor): Inputs to the model.\n\n Returns:\n tuple: Outputs from the forward pass. (valid, labels)\n \"\"\"\n x = self.conv_1(inputs)\n x = self.conv_2(x)\n x = self.conv_3(x)\n\n if self.target_size >= 128:\n x = self.conv_4(x)\n if self.target_size == 256:\n x = self.conv_5(x)\n\n x = self.conv_final(x)\n input_ = x.view(x.size(0), -1)\n labels = self.aux(input_)\n valid = self.discrim(input_)\n return valid, labels\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d"
]
] |
JamesKing76/AudioSuperResolution
|
[
"85114887248c02b1c80f7162c909f6fe51d3667e"
] |
[
"Processing/Downsampler.py"
] |
[
"import os\n\nimport numpy as np\nimport soundfile as sf\n\n\ndef retrive_data_low(file, downsample_rate, n, m):\n \"\"\"\n This function downsamples a file and extracts its lowpoints and crops it to be of an appropriate size\n :param file: The audio file to be downasmpled\n :param downsample_rate: The amount we downsample the singal by\n :param n: The amount before extracted in each set\n :param m: The amount after extracted in each set\n :return: An array of the set of low points\n \"\"\"\n\n data_points, sample_rate = sf.read(file)\n new_data_points = data_points[0::downsample_rate]\n new_paded_data_points = np.pad(new_data_points, (n, m))\n data = [[]] * (len(new_data_points))\n\n for i in range(0, len(new_data_points)):\n data[i] = new_paded_data_points[i + 1:i + 1 + m + n:]\n\n return np.array(data)\n\n\ndef retrive_data_high(file, downsample_rate):\n \"\"\"\n This function crops the file and extracts the high resolution samples\n :param file: The audio file to be downasmpled\n :param downsample_rate: The amount we downsample the signal by\n :return: And array of the high points\n \"\"\"\n\n data_points, sample_rate = sf.read(file)\n modesumtemp = len(data_points) % downsample_rate\n new_paded_data_points = np.zeros(\n len(data_points) + (0 if modesumtemp == 0 else (downsample_rate - modesumtemp)))\n new_paded_data_points[0:len(data_points):] = data_points\n data = [[0 in range(downsample_rate)]] * (len(new_paded_data_points) // downsample_rate)\n\n for i in range(0, len(data)):\n data[i] = new_paded_data_points[downsample_rate * i:downsample_rate * i + downsample_rate:]\n\n return np.array(data)\n\n\ndef retrive_from_directory(dir_to_search, downsample_rate, n, m):\n \"\"\"\n This function gets both the high and low samples from every file in a directory\n :param dir_to_search: The directory to extract the files from\n :param downsample_rate: The amount we downsample the signal by\n :param n: The amount before extracted in each set in the low extraction\n :param m: The amount after extracted in each set in the low extraction\n :return: Both the set of low points and the high points for each file in the directory\n \"\"\"\n\n total_high = np.zeros((0, downsample_rate))\n total_low = np.zeros((0, m + n))\n\n for subdirectory, directory, files in os.walk(dir_to_search):\n for file in files:\n if file.endswith(\".flac\"):\n filepath = subdirectory + os.sep + file\n current = retrive_data(filepath, downsample_rate, n, m)\n total_low = np.concatenate((total_low, current[0]), axis=0)\n total_high = np.concatenate((total_high, current[1]), axis=0)\n\n return total_low, total_high\n\n\ndef retrive_data(file, downsample_rate, n, m):\n \"\"\"\n This function retrieves data from a single file\n :param file: The audio file to be downasmpled\n :param downsample_rate: The amount we downsample the signal by\n :param n: The amount before extracted in each set in the low extraction\n :param m: The amount after extracted in each set in the low extraction\n :return:\n \"\"\"\n\n return retrive_data_low(file, downsample_rate, n, m), retrive_data_high(file, downsample_rate)\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.pad"
]
] |
Emilie-Thome/Multi-Agent-RL
|
[
"4546abb48a5febb1c7ea24fc6af99dcf4c6fd811",
"4546abb48a5febb1c7ea24fc6af99dcf4c6fd811"
] |
[
"data/local/test-discounts/exp_plot.py",
"data/local/test-transfer-params/exp_plot.py"
] |
[
"import csv\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport numpy as np\n\n\ndir_prefix = 'test_discounts_2021_04_16_10_06_18_00'\ndiscounts = [0.5, 0.75, 0.99]\nparticipation_rates = [0.5, 1]\nagents_numbers = [5, 10]\naverage_periods = [1, 5, 10]\n\nfiles_id = ['0'+str(i) for i in range(1,10)] + [str(i) for i in range(10,37)]\nfile = '/progress.csv'\n\n\nfor k_per, average_period in enumerate(average_periods):\n\tfig = plt.figure(figsize=(20,10), dpi=70)\n\taxs = fig.subplots(len(participation_rates), len(agents_numbers))\n\n\tfor k_dis, discount in enumerate(discounts):\n\t\tfor k_part, participation_rate in enumerate(participation_rates):\n\t\t\tfor k_agent, agents_number in enumerate(agents_numbers):\n\t\t\t\n\t\t\t\tid_file = files_id[len(participation_rates)*len(agents_numbers)*len(average_periods)*k_dis\n\t\t\t\t\t+ len(agents_numbers)*len(average_periods)*k_part\n\t\t\t\t\t+ len(average_periods)*k_agent\n\t\t\t\t\t+k_per]\n\t\t\t\ttransf_bits = [0]\n\t\t\t\taverage_returns = [0]\n\t\t\t\twith open(dir_prefix + id_file + file) as csvfile:\n\t\t\t\t\treader = csv.DictReader(csvfile)\n\t\t\t\t\tfor row in reader:\n\t\t\t\t\t\ttransf_bits.append(int(row['TransfBits']))\n\t\t\t\t\t\taverage_returns.append(float(row['TotalAverageReturn']))\n\t\t\t\taxs[k_part][k_agent].plot(transf_bits, average_returns, label='Discount: ' + str(discount))\n\t\t\t\taxs[k_part][k_agent].set_title('Average period: ' + str(average_period) + ' ; Agents number: ' + str(agents_number) + ' ; Participation rate: ' + str(participation_rate))\n\t\t\t\taxs[k_part][k_agent].set(xlabel='Transferred Bits', ylabel='Average returns')\n\n\thandles, labels = axs[0,0].get_legend_handles_labels()\n\tfig.legend(handles, labels, shadow=True, fancybox=True, bbox_to_anchor=[0.9, 0.3])\n\tfig.suptitle('Difference parameters, every agent update their mean parameters reference, quantized, average period: ' + str(average_period))\n\tfig.savefig(dir_prefix + 'average_period' + str(average_period))",
"import csv\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport numpy as np\n\n\ndir_prefix = 'test_transfer_params_2021_04_14_18_30_29_000'\nquantization_tunings = [1, 10]\nparticipation_rate = 1\nagents_number = 10\naverage_period = 5\n\nfiles_id = [str(i) for i in range(1,5)]\nfile = '/progress.csv'\n\nfig = plt.figure(figsize=(10,5), dpi=100)\nax = fig.add_subplot()\nfor k_quant, quantization_tuning in enumerate(quantization_tunings):\n\tid_file = files_id[k_quant]\n\ttransf_bits = [0]\n\taverage_returns = [0]\n\twith open(dir_prefix + id_file + file) as csvfile:\n\t\treader = csv.DictReader(csvfile)\n\t\tfor row in reader:\n\t\t\ttransf_bits.append(int(row['TransfBits']))\n\t\t\taverage_returns.append(float(row['TotalAverageReturn']))\n\tax.plot(transf_bits, average_returns, label='Quantization tuning: ' + str(quantization_tuning))\nax.set_title('Average period: ' + str(average_period) + ' ; Agents number: ' + str(agents_number) + ' ; Participation rate: ' + str(participation_rate))\nax.set(xlabel='Transferred Bits', ylabel='Average returns')\n\nhandles, labels = ax.get_legend_handles_labels()\nfig.legend(handles, labels, shadow=True, fancybox=True, bbox_to_anchor=[0.9, 0.5])\nfig.suptitle('Entire parameters, quantized')\nfig.savefig(dir_prefix)"
] |
[
[
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.figure"
]
] |
collodi/svd_layer
|
[
"67a608ca10d3d37bf861e4e7490e62d298fa83b9"
] |
[
"svd_layer/conv.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.cv_drop = nn.Dropout2d(p=0.2)\n\n\t\tself.cv1 = nn.Conv2d(1, 5, 5, padding=2)\n\t\tself.cv2 = nn.Conv2d(5, 5, 5, padding=2)\n\t\tself.cv3 = nn.Conv2d(5, 5, 5, padding=2)\n\n\t\tself.fc = nn.Sequential(\n\t\t\t\tnn.AlphaDropout(p=0.25),\n\t\t\t\tnn.Linear(80, 40), nn.SELU(),\n\t\t\t\tnn.Linear(40, 40), nn.SELU()\n\t\t\t)\n\n\t\tself.out = nn.Linear(40, 10)\n\n\tdef forward(self, x):\n\t\tx = F.selu(self.cv1(x))\n\t\tx = self.cv_drop(x)\n\t\tx = F.adaptive_max_pool2d(x, 24)\n\n\t\tx = F.selu(self.cv2(x))\n\t\tx = self.cv_drop(x)\n\t\tx = F.adaptive_max_pool2d(x, 10)\n\n\t\tx = F.selu(self.cv3(x))\n\t\tx = F.adaptive_max_pool2d(x, 4)\n\n\t\tx = x.view(x.size(0), -1)\n\t\tx = self.fc(x)\n\t\treturn self.out(x)\n"
] |
[
[
"torch.nn.Dropout2d",
"torch.nn.AlphaDropout",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.adaptive_max_pool2d",
"torch.nn.SELU"
]
] |
xx-zhou16/Grammar
|
[
"e4a5427ef4ffad63fa265acbade098bb963a814b"
] |
[
"fairseq/criterions/cross_entropy.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom dataclasses import dataclass\n\nimport torch.nn.functional as F\nfrom fairseq import metrics, utils\nfrom fairseq.criterions import FairseqCriterion, register_criterion\nfrom fairseq.dataclass.data_class import DDP_BACKEND_CHOICES\nfrom fairseq.dataclass.utils import FairseqDataclass, gen_parser_from_dataclass\nfrom omegaconf import II\n\n\n@dataclass\nclass CrossEntropyCriterionConfig(FairseqDataclass):\n sentence_avg: bool = II(\"params.optimization.sentence_avg\")\n ddp_backend: DDP_BACKEND_CHOICES = II(\"params.distributed_training.ddp_backend\")\n\n\n@register_criterion(\"cross_entropy\")\nclass CrossEntropyCriterion(FairseqCriterion):\n def __init__(self, task, sentence_avg):\n super().__init__(task)\n self.sentence_avg = sentence_avg\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add task-specific arguments to the parser. optionaly register config store\"\"\"\n gen_parser_from_dataclass(parser, CrossEntropyCriterionConfig())\n\n def forward(self, model, sample, reduce=True):\n \"\"\"Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) the loss\n 2) the sample size, which is used as the denominator for the gradient\n 3) logging outputs to display while training\n \"\"\"\n net_output = model(**sample[\"net_input\"])\n loss, _ = self.compute_loss(model, net_output, sample, reduce=reduce)\n sample_size = (\n sample[\"target\"].size(0) if self.sentence_avg else sample[\"ntokens\"]\n )\n logging_output = {\n \"loss\": loss.data,\n \"ntokens\": sample[\"ntokens\"],\n \"nsentences\": sample[\"target\"].size(0),\n \"sample_size\": sample_size,\n }\n return loss, sample_size, logging_output\n\n def compute_loss(self, model, net_output, sample, reduce=True):\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1))\n target = model.get_targets(sample, net_output).view(-1)\n loss = F.nll_loss(\n lprobs,\n target,\n ignore_index=self.padding_idx,\n reduction=\"sum\" if reduce else \"none\",\n )\n return loss, loss\n\n @staticmethod\n def reduce_metrics(logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get(\"loss\", 0) for log in logging_outputs)\n ntokens = sum(log.get(\"ntokens\", 0) for log in logging_outputs)\n sample_size = sum(log.get(\"sample_size\", 0) for log in logging_outputs)\n\n metrics.log_scalar(\n \"loss\", loss_sum / sample_size / math.log(2), sample_size, round=3\n )\n if sample_size != ntokens:\n metrics.log_scalar(\n \"nll_loss\", loss_sum / ntokens / math.log(2), ntokens, round=3\n )\n metrics.log_derived(\n \"ppl\", lambda meters: utils.get_perplexity(meters[\"nll_loss\"].avg)\n )\n else:\n metrics.log_derived(\n \"ppl\", lambda meters: utils.get_perplexity(meters[\"loss\"].avg)\n )\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n"
] |
[
[
"torch.nn.functional.nll_loss"
]
] |
kastnerkyle/PyCon2015
|
[
"649700cb4ce2e55c0c23315538970152a63c7173"
] |
[
"ex1_recommendations.py"
] |
[
"from pandas.io.excel import read_excel\nfrom matrix_factorization import PMF\nimport matplotlib.pyplot as plt\nfrom utils import download\nfrom scipy import sparse\nimport numpy as np\nimport zipfile\nimport os\n\n\"\"\"\nA dataset of jokes and associated user ratings.\nEigentaste: A Constant Time Collaborative Filtering Algorithm.\nKen Goldberg, Theresa Roeder, Dhruv Gupta, and Chris Perkins.\nInformation Retrieval, 4(2), 133-151. July 2001.\nhttp://eigentaste.berkeley.edu/dataset/\n\nWe will use this dataset to test our simple recommendation algorithm.\n\"\"\"\ndataset_url = \"http://eigentaste.berkeley.edu/dataset/jester_dataset_1_1.zip\"\n\n\"\"\"\nNext, download the jester dataset to jester_dataset_1_1.zip if it hasn't been\ndownloaded yet\n\"\"\"\ndataset_fname = dataset_url.split(\"/\")[-1]\nif not os.path.exists(dataset_fname):\n download(dataset_url, server_fname=dataset_fname)\n\n\"\"\"\nThe dataset is stored as an Excel spreadsheet (XLS).\nWe can read it without unzipping using the zipfile library.\n\"\"\"\narchive = zipfile.ZipFile(dataset_fname, 'r')\n# Only one file in the zipfile we are reading from\n# archive.open returns a file-like object - perfect for sending to pandas\nfile_handle = archive.open(archive.infolist()[0])\n\n\"\"\"\nTo read the actual XLS file, we can use pandas.\n\"\"\"\ndataframe = read_excel(file_handle)\ndata = dataframe.values\n\n\"\"\"\nOnly use the first 100 users for this example.\n\"\"\"\nuser_indices = data[:100, 0]\nratings = data[:100, 1:]\n# Necessary because this is a view of the underlying data, want separate copy\ntrue_ratings = np.copy(data[:100, 1:])\n\n\"\"\"\nIn this dataset, any rating of 99. means that a joke was unrated. Since these\nare floating point values, it is best to create the sparse array by hand.\nWe can get these indices with np.where.\n\"\"\"\nrated = np.where(ratings <= 10.)\nnp.random.RandomState(1999)\n# Use 20% for validation\nn_validation = int(0.2 * len(rated[0]))\nidx = np.random.randint(0, len(rated[0]), n_validation)\n# Stack and transpose to get an (x, 2) array of indices\nvalidation_indices = np.vstack((rated[0], rated[1])).T[idx]\n# Set validation to NaN now\nratings[validation_indices[:, 0], validation_indices[:, 1]] = 99.\n# Keep this mask for plotting to include validation\nmask = (ratings <= 10.)\n# Redo NaN check\nrated = np.where(ratings <= 10.)\nratings = sparse.coo_matrix((ratings[rated[0], rated[1]], (rated[0], rated[1])))\n\n\"\"\"\nFor now, treat this algorithm as a black box with input ratings,\noutput recommendation basis matrices which can be used for predictions.\nIf curious, see the docstrings of the function for the original paper.\n\"\"\"\nU, V, m = PMF(ratings, minibatch_size=10, learning_rate=0.001, momentum=0.95,\n regularization=0.75, max_epoch=100, rank=20, random_state=2000)\npredicted_ratings = np.dot(U, V.T) + m\npredicted_ratings = np.clip(predicted_ratings, -10, 10)\n\n\"\"\"\nCalculate mean absolute error on validation indices\n\"\"\"\nval_truth = true_ratings[validation_indices[:, 0], validation_indices[:, 1]]\nval_predict = predicted_ratings[validation_indices[:, 0],\n validation_indices[:, 1]]\n# Mean absolute error\nmae = np.mean(np.abs(val_truth - val_predict))\nprint(\"Validation mean absolute error %f\" % mae)\n\n\"\"\"\nPlot the first 100 user prediction matrix\n\"\"\"\nf, axarr = plt.subplots(1, 2)\naxarr[0].matshow((true_ratings * mask), cmap=\"gray\")\naxarr[0].set_title(\"Ground truth ratings\")\naxarr[1].matshow((predicted_ratings * mask), cmap=\"gray\")\naxarr[1].set_title(\"Predicted ratings\\n Validation mean absolute error %f\" % mae)\naxarr[0].axis(\"off\")\naxarr[1].axis(\"off\")\nplt.show()\n"
] |
[
[
"numpy.dot",
"scipy.sparse.coo_matrix",
"numpy.abs",
"numpy.clip",
"numpy.vstack",
"matplotlib.pyplot.subplots",
"numpy.copy",
"pandas.io.excel.read_excel",
"numpy.random.RandomState",
"numpy.where",
"matplotlib.pyplot.show"
]
] |
milo-lab/biomass_distribution
|
[
"36cf0a80ec94deb73cb560b66cbd9fa190f528ce"
] |
[
"bacteria_archaea/marine_deep_subsurface/cell_num/marine_deep_subsurface_prok_cell_num.py"
] |
[
"\n# coding: utf-8\n\n# In[1]:\n\n# Load dependencies\nimport pandas as pd\nimport numpy as np\nimport sys\nfrom scipy.stats import gmean\nsys.path.insert(0, '../../../statistics_helper')\nfrom CI_helper import *\n\n\n# # Estimating the total number of bacteria and archaea in the marine deep subsurface\n# In order to estimate the total number of cells of bacteria and archaea in the marine deep subsurface, we rely of estimates from two studies - [Parkes et al.](http://www.sciencedirect.com/science/article/pii/S0025322714000425), and [Kallmeyer et al.](http://dx.doi.org/10.1073/pnas.1203849109). Our best esimate for the total number of cells of bacteria and archaea in the marine deep subsurface is the geometric mean of the estimates by Parkes et al. and Kallmeyer et al.\n\n# In[2]:\n\n#Kallmeyer et al. estimate ≈2.9×10^29 cells in the marine deep subsurface\nkallmeyer = 2.9e29\n#Parkes et al. estimate ≈5.4×10^29 cells in the marine deep subsurface\nparkes = 5.4e29\n\nbest_estimate = gmean([kallmeyer,parkes])\nprint('Our best estimate for the total number of cells of bacteria and archaea the marine deep subsurface is %.1e.' % best_estimate)\n\n\n# # Uncertainty analysis\n# \n# To calculate the uncertainty associated with the estimate for the total number of of bacteria and archaea in the marine deep subsurface, we first collect all available uncertainties and then take the largest value as our best projection for the uncertainty. \n# \n# ## Intra-study uncertainty\n# We survey the uncertainties reported in Parkes et al. and Kallmeyer et al. for their estimates of the total number of cells in the marine deep subsurface.\n# Parkes et al. reports a 95% confidence interval of $1.95×10^{29}-4.35×10^{30}$ with a mean of $8.65×10^{29}$ excluding contribution from Ocean Gyre sites, and a mean of $5.39×10^{29}$. As we do not know the 95% confidence interval of the estimate including Ocean Gyre sites, we use the 95% confidence interval from the estimate excluding Ocean Gyre sites as a measure of the intra-study uncertainty of the estimate of the total number of bacteria and archaea in the marine deep subsurface. We report uncertainty as a multiplicative factor, so we calculate the fold change of the minimal and maximal values in the 95% confidence interval relative to the mean estiamte and use this value as the intra-study uncertainty of Parkes et al.\n\n# In[3]:\n\nparkes_low = 1.95e29\nparkes_high = 4.34e30\nparkes_mean_ex_ocean_gyre = 8.65e29\n\n# We calculate the fold change in the minimum and maximum of the 95% confidence interval relative to the mean estimate\nparkes_high_mul_CI = parkes_high/parkes_mean_ex_ocean_gyre\nparkes_low_mul_CI = parkes_mean_ex_ocean_gyre/parkes_low\n\n# We use the average of the fold changes as our estimate for the intra-study uncertainty of the estimate by Parkes et al.\nparkes_mul_CI = np.mean([parkes_high_mul_CI,parkes_low_mul_CI])\n\nprint('The intra-study uncertainty of the estimate by Parkes et al. is %.1f-fold' % parkes_mul_CI)\n\n\n# Kallmeyer et al., report an estimate of ≈$2.9×10^{29}$ cells of bacteria and archaea in the marine deep subsurface. Kallmeyer et al. bootstrap the parameters of the model for estimating the total number of cells, which results in a distribution of estimates for the total number of cells. Kallmeyer et al. report a range of one standard deviation from the mean estimate of ≈$1.2×10^{29}-≈8×10^{29}$. We use this range as a measure of the intra-study uncertainty of the estimate by Kallmeyer et al. As Kallmeyer et al. only reports a standard deviation range, we convert this range to 95% multiplicative confidence interval by calculating the fold change of the minimum and maximum of the range relative to the average estimate by Kallmeyer et al., and taking this fold change to the power of 1.96 to move from one standard deviation to 95% confidence interval.\n\n# In[4]:\n\nkallmeyer_low = 1.2e29\nkallmeyer_high = 8e29\n\n# We calculate the fold change in the minimum and maximum of the standard deviation range relative to the mean estimate\nkallmeyer_high_mul_std = (kallmeyer_high/kallmeyer)\nkallmeyer_low_mul_std = (kallmeyer/kallmeyer_low)\n\n# We use the average of the fold changes as our estimate for the intra-study uncertainty of the estimate by Parkes et al.\nkallmeyer_mul_CI = np.mean([kallmeyer_high_mul_std,kallmeyer_low_mul_std])**1.96\nprint('The intra-study uncertainty of the estimate by Kallmeyer et al. is %.1f-fold' % kallmeyer_mul_CI)\n\n\n# ## Interstudy uncetainty\n# We calculate the 95% confidence interval of the geometric mean of the estimates by Parkes et al. and Kallmeyer et al. as a measure of the interstudy uncertainty.\n\n# In[5]:\n\ninter_mul_CI = geo_CI_calc(np.array([parkes,kallmeyer]))\n\nprint('The interstudy uncertainty of the geometric mean of the estimates by Parkes et al. and Kallmeyer et al. is %.1f-fold' % inter_mul_CI)\n\n\n# We use the highest uncertainty among the intra-study and interstudy uncertainties as our projection of the uncertainty associated with the estimate of the total number of cells of bacteria and archaea in the marine deep subsurface. Are final parameters are:\n\n# In[6]:\n\n# Take the maximal uncetainty as our best projection of uncertainty\nmul_CI = np.max([parkes_mul_CI,kallmeyer_mul_CI,inter_mul_CI])\n\nprint('Total number of bacteria and archaea in the marine deep subsurface: %.1e' % best_estimate)\nprint('Uncertainty associated with the total number of bacteria and archaea in the marine deep subsurface: %.1f-fold' % mul_CI)\n\nold_results = pd.read_excel('../marine_deep_subsurface_prok_biomass_estimate.xlsx')\nresult = old_results.copy()\nresult.loc[0] = pd.Series({\n 'Parameter': 'Total number of bacteria and archaea in the marine deep subsurface',\n 'Value': best_estimate,\n 'Units': 'Cells',\n 'Uncertainty': \"{0:.1f}\".format(mul_CI)\n })\n\nresult.to_excel('../marine_deep_subsurface_prok_biomass_estimate.xlsx',index=False)\n\n"
] |
[
[
"scipy.stats.gmean",
"pandas.read_excel",
"numpy.max",
"numpy.mean",
"numpy.array"
]
] |
RyogaLi/tilseq_mutcount
|
[
"ba6d82851981d0849673e8858b208a5aecab4064"
] |
[
"TileSeqMut/help_functions.py"
] |
[
"#!/usr/bin/env python3.7\n\n# Helper functions\n# 1. downsample fastq files into n reads\n# 2. loading process animation function\n# 3. parse input json file\n\nimport pandas as pd\nimport random\nimport os\nimport sys\nimport json\nimport time\nimport itertools\nimport logging\nfrom Bio.Seq import Seq\n\n\ndef parse_json(json_file):\n \"\"\"\n parse input json file\n return information about the run\n \"\"\"\n with open(json_file, \"r\") as jsonf:\n data = json.load(jsonf)\n project = data[\"project\"] # project name\n seq = pd.DataFrame(data[\"template\"], index=[0]) # sequence\n cds_seq = seq.seq[0]\n cds_seq = cds_seq[int(seq.cds_start)-1: int(seq.cds_end)]\n # create dictionary to map tile/region # to start,end positions\n try:\n tile_map = pd.DataFrame(data[\"tiles\"])\n except:\n tile_map = pd.DataFrame(data[\"tiles\"], index=[0])\n\n try:\n region_map = pd.DataFrame(data[\"regions\"])\n except:\n region_map = pd.DataFrame(data[\"regions\"], index=[0])\n try:\n samples = pd.DataFrame.from_dict(data[\"samples\"])\n except:\n samples = pd.DataFrame.from_dict(data[\"samples\"], index=[0])\n\n relations = data[\"conditions\"][\"definitions\"]\n # get posterior quality cut off\n var_caller = data[\"varcaller\"]\n return project, seq, cds_seq, tile_map, region_map, samples, var_caller, relations\n\n\ndef loadingAnimation(process):\n \"\"\"\n loading animation to show when loading a process\n \"\"\"\n\n while process.is_alive():\n chars = \"/—\\|\"\n for char in chars:\n sys.stdout.write('\\r'+'downsamping reads ... '+char)\n time.sleep(.1)\n sys.stdout.flush()\n sys.stdout.write(\"\\n\")\n\n\ndef build_lookup(cds_start, cds_end, cds_seq):\n \"\"\"\n build a lookup df for a given gene\n return a df with columns:\n temp_pos, cds, dna_pos, protein, protein_pos\n \"\"\"\n lookup_table = {}\n # list of template pos\n temp = list(range(cds_start, cds_end+1))\n # list of coding DNA bases\n cDNA = [i for i in cds_seq]\n cDNA_pos = list(range(1, len(cDNA)+1))\n # list of protein bases\n protein = [i for i in Seq(cds_seq).translate()]\n protein_pos = range(1, len(protein)+1)\n lookup_table[\"temp_pos\"] = temp\n lookup_table[\"cds\"] = cDNA\n lookup_table[\"cds_pos\"] = cDNA_pos\n lookup_table[\"protein\"] = list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in protein))\n lookup_table[\"protein_pos\"] = list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in protein_pos))\n df = pd.DataFrame(lookup_table)\n return df\n\n\ndef logginginit(log_level, log_f):\n \"\"\"\n Init logging in console as well as main log\n \"\"\"\n log_level = log_level.upper()\n logging.basicConfig(filename=log_f,\n filemode=\"w\",\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n datefmt=\"%m/%d/%Y %I:%M:%S %p\",\n level=log_level)\n\n # define a Handler which writes INFO messages or higher to the sys.stdout\n console = logging.StreamHandler(sys.stdout)\n console.setLevel(log_level)\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(asctime)s - %(name)-8s: %(levelname)-4s %(message)s')\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n\n # stderr_logger = logging.getLogger('STDERR')\n # sl = StreamToLogger(stderr_logger, logging.ERROR)\n # sys.stderr = sl\n\n return logging\n\n\nclass StreamToLogger(object):\n \"\"\"\n Fake file-like stream object that redirects writes to a logger instance.\n \"\"\"\n def __init__(self, logger, log_level=logging.INFO):\n self.logger = logger\n self.log_level = log_level\n self.linebuf = ''\n\n def write(self, buf):\n for line in buf.rstrip().splitlines():\n self.logger.log(self.log_level, line.rstrip())\n\n\nif __name__ == \"__main__\":\n j = \"/home/rothlab2/rli/tileseq_output/210416_CHEK2_QC_2021-04-19-16-02-03/210416_optimizedRef_CHEK2.json\"\n parse_json(j)\n"
] |
[
[
"pandas.DataFrame",
"pandas.DataFrame.from_dict"
]
] |
Doctorado-ML/RSvm
|
[
"42c2e40000d9dded4c80a827aeda236ab91a0cd3"
] |
[
"rsvm/RSvm.py"
] |
[
"import numpy as np\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.utils.multiclass import (\n check_classification_targets,\n type_of_target,\n)\nfrom sklearn.utils.validation import (\n check_X_y,\n check_array,\n check_is_fitted,\n)\n\n\nclass RSvm(BaseEstimator, ClassifierMixin):\n def __init__(\n self,\n C: float = 1,\n kernel: str = \"linear\",\n max_iter: int = 1000,\n random_state: int = None,\n degree: int = 3,\n gamma: float = 1.0,\n verbose: bool = False,\n ):\n self.C = C\n self.kernel = kernel\n self.max_iter = max_iter\n self.random_state = random_state\n self.degree = degree\n self.gamma = gamma\n self.verbose = verbose\n\n def fit(self, X: np.array, y: np.array) -> \"RSvm\":\n if self.C < 0:\n raise ValueError(\n f\"Penalty term must be positive... got (C={self.C:f})\"\n )\n self._kernel = {\n \"poly\": lambda x, y: np.dot(x, y.T) ** self.degree,\n \"rbf\": lambda x, y: np.exp(\n -self.gamma * np.sum((y - x[:, np.newaxis]) ** 2, axis=-1)\n ),\n \"linear\": lambda x, y: np.dot(x, y.T),\n \"sigmoid\": lambda x, y: np.tanh(self.gamma * np.dot(x, y.T)),\n }[self.kernel]\n if type_of_target(y) != \"binary\":\n labels = np.unique(y)\n raise ValueError(\n f\"Only binary problems allowed, found {labels} labels\"\n )\n check_classification_targets(y)\n X, y = check_X_y(X, y)\n # self.y_ = RSvm.normalize_label(y)\n self.X_ = X.copy()\n self.y_ = y * 2 - 1\n self._lambdas = np.zeros_like(self.y_, dtype=float)\n # Vectorized version of Wolfe dual problem (p. 61)?\n self._K = (\n self._kernel(self.X_, self.X_) * self.y_[:, np.newaxis] * self.y_\n )\n\n for iter in range(self.max_iter):\n if self.verbose and iter % 100 == 0:\n print(f\"{iter}, \", end=\"\", flush=True)\n for idxM in range(len(self._lambdas)):\n idxL = np.random.randint(0, len(self._lambdas))\n Q = self._K[\n [[idxM, idxM], [idxL, idxL]], [[idxM, idxL], [idxM, idxL]]\n ]\n v0 = self._lambdas[[idxM, idxL]]\n k0 = 1 - np.sum(self._lambdas * self._K[[idxM, idxL]], axis=1)\n u = np.array([-self.y_[idxL], self.y_[idxM]])\n t_max = np.dot(k0, u) / (np.dot(np.dot(Q, u), u) + 1e-15)\n self._lambdas[[idxM, idxL]] = v0 + u * self.restrict_to_square(\n t_max, v0, u\n )\n\n (idx,) = np.nonzero(self._lambdas > 1e-15)\n self._b = np.mean(\n (1.0 - np.sum(self._K[idx] * self._lambdas, axis=1)) * self.y_[idx]\n )\n self.fitted_ = True\n return self\n\n def restrict_to_square(self, t, v0, u):\n t = (np.clip(v0 + t * u, 0, self.C) - v0)[1] / u[1]\n return (np.clip(v0 + t * u, 0, self.C) - v0)[0] / u[0]\n\n def decision_function(self, X: np.array) -> np.array:\n \"\"\"Evaluate decision_function for the samples in X\n\n Parameters\n ----------\n X : np.array\n The samples to apply the decision function\n\n Returns\n -------\n np.array\n distances of the samples to the hyperplane\n \"\"\"\n return (\n np.sum(self._kernel(X, self.X_) * self.y_ * self._lambdas, axis=1)\n + self._b\n )\n\n def predict(self, X: np.array) -> np.array:\n check_is_fitted(self, [\"fitted_\"])\n X = check_array(X)\n return (np.sign(self.decision_function(X)) + 1) // 2\n"
] |
[
[
"numpy.dot",
"sklearn.utils.validation.check_is_fitted",
"numpy.nonzero",
"sklearn.utils.validation.check_array",
"numpy.unique",
"numpy.clip",
"sklearn.utils.multiclass.check_classification_targets",
"numpy.zeros_like",
"sklearn.utils.validation.check_X_y",
"sklearn.utils.multiclass.type_of_target",
"numpy.array",
"numpy.sum"
]
] |
liuguiyangnwpu/rrcf
|
[
"936ec1356cfbbc2ec77e9c90d7755d8afeb0b093"
] |
[
"test/test_rrcf.py"
] |
[
"import numpy as np\nimport rrcf\n\nnp.random.seed(0)\nn = 100\nd = 3\nX = np.random.randn(n, d)\nZ = np.copy(X)\nZ[90:, :] = 1\n\ntree = rrcf.RCTree(X)\nduplicate_tree = rrcf.RCTree(Z)\n\ntree_seeded = rrcf.RCTree(random_state=0)\nduplicate_tree_seeded = rrcf.RCTree(random_state=np.random.RandomState(0))\n\ndeck = np.arange(n, dtype=int)\nnp.random.shuffle(deck)\nindexes = deck[:5]\n\n\ndef test_batch():\n # Check stored bounding boxes and leaf counts after instantiating from batch\n branches = []\n tree.map_branches(tree.root, op=tree._get_nodes_, stack=branches)\n leafcount = tree._count_leaves_(tree.root)\n assert (leafcount == n)\n for branch in branches:\n leafcount = tree._count_leaves_(branch)\n assert (leafcount == branch.n)\n bbox = tree.get_bbox(branch)\n assert (bbox == branch.b).all()\n\n\ndef test_codisp():\n for i in range(100):\n codisp = tree.codisp(i)\n assert codisp > 0\n\n\ndef test_disp():\n for i in range(100):\n disp = tree.disp(i)\n assert disp > 0\n\n\ndef test_forget_batch():\n # Check stored bounding boxes and leaf counts after forgetting points\n for index in indexes:\n forgotten = tree.forget_point(index)\n branches = []\n tree.map_branches(tree.root, op=tree._get_nodes_, stack=branches)\n for branch in branches:\n leafcount = tree._count_leaves_(branch)\n try:\n assert (leafcount == branch.n)\n except:\n print(forgotten.x)\n print('Computed:\\n', leafcount)\n print('Stored:\\n', branch.n)\n raise\n bbox = tree.get_bbox(branch)\n try:\n assert np.allclose(bbox, branch.b)\n except:\n print(forgotten.x)\n print('Computed:\\n', bbox)\n print('Stored:\\n', branch.b)\n raise\n\n\ndef test_insert_batch():\n # Check stored bounding boxes and leaf counts after inserting points\n for index in indexes:\n x = np.random.randn(d)\n tree.insert_point(x, index=index)\n branches = []\n tree.map_branches(tree.root, op=tree._get_nodes_, stack=branches)\n for branch in branches:\n leafcount = tree._count_leaves_(branch)\n try:\n assert (leafcount == branch.n)\n except:\n print(x)\n print('Computed:\\n', leafcount)\n print('Stored:\\n', branch.n)\n raise\n bbox = tree.get_bbox(branch)\n try:\n assert np.allclose(bbox, branch.b)\n except:\n print(x)\n print('Computed:\\n', bbox)\n print('Stored:\\n', branch.b)\n raise\n\n\ndef test_batch_with_duplicates():\n # Instantiate tree with 10 duplicates\n leafcount = duplicate_tree._count_leaves_(tree.root)\n assert (leafcount == n)\n for i in range(90, 100):\n try:\n assert duplicate_tree.leaves[i].n == 10\n except:\n print(i)\n print(duplicate_tree.leaves[i].n)\n raise\n\n\ndef test_insert_duplicate():\n # Insert duplicate point\n point = (1., 1., 1.)\n leaf = duplicate_tree.insert_point(point, index=100)\n assert leaf.n == 11\n for i in range(90, 100):\n try:\n assert duplicate_tree.leaves[i].n == 11\n except:\n print(i)\n print(duplicate_tree.leaves[i].n)\n raise\n\n\ndef test_find_duplicate():\n # Find duplicate point\n point = (1, 1, 1)\n duplicate = duplicate_tree.find_duplicate(point)\n assert duplicate is not None\n\n\ndef test_forget_duplicate():\n # Forget duplicate point\n leaf = duplicate_tree.forget_point(100)\n for i in range(90, 100):\n assert duplicate_tree.leaves[i].n == 10\n\n\ndef test_shingle():\n shingle = rrcf.shingle(X, 3)\n step_0 = next(shingle)\n step_1 = next(shingle)\n assert (step_0[1] == step_1[0]).all()\n\n\ndef test_random_state():\n # The two trees should have the exact same random-cuts\n points = np.random.uniform(size=(100, 5))\n for idx, point in enumerate(points):\n tree_seeded.insert_point(point, idx)\n duplicate_tree_seeded.insert_point(point, idx)\n assert str(tree_seeded) == str(duplicate_tree_seeded)\n\n\ndef test_insert_depth():\n tree = rrcf.RCTree()\n tree.insert_point([0., 0.], index=0)\n tree.insert_point([0., 0.], index=1)\n tree.insert_point([0., 0.], index=2)\n tree.insert_point([0., 1.], index=3)\n tree.forget_point(index=3)\n min_depth = min(leaf.d for leaf in tree.leaves.values())\n assert min_depth >= 0\n\n\nif __name__ == '__main__':\n test_batch()\n test_batch_with_duplicates()\n test_codisp()\n test_disp()\n test_find_duplicate()\n # test_forget_duplicate()\n test_insert_depth()\n test_shingle()\n"
] |
[
[
"numpy.allclose",
"numpy.random.seed",
"numpy.arange",
"numpy.random.shuffle",
"numpy.copy",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.random.RandomState"
]
] |
soytupadrrre/Master_Python_Eip
|
[
"c4774209d7dd15584233fe5d4cc01b1434c9316b"
] |
[
"creacion_de_aplicaciones/tkinter_iris/app/gui/sepal_plot.py"
] |
[
"import tkinter as tk\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.backends.backend_tkagg import NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\nimport pandas as pd\n\nclass SepalPlotApp:\n def __init__(self, master=None):\n # build ui\n self.sepal_length_plot_view = tk.Tk() if master is None else tk.Toplevel(master)\n self.sepal_length_plot_view.title(\"Victor Luque - Tkinter - Sepal Plot\")\n self.sepal_length_plot_header = tk.Label(self.sepal_length_plot_view)\n self.sepal_length_plot_header.configure(\n font=\"{Calibri} 16 {}\", justify=\"center\", text=\"Sepal Plot\"\n )\n self.sepal_length_plot_header.pack(padx=\"10\", pady=\"10\", side=\"top\")\n self.figure = Figure(figsize=(6, 4))\n self.df = pd.read_csv(\"data/iris.csv\")\n # Create color column based on species\n self.ax = self.figure.add_subplot(111)\n self.ax.set_title(\"Sepal\")\n self.ax.set_xlabel(\"Sepal Length\")\n self.ax.set_ylabel(\"Sepal Width\")\n # Create scatter where self.df[\"species\"] == \"setosa\"\n self.ax.scatter(\n self.df[self.df[\"species\"] == \"setosa\"][\"sepal_length\"],\n self.df[self.df[\"species\"] == \"setosa\"][\"sepal_width\"],\n color=\"blue\",\n label=\"setosa\"\n )\n # Create scatter where self.df[\"species\"] == \"versicolor\"\n self.ax.scatter(\n self.df[self.df[\"species\"] == \"versicolor\"][\"sepal_length\"],\n self.df[self.df[\"species\"] == \"versicolor\"][\"sepal_width\"],\n color=\"green\",\n label=\"versicolor\"\n )\n # Create scatter where self.df[\"species\"] == \"virginica\"\n self.ax.scatter(\n self.df[self.df[\"species\"] == \"virginica\"][\"sepal_length\"],\n self.df[self.df[\"species\"] == \"virginica\"][\"sepal_width\"],\n color=\"red\",\n label=\"virginica\"\n )\n self.ax.legend()\n\n self.canvas = FigureCanvasTkAgg(self.figure, self.sepal_length_plot_view)\n self.canvas.get_tk_widget().pack()\n self.canvas.draw()\n self.canvas.get_tk_widget().pack()\n self.toolbar = NavigationToolbar2Tk(self.canvas, self.sepal_length_plot_view)\n self.toolbar.update()\n self.canvas.get_tk_widget().pack()\n\n self.mainwindow = self.sepal_length_plot_view\n\n def run(self):\n self.mainwindow.mainloop()\n \nif __name__ == \"__main__\":\n app = SepalPlotApp()\n app.run()\n"
] |
[
[
"matplotlib.backends.backend_tkagg.NavigationToolbar2Tk",
"pandas.read_csv",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg",
"matplotlib.figure.Figure"
]
] |
changliao1025/WellApplication
|
[
"dc0d343614b731daea93579347e5820341acf9f6"
] |
[
"wellapplication/MannKendall.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 8 19:55:22 2016\n\n@author: p\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import norm\n\nimport sys\n\nif sys.version_info >= (3, 0):\n def xrange(*args, **kwargs):\n return iter(range(*args, **kwargs))\n\ndef mk_test(x, alpha = 0.05):\n \"\"\"This perform the MK (Mann-Kendall) test to check if there is any trend present in \n data or not\n \n Args:\n x: a vector of data\n alpha: significance level\n \n Returns:\n trend: tells the trend (increasing, decreasing or no trend)\n h: True (if trend is present) or False (if trend is absence)\n p: p value of the sifnificance test\n z: normalized test statistics \n \n Examples::\n >>> x = np.random.rand(100)\n >>> trend = mk_test(x,0.05)\n >>> print(trend.trend)\n increasing\n \n Credit: http://pydoc.net/Python/ambhas/0.4.0/ambhas.stats/\n \"\"\"\n n = len(x)\n ta = n*(n-1)/2\n # calculate S \n s = 0\n for k in xrange(n-1):\n for j in xrange(k+1,n):\n s += np.sign(x[j] - x[k])\n \n # calculate the unique data\n unique_x = np.unique(x)\n g = len(unique_x)\n \n # calculate the var(s)\n if n == g: # there is no tie\n var_s = (n*(n-1)*(2*n+5))/18\n else: # there are some ties in data\n tp = np.zeros(unique_x.shape)\n for i in xrange(len(unique_x)):\n tp[i] = sum(unique_x[i] == x)\n var_s = (n*(n-1)*(2*n+5) - np.sum(tp*(tp-1)*(2*tp+5)))/18\n \n if s>0:\n z = (s - 1)/np.sqrt(var_s)\n elif s == 0:\n z = 0\n elif s<0:\n z = (s + 1)/np.sqrt(var_s)\n else:\n z = 0\n \n # calculate the p_value\n p = 2*(1- norm.cdf(abs(z))) # two tail test\n h = abs(z) > norm.ppf(1-alpha/2)\n \n if (z<0) and h:\n trend = 'decreasing'\n elif (z>0) and h:\n trend = 'increasing'\n else:\n trend = 'no trend'\n \n return pd.Series({'trend':trend, 'varS':round(var_s,3), 'p':round(p,3), 'z':round(z,3), 's':round(s,3), 'n':n, 'ta':ta})\n \ndef mk_ts(df, const, group1, orderby = 'year', alpha = 0.05):\n \"\"\"\n df = dataframe\n const = variable tested for trend\n group1 = variable to group by\n orderby = variable to order by (typically a date)\n \"\"\"\n \n def zcalc(Sp, Varp):\n if Sp > 0:\n return (Sp - 1)/Varp**0.5\n elif Sp < 0:\n return (Sp + 1)/Varp**0.5\n else:\n return 0 \n \n df.is_copy = False\n \n df[const] = pd.to_numeric(df.ix[:,const])\n # remove null values\n df[const].dropna(inplace=True)\n # remove index\n df.reset_index(inplace=True, drop=True)\n # sort by groups, then time\n df.sort_values(by=[group1,orderby],axis=0, inplace=True)\n \n # group by group and apply mk_test\n dg = df.groupby(group1).apply(lambda x: mk_test(x.loc[:,const].dropna().values, alpha))\n Var_S = dg.loc[:,'varS'].sum()\n S = dg.loc[:,'s'].sum()\n N = dg.loc[:,'n'].sum()\n Z = zcalc(S,Var_S)\n P = 2*(1-norm.cdf(abs(Z)))\n group_n = len(dg)\n h = abs(Z) > norm.ppf(1-alpha/2) \n tau = S/dg.loc[:,'ta'].sum()\n\n if (Z<0) and h:\n trend = 'decreasing'\n elif (Z>0) and h:\n trend = 'increasing'\n else:\n trend = 'no trend'\n \n \n return pd.Series({'S':S, 'Z':round(Z,2), 'p':P, 'trend':trend, 'group_n':group_n, 'sample_n':N, 'Var_S':Var_S, 'tau':round(tau,2)})\n\n \n"
] |
[
[
"scipy.stats.norm.ppf",
"numpy.sqrt",
"numpy.unique",
"numpy.sign",
"pandas.to_numeric",
"numpy.sum",
"numpy.zeros"
]
] |
nasa42/prophet
|
[
"31de123e3ca2ad9c448088be4905f44f47b5b087"
] |
[
"test/support/country_holidays.py"
] |
[
"import pandas as pd\nfrom fbprophet import Prophet\n\n# float_precision='high' required for pd.read_csv to match precision of Rover.read_csv\ndf = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high')\n\nm = Prophet()\nm.add_country_holidays(country_name='US')\nm.fit(df, seed=123)\nfuture = m.make_future_dataframe(periods=365)\nforecast = m.predict(future)\nprint(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())\nm.plot(forecast).savefig('/tmp/py_country_holidays.png')\nm.plot_components(forecast).savefig('/tmp/py_country_holidays2.png')\n"
] |
[
[
"pandas.read_csv"
]
] |
ViktorAlm/COVID-QA
|
[
"a2a300f07b02aa5b2e078c1f2bb184894717264d"
] |
[
"datasources/META_scraper.py"
] |
[
"import importlib.util\nimport logging\nimport os\n\nimport pandas as pd\nfrom haystack.database.elasticsearch import ElasticsearchDocumentStore\nfrom haystack.retriever.elasticsearch import ElasticsearchRetriever\nfrom scrapy.crawler import CrawlerProcess\n\nlogger = logging.getLogger(__name__)\n\nPATH = os.getcwd() + \"/scrapers\"\nRESULTS = []\nMISSED = []\n\n\nclass Pipeline(object):\n questionsOnly = True\n\n def filter(self, item, index):\n question = item['question'][index].strip()\n if self.questionsOnly and not question.endswith(\"?\"):\n return False\n if len(item['answer'][index].strip()) == 0:\n return False\n return True\n\n def process_item(self, item, spider):\n if len(item['question']) == 0:\n logger.error(\"Scraper '\" + spider.name + \"' provided zero results!\")\n MISSED.append(spider.name)\n return\n validatedItems = {}\n for key, values in item.items():\n validatedItems[key] = []\n for i in range(len(item['question'])):\n if not self.filter(item, i):\n continue\n for key, values in item.items():\n validatedItems[key].append(values[i])\n if len(validatedItems['question']) == 0:\n logger.error(\"Scraper '\" + spider.name + \"' provided zero results after filtering!\")\n MISSED.append(spider.name)\n return\n df = pd.DataFrame.from_dict(validatedItems)\n RESULTS.append(df)\n\n\nif __name__ == \"__main__\":\n logging.disable(logging.WARNING)\n\n crawler_files = [os.path.join(PATH, f) for f in os.listdir(PATH) if os.path.isfile(os.path.join(PATH, f)) and (not f.startswith('.'))]\n process = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',\n 'ITEM_PIPELINES': {'__main__.Pipeline': 1}\n })\n for crawler in crawler_files:\n scraper_spec = importlib.util.spec_from_file_location(\"CovidScraper\", crawler)\n scraper = importlib.util.module_from_spec(scraper_spec)\n scraper_spec.loader.exec_module(scraper)\n CovidScraper = scraper.CovidScraper\n process.crawl(CovidScraper)\n process.start()\n dataframe = pd.concat(RESULTS)\n if len(MISSED) > 0:\n logger.error(f\"Could not scrape: {', '.join(MISSED)} \")\n\n MODEL = \"bert-base-uncased\"\n GPU = False\n document_store = ElasticsearchDocumentStore(\n host=\"localhost\",\n username=\"\",\n password=\"\",\n index=\"document\",\n text_field=\"answer\",\n embedding_field=\"question_emb\",\n embedding_dim=768,\n excluded_meta_data=[\"question_emb\"],\n )\n\n retriever = ElasticsearchRetriever(document_store=document_store, embedding_model=MODEL, gpu=GPU)\n\n dataframe.fillna(value=\"\", inplace=True)\n # Index to ES\n docs_to_index = []\n\n for doc_id, (_, row) in enumerate(dataframe.iterrows()):\n d = row.to_dict()\n d = {k: v.strip() for k, v in d.items()}\n d[\"document_id\"] = doc_id\n # add embedding\n question_embedding = retriever.create_embedding(row[\"question\"])\n d[\"question_emb\"] = question_embedding\n docs_to_index.append(d)\n document_store.write_documents(docs_to_index)\n"
] |
[
[
"pandas.concat",
"pandas.DataFrame.from_dict"
]
] |
ft-lab/Shade3D_sample_scripts
|
[
"881fef1affce09d5ba6b5081256c8e4ef4c334ae"
] |
[
"scripts/ConvLineToPolyLine.py"
] |
[
"# -----------------------------------------------------.\n# 線形状を等間隔の直線群に変換.\n#\n# @title \\en Convert line to equally spaced line groups \\enden\n# @title \\ja 線形状を等間隔の直線群に変換 \\endja\n# -----------------------------------------------------.\nimport numpy\nimport math\n\nscene = xshade.scene()\n\n#---------------------------------------.\n# ゼロチェック.\n#---------------------------------------.\ndef isZero (v):\n minV = 1e-5\n if v > -minV and v < minV:\n return True\n return False\n\n#---------------------------------------.\n# ベジェ上の位置を計算.\n#---------------------------------------.\ndef getBezierPoint (v1Pos, v1Out, v2In, v2Pos, fPos):\n fMin = 1e-6\n\n rPos = [0.0, 0.0, 0.0]\n cPos = []\n cPos.append([v1Pos[0], v1Pos[1], v1Pos[2]])\n cPos.append([v1Out[0], v1Out[1], v1Out[2]])\n cPos.append([v2In[0], v2In[1], v2In[2]])\n cPos.append([v2Pos[0], v2Pos[1], v2Pos[2]])\n\n fPos2 = float(fPos)\n fPos2 = max(0.0, fPos2)\n fPos2 = min(1.0, fPos2)\n \n if isZero(fPos2):\n rPos = cPos[0]\n return rPos\n\n if isZero(fPos2 - 1.0):\n rPos = cPos[3]\n return rPos\n\n # ベジェ曲線の計算.\n t = fPos2\n t2 = 1.0 - t\n t2d = t2 * t2\n td = t * t\n b1 = t2d * t2\n b2 = 3.0 * t * t2d\n b3 = 3.0 * td * t2\n b4 = t * td\n\n for i in range(3):\n rPos[i] = b1 * cPos[0][i] + b2 * cPos[1][i] + b3 * cPos[2][i] + b4 * cPos[3][i]\n\n return rPos\n\n#---------------------------------------.\n# 線形状を直線の集まりに分解.\n# @param[in] shape 対象形状.\n# @param[in] lineDivCou ラインの全体の分割数.\n# @return ポイントの配列.\n#---------------------------------------.\ndef getLinePoints (shape, lineDivCou):\n vCou = shape.total_number_of_control_points\n vList = []\n if shape.type != 4 or vCou < 2: # 線形状でない場合.\n return vList\n \n divCou = lineDivCou / vCou\n if divCou < 4:\n divCou = 4\n divD = 1.0 / float(divCou)\n\n # ベジェをポイントで保持.\n for i in range(vCou):\n if shape.closed == False and (i + 1 >= vCou):\n break\n p1 = shape.control_point(i)\n p2 = shape.control_point((i + 1) % vCou)\n\n dPos = 0.0\n for j in range(divCou + 1):\n p = getBezierPoint(p1.position, p1.out_handle, p2.in_handle, p2.position, dPos)\n if (i == 0) or (i != 0 and j > 0):\n vList.append(p)\n dPos += divD\n\n return vList\n\n#---------------------------------------.\n# ポイントのみで構成された配列情報から、等間隔になるように再計算.\n# @param[in] vList ポイントの配列.\n# @param[in] divCou 新しいラインの分割数.\n# @return ポイントの配列.\n#---------------------------------------.\ndef recalcLinePoints (vList, divCou):\n # numpyの形式に配列に格納し直す.\n vListLen = len(vList)\n if vListLen < 2:\n return []\n\n posA = []\n for i in range(vListLen):\n posA.append(numpy.array([vList[i][0], vList[i][1], vList[i][2]]))\n\n # ラインの長さを計算.\n allLen = 0.0\n lenList = []\n for i in range(vListLen - 1):\n vLen = numpy.linalg.norm(posA[i + 1] - posA[i])\n lenList.append(vLen)\n allLen += vLen\n\n dLen = allLen / (divCou - 1.0)\n newPosA = []\n newPosA.append([posA[0][0], posA[0][1], posA[0][2]])\n dPos = 0.0\n for i in range(vListLen - 1):\n len1 = lenList[i]\n\n if dPos + len1 < dLen:\n dPos += len1\n continue\n\n dPos2 = 0.0\n while dPos2 < len1:\n dd = (dPos2 + (dLen - dPos)) / len1\n p = (posA[i + 1] - posA[i]) * dd + posA[i]\n newPosA.append([p[0], p[1], p[2]])\n if len(newPosA) >= divCou - 1:\n break\n dd2 = dLen - dPos\n if dPos2 + dd2 + dLen > len1:\n dPos = len1 - (dPos2 + dd2)\n break\n dPos2 += dd2\n dPos = 0.0\n\n if len(newPosA) >= divCou - 1:\n break\n\n newPosA.append([posA[-1][0], posA[-1][1], posA[-1][2]])\n return newPosA\n\n# ---------------------------------------------.\nshape = scene.active_shape()\n\nif shape.type != 4 or shape.total_number_of_control_points < 2:\n xshade.show_message_box('ポイント数が2以上の線形状を選択してください。', False)\n\nelse:\n # ダイアログボックスの作成と表示.\n dlg = xshade.create_dialog_with_uuid('05783960-e90b-4a70-9488-daefa220447e')\n div_id = dlg.append_int('分割数')\n dlg.set_value(div_id, 10)\n dlg.set_default_value(div_id, 10)\n\n dlg.append_default_button()\n\n if dlg.ask(\"線形状を等間隔の直線群に変換\"):\n rDivCou = dlg.get_value(div_id) + 1\n if rDivCou < 2:\n rDivCou = 2\n\n # 線形状をポイントで分割.\n divCou = min(40, rDivCou * 4)\n vList = getLinePoints(shape, divCou)\n vList2 = recalcLinePoints(vList, rDivCou)\n if shape.closed:\n vList2.pop()\n\n # 線形状として配置.\n scene.begin_creating()\n scene.begin_line(None, shape.closed)\n\n for p in vList2:\n scene.append_point(p)\n\n scene.end_line()\n scene.end_creating()\n"
] |
[
[
"numpy.array",
"numpy.linalg.norm"
]
] |
AlexB-B/DeePyMoD_torch_AlexVersion
|
[
"183f938e3a9a9acfb43f9bc0ce4629ed64b0fa0c"
] |
[
"src/deepymod_torch/network.py"
] |
[
"import torch\nimport torch.nn as nn\n\n\nclass Library(nn.Module):\n def __init__(self, library_func, library_args={}):\n super().__init__()\n self.library_func = library_func\n self.library_args = library_args\n\n def forward(self, input):\n self.time_deriv_list, self.theta = self.library_func(input, **self.library_args)\n return self.time_deriv_list, self.theta\n\n\nclass Fitting(nn.Module):\n def __init__(self, n_equations, n_terms, library_config):\n super().__init__()\n tensor_list = [torch.rand((n_terms, 1), dtype=torch.float32) for _ in torch.arange(n_equations)]\n if 'coeff_sign' in library_config:\n tensor_list = [library_config['coeff_sign']*abs(tensor) for tensor in tensor_list]\n self.coeff_vector = nn.ParameterList([torch.nn.Parameter(tensor) for tensor in tensor_list])\n self.sparsity_mask = [torch.arange(n_terms) for _ in torch.arange(n_equations)]\n self.coeff_vector_history = []\n self.sparsity_mask_history = []\n\n def forward(self, input):\n sparse_theta = self.apply_mask(input)\n return sparse_theta, self.coeff_vector\n\n def apply_mask(self, theta):\n sparse_theta = [theta[:, sparsity_mask] for sparsity_mask in self.sparsity_mask]\n return sparse_theta\n"
] |
[
[
"torch.nn.Parameter",
"torch.rand",
"torch.arange"
]
] |
jcraig0/MiniAlphaZero
|
[
"b1533263d4ef6fadbf6ecff69cff6149747b6079"
] |
[
"mcts.py"
] |
[
"import torch\r\nimport config\r\nimport math\r\nimport copy\r\n\r\n\r\nclass Node:\r\n def __init__(self):\r\n self.wins = 0\r\n self.visits = 0\r\n self.probs = None\r\n self.move = None\r\n self.children = []\r\n self.parent = None\r\n\r\n\r\ndef board_to_tensor(board):\r\n row_num, col_num = len(board.grid), len(board.grid[0])\r\n tensor = torch.zeros([1, 1, row_num, col_num], dtype=torch.float).cuda()\r\n for i in range(row_num):\r\n for j in range(col_num):\r\n value = {'X': 1, 'O': 0, ' ': .5}[board.grid[i][j]]\r\n tensor[0, 0, i, j] = value if board.turn else 1 - value\r\n return tensor\r\n\r\n\r\ndef ucb(curr_node, child):\r\n prob = curr_node.probs[child.move]\r\n if child.visits:\r\n # \"-1 + 2 *\" projects the range [0, 1] to [-1, 1]\r\n return -1 + 2 * child.wins / child.visits + prob \\\r\n * math.sqrt(curr_node.visits) / (child.visits + 1)\r\n else:\r\n return prob * math.sqrt(curr_node.visits + 1e-8)\r\n\r\n\r\ndef simulate(model, board):\r\n model.eval()\r\n root = Node()\r\n\r\n for i in range(config.MCTS_SIMS):\r\n board_copy = copy.deepcopy(board)\r\n curr_node = root\r\n\r\n # Selection phase\r\n while curr_node.children:\r\n curr_node = max(curr_node.children, key=lambda child:\r\n ucb(curr_node, child))\r\n board_copy.push(curr_node.move)\r\n\r\n # Expansion phase\r\n if not board_copy.is_game_over():\r\n with torch.no_grad():\r\n policy, value = model(board_to_tensor(board_copy))\r\n\r\n move_nums = torch.zeros(board.num_total_moves).cuda()\r\n for move in board_copy.legal_moves:\r\n new_node = Node()\r\n new_node.move = move\r\n new_node.parent = curr_node\r\n curr_node.children.append(new_node)\r\n move_nums[move] = 1\r\n policy *= move_nums\r\n curr_node.probs = (policy / torch.sum(policy)).tolist()\r\n\r\n value = value.item()\r\n else:\r\n # To be inverted to the correct value in backpropagation\r\n value = .5 if board_copy.winner == '1/2-1/2' else 0\r\n\r\n # Backpropagation phase\r\n while curr_node is not None:\r\n # Value is inverted to pertain to previous player\r\n value = 1 - value\r\n curr_node.wins += value\r\n curr_node.visits += 1\r\n curr_node = curr_node.parent\r\n\r\n return root\r\n"
] |
[
[
"torch.sum",
"torch.no_grad",
"torch.zeros"
]
] |
MunkiChung/dm_control
|
[
"eeddc6619979c5e10ce554c4496b9f41bee90711"
] |
[
"dm_control/mujoco/wrapper/core.py"
] |
[
"# Copyright 2017 The dm_control 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\n\"\"\"Main user-facing classes and utility functions for loading MuJoCo models.\"\"\"\n\nimport contextlib\nimport ctypes\nimport os\nimport threading\nimport weakref\n\nfrom absl import logging\n\nfrom dm_control.mujoco.wrapper import util\nfrom dm_control.mujoco.wrapper.mjbindings import constants\nfrom dm_control.mujoco.wrapper.mjbindings import enums\nfrom dm_control.mujoco.wrapper.mjbindings import functions\nfrom dm_control.mujoco.wrapper.mjbindings import mjlib\nfrom dm_control.mujoco.wrapper.mjbindings import types\nfrom dm_control.mujoco.wrapper.mjbindings import wrappers\nimport numpy as np\n\n# Internal analytics import.\n# Unused internal import: resources.\n\n_NULL = b\"\\00\"\n_FAKE_XML_FILENAME = b\"model.xml\"\n_FAKE_BINARY_FILENAME = b\"model.mjb\"\n\n# Although `mjMAXVFSNAME` from `mjmodel.h` specifies a limit of 100 bytes\n# (including the terminal null byte), the actual limit seems to be 99 bytes\n# (98 characters).\n_MAX_VFS_FILENAME_CHARACTERS = 98\n_VFS_FILENAME_TOO_LONG = (\n \"Filename length {length} exceeds {limit} character limit: {filename}\")\n_INVALID_FONT_SCALE = (\"`font_scale` must be one of {}, got {{}}.\"\n .format(enums.mjtFontScale))\n\n_CONTACT_ID_OUT_OF_RANGE = (\n \"`contact_id` must be between 0 and {max_valid} (inclusive), got: {actual}.\"\n)\n\n# Global cache used to store finalizers for freeing ctypes pointers.\n# Contains {pointer_address: weakref_object} pairs.\n_FINALIZERS = {}\n\n\nclass Error(Exception):\n \"\"\"Base class for MuJoCo exceptions.\"\"\"\n pass\n\n\nif constants.mjVERSION_HEADER != mjlib.mj_version():\n raise Error(\"MuJoCo library version ({0}) does not match header version \"\n \"({1})\".format(constants.mjVERSION_HEADER, mjlib.mj_version()))\n\n_REGISTERED = False\n_REGISTRATION_LOCK = threading.Lock()\n_ERROR_BUFSIZE = 1000\n\n# This is used to keep track of the `MJMODEL` pointer that was most recently\n# loaded by `_get_model_ptr_from_xml`. Only this model can be saved to XML.\n_LAST_PARSED_MODEL_PTR = None\n\n_NOT_LAST_PARSED_ERROR = (\n \"Only the model that was most recently loaded from an XML file or string \"\n \"can be saved to an XML file.\")\n\nimport time\n\n# NB: Python functions that are called from C are defined at module-level to\n# ensure they won't be garbage-collected before they are called.\[email protected](None, ctypes.c_char_p)\ndef _warning_callback(message):\n logging.warning(util.to_native_string(message))\n\n\[email protected](None, ctypes.c_char_p)\ndef _error_callback(message):\n logging.fatal(util.to_native_string(message))\n\n\n# Override MuJoCo's callbacks for handling warnings and errors.\nmjlib.mju_user_warning = ctypes.c_void_p.in_dll(mjlib, \"mju_user_warning\")\nmjlib.mju_user_error = ctypes.c_void_p.in_dll(mjlib, \"mju_user_error\")\nmjlib.mju_user_warning.value = ctypes.cast(\n _warning_callback, ctypes.c_void_p).value\nmjlib.mju_user_error.value = ctypes.cast(\n _error_callback, ctypes.c_void_p).value\n\n\ndef enable_timer(enabled=True):\n if enabled:\n set_callback(\"mjcb_time\", time.time)\n else:\n set_callback(\"mjcb_time\", None)\n\n\ndef _maybe_register_license(path=None):\n \"\"\"Registers the MuJoCo license if not already registered.\n\n Args:\n path: Optional custom path to license key file.\n\n Raises:\n Error: If the license could not be registered.\n \"\"\"\n with _REGISTRATION_LOCK:\n global _REGISTERED\n if not _REGISTERED:\n if path is None:\n path = util.get_mjkey_path()\n # TODO(b/176220357): Repeatedly activating a trial license results in\n # errors (for example this could happen if\n # `mj_activate` was already called by another library\n # within the same process). To avoid such errors we\n # unconditionally deactivate any active licenses before\n # calling `mj_activate`.\n mjlib.mj_deactivate()\n result = mjlib.mj_activate(util.to_binary_string(path))\n if result == 1:\n _REGISTERED = True\n # Internal analytics of mj_activate.\n elif result == 0:\n raise Error(\"Could not register MuJoCo license. Acquire a license \"\n \"here: https://www.roboti.us/license.html\")\n else:\n raise Error(\"Unknown error while registering MuJoCo license \"\n \"(code: {})\".format(result))\n\n\ndef _str2type(type_str):\n type_id = mjlib.mju_str2Type(util.to_binary_string(type_str))\n if not type_id:\n raise Error(\"{!r} is not a valid object type name.\".format(type_str))\n return type_id\n\n\ndef _type2str(type_id):\n type_str_ptr = mjlib.mju_type2Str(type_id)\n if not type_str_ptr:\n raise Error(\"{!r} is not a valid object type ID.\".format(type_id))\n return ctypes.string_at(type_str_ptr)\n\n\ndef set_callback(name, new_callback=None):\n \"\"\"Sets a user-defined callback function to modify MuJoCo's behavior.\n\n Callback functions should have the following signature:\n func(const_mjmodel_ptr, mjdata_ptr) -> None\n\n Args:\n name: Name of the callback to set. Must be a field in\n `functions.function_pointers`.\n new_callback: The new callback. This can be one of the following:\n * A Python callable\n * A C function exposed by a `ctypes.CDLL` object\n * An integer specifying the address of a callback function\n * None, in which case any existing callback of that name is removed\n \"\"\"\n setattr(functions.callbacks, name, new_callback)\n\n\[email protected]\ndef callback_context(name, new_callback=None):\n \"\"\"Context manager that temporarily overrides a MuJoCo callback function.\n\n On exit, the callback will be restored to its original value (None if the\n callback was not already overridden when the context was entered).\n\n Args:\n name: Name of the callback to set. Must be a field in\n `mjbindings.function_pointers`.\n new_callback: The new callback. This can be one of the following:\n * A Python callable\n * A C function exposed by a `ctypes.CDLL` object\n * An integer specifying the address of a callback function\n * None, in which case any existing callback of that name is removed\n\n Yields:\n None\n \"\"\"\n old_callback = getattr(functions.callbacks, name)\n set_callback(name, new_callback)\n try:\n yield\n finally:\n # Ensure that the callback is reset on exit, even if an exception is raised.\n set_callback(name, old_callback)\n\n\ndef get_schema():\n \"\"\"Returns a string containing the schema used by the MuJoCo XML parser.\"\"\"\n buf = ctypes.create_string_buffer(100000)\n mjlib.mj_printSchema(None, buf, len(buf), 0, 0)\n return buf.value\n\n\[email protected]\ndef _temporary_vfs(filenames_and_contents):\n \"\"\"Creates a temporary VFS containing one or more files.\n\n Args:\n filenames_and_contents: A dict containing `{filename: contents}` pairs.\n The length of each filename must not exceed 98 characters.\n\n Yields:\n A `types.MJVFS` instance.\n\n Raises:\n Error: If a file cannot be added to the VFS, or if an error occurs when\n looking up the filename.\n ValueError: If the length of a filename exceeds 98 characters.\n \"\"\"\n vfs = types.MJVFS()\n mjlib.mj_defaultVFS(vfs)\n for filename, contents in filenames_and_contents.items():\n if len(filename) > _MAX_VFS_FILENAME_CHARACTERS:\n raise ValueError(\n _VFS_FILENAME_TOO_LONG.format(\n length=len(filename),\n limit=_MAX_VFS_FILENAME_CHARACTERS,\n filename=filename))\n filename = util.to_binary_string(filename)\n contents = util.to_binary_string(contents)\n _, extension = os.path.splitext(filename)\n # For XML files we need to append a NULL byte, otherwise MuJoCo's parser\n # can sometimes read past the end of the string. However, we should *not*\n # do this for other file types (in particular for STL meshes, where this\n # causes MuJoCo's compiler to complain that the file size is incorrect).\n append_null = extension.lower() == b\".xml\"\n num_bytes = len(contents) + append_null\n retcode = mjlib.mj_makeEmptyFileVFS(vfs, filename, num_bytes)\n if retcode == 1:\n raise Error(\"Failed to create {!r}: VFS is full.\".format(filename))\n elif retcode == 2:\n raise Error(\"Failed to create {!r}: duplicate filename.\".format(filename))\n file_index = mjlib.mj_findFileVFS(vfs, filename)\n if file_index == -1:\n raise Error(\"Could not find {!r} in the VFS\".format(filename))\n vf = vfs.filedata[file_index]\n vf_as_char_arr = ctypes.cast(vf, ctypes.POINTER(ctypes.c_char * num_bytes))\n vf_as_char_arr.contents[:len(contents)] = contents\n if append_null:\n vf_as_char_arr.contents[-1] = _NULL\n try:\n yield vfs\n finally:\n mjlib.mj_deleteVFS(vfs) # Ensure that we free the VFS afterwards.\n\n\ndef _create_finalizer(ptr, free_func):\n \"\"\"Creates a finalizer for a ctypes pointer.\n\n Args:\n ptr: A `ctypes.POINTER` to be freed.\n free_func: A callable that frees the pointer. It will be called with `ptr`\n as its only argument when `ptr` is garbage collected.\n \"\"\"\n ptr_type = type(ptr)\n address = ctypes.addressof(ptr.contents)\n\n if address not in _FINALIZERS: # Only one finalizer needed per address.\n\n logging.debug(\"Allocated %s at %x\", ptr_type.__name__, address)\n\n def callback(dead_ptr_ref):\n \"\"\"A weakref callback that frees the resource held by a pointer.\"\"\"\n del dead_ptr_ref # Unused weakref to the dead ctypes pointer object.\n if address not in _FINALIZERS:\n # Someone had already explicitly called `call_finalizer_for_pointer`.\n return\n else:\n # Turn the address back into a pointer to be freed.\n if ctypes.cast is None:\n return\n # `ctypes.cast` might be None if the interpreter is in the process of\n # exiting. In this case it doesn't really matter whether or not we\n # explicitly free the pointer, since any remaining pointers will be\n # freed anyway when the process terminates. We bail out silently in\n # order to avoid logging an unsightly (but harmless) error.\n temp_ptr = ctypes.cast(address, ptr_type)\n free_func(temp_ptr)\n logging.debug(\"Freed %s at %x\", ptr_type.__name__, address)\n del _FINALIZERS[address] # Remove the weakref from the global cache.\n\n # Store weakrefs in a global cache so that they don't get garbage collected\n # before their referents.\n _FINALIZERS[address] = (weakref.ref(ptr, callback), callback)\n\n\ndef _finalize(ptr):\n \"\"\"Calls the finalizer for the specified pointer to free allocated memory.\"\"\"\n address = ctypes.addressof(ptr.contents)\n try:\n ptr_ref, callback = _FINALIZERS[address]\n callback(ptr_ref)\n except KeyError:\n pass\n\n\ndef _load_xml(filename, vfs_or_none):\n \"\"\"Invokes `mj_loadXML` with logging/error handling.\"\"\"\n error_buf = ctypes.create_string_buffer(_ERROR_BUFSIZE)\n model_ptr = mjlib.mj_loadXML(\n util.to_binary_string(filename),\n vfs_or_none,\n error_buf,\n _ERROR_BUFSIZE)\n if not model_ptr:\n raise Error(util.to_native_string(error_buf.value))\n elif error_buf.value:\n logging.warning(util.to_native_string(error_buf.value))\n\n # Free resources when the ctypes pointer is garbage collected.\n _create_finalizer(model_ptr, mjlib.mj_deleteModel)\n\n return model_ptr\n\n\ndef _get_model_ptr_from_xml(xml_path=None, xml_string=None, assets=None):\n \"\"\"Parses a model XML file, compiles it, and returns a pointer to an mjModel.\n\n Args:\n xml_path: None or a path to a model XML file in MJCF or URDF format.\n xml_string: None or an XML string containing an MJCF or URDF model\n description.\n assets: None or a dict containing external assets referenced by the model\n (such as additional XML files, textures, meshes etc.), in the form of\n `{filename: contents_string}` pairs. The keys should correspond to the\n filenames specified in the model XML. Ignored if `xml_string` is None.\n\n One of `xml_path` or `xml_string` must be specified.\n\n Returns:\n A `ctypes.POINTER` to a new `mjbindings.types.MJMODEL` instance.\n\n Raises:\n TypeError: If both or neither of `xml_path` and `xml_string` are specified.\n Error: If the model is not created successfully.\n \"\"\"\n if xml_path is None and xml_string is None:\n raise TypeError(\n \"At least one of `xml_path` or `xml_string` must be specified.\")\n elif xml_path is not None and xml_string is not None:\n raise TypeError(\n \"Only one of `xml_path` or `xml_string` may be specified.\")\n\n _maybe_register_license()\n\n if xml_string is not None:\n assets = {} if assets is None else assets.copy()\n # Ensure that the fake XML filename doesn't overwrite an existing asset.\n xml_path = _FAKE_XML_FILENAME\n while xml_path in assets:\n xml_path = \"_\" + xml_path\n assets[xml_path] = xml_string\n with _temporary_vfs(assets) as vfs:\n ptr = _load_xml(xml_path, vfs)\n else:\n ptr = _load_xml(xml_path, None)\n\n global _LAST_PARSED_MODEL_PTR\n _LAST_PARSED_MODEL_PTR = ptr\n\n return ptr\n\n\ndef save_last_parsed_model_to_xml(xml_path, check_model=None):\n \"\"\"Writes a description of the most recently loaded model to an MJCF XML file.\n\n Args:\n xml_path: Path to the output XML file.\n check_model: Optional `MjModel` instance. If specified, this model will be\n checked to see if it is the most recently parsed one, and a ValueError\n will be raised otherwise.\n Raises:\n Error: If MuJoCo encounters an error while writing the XML file.\n ValueError: If `check_model` was passed, and this model is not the most\n recently parsed one.\n \"\"\"\n if check_model and check_model.ptr is not _LAST_PARSED_MODEL_PTR:\n raise ValueError(_NOT_LAST_PARSED_ERROR)\n error_buf = ctypes.create_string_buffer(_ERROR_BUFSIZE)\n mjlib.mj_saveLastXML(util.to_binary_string(xml_path),\n _LAST_PARSED_MODEL_PTR,\n error_buf,\n _ERROR_BUFSIZE)\n if error_buf.value:\n raise Error(error_buf.value)\n\n\ndef _get_model_ptr_from_binary(binary_path=None, byte_string=None):\n \"\"\"Returns a pointer to an mjModel from the contents of a MuJoCo model binary.\n\n Args:\n binary_path: Path to an MJB file (as produced by MjModel.save_binary).\n byte_string: String of bytes (as returned by MjModel.to_bytes).\n\n One of `binary_path` or `byte_string` must be specified.\n\n Returns:\n A `ctypes.POINTER` to a new `mjbindings.types.MJMODEL` instance.\n\n Raises:\n TypeError: If both or neither of `byte_string` and `binary_path`\n are specified.\n \"\"\"\n if binary_path is None and byte_string is None:\n raise TypeError(\n \"At least one of `byte_string` or `binary_path` must be specified.\")\n elif binary_path is not None and byte_string is not None:\n raise TypeError(\n \"Only one of `byte_string` or `binary_path` may be specified.\")\n\n _maybe_register_license()\n\n if byte_string is not None:\n with _temporary_vfs({_FAKE_BINARY_FILENAME: byte_string}) as vfs:\n ptr = mjlib.mj_loadModel(_FAKE_BINARY_FILENAME, vfs)\n else:\n ptr = mjlib.mj_loadModel(util.to_binary_string(binary_path), None)\n\n # Free resources when the ctypes pointer is garbage collected.\n _create_finalizer(ptr, mjlib.mj_deleteModel)\n\n return ptr\n\n\n# Subclasses implementing constructors/destructors for low-level wrappers.\n# ------------------------------------------------------------------------------\n\n\nclass MjModel(wrappers.MjModelWrapper):\n \"\"\"Wrapper class for a MuJoCo 'mjModel' instance.\n\n MjModel encapsulates features of the model that are expected to remain\n constant. It also contains simulation and visualization options which may be\n changed occasionally, although this is done explicitly by the user.\n \"\"\"\n\n def __init__(self, model_ptr):\n \"\"\"Creates a new MjModel instance from a ctypes pointer.\n\n Args:\n model_ptr: A `ctypes.POINTER` to an `mjbindings.types.MJMODEL` instance.\n \"\"\"\n super().__init__(ptr=model_ptr)\n\n def __getstate__(self):\n # All of MjModel's state is assumed to reside within the MuJoCo C struct.\n # However there is no mechanism to prevent users from adding arbitrary\n # Python attributes to an MjModel instance - these would not be serialized.\n return self.to_bytes()\n\n def __setstate__(self, byte_string):\n model_ptr = _get_model_ptr_from_binary(byte_string=byte_string)\n self.__init__(model_ptr)\n\n def __copy__(self):\n new_model_ptr = mjlib.mj_copyModel(None, self.ptr)\n return self.__class__(new_model_ptr)\n\n @classmethod\n def from_xml_string(cls, xml_string, assets=None):\n \"\"\"Creates an `MjModel` instance from a model description XML string.\n\n Args:\n xml_string: String containing an MJCF or URDF model description.\n assets: Optional dict containing external assets referenced by the model\n (such as additional XML files, textures, meshes etc.), in the form of\n `{filename: contents_string}` pairs. The keys should correspond to the\n filenames specified in the model XML.\n\n Returns:\n An `MjModel` instance.\n \"\"\"\n model_ptr = _get_model_ptr_from_xml(xml_string=xml_string, assets=assets)\n return cls(model_ptr)\n\n @classmethod\n def from_byte_string(cls, byte_string):\n \"\"\"Creates an MjModel instance from a model binary as a string of bytes.\"\"\"\n model_ptr = _get_model_ptr_from_binary(byte_string=byte_string)\n return cls(model_ptr)\n\n @classmethod\n def from_xml_path(cls, xml_path):\n \"\"\"Creates an MjModel instance from a path to a model XML file.\"\"\"\n model_ptr = _get_model_ptr_from_xml(xml_path=xml_path)\n return cls(model_ptr)\n\n @classmethod\n def from_binary_path(cls, binary_path):\n \"\"\"Creates an MjModel instance from a path to a compiled model binary.\"\"\"\n model_ptr = _get_model_ptr_from_binary(binary_path=binary_path)\n return cls(model_ptr)\n\n def save_binary(self, binary_path):\n \"\"\"Saves the MjModel instance to a binary file.\"\"\"\n mjlib.mj_saveModel(self.ptr, util.to_binary_string(binary_path), None, 0)\n\n def to_bytes(self):\n \"\"\"Serialize the model to a string of bytes.\"\"\"\n bufsize = mjlib.mj_sizeModel(self.ptr)\n buf = ctypes.create_string_buffer(bufsize)\n mjlib.mj_saveModel(self.ptr, None, buf, bufsize)\n return buf.raw\n\n def copy(self):\n \"\"\"Returns a copy of this MjModel instance.\"\"\"\n return self.__copy__()\n\n def free(self):\n \"\"\"Frees the native resources held by this MjModel.\n\n This is an advanced feature for use when manual memory management is\n necessary. This MjModel object MUST NOT be used after this function has\n been called.\n \"\"\"\n _finalize(self._ptr)\n del self._ptr\n\n def name2id(self, name, object_type):\n \"\"\"Returns the integer ID of a specified MuJoCo object.\n\n Args:\n name: String specifying the name of the object to query.\n object_type: The type of the object. Can be either a lowercase string\n (e.g. 'body', 'geom') or an `mjtObj` enum value.\n\n Returns:\n An integer object ID.\n\n Raises:\n Error: If `object_type` is not a valid MuJoCo object type, or if no object\n with the corresponding name and type was found.\n \"\"\"\n if not isinstance(object_type, int):\n object_type = _str2type(object_type)\n obj_id = mjlib.mj_name2id(\n self.ptr, object_type, util.to_binary_string(name))\n if obj_id == -1:\n raise Error(\"Object of type {!r} with name {!r} does not exist.\".format(\n _type2str(object_type), name))\n return obj_id\n\n def id2name(self, object_id, object_type):\n \"\"\"Returns the name associated with a MuJoCo object ID, if there is one.\n\n Args:\n object_id: Integer ID.\n object_type: The type of the object. Can be either a lowercase string\n (e.g. 'body', 'geom') or an `mjtObj` enum value.\n\n Returns:\n A string containing the object name, or an empty string if the object ID\n either doesn't exist or has no name.\n\n Raises:\n Error: If `object_type` is not a valid MuJoCo object type.\n \"\"\"\n if not isinstance(object_type, int):\n object_type = _str2type(object_type)\n name_ptr = mjlib.mj_id2name(self.ptr, object_type, object_id)\n if not name_ptr:\n return \"\"\n return util.to_native_string(ctypes.string_at(name_ptr))\n\n @contextlib.contextmanager\n def disable(self, *flags):\n \"\"\"Context manager for temporarily disabling MuJoCo flags.\n\n Args:\n *flags: Positional arguments specifying flags to disable. Can be either\n lowercase strings (e.g. 'gravity', 'contact') or `mjtDisableBit` enum\n values.\n\n Yields:\n None\n\n Raises:\n ValueError: If any item in `flags` is neither a valid name nor a value\n from `enums.mjtDisableBit`.\n \"\"\"\n old_bitmask = self.opt.disableflags\n new_bitmask = old_bitmask\n for flag in flags:\n if isinstance(flag, str):\n try:\n field_name = \"mjDSBL_\" + flag.upper()\n bitmask = getattr(enums.mjtDisableBit, field_name)\n except AttributeError:\n valid_names = [field_name.split(\"_\")[1].lower()\n for field_name in enums.mjtDisableBit._fields[:-1]]\n raise ValueError(\"'{}' is not a valid flag name. Valid names: {}\"\n .format(flag, \", \".join(valid_names)))\n else:\n if flag not in enums.mjtDisableBit[:-1]:\n raise ValueError(\"'{}' is not a value in `enums.mjtDisableBit`. \"\n \"Valid values: {}\"\n .format(flag, tuple(enums.mjtDisableBit[:-1])))\n bitmask = flag\n new_bitmask |= bitmask\n self.opt.disableflags = new_bitmask\n try:\n yield\n finally:\n self.opt.disableflags = old_bitmask\n\n @property\n def name(self):\n \"\"\"Returns the name of the model.\"\"\"\n # The model name is the first null-terminated string in the `names` buffer.\n return util.to_native_string(\n ctypes.string_at(ctypes.addressof(self.names.contents)))\n\n\nclass MjData(wrappers.MjDataWrapper):\n \"\"\"Wrapper class for a MuJoCo 'mjData' instance.\n\n MjData contains all of the dynamic variables and intermediate results produced\n by the simulation. These are expected to change on each simulation timestep.\n \"\"\"\n\n def __init__(self, model):\n \"\"\"Construct a new MjData instance.\n\n Args:\n model: An MjModel instance.\n \"\"\"\n self._model = model\n\n # Allocate resources for mjData.\n data_ptr = mjlib.mj_makeData(model.ptr)\n\n # Free resources when the ctypes pointer is garbage collected.\n _create_finalizer(data_ptr, mjlib.mj_deleteData)\n\n super().__init__(data_ptr, model)\n\n def __getstate__(self):\n # Note: we can replace this once a `saveData` MJAPI function exists.\n # To reconstruct an MjData instance we need three things:\n # 1. Its parent MjModel instance\n # 2. A subset of its fixed-size fields whose values aren't determined by\n # the model\n # 3. The contents of its internal buffer (all of its pointer fields point\n # into this)\n struct_fields = {}\n for name in [\"solver\", \"timer\", \"warning\"]:\n struct_fields[name] = getattr(self, name).copy()\n scalar_field_names = [\"ncon\", \"time\", \"energy\"]\n scalar_fields = {name: getattr(self, name) for name in scalar_field_names}\n static_fields = {\"struct_fields\": struct_fields,\n \"scalar_fields\": scalar_fields}\n buffer_contents = ctypes.string_at(self.buffer_, self.nbuffer)\n return (self._model, static_fields, buffer_contents)\n\n def __setstate__(self, state_tuple):\n # Replace this once a `loadData` MJAPI function exists.\n self._model, static_fields, buffer_contents = state_tuple\n self.__init__(self.model)\n for name, contents in static_fields[\"struct_fields\"].items():\n getattr(self, name)[:] = contents\n\n for name, value in static_fields[\"scalar_fields\"].items():\n # Array and scalar values must be handled separately.\n try:\n getattr(self, name)[:] = value\n except TypeError:\n setattr(self, name, value)\n buf_ptr = (ctypes.c_char * self.nbuffer).from_address(self.buffer_)\n buf_ptr[:] = buffer_contents\n\n def __copy__(self):\n # This makes a shallow copy that shares the same parent MjModel instance.\n new_obj = self.__class__(self.model)\n mjlib.mj_copyData(new_obj.ptr, self.model.ptr, self.ptr)\n return new_obj\n\n def copy(self):\n \"\"\"Returns a copy of this MjData instance with the same parent MjModel.\"\"\"\n return self.__copy__()\n\n def free(self):\n \"\"\"Frees the native resources held by this MjData.\n\n This is an advanced feature for use when manual memory management is\n necessary. This MjData object MUST NOT be used after this function has\n been called.\n \"\"\"\n _finalize(self._ptr)\n del self._ptr\n\n def object_velocity(self, object_id, object_type, local_frame=False):\n \"\"\"Returns the 6D velocity (linear, angular) of a MuJoCo object.\n\n Args:\n object_id: Object identifier. Can be either integer ID or String name.\n object_type: The type of the object. Can be either a lowercase string\n (e.g. 'body', 'geom') or an `mjtObj` enum value.\n local_frame: Boolean specifiying whether the velocity is given in the\n global (worldbody), or local (object) frame.\n\n Returns:\n 2x3 array with stacked (linear_velocity, angular_velocity)\n\n Raises:\n Error: If `object_type` is not a valid MuJoCo object type, or if no object\n with the corresponding name and type was found.\n \"\"\"\n if not isinstance(object_type, int):\n object_type = _str2type(object_type)\n velocity = np.empty(6, dtype=np.float64)\n if not isinstance(object_id, int):\n object_id = self.model.name2id(object_id, object_type)\n mjlib.mj_objectVelocity(self.model.ptr, self.ptr,\n object_type, object_id, velocity, local_frame)\n # MuJoCo returns velocities in (angular, linear) order, which we flip here.\n return velocity.reshape(2, 3)[::-1]\n\n def contact_force(self, contact_id):\n \"\"\"Returns the wrench of a contact as a 2 x 3 array of (forces, torques).\n\n Args:\n contact_id: Integer, the index of the contact within the contact buffer\n (`self.contact`).\n\n Returns:\n 2x3 array with stacked (force, torque). Note that the order of dimensions\n is (normal, tangent, tangent), in the contact's frame.\n\n Raises:\n ValueError: If `contact_id` is negative or bigger than ncon-1.\n \"\"\"\n if not 0 <= contact_id < self.ncon:\n raise ValueError(_CONTACT_ID_OUT_OF_RANGE\n .format(max_valid=self.ncon-1, actual=contact_id))\n wrench = np.empty(6, dtype=np.float64)\n mjlib.mj_contactForce(self.model.ptr, self.ptr, contact_id, wrench)\n return wrench.reshape(2, 3)\n\n @property\n def model(self):\n \"\"\"The parent MjModel for this MjData instance.\"\"\"\n return self._model\n\n @util.CachedProperty\n def _contact_buffer(self):\n \"\"\"Cached structured array containing the full contact buffer.\"\"\"\n contact_array = util.buf_to_npy(\n super().contact, shape=(self._model.nconmax,))\n return contact_array\n\n @property\n def contact(self):\n \"\"\"Variable-length recarray containing all current contacts.\"\"\"\n return self._contact_buffer[:self.ncon]\n\n\n# Docstrings for these subclasses are inherited from their Wrapper parent class.\n\n\nclass MjvCamera(wrappers.MjvCameraWrapper):\n\n def __init__(self):\n ptr = ctypes.pointer(types.MJVCAMERA())\n mjlib.mjv_defaultCamera(ptr)\n super().__init__(ptr)\n\n\nclass MjvOption(wrappers.MjvOptionWrapper):\n\n def __init__(self):\n ptr = ctypes.pointer(types.MJVOPTION())\n mjlib.mjv_defaultOption(ptr)\n # Do not visualize rangefinder lines by default:\n ptr.contents.flags[enums.mjtVisFlag.mjVIS_RANGEFINDER] = False\n super().__init__(ptr)\n\n\nclass UnmanagedMjrContext(wrappers.MjrContextWrapper):\n \"\"\"A wrapper for MjrContext that does not manage the native object's lifetime.\n\n This wrapper is provided for API backward-compatibility reasons, since the\n creating and destruction of an MjrContext requires an OpenGL context to be\n provided.\n \"\"\"\n\n def __init__(self):\n ptr = ctypes.pointer(types.MJRCONTEXT())\n mjlib.mjr_defaultContext(ptr)\n super().__init__(ptr)\n\n\nclass MjrContext(wrappers.MjrContextWrapper): # pylint: disable=missing-docstring\n\n def __init__(self,\n model,\n gl_context,\n font_scale=enums.mjtFontScale.mjFONTSCALE_150):\n \"\"\"Initializes this MjrContext instance.\n\n Args:\n model: An `MjModel` instance.\n gl_context: A `render.ContextBase` instance.\n font_scale: Integer controlling the font size for text. Must be a value\n in `mjbindings.enums.mjtFontScale`.\n\n Raises:\n ValueError: If `font_scale` is invalid.\n \"\"\"\n if font_scale not in enums.mjtFontScale:\n raise ValueError(_INVALID_FONT_SCALE.format(font_scale))\n\n ptr = ctypes.pointer(types.MJRCONTEXT())\n mjlib.mjr_defaultContext(ptr)\n\n with gl_context.make_current() as ctx:\n ctx.call(mjlib.mjr_makeContext, model.ptr, ptr, font_scale)\n ctx.call(mjlib.mjr_setBuffer, enums.mjtFramebuffer.mjFB_OFFSCREEN, ptr)\n gl_context.increment_refcount()\n\n # Free resources when the ctypes pointer is garbage collected.\n def finalize_mjr_context(ptr):\n if not gl_context.terminated:\n with gl_context.make_current() as ctx:\n ctx.call(mjlib.mjr_freeContext, ptr)\n gl_context.decrement_refcount()\n\n _create_finalizer(ptr, finalize_mjr_context)\n\n super().__init__(ptr)\n\n def free(self):\n \"\"\"Frees the native resources held by this MjrContext.\n\n This is an advanced feature for use when manual memory management is\n necessary. This MjrContext object MUST NOT be used after this function has\n been called.\n \"\"\"\n _finalize(self._ptr)\n del self._ptr\n\n\n# A mapping from human-readable short names to mjtRndFlag enum values, i.e.\n# {'shadow': mjtRndFlag.mjRND_SHADOW, 'fog': mjtRndFlag.mjRND_FOG, ...}\n_NAME_TO_RENDER_FLAG_ENUM_VALUE = {\n name[len(\"mjRND_\"):].lower(): getattr(enums.mjtRndFlag, name)\n for name in enums.mjtRndFlag._fields[:-1] # Exclude mjRND_NUMRNDFLAG entry.\n}\n\n\ndef _estimate_max_renderable_geoms(model):\n \"\"\"Estimates the maximum number of renderable geoms for a given model.\"\"\"\n # Only one type of object frame can be rendered at once.\n max_nframes = max(\n [model.nbody, model.ngeom, model.nsite, model.ncam, model.nlight])\n # This is probably an underestimate, but it is unlikely that all possible\n # rendering options will be enabled simultaneously, or that all renderable\n # geoms will be present within the viewing frustum at the same time.\n return (\n 3 * max_nframes + # 1 geom per axis for each frame.\n 4 * model.ngeom + # geom itself + contacts + 2 * split contact forces.\n 3 * model.nbody + # COM + inertia box + perturbation force.\n model.nsite +\n model.ntendon +\n model.njnt +\n model.nu +\n model.nskin +\n model.ncam +\n model.nlight)\n\n\nclass MjvScene(wrappers.MjvSceneWrapper): # pylint: disable=missing-docstring\n\n def __init__(self, model=None, max_geom=None):\n \"\"\"Initializes a new `MjvScene` instance.\n\n Args:\n model: (optional) An `MjModel` instance.\n max_geom: (optional) An integer specifying the maximum number of geoms\n that can be represented in the scene. If None, this will be chosen\n automatically based on `model`.\n \"\"\"\n model_ptr = model.ptr if model is not None else None\n scene_ptr = ctypes.pointer(types.MJVSCENE())\n\n if max_geom is None:\n if model is None:\n max_renderable_geoms = 0\n else:\n max_renderable_geoms = _estimate_max_renderable_geoms(model)\n max_geom = max(1000, max_renderable_geoms)\n\n # Allocate and initialize resources for the abstract scene.\n mjlib.mjv_makeScene(model_ptr, scene_ptr, max_geom)\n\n # Free resources when the ctypes pointer is garbage collected.\n _create_finalizer(scene_ptr, mjlib.mjv_freeScene)\n\n super().__init__(scene_ptr)\n\n @contextlib.contextmanager\n def override_flags(self, overrides):\n \"\"\"Context manager for temporarily overriding rendering flags.\n\n Args:\n overrides: A mapping specifying rendering flags to override. The keys can\n be either lowercase strings or `mjtRndFlag` enum values, and the values\n are the overridden flag values, e.g. `{'wireframe': True}` or\n `{enums.mjtRndFlag.mjRND_WIREFRAME: True}`. See `enums.mjtRndFlag` for\n the set of valid flags.\n\n Yields:\n None\n \"\"\"\n if not overrides:\n yield\n else:\n original_flags = self.flags.copy()\n for key, value in overrides.items():\n index = _NAME_TO_RENDER_FLAG_ENUM_VALUE.get(key, key)\n self.flags[index] = value\n try:\n yield\n finally:\n np.copyto(self.flags, original_flags)\n\n def free(self):\n \"\"\"Frees the native resources held by this MjvScene.\n\n This is an advanced feature for use when manual memory management is\n necessary. This MjvScene object MUST NOT be used after this function has\n been called.\n \"\"\"\n _finalize(self._ptr)\n del self._ptr\n\n @util.CachedProperty\n def _geoms_buffer(self):\n \"\"\"Cached recarray containing the full geom buffer.\"\"\"\n return util.buf_to_npy(super().geoms, shape=(self.maxgeom,))\n\n @property\n def geoms(self):\n \"\"\"Variable-length recarray containing all geoms currently in the buffer.\"\"\"\n return self._geoms_buffer[:self.ngeom]\n\n\nclass MjvPerturb(wrappers.MjvPerturbWrapper):\n\n def __init__(self):\n ptr = ctypes.pointer(types.MJVPERTURB())\n mjlib.mjv_defaultPerturb(ptr)\n super().__init__(ptr)\n\n\nclass MjvFigure(wrappers.MjvFigureWrapper):\n\n def __init__(self):\n ptr = ctypes.pointer(types.MJVFIGURE())\n mjlib.mjv_defaultFigure(ptr)\n super().__init__(ptr)\n"
] |
[
[
"numpy.copyto",
"numpy.empty"
]
] |
Dangandy/covid
|
[
"2c8b9f4ab365c5b460e7d7e28273d7966e382b77"
] |
[
"backend/lstm.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"\nImplementation of building LSTM model\n\"\"\"\n# 3rd party imports\nimport pandas as pd\nimport numpy as np\nimport random as rn\nimport datetime as datetime\n\n# model\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import LSTM\nfrom keras.layers import Dense\nfrom keras.losses import MeanSquaredLogarithmicError\nfrom sklearn.model_selection import train_test_split\n\n# local imports\nfrom db.model import db, Stat\n\n\nclass Lstm:\n def extract(self) -> pd.DataFrame:\n \"\"\"\n extract data from database and output into dataframe\n \"\"\"\n # grab all record from stat table\n df = pd.read_sql_table(\"stat\", \"sqlite:///db/site.db\")\n\n # return\n return df\n\n def transform(self, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n transforms done to dataframe:\n - calculate the difference of each metric\n - onehotencode countries\n \"\"\"\n # get diff\n df[\"confirmed_diff\"] = np.where(\n df.country == df.country.shift(), df.confirmed - df.confirmed.shift(), 0\n )\n df[\"recovered_diff\"] = np.where(\n df.country == df.country.shift(), df.recovered - df.recovered.shift(), 0\n )\n df[\"deaths_diff\"] = np.where(\n df.country == df.country.shift(), df.deaths - df.deaths.shift(), 0\n )\n\n # encode country with pd.dummies\n dummies = pd.get_dummies(df.country)\n dummies[\"id\"] = df.id\n df = pd.merge(df, dummies, on=[\"id\"])\n\n # return\n return df\n\n def load(\n self,\n df: pd.DataFrame,\n metric=\"confirmed\",\n win_size=7,\n epochs=5,\n batch_size=32,\n save=False,\n ) -> Sequential:\n \"\"\"\n load dataframe into sequential\n \"\"\"\n # variables\n x, y = [], []\n countries = db.session.query(Stat.country).distinct().all()\n\n # countries come in the form of [('Afghanistan',), ('Albania',), ... ]\n for (country,) in countries:\n country_df = df[df.country == country]\n series = list(country_df[metric])\n for i in range(0, len(series) - win_size):\n end = i + win_size\n series_x, series_y = series[i:end], series[end]\n if series_y:\n x.append(series_x)\n y.append(series_y)\n X, y = np.array(x), np.array(y)\n\n # TTS\n X_train, X_val, y_train, y_val = train_test_split(\n X, y, test_size=0.2, random_state=42\n )\n\n # preprocess\n X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])\n X_val = X_val.reshape(X_val.shape[0], 1, X_val.shape[1])\n\n # build model\n model = Sequential()\n model.add(\n LSTM(\n 100,\n activation=\"relu\",\n input_shape=(1, win_size),\n return_sequences=True,\n )\n )\n model.add(LSTM(150, activation=\"relu\"))\n model.add(Dense(1, activation=\"relu\"))\n\n # Compile Model\n model.compile(optimizer=\"adam\", loss=MeanSquaredLogarithmicError())\n\n # Fit Model\n model.fit(\n X_train,\n y_train,\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(X_val, y_val),\n verbose=2,\n shuffle=True,\n )\n\n # Export Model\n if save:\n model.save(\"lstm_model.h5\")\n\n\ndef main():\n \"\"\"\n run code\n \"\"\"\n # Set random state for Keras\n np.random.seed(42)\n rn.seed(12345)\n\n # build model and save it\n model = Lstm()\n df = model.extract()\n df = model.transform(df)\n lstm = model.load(df, save=True)\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] |
[
[
"pandas.merge",
"numpy.random.seed",
"pandas.read_sql_table",
"sklearn.model_selection.train_test_split",
"numpy.array",
"pandas.get_dummies"
]
] |
persalteas/RNAnet
|
[
"60f0af5acad06695acd782f9401f5e166852f45f"
] |
[
"geometric_stats.py"
] |
[
"#!/usr/bin/python3\n\n# RNANet statistics\n# Developed by Aglaé Tabot & Louis Becquey, 2021 \n\n# This file computes additional geometric measures over the produced dataset,\n# and estimates their distribtuions through Gaussian mixture models.\n# THIS FILE IS NOT SUPPOSED TO BE RUN DIRECTLY.\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as st\nimport Bio, glob, json, os, random, sqlite3, warnings\nfrom Bio.PDB.MMCIFParser import MMCIFParser\nfrom Bio.PDB.vectors import Vector, calc_angle, calc_dihedral\nfrom multiprocessing import Pool, Value\nfrom pandas.core.common import SettingWithCopyWarning\nfrom setproctitle import setproctitle\nfrom sklearn.mixture import GaussianMixture\nfrom tqdm import tqdm\nfrom RNAnet import init_with_tqdm, trace_unhandled_exceptions, warn, notify\n\nrunDir = os.getcwd()\n\n# This dic stores the number laws to use in the GMM to estimate each parameter's distribution.\n# If you do not want to trust this data, you can use the --rescan-nmodes option.\n# GMMs will be trained between 1 and 8 modes and the best model will be kept.\nmodes_data = { \n # bonded distances, all-atom, common to all. Some are also used for HiRE-RNA.\n \"C1'-C2'\":3, \"C2'-C3'\":2, \"C2'-O2'\":2, \"C3'-O3'\":2, \"C4'-C3'\":2, \"C4'-O4'\":2, \"C5'-C4'\":2, \"O3'-P\":3, \"O4'-C1'\":3, \"O5'-C5'\":3, \"P-O5'\":3, \"P-OP1\":2, \"P-OP2\":2,\n \n # bonded distances, all-atom, purines\n \"C4-C5\":3, \"C4-N9\":2, \"N3-C4\":2, \"C2-N3\":2, \"C2-N2\":5, \"N1-C2\":3, \"C6-N1\":3, \"C6-N6\":3, \"C6-O6\":3, \"C5-C6\":2, \"N7-C5\":3, \"C8-N7\":2, \"N9-C8\":4, \"C1'-N9\":2,\n\n # bonded distances, all-atom, pyrimidines\n \"C4-O4\":2, \"C4-N4\":2, \"C2-N1\":1, \"C2-O2\":3, \"N3-C2\":4, \"C4-N3\":4, \"C5-C4\":2, \"C6-C5\":3, \"N1-C6\":2, \"C1'-N1\":2,\n\n # torsions, all atom\n \"Alpha\":3, \"Beta\":2, \"Delta\":2, \"Epsilon\":2, \"Gamma\":3, \"Xhi\":3, \"Zeta\":3,\n\n # Pyle, distances\n \"C1'-P\":3, \"C4'-P\":3, \"P-C1'\":3, \"P-C4'\":3,\n\n # Pyle, angles\n \"C1'-P°-C1'°\":3, \"P-C1'-P°\":2,\n\n # Pyle, torsions\n \"Eta\":1, \"Theta\":1, \"Eta'\":1, \"Theta'\":1, \"Eta''\":4, \"Theta''\":3,\n\n # HiRE-RNA, distances\n \"C4'-P\":3, \"C4'-C1'\":3, \"C1'-B1\":3, \"B1-B2\":2,\n\n # HiRE-RNA, angles\n \"P-O5'-C5'\":2, \"O5'-C5'-C4'\":1, \"C5'-C4'-P\":2, \"C5'-C4'-C1'\":2, \"C4'-P-O5'\":2, \"C4'-C1'-B1\":2, \"C1'-C4'-P\":2, \"C1'-B1-B2\":2,\n\n # HiRE-RNA, torsions\n \"P-O5'-C5'-C4'\":3, \"O5'-C5'-C4'-P°\":3, \"O5'-C5'-C4'-C1'\":3, \"C5'-C4'-P°-O5'°\":3, \"C5'-C4'-C1'-B1\":2, \"C4'-P°-O5'°-C5'°\":3, \"C4'-C1'-B1-B2\":3, \"C1'-C4'-P°-O5'°\":3,\n\n # HiRE-RNA, basepairs\n \"cWW_AA_tips_distance\":3, \"cWW_AA_C1'-B1-B1pair\":1, \"cWW_AA_B1-B1pair-C1'pair\":1, \"cWW_AA_C4'-C1'-B1-B1pair\":2, \"cWW_AA_B1-B1pair-C1'pair-C4'pair\":3, \"cWW_AA_alpha_1\":2, \"cWW_AA_alpha_2\":3, \"cWW_AA_dB1\":3, \"cWW_AA_dB2\":3, \n \"tWW_AA_tips_distance\":1, \"tWW_AA_C1'-B1-B1pair\":1, \"tWW_AA_B1-B1pair-C1'pair\":1, \"tWW_AA_C4'-C1'-B1-B1pair\":2, \"tWW_AA_B1-B1pair-C1'pair-C4'pair\":3, \"tWW_AA_alpha_1\":2, \"tWW_AA_alpha_2\":1, \"tWW_AA_dB1\":1, \"tWW_AA_dB2\":2, \n \"cWH_AA_tips_distance\":3, \"cWH_AA_C1'-B1-B1pair\":2, \"cWH_AA_B1-B1pair-C1'pair\":2, \"cWH_AA_C4'-C1'-B1-B1pair\":2, \"cWH_AA_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_AA_alpha_1\":1, \"cWH_AA_alpha_2\":2, \"cWH_AA_dB1\":3, \"cWH_AA_dB2\":2, \n \"tWH_AA_tips_distance\":3, \"tWH_AA_C1'-B1-B1pair\":1, \"tWH_AA_B1-B1pair-C1'pair\":3, \"tWH_AA_C4'-C1'-B1-B1pair\":2, \"tWH_AA_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_AA_alpha_1\":1, \"tWH_AA_alpha_2\":3, \"tWH_AA_dB1\":2, \"tWH_AA_dB2\":1, \n \"cHW_AA_tips_distance\":1, \"cHW_AA_C1'-B1-B1pair\":2, \"cHW_AA_B1-B1pair-C1'pair\":2, \"cHW_AA_C4'-C1'-B1-B1pair\":3, \"cHW_AA_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_AA_alpha_1\":2, \"cHW_AA_alpha_2\":2, \"cHW_AA_dB1\":3, \"cHW_AA_dB2\":2, \n \"tHW_AA_tips_distance\":4, \"tHW_AA_C1'-B1-B1pair\":2, \"tHW_AA_B1-B1pair-C1'pair\":2, \"tHW_AA_C4'-C1'-B1-B1pair\":2, \"tHW_AA_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_AA_alpha_1\":2, \"tHW_AA_alpha_2\":1, \"tHW_AA_dB1\":2, \"tHW_AA_dB2\":1, \n \"cWS_AA_tips_distance\":2, \"cWS_AA_C1'-B1-B1pair\":2, \"cWS_AA_B1-B1pair-C1'pair\":2, \"cWS_AA_C4'-C1'-B1-B1pair\":2, \"cWS_AA_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_AA_alpha_1\":2, \"cWS_AA_alpha_2\":2, \"cWS_AA_dB1\":2, \"cWS_AA_dB2\":1, \n \"tWS_AA_tips_distance\":2, \"tWS_AA_C1'-B1-B1pair\":2, \"tWS_AA_B1-B1pair-C1'pair\":2, \"tWS_AA_C4'-C1'-B1-B1pair\":3, \"tWS_AA_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_AA_alpha_1\":2, \"tWS_AA_alpha_2\":2, \"tWS_AA_dB1\":2, \"tWS_AA_dB2\":3, \n \"cSW_AA_tips_distance\":3, \"cSW_AA_C1'-B1-B1pair\":3, \"cSW_AA_B1-B1pair-C1'pair\":2, \"cSW_AA_C4'-C1'-B1-B1pair\":1, \"cSW_AA_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_AA_alpha_1\":2, \"cSW_AA_alpha_2\":2, \"cSW_AA_dB1\":1, \"cSW_AA_dB2\":1, \n \"tSW_AA_tips_distance\":3, \"tSW_AA_C1'-B1-B1pair\":3, \"tSW_AA_B1-B1pair-C1'pair\":3, \"tSW_AA_C4'-C1'-B1-B1pair\":2, \"tSW_AA_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_AA_alpha_1\":2, \"tSW_AA_alpha_2\":2, \"tSW_AA_dB1\":2, \"tSW_AA_dB2\":2, \n \"cHH_AA_tips_distance\":4, \"cHH_AA_C1'-B1-B1pair\":2, \"cHH_AA_B1-B1pair-C1'pair\":3, \"cHH_AA_C4'-C1'-B1-B1pair\":3, \"cHH_AA_B1-B1pair-C1'pair-C4'pair\":3, \"cHH_AA_alpha_1\":2, \"cHH_AA_alpha_2\":3, \"cHH_AA_dB1\":3, \"cHH_AA_dB2\":1, \n \"tHH_AA_tips_distance\":2, \"tHH_AA_C1'-B1-B1pair\":2, \"tHH_AA_B1-B1pair-C1'pair\":2, \"tHH_AA_C4'-C1'-B1-B1pair\":3, \"tHH_AA_B1-B1pair-C1'pair-C4'pair\":1, \"tHH_AA_alpha_1\":2, \"tHH_AA_alpha_2\":2, \"tHH_AA_dB1\":2, \"tHH_AA_dB2\":2, \n \"cSH_AA_tips_distance\":2, \"cSH_AA_C1'-B1-B1pair\":2, \"cSH_AA_B1-B1pair-C1'pair\":1, \"cSH_AA_C4'-C1'-B1-B1pair\":3, \"cSH_AA_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_AA_alpha_1\":2, \"cSH_AA_alpha_2\":2, \"cSH_AA_dB1\":4, \"cSH_AA_dB2\":1, \n \"tSH_AA_tips_distance\":2, \"tSH_AA_C1'-B1-B1pair\":1, \"tSH_AA_B1-B1pair-C1'pair\":2, \"tSH_AA_C4'-C1'-B1-B1pair\":2, \"tSH_AA_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_AA_alpha_1\":2, \"tSH_AA_alpha_2\":3, \"tSH_AA_dB1\":2, \"tSH_AA_dB2\":2, \n \"cHS_AA_tips_distance\":3, \"cHS_AA_C1'-B1-B1pair\":2, \"cHS_AA_B1-B1pair-C1'pair\":2, \"cHS_AA_C4'-C1'-B1-B1pair\":2, \"cHS_AA_B1-B1pair-C1'pair-C4'pair\":1, \"cHS_AA_alpha_1\":2, \"cHS_AA_alpha_2\":2, \"cHS_AA_dB1\":1, \"cHS_AA_dB2\":4, \n \"tHS_AA_tips_distance\":4, \"tHS_AA_C1'-B1-B1pair\":2, \"tHS_AA_B1-B1pair-C1'pair\":2, \"tHS_AA_C4'-C1'-B1-B1pair\":2, \"tHS_AA_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_AA_alpha_1\":2, \"tHS_AA_alpha_2\":1, \"tHS_AA_dB1\":2, \"tHS_AA_dB2\":1, \n \"cSS_AA_tips_distance\":6, \"cSS_AA_C1'-B1-B1pair\":3, \"cSS_AA_B1-B1pair-C1'pair\":3, \"cSS_AA_C4'-C1'-B1-B1pair\":2, \"cSS_AA_B1-B1pair-C1'pair-C4'pair\":2, \"cSS_AA_alpha_1\":3, \"cSS_AA_alpha_2\":3, \"cSS_AA_dB1\":3, \"cSS_AA_dB2\":5, \n \"tSS_AA_tips_distance\":5, \"tSS_AA_C1'-B1-B1pair\":1, \"tSS_AA_B1-B1pair-C1'pair\":1, \"tSS_AA_C4'-C1'-B1-B1pair\":2, \"tSS_AA_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_AA_alpha_1\":3, \"tSS_AA_alpha_2\":1, \"tSS_AA_dB1\":4, \"tSS_AA_dB2\":2, \n \"cWW_AC_tips_distance\":2, \"cWW_AC_C1'-B1-B1pair\":1, \"cWW_AC_B1-B1pair-C1'pair\":2, \"cWW_AC_C4'-C1'-B1-B1pair\":2, \"cWW_AC_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_AC_alpha_1\":1, \"cWW_AC_alpha_2\":2, \"cWW_AC_dB1\":3, \"cWW_AC_dB2\":3, \n \"tWW_AC_tips_distance\":2, \"tWW_AC_C1'-B1-B1pair\":3, \"tWW_AC_B1-B1pair-C1'pair\":2, \"tWW_AC_C4'-C1'-B1-B1pair\":3, \"tWW_AC_B1-B1pair-C1'pair-C4'pair\":3, \"tWW_AC_alpha_1\":3, \"tWW_AC_alpha_2\":2, \"tWW_AC_dB1\":4, \"tWW_AC_dB2\":3, \n \"cWH_AC_tips_distance\":5, \"cWH_AC_C1'-B1-B1pair\":2, \"cWH_AC_B1-B1pair-C1'pair\":2, \"cWH_AC_C4'-C1'-B1-B1pair\":1, \"cWH_AC_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_AC_alpha_1\":2, \"cWH_AC_alpha_2\":2, \"cWH_AC_dB1\":4, \"cWH_AC_dB2\":4, \n \"tWH_AC_tips_distance\":8, \"tWH_AC_C1'-B1-B1pair\":1, \"tWH_AC_B1-B1pair-C1'pair\":2, \"tWH_AC_C4'-C1'-B1-B1pair\":2, \"tWH_AC_B1-B1pair-C1'pair-C4'pair\":3, \"tWH_AC_alpha_1\":2, \"tWH_AC_alpha_2\":2, \"tWH_AC_dB1\":3, \"tWH_AC_dB2\":3, \n \"cHW_AC_tips_distance\":2, \"cHW_AC_C1'-B1-B1pair\":2, \"cHW_AC_B1-B1pair-C1'pair\":2, \"cHW_AC_C4'-C1'-B1-B1pair\":3, \"cHW_AC_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_AC_alpha_1\":2, \"cHW_AC_alpha_2\":3, \"cHW_AC_dB1\":2, \"cHW_AC_dB2\":5, \n \"tHW_AC_tips_distance\":3, \"tHW_AC_C1'-B1-B1pair\":2, \"tHW_AC_B1-B1pair-C1'pair\":3, \"tHW_AC_C4'-C1'-B1-B1pair\":3, \"tHW_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_AC_alpha_1\":2, \"tHW_AC_alpha_2\":2, \"tHW_AC_dB1\":3, \"tHW_AC_dB2\":3, \n \"cWS_AC_tips_distance\":3, \"cWS_AC_C1'-B1-B1pair\":2, \"cWS_AC_B1-B1pair-C1'pair\":1, \"cWS_AC_C4'-C1'-B1-B1pair\":2, \"cWS_AC_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_AC_alpha_1\":2, \"cWS_AC_alpha_2\":1, \"cWS_AC_dB1\":1, \"cWS_AC_dB2\":1, \n \"tWS_AC_tips_distance\":4, \"tWS_AC_C1'-B1-B1pair\":2, \"tWS_AC_B1-B1pair-C1'pair\":1, \"tWS_AC_C4'-C1'-B1-B1pair\":2, \"tWS_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_AC_alpha_1\":3, \"tWS_AC_alpha_2\":1, \"tWS_AC_dB1\":3, \"tWS_AC_dB2\":2, \n \"cSW_AC_tips_distance\":6, \"cSW_AC_C1'-B1-B1pair\":2, \"cSW_AC_B1-B1pair-C1'pair\":2, \"cSW_AC_C4'-C1'-B1-B1pair\":2, \"cSW_AC_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_AC_alpha_1\":3, \"cSW_AC_alpha_2\":2, \"cSW_AC_dB1\":2, \"cSW_AC_dB2\":3, \n \"tSW_AC_tips_distance\":5, \"tSW_AC_C1'-B1-B1pair\":1, \"tSW_AC_B1-B1pair-C1'pair\":2, \"tSW_AC_C4'-C1'-B1-B1pair\":1, \"tSW_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_AC_alpha_1\":1, \"tSW_AC_alpha_2\":2, \"tSW_AC_dB1\":2, \"tSW_AC_dB2\":3, \n \"cHH_AC_tips_distance\":5, \"cHH_AC_C1'-B1-B1pair\":2, \"cHH_AC_B1-B1pair-C1'pair\":2, \"cHH_AC_C4'-C1'-B1-B1pair\":2, \"cHH_AC_B1-B1pair-C1'pair-C4'pair\":1, \"cHH_AC_alpha_1\":3, \"cHH_AC_alpha_2\":3, \"cHH_AC_dB1\":3, \"cHH_AC_dB2\":4, \n \"tHH_AC_tips_distance\":4, \"tHH_AC_C1'-B1-B1pair\":1, \"tHH_AC_B1-B1pair-C1'pair\":2, \"tHH_AC_C4'-C1'-B1-B1pair\":2, \"tHH_AC_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_AC_alpha_1\":2, \"tHH_AC_alpha_2\":2, \"tHH_AC_dB1\":4, \"tHH_AC_dB2\":3, \n \"cSH_AC_tips_distance\":3, \"cSH_AC_C1'-B1-B1pair\":1, \"cSH_AC_B1-B1pair-C1'pair\":3, \"cSH_AC_C4'-C1'-B1-B1pair\":1, \"cSH_AC_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_AC_alpha_1\":1, \"cSH_AC_alpha_2\":1, \"cSH_AC_dB1\":2, \"cSH_AC_dB2\":6, \n \"tSH_AC_tips_distance\":8, \"tSH_AC_C1'-B1-B1pair\":3, \"tSH_AC_B1-B1pair-C1'pair\":2, \"tSH_AC_C4'-C1'-B1-B1pair\":1, \"tSH_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_AC_alpha_1\":2, \"tSH_AC_alpha_2\":3, \"tSH_AC_dB1\":1, \"tSH_AC_dB2\":2, \n \"cHS_AC_tips_distance\":4, \"cHS_AC_C1'-B1-B1pair\":1, \"cHS_AC_B1-B1pair-C1'pair\":1, \"cHS_AC_C4'-C1'-B1-B1pair\":2, \"cHS_AC_B1-B1pair-C1'pair-C4'pair\":1, \"cHS_AC_alpha_1\":1, \"cHS_AC_alpha_2\":1, \"cHS_AC_dB1\":3, \"cHS_AC_dB2\":2, \n \"tHS_AC_tips_distance\":8, \"tHS_AC_C1'-B1-B1pair\":1, \"tHS_AC_B1-B1pair-C1'pair\":2, \"tHS_AC_C4'-C1'-B1-B1pair\":2, \"tHS_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tHS_AC_alpha_1\":1, \"tHS_AC_alpha_2\":1, \"tHS_AC_dB1\":1, \"tHS_AC_dB2\":1, \n \"cSS_AC_tips_distance\":2, \"cSS_AC_C1'-B1-B1pair\":2, \"cSS_AC_B1-B1pair-C1'pair\":2, \"cSS_AC_C4'-C1'-B1-B1pair\":1, \"cSS_AC_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_AC_alpha_1\":2, \"cSS_AC_alpha_2\":1, \"cSS_AC_dB1\":1, \"cSS_AC_dB2\":5, \n \"tSS_AC_tips_distance\":5, \"tSS_AC_C1'-B1-B1pair\":2, \"tSS_AC_B1-B1pair-C1'pair\":2, \"tSS_AC_C4'-C1'-B1-B1pair\":1, \"tSS_AC_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_AC_alpha_1\":2, \"tSS_AC_alpha_2\":2, \"tSS_AC_dB1\":3, \"tSS_AC_dB2\":5, \n \"cWW_AG_tips_distance\":3, \"cWW_AG_C1'-B1-B1pair\":1, \"cWW_AG_B1-B1pair-C1'pair\":1, \"cWW_AG_C4'-C1'-B1-B1pair\":2, \"cWW_AG_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_AG_alpha_1\":1, \"cWW_AG_alpha_2\":1, \"cWW_AG_dB1\":1, \"cWW_AG_dB2\":1, \n \"tWW_AG_tips_distance\":5, \"tWW_AG_C1'-B1-B1pair\":1, \"tWW_AG_B1-B1pair-C1'pair\":1, \"tWW_AG_C4'-C1'-B1-B1pair\":2, \"tWW_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_AG_alpha_1\":2, \"tWW_AG_alpha_2\":2, \"tWW_AG_dB1\":2, \"tWW_AG_dB2\":3, \n \"cWH_AG_tips_distance\":4, \"cWH_AG_C1'-B1-B1pair\":1, \"cWH_AG_B1-B1pair-C1'pair\":1, \"cWH_AG_C4'-C1'-B1-B1pair\":2, \"cWH_AG_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_AG_alpha_1\":3, \"cWH_AG_alpha_2\":1, \"cWH_AG_dB1\":2, \"cWH_AG_dB2\":1, \n \"tWH_AG_tips_distance\":3, \"tWH_AG_C1'-B1-B1pair\":1, \"tWH_AG_B1-B1pair-C1'pair\":1, \"tWH_AG_C4'-C1'-B1-B1pair\":2, \"tWH_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_AG_alpha_1\":2, \"tWH_AG_alpha_2\":1, \"tWH_AG_dB1\":2, \"tWH_AG_dB2\":1, \n \"cHW_AG_tips_distance\":2, \"cHW_AG_C1'-B1-B1pair\":2, \"cHW_AG_B1-B1pair-C1'pair\":1, \"cHW_AG_C4'-C1'-B1-B1pair\":2, \"cHW_AG_B1-B1pair-C1'pair-C4'pair\":1, \"cHW_AG_alpha_1\":1, \"cHW_AG_alpha_2\":2, \"cHW_AG_dB1\":2, \"cHW_AG_dB2\":2, \n \"tHW_AG_tips_distance\":3, \"tHW_AG_C1'-B1-B1pair\":2, \"tHW_AG_B1-B1pair-C1'pair\":2, \"tHW_AG_C4'-C1'-B1-B1pair\":2, \"tHW_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_AG_alpha_1\":2, \"tHW_AG_alpha_2\":2, \"tHW_AG_dB1\":2, \"tHW_AG_dB2\":2, \n \"cWS_AG_tips_distance\":1, \"cWS_AG_C1'-B1-B1pair\":3, \"cWS_AG_B1-B1pair-C1'pair\":1, \"cWS_AG_C4'-C1'-B1-B1pair\":1, \"cWS_AG_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_AG_alpha_1\":2, \"cWS_AG_alpha_2\":2, \"cWS_AG_dB1\":2, \"cWS_AG_dB2\":1, \n \"tWS_AG_tips_distance\":6, \"tWS_AG_C1'-B1-B1pair\":1, \"tWS_AG_B1-B1pair-C1'pair\":2, \"tWS_AG_C4'-C1'-B1-B1pair\":2, \"tWS_AG_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_AG_alpha_1\":2, \"tWS_AG_alpha_2\":2, \"tWS_AG_dB1\":1, \"tWS_AG_dB2\":3, \n \"cSW_AG_tips_distance\":4, \"cSW_AG_C1'-B1-B1pair\":1, \"cSW_AG_B1-B1pair-C1'pair\":2, \"cSW_AG_C4'-C1'-B1-B1pair\":1, \"cSW_AG_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_AG_alpha_1\":1, \"cSW_AG_alpha_2\":2, \"cSW_AG_dB1\":3, \"cSW_AG_dB2\":1, \n \"tSW_AG_tips_distance\":7, \"tSW_AG_C1'-B1-B1pair\":3, \"tSW_AG_B1-B1pair-C1'pair\":2, \"tSW_AG_C4'-C1'-B1-B1pair\":2, \"tSW_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_AG_alpha_1\":2, \"tSW_AG_alpha_2\":2, \"tSW_AG_dB1\":3, \"tSW_AG_dB2\":3, \n \"cHH_AG_tips_distance\":2, \"cHH_AG_C1'-B1-B1pair\":2, \"cHH_AG_B1-B1pair-C1'pair\":4, \"cHH_AG_C4'-C1'-B1-B1pair\":3, \"cHH_AG_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_AG_alpha_1\":2, \"cHH_AG_alpha_2\":3, \"cHH_AG_dB1\":1, \"cHH_AG_dB2\":2, \n \"tHH_AG_tips_distance\":8, \"tHH_AG_C1'-B1-B1pair\":3, \"tHH_AG_B1-B1pair-C1'pair\":3, \"tHH_AG_C4'-C1'-B1-B1pair\":3, \"tHH_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_AG_alpha_1\":3, \"tHH_AG_alpha_2\":3, \"tHH_AG_dB1\":1, \"tHH_AG_dB2\":2, \n \"cSH_AG_tips_distance\":5, \"cSH_AG_C1'-B1-B1pair\":2, \"cSH_AG_B1-B1pair-C1'pair\":2, \"cSH_AG_C4'-C1'-B1-B1pair\":2, \"cSH_AG_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_AG_alpha_1\":3, \"cSH_AG_alpha_2\":1, \"cSH_AG_dB1\":1, \"cSH_AG_dB2\":3, \n \"tSH_AG_tips_distance\":5, \"tSH_AG_C1'-B1-B1pair\":2, \"tSH_AG_B1-B1pair-C1'pair\":2, \"tSH_AG_C4'-C1'-B1-B1pair\":2, \"tSH_AG_B1-B1pair-C1'pair-C4'pair\":3, \"tSH_AG_alpha_1\":2, \"tSH_AG_alpha_2\":4, \"tSH_AG_dB1\":3, \"tSH_AG_dB2\":2, \n \"cHS_AG_tips_distance\":1, \"cHS_AG_C1'-B1-B1pair\":3, \"cHS_AG_B1-B1pair-C1'pair\":1, \"cHS_AG_C4'-C1'-B1-B1pair\":3, \"cHS_AG_B1-B1pair-C1'pair-C4'pair\":1, \"cHS_AG_alpha_1\":2, \"cHS_AG_alpha_2\":3, \"cHS_AG_dB1\":1, \"cHS_AG_dB2\":2, \n \"tHS_AG_tips_distance\":6, \"tHS_AG_C1'-B1-B1pair\":1, \"tHS_AG_B1-B1pair-C1'pair\":2, \"tHS_AG_C4'-C1'-B1-B1pair\":2, \"tHS_AG_B1-B1pair-C1'pair-C4'pair\":2, \"tHS_AG_alpha_1\":1, \"tHS_AG_alpha_2\":2, \"tHS_AG_dB1\":2, \"tHS_AG_dB2\":1, \n \"cSS_AG_tips_distance\":2, \"cSS_AG_C1'-B1-B1pair\":2, \"cSS_AG_B1-B1pair-C1'pair\":2, \"cSS_AG_C4'-C1'-B1-B1pair\":2, \"cSS_AG_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_AG_alpha_1\":2, \"cSS_AG_alpha_2\":1, \"cSS_AG_dB1\":2, \"cSS_AG_dB2\":4, \n \"tSS_AG_tips_distance\":4, \"tSS_AG_C1'-B1-B1pair\":3, \"tSS_AG_B1-B1pair-C1'pair\":1, \"tSS_AG_C4'-C1'-B1-B1pair\":2, \"tSS_AG_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_AG_alpha_1\":2, \"tSS_AG_alpha_2\":1, \"tSS_AG_dB1\":2, \"tSS_AG_dB2\":4, \n \"cWW_AU_tips_distance\":3, \"cWW_AU_C1'-B1-B1pair\":1, \"cWW_AU_B1-B1pair-C1'pair\":2, \"cWW_AU_C4'-C1'-B1-B1pair\":3, \"cWW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_AU_alpha_1\":3, \"cWW_AU_alpha_2\":1, \"cWW_AU_dB1\":4, \"cWW_AU_dB2\":2, \n \"tWW_AU_tips_distance\":3, \"tWW_AU_C1'-B1-B1pair\":3, \"tWW_AU_B1-B1pair-C1'pair\":3, \"tWW_AU_C4'-C1'-B1-B1pair\":2, \"tWW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_AU_alpha_1\":3, \"tWW_AU_alpha_2\":2, \"tWW_AU_dB1\":3, \"tWW_AU_dB2\":2, \n \"cWH_AU_tips_distance\":5, \"cWH_AU_C1'-B1-B1pair\":2, \"cWH_AU_B1-B1pair-C1'pair\":2, \"cWH_AU_C4'-C1'-B1-B1pair\":2, \"cWH_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_AU_alpha_1\":1, \"cWH_AU_alpha_2\":3, \"cWH_AU_dB1\":3, \"cWH_AU_dB2\":3, \n \"tWH_AU_tips_distance\":6, \"tWH_AU_C1'-B1-B1pair\":1, \"tWH_AU_B1-B1pair-C1'pair\":3, \"tWH_AU_C4'-C1'-B1-B1pair\":2, \"tWH_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_AU_alpha_1\":2, \"tWH_AU_alpha_2\":2, \"tWH_AU_dB1\":1, \"tWH_AU_dB2\":3, \n \"cHW_AU_tips_distance\":3, \"cHW_AU_C1'-B1-B1pair\":3, \"cHW_AU_B1-B1pair-C1'pair\":3, \"cHW_AU_C4'-C1'-B1-B1pair\":2, \"cHW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_AU_alpha_1\":1, \"cHW_AU_alpha_2\":2, \"cHW_AU_dB1\":2, \"cHW_AU_dB2\":2, \n \"tHW_AU_tips_distance\":3, \"tHW_AU_C1'-B1-B1pair\":2, \"tHW_AU_B1-B1pair-C1'pair\":2, \"tHW_AU_C4'-C1'-B1-B1pair\":2, \"tHW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_AU_alpha_1\":2, \"tHW_AU_alpha_2\":1, \"tHW_AU_dB1\":1, \"tHW_AU_dB2\":4, \n \"cWS_AU_tips_distance\":2, \"cWS_AU_C1'-B1-B1pair\":1, \"cWS_AU_B1-B1pair-C1'pair\":1, \"cWS_AU_C4'-C1'-B1-B1pair\":2, \"cWS_AU_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_AU_alpha_1\":2, \"cWS_AU_alpha_2\":2, \"cWS_AU_dB1\":2, \"cWS_AU_dB2\":5, \n \"tWS_AU_tips_distance\":2, \"tWS_AU_C1'-B1-B1pair\":2, \"tWS_AU_B1-B1pair-C1'pair\":2, \"tWS_AU_C4'-C1'-B1-B1pair\":2, \"tWS_AU_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_AU_alpha_1\":2, \"tWS_AU_alpha_2\":2, \"tWS_AU_dB1\":3, \"tWS_AU_dB2\":4, \n \"cSW_AU_tips_distance\":2, \"cSW_AU_C1'-B1-B1pair\":3, \"cSW_AU_B1-B1pair-C1'pair\":2, \"cSW_AU_C4'-C1'-B1-B1pair\":2, \"cSW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_AU_alpha_1\":3, \"cSW_AU_alpha_2\":2, \"cSW_AU_dB1\":2, \"cSW_AU_dB2\":3, \n \"tSW_AU_tips_distance\":3, \"tSW_AU_C1'-B1-B1pair\":2, \"tSW_AU_B1-B1pair-C1'pair\":3, \"tSW_AU_C4'-C1'-B1-B1pair\":3, \"tSW_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_AU_alpha_1\":2, \"tSW_AU_alpha_2\":1, \"tSW_AU_dB1\":3, \"tSW_AU_dB2\":4, \n \"cHH_AU_tips_distance\":6, \"cHH_AU_C1'-B1-B1pair\":2, \"cHH_AU_B1-B1pair-C1'pair\":1, \"cHH_AU_C4'-C1'-B1-B1pair\":2, \"cHH_AU_B1-B1pair-C1'pair-C4'pair\":1, \"cHH_AU_alpha_1\":2, \"cHH_AU_alpha_2\":2, \"cHH_AU_dB1\":1, \"cHH_AU_dB2\":2, \n \"tHH_AU_tips_distance\":8, \"tHH_AU_C1'-B1-B1pair\":3, \"tHH_AU_B1-B1pair-C1'pair\":3, \"tHH_AU_C4'-C1'-B1-B1pair\":3, \"tHH_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_AU_alpha_1\":3, \"tHH_AU_alpha_2\":3, \"tHH_AU_dB1\":1, \"tHH_AU_dB2\":3, \n \"cSH_AU_tips_distance\":5, \"cSH_AU_C1'-B1-B1pair\":1, \"cSH_AU_B1-B1pair-C1'pair\":3, \"cSH_AU_C4'-C1'-B1-B1pair\":3, \"cSH_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_AU_alpha_1\":2, \"cSH_AU_alpha_2\":1, \"cSH_AU_dB1\":4, \"cSH_AU_dB2\":4, \n \"tSH_AU_tips_distance\":5, \"tSH_AU_C1'-B1-B1pair\":3, \"tSH_AU_B1-B1pair-C1'pair\":1, \"tSH_AU_C4'-C1'-B1-B1pair\":1, \"tSH_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_AU_alpha_1\":3, \"tSH_AU_alpha_2\":3, \"tSH_AU_dB1\":3, \"tSH_AU_dB2\":4, \n \"cHS_AU_tips_distance\":2, \"cHS_AU_C1'-B1-B1pair\":3, \"cHS_AU_B1-B1pair-C1'pair\":1, \"cHS_AU_C4'-C1'-B1-B1pair\":2, \"cHS_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_AU_alpha_1\":2, \"cHS_AU_alpha_2\":2, \"cHS_AU_dB1\":1, \"cHS_AU_dB2\":3, \n \"tHS_AU_tips_distance\":2, \"tHS_AU_C1'-B1-B1pair\":2, \"tHS_AU_B1-B1pair-C1'pair\":2, \"tHS_AU_C4'-C1'-B1-B1pair\":2, \"tHS_AU_B1-B1pair-C1'pair-C4'pair\":3, \"tHS_AU_alpha_1\":3, \"tHS_AU_alpha_2\":2, \"tHS_AU_dB1\":3, \"tHS_AU_dB2\":3, \n \"cSS_AU_tips_distance\":3, \"cSS_AU_C1'-B1-B1pair\":2, \"cSS_AU_B1-B1pair-C1'pair\":2, \"cSS_AU_C4'-C1'-B1-B1pair\":1, \"cSS_AU_B1-B1pair-C1'pair-C4'pair\":2, \"cSS_AU_alpha_1\":3, \"cSS_AU_alpha_2\":2, \"cSS_AU_dB1\":1, \"cSS_AU_dB2\":4, \n \"tSS_AU_tips_distance\":5, \"tSS_AU_C1'-B1-B1pair\":2, \"tSS_AU_B1-B1pair-C1'pair\":1, \"tSS_AU_C4'-C1'-B1-B1pair\":3, \"tSS_AU_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_AU_alpha_1\":2, \"tSS_AU_alpha_2\":3, \"tSS_AU_dB1\":3, \"tSS_AU_dB2\":8, \n \"cWW_CA_tips_distance\":2, \"cWW_CA_C1'-B1-B1pair\":2, \"cWW_CA_B1-B1pair-C1'pair\":1, \"cWW_CA_C4'-C1'-B1-B1pair\":2, \"cWW_CA_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_CA_alpha_1\":1, \"cWW_CA_alpha_2\":2, \"cWW_CA_dB1\":1, \"cWW_CA_dB2\":1, \n \"tWW_CA_tips_distance\":4, \"tWW_CA_C1'-B1-B1pair\":2, \"tWW_CA_B1-B1pair-C1'pair\":2, \"tWW_CA_C4'-C1'-B1-B1pair\":3, \"tWW_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_CA_alpha_1\":2, \"tWW_CA_alpha_2\":1, \"tWW_CA_dB1\":4, \"tWW_CA_dB2\":2, \n \"cWH_CA_tips_distance\":3, \"cWH_CA_C1'-B1-B1pair\":3, \"cWH_CA_B1-B1pair-C1'pair\":2, \"cWH_CA_C4'-C1'-B1-B1pair\":2, \"cWH_CA_B1-B1pair-C1'pair-C4'pair\":3, \"cWH_CA_alpha_1\":3, \"cWH_CA_alpha_2\":2, \"cWH_CA_dB1\":5, \"cWH_CA_dB2\":2, \n \"tWH_CA_tips_distance\":5, \"tWH_CA_C1'-B1-B1pair\":1, \"tWH_CA_B1-B1pair-C1'pair\":1, \"tWH_CA_C4'-C1'-B1-B1pair\":2, \"tWH_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_CA_alpha_1\":3, \"tWH_CA_alpha_2\":1, \"tWH_CA_dB1\":3, \"tWH_CA_dB2\":2, \n \"cHW_CA_tips_distance\":2, \"cHW_CA_C1'-B1-B1pair\":2, \"cHW_CA_B1-B1pair-C1'pair\":2, \"cHW_CA_C4'-C1'-B1-B1pair\":2, \"cHW_CA_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_CA_alpha_1\":2, \"cHW_CA_alpha_2\":2, \"cHW_CA_dB1\":4, \"cHW_CA_dB2\":2, \n \"tHW_CA_tips_distance\":2, \"tHW_CA_C1'-B1-B1pair\":2, \"tHW_CA_B1-B1pair-C1'pair\":2, \"tHW_CA_C4'-C1'-B1-B1pair\":2, \"tHW_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_CA_alpha_1\":2, \"tHW_CA_alpha_2\":2, \"tHW_CA_dB1\":6, \"tHW_CA_dB2\":2, \n \"cWS_CA_tips_distance\":2, \"cWS_CA_C1'-B1-B1pair\":2, \"cWS_CA_B1-B1pair-C1'pair\":2, \"cWS_CA_C4'-C1'-B1-B1pair\":2, \"cWS_CA_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_CA_alpha_1\":2, \"cWS_CA_alpha_2\":2, \"cWS_CA_dB1\":4, \"cWS_CA_dB2\":2, \n \"tWS_CA_tips_distance\":5, \"tWS_CA_C1'-B1-B1pair\":3, \"tWS_CA_B1-B1pair-C1'pair\":1, \"tWS_CA_C4'-C1'-B1-B1pair\":3, \"tWS_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_CA_alpha_1\":3, \"tWS_CA_alpha_2\":1, \"tWS_CA_dB1\":1, \"tWS_CA_dB2\":1, \n \"cSW_CA_tips_distance\":1, \"cSW_CA_C1'-B1-B1pair\":1, \"cSW_CA_B1-B1pair-C1'pair\":1, \"cSW_CA_C4'-C1'-B1-B1pair\":1, \"cSW_CA_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_CA_alpha_1\":1, \"cSW_CA_alpha_2\":3, \"cSW_CA_dB1\":1, \"cSW_CA_dB2\":1, \n \"tSW_CA_tips_distance\":3, \"tSW_CA_C1'-B1-B1pair\":2, \"tSW_CA_B1-B1pair-C1'pair\":2, \"tSW_CA_C4'-C1'-B1-B1pair\":1, \"tSW_CA_B1-B1pair-C1'pair-C4'pair\":1, \"tSW_CA_alpha_1\":2, \"tSW_CA_alpha_2\":3, \"tSW_CA_dB1\":3, \"tSW_CA_dB2\":1, \n \"cHH_CA_tips_distance\":5, \"cHH_CA_C1'-B1-B1pair\":2, \"cHH_CA_B1-B1pair-C1'pair\":1, \"cHH_CA_C4'-C1'-B1-B1pair\":3, \"cHH_CA_B1-B1pair-C1'pair-C4'pair\":1, \"cHH_CA_alpha_1\":2, \"cHH_CA_alpha_2\":1, \"cHH_CA_dB1\":1, \"cHH_CA_dB2\":2, \n \"tHH_CA_tips_distance\":1, \"tHH_CA_C1'-B1-B1pair\":2, \"tHH_CA_B1-B1pair-C1'pair\":2, \"tHH_CA_C4'-C1'-B1-B1pair\":3, \"tHH_CA_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_CA_alpha_1\":2, \"tHH_CA_alpha_2\":1, \"tHH_CA_dB1\":3, \"tHH_CA_dB2\":5, \n \"cSH_CA_tips_distance\":3, \"cSH_CA_C1'-B1-B1pair\":1, \"cSH_CA_B1-B1pair-C1'pair\":3, \"cSH_CA_C4'-C1'-B1-B1pair\":2, \"cSH_CA_B1-B1pair-C1'pair-C4'pair\":1, \"cSH_CA_alpha_1\":1, \"cSH_CA_alpha_2\":1, \"cSH_CA_dB1\":2, \"cSH_CA_dB2\":3, \n \"tSH_CA_tips_distance\":2, \"tSH_CA_C1'-B1-B1pair\":1, \"tSH_CA_B1-B1pair-C1'pair\":2, \"tSH_CA_C4'-C1'-B1-B1pair\":2, \"tSH_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_CA_alpha_1\":3, \"tSH_CA_alpha_2\":2, \"tSH_CA_dB1\":6, \"tSH_CA_dB2\":4, \n \"cHS_CA_tips_distance\":2, \"cHS_CA_C1'-B1-B1pair\":2, \"cHS_CA_B1-B1pair-C1'pair\":2, \"cHS_CA_C4'-C1'-B1-B1pair\":1, \"cHS_CA_B1-B1pair-C1'pair-C4'pair\":1, \"cHS_CA_alpha_1\":1, \"cHS_CA_alpha_2\":2, \"cHS_CA_dB1\":2, \"cHS_CA_dB2\":2, \n \"tHS_CA_tips_distance\":3, \"tHS_CA_C1'-B1-B1pair\":2, \"tHS_CA_B1-B1pair-C1'pair\":1, \"tHS_CA_C4'-C1'-B1-B1pair\":2, \"tHS_CA_B1-B1pair-C1'pair-C4'pair\":2, \"tHS_CA_alpha_1\":3, \"tHS_CA_alpha_2\":3, \"tHS_CA_dB1\":2, \"tHS_CA_dB2\":1, \n \"cSS_CA_tips_distance\":7, \"cSS_CA_C1'-B1-B1pair\":2, \"cSS_CA_B1-B1pair-C1'pair\":2, \"cSS_CA_C4'-C1'-B1-B1pair\":1, \"cSS_CA_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_CA_alpha_1\":3, \"cSS_CA_alpha_2\":3, \"cSS_CA_dB1\":3, \"cSS_CA_dB2\":1, \n \"tSS_CA_tips_distance\":5, \"tSS_CA_C1'-B1-B1pair\":2, \"tSS_CA_B1-B1pair-C1'pair\":2, \"tSS_CA_C4'-C1'-B1-B1pair\":2, \"tSS_CA_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_CA_alpha_1\":2, \"tSS_CA_alpha_2\":2, \"tSS_CA_dB1\":4, \"tSS_CA_dB2\":2, \n \"cWW_CC_tips_distance\":3, \"cWW_CC_C1'-B1-B1pair\":1, \"cWW_CC_B1-B1pair-C1'pair\":1, \"cWW_CC_C4'-C1'-B1-B1pair\":2, \"cWW_CC_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_CC_alpha_1\":1, \"cWW_CC_alpha_2\":2, \"cWW_CC_dB1\":2, \"cWW_CC_dB2\":2, \n \"tWW_CC_tips_distance\":6, \"tWW_CC_C1'-B1-B1pair\":3, \"tWW_CC_B1-B1pair-C1'pair\":3, \"tWW_CC_C4'-C1'-B1-B1pair\":3, \"tWW_CC_B1-B1pair-C1'pair-C4'pair\":3, \"tWW_CC_alpha_1\":2, \"tWW_CC_alpha_2\":2, \"tWW_CC_dB1\":6, \"tWW_CC_dB2\":3, \n \"cWH_CC_tips_distance\":4, \"cWH_CC_C1'-B1-B1pair\":2, \"cWH_CC_B1-B1pair-C1'pair\":2, \"cWH_CC_C4'-C1'-B1-B1pair\":2, \"cWH_CC_B1-B1pair-C1'pair-C4'pair\":1, \"cWH_CC_alpha_1\":1, \"cWH_CC_alpha_2\":3, \"cWH_CC_dB1\":3, \"cWH_CC_dB2\":2, \n \"tWH_CC_tips_distance\":1, \"tWH_CC_C1'-B1-B1pair\":1, \"tWH_CC_B1-B1pair-C1'pair\":3, \"tWH_CC_C4'-C1'-B1-B1pair\":2, \"tWH_CC_B1-B1pair-C1'pair-C4'pair\":1, \"tWH_CC_alpha_1\":3, \"tWH_CC_alpha_2\":1, \"tWH_CC_dB1\":3, \"tWH_CC_dB2\":3, \n \"cHW_CC_tips_distance\":4, \"cHW_CC_C1'-B1-B1pair\":3, \"cHW_CC_B1-B1pair-C1'pair\":2, \"cHW_CC_C4'-C1'-B1-B1pair\":1, \"cHW_CC_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_CC_alpha_1\":2, \"cHW_CC_alpha_2\":2, \"cHW_CC_dB1\":2, \"cHW_CC_dB2\":3, \n \"tHW_CC_tips_distance\":2, \"tHW_CC_C1'-B1-B1pair\":1, \"tHW_CC_B1-B1pair-C1'pair\":3, \"tHW_CC_C4'-C1'-B1-B1pair\":3, \"tHW_CC_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_CC_alpha_1\":2, \"tHW_CC_alpha_2\":2, \"tHW_CC_dB1\":3, \"tHW_CC_dB2\":3, \n \"cWS_CC_tips_distance\":3, \"cWS_CC_C1'-B1-B1pair\":2, \"cWS_CC_B1-B1pair-C1'pair\":2, \"cWS_CC_C4'-C1'-B1-B1pair\":1, \"cWS_CC_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_CC_alpha_1\":2, \"cWS_CC_alpha_2\":3, \"cWS_CC_dB1\":2, \"cWS_CC_dB2\":1, \n \"tWS_CC_tips_distance\":5, \"tWS_CC_C1'-B1-B1pair\":2, \"tWS_CC_B1-B1pair-C1'pair\":2, \"tWS_CC_C4'-C1'-B1-B1pair\":2, \"tWS_CC_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_CC_alpha_1\":2, \"tWS_CC_alpha_2\":2, \"tWS_CC_dB1\":2, \"tWS_CC_dB2\":2, \n \"cSW_CC_tips_distance\":3, \"cSW_CC_C1'-B1-B1pair\":2, \"cSW_CC_B1-B1pair-C1'pair\":2, \"cSW_CC_C4'-C1'-B1-B1pair\":2, \"cSW_CC_B1-B1pair-C1'pair-C4'pair\":1, \"cSW_CC_alpha_1\":3, \"cSW_CC_alpha_2\":2, \"cSW_CC_dB1\":2, \"cSW_CC_dB2\":2, \n \"tSW_CC_tips_distance\":5, \"tSW_CC_C1'-B1-B1pair\":1, \"tSW_CC_B1-B1pair-C1'pair\":2, \"tSW_CC_C4'-C1'-B1-B1pair\":1, \"tSW_CC_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_CC_alpha_1\":1, \"tSW_CC_alpha_2\":2, \"tSW_CC_dB1\":3, \"tSW_CC_dB2\":2, \n \"cHH_CC_tips_distance\":5, \"cHH_CC_C1'-B1-B1pair\":1, \"cHH_CC_B1-B1pair-C1'pair\":1, \"cHH_CC_C4'-C1'-B1-B1pair\":1, \"cHH_CC_B1-B1pair-C1'pair-C4'pair\":1, \"cHH_CC_alpha_1\":2, \"cHH_CC_alpha_2\":1, \"cHH_CC_dB1\":7, \"cHH_CC_dB2\":7, \n \"tHH_CC_tips_distance\":5, \"tHH_CC_C1'-B1-B1pair\":3, \"tHH_CC_B1-B1pair-C1'pair\":2, \"tHH_CC_C4'-C1'-B1-B1pair\":3, \"tHH_CC_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_CC_alpha_1\":1, \"tHH_CC_alpha_2\":3, \"tHH_CC_dB1\":5, \"tHH_CC_dB2\":5, \n \"cSH_CC_tips_distance\":3, \"cSH_CC_C1'-B1-B1pair\":2, \"cSH_CC_B1-B1pair-C1'pair\":2, \"cSH_CC_C4'-C1'-B1-B1pair\":2, \"cSH_CC_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_CC_alpha_1\":3, \"cSH_CC_alpha_2\":2, \"cSH_CC_dB1\":5, \"cSH_CC_dB2\":2, \n \"tSH_CC_tips_distance\":5, \"tSH_CC_C1'-B1-B1pair\":2, \"tSH_CC_B1-B1pair-C1'pair\":1, \"tSH_CC_C4'-C1'-B1-B1pair\":2, \"tSH_CC_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_CC_alpha_1\":3, \"tSH_CC_alpha_2\":1, \"tSH_CC_dB1\":4, \"tSH_CC_dB2\":2, \n \"cHS_CC_tips_distance\":3, \"cHS_CC_C1'-B1-B1pair\":2, \"cHS_CC_B1-B1pair-C1'pair\":2, \"cHS_CC_C4'-C1'-B1-B1pair\":2, \"cHS_CC_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_CC_alpha_1\":3, \"cHS_CC_alpha_2\":2, \"cHS_CC_dB1\":2, \"cHS_CC_dB2\":2, \n \"tHS_CC_tips_distance\":5, \"tHS_CC_C1'-B1-B1pair\":3, \"tHS_CC_B1-B1pair-C1'pair\":1, \"tHS_CC_C4'-C1'-B1-B1pair\":2, \"tHS_CC_B1-B1pair-C1'pair-C4'pair\":3, \"tHS_CC_alpha_1\":1, \"tHS_CC_alpha_2\":2, \"tHS_CC_dB1\":4, \"tHS_CC_dB2\":4, \n \"cSS_CC_tips_distance\":5, \"cSS_CC_C1'-B1-B1pair\":2, \"cSS_CC_B1-B1pair-C1'pair\":2, \"cSS_CC_C4'-C1'-B1-B1pair\":2, \"cSS_CC_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_CC_alpha_1\":1, \"cSS_CC_alpha_2\":3, \"cSS_CC_dB1\":1, \"cSS_CC_dB2\":3, \n \"tSS_CC_tips_distance\":5, \"tSS_CC_C1'-B1-B1pair\":2, \"tSS_CC_B1-B1pair-C1'pair\":2, \"tSS_CC_C4'-C1'-B1-B1pair\":3, \"tSS_CC_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_CC_alpha_1\":3, \"tSS_CC_alpha_2\":2, \"tSS_CC_dB1\":2, \"tSS_CC_dB2\":1, \n \"cWW_CG_tips_distance\":5, \"cWW_CG_C1'-B1-B1pair\":2, \"cWW_CG_B1-B1pair-C1'pair\":1, \"cWW_CG_C4'-C1'-B1-B1pair\":2, \"cWW_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_CG_alpha_1\":2, \"cWW_CG_alpha_2\":3, \"cWW_CG_dB1\":2, \"cWW_CG_dB2\":2, \n \"tWW_CG_tips_distance\":3, \"tWW_CG_C1'-B1-B1pair\":1, \"tWW_CG_B1-B1pair-C1'pair\":2, \"tWW_CG_C4'-C1'-B1-B1pair\":2, \"tWW_CG_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_CG_alpha_1\":2, \"tWW_CG_alpha_2\":1, \"tWW_CG_dB1\":1, \"tWW_CG_dB2\":4, \n \"cWH_CG_tips_distance\":3, \"cWH_CG_C1'-B1-B1pair\":1, \"cWH_CG_B1-B1pair-C1'pair\":1, \"cWH_CG_C4'-C1'-B1-B1pair\":2, \"cWH_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_CG_alpha_1\":2, \"cWH_CG_alpha_2\":1, \"cWH_CG_dB1\":4, \"cWH_CG_dB2\":2, \n \"tWH_CG_tips_distance\":4, \"tWH_CG_C1'-B1-B1pair\":2, \"tWH_CG_B1-B1pair-C1'pair\":1, \"tWH_CG_C4'-C1'-B1-B1pair\":2, \"tWH_CG_B1-B1pair-C1'pair-C4'pair\":3, \"tWH_CG_alpha_1\":2, \"tWH_CG_alpha_2\":1, \"tWH_CG_dB1\":3, \"tWH_CG_dB2\":2, \n \"cHW_CG_tips_distance\":3, \"cHW_CG_C1'-B1-B1pair\":2, \"cHW_CG_B1-B1pair-C1'pair\":2, \"cHW_CG_C4'-C1'-B1-B1pair\":1, \"cHW_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_CG_alpha_1\":1, \"cHW_CG_alpha_2\":2, \"cHW_CG_dB1\":2, \"cHW_CG_dB2\":2, \n \"tHW_CG_tips_distance\":5, \"tHW_CG_C1'-B1-B1pair\":1, \"tHW_CG_B1-B1pair-C1'pair\":2, \"tHW_CG_C4'-C1'-B1-B1pair\":1, \"tHW_CG_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_CG_alpha_1\":3, \"tHW_CG_alpha_2\":2, \"tHW_CG_dB1\":4, \"tHW_CG_dB2\":3, \n \"cWS_CG_tips_distance\":2, \"cWS_CG_C1'-B1-B1pair\":1, \"cWS_CG_B1-B1pair-C1'pair\":1, \"cWS_CG_C4'-C1'-B1-B1pair\":2, \"cWS_CG_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_CG_alpha_1\":1, \"cWS_CG_alpha_2\":2, \"cWS_CG_dB1\":2, \"cWS_CG_dB2\":3, \n \"tWS_CG_tips_distance\":2, \"tWS_CG_C1'-B1-B1pair\":3, \"tWS_CG_B1-B1pair-C1'pair\":1, \"tWS_CG_C4'-C1'-B1-B1pair\":2, \"tWS_CG_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_CG_alpha_1\":2, \"tWS_CG_alpha_2\":1, \"tWS_CG_dB1\":2, \"tWS_CG_dB2\":4, \n \"cSW_CG_tips_distance\":7, \"cSW_CG_C1'-B1-B1pair\":1, \"cSW_CG_B1-B1pair-C1'pair\":2, \"cSW_CG_C4'-C1'-B1-B1pair\":2, \"cSW_CG_B1-B1pair-C1'pair-C4'pair\":3, \"cSW_CG_alpha_1\":1, \"cSW_CG_alpha_2\":2, \"cSW_CG_dB1\":1, \"cSW_CG_dB2\":3, \n \"tSW_CG_tips_distance\":4, \"tSW_CG_C1'-B1-B1pair\":1, \"tSW_CG_B1-B1pair-C1'pair\":2, \"tSW_CG_C4'-C1'-B1-B1pair\":3, \"tSW_CG_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_CG_alpha_1\":1, \"tSW_CG_alpha_2\":2, \"tSW_CG_dB1\":7, \"tSW_CG_dB2\":2, \n \"cHH_CG_tips_distance\":1, \"cHH_CG_C1'-B1-B1pair\":1, \"cHH_CG_B1-B1pair-C1'pair\":2, \"cHH_CG_C4'-C1'-B1-B1pair\":3, \"cHH_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_CG_alpha_1\":1, \"cHH_CG_alpha_2\":2, \"cHH_CG_dB1\":4, \"cHH_CG_dB2\":1, \n \"tHH_CG_tips_distance\":8, \"tHH_CG_C1'-B1-B1pair\":2, \"tHH_CG_B1-B1pair-C1'pair\":2, \"tHH_CG_C4'-C1'-B1-B1pair\":3, \"tHH_CG_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_CG_alpha_1\":2, \"tHH_CG_alpha_2\":3, \"tHH_CG_dB1\":3, \"tHH_CG_dB2\":4, \n \"cSH_CG_tips_distance\":5, \"cSH_CG_C1'-B1-B1pair\":1, \"cSH_CG_B1-B1pair-C1'pair\":2, \"cSH_CG_C4'-C1'-B1-B1pair\":2, \"cSH_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_CG_alpha_1\":1, \"cSH_CG_alpha_2\":2, \"cSH_CG_dB1\":6, \"cSH_CG_dB2\":4, \n \"tSH_CG_tips_distance\":5, \"tSH_CG_C1'-B1-B1pair\":1, \"tSH_CG_B1-B1pair-C1'pair\":2, \"tSH_CG_C4'-C1'-B1-B1pair\":2, \"tSH_CG_B1-B1pair-C1'pair-C4'pair\":1, \"tSH_CG_alpha_1\":1, \"tSH_CG_alpha_2\":3, \"tSH_CG_dB1\":2, \"tSH_CG_dB2\":3, \n \"cHS_CG_tips_distance\":4, \"cHS_CG_C1'-B1-B1pair\":2, \"cHS_CG_B1-B1pair-C1'pair\":2, \"cHS_CG_C4'-C1'-B1-B1pair\":3, \"cHS_CG_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_CG_alpha_1\":2, \"cHS_CG_alpha_2\":3, \"cHS_CG_dB1\":5, \"cHS_CG_dB2\":2, \n \"tHS_CG_tips_distance\":4, \"tHS_CG_C1'-B1-B1pair\":1, \"tHS_CG_B1-B1pair-C1'pair\":2, \"tHS_CG_C4'-C1'-B1-B1pair\":3, \"tHS_CG_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_CG_alpha_1\":1, \"tHS_CG_alpha_2\":1, \"tHS_CG_dB1\":3, \"tHS_CG_dB2\":2, \n \"cSS_CG_tips_distance\":1, \"cSS_CG_C1'-B1-B1pair\":2, \"cSS_CG_B1-B1pair-C1'pair\":1, \"cSS_CG_C4'-C1'-B1-B1pair\":2, \"cSS_CG_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_CG_alpha_1\":1, \"cSS_CG_alpha_2\":2, \"cSS_CG_dB1\":3, \"cSS_CG_dB2\":3, \n \"tSS_CG_tips_distance\":5, \"tSS_CG_C1'-B1-B1pair\":2, \"tSS_CG_B1-B1pair-C1'pair\":2, \"tSS_CG_C4'-C1'-B1-B1pair\":1, \"tSS_CG_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_CG_alpha_1\":1, \"tSS_CG_alpha_2\":2, \"tSS_CG_dB1\":1, \"tSS_CG_dB2\":2, \n \"cWW_CU_tips_distance\":4, \"cWW_CU_C1'-B1-B1pair\":1, \"cWW_CU_B1-B1pair-C1'pair\":1, \"cWW_CU_C4'-C1'-B1-B1pair\":2, \"cWW_CU_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_CU_alpha_1\":1, \"cWW_CU_alpha_2\":1, \"cWW_CU_dB1\":1, \"cWW_CU_dB2\":1, \n \"tWW_CU_tips_distance\":1, \"tWW_CU_C1'-B1-B1pair\":2, \"tWW_CU_B1-B1pair-C1'pair\":2, \"tWW_CU_C4'-C1'-B1-B1pair\":2, \"tWW_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_CU_alpha_1\":1, \"tWW_CU_alpha_2\":2, \"tWW_CU_dB1\":2, \"tWW_CU_dB2\":1, \n \"cWH_CU_tips_distance\":5, \"cWH_CU_C1'-B1-B1pair\":2, \"cWH_CU_B1-B1pair-C1'pair\":2, \"cWH_CU_C4'-C1'-B1-B1pair\":2, \"cWH_CU_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_CU_alpha_1\":3, \"cWH_CU_alpha_2\":2, \"cWH_CU_dB1\":3, \"cWH_CU_dB2\":1, \n \"tWH_CU_tips_distance\":1, \"tWH_CU_C1'-B1-B1pair\":2, \"tWH_CU_B1-B1pair-C1'pair\":2, \"tWH_CU_C4'-C1'-B1-B1pair\":3, \"tWH_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_CU_alpha_1\":3, \"tWH_CU_alpha_2\":3, \"tWH_CU_dB1\":5, \"tWH_CU_dB2\":2, \n \"cHW_CU_tips_distance\":3, \"cHW_CU_C1'-B1-B1pair\":2, \"cHW_CU_B1-B1pair-C1'pair\":2, \"cHW_CU_C4'-C1'-B1-B1pair\":1, \"cHW_CU_B1-B1pair-C1'pair-C4'pair\":3, \"cHW_CU_alpha_1\":2, \"cHW_CU_alpha_2\":2, \"cHW_CU_dB1\":1, \"cHW_CU_dB2\":3, \n \"tHW_CU_tips_distance\":8, \"tHW_CU_C1'-B1-B1pair\":1, \"tHW_CU_B1-B1pair-C1'pair\":1, \"tHW_CU_C4'-C1'-B1-B1pair\":3, \"tHW_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_CU_alpha_1\":1, \"tHW_CU_alpha_2\":2, \"tHW_CU_dB1\":3, \"tHW_CU_dB2\":3, \n \"cWS_CU_tips_distance\":4, \"cWS_CU_C1'-B1-B1pair\":1, \"cWS_CU_B1-B1pair-C1'pair\":2, \"cWS_CU_C4'-C1'-B1-B1pair\":3, \"cWS_CU_B1-B1pair-C1'pair-C4'pair\":2, \"cWS_CU_alpha_1\":3, \"cWS_CU_alpha_2\":2, \"cWS_CU_dB1\":4, \"cWS_CU_dB2\":2, \n \"tWS_CU_tips_distance\":5, \"tWS_CU_C1'-B1-B1pair\":3, \"tWS_CU_B1-B1pair-C1'pair\":1, \"tWS_CU_C4'-C1'-B1-B1pair\":2, \"tWS_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_CU_alpha_1\":2, \"tWS_CU_alpha_2\":1, \"tWS_CU_dB1\":3, \"tWS_CU_dB2\":5, \n \"cSW_CU_tips_distance\":3, \"cSW_CU_C1'-B1-B1pair\":2, \"cSW_CU_B1-B1pair-C1'pair\":2, \"cSW_CU_C4'-C1'-B1-B1pair\":2, \"cSW_CU_B1-B1pair-C1'pair-C4'pair\":3, \"cSW_CU_alpha_1\":3, \"cSW_CU_alpha_2\":3, \"cSW_CU_dB1\":2, \"cSW_CU_dB2\":4, \n \"tSW_CU_tips_distance\":7, \"tSW_CU_C1'-B1-B1pair\":2, \"tSW_CU_B1-B1pair-C1'pair\":2, \"tSW_CU_C4'-C1'-B1-B1pair\":2, \"tSW_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_CU_alpha_1\":2, \"tSW_CU_alpha_2\":2, \"tSW_CU_dB1\":2, \"tSW_CU_dB2\":2, \n \"cHH_CU_tips_distance\":6, \"cHH_CU_C1'-B1-B1pair\":2, \"cHH_CU_B1-B1pair-C1'pair\":1, \"cHH_CU_C4'-C1'-B1-B1pair\":2, \"cHH_CU_B1-B1pair-C1'pair-C4'pair\":3, \"cHH_CU_alpha_1\":1, \"cHH_CU_alpha_2\":1, \"cHH_CU_dB1\":2, \"cHH_CU_dB2\":4, \n \"tHH_CU_tips_distance\":5, \"tHH_CU_C1'-B1-B1pair\":3, \"tHH_CU_B1-B1pair-C1'pair\":2, \"tHH_CU_C4'-C1'-B1-B1pair\":2, \"tHH_CU_B1-B1pair-C1'pair-C4'pair\":1, \"tHH_CU_alpha_1\":2, \"tHH_CU_alpha_2\":2, \"tHH_CU_dB1\":2, \"tHH_CU_dB2\":2, \n \"cSH_CU_tips_distance\":5, \"cSH_CU_C1'-B1-B1pair\":2, \"cSH_CU_B1-B1pair-C1'pair\":2, \"cSH_CU_C4'-C1'-B1-B1pair\":2, \"cSH_CU_B1-B1pair-C1'pair-C4'pair\":1, \"cSH_CU_alpha_1\":1, \"cSH_CU_alpha_2\":1, \"cSH_CU_dB1\":4, \"cSH_CU_dB2\":2, \n \"tSH_CU_tips_distance\":5, \"tSH_CU_C1'-B1-B1pair\":2, \"tSH_CU_B1-B1pair-C1'pair\":3, \"tSH_CU_C4'-C1'-B1-B1pair\":2, \"tSH_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_CU_alpha_1\":3, \"tSH_CU_alpha_2\":3, \"tSH_CU_dB1\":4, \"tSH_CU_dB2\":2, \n \"cHS_CU_tips_distance\":2, \"cHS_CU_C1'-B1-B1pair\":1, \"cHS_CU_B1-B1pair-C1'pair\":2, \"cHS_CU_C4'-C1'-B1-B1pair\":2, \"cHS_CU_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_CU_alpha_1\":1, \"cHS_CU_alpha_2\":2, \"cHS_CU_dB1\":2, \"cHS_CU_dB2\":4, \n \"tHS_CU_tips_distance\":8, \"tHS_CU_C1'-B1-B1pair\":2, \"tHS_CU_B1-B1pair-C1'pair\":1, \"tHS_CU_C4'-C1'-B1-B1pair\":2, \"tHS_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tHS_CU_alpha_1\":2, \"tHS_CU_alpha_2\":2, \"tHS_CU_dB1\":3, \"tHS_CU_dB2\":4, \n \"cSS_CU_tips_distance\":5, \"cSS_CU_C1'-B1-B1pair\":2, \"cSS_CU_B1-B1pair-C1'pair\":2, \"cSS_CU_C4'-C1'-B1-B1pair\":1, \"cSS_CU_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_CU_alpha_1\":2, \"cSS_CU_alpha_2\":3, \"cSS_CU_dB1\":6, \"cSS_CU_dB2\":1, \n \"tSS_CU_tips_distance\":5, \"tSS_CU_C1'-B1-B1pair\":2, \"tSS_CU_B1-B1pair-C1'pair\":3, \"tSS_CU_C4'-C1'-B1-B1pair\":2, \"tSS_CU_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_CU_alpha_1\":3, \"tSS_CU_alpha_2\":3, \"tSS_CU_dB1\":7, \"tSS_CU_dB2\":2, \n \"cWW_GA_tips_distance\":5, \"cWW_GA_C1'-B1-B1pair\":1, \"cWW_GA_B1-B1pair-C1'pair\":1, \"cWW_GA_C4'-C1'-B1-B1pair\":2, \"cWW_GA_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_GA_alpha_1\":1, \"cWW_GA_alpha_2\":1, \"cWW_GA_dB1\":2, \"cWW_GA_dB2\":1, \n \"tWW_GA_tips_distance\":6, \"tWW_GA_C1'-B1-B1pair\":1, \"tWW_GA_B1-B1pair-C1'pair\":1, \"tWW_GA_C4'-C1'-B1-B1pair\":1, \"tWW_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_GA_alpha_1\":2, \"tWW_GA_alpha_2\":2, \"tWW_GA_dB1\":1, \"tWW_GA_dB2\":2, \n \"cWH_GA_tips_distance\":2, \"cWH_GA_C1'-B1-B1pair\":1, \"cWH_GA_B1-B1pair-C1'pair\":1, \"cWH_GA_C4'-C1'-B1-B1pair\":3, \"cWH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_GA_alpha_1\":2, \"cWH_GA_alpha_2\":1, \"cWH_GA_dB1\":2, \"cWH_GA_dB2\":2, \n \"tWH_GA_tips_distance\":7, \"tWH_GA_C1'-B1-B1pair\":1, \"tWH_GA_B1-B1pair-C1'pair\":2, \"tWH_GA_C4'-C1'-B1-B1pair\":1, \"tWH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_GA_alpha_1\":2, \"tWH_GA_alpha_2\":2, \"tWH_GA_dB1\":1, \"tWH_GA_dB2\":6, \n \"cHW_GA_tips_distance\":4, \"cHW_GA_C1'-B1-B1pair\":2, \"cHW_GA_B1-B1pair-C1'pair\":2, \"cHW_GA_C4'-C1'-B1-B1pair\":2, \"cHW_GA_B1-B1pair-C1'pair-C4'pair\":3, \"cHW_GA_alpha_1\":1, \"cHW_GA_alpha_2\":2, \"cHW_GA_dB1\":1, \"cHW_GA_dB2\":4, \n \"tHW_GA_tips_distance\":3, \"tHW_GA_C1'-B1-B1pair\":2, \"tHW_GA_B1-B1pair-C1'pair\":1, \"tHW_GA_C4'-C1'-B1-B1pair\":2, \"tHW_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_GA_alpha_1\":1, \"tHW_GA_alpha_2\":2, \"tHW_GA_dB1\":3, \"tHW_GA_dB2\":1, \n \"cWS_GA_tips_distance\":6, \"cWS_GA_C1'-B1-B1pair\":3, \"cWS_GA_B1-B1pair-C1'pair\":2, \"cWS_GA_C4'-C1'-B1-B1pair\":2, \"cWS_GA_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_GA_alpha_1\":2, \"cWS_GA_alpha_2\":3, \"cWS_GA_dB1\":3, \"cWS_GA_dB2\":4, \n \"tWS_GA_tips_distance\":5, \"tWS_GA_C1'-B1-B1pair\":3, \"tWS_GA_B1-B1pair-C1'pair\":2, \"tWS_GA_C4'-C1'-B1-B1pair\":1, \"tWS_GA_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_GA_alpha_1\":2, \"tWS_GA_alpha_2\":2, \"tWS_GA_dB1\":2, \"tWS_GA_dB2\":5, \n \"cSW_GA_tips_distance\":4, \"cSW_GA_C1'-B1-B1pair\":1, \"cSW_GA_B1-B1pair-C1'pair\":1, \"cSW_GA_C4'-C1'-B1-B1pair\":1, \"cSW_GA_B1-B1pair-C1'pair-C4'pair\":1, \"cSW_GA_alpha_1\":1, \"cSW_GA_alpha_2\":2, \"cSW_GA_dB1\":1, \"cSW_GA_dB2\":2, \n \"tSW_GA_tips_distance\":2, \"tSW_GA_C1'-B1-B1pair\":1, \"tSW_GA_B1-B1pair-C1'pair\":2, \"tSW_GA_C4'-C1'-B1-B1pair\":1, \"tSW_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_GA_alpha_1\":1, \"tSW_GA_alpha_2\":3, \"tSW_GA_dB1\":2, \"tSW_GA_dB2\":2, \n \"cHH_GA_tips_distance\":3, \"cHH_GA_C1'-B1-B1pair\":2, \"cHH_GA_B1-B1pair-C1'pair\":2, \"cHH_GA_C4'-C1'-B1-B1pair\":2, \"cHH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_GA_alpha_1\":2, \"cHH_GA_alpha_2\":3, \"cHH_GA_dB1\":2, \"cHH_GA_dB2\":3, \n \"tHH_GA_tips_distance\":3, \"tHH_GA_C1'-B1-B1pair\":3, \"tHH_GA_B1-B1pair-C1'pair\":2, \"tHH_GA_C4'-C1'-B1-B1pair\":2, \"tHH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_GA_alpha_1\":1, \"tHH_GA_alpha_2\":2, \"tHH_GA_dB1\":3, \"tHH_GA_dB2\":2, \n \"cSH_GA_tips_distance\":1, \"cSH_GA_C1'-B1-B1pair\":2, \"cSH_GA_B1-B1pair-C1'pair\":2, \"cSH_GA_C4'-C1'-B1-B1pair\":2, \"cSH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_GA_alpha_1\":1, \"cSH_GA_alpha_2\":2, \"cSH_GA_dB1\":2, \"cSH_GA_dB2\":1, \n \"tSH_GA_tips_distance\":3, \"tSH_GA_C1'-B1-B1pair\":1, \"tSH_GA_B1-B1pair-C1'pair\":1, \"tSH_GA_C4'-C1'-B1-B1pair\":2, \"tSH_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_GA_alpha_1\":2, \"tSH_GA_alpha_2\":2, \"tSH_GA_dB1\":2, \"tSH_GA_dB2\":7, \n \"cHS_GA_tips_distance\":5, \"cHS_GA_C1'-B1-B1pair\":3, \"cHS_GA_B1-B1pair-C1'pair\":3, \"cHS_GA_C4'-C1'-B1-B1pair\":3, \"cHS_GA_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_GA_alpha_1\":2, \"cHS_GA_alpha_2\":2, \"cHS_GA_dB1\":3, \"cHS_GA_dB2\":4, \n \"tHS_GA_tips_distance\":5, \"tHS_GA_C1'-B1-B1pair\":3, \"tHS_GA_B1-B1pair-C1'pair\":1, \"tHS_GA_C4'-C1'-B1-B1pair\":3, \"tHS_GA_B1-B1pair-C1'pair-C4'pair\":2, \"tHS_GA_alpha_1\":2, \"tHS_GA_alpha_2\":1, \"tHS_GA_dB1\":1, \"tHS_GA_dB2\":2, \n \"cSS_GA_tips_distance\":4, \"cSS_GA_C1'-B1-B1pair\":3, \"cSS_GA_B1-B1pair-C1'pair\":2, \"cSS_GA_C4'-C1'-B1-B1pair\":1, \"cSS_GA_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_GA_alpha_1\":2, \"cSS_GA_alpha_2\":1, \"cSS_GA_dB1\":1, \"cSS_GA_dB2\":1, \n \"tSS_GA_tips_distance\":4, \"tSS_GA_C1'-B1-B1pair\":1, \"tSS_GA_B1-B1pair-C1'pair\":1, \"tSS_GA_C4'-C1'-B1-B1pair\":1, \"tSS_GA_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_GA_alpha_1\":1, \"tSS_GA_alpha_2\":2, \"tSS_GA_dB1\":5, \"tSS_GA_dB2\":2, \n \"cWW_GC_tips_distance\":5, \"cWW_GC_C1'-B1-B1pair\":1, \"cWW_GC_B1-B1pair-C1'pair\":2, \"cWW_GC_C4'-C1'-B1-B1pair\":2, \"cWW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_GC_alpha_1\":2, \"cWW_GC_alpha_2\":1, \"cWW_GC_dB1\":2, \"cWW_GC_dB2\":3, \n \"tWW_GC_tips_distance\":3, \"tWW_GC_C1'-B1-B1pair\":1, \"tWW_GC_B1-B1pair-C1'pair\":2, \"tWW_GC_C4'-C1'-B1-B1pair\":2, \"tWW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_GC_alpha_1\":1, \"tWW_GC_alpha_2\":2, \"tWW_GC_dB1\":3, \"tWW_GC_dB2\":4, \n \"cWH_GC_tips_distance\":7, \"cWH_GC_C1'-B1-B1pair\":2, \"cWH_GC_B1-B1pair-C1'pair\":2, \"cWH_GC_C4'-C1'-B1-B1pair\":2, \"cWH_GC_B1-B1pair-C1'pair-C4'pair\":1, \"cWH_GC_alpha_1\":2, \"cWH_GC_alpha_2\":2, \"cWH_GC_dB1\":2, \"cWH_GC_dB2\":3, \n \"tWH_GC_tips_distance\":5, \"tWH_GC_C1'-B1-B1pair\":1, \"tWH_GC_B1-B1pair-C1'pair\":1, \"tWH_GC_C4'-C1'-B1-B1pair\":2, \"tWH_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_GC_alpha_1\":3, \"tWH_GC_alpha_2\":3, \"tWH_GC_dB1\":2, \"tWH_GC_dB2\":2, \n \"cHW_GC_tips_distance\":4, \"cHW_GC_C1'-B1-B1pair\":1, \"cHW_GC_B1-B1pair-C1'pair\":1, \"cHW_GC_C4'-C1'-B1-B1pair\":2, \"cHW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_GC_alpha_1\":1, \"cHW_GC_alpha_2\":1, \"cHW_GC_dB1\":3, \"cHW_GC_dB2\":4, \n \"tHW_GC_tips_distance\":5, \"tHW_GC_C1'-B1-B1pair\":2, \"tHW_GC_B1-B1pair-C1'pair\":2, \"tHW_GC_C4'-C1'-B1-B1pair\":2, \"tHW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_GC_alpha_1\":2, \"tHW_GC_alpha_2\":2, \"tHW_GC_dB1\":2, \"tHW_GC_dB2\":4, \n \"cWS_GC_tips_distance\":8, \"cWS_GC_C1'-B1-B1pair\":1, \"cWS_GC_B1-B1pair-C1'pair\":1, \"cWS_GC_C4'-C1'-B1-B1pair\":2, \"cWS_GC_B1-B1pair-C1'pair-C4'pair\":2, \"cWS_GC_alpha_1\":2, \"cWS_GC_alpha_2\":1, \"cWS_GC_dB1\":2, \"cWS_GC_dB2\":1, \n \"tWS_GC_tips_distance\":2, \"tWS_GC_C1'-B1-B1pair\":1, \"tWS_GC_B1-B1pair-C1'pair\":1, \"tWS_GC_C4'-C1'-B1-B1pair\":3, \"tWS_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_GC_alpha_1\":2, \"tWS_GC_alpha_2\":1, \"tWS_GC_dB1\":4, \"tWS_GC_dB2\":5, \n \"cSW_GC_tips_distance\":4, \"cSW_GC_C1'-B1-B1pair\":2, \"cSW_GC_B1-B1pair-C1'pair\":3, \"cSW_GC_C4'-C1'-B1-B1pair\":1, \"cSW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_GC_alpha_1\":3, \"cSW_GC_alpha_2\":2, \"cSW_GC_dB1\":3, \"cSW_GC_dB2\":2, \n \"tSW_GC_tips_distance\":2, \"tSW_GC_C1'-B1-B1pair\":1, \"tSW_GC_B1-B1pair-C1'pair\":3, \"tSW_GC_C4'-C1'-B1-B1pair\":1, \"tSW_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_GC_alpha_1\":2, \"tSW_GC_alpha_2\":2, \"tSW_GC_dB1\":4, \"tSW_GC_dB2\":2, \n \"cHH_GC_tips_distance\":1, \"cHH_GC_C1'-B1-B1pair\":3, \"cHH_GC_B1-B1pair-C1'pair\":1, \"cHH_GC_C4'-C1'-B1-B1pair\":2, \"cHH_GC_B1-B1pair-C1'pair-C4'pair\":1, \"cHH_GC_alpha_1\":2, \"cHH_GC_alpha_2\":2, \"cHH_GC_dB1\":3, \"cHH_GC_dB2\":3, \n \"tHH_GC_tips_distance\":8, \"tHH_GC_C1'-B1-B1pair\":2, \"tHH_GC_B1-B1pair-C1'pair\":1, \"tHH_GC_C4'-C1'-B1-B1pair\":2, \"tHH_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_GC_alpha_1\":3, \"tHH_GC_alpha_2\":1, \"tHH_GC_dB1\":6, \"tHH_GC_dB2\":3, \n \"cSH_GC_tips_distance\":8, \"cSH_GC_C1'-B1-B1pair\":2, \"cSH_GC_B1-B1pair-C1'pair\":3, \"cSH_GC_C4'-C1'-B1-B1pair\":1, \"cSH_GC_B1-B1pair-C1'pair-C4'pair\":3, \"cSH_GC_alpha_1\":2, \"cSH_GC_alpha_2\":2, \"cSH_GC_dB1\":5, \"cSH_GC_dB2\":4, \n \"tSH_GC_tips_distance\":4, \"tSH_GC_C1'-B1-B1pair\":1, \"tSH_GC_B1-B1pair-C1'pair\":2, \"tSH_GC_C4'-C1'-B1-B1pair\":1, \"tSH_GC_B1-B1pair-C1'pair-C4'pair\":4, \"tSH_GC_alpha_1\":1, \"tSH_GC_alpha_2\":2, \"tSH_GC_dB1\":2, \"tSH_GC_dB2\":3, \n \"cHS_GC_tips_distance\":5, \"cHS_GC_C1'-B1-B1pair\":2, \"cHS_GC_B1-B1pair-C1'pair\":2, \"cHS_GC_C4'-C1'-B1-B1pair\":2, \"cHS_GC_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_GC_alpha_1\":3, \"cHS_GC_alpha_2\":1, \"cHS_GC_dB1\":2, \"cHS_GC_dB2\":5, \n \"tHS_GC_tips_distance\":5, \"tHS_GC_C1'-B1-B1pair\":2, \"tHS_GC_B1-B1pair-C1'pair\":2, \"tHS_GC_C4'-C1'-B1-B1pair\":2, \"tHS_GC_B1-B1pair-C1'pair-C4'pair\":3, \"tHS_GC_alpha_1\":2, \"tHS_GC_alpha_2\":2, \"tHS_GC_dB1\":2, \"tHS_GC_dB2\":2, \n \"cSS_GC_tips_distance\":2, \"cSS_GC_C1'-B1-B1pair\":2, \"cSS_GC_B1-B1pair-C1'pair\":2, \"cSS_GC_C4'-C1'-B1-B1pair\":1, \"cSS_GC_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_GC_alpha_1\":2, \"cSS_GC_alpha_2\":3, \"cSS_GC_dB1\":3, \"cSS_GC_dB2\":3, \n \"tSS_GC_tips_distance\":5, \"tSS_GC_C1'-B1-B1pair\":2, \"tSS_GC_B1-B1pair-C1'pair\":2, \"tSS_GC_C4'-C1'-B1-B1pair\":1, \"tSS_GC_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_GC_alpha_1\":2, \"tSS_GC_alpha_2\":3, \"tSS_GC_dB1\":2, \"tSS_GC_dB2\":1, \n \"cWW_GG_tips_distance\":3, \"cWW_GG_C1'-B1-B1pair\":1, \"cWW_GG_B1-B1pair-C1'pair\":1, \"cWW_GG_C4'-C1'-B1-B1pair\":2, \"cWW_GG_B1-B1pair-C1'pair-C4'pair\":1, \"cWW_GG_alpha_1\":1, \"cWW_GG_alpha_2\":2, \"cWW_GG_dB1\":2, \"cWW_GG_dB2\":2, \n \"tWW_GG_tips_distance\":4, \"tWW_GG_C1'-B1-B1pair\":1, \"tWW_GG_B1-B1pair-C1'pair\":1, \"tWW_GG_C4'-C1'-B1-B1pair\":2, \"tWW_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_GG_alpha_1\":2, \"tWW_GG_alpha_2\":2, \"tWW_GG_dB1\":1, \"tWW_GG_dB2\":2, \n \"cWH_GG_tips_distance\":2, \"cWH_GG_C1'-B1-B1pair\":2, \"cWH_GG_B1-B1pair-C1'pair\":2, \"cWH_GG_C4'-C1'-B1-B1pair\":2, \"cWH_GG_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_GG_alpha_1\":2, \"cWH_GG_alpha_2\":2, \"cWH_GG_dB1\":4, \"cWH_GG_dB2\":3, \n \"tWH_GG_tips_distance\":2, \"tWH_GG_C1'-B1-B1pair\":1, \"tWH_GG_B1-B1pair-C1'pair\":2, \"tWH_GG_C4'-C1'-B1-B1pair\":2, \"tWH_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_GG_alpha_1\":2, \"tWH_GG_alpha_2\":2, \"tWH_GG_dB1\":2, \"tWH_GG_dB2\":3, \n \"cHW_GG_tips_distance\":3, \"cHW_GG_C1'-B1-B1pair\":2, \"cHW_GG_B1-B1pair-C1'pair\":2, \"cHW_GG_C4'-C1'-B1-B1pair\":2, \"cHW_GG_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_GG_alpha_1\":1, \"cHW_GG_alpha_2\":1, \"cHW_GG_dB1\":2, \"cHW_GG_dB2\":2, \n \"tHW_GG_tips_distance\":4, \"tHW_GG_C1'-B1-B1pair\":2, \"tHW_GG_B1-B1pair-C1'pair\":2, \"tHW_GG_C4'-C1'-B1-B1pair\":1, \"tHW_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_GG_alpha_1\":2, \"tHW_GG_alpha_2\":2, \"tHW_GG_dB1\":1, \"tHW_GG_dB2\":4, \n \"cWS_GG_tips_distance\":2, \"cWS_GG_C1'-B1-B1pair\":1, \"cWS_GG_B1-B1pair-C1'pair\":1, \"cWS_GG_C4'-C1'-B1-B1pair\":2, \"cWS_GG_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_GG_alpha_1\":2, \"cWS_GG_alpha_2\":2, \"cWS_GG_dB1\":4, \"cWS_GG_dB2\":3, \n \"tWS_GG_tips_distance\":8, \"tWS_GG_C1'-B1-B1pair\":3, \"tWS_GG_B1-B1pair-C1'pair\":2, \"tWS_GG_C4'-C1'-B1-B1pair\":3, \"tWS_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_GG_alpha_1\":1, \"tWS_GG_alpha_2\":1, \"tWS_GG_dB1\":1, \"tWS_GG_dB2\":3, \n \"cSW_GG_tips_distance\":1, \"cSW_GG_C1'-B1-B1pair\":1, \"cSW_GG_B1-B1pair-C1'pair\":1, \"cSW_GG_C4'-C1'-B1-B1pair\":1, \"cSW_GG_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_GG_alpha_1\":2, \"cSW_GG_alpha_2\":2, \"cSW_GG_dB1\":2, \"cSW_GG_dB2\":2, \n \"tSW_GG_tips_distance\":5, \"tSW_GG_C1'-B1-B1pair\":3, \"tSW_GG_B1-B1pair-C1'pair\":2, \"tSW_GG_C4'-C1'-B1-B1pair\":3, \"tSW_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_GG_alpha_1\":1, \"tSW_GG_alpha_2\":3, \"tSW_GG_dB1\":2, \"tSW_GG_dB2\":1, \n \"cHH_GG_tips_distance\":4, \"cHH_GG_C1'-B1-B1pair\":1, \"cHH_GG_B1-B1pair-C1'pair\":1, \"cHH_GG_C4'-C1'-B1-B1pair\":2, \"cHH_GG_B1-B1pair-C1'pair-C4'pair\":3, \"cHH_GG_alpha_1\":1, \"cHH_GG_alpha_2\":2, \"cHH_GG_dB1\":2, \"cHH_GG_dB2\":3, \n \"tHH_GG_tips_distance\":8, \"tHH_GG_C1'-B1-B1pair\":2, \"tHH_GG_B1-B1pair-C1'pair\":2, \"tHH_GG_C4'-C1'-B1-B1pair\":2, \"tHH_GG_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_GG_alpha_1\":2, \"tHH_GG_alpha_2\":2, \"tHH_GG_dB1\":2, \"tHH_GG_dB2\":3, \n \"cSH_GG_tips_distance\":2, \"cSH_GG_C1'-B1-B1pair\":2, \"cSH_GG_B1-B1pair-C1'pair\":1, \"cSH_GG_C4'-C1'-B1-B1pair\":1, \"cSH_GG_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_GG_alpha_1\":2, \"cSH_GG_alpha_2\":1, \"cSH_GG_dB1\":1, \"cSH_GG_dB2\":1, \n \"tSH_GG_tips_distance\":2, \"tSH_GG_C1'-B1-B1pair\":2, \"tSH_GG_B1-B1pair-C1'pair\":2, \"tSH_GG_C4'-C1'-B1-B1pair\":2, \"tSH_GG_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_GG_alpha_1\":2, \"tSH_GG_alpha_2\":2, \"tSH_GG_dB1\":1, \"tSH_GG_dB2\":2, \n \"cHS_GG_tips_distance\":2, \"cHS_GG_C1'-B1-B1pair\":1, \"cHS_GG_B1-B1pair-C1'pair\":2, \"cHS_GG_C4'-C1'-B1-B1pair\":2, \"cHS_GG_B1-B1pair-C1'pair-C4'pair\":1, \"cHS_GG_alpha_1\":1, \"cHS_GG_alpha_2\":2, \"cHS_GG_dB1\":1, \"cHS_GG_dB2\":2, \n \"tHS_GG_tips_distance\":2, \"tHS_GG_C1'-B1-B1pair\":2, \"tHS_GG_B1-B1pair-C1'pair\":2, \"tHS_GG_C4'-C1'-B1-B1pair\":2, \"tHS_GG_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_GG_alpha_1\":2, \"tHS_GG_alpha_2\":3, \"tHS_GG_dB1\":2, \"tHS_GG_dB2\":1, \n \"cSS_GG_tips_distance\":2, \"cSS_GG_C1'-B1-B1pair\":2, \"cSS_GG_B1-B1pair-C1'pair\":2, \"cSS_GG_C4'-C1'-B1-B1pair\":1, \"cSS_GG_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_GG_alpha_1\":2, \"cSS_GG_alpha_2\":3, \"cSS_GG_dB1\":3, \"cSS_GG_dB2\":5, \n \"tSS_GG_tips_distance\":2, \"tSS_GG_C1'-B1-B1pair\":3, \"tSS_GG_B1-B1pair-C1'pair\":2, \"tSS_GG_C4'-C1'-B1-B1pair\":2, \"tSS_GG_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_GG_alpha_1\":1, \"tSS_GG_alpha_2\":3, \"tSS_GG_dB1\":3, \"tSS_GG_dB2\":2, \n \"cWW_GU_tips_distance\":2, \"cWW_GU_C1'-B1-B1pair\":2, \"cWW_GU_B1-B1pair-C1'pair\":2, \"cWW_GU_C4'-C1'-B1-B1pair\":2, \"cWW_GU_B1-B1pair-C1'pair-C4'pair\":1, \"cWW_GU_alpha_1\":3, \"cWW_GU_alpha_2\":2, \"cWW_GU_dB1\":4, \"cWW_GU_dB2\":3, \n \"tWW_GU_tips_distance\":2, \"tWW_GU_C1'-B1-B1pair\":3, \"tWW_GU_B1-B1pair-C1'pair\":2, \"tWW_GU_C4'-C1'-B1-B1pair\":2, \"tWW_GU_B1-B1pair-C1'pair-C4'pair\":3, \"tWW_GU_alpha_1\":2, \"tWW_GU_alpha_2\":2, \"tWW_GU_dB1\":3, \"tWW_GU_dB2\":3, \n \"cWH_GU_tips_distance\":2, \"cWH_GU_C1'-B1-B1pair\":1, \"cWH_GU_B1-B1pair-C1'pair\":2, \"cWH_GU_C4'-C1'-B1-B1pair\":1, \"cWH_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_GU_alpha_1\":2, \"cWH_GU_alpha_2\":4, \"cWH_GU_dB1\":3, \"cWH_GU_dB2\":1, \n \"tWH_GU_tips_distance\":8, \"tWH_GU_C1'-B1-B1pair\":1, \"tWH_GU_B1-B1pair-C1'pair\":2, \"tWH_GU_C4'-C1'-B1-B1pair\":2, \"tWH_GU_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_GU_alpha_1\":2, \"tWH_GU_alpha_2\":2, \"tWH_GU_dB1\":3, \"tWH_GU_dB2\":1, \n \"cHW_GU_tips_distance\":4, \"cHW_GU_C1'-B1-B1pair\":2, \"cHW_GU_B1-B1pair-C1'pair\":1, \"cHW_GU_C4'-C1'-B1-B1pair\":2, \"cHW_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_GU_alpha_1\":2, \"cHW_GU_alpha_2\":2, \"cHW_GU_dB1\":3, \"cHW_GU_dB2\":3, \n \"tHW_GU_tips_distance\":1, \"tHW_GU_C1'-B1-B1pair\":3, \"tHW_GU_B1-B1pair-C1'pair\":1, \"tHW_GU_C4'-C1'-B1-B1pair\":2, \"tHW_GU_B1-B1pair-C1'pair-C4'pair\":3, \"tHW_GU_alpha_1\":3, \"tHW_GU_alpha_2\":1, \"tHW_GU_dB1\":2, \"tHW_GU_dB2\":5, \n \"cWS_GU_tips_distance\":2, \"cWS_GU_C1'-B1-B1pair\":1, \"cWS_GU_B1-B1pair-C1'pair\":1, \"cWS_GU_C4'-C1'-B1-B1pair\":1, \"cWS_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cWS_GU_alpha_1\":3, \"cWS_GU_alpha_2\":3, \"cWS_GU_dB1\":2, \"cWS_GU_dB2\":3, \n \"tWS_GU_tips_distance\":4, \"tWS_GU_C1'-B1-B1pair\":3, \"tWS_GU_B1-B1pair-C1'pair\":1, \"tWS_GU_C4'-C1'-B1-B1pair\":3, \"tWS_GU_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_GU_alpha_1\":1, \"tWS_GU_alpha_2\":2, \"tWS_GU_dB1\":3, \"tWS_GU_dB2\":3, \n \"cSW_GU_tips_distance\":2, \"cSW_GU_C1'-B1-B1pair\":2, \"cSW_GU_B1-B1pair-C1'pair\":2, \"cSW_GU_C4'-C1'-B1-B1pair\":2, \"cSW_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_GU_alpha_1\":1, \"cSW_GU_alpha_2\":2, \"cSW_GU_dB1\":3, \"cSW_GU_dB2\":2, \n \"tSW_GU_tips_distance\":3, \"tSW_GU_C1'-B1-B1pair\":1, \"tSW_GU_B1-B1pair-C1'pair\":2, \"tSW_GU_C4'-C1'-B1-B1pair\":2, \"tSW_GU_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_GU_alpha_1\":1, \"tSW_GU_alpha_2\":2, \"tSW_GU_dB1\":5, \"tSW_GU_dB2\":1, \n \"cHH_GU_tips_distance\":5, \"cHH_GU_C1'-B1-B1pair\":2, \"cHH_GU_B1-B1pair-C1'pair\":3, \"cHH_GU_C4'-C1'-B1-B1pair\":2, \"cHH_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_GU_alpha_1\":2, \"cHH_GU_alpha_2\":2, \"cHH_GU_dB1\":5, \"cHH_GU_dB2\":3, \n \"tHH_GU_tips_distance\":5, \"tHH_GU_C1'-B1-B1pair\":2, \"tHH_GU_B1-B1pair-C1'pair\":1, \"tHH_GU_C4'-C1'-B1-B1pair\":1, \"tHH_GU_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_GU_alpha_1\":2, \"tHH_GU_alpha_2\":1, \"tHH_GU_dB1\":8, \"tHH_GU_dB2\":2, \n \"cSH_GU_tips_distance\":3, \"cSH_GU_C1'-B1-B1pair\":1, \"cSH_GU_B1-B1pair-C1'pair\":2, \"cSH_GU_C4'-C1'-B1-B1pair\":3, \"cSH_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_GU_alpha_1\":2, \"cSH_GU_alpha_2\":1, \"cSH_GU_dB1\":2, \"cSH_GU_dB2\":2, \n \"tSH_GU_tips_distance\":2, \"tSH_GU_C1'-B1-B1pair\":2, \"tSH_GU_B1-B1pair-C1'pair\":2, \"tSH_GU_C4'-C1'-B1-B1pair\":1, \"tSH_GU_B1-B1pair-C1'pair-C4'pair\":1, \"tSH_GU_alpha_1\":2, \"tSH_GU_alpha_2\":3, \"tSH_GU_dB1\":3, \"tSH_GU_dB2\":3, \n \"cHS_GU_tips_distance\":8, \"cHS_GU_C1'-B1-B1pair\":1, \"cHS_GU_B1-B1pair-C1'pair\":1, \"cHS_GU_C4'-C1'-B1-B1pair\":2, \"cHS_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_GU_alpha_1\":1, \"cHS_GU_alpha_2\":1, \"cHS_GU_dB1\":4, \"cHS_GU_dB2\":3, \n \"tHS_GU_tips_distance\":5, \"tHS_GU_C1'-B1-B1pair\":4, \"tHS_GU_B1-B1pair-C1'pair\":2, \"tHS_GU_C4'-C1'-B1-B1pair\":2, \"tHS_GU_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_GU_alpha_1\":2, \"tHS_GU_alpha_2\":1, \"tHS_GU_dB1\":1, \"tHS_GU_dB2\":3, \n \"cSS_GU_tips_distance\":2, \"cSS_GU_C1'-B1-B1pair\":3, \"cSS_GU_B1-B1pair-C1'pair\":2, \"cSS_GU_C4'-C1'-B1-B1pair\":2, \"cSS_GU_B1-B1pair-C1'pair-C4'pair\":2, \"cSS_GU_alpha_1\":2, \"cSS_GU_alpha_2\":1, \"cSS_GU_dB1\":3, \"cSS_GU_dB2\":4, \n \"tSS_GU_tips_distance\":5, \"tSS_GU_C1'-B1-B1pair\":2, \"tSS_GU_B1-B1pair-C1'pair\":2, \"tSS_GU_C4'-C1'-B1-B1pair\":1, \"tSS_GU_B1-B1pair-C1'pair-C4'pair\":3, \"tSS_GU_alpha_1\":2, \"tSS_GU_alpha_2\":2, \"tSS_GU_dB1\":2, \"tSS_GU_dB2\":6, \n \"cWW_UA_tips_distance\":4, \"cWW_UA_C1'-B1-B1pair\":2, \"cWW_UA_B1-B1pair-C1'pair\":2, \"cWW_UA_C4'-C1'-B1-B1pair\":1, \"cWW_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_UA_alpha_1\":2, \"cWW_UA_alpha_2\":2, \"cWW_UA_dB1\":2, \"cWW_UA_dB2\":7, \n \"tWW_UA_tips_distance\":2, \"tWW_UA_C1'-B1-B1pair\":1, \"tWW_UA_B1-B1pair-C1'pair\":2, \"tWW_UA_C4'-C1'-B1-B1pair\":2, \"tWW_UA_B1-B1pair-C1'pair-C4'pair\":1, \"tWW_UA_alpha_1\":2, \"tWW_UA_alpha_2\":1, \"tWW_UA_dB1\":6, \"tWW_UA_dB2\":1, \n \"cWH_UA_tips_distance\":3, \"cWH_UA_C1'-B1-B1pair\":3, \"cWH_UA_B1-B1pair-C1'pair\":3, \"cWH_UA_C4'-C1'-B1-B1pair\":3, \"cWH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_UA_alpha_1\":2, \"cWH_UA_alpha_2\":3, \"cWH_UA_dB1\":4, \"cWH_UA_dB2\":3, \n \"tWH_UA_tips_distance\":3, \"tWH_UA_C1'-B1-B1pair\":2, \"tWH_UA_B1-B1pair-C1'pair\":1, \"tWH_UA_C4'-C1'-B1-B1pair\":2, \"tWH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_UA_alpha_1\":1, \"tWH_UA_alpha_2\":2, \"tWH_UA_dB1\":3, \"tWH_UA_dB2\":2, \n \"cHW_UA_tips_distance\":5, \"cHW_UA_C1'-B1-B1pair\":1, \"cHW_UA_B1-B1pair-C1'pair\":1, \"cHW_UA_C4'-C1'-B1-B1pair\":3, \"cHW_UA_B1-B1pair-C1'pair-C4'pair\":1, \"cHW_UA_alpha_1\":1, \"cHW_UA_alpha_2\":1, \"cHW_UA_dB1\":3, \"cHW_UA_dB2\":1, \n \"tHW_UA_tips_distance\":7, \"tHW_UA_C1'-B1-B1pair\":3, \"tHW_UA_B1-B1pair-C1'pair\":2, \"tHW_UA_C4'-C1'-B1-B1pair\":1, \"tHW_UA_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_UA_alpha_1\":3, \"tHW_UA_alpha_2\":3, \"tHW_UA_dB1\":2, \"tHW_UA_dB2\":1, \n \"cWS_UA_tips_distance\":1, \"cWS_UA_C1'-B1-B1pair\":2, \"cWS_UA_B1-B1pair-C1'pair\":3, \"cWS_UA_C4'-C1'-B1-B1pair\":2, \"cWS_UA_B1-B1pair-C1'pair-C4'pair\":1, \"cWS_UA_alpha_1\":2, \"cWS_UA_alpha_2\":2, \"cWS_UA_dB1\":3, \"cWS_UA_dB2\":4, \n \"tWS_UA_tips_distance\":5, \"tWS_UA_C1'-B1-B1pair\":1, \"tWS_UA_B1-B1pair-C1'pair\":2, \"tWS_UA_C4'-C1'-B1-B1pair\":2, \"tWS_UA_B1-B1pair-C1'pair-C4'pair\":1, \"tWS_UA_alpha_1\":1, \"tWS_UA_alpha_2\":3, \"tWS_UA_dB1\":1, \"tWS_UA_dB2\":1, \n \"cSW_UA_tips_distance\":2, \"cSW_UA_C1'-B1-B1pair\":1, \"cSW_UA_B1-B1pair-C1'pair\":1, \"cSW_UA_C4'-C1'-B1-B1pair\":2, \"cSW_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_UA_alpha_1\":2, \"cSW_UA_alpha_2\":3, \"cSW_UA_dB1\":3, \"cSW_UA_dB2\":3, \n \"tSW_UA_tips_distance\":2, \"tSW_UA_C1'-B1-B1pair\":1, \"tSW_UA_B1-B1pair-C1'pair\":2, \"tSW_UA_C4'-C1'-B1-B1pair\":1, \"tSW_UA_B1-B1pair-C1'pair-C4'pair\":1, \"tSW_UA_alpha_1\":2, \"tSW_UA_alpha_2\":2, \"tSW_UA_dB1\":3, \"tSW_UA_dB2\":2, \n \"cHH_UA_tips_distance\":4, \"cHH_UA_C1'-B1-B1pair\":1, \"cHH_UA_B1-B1pair-C1'pair\":1, \"cHH_UA_C4'-C1'-B1-B1pair\":1, \"cHH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_UA_alpha_1\":2, \"cHH_UA_alpha_2\":2, \"cHH_UA_dB1\":5, \"cHH_UA_dB2\":2, \n \"tHH_UA_tips_distance\":4, \"tHH_UA_C1'-B1-B1pair\":2, \"tHH_UA_B1-B1pair-C1'pair\":2, \"tHH_UA_C4'-C1'-B1-B1pair\":2, \"tHH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"tHH_UA_alpha_1\":2, \"tHH_UA_alpha_2\":3, \"tHH_UA_dB1\":3, \"tHH_UA_dB2\":1, \n \"cSH_UA_tips_distance\":4, \"cSH_UA_C1'-B1-B1pair\":1, \"cSH_UA_B1-B1pair-C1'pair\":1, \"cSH_UA_C4'-C1'-B1-B1pair\":2, \"cSH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_UA_alpha_1\":2, \"cSH_UA_alpha_2\":2, \"cSH_UA_dB1\":3, \"cSH_UA_dB2\":2, \n \"tSH_UA_tips_distance\":2, \"tSH_UA_C1'-B1-B1pair\":2, \"tSH_UA_B1-B1pair-C1'pair\":2, \"tSH_UA_C4'-C1'-B1-B1pair\":3, \"tSH_UA_B1-B1pair-C1'pair-C4'pair\":2, \"tSH_UA_alpha_1\":3, \"tSH_UA_alpha_2\":2, \"tSH_UA_dB1\":4, \"tSH_UA_dB2\":1, \n \"cHS_UA_tips_distance\":5, \"cHS_UA_C1'-B1-B1pair\":2, \"cHS_UA_B1-B1pair-C1'pair\":2, \"cHS_UA_C4'-C1'-B1-B1pair\":2, \"cHS_UA_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_UA_alpha_1\":2, \"cHS_UA_alpha_2\":2, \"cHS_UA_dB1\":1, \"cHS_UA_dB2\":3, \n \"tHS_UA_tips_distance\":5, \"tHS_UA_C1'-B1-B1pair\":2, \"tHS_UA_B1-B1pair-C1'pair\":2, \"tHS_UA_C4'-C1'-B1-B1pair\":3, \"tHS_UA_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_UA_alpha_1\":3, \"tHS_UA_alpha_2\":3, \"tHS_UA_dB1\":2, \"tHS_UA_dB2\":7, \n \"cSS_UA_tips_distance\":2, \"cSS_UA_C1'-B1-B1pair\":2, \"cSS_UA_B1-B1pair-C1'pair\":2, \"cSS_UA_C4'-C1'-B1-B1pair\":2, \"cSS_UA_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_UA_alpha_1\":1, \"cSS_UA_alpha_2\":1, \"cSS_UA_dB1\":2, \"cSS_UA_dB2\":1, \n \"tSS_UA_tips_distance\":5, \"tSS_UA_C1'-B1-B1pair\":1, \"tSS_UA_B1-B1pair-C1'pair\":3, \"tSS_UA_C4'-C1'-B1-B1pair\":2, \"tSS_UA_B1-B1pair-C1'pair-C4'pair\":3, \"tSS_UA_alpha_1\":2, \"tSS_UA_alpha_2\":2, \"tSS_UA_dB1\":4, \"tSS_UA_dB2\":4, \n \"cWW_UC_tips_distance\":3, \"cWW_UC_C1'-B1-B1pair\":1, \"cWW_UC_B1-B1pair-C1'pair\":2, \"cWW_UC_C4'-C1'-B1-B1pair\":2, \"cWW_UC_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_UC_alpha_1\":2, \"cWW_UC_alpha_2\":1, \"cWW_UC_dB1\":1, \"cWW_UC_dB2\":2, \n \"tWW_UC_tips_distance\":4, \"tWW_UC_C1'-B1-B1pair\":2, \"tWW_UC_B1-B1pair-C1'pair\":2, \"tWW_UC_C4'-C1'-B1-B1pair\":2, \"tWW_UC_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_UC_alpha_1\":3, \"tWW_UC_alpha_2\":1, \"tWW_UC_dB1\":1, \"tWW_UC_dB2\":4, \n \"cWH_UC_tips_distance\":2, \"cWH_UC_C1'-B1-B1pair\":2, \"cWH_UC_B1-B1pair-C1'pair\":2, \"cWH_UC_C4'-C1'-B1-B1pair\":2, \"cWH_UC_B1-B1pair-C1'pair-C4'pair\":4, \"cWH_UC_alpha_1\":2, \"cWH_UC_alpha_2\":3, \"cWH_UC_dB1\":3, \"cWH_UC_dB2\":3, \n \"tWH_UC_tips_distance\":4, \"tWH_UC_C1'-B1-B1pair\":3, \"tWH_UC_B1-B1pair-C1'pair\":2, \"tWH_UC_C4'-C1'-B1-B1pair\":3, \"tWH_UC_B1-B1pair-C1'pair-C4'pair\":1, \"tWH_UC_alpha_1\":4, \"tWH_UC_alpha_2\":1, \"tWH_UC_dB1\":4, \"tWH_UC_dB2\":2, \n \"cHW_UC_tips_distance\":5, \"cHW_UC_C1'-B1-B1pair\":2, \"cHW_UC_B1-B1pair-C1'pair\":2, \"cHW_UC_C4'-C1'-B1-B1pair\":1, \"cHW_UC_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_UC_alpha_1\":2, \"cHW_UC_alpha_2\":2, \"cHW_UC_dB1\":2, \"cHW_UC_dB2\":6, \n \"tHW_UC_tips_distance\":2, \"tHW_UC_C1'-B1-B1pair\":2, \"tHW_UC_B1-B1pair-C1'pair\":2, \"tHW_UC_C4'-C1'-B1-B1pair\":3, \"tHW_UC_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_UC_alpha_1\":2, \"tHW_UC_alpha_2\":4, \"tHW_UC_dB1\":4, \"tHW_UC_dB2\":4, \n \"cWS_UC_tips_distance\":4, \"cWS_UC_C1'-B1-B1pair\":2, \"cWS_UC_B1-B1pair-C1'pair\":2, \"cWS_UC_C4'-C1'-B1-B1pair\":2, \"cWS_UC_B1-B1pair-C1'pair-C4'pair\":2, \"cWS_UC_alpha_1\":3, \"cWS_UC_alpha_2\":2, \"cWS_UC_dB1\":3, \"cWS_UC_dB2\":2, \n \"tWS_UC_tips_distance\":4, \"tWS_UC_C1'-B1-B1pair\":2, \"tWS_UC_B1-B1pair-C1'pair\":1, \"tWS_UC_C4'-C1'-B1-B1pair\":2, \"tWS_UC_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_UC_alpha_1\":2, \"tWS_UC_alpha_2\":1, \"tWS_UC_dB1\":3, \"tWS_UC_dB2\":2, \n \"cSW_UC_tips_distance\":4, \"cSW_UC_C1'-B1-B1pair\":1, \"cSW_UC_B1-B1pair-C1'pair\":2, \"cSW_UC_C4'-C1'-B1-B1pair\":2, \"cSW_UC_B1-B1pair-C1'pair-C4'pair\":2, \"cSW_UC_alpha_1\":2, \"cSW_UC_alpha_2\":3, \"cSW_UC_dB1\":3, \"cSW_UC_dB2\":6, \n \"tSW_UC_tips_distance\":5, \"tSW_UC_C1'-B1-B1pair\":1, \"tSW_UC_B1-B1pair-C1'pair\":2, \"tSW_UC_C4'-C1'-B1-B1pair\":3, \"tSW_UC_B1-B1pair-C1'pair-C4'pair\":1, \"tSW_UC_alpha_1\":2, \"tSW_UC_alpha_2\":2, \"tSW_UC_dB1\":2, \"tSW_UC_dB2\":1, \n \"cHH_UC_tips_distance\":5, \"cHH_UC_C1'-B1-B1pair\":2, \"cHH_UC_B1-B1pair-C1'pair\":1, \"cHH_UC_C4'-C1'-B1-B1pair\":2, \"cHH_UC_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_UC_alpha_1\":1, \"cHH_UC_alpha_2\":3, \"cHH_UC_dB1\":7, \"cHH_UC_dB2\":3, \n \"tHH_UC_tips_distance\":5, \"tHH_UC_C1'-B1-B1pair\":1, \"tHH_UC_B1-B1pair-C1'pair\":1, \"tHH_UC_C4'-C1'-B1-B1pair\":2, \"tHH_UC_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_UC_alpha_1\":2, \"tHH_UC_alpha_2\":2, \"tHH_UC_dB1\":8, \"tHH_UC_dB2\":8, \n \"cSH_UC_tips_distance\":5, \"cSH_UC_C1'-B1-B1pair\":2, \"cSH_UC_B1-B1pair-C1'pair\":2, \"cSH_UC_C4'-C1'-B1-B1pair\":2, \"cSH_UC_B1-B1pair-C1'pair-C4'pair\":1, \"cSH_UC_alpha_1\":2, \"cSH_UC_alpha_2\":3, \"cSH_UC_dB1\":5, \"cSH_UC_dB2\":3, \n \"tSH_UC_tips_distance\":2, \"tSH_UC_C1'-B1-B1pair\":1, \"tSH_UC_B1-B1pair-C1'pair\":1, \"tSH_UC_C4'-C1'-B1-B1pair\":2, \"tSH_UC_B1-B1pair-C1'pair-C4'pair\":1, \"tSH_UC_alpha_1\":2, \"tSH_UC_alpha_2\":2, \"tSH_UC_dB1\":2, \"tSH_UC_dB2\":7, \n \"cHS_UC_tips_distance\":5, \"cHS_UC_C1'-B1-B1pair\":2, \"cHS_UC_B1-B1pair-C1'pair\":2, \"cHS_UC_C4'-C1'-B1-B1pair\":1, \"cHS_UC_B1-B1pair-C1'pair-C4'pair\":3, \"cHS_UC_alpha_1\":3, \"cHS_UC_alpha_2\":2, \"cHS_UC_dB1\":6, \"cHS_UC_dB2\":7, \n \"tHS_UC_tips_distance\":5, \"tHS_UC_C1'-B1-B1pair\":3, \"tHS_UC_B1-B1pair-C1'pair\":2, \"tHS_UC_C4'-C1'-B1-B1pair\":2, \"tHS_UC_B1-B1pair-C1'pair-C4'pair\":3, \"tHS_UC_alpha_1\":3, \"tHS_UC_alpha_2\":1, \"tHS_UC_dB1\":5, \"tHS_UC_dB2\":7, \n \"cSS_UC_tips_distance\":5, \"cSS_UC_C1'-B1-B1pair\":2, \"cSS_UC_B1-B1pair-C1'pair\":1, \"cSS_UC_C4'-C1'-B1-B1pair\":3, \"cSS_UC_B1-B1pair-C1'pair-C4'pair\":1, \"cSS_UC_alpha_1\":3, \"cSS_UC_alpha_2\":3, \"cSS_UC_dB1\":8, \"cSS_UC_dB2\":5, \n \"tSS_UC_tips_distance\":5, \"tSS_UC_C1'-B1-B1pair\":2, \"tSS_UC_B1-B1pair-C1'pair\":1, \"tSS_UC_C4'-C1'-B1-B1pair\":3, \"tSS_UC_B1-B1pair-C1'pair-C4'pair\":3, \"tSS_UC_alpha_1\":3, \"tSS_UC_alpha_2\":1, \"tSS_UC_dB1\":8, \"tSS_UC_dB2\":7, \n \"cWW_UG_tips_distance\":3, \"cWW_UG_C1'-B1-B1pair\":2, \"cWW_UG_B1-B1pair-C1'pair\":3, \"cWW_UG_C4'-C1'-B1-B1pair\":2, \"cWW_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_UG_alpha_1\":2, \"cWW_UG_alpha_2\":3, \"cWW_UG_dB1\":4, \"cWW_UG_dB2\":3, \n \"tWW_UG_tips_distance\":2, \"tWW_UG_C1'-B1-B1pair\":1, \"tWW_UG_B1-B1pair-C1'pair\":1, \"tWW_UG_C4'-C1'-B1-B1pair\":2, \"tWW_UG_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_UG_alpha_1\":3, \"tWW_UG_alpha_2\":3, \"tWW_UG_dB1\":3, \"tWW_UG_dB2\":4, \n \"cWH_UG_tips_distance\":2, \"cWH_UG_C1'-B1-B1pair\":1, \"cWH_UG_B1-B1pair-C1'pair\":2, \"cWH_UG_C4'-C1'-B1-B1pair\":2, \"cWH_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cWH_UG_alpha_1\":2, \"cWH_UG_alpha_2\":2, \"cWH_UG_dB1\":2, \"cWH_UG_dB2\":2, \n \"tWH_UG_tips_distance\":1, \"tWH_UG_C1'-B1-B1pair\":2, \"tWH_UG_B1-B1pair-C1'pair\":2, \"tWH_UG_C4'-C1'-B1-B1pair\":2, \"tWH_UG_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_UG_alpha_1\":2, \"tWH_UG_alpha_2\":2, \"tWH_UG_dB1\":6, \"tWH_UG_dB2\":2, \n \"cHW_UG_tips_distance\":2, \"cHW_UG_C1'-B1-B1pair\":2, \"cHW_UG_B1-B1pair-C1'pair\":2, \"cHW_UG_C4'-C1'-B1-B1pair\":1, \"cHW_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cHW_UG_alpha_1\":1, \"cHW_UG_alpha_2\":2, \"cHW_UG_dB1\":4, \"cHW_UG_dB2\":4, \n \"tHW_UG_tips_distance\":1, \"tHW_UG_C1'-B1-B1pair\":2, \"tHW_UG_B1-B1pair-C1'pair\":1, \"tHW_UG_C4'-C1'-B1-B1pair\":2, \"tHW_UG_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_UG_alpha_1\":3, \"tHW_UG_alpha_2\":2, \"tHW_UG_dB1\":6, \"tHW_UG_dB2\":3, \n \"cWS_UG_tips_distance\":2, \"cWS_UG_C1'-B1-B1pair\":4, \"cWS_UG_B1-B1pair-C1'pair\":2, \"cWS_UG_C4'-C1'-B1-B1pair\":3, \"cWS_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cWS_UG_alpha_1\":2, \"cWS_UG_alpha_2\":2, \"cWS_UG_dB1\":2, \"cWS_UG_dB2\":2, \n \"tWS_UG_tips_distance\":5, \"tWS_UG_C1'-B1-B1pair\":2, \"tWS_UG_B1-B1pair-C1'pair\":2, \"tWS_UG_C4'-C1'-B1-B1pair\":2, \"tWS_UG_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_UG_alpha_1\":2, \"tWS_UG_alpha_2\":1, \"tWS_UG_dB1\":3, \"tWS_UG_dB2\":5, \n \"cSW_UG_tips_distance\":2, \"cSW_UG_C1'-B1-B1pair\":2, \"cSW_UG_B1-B1pair-C1'pair\":3, \"cSW_UG_C4'-C1'-B1-B1pair\":2, \"cSW_UG_B1-B1pair-C1'pair-C4'pair\":1, \"cSW_UG_alpha_1\":2, \"cSW_UG_alpha_2\":2, \"cSW_UG_dB1\":3, \"cSW_UG_dB2\":2, \n \"tSW_UG_tips_distance\":4, \"tSW_UG_C1'-B1-B1pair\":1, \"tSW_UG_B1-B1pair-C1'pair\":1, \"tSW_UG_C4'-C1'-B1-B1pair\":2, \"tSW_UG_B1-B1pair-C1'pair-C4'pair\":3, \"tSW_UG_alpha_1\":2, \"tSW_UG_alpha_2\":2, \"tSW_UG_dB1\":2, \"tSW_UG_dB2\":2, \n \"cHH_UG_tips_distance\":5, \"cHH_UG_C1'-B1-B1pair\":3, \"cHH_UG_B1-B1pair-C1'pair\":2, \"cHH_UG_C4'-C1'-B1-B1pair\":2, \"cHH_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_UG_alpha_1\":2, \"cHH_UG_alpha_2\":3, \"cHH_UG_dB1\":4, \"cHH_UG_dB2\":5, \n \"tHH_UG_tips_distance\":5, \"tHH_UG_C1'-B1-B1pair\":2, \"tHH_UG_B1-B1pair-C1'pair\":2, \"tHH_UG_C4'-C1'-B1-B1pair\":2, \"tHH_UG_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_UG_alpha_1\":3, \"tHH_UG_alpha_2\":2, \"tHH_UG_dB1\":3, \"tHH_UG_dB2\":2, \n \"cSH_UG_tips_distance\":5, \"cSH_UG_C1'-B1-B1pair\":1, \"cSH_UG_B1-B1pair-C1'pair\":2, \"cSH_UG_C4'-C1'-B1-B1pair\":2, \"cSH_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_UG_alpha_1\":2, \"cSH_UG_alpha_2\":2, \"cSH_UG_dB1\":3, \"cSH_UG_dB2\":4, \n \"tSH_UG_tips_distance\":5, \"tSH_UG_C1'-B1-B1pair\":2, \"tSH_UG_B1-B1pair-C1'pair\":1, \"tSH_UG_C4'-C1'-B1-B1pair\":2, \"tSH_UG_B1-B1pair-C1'pair-C4'pair\":1, \"tSH_UG_alpha_1\":3, \"tSH_UG_alpha_2\":1, \"tSH_UG_dB1\":2, \"tSH_UG_dB2\":2, \n \"cHS_UG_tips_distance\":3, \"cHS_UG_C1'-B1-B1pair\":2, \"cHS_UG_B1-B1pair-C1'pair\":3, \"cHS_UG_C4'-C1'-B1-B1pair\":2, \"cHS_UG_B1-B1pair-C1'pair-C4'pair\":4, \"cHS_UG_alpha_1\":2, \"cHS_UG_alpha_2\":3, \"cHS_UG_dB1\":3, \"cHS_UG_dB2\":4, \n \"tHS_UG_tips_distance\":7, \"tHS_UG_C1'-B1-B1pair\":1, \"tHS_UG_B1-B1pair-C1'pair\":3, \"tHS_UG_C4'-C1'-B1-B1pair\":2, \"tHS_UG_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_UG_alpha_1\":2, \"tHS_UG_alpha_2\":3, \"tHS_UG_dB1\":2, \"tHS_UG_dB2\":1, \n \"cSS_UG_tips_distance\":2, \"cSS_UG_C1'-B1-B1pair\":2, \"cSS_UG_B1-B1pair-C1'pair\":2, \"cSS_UG_C4'-C1'-B1-B1pair\":2, \"cSS_UG_B1-B1pair-C1'pair-C4'pair\":2, \"cSS_UG_alpha_1\":1, \"cSS_UG_alpha_2\":2, \"cSS_UG_dB1\":2, \"cSS_UG_dB2\":3, \n \"tSS_UG_tips_distance\":5, \"tSS_UG_C1'-B1-B1pair\":2, \"tSS_UG_B1-B1pair-C1'pair\":2, \"tSS_UG_C4'-C1'-B1-B1pair\":1, \"tSS_UG_B1-B1pair-C1'pair-C4'pair\":2, \"tSS_UG_alpha_1\":2, \"tSS_UG_alpha_2\":2, \"tSS_UG_dB1\":3, \"tSS_UG_dB2\":4, \n \"cWW_UU_tips_distance\":1, \"cWW_UU_C1'-B1-B1pair\":2, \"cWW_UU_B1-B1pair-C1'pair\":3, \"cWW_UU_C4'-C1'-B1-B1pair\":3, \"cWW_UU_B1-B1pair-C1'pair-C4'pair\":2, \"cWW_UU_alpha_1\":2, \"cWW_UU_alpha_2\":2, \"cWW_UU_dB1\":2, \"cWW_UU_dB2\":1, \n \"tWW_UU_tips_distance\":3, \"tWW_UU_C1'-B1-B1pair\":2, \"tWW_UU_B1-B1pair-C1'pair\":2, \"tWW_UU_C4'-C1'-B1-B1pair\":2, \"tWW_UU_B1-B1pair-C1'pair-C4'pair\":2, \"tWW_UU_alpha_1\":2, \"tWW_UU_alpha_2\":2, \"tWW_UU_dB1\":4, \"tWW_UU_dB2\":5, \n \"cWH_UU_tips_distance\":2, \"cWH_UU_C1'-B1-B1pair\":2, \"cWH_UU_B1-B1pair-C1'pair\":2, \"cWH_UU_C4'-C1'-B1-B1pair\":3, \"cWH_UU_B1-B1pair-C1'pair-C4'pair\":3, \"cWH_UU_alpha_1\":2, \"cWH_UU_alpha_2\":3, \"cWH_UU_dB1\":3, \"cWH_UU_dB2\":5, \n \"tWH_UU_tips_distance\":3, \"tWH_UU_C1'-B1-B1pair\":2, \"tWH_UU_B1-B1pair-C1'pair\":2, \"tWH_UU_C4'-C1'-B1-B1pair\":2, \"tWH_UU_B1-B1pair-C1'pair-C4'pair\":2, \"tWH_UU_alpha_1\":3, \"tWH_UU_alpha_2\":3, \"tWH_UU_dB1\":2, \"tWH_UU_dB2\":2, \n \"cHW_UU_tips_distance\":1, \"cHW_UU_C1'-B1-B1pair\":2, \"cHW_UU_B1-B1pair-C1'pair\":3, \"cHW_UU_C4'-C1'-B1-B1pair\":1, \"cHW_UU_B1-B1pair-C1'pair-C4'pair\":3, \"cHW_UU_alpha_1\":2, \"cHW_UU_alpha_2\":2, \"cHW_UU_dB1\":3, \"cHW_UU_dB2\":4, \n \"tHW_UU_tips_distance\":3, \"tHW_UU_C1'-B1-B1pair\":3, \"tHW_UU_B1-B1pair-C1'pair\":2, \"tHW_UU_C4'-C1'-B1-B1pair\":2, \"tHW_UU_B1-B1pair-C1'pair-C4'pair\":2, \"tHW_UU_alpha_1\":2, \"tHW_UU_alpha_2\":3, \"tHW_UU_dB1\":2, \"tHW_UU_dB2\":2, \n \"cWS_UU_tips_distance\":5, \"cWS_UU_C1'-B1-B1pair\":1, \"cWS_UU_B1-B1pair-C1'pair\":1, \"cWS_UU_C4'-C1'-B1-B1pair\":2, \"cWS_UU_B1-B1pair-C1'pair-C4'pair\":3, \"cWS_UU_alpha_1\":2, \"cWS_UU_alpha_2\":1, \"cWS_UU_dB1\":2, \"cWS_UU_dB2\":1, \n \"tWS_UU_tips_distance\":3, \"tWS_UU_C1'-B1-B1pair\":2, \"tWS_UU_B1-B1pair-C1'pair\":2, \"tWS_UU_C4'-C1'-B1-B1pair\":3, \"tWS_UU_B1-B1pair-C1'pair-C4'pair\":2, \"tWS_UU_alpha_1\":2, \"tWS_UU_alpha_2\":2, \"tWS_UU_dB1\":3, \"tWS_UU_dB2\":3, \n \"cSW_UU_tips_distance\":5, \"cSW_UU_C1'-B1-B1pair\":1, \"cSW_UU_B1-B1pair-C1'pair\":3, \"cSW_UU_C4'-C1'-B1-B1pair\":2, \"cSW_UU_B1-B1pair-C1'pair-C4'pair\":3, \"cSW_UU_alpha_1\":2, \"cSW_UU_alpha_2\":3, \"cSW_UU_dB1\":1, \"cSW_UU_dB2\":4, \n \"tSW_UU_tips_distance\":6, \"tSW_UU_C1'-B1-B1pair\":3, \"tSW_UU_B1-B1pair-C1'pair\":1, \"tSW_UU_C4'-C1'-B1-B1pair\":2, \"tSW_UU_B1-B1pair-C1'pair-C4'pair\":2, \"tSW_UU_alpha_1\":1, \"tSW_UU_alpha_2\":2, \"tSW_UU_dB1\":3, \"tSW_UU_dB2\":3, \n \"cHH_UU_tips_distance\":5, \"cHH_UU_C1'-B1-B1pair\":1, \"cHH_UU_B1-B1pair-C1'pair\":1, \"cHH_UU_C4'-C1'-B1-B1pair\":3, \"cHH_UU_B1-B1pair-C1'pair-C4'pair\":2, \"cHH_UU_alpha_1\":2, \"cHH_UU_alpha_2\":2, \"cHH_UU_dB1\":1, \"cHH_UU_dB2\":5, \n \"tHH_UU_tips_distance\":5, \"tHH_UU_C1'-B1-B1pair\":2, \"tHH_UU_B1-B1pair-C1'pair\":3, \"tHH_UU_C4'-C1'-B1-B1pair\":1, \"tHH_UU_B1-B1pair-C1'pair-C4'pair\":3, \"tHH_UU_alpha_1\":2, \"tHH_UU_alpha_2\":4, \"tHH_UU_dB1\":4, \"tHH_UU_dB2\":5, \n \"cSH_UU_tips_distance\":5, \"cSH_UU_C1'-B1-B1pair\":1, \"cSH_UU_B1-B1pair-C1'pair\":3, \"cSH_UU_C4'-C1'-B1-B1pair\":2, \"cSH_UU_B1-B1pair-C1'pair-C4'pair\":2, \"cSH_UU_alpha_1\":3, \"cSH_UU_alpha_2\":2, \"cSH_UU_dB1\":2, \"cSH_UU_dB2\":5, \n \"tSH_UU_tips_distance\":5, \"tSH_UU_C1'-B1-B1pair\":2, \"tSH_UU_B1-B1pair-C1'pair\":1, \"tSH_UU_C4'-C1'-B1-B1pair\":3, \"tSH_UU_B1-B1pair-C1'pair-C4'pair\":3, \"tSH_UU_alpha_1\":1, \"tSH_UU_alpha_2\":1, \"tSH_UU_dB1\":1, \"tSH_UU_dB2\":5, \n \"cHS_UU_tips_distance\":7, \"cHS_UU_C1'-B1-B1pair\":2, \"cHS_UU_B1-B1pair-C1'pair\":2, \"cHS_UU_C4'-C1'-B1-B1pair\":2, \"cHS_UU_B1-B1pair-C1'pair-C4'pair\":2, \"cHS_UU_alpha_1\":2, \"cHS_UU_alpha_2\":2, \"cHS_UU_dB1\":3, \"cHS_UU_dB2\":2, \n \"tHS_UU_tips_distance\":5, \"tHS_UU_C1'-B1-B1pair\":1, \"tHS_UU_B1-B1pair-C1'pair\":2, \"tHS_UU_C4'-C1'-B1-B1pair\":2, \"tHS_UU_B1-B1pair-C1'pair-C4'pair\":1, \"tHS_UU_alpha_1\":1, \"tHS_UU_alpha_2\":2, \"tHS_UU_dB1\":4, \"tHS_UU_dB2\":1, \n \"cSS_UU_tips_distance\":5, \"cSS_UU_C1'-B1-B1pair\":2, \"cSS_UU_B1-B1pair-C1'pair\":2, \"cSS_UU_C4'-C1'-B1-B1pair\":2, \"cSS_UU_B1-B1pair-C1'pair-C4'pair\":3, \"cSS_UU_alpha_1\":2, \"cSS_UU_alpha_2\":2, \"cSS_UU_dB1\":6, \"cSS_UU_dB2\":4, \n \"tSS_UU_tips_distance\":8, \"tSS_UU_C1'-B1-B1pair\":1, \"tSS_UU_B1-B1pair-C1'pair\":1, \"tSS_UU_C4'-C1'-B1-B1pair\":2, \"tSS_UU_B1-B1pair-C1'pair-C4'pair\":1, \"tSS_UU_alpha_1\":1, \"tSS_UU_alpha_2\":2, \"tSS_UU_dB1\":3, \"tSS_UU_dB2\":4, \n} \n\n@trace_unhandled_exceptions\ndef retrieve_angles(db, res): \n \"\"\"\n Retrieve torsion angles from RNANet.db and convert them to degrees\n \"\"\"\n\n # Retrieve angle values\n with sqlite3.connect(runDir + \"/results/RNANet.db\") as conn:\n conn.execute('pragma journal_mode=wal')\n df = pd.read_sql(f\"\"\"SELECT chain_id, nt_name, alpha, beta, gamma, delta, epsilon, zeta, chi \n FROM (\n SELECT chain_id FROM chain JOIN structure ON chain.structure_id = structure.pdb_id\n WHERE chain.rfam_acc = 'unmappd' AND structure.resolution <= {res} AND issue = 0\n ) AS c NATURAL JOIN nucleotide\n WHERE nt_name='A' OR nt_name='C' OR nt_name='G' OR nt_name='U';\"\"\", conn)\n\n # convert to degrees\n j = (180.0/np.pi)\n torsions = df.iloc[:, 0:2].merge(\n df.iloc[:, 2:9].applymap(lambda x: j*x if x <= np.pi else j*x-360.0, na_action='ignore'), \n left_index=True, right_index=True\n )\n return torsions\n\ndef retrieve_eta_theta(db, res):\n \"\"\"\n Retrieve pseudotorsions from RNANet.db and convert them to degrees\n \"\"\"\n # Retrieve angle values\n with sqlite3.connect(runDir + \"/results/RNANet.db\") as conn:\n conn.execute('pragma journal_mode=wal')\n df = pd.read_sql(f\"\"\"SELECT chain_id, nt_name, eta, theta, eta_prime, theta_prime, eta_base, theta_base \n FROM (\n SELECT chain_id FROM chain JOIN structure ON chain.structure_id = structure.pdb_id\n WHERE chain.rfam_acc = 'unmappd' AND structure.resolution <= {res} AND issue = 0\n ) AS c NATURAL JOIN nucleotide\n WHERE nt_name='A' OR nt_name='C' OR nt_name='G' OR nt_name='U';\"\"\", conn)\n\n # convert to degrees\n j = (180.0/np.pi)\n pseudotorsions = df.iloc[:, 0:2].merge(\n df.iloc[:, 2:8].applymap(lambda x: j*x if x <= np.pi else j*x-360.0, na_action='ignore'), \n left_index=True, right_index=True\n )\n return pseudotorsions\n\ndef get_euclidian_distance(L1, L2):\n \"\"\"\n Returns the distance between two points (coordinates in lists)\n \"\"\"\n\n if len(L1)*len(L2) == 0:\n return np.nan\n \n if len(L1) == 1:\n L1 = L1[0]\n if len(L2) == 1:\n L2 = L2[0]\n\n e = 0\n for i in range(len(L1)):\n try:\n e += float(L1[i] - L2[i])**2\n except TypeError:\n print(\"Terms: \", L1, L2)\n except IndexError:\n print(\"Terms: \", L1, L2)\n\n return np.sqrt(e)\n\ndef get_flat_angle(L1, L2, L3):\n \"\"\"\n Returns the flat angles (in radians) defined by 3 points.\n L1, L2, L3 : lists of (x,y,z) coordinates\n Returns NaN if one of the lists is empty.\n \"\"\"\n\n if len(L1)*len(L2)*len(L3) == 0:\n return np.nan\n\n return calc_angle(Vector(L1[0]), Vector(L2[0]), Vector(L3[0]))*(180/np.pi)\n\ndef get_torsion_angle(L1, L2, L3, L4):\n if len(L1)*len(L2)*len(L3)*len(L4) == 0:\n return np.nan\n \n return calc_dihedral(Vector(L1[0]), Vector(L2[0]), Vector(L3[0]), Vector(L4[0]))*(180/np.pi)\n\ndef pos_b1(res):\n \"\"\"\n Returns the coordinates of virtual atom B1 (center of the first aromatic cycle)\n \"\"\"\n coordb1=[]\n somme_x_b1=0\n somme_y_b1=0\n somme_z_b1=0\n moy_x_b1=0\n moy_y_b1=0\n moy_z_b1=0\n #different cases\n #some residues have 2 aromatic cycles \n if res.get_resname() in ['A', 'G', '2MG', '7MG', 'MA6', '6IA', 'OMG' , '2MA', 'B9B', 'A2M', '1MA', 'E7G', 'P7G', 'B8W', 'B8K', 'BGH', '6MZ', 'E6G', 'MHG', 'M7A', 'M2G', 'P5P', 'G7M', '1MG', 'T6A', 'MIA', 'YG', 'YYG', 'I', 'DG', 'N79', '574', 'DJF', 'AET', '12A', 'ANZ', 'UY4'] : \n c=0\n names=[]\n for atom in res : \n if (atom.get_fullname() in ['N9', 'C8', 'N7', 'C4', 'C5']) :\n c=c+1\n names.append(atom.get_name())\n coord=atom.get_vector()\n somme_x_b1=somme_x_b1+coord[0]\n somme_y_b1=somme_y_b1+coord[1]\n somme_z_b1=somme_z_b1+coord[2]\n else : \n c=c\n #calcul coord B1\n if c != 0 :\n moy_x_b1=somme_x_b1/c\n moy_y_b1=somme_y_b1/c\n moy_z_b1=somme_z_b1/c\n coordb1.append(moy_x_b1)\n coordb1.append(moy_y_b1)\n coordb1.append(moy_z_b1)\n #others have only one cycle\n if res.get_resname() in ['C', 'U', 'AG9', '70U', '1RN', 'RSP', '3AU', 'CM0', 'U8U', 'IU', 'E3C', '4SU', '5HM', 'LV2', 'LHH', '4AC', 'CH', 'Y5P', '2MU', '4OC', 'B8T', 'JMH', 'JMC', 'DC', 'B9H', 'UR3', 'I4U', 'B8Q', 'P4U', 'OMU', 'OMC', '5MU', 'H2U', 'CBV', 'M1Y', 'B8N', '3TD', 'B8H'] :\n c=0\n for atom in res :\n if (atom.get_fullname() in ['C6', 'N3', 'N1', 'C2', 'C4', 'C5']):\n c=c+1\n coord=atom.get_vector()\n somme_x_b1=somme_x_b1+coord[0]\n somme_y_b1=somme_y_b1+coord[1]\n somme_z_b1=somme_z_b1+coord[2]\n #calcul coord B1\n if c != 0 :\n moy_x_b1=somme_x_b1/c\n moy_y_b1=somme_y_b1/c\n moy_z_b1=somme_z_b1/c\n coordb1.append(moy_x_b1)\n coordb1.append(moy_y_b1)\n coordb1.append(moy_z_b1)\n\n if len(coordb1):\n return [coordb1]\n else:\n return []\n\ndef pos_b2(res):\n \"\"\"\n Returns the coordinates of virtual atom B2 (center of the second aromatic cycle, if exists)\n \"\"\"\n coordb2=[]\n somme_x_b2=0\n somme_y_b2=0\n somme_z_b2=0\n moy_x_b2=0\n moy_y_b2=0\n moy_z_b2=0\n\n if res.get_resname() in ['A', 'G', '2MG', '7MG', 'MA6', '6IA', 'OMG' , '2MA', 'B9B', 'A2M', '1MA', 'E7G', 'P7G', 'B8W', 'B8K', 'BGH', '6MZ', 'E6G', 'MHG', 'M7A', 'M2G', 'P5P', 'G7M', '1MG', 'T6A', 'MIA', 'YG', 'YYG', 'I', 'DG', 'N79', '574', 'DJF', 'AET', '12A', 'ANZ', 'UY4'] : #2 cycles aromatiques\n c=0\n for atom in res :\n if atom.get_fullname() in ['C6', 'N3', 'N1', 'C2', 'C4', 'C5'] :\n c=c+1\n coord=atom.get_vector()\n somme_x_b2=somme_x_b2+coord[0]\n somme_y_b2=somme_y_b2+coord[1]\n somme_z_b2=somme_z_b2+coord[2]\n #calcul coord B2\n if c!=0 :\n moy_x_b2=somme_x_b2/c\n moy_y_b2=somme_y_b2/c\n moy_z_b2=somme_z_b2/c\n coordb2.append(moy_x_b2)\n coordb2.append(moy_y_b2)\n coordb2.append(moy_z_b2)\n if len(coordb2):\n return [coordb2]\n else:\n return []\n\n@trace_unhandled_exceptions\ndef measures_aa(name, s, thr_idx):\n \"\"\"\n Measures the distance between atoms linked by covalent bonds\n \"\"\"\n\n # do not recompute something already computed\n if os.path.isfile(runDir + \"/results/geometry/all-atoms/distances/dist_atoms_\" + name + \".csv\"):\n return\n \n last_o3p = [] # o3 'of the previous nucleotide linked to the P of the current nucleotide\n l_common = []\n l_purines = []\n l_pyrimidines = []\n setproctitle(f\"RNANet statistics.py Worker {thr_idx+1} measure_aa_dists({name})\")\n\n chain = next(s[0].get_chains()) # 1 chain per file\n residues = list(chain.get_residues())\n pbar = tqdm(total=len(residues), position=thr_idx+1, desc=f\"Worker {thr_idx+1}: {name} measure_aa_dists\", unit=\"res\", leave=False)\n pbar.update(0)\n for res in chain :\n \n # for residues A, G, C, U\n op3_p = []\n p_op1 = []\n p_op2 = []\n p_o5p = []\n o5p_c5p = []\n c5p_c4p = []\n c4p_o4p = []\n o4p_c1p = []\n c1p_c2p = []\n c2p_o2p = []\n c2p_c3p = []\n c3p_o3p = []\n c4p_c3p = []\n \n # if res = A or G\n c1p_n9 = None\n n9_c8 = None\n c8_n7 = None\n n7_c5 = None\n c5_c6 = None\n c6_n1 = None\n n1_c2 = None\n c2_n3 = None\n n3_c4 = None\n c4_n9 = None\n c4_c5 = None\n # if res = G\n c6_o6 = None\n c2_n2 = None\n # if res = A\n c6_n6 = None\n # if res = C or U\n c1p_n1 = None\n n1_c6 = None\n c6_c5 = None\n c5_c4 = None\n c4_n3 = None\n n3_c2 = None\n c2_n1 = None\n c2_o2 = None\n # if res = C\n c4_n4 = None\n # if res = U\n c4_o4 = None\n last_o3p_p = None\n\n\n if res.get_resname()=='A' or res.get_resname()=='G' or res.get_resname()=='C' or res.get_resname()=='U' :\n\n # get the coordinates of the atoms\n atom_p = [ atom.get_coord() for atom in res if atom.get_name() == \"P\"]\n atom_op3 = [ atom.get_coord() for atom in res if \"OP3\" in atom.get_fullname() ] # OP3 belongs to previous nucleotide !\n atom_op1 = [ atom.get_coord() for atom in res if \"OP1\" in atom.get_fullname() ]\n atom_op2 = [ atom.get_coord() for atom in res if \"OP2\" in atom.get_fullname() ]\n atom_o5p= [ atom.get_coord() for atom in res if \"O5'\" in atom.get_fullname() ]\n atom_c5p = [ atom.get_coord() for atom in res if \"C5'\" in atom.get_fullname() ]\n atom_c4p = [ atom.get_coord() for atom in res if \"C4'\" in atom.get_fullname() ]\n atom_o4p = [ atom.get_coord() for atom in res if \"O4'\" in atom.get_fullname() ]\n atom_c3p = [ atom.get_coord() for atom in res if \"C3'\" in atom.get_fullname() ]\n atom_o3p = [ atom.get_coord() for atom in res if \"O3'\" in atom.get_fullname() ]\n atom_c2p = [ atom.get_coord() for atom in res if \"C2'\" in atom.get_fullname() ]\n atom_o2p = [ atom.get_coord() for atom in res if \"O2'\" in atom.get_fullname() ]\n atom_c1p = [ atom.get_coord() for atom in res if \"C1'\" in atom.get_fullname() ]\n atom_n9 = [ atom.get_coord() for atom in res if \"N9\" in atom.get_fullname() ]\n atom_c8 = [ atom.get_coord() for atom in res if \"C8\" in atom.get_fullname() ]\n atom_n7 = [ atom.get_coord() for atom in res if \"N7\" in atom.get_fullname() ]\n atom_c5 = [ atom.get_coord() for atom in res if atom.get_name() == \"C5\"]\n atom_c6 = [ atom.get_coord() for atom in res if \"C6\" in atom.get_fullname() ]\n atom_o6 = [ atom.get_coord() for atom in res if \"O6\" in atom.get_fullname() ]\n atom_n6 = [ atom.get_coord() for atom in res if \"N6\" in atom.get_fullname() ]\n atom_n1 = [ atom.get_coord() for atom in res if \"N1\" in atom.get_fullname() ]\n atom_c2 = [ atom.get_coord() for atom in res if atom.get_name() == \"C2\"]\n atom_n2 = [ atom.get_coord() for atom in res if \"N2\" in atom.get_fullname() ]\n atom_o2 = [ atom.get_coord() for atom in res if atom.get_name() == \"O2\"]\n atom_n3 = [ atom.get_coord() for atom in res if \"N3\" in atom.get_fullname() ]\n atom_c4 = [ atom.get_coord() for atom in res if atom.get_name() == \"C4\" ]\n atom_n4 = [ atom.get_coord() for atom in res if \"N4\" in atom.get_fullname() ]\n atom_o4 = [ atom.get_coord() for atom in res if atom.get_name() == \"O4\"]\n \n if len(atom_op3):\n last_o3p_p = get_euclidian_distance(atom_op3, atom_p) # This nucleotide has an OP3 atom (likely the begining of a chain)\n else:\n last_o3p_p = get_euclidian_distance(last_o3p, atom_p) # link with the previous nucleotide\n p_op1 = get_euclidian_distance(atom_op1, atom_p)\n p_op2 = get_euclidian_distance(atom_op2, atom_p)\n p_o5p = get_euclidian_distance(atom_o5p, atom_p)\n o5p_c5p = get_euclidian_distance(atom_o5p, atom_c5p)\n c5p_c4p = get_euclidian_distance(atom_c5p, atom_c4p)\n c4p_o4p = get_euclidian_distance(atom_c4p, atom_o4p)\n c4p_c3p = get_euclidian_distance(atom_c4p, atom_c3p)\n o4p_c1p = get_euclidian_distance(atom_o4p, atom_c1p)\n c1p_c2p = get_euclidian_distance(atom_c1p, atom_c2p)\n c2p_o2p = get_euclidian_distance(atom_c2p, atom_o2p)\n c2p_c3p = get_euclidian_distance(atom_c2p, atom_c3p)\n c3p_o3p = get_euclidian_distance(atom_c3p, atom_o3p)\n\n last_o3p = atom_o3p # o3' of this residue becomes the previous o3' of the following\n \n # different cases for the aromatic cycles\n if res.get_resname()=='A' or res.get_resname()=='G': \n # compute the distances between atoms of aromatic cycles\n c1p_n9 = get_euclidian_distance(atom_c1p, atom_n9)\n n9_c8 = get_euclidian_distance(atom_n9, atom_c8)\n c8_n7 = get_euclidian_distance(atom_c8, atom_n7)\n n7_c5 = get_euclidian_distance(atom_n7, atom_c5)\n c5_c6 = get_euclidian_distance(atom_c5, atom_c6)\n c6_o6 = get_euclidian_distance(atom_c6, atom_o6)\n c6_n6 = get_euclidian_distance(atom_c6, atom_n6)\n c6_n1 = get_euclidian_distance(atom_c6, atom_n1)\n n1_c2 = get_euclidian_distance(atom_n1, atom_c2)\n c2_n2 = get_euclidian_distance(atom_c2, atom_n2)\n c2_n3 = get_euclidian_distance(atom_c2, atom_n3)\n n3_c4 = get_euclidian_distance(atom_n3, atom_c4)\n c4_n9 = get_euclidian_distance(atom_c4, atom_n9)\n c4_c5 = get_euclidian_distance(atom_c4, atom_c5)\n if res.get_resname()=='C' or res.get_resname()=='U' :\n c1p_n1 = get_euclidian_distance(atom_c1p, atom_n1)\n n1_c6 = get_euclidian_distance(atom_n1, atom_c6)\n c6_c5 = get_euclidian_distance(atom_c6, atom_c5)\n c5_c4 = get_euclidian_distance(atom_c5, atom_c4)\n c4_n3 = get_euclidian_distance(atom_c4, atom_n3)\n n3_c2 = get_euclidian_distance(atom_n3, atom_c2)\n c2_o2 = get_euclidian_distance(atom_c2, atom_o2)\n c2_n1 = get_euclidian_distance(atom_c2, atom_n1)\n c4_n4 = get_euclidian_distance(atom_c4, atom_n4)\n c4_o4 = get_euclidian_distance(atom_c4, atom_o4)\n\n l_common.append([res.get_resname(), last_o3p_p, p_op1, p_op2, p_o5p, o5p_c5p, c5p_c4p, c4p_o4p, c4p_c3p, o4p_c1p, c1p_c2p, c2p_o2p, c2p_c3p, c3p_o3p] )\n l_purines.append([c1p_n9, n9_c8, c8_n7, n7_c5, c5_c6, c6_o6, c6_n6, c6_n1, n1_c2, c2_n2, c2_n3, n3_c4, c4_n9, c4_c5])\n l_pyrimidines.append([c1p_n1, n1_c6, c6_c5, c5_c4, c4_n3, n3_c2, c2_o2, c2_n1, c4_n4, c4_o4])\n pbar.update(1)\n\n df_comm = pd.DataFrame(l_common, columns=[\"Residue\", \"O3'-P\", \"P-OP1\", \"P-OP2\", \"P-O5'\", \"O5'-C5'\", \"C5'-C4'\", \"C4'-O4'\", \"C4'-C3'\", \"O4'-C1'\", \"C1'-C2'\", \"C2'-O2'\", \"C2'-C3'\", \"C3'-O3'\"])\n df_pur = pd.DataFrame(l_purines, columns=[\"C1'-N9\", \"N9-C8\", \"C8-N7\", \"N7-C5\", \"C5-C6\", \"C6-O6\", \"C6-N6\", \"C6-N1\", \"N1-C2\", \"C2-N2\", \"C2-N3\", \"N3-C4\", \"C4-N9\", \"C4-C5\" ])\n df_pyr = pd.DataFrame(l_pyrimidines, columns=[\"C1'-N1\", \"N1-C6\", \"C6-C5\", \"C5-C4\", \"C4-N3\", \"N3-C2\", \"C2-O2\", \"C2-N1\", \"C4-N4\", \"C4-O4\"])\n df = pd.concat([df_comm, df_pur, df_pyr], axis = 1)\n pbar.close()\n \n df.to_csv(runDir + \"/results/geometry/all-atoms/distances/dist_atoms_\" + name + \".csv\")\n\n@trace_unhandled_exceptions\ndef measures_pyle(name, s, thr_idx):\n \"\"\"\n Measures the distances and plane angles involving C1' and P atoms \n Saves the results in a dataframe\n \"\"\"\n\n # do not recompute something already computed\n if (os.path.isfile(runDir + '/results/geometry/Pyle/angles/flat_angles_pyle_' + name + '.csv') and\n os.path.isfile(runDir + \"/results/geometry/Pyle/distances/distances_pyle_\" + name + \".csv\")):\n return\n\n l_dist = []\n l_angl = []\n last_p = []\n last_c1p = []\n last_c4p = []\n\n setproctitle(f\"RNANet statistics.py Worker {thr_idx+1} measures_pyle({name})\")\n\n chain = next(s[0].get_chains())\n for res in tqdm(chain, position=thr_idx+1, desc=f\"Worker {thr_idx+1}: {name} measures_pyle\", unit=\"res\", leave=False):\n p_c1p_psuiv = np.nan\n c1p_psuiv_c1psuiv = np.nan\n if res.get_resname() not in ['ATP', 'CCC', 'A3P', 'A23', 'GDP', 'RIA', \"2BA\"] :\n atom_p = [ atom.get_coord() for atom in res if atom.get_name() == \"P\"]\n atom_c1p = [ atom.get_coord() for atom in res if \"C1'\" in atom.get_fullname() ]\n atom_c4p = [ atom.get_coord() for atom in res if \"C4'\" in atom.get_fullname() ]\n if len(atom_c1p) > 1:\n for atom in res:\n if \"C1'\" in atom.get_fullname():\n print(\"\\n\", atom.get_fullname(), \"-\", res.get_resname(), \"\\n\")\n\n p_c1p_psuiv = get_flat_angle(last_p, last_c1p, atom_p)\n c1p_psuiv_c1psuiv = get_flat_angle(last_c1p, atom_p, atom_c1p)\n c1p_psuiv = get_euclidian_distance(last_c1p, atom_p)\n p_c1p = get_euclidian_distance(atom_p, atom_c1p)\n c4p_psuiv = get_euclidian_distance(last_c4p, atom_p)\n p_c4p = get_euclidian_distance(atom_p, atom_c4p)\n\n last_p = atom_p\n last_c1p = atom_c1p\n last_c4p = atom_c4p\n\n l_dist.append([res.get_resname(), c1p_psuiv, p_c1p, c4p_psuiv, p_c4p])\n l_angl.append([res.get_resname(), p_c1p_psuiv, c1p_psuiv_c1psuiv])\n\n df = pd.DataFrame(l_dist, columns=[\"Residue\", \"C1'-P\", \"P-C1'\", \"C4'-P\", \"P-C4'\"])\n df.to_csv(runDir + \"/results/geometry/Pyle/distances/distances_pyle_\" + name + \".csv\")\n df = pd.DataFrame(l_angl, columns=[\"Residue\", \"P-C1'-P°\", \"C1'-P°-C1'°\"])\n df.to_csv(runDir + \"/results/geometry/Pyle/angles/flat_angles_pyle_\"+name+\".csv\")\n\n@trace_unhandled_exceptions\ndef measures_hrna(name, s, thr_idx):\n \"\"\"\n Measures the distance/angles between the atoms of the HiRE-RNA model linked by covalent bonds\n \"\"\"\n \n # do not recompute something already computed\n if (os.path.isfile(runDir + '/results/geometry/HiRE-RNA/distances/distances_HiRERNA '+name+'.csv') and \n os.path.isfile(runDir + '/results/geometry/HiRE-RNA/angles/angles_HiRERNA '+name+'.csv') and \n os.path.isfile(runDir + '/results/geometry/HiRE-RNA/torsions/torsions_HiRERNA '+name+'.csv')):\n return\n\n l_dist = []\n l_angl = []\n l_tors = []\n last_c4p = []\n last_c5p = []\n last_c1p = []\n last_o5p = []\n\n setproctitle(f\"RNANet statistics.py Worker {thr_idx+1} measures_hrna({name})\")\n\n chain = next(s[0].get_chains())\n residues=list(chain.get_residues())\n for res in tqdm(chain, position=thr_idx+1, desc=f\"Worker {thr_idx+1}: {name} measures_hrna\", unit=\"res\", leave=False):\n # distances\n p_o5p = None\n o5p_c5p = None\n c5p_c4p = None\n c4p_c1p = None\n c1p_b1 = None\n b1_b2 = None\n last_c4p_p = np.nan\n \n # angles\n p_o5p_c5p = None\n o5p_c5p_c4p = None\n c5p_c4p_c1p = None\n c4p_c1p_b1 = None\n c1p_b1_b2 = None\n lastc4p_p_o5p = None\n lastc5p_lastc4p_p = None\n lastc1p_lastc4p_p = None\n\n # torsions\n p_o5_c5_c4 = np.nan\n o5_c5_c4_c1 = np.nan\n c5_c4_c1_b1 = np.nan\n c4_c1_b1_b2 = np.nan\n o5_c5_c4_psuiv = np.nan\n c5_c4_psuiv_o5suiv = np.nan\n c4_psuiv_o5suiv_c5suiv = np.nan\n c1_c4_psuiv_o5suiv = np.nan\n\n if res.get_resname() not in ['ATP', 'CCC', 'A3P', 'A23', 'GDP', 'RIA', \"2BA\"] : # several phosphate groups, ignore\n atom_p = [ atom.get_coord() for atom in res if atom.get_name() == \"P\"]\n atom_o5p = [ atom.get_coord() for atom in res if \"O5'\" in atom.get_fullname() ]\n atom_c5p = [ atom.get_coord() for atom in res if \"C5'\" in atom.get_fullname() ]\n atom_c4p = [ atom.get_coord() for atom in res if \"C4'\" in atom.get_fullname() ]\n atom_c1p = [ atom.get_coord() for atom in res if \"C1'\" in atom.get_fullname() ]\n atom_b1 = pos_b1(res) # position b1 to be calculated, depending on the case\n atom_b2 = pos_b2(res) # position b2 to be calculated only for those with 2 cycles\n\n # Distances. If one of the atoms is empty, the euclidian distance returns NaN.\n last_c4p_p = get_euclidian_distance(last_c4p, atom_p)\n p_o5p = get_euclidian_distance(atom_p, atom_o5p)\n o5p_c5p = get_euclidian_distance(atom_o5p, atom_c5p)\n c5p_c4p = get_euclidian_distance(atom_c5p, atom_c4p)\n c4p_c1p = get_euclidian_distance(atom_c4p, atom_c1p)\n c1p_b1 = get_euclidian_distance(atom_c1p, atom_b1)\n b1_b2 = get_euclidian_distance(atom_b1, atom_b2)\n\n # flat angles. Same.\n lastc4p_p_o5p = get_flat_angle(last_c4p, atom_p, atom_o5p)\n lastc1p_lastc4p_p = get_flat_angle(last_c1p, last_c4p, atom_p)\n lastc5p_lastc4p_p = get_flat_angle(last_c5p, last_c4p, atom_p)\n p_o5p_c5p = get_flat_angle(atom_p, atom_o5p, atom_c5p)\n o5p_c5p_c4p = get_flat_angle(atom_o5p, atom_c5p, atom_c4p)\n c5p_c4p_c1p = get_flat_angle(atom_c5p, atom_c4p, atom_c1p)\n c4p_c1p_b1 = get_flat_angle(atom_c4p, atom_c1p, atom_b1)\n c1p_b1_b2 = get_flat_angle(atom_c1p, atom_b1, atom_b2)\n\n # torsions. Idem.\n p_o5_c5_c4 = get_torsion_angle(atom_p, atom_o5p, atom_c5p, atom_c4p)\n o5_c5_c4_c1 = get_torsion_angle(atom_o5p, atom_c5p, atom_c4p, atom_c1p)\n c5_c4_c1_b1 = get_torsion_angle(atom_c5p, atom_c4p, atom_c1p, atom_b1)\n c4_c1_b1_b2 = get_torsion_angle(atom_c4p, atom_c1p, atom_b1, atom_b2)\n o5_c5_c4_psuiv = get_torsion_angle(last_o5p, last_c5p, last_c4p, atom_p)\n c5_c4_psuiv_o5suiv = get_torsion_angle(last_c5p, last_c4p, atom_p, atom_o5p)\n c4_psuiv_o5suiv_c5suiv = get_torsion_angle(last_c4p, atom_p, atom_o5p, atom_c5p)\n c1_c4_psuiv_o5suiv = get_torsion_angle(last_c1p, last_c4p, atom_p, atom_o5p)\n\n last_c4p = atom_c4p\n last_c5p = atom_c5p\n last_c1p = atom_c1p\n last_o5p = atom_o5p\n l_dist.append([res.get_resname(), last_c4p_p, p_o5p, o5p_c5p, c5p_c4p, c4p_c1p, c1p_b1, b1_b2])\n l_angl.append([res.get_resname(), lastc4p_p_o5p, lastc1p_lastc4p_p, lastc5p_lastc4p_p, p_o5p_c5p, o5p_c5p_c4p, c5p_c4p_c1p, c4p_c1p_b1, c1p_b1_b2])\n l_tors.append([res.get_resname(), p_o5_c5_c4, o5_c5_c4_c1, c5_c4_c1_b1, c4_c1_b1_b2, o5_c5_c4_psuiv, c5_c4_psuiv_o5suiv, c4_psuiv_o5suiv_c5suiv, c1_c4_psuiv_o5suiv])\n\n df = pd.DataFrame(l_dist, columns=[\"Residue\", \"C4'-P\", \"P-O5'\", \"O5'-C5'\", \"C5'-C4'\", \"C4'-C1'\", \"C1'-B1\", \"B1-B2\"])\n df.to_csv(runDir + '/results/geometry/HiRE-RNA/distances/distances_HiRERNA '+name+'.csv')\n df = pd.DataFrame(l_angl, columns=[\"Residue\", \"C4'-P-O5'\", \"C1'-C4'-P\", \"C5'-C4'-P\", \"P-O5'-C5'\", \"O5'-C5'-C4'\", \"C5'-C4'-C1'\", \"C4'-C1'-B1\", \"C1'-B1-B2\"])\n df.to_csv(runDir + '/results/geometry/HiRE-RNA/angles/angles_HiRERNA ' + name + \".csv\")\n df=pd.DataFrame(l_tors, columns=[\"Residue\", \"P-O5'-C5'-C4'\", \"O5'-C5'-C4'-C1'\", \"C5'-C4'-C1'-B1\", \"C4'-C1'-B1-B2\", \"O5'-C5'-C4'-P°\", \"C5'-C4'-P°-O5'°\", \"C4'-P°-O5'°-C5'°\", \"C1'-C4'-P°-O5'°\"])\n df.to_csv(runDir + '/results/geometry/HiRE-RNA/torsions/torsions_HiRERNA '+name+'.csv')\n\n@trace_unhandled_exceptions\ndef measures_hrna_basepairs(name, s, path_to_3D_data, thr_idx):\n \"\"\"\n Open a rna_only/ file, and run measures_hrna_basepairs_chain() on every chain\n \"\"\" \n\n setproctitle(f\"RNANet statistics.py Worker {thr_idx+1} measures_hrna_basepairs({name})\")\n \n l = []\n chain = next(s[0].get_chains())\n \n # do not recompute something already computed\n if os.path.isfile(runDir + \"/results/geometry/HiRE-RNA/basepairs/basepairs_\"+name+\".csv\"):\n return\n\n df = pd.read_csv(os.path.abspath(path_to_3D_data +\"datapoints/\" + name))\n\n # if df['index_chain'][0] == 1: # ignore files with numbering errors : TODO : remove when we get DSSR Pro, there should not be numbering errors anymore\n l = measures_hrna_basepairs_chain(name, chain, df, thr_idx)\n df_calc = pd.DataFrame(l, columns=[\"type_LW\", \"nt1_idx\", \"nt1_res\", \"nt2_idx\", \"nt2_res\", \"Distance\", \n \"211_angle\", \"112_angle\", \"dB1\", \"dB2\", \"alpha1\", \"alpha2\", \"3211_torsion\", \"1123_torsion\"])\n df_calc.to_csv(runDir + \"/results/geometry/HiRE-RNA/basepairs/\"+'basepairs_' + name + '.csv', float_format=\"%.3f\")\n\n@trace_unhandled_exceptions\ndef measures_hrna_basepairs_chain(name, chain, df, thr_idx):\n \"\"\"\n Cleanup of the dataset\n measurements of distances and angles between paired nucleotides in the chain\n \"\"\"\n\n results = []\n warnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\n\n pairs = df[['index_chain', 'old_nt_resnum', 'paired', 'pair_type_LW']] # columns we keep\n for i in range(pairs.shape[0]): # we remove the lines where no pairing (NaN in paired)\n index_with_nan = pairs.index[pairs.iloc[:,2].isnull()]\n pairs.drop(index_with_nan, 0, inplace=True)\n\n paired_int = []\n for i in pairs.index: # convert values from paired to integers or lists of integers\n paired = pairs.at[i, 'paired']\n if type(paired) is np.int64 or type(paired) is np.float64:\n paired_int.append(int(paired))\n else : #strings\n if len(paired) < 3: # a single pairing\n paired_int.append(int(paired)) \n else : # several pairings\n paired = paired.split(',')\n l = [ int(i) for i in paired ]\n paired_int.append(l)\n\n pair_type_LW_bis = []\n for j in pairs.index:\n pair_type_LW = pairs.at[j, 'pair_type_LW']\n if len(pair_type_LW) < 4 : # a single pairing\n pair_type_LW_bis.append(pair_type_LW)\n else : # several pairings\n pair_type_LW = pair_type_LW.split(',')\n l = [ i for i in pair_type_LW ]\n pair_type_LW_bis.append(pair_type_LW)\n\n # addition of these new columns\n pairs.insert(4, \"paired_int\", paired_int, True)\n pairs.insert(5, \"pair_type_LW_bis\", pair_type_LW_bis, True)\n \n indexNames = pairs[pairs['paired_int'] == 0].index\n pairs.drop(indexNames, inplace=True) # deletion of lines with a 0 in paired_int (matching to another RNA chain)\n\n for i in tqdm(pairs.index, position=thr_idx+1, desc=f\"Worker {thr_idx+1}: {name} measures_hrna_basepairs_chain\", unit=\"res\", leave=False):\n # calculations for each row of the pairs dataset\n index = pairs.at[i, 'index_chain'] \n res1 = chain[(' ', index, ' ')].get_resname()\n if res1 not in ['A','C','G','U']:\n continue\n type_LW = pairs.at[i, 'pair_type_LW_bis'] # pairing type\n num_paired = pairs.at[i, 'paired_int'] # number (index_chain) of the paired nucleotide\n \n if type(num_paired) is int or type(num_paired) is np.int64:\n res2 = chain[(' ', num_paired, ' ')].get_resname()\n if res2 not in [\"A\",\"C\",\"G\",\"U\"]:\n continue\n measures = basepair_measures(chain[(' ', index, ' ')], chain[(' ', num_paired, ' ')])\n if measures is not None:\n results.append([type_LW, index, res1, num_paired, res2] + measures)\n else:\n for j in range(len(num_paired)): # if several pairings, process them one by one\n if num_paired[j] != 0:\n res2 = chain[(' ', num_paired[j], ' ')].get_resname()\n if res2 not in [\"A\",\"C\",\"G\",\"U\"]:\n continue\n measures = basepair_measures(chain[(' ', index, ' ')], chain[(' ', num_paired[j], ' ')])\n if measures is not None:\n results.append([type_LW[j], index, res1, num_paired[j], res2] + measures)\n\n return results\n\n@trace_unhandled_exceptions\ndef basepair_measures(res, pair):\n \"\"\"\n Measurement of the flat angles describing a basepair in the HiRE-RNA model\n \"\"\"\n\n if res.get_resname()=='C' or res.get_resname()=='U' :\n atom_c4_res = [ atom.get_coord() for atom in res if \"C4'\" in atom.get_fullname() ] \n atom_c1p_res = [ atom.get_coord() for atom in res if \"C1'\" in atom.get_fullname() ]\n atom_b1_res = pos_b1(res)\n if not len(atom_c4_res) or not len(atom_c1p_res) or not len(atom_b1_res):\n return\n a3_res = Vector(atom_c4_res[0])\n a2_res = Vector(atom_c1p_res[0])\n a1_res = Vector(atom_b1_res[0])\n if res.get_resname()=='A' or res.get_resname()=='G' :\n atom_c1p_res = [ atom.get_coord() for atom in res if \"C1'\" in atom.get_fullname() ]\n atom_b1_res = pos_b1(res)\n atom_b2_res = pos_b2(res)\n if not len(atom_c1p_res) or not len(atom_b1_res) or not len(atom_b2_res): \n return\n a3_res = Vector(atom_c1p_res[0])\n a2_res = Vector(atom_b1_res[0])\n a1_res = Vector(atom_b2_res[0])\n \n if pair.get_resname()=='C' or pair.get_resname()=='U' :\n atom_c4_pair = [ atom.get_coord() for atom in pair if \"C4'\" in atom.get_fullname() ]\n atom_c1p_pair = [ atom.get_coord() for atom in pair if \"C1'\" in atom.get_fullname() ]\n atom_b1_pair = pos_b1(pair)\n if not len(atom_c4_pair) or not len(atom_c1p_pair) or not len(atom_b1_pair):\n return\n a3_pair = Vector(atom_c4_pair[0])\n a2_pair = Vector(atom_c1p_pair[0])\n a1_pair = Vector(atom_b1_pair[0])\n if pair.get_resname()=='A' or pair.get_resname()=='G' :\n atom_c1p_pair = [ atom.get_coord() for atom in pair if \"C1'\" in atom.get_fullname() ]\n atom_b1_pair = pos_b1(pair)\n atom_b2_pair = pos_b2(pair)\n if not len(atom_c1p_pair) or not len(atom_b1_pair) or not len(atom_b2_pair): # No C1' atom in the paired nucleotide, skip measures.\n return\n a3_pair = Vector(atom_c1p_pair[0])\n a2_pair = Vector(atom_b1_pair[0])\n a1_pair = Vector(atom_b2_pair[0])\n\n # Bond vectors\n res_32 = a3_res - a2_res\n res_12 = a1_res - a2_res\n pair_32 = a3_pair - a2_pair\n pair_12 = a1_pair - a2_pair\n rho = a1_res - a1_pair # from pair to res\n\n # dist\n dist = rho.norm()\n\n # we calculate the 2 plane angles\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', RuntimeWarning)\n b = res_12.angle(rho)*(180/np.pi) # equal to the previous implementation\n c = pair_12.angle(-rho)*(180/np.pi) #\n \n # Compute plane vectors\n n1 = (res_32**res_12).normalized() # ** between vectors, is the cross product\n n2 = (pair_32**pair_12).normalized()\n\n # Distances between base tip and the other base's plane (orthogonal projection)\n # if angle(rho, n) > pi/2 the distance is negative (signed following n)\n d1 = rho*n1 # projection of rho on axis n1\n d2 = rho*n2\n\n # Now the projection of rho in the planes. It's just a sum of the triangles' two other edges.\n p1 = (-rho+n1**d1).normalized() # between vector and scalar, ** is the multiplication by a scalar\n p2 = (rho-n2**d2).normalized()\n\n # Measure tau, the dihedral\n u = (res_12**rho).normalized()\n v = (rho**pair_12).normalized()\n cosTau1 = n1*u\n cosTau2 = v*n2 \n \n # cosTau is enough to compute alpha, but we can't distinguish\n # yet betwwen tau and -tau. If the full computation if required, then:\n tau1 = np.arccos(cosTau1)*(180/np.pi)\n tau2 = np.arccos(cosTau2)*(180/np.pi)\n w1 = u**n1\n w2 = v**n2\n if res_12*w1 < 0:\n tau1 = -tau1\n if pair_12*w2 < 0:\n tau2 = -tau2\n\n # And finally, the a1 and a2 angles between res_12 and p1 / pair_12 and p2\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', RuntimeWarning)\n a1 = (-res_12).angle(p1)*(180/np.pi)\n a2 = (-pair_12).angle(p2)*(180/np.pi)\n if cosTau1 > 0:\n # CosTau > 0 (Tau < 90 or Tau > 270) implies that alpha > 180.\n a1 = -a1\n if cosTau2 > 0:\n a2 = -a2\n\n return [dist, b, c, d1, d2, a1, a2, tau1, tau2]\n\n@trace_unhandled_exceptions\ndef GMM_histo(data_ori, name_data, scan, toric=False, hist=True, col=None, save=True) :\n \"\"\"\n Plot Gaussian-Mixture-Model (with or without histograms)\n \"\"\"\n\n if len(data_ori) < 30:\n warn(f\"We only have {len(data_ori)} observations of {name_data}, we cannot model it. Skipping.\")\n return\n\n data_ori = np.array(data_ori)\n\n if toric:\n # Extend the data on the right and on the left (for angles)\n data = np.concatenate([data_ori, data_ori-360.0, data_ori+360.0])\n else:\n data = data_ori\n\n # chooses the number of components based on the maximum likelihood value (maxlogv)\n if scan:\n n_components_range = np.arange(8)+1\n # aic = []\n # bic = []\n maxlogv=[]\n md = np.array(data).reshape(-1,1)\n nb_components = 1\n nb_log_max = n_components_range[0]\n log_max = 0\n for n_comp in n_components_range:\n gmm = GaussianMixture(n_components=n_comp, random_state=1234).fit(md)\n # aic.append(abs(gmm.aic(md)))\n # bic.append(abs(gmm.bic(md)))\n maxlogv.append(gmm.lower_bound_)\n if gmm.lower_bound_== max(maxlogv) : # takes the maximum\n nb_components = n_comp\n # if there is convergence, keep the first maximum found\n if abs(gmm.lower_bound_-log_max) < 0.02 : # threshold=0.02\n nb_components = nb_log_max\n break\n log_max = max(maxlogv)\n nb_log_max = n_comp\n else:\n try:\n nb_components = modes_data[name_data]\n except KeyError:\n warn(f\"Unexpected key {name_data} not known in geometric_stats.py mode_data. Skipping.\")\n return # unexpected atom ? skip it...\n if toric:\n nb_components = nb_components * 2 + 1 # because we extend the xrange for toric computation. It will be restored later.\n \n # Now compute the final GMM\n obs = np.array(data).reshape(-1,1) # still on extended data\n g = GaussianMixture(n_components=nb_components, random_state=1234)\n g.fit(obs)\n\n if toric:\n # Now decide which to keep\n keep = []\n weights = []\n means = []\n covariances = []\n sum_weights = 0.0\n for m in g.means_:\n keep.append(m > -180 and m <= 180)\n for i, w in enumerate(g.weights_):\n if not keep[i]:\n continue\n sum_weights += w\n for i in range(nb_components):\n if not keep[i]:\n continue\n means.append(g.means_[i])\n covariances.append(g.covariances_[i])\n weights.append(g.weights_[i]/sum_weights)\n nb_components = len(means)\n else:\n weights = g.weights_\n means = g.means_\n covariances = g.covariances_\n\n if nb_components == 0:\n # Happens when the gaussians averages are outside [-180, 180]\n # an have been eliminated. Fix: increase the number of components\n # so that at least one is inside [-180,180]\n warn(f\"Found 0 gaussians in interval [-180,180] for the {name_data} GMM. Please retry with a higher number of gaussians. Ignoring the measure for now.\", error=True)\n return\n\n # plot histograms if asked, with the appropriate number of components\n if hist:\n plt.hist(data_ori, color=\"green\", edgecolor='black', linewidth=1.2, bins=50, density=True)\n if toric:\n plt.xlabel(\"Angle (Degrees)\")\n else:\n plt.xlabel(\"Distance (Angströms)\")\n plt.ylabel(\"Density\")\n\n # Prepare the GMM curve with some absciss points\n if toric:\n x = np.linspace(-360.0,360.0,721)\n else:\n D = obs.ravel()\n xmin = D.min()\n #xmax = min(10.0, D.max())\n xmax = D.max()\n x = np.linspace(xmin,xmax,1000)\n colors=['red', 'blue', 'gold', 'cyan', 'magenta', 'white', 'black', 'green']\n\n # prepare the dictionary to save the parameters\n summary_data = {}\n summary_data[\"measure\"] = name_data\n summary_data[\"weights\"] = []\n summary_data[\"means\"] = []\n summary_data[\"std\"] = []\n\n # plot\n curves = []\n newx = None # to be defined inside the loop\n for i in range(nb_components):\n\n # store the parameters\n mean = means[i]\n sigma = np.sqrt(covariances[i])\n weight = weights[i]\n summary_data[\"means\"].append(\"{:.2f}\".format(float(str(mean).strip(\"[]\"))))\n summary_data[\"std\"].append(\"{:.2f}\".format(float(str(sigma).strip(\"[]\"))))\n summary_data[\"weights\"].append(\"{:.2f}\".format(float(str(weight).strip(\"[]\"))))\n\n # compute the right x and y data to plot\n y = weight*st.norm.pdf(x, mean, sigma)\n if toric:\n y_mod = (((y[0]+180.0)%360.0)-180.0)\n x_mod = (((x+180.0)%360.0)-180.0)\n s = sorted(zip(x_mod,y_mod))\n newx = []\n newy = []\n for k in range(0, len(s), 2):\n if k == 362.0:\n continue # this value is dealt with when k = 360.0\n # print(k, \"summing: \", s[k-int(k>360)], s[k+1-int(k>360)])\n newx.append(s[k-int(k>360)][0])\n if k == 360.0:\n newy.append(s[k][1]+s[k+1][1]+s[k+2][1])\n else:\n newy.append(s[k-int(k>360)][1]+s[k+1-int(k>360)][1])\n else:\n newx = x\n newy = y[0]\n\n if hist:\n # plot on top of the histograms\n plt.plot(newx, newy, c=colors[i])\n else:\n # store for later summation\n curves.append(np.array(newy))\n\n if hist:\n plt.title(f\"Histogram of {name_data} with GMM of {nb_components} components (\" + str(len(data_ori))+\" values)\")\n if save:\n plt.savefig(f\"Histogram_{name_data}_{nb_components}_comps.png\")\n plt.close()\n else:\n # Plot their sum, do not save figure yet\n plt.plot(newx, sum(curves), c=col, label=name_data)\n plt.legend()\n\n # Save the json\n with open(runDir + \"/results/geometry/json/\" + name_data + \".json\", 'w', encoding='utf-8') as f:\n json.dump(summary_data, f, indent=4)\n notify(\"Saved \" + name_data + \".json\")\n\n@trace_unhandled_exceptions\ndef gmm_aa_dists(scan):\n \"\"\"\n Draw the figures representing the data on the measurements of distances between atoms\n \"\"\"\n\n setproctitle(\"GMM (all atoms, distances)\")\n\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/all-atoms/distances/dist_atoms.csv\"))\n\n last_o3p_p = df[\"O3'-P\"][~ np.isnan(df[\"O3'-P\"])].values.tolist()\n p_op1 = df[\"P-OP1\"][~ np.isnan(df[\"P-OP1\"])].values.tolist()\n p_op2 = df[\"P-OP2\"][~ np.isnan(df[\"P-OP2\"])].values.tolist()\n p_o5p = df[\"P-O5'\"][~ np.isnan(df[\"P-O5'\"])].values.tolist()\n o5p_c5p = df[\"O5'-C5'\"][~ np.isnan(df[\"O5'-C5'\"])].values.tolist()\n c5p_c4p = df[\"C5'-C4'\"][~ np.isnan(df[\"C5'-C4'\"])].values.tolist()\n c4p_o4p = df[\"C4'-O4'\"][~ np.isnan(df[\"C4'-O4'\"])].values.tolist()\n o4p_c1p = df[\"O4'-C1'\"][~ np.isnan(df[\"O4'-C1'\"])].values.tolist()\n c1p_c2p = df[\"C1'-C2'\"][~ np.isnan(df[\"C1'-C2'\"])].values.tolist()\n c2p_o2p = df[\"C2'-O2'\"][~ np.isnan(df[\"C2'-O2'\"])].values.tolist()\n c2p_c3p = df[\"C2'-C3'\"][~ np.isnan(df[\"C2'-C3'\"])].values.tolist()\n c3p_o3p = df[\"C3'-O3'\"][~ np.isnan(df[\"C3'-O3'\"])].values.tolist()\n c4p_c3p = df[\"C4'-C3'\"][~ np.isnan(df[\"C4'-C3'\"])].values.tolist()\n \n #if res = A ou G\n c1p_n9 = df[\"C1'-N9\"][~ np.isnan(df[\"C1'-N9\"])].values.tolist()\n n9_c8 = df[\"N9-C8\"][~ np.isnan(df[\"N9-C8\"])].values.tolist()\n c8_n7 = df[\"C8-N7\"][~ np.isnan(df[\"C8-N7\"])].values.tolist()\n n7_c5 = df[\"N7-C5\"][~ np.isnan(df[\"N7-C5\"])].values.tolist()\n c5_c6 = df[\"C5-C6\"][~ np.isnan(df[\"C5-C6\"])].values.tolist()\n c6_n1 = df[\"C6-N1\"][~ np.isnan(df[\"C6-N1\"])].values.tolist()\n n1_c2 = df[\"N1-C2\"][~ np.isnan(df[\"N1-C2\"])].values.tolist()\n c2_n3 = df[\"C2-N3\"][~ np.isnan(df[\"C2-N3\"])].values.tolist()\n n3_c4 = df[\"N3-C4\"][~ np.isnan(df[\"N3-C4\"])].values.tolist()\n c4_n9 = df[\"C4-N9\"][~ np.isnan(df[\"C4-N9\"])].values.tolist()\n c4_c5 = df[\"C4-C5\"][~ np.isnan(df[\"C4-C5\"])].values.tolist()\n #if res = G\n c6_o6 = df[\"C6-O6\"][~ np.isnan(df[\"C6-O6\"])].values.tolist()\n c2_n2 = df[\"C2-N2\"][~ np.isnan(df[\"C2-N2\"])].values.tolist()\n #if res = A\n c6_n6 = df[\"C6-N6\"][~ np.isnan(df[\"C6-N6\"])].values.tolist()\n #if res = C ou U\n c1p_n1 = df[\"C1'-N1\"][~ np.isnan(df[\"C1'-N1\"])].values.tolist()\n n1_c6 = df[\"N1-C6\"][~ np.isnan(df[\"N1-C6\"])].values.tolist()\n c6_c5 = df[\"C6-C5\"][~ np.isnan(df[\"C6-C5\"])].values.tolist()\n c5_c4 = df[\"C5-C4\"][~ np.isnan(df[\"C5-C4\"])].values.tolist()\n c4_n3 = df[\"C4-N3\"][~ np.isnan(df[\"C4-N3\"])].values.tolist()\n n3_c2 = df[\"N3-C2\"][~ np.isnan(df[\"N3-C2\"])].values.tolist()\n c2_n1 = df[\"C2-N1\"][~ np.isnan(df[\"C2-N1\"])].values.tolist()\n c2_o2 = df[\"C2-O2\"][~ np.isnan(df[\"C2-O2\"])].values.tolist()\n #if res =C\n c4_n4 = df[\"C4-N4\"][~ np.isnan(df[\"C4-N4\"])].values.tolist()\n #if res=U\n c4_o4 = df[\"C4-O4\"][~ np.isnan(df[\"C4-O4\"])].values.tolist()\n\n os.makedirs(runDir+\"/results/figures/GMM/all-atoms/distances/commun/\", exist_ok=True)\n os.chdir(runDir+\"/results/figures/GMM/all-atoms/distances/commun/\")\n\n # draw figures for atoms common to all nucleotides\n GMM_histo(last_o3p_p, \"O3'-P\", scan)\n GMM_histo(p_op1, \"P-OP1\", scan)\n GMM_histo(p_op2, \"P-OP2\", scan)\n GMM_histo(p_o5p, \"P-O5'\", scan)\n GMM_histo(o5p_c5p, \"O5'-C5'\", scan)\n GMM_histo(c5p_c4p, \"C5'-C4'\", scan)\n GMM_histo(c4p_o4p, \"C4'-O4'\", scan)\n GMM_histo(c4p_c3p, \"C4'-C3'\", scan)\n GMM_histo(c3p_o3p, \"C3'-O3'\", scan)\n GMM_histo(o4p_c1p, \"O4'-C1'\", scan)\n GMM_histo(c1p_c2p, \"C1'-C2'\", scan)\n GMM_histo(c2p_c3p, \"C2'-C3'\", scan)\n GMM_histo(c2p_o2p, \"C2'-O2'\", scan)\n GMM_histo(last_o3p_p, \"O3'-P\", scan, toric=False, hist=False, col='saddlebrown')\n GMM_histo(p_op1, \"P-OP1\", scan, toric=False, hist=False, col='gold')\n GMM_histo(p_op2, \"P-OP2\", scan, toric=False, hist=False, col='lightseagreen')\n GMM_histo(p_o5p, \"P-O5'\", scan, toric=False, hist=False, col='darkturquoise')\n GMM_histo(o5p_c5p, \"O5'-C5'\", scan, toric=False, hist=False, col='darkkhaki')\n GMM_histo(c5p_c4p, \"C5'-C4'\", scan, toric=False, hist=False, col='indigo')\n GMM_histo(c4p_o4p, \"C4'-O4'\", scan, toric=False, hist=False, col='maroon')\n GMM_histo(c4p_c3p, \"C4'-C3'\", scan, toric=False, hist=False, col='burlywood')\n GMM_histo(c3p_o3p, \"C3'-O3'\", scan, toric=False, hist=False, col='steelblue')\n GMM_histo(o4p_c1p, \"O4'-C1'\", scan, toric=False, hist=False, col='tomato')\n GMM_histo(c1p_c2p, \"C1'-C2'\", scan, toric=False, hist=False, col='darkolivegreen')\n GMM_histo(c2p_c3p, \"C2'-C3'\", scan, toric=False, hist=False, col='orchid')\n GMM_histo(c2p_o2p, \"C2'-O2'\", scan, toric=False, hist=False, col='deeppink')\n axes = plt.gca()\n axes.set_ylim(0, 100)\n plt.xlabel(\"Distance (Angströms)\")\n plt.title(\"GMM of distances between common atoms \")\n plt.savefig(runDir + \"/results/figures/GMM/all-atoms/distances/commun/\" + \"GMM_distances_common_atoms.png\")\n plt.close()\n\n\n # purines\n os.makedirs(runDir+\"/results/figures/GMM/all-atoms/distances/purines/\", exist_ok=True)\n os.chdir(runDir+\"/results/figures/GMM/all-atoms/distances/purines/\")\n GMM_histo(c1p_n9, \"C1'-N9\", scan)\n GMM_histo(n9_c8, \"N9-C8\", scan)\n GMM_histo(c8_n7, \"C8-N7\", scan)\n GMM_histo(n7_c5, \"N7-C5\", scan)\n GMM_histo(c5_c6, \"C5-C6\", scan)\n GMM_histo(c6_o6, \"C6-O6\", scan)\n GMM_histo(c6_n6, \"C6-N6\", scan)\n GMM_histo(c6_n1, \"C6-N1\", scan)\n GMM_histo(n1_c2, \"N1-C2\", scan)\n GMM_histo(c2_n2, \"C2-N2\", scan)\n GMM_histo(c2_n3, \"C2-N3\", scan)\n GMM_histo(n3_c4, \"N3-C4\", scan)\n GMM_histo(c4_n9, \"C4-N9\", scan)\n GMM_histo(c4_c5, \"C4-C5\", scan)\n GMM_histo(c1p_n9, \"C1'-N9\", scan, hist=False, col='lightcoral')\n GMM_histo(n9_c8, \"N9-C8\", scan, hist=False, col='gold')\n GMM_histo(c8_n7, \"C8-N7\", scan, hist=False, col='lightseagreen')\n GMM_histo(n7_c5, \"N7-C5\", scan, hist=False, col='saddlebrown')\n GMM_histo(c5_c6, \"C5-C6\", scan, hist=False, col='darkturquoise')\n GMM_histo(c6_o6, \"C6-O6\", scan, hist=False, col='darkkhaki')\n GMM_histo(c6_n6, \"C6-N6\", scan, hist=False, col='indigo')\n GMM_histo(c6_n1, \"C6-N1\", scan, hist=False, col='maroon')\n GMM_histo(n1_c2, \"N1-C2\", scan, hist=False, col='burlywood')\n GMM_histo(c2_n2, \"C2-N2\", scan, hist=False, col='steelblue')\n GMM_histo(c2_n3, \"C2-N3\", scan, hist=False, col='tomato')\n GMM_histo(n3_c4, \"N3-C4\", scan, hist=False, col='darkolivegreen')\n GMM_histo(c4_n9, \"C4-N9\", scan, hist=False, col='orchid')\n GMM_histo(c4_c5, \"C4-C5\", scan, hist=False, col='deeppink')\n axes = plt.gca()\n axes.set_ylim(0, 100)\n plt.xlabel(\"Distance (Angströms)\")\n plt.title(\"GMM of distances between atoms of the purine cycles\", fontsize=10)\n plt.savefig(runDir+ \"/results/figures/GMM/all-atoms/distances/purines/\" + \"GMM_distances_purine_cycles.png\")\n plt.close()\n\n # pyrimidines\n os.makedirs(runDir+\"/results/figures/GMM/all-atoms/distances/pyrimidines/\", exist_ok=True)\n os.chdir(runDir+\"/results/figures/GMM/all-atoms/distances/pyrimidines/\")\n GMM_histo(c1p_n1, \"C1'-N1\", scan)\n GMM_histo(n1_c6, \"N1-C6\", scan)\n GMM_histo(c6_c5, \"C6-C5\", scan)\n GMM_histo(c5_c4, \"C5-C4\", scan)\n GMM_histo(c4_n3, \"C4-N3\", scan)\n GMM_histo(n3_c2, \"N3-C2\", scan)\n GMM_histo(c2_o2, \"C2-O2\", scan)\n GMM_histo(c2_n1, \"C2-N1\", scan)\n GMM_histo(c4_n4, \"C4-N4\", scan)\n GMM_histo(c4_o4, \"C4-O4\", scan)\n GMM_histo(c1p_n1, \"C1'-N1\", scan, hist=False, col='lightcoral')\n GMM_histo(n1_c6, \"N1-C6\", scan, hist=False, col='gold')\n GMM_histo(c6_c5, \"C6-C5\", scan, hist=False, col='lightseagreen')\n GMM_histo(c5_c4, \"C5-C4\", scan, hist=False, col='deeppink')\n GMM_histo(c4_n3, \"C4-N3\", scan, hist=False, col='red')\n GMM_histo(n3_c2, \"N3-C2\", scan, hist=False, col='lime')\n GMM_histo(c2_o2, \"C2-O2\", scan, hist=False, col='indigo')\n GMM_histo(c2_n1, \"C2-N1\", scan, hist=False, col='maroon')\n GMM_histo(c4_n4, \"C4-N4\", scan, hist=False, col='burlywood')\n GMM_histo(c4_o4, \"C4-O4\", scan, hist=False, col='steelblue')\n axes = plt.gca()\n #axes.set_xlim(1, 2)\n axes.set_ylim(0, 100)\n plt.xlabel(\"Distance (Angströms\")\n plt.title(\"GMM of distances between atoms of the pyrimidine cycles\", fontsize=10)\n plt.savefig(runDir + \"/results/figures/GMM/all-atoms/distances/pyrimidines/\" + \"GMM_distances_pyrimidine_cycles.png\")\n plt.close()\n\n os.chdir(runDir)\n setproctitle(\"GMM (all atoms, distances) finished\")\n\n@trace_unhandled_exceptions\ndef gmm_aa_torsions(scan, res):\n \"\"\"\n Separates the torsion angle measurements by angle type and plots the figures representing the data\n \"\"\"\n\n setproctitle(\"GMM (all atoms, torsions)\")\n\n # we create lists to store the values of each angle\n alpha = []\n beta = []\n gamma = []\n delta = []\n epsilon = []\n zeta = []\n chi = []\n angles_deg = retrieve_angles(runDir + \"/results/RNANet.db\", res)\n\n # we remove the null values\n alpha = angles_deg.alpha.values\n beta = angles_deg.beta.values\n gamma = angles_deg.gamma.values\n delta = angles_deg.delta.values\n epsilon = angles_deg.epsilon.values\n zeta = angles_deg.zeta.values\n chi = angles_deg.chi.values\n alpha = alpha[~np.isnan(alpha)]\n beta = beta[~np.isnan(beta)]\n gamma = gamma[~np.isnan(gamma)]\n delta = delta[~np.isnan(delta)]\n epsilon = epsilon[~np.isnan(epsilon)]\n zeta = zeta[~np.isnan(zeta)]\n chi = chi[~np.isnan(chi)]\n\n os.makedirs(runDir + \"/results/figures/GMM/all-atoms/torsions/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/all-atoms/torsions/\")\n\n \"\"\"\n We plot the GMMs with histogram for each angle\n We create the corresponding json with the means and standard deviations of each Gaussian\n We draw the figure grouping the GMMs of all angles without histogram to compare them with each other\n \"\"\"\n\n GMM_histo(alpha, \"Alpha\", scan, toric=True)\n GMM_histo(beta, \"Beta\", scan, toric=True)\n GMM_histo(gamma, \"Gamma\", scan, toric=True)\n GMM_histo(delta, \"Delta\", scan, toric=True)\n GMM_histo(epsilon, \"Epsilon\", scan, toric=True)\n GMM_histo(zeta, \"Zeta\", scan, toric=True)\n GMM_histo(chi, \"Xhi\", scan, toric=True)\n GMM_histo(alpha, \"Alpha\", scan, toric=True, hist=False, col='red')\n GMM_histo(beta, \"Beta\", scan, toric=True, hist=False, col='firebrick')\n GMM_histo(gamma, \"Gamma\", scan, toric=True, hist=False, col='limegreen')\n GMM_histo(delta, \"Delta\", scan, toric=True, hist=False, col='darkslateblue')\n GMM_histo(epsilon, \"Epsilon\", scan, toric=True, hist=False, col='goldenrod')\n GMM_histo(zeta, \"Zeta\", scan, toric=True, hist=False, col='teal')\n GMM_histo(chi, \"Xhi\", scan, toric=True, hist=False, col='hotpink')\n plt.xlabel(\"Angle (Degrees)\")\n plt.title(\"GMM of torsion angles\")\n plt.savefig(\"GMM_torsions.png\")\n plt.close()\n\n os.chdir(runDir)\n setproctitle(\"GMM (all atoms, torsions) finished\")\n\n@trace_unhandled_exceptions\ndef gmm_pyle(scan, res):\n\n setproctitle(\"GMM (Pyle model)\")\n\n # Distances\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/Pyle/distances/distances_pyle.csv\")) \n\n p_c1p = df[\"C1'-P\"][~ np.isnan(df[\"C1'-P\"])].values.tolist()\n c1p_p = df[\"P-C1'\"][~ np.isnan(df[\"P-C1'\"])].values.tolist()\n p_c4p = df[\"C4'-P\"][~ np.isnan(df[\"C4'-P\"])].values.tolist()\n c4p_p = df[\"P-C4'\"][~ np.isnan(df[\"P-C4'\"])].values.tolist()\n\n os.makedirs(runDir + \"/results/figures/GMM/Pyle/distances/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/Pyle/distances/\")\n\n GMM_histo(p_c1p, \"P-C1'\", scan)\n GMM_histo(c1p_p, \"C1'-P\", scan)\n GMM_histo(p_c4p, \"P-C4'\", scan)\n GMM_histo(c4p_p, \"C4'-P\", scan)\n GMM_histo(p_c4p, \"P-C4'\", scan, toric=False, hist=False, col='gold')\n GMM_histo(c4p_p, \"C4'-P\", scan, toric=False, hist=False, col='indigo')\n GMM_histo(p_c1p, \"P-C1'\", scan, toric=False, hist=False, col='firebrick')\n GMM_histo(c1p_p, \"C1'-P\", scan, toric=False, hist=False, col='seagreen')\n plt.xlabel(\"Distance (Angströms)\")\n plt.title(\"GMM of distances (Pyle model)\")\n plt.savefig(\"GMM_distances_pyle_model.png\")\n plt.close()\n\n # Flat Angles\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/Pyle/angles/flat_angles_pyle.csv\")) \n\n p_c1p_psuiv = list(df[\"P-C1'-P°\"][~ np.isnan(df[\"P-C1'-P°\"])])\n c1p_psuiv_c1psuiv = list(df[\"C1'-P°-C1'°\"][~ np.isnan(df[\"C1'-P°-C1'°\"])])\n\n os.makedirs(runDir + \"/results/figures/GMM/Pyle/angles/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/Pyle/angles/\")\n\n GMM_histo(p_c1p_psuiv, \"P-C1'-P°\", scan, toric=True)\n GMM_histo(c1p_psuiv_c1psuiv, \"C1'-P°-C1'°\", scan, toric=True)\n GMM_histo(p_c1p_psuiv, \"P-C1'-P°\", scan, toric=True, hist=False, col='firebrick')\n GMM_histo(c1p_psuiv_c1psuiv, \"C1'-P°-C1'°\", scan, toric=True, hist=False, col='seagreen')\n plt.xlabel(\"Angle (Degrees)\")\n plt.title(\"GMM of flat angles (Pyle model)\")\n plt.savefig(\"GMM_flat_angles_pyle_model.png\")\n plt.close()\n\n # Torsion angles \n eta=[]\n theta=[]\n eta_prime=[]\n theta_prime=[]\n eta_base=[]\n theta_base=[]\n\n angles_deg = retrieve_eta_theta(runDir + \"/results/RNANet.db\", res)\n\n eta = angles_deg.eta.values\n theta = angles_deg.theta.values\n eta_prime = angles_deg.eta_prime.values\n theta_prime = angles_deg.theta_prime.values\n eta_base = angles_deg.eta_base.values\n theta_base = angles_deg.theta_base.values\n eta = eta[~np.isnan(eta)]\n theta = theta[~np.isnan(theta)]\n eta_prime = eta_prime[~np.isnan(eta_prime)]\n theta_prime = theta_prime[~np.isnan(theta_prime)]\n eta_base = eta_base[~np.isnan(eta_base)]\n theta_base = theta_base[~np.isnan(theta_base)]\n\n os.makedirs(runDir + \"/results/figures/GMM/Pyle/pseudotorsions/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/Pyle/pseudotorsions/\")\n\n GMM_histo(eta, \"Eta\", scan, toric=True)\n GMM_histo(theta, \"Theta\", scan, toric=True)\n GMM_histo(eta_prime, \"Eta'\", scan, toric=True)\n GMM_histo(theta_prime, \"Theta'\", scan, toric=True)\n GMM_histo(eta_base, \"Eta''\", scan, toric=True)\n GMM_histo(theta_base, \"Theta''\", scan, toric=True)\n GMM_histo(eta, \"Eta\", scan, toric=True, hist=False, col='mediumaquamarine')\n GMM_histo(theta, \"Theta\", scan, toric=True, hist=False, col='darkorchid')\n GMM_histo(eta_prime, \"Eta'\", scan, toric=True, hist=False, col='cyan')\n GMM_histo(theta_prime, \"Theta'\", scan, toric=True, hist=False, col='crimson')\n GMM_histo(eta_base, \"Eta''\", scan, toric=True, hist=False, col='royalblue')\n GMM_histo(theta_base, \"Theta''\", scan, toric=True, hist=False, col='palevioletred')\n plt.xlabel(\"Angle (Degrees)\")\n plt.title(\"GMM of pseudo-torsion angles (Pyle Model)\")\n plt.savefig(\"GMM_pseudotorsion_angles_pyle_model.png\")\n plt.close()\n \n os.chdir(runDir)\n setproctitle(\"GMM (Pyle model) finished\") \n\n@trace_unhandled_exceptions\ndef gmm_hrna(scan):\n \"\"\"\n Draw the figures representing the data on the measurements between atoms of the HiRE-RNA model\n \"\"\"\n\n setproctitle(\"GMM (HiRE-RNA)\")\n\n # Distances\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/HiRE-RNA/distances/distances_HiRERNA.csv\")) \n\n last_c4p_p = list(df[\"C4'-P\"][~ np.isnan(df[\"C4'-P\"])])\n p_o5p = list(df[\"P-O5'\"][~ np.isnan(df[\"P-O5'\"])])\n o5p_c5p = list(df[\"O5'-C5'\"][~ np.isnan(df[\"O5'-C5'\"])])\n c5p_c4p = list(df[\"C5'-C4'\"][~ np.isnan(df[\"C5'-C4'\"])])\n c4p_c1p = list(df[\"C4'-C1'\"][~ np.isnan(df[\"C4'-C1'\"])])\n c1p_b1 = list(df[\"C1'-B1\"][~ np.isnan(df[\"C1'-B1\"])])\n b1_b2 = list(df[\"B1-B2\"][~ np.isnan(df[\"B1-B2\"])])\n\n os.makedirs(runDir + \"/results/figures/GMM/HiRE-RNA/distances/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/HiRE-RNA/distances/\")\n\n GMM_histo(o5p_c5p, \"O5'-C5'\", scan)\n GMM_histo(b1_b2, \"B1-B2\", scan)\n GMM_histo(c1p_b1, \"C1'-B1\", scan)\n GMM_histo(c5p_c4p, \"C5'-C4'\", scan)\n GMM_histo(c4p_c1p, \"C4'-C1'\", scan)\n GMM_histo(p_o5p, \"P-O5'\", scan)\n GMM_histo(last_c4p_p, \"C4'-P\", scan)\n \n GMM_histo(o5p_c5p, \"O5'-C5'\", scan, toric=False, hist=False, col='lightcoral')\n GMM_histo(b1_b2, \"B1-B2\", scan, toric=False, hist=False, col='limegreen')\n GMM_histo(c1p_b1, \"C1'-B1\", scan, toric=False, hist=False, col='tomato')\n GMM_histo(c5p_c4p, \"C5'-C4'\", scan, toric=False, hist=False, col='aquamarine')\n GMM_histo(c4p_c1p, \"C4'-C1'\", scan, toric=False, hist=False, col='goldenrod')\n GMM_histo(p_o5p, \"P-O5'\", scan, toric=False, hist=False, col='darkcyan')\n GMM_histo(last_c4p_p, \"C4'-P\", scan, toric=False, hist=False, col='deeppink')\n axes = plt.gca()\n axes.set_ylim(0, 100)\n plt.xlabel(\"Distance (Angströms)\")\n plt.title(\"GMM of distances between HiRE-RNA beads\")\n plt.savefig(runDir + \"/results/figures/GMM/HiRE-RNA/distances/GMM_distances_HiRE_RNA.png\")\n plt.close()\n\n # Angles\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/HiRE-RNA/angles/angles_HiRERNA.csv\")) \n\n lastc4p_p_o5p = list(df[\"C4'-P-O5'\"][~ np.isnan(df[\"C4'-P-O5'\"])])\n lastc1p_lastc4p_p = list(df[\"C1'-C4'-P\"][~ np.isnan(df[\"C1'-C4'-P\"])])\n lastc5p_lastc4p_p = list(df[\"C5'-C4'-P\"][~ np.isnan(df[\"C5'-C4'-P\"])])\n p_o5p_c5p = list(df[\"P-O5'-C5'\"][~ np.isnan(df[\"P-O5'-C5'\"])])\n o5p_c5p_c4p = list(df[\"O5'-C5'-C4'\"][~ np.isnan(df[\"O5'-C5'-C4'\"])])\n c5p_c4p_c1p = list(df[\"C5'-C4'-C1'\"][~ np.isnan(df[\"C5'-C4'-C1'\"])])\n c4p_c1p_b1 = list(df[\"C4'-C1'-B1\"][~ np.isnan(df[\"C4'-C1'-B1\"])])\n c1p_b1_b2 = list(df[\"C1'-B1-B2\"][~ np.isnan(df[\"C1'-B1-B2\"])])\n\n os.makedirs(runDir + \"/results/figures/GMM/HiRE-RNA/angles/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/HiRE-RNA/angles/\")\n\n GMM_histo(lastc4p_p_o5p, \"C4'-P-O5'\", scan, toric=True)\n GMM_histo(lastc1p_lastc4p_p, \"C1'-C4'-P\", scan, toric=True)\n GMM_histo(lastc5p_lastc4p_p, \"C5'-C4'-P\", scan, toric=True)\n GMM_histo(p_o5p_c5p, \"P-O5'-C5'\", scan, toric=True)\n GMM_histo(o5p_c5p_c4p, \"O5'-C5'-C4'\", scan, toric=True)\n GMM_histo(c5p_c4p_c1p, \"C5'-C4'-C1'\", scan, toric=True)\n GMM_histo(c4p_c1p_b1, \"C4'-C1'-B1\", scan, toric=True)\n GMM_histo(c1p_b1_b2, \"C1'-B1-B2\", scan, toric=True)\n \n GMM_histo(lastc4p_p_o5p, \"C4'-P-O5'\", scan, toric=True, hist=False, col='lightcoral')\n GMM_histo(lastc1p_lastc4p_p, \"C1'-C4'-P\", scan, toric=True, hist=False, col='limegreen')\n GMM_histo(lastc5p_lastc4p_p, \"C5'-C4'-P\", scan, toric=True, hist=False, col='tomato')\n GMM_histo(p_o5p_c5p, \"P-O5'-C5'\", scan, toric=True, hist=False, col='aquamarine')\n GMM_histo(o5p_c5p_c4p, \"O5'-C5'-C4'\", scan, toric=True, hist=False, col='goldenrod')\n GMM_histo(c5p_c4p_c1p, \"C5'-C4'-C1'\", scan, toric=True, hist=False, col='darkcyan')\n GMM_histo(c4p_c1p_b1, \"C4'-C1'-B1\", scan, toric=True, hist=False, col='deeppink')\n GMM_histo(c1p_b1_b2, \"C1'-B1-B2\", scan, toric=True, hist=False, col='indigo')\n axes = plt.gca()\n axes.set_ylim(0, 100)\n plt.xlabel(\"Angle (Degres)\")\n plt.title(\"GMM of angles between HiRE-RNA beads\")\n plt.savefig(runDir + \"/results/figures/GMM/HiRE-RNA/angles/GMM_angles_HiRE_RNA.png\")\n plt.close()\n\n # Torsions \n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/HiRE-RNA/torsions/torsions_HiRERNA.csv\")) \n\n p_o5_c5_c4 = list(df[\"P-O5'-C5'-C4'\"][~ np.isnan(df[\"P-O5'-C5'-C4'\"])])\n o5_c5_c4_c1 = list(df[\"O5'-C5'-C4'-C1'\"][~ np.isnan(df[\"O5'-C5'-C4'-C1'\"])])\n c5_c4_c1_b1 = list(df[\"C5'-C4'-C1'-B1\"][~ np.isnan(df[\"C5'-C4'-C1'-B1\"])])\n c4_c1_b1_b2 = list(df[\"C4'-C1'-B1-B2\"][~ np.isnan(df[\"C4'-C1'-B1-B2\"])])\n o5_c5_c4_psuiv = list(df[\"O5'-C5'-C4'-P°\"][~ np.isnan(df[\"O5'-C5'-C4'-P°\"])])\n c5_c4_psuiv_o5suiv = list(df[\"C5'-C4'-P°-O5'°\"][~ np.isnan(df[\"C5'-C4'-P°-O5'°\"])])\n c4_psuiv_o5suiv_c5suiv = list(df[\"C4'-P°-O5'°-C5'°\"][~ np.isnan(df[\"C4'-P°-O5'°-C5'°\"])])\n c1_c4_psuiv_o5suiv = list(df[\"C1'-C4'-P°-O5'°\"][~ np.isnan(df[\"C1'-C4'-P°-O5'°\"])])\n\n os.makedirs(runDir + \"/results/figures/GMM/HiRE-RNA/torsions/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/HiRE-RNA/torsions/\")\n\n GMM_histo(p_o5_c5_c4, \"P-O5'-C5'-C4'\", scan, toric=True)\n GMM_histo(o5_c5_c4_c1, \"O5'-C5'-C4'-C1'\", scan, toric=True)\n GMM_histo(c5_c4_c1_b1, \"C5'-C4'-C1'-B1\", scan, toric=True)\n GMM_histo(c4_c1_b1_b2, \"C4'-C1'-B1-B2\", scan, toric=True)\n GMM_histo(o5_c5_c4_psuiv, \"O5'-C5'-C4'-P°\", scan, toric=True)\n GMM_histo(c5_c4_psuiv_o5suiv, \"C5'-C4'-P°-O5'°\", scan, toric=True)\n GMM_histo(c4_psuiv_o5suiv_c5suiv, \"C4'-P°-O5'°-C5'°\", scan, toric=True)\n GMM_histo(c1_c4_psuiv_o5suiv, \"C1'-C4'-P°-O5'°\", scan, toric=True)\n\n GMM_histo(p_o5_c5_c4, \"P-O5'-C5'-C4'\", scan, toric=True, hist=False, col='darkred')\n GMM_histo(o5_c5_c4_c1, \"O5'-C5'-C4'-C1'\", scan, toric=True, hist=False, col='chocolate')\n GMM_histo(c5_c4_c1_b1, \"C5'-C4'-C1'-B1\", scan, toric=True, hist=False, col='mediumvioletred')\n GMM_histo(c4_c1_b1_b2, \"C4'-C1'-B1-B2\", scan, toric=True, hist=False, col='cadetblue')\n GMM_histo(o5_c5_c4_psuiv, \"O5'-C5'-C4'-P°\", scan, toric=True, hist=False, col='darkkhaki')\n GMM_histo(c5_c4_psuiv_o5suiv, \"C5'-C4'-P°-O5'°\", scan, toric=True, hist=False, col='springgreen')\n GMM_histo(c4_psuiv_o5suiv_c5suiv, \"C4'-P°-O5'°-C5'°\", scan, toric=True, hist=False, col='indigo')\n GMM_histo(c1_c4_psuiv_o5suiv, \"C1'-C4'-P°-O5'°\", scan, toric=True, hist=False, col='gold')\n plt.xlabel(\"Angle (Degrees)\")\n plt.title(\"GMM of torsion angles between HiRE-RNA beads\")\n plt.savefig(\"GMM_torsions_HiRE_RNA.png\")\n plt.close()\n\n os.chdir(runDir)\n setproctitle(\"GMM (HiRE-RNA) finished\")\n\n@trace_unhandled_exceptions\ndef gmm_hrna_basepairs(scan):\n \"\"\"\n Measures parameters of all kinds of non-canonical basepairs for the HiRE-RNA model.\n Please see Cragnolini & al 2015 to understand them.\n \"\"\"\n\n setproctitle(\"GMM (HiRE-RNA basepairs)\")\n\n df = pd.read_csv(os.path.abspath(runDir + \"/results/geometry/HiRE-RNA/basepairs/basepairs_HiRERNA.csv\"))\n\n lw = [\"cWW\", \"tWW\", \"cWH\", \"tWH\", \"cHW\", \"tHW\", \"cWS\", \"tWS\", \"cSW\", \"tSW\", \"cHH\", \"tHH\", \"cSH\", \"tSH\", \"cHS\", \"tHS\", \"cSS\", \"tSS\"]\n\n os.makedirs(runDir + \"/results/figures/GMM/HiRE-RNA/basepairs/\", exist_ok=True)\n os.chdir(runDir + \"/results/figures/GMM/HiRE-RNA/basepairs/\")\n\n for lw_type in lw:\n data = df[df['type_LW'] == lw_type ]\n if len(data):\n for b1 in ['A','C','G','U']:\n for b2 in ['A','C','G','U']:\n thisbases = data[(data.nt1_res == b1)&(data.nt2_res == b2)]\n if len(thisbases):\n gmm_hrna_basepair_type(lw_type, b1+b2, thisbases, scan)\n\n os.chdir(runDir)\n setproctitle(f\"GMM (HiRE-RNA basepairs) finished\")\n\n@trace_unhandled_exceptions\ndef gmm_hrna_basepair_type(type_LW, ntpair, data, scan):\n \"\"\"\n function to plot the statistical figures you want\n By type of pairing:\n Superposition of GMMs of plane angles\n Superposition of the histogram and the GMM of the distances\n all in the same window\n \"\"\"\n\n setproctitle(f\"GMM (HiRE-RNA {type_LW} basepairs)\")\n\n figure = plt.figure(figsize = (10, 10))\n plt.gcf().subplots_adjust(left = 0.1, bottom = 0.1, right = 0.9, top = 0.9, wspace = 0, hspace = 0.5)\n \n plt.subplot(2, 1, 1)\n GMM_histo(data[\"211_angle\"], f\"{type_LW}_{ntpair}_C1'-B1-B1pair\", scan, toric=True, hist=False, col='cyan' )\n GMM_histo(data[\"112_angle\"], f\"{type_LW}_{ntpair}_B1-B1pair-C1'pair\", scan, toric=True, hist=False, col='magenta')\n GMM_histo(data[\"3211_torsion\"], f\"{type_LW}_{ntpair}_C4'-C1'-B1-B1pair\", scan, toric=True, hist=False, col='black' )\n GMM_histo(data[\"1123_torsion\"], f\"{type_LW}_{ntpair}_B1-B1pair-C1'pair-C4'pair\", scan, toric=True, hist=False, col='maroon')\n GMM_histo(data[\"alpha1\"], f\"{type_LW}_{ntpair}_alpha_1\", scan, toric=True, hist=False, col=\"yellow\")\n GMM_histo(data[\"alpha2\"], f\"{type_LW}_{ntpair}_alpha_2\", scan, toric=True, hist=False, col='olive')\n plt.xlabel(\"Angle (degree)\")\n plt.title(f\"GMM of plane angles for {type_LW} {ntpair} basepairs\", fontsize=10)\n\n plt.subplot(2, 1, 2)\n GMM_histo(data[\"Distance\"], f\"{type_LW}_{ntpair}_tips_distance\", scan, toric=False, hist=False, col=\"cyan\")\n GMM_histo(data[\"dB1\"], f\"{type_LW}_{ntpair}_dB1\", scan, toric=False, hist=False, col=\"tomato\")\n GMM_histo(data[\"dB2\"], f\"{type_LW}_{ntpair}_dB2\", scan, toric=False, hist=False, col=\"goldenrod\")\n plt.xlabel(\"Distance (Angströms)\")\n plt.title(f\"GMM of distances for {type_LW} {ntpair} basepairs\", fontsize=10)\n \n plt.savefig(f\"{type_LW}_{ntpair}_basepairs.png\" )\n plt.close()\n setproctitle(f\"GMM (HiRE-RNA {type_LW} {ntpair} basepairs) finished\")\n\n@trace_unhandled_exceptions\ndef merge_jsons(do_hrna):\n \"\"\"\n Reads the tons of JSON files produced by the geometric analyses, and compiles them into fewer files.\n It is simple concatenation of the JSONs.\n The original files are then deleted.\n \"\"\"\n\n # All atom distances\n bonds = [\"O3'-P\", \"P-OP1\", \"P-OP2\", \"P-O5'\", \"O5'-C5'\", \"C5'-C4'\", \"C4'-O4'\", \"C4'-C3'\", \"O4'-C1'\", \"C1'-C2'\", \"C2'-O2'\", \"C2'-C3'\", \"C3'-O3'\", \"C1'-N9\",\n \"N9-C8\", \"C8-N7\", \"N7-C5\", \"C5-C6\", \"C6-O6\", \"C6-N6\", \"C6-N1\", \"N1-C2\", \"C2-N2\", \"C2-N3\", \"N3-C4\", \"C4-N9\", \"C4-C5\", \n \"C1'-N1\", \"N1-C6\", \"C6-C5\", \"C5-C4\", \"C4-N3\", \"N3-C2\", \"C2-O2\", \"C2-N1\", \"C4-N4\", \"C4-O4\"]\n bonds = [ runDir + \"/results/geometry/json/\" + x + \".json\" for x in bonds ]\n concat_jsons(bonds, runDir + \"/results/geometry/json/all_atom_distances.json\")\n \n # All atom torsions\n torsions = [\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Xhi\", \"Zeta\"]\n torsions = [ runDir + \"/results/geometry/json/\" + x + \".json\" for x in torsions ]\n concat_jsons(torsions, runDir + \"/results/geometry/json/all_atom_torsions.json\")\n \n # Delete previous files\n for f in bonds + torsions:\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n\n if do_hrna:\n # HiRE-RNA distances\n hrnabonds = [r\"P-O5'\", r\"O5'-C5'\", r\"C5'-C4'\", r\"C4'-C1'\", r\"C1'-B1\", r\"B1-B2\", r\"C4'-P\"]\n hrnabonds = [ runDir + \"/results/geometry/json/\" + x + \".json\" for x in hrnabonds ]\n concat_jsons(hrnabonds, runDir + \"/results/geometry/json/hirerna_distances.json\")\n\n # HiRE-RNA angles\n hrnaangles = [r\"P-O5'-C5'\", r\"O5'-C5'-C4'\", r\"C5'-C4'-C1'\", r\"C4'-C1'-B1\", r\"C1'-B1-B2\", r\"C4'-P-O5'\", r\"C5'-C4'-P\", r\"C1'-C4'-P\"]\n hrnaangles = [ runDir + \"/results/geometry/json/\" + x + \".json\" for x in hrnaangles ]\n concat_jsons(hrnaangles, runDir + \"/results/geometry/json/hirerna_angles.json\")\n\n # HiRE-RNA torsions\n hrnators = [r\"P-O5'-C5'-C4'\", r\"O5'-C5'-C4'-C1'\", r\"C5'-C4'-C1'-B1\", r\"C4'-C1'-B1-B2\", r\"C4'-P°-O5'°-C5'°\", r\"C5'-C4'-P°-O5'°\", r\"C1'-C4'-P°-O5'°\", r\"O5'-C5'-C4'-P°\"]\n hrnators = [ runDir + \"/results/geometry/json/\" + x + \".json\" for x in hrnators ]\n concat_jsons(hrnators, runDir + \"/results/geometry/json/hirerna_torsions.json\")\n\n # HiRE-RNA basepairs\n for nt1 in ['A', 'C', 'G', 'U']:\n for nt2 in ['A', 'C', 'G', 'U']:\n bps = glob.glob(runDir + f\"/results/geometry/json/*{nt1}{nt2}*.json\")\n concat_jsons(bps, runDir + f\"/results/geometry/json/hirerna_{nt1}{nt2}_basepairs.json\")\n\n # Delete previous files\n for f in hrnabonds + hrnaangles + hrnators:\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n for f in glob.glob(runDir + \"/results/geometry/json/t*.json\"):\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n for f in glob.glob(runDir + \"/results/geometry/json/c*.json\"):\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n for f in glob.glob(runDir + \"/results/geometry/json/*tips_distance.json\"):\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n \n@trace_unhandled_exceptions\ndef concat_worker(bunch):\n \"\"\"\n Concatenates a bunch of CSV files and returns a Pandas DataFrame.\n bunch: List of strings (filepaths to CSV files)\n\n The function logs concatenations to a global TQDM progress bar.\n The function is expected to be used in parallel.\n \"\"\"\n\n global sharedpbar\n global finished\n\n # initiate the dataframe with the first CSV file\n df_tot = pd.read_csv(bunch.pop(), engine=\"c\")\n with finished.get_lock():\n finished.value += 1\n\n for f in range(len(bunch)):\n # Read and concatenate a new file\n df = pd.read_csv(bunch.pop(), engine='c')\n df_tot = pd.concat([df_tot, df], ignore_index=True)\n\n # Update the global progress bar\n with finished.get_lock():\n finished.value += 1\n with sharedpbar.get_lock():\n sharedpbar.n = finished.value\n sharedpbar.refresh()\n\n return df_tot\n\n@trace_unhandled_exceptions\ndef concat_dataframes(fpath, outfilename, nworkers):\n \"\"\"\n Concatenates the CSV files from fpath folder into a DataFrame gathering all.\n The function splits the file list into nworkers concatenation workers, and then merges the nworkers dataframes.\n \"\"\"\n setproctitle(f\"Concatenation of {fpath}\")\n\n # Get the list of files\n flist = os.listdir(fpath)\n random.shuffle(flist)\n flist = [ os.path.abspath(fpath + x) for x in flist ]\n\n # Define a global progress bar to be shared between workers\n global sharedpbar\n global finished\n sharedpbar = tqdm(total=len(flist), position=0, desc=\"Preparing \"+outfilename, leave=False)\n finished = Value('i', 0)\n\n # Divide the list into chunks\n start = 0\n end = int(len(flist)/nworkers)+1\n size = end\n chunks = []\n for i in range(nworkers):\n if i == nworkers-1:\n chunks.append(flist[start:])\n else:\n chunks.append(flist[start:end])\n start, end = end, end+size\n\n # Run parallel concatenations\n p = Pool(initializer=init_with_tqdm, initargs=(tqdm.get_lock(),), processes=nworkers)\n results = p.map(concat_worker, chunks, chunksize=1)\n p.close()\n p.join()\n sharedpbar.close()\n\n # Concatenate the results and save\n df_tot = pd.concat(results, ignore_index=True)\n df_tot.to_csv(fpath + outfilename)\n\n@trace_unhandled_exceptions\ndef concat_jsons(flist, outfilename):\n \"\"\"\n Reads JSON files computed by the geometry jobs and merge them into a smaller\n number of files\n \"\"\"\n \n result = []\n for f in flist:\n if not os.path.isfile(f):\n warn(\"Unable to find \"+f.split('/')[-1])\n continue\n with open(f, \"rb\") as infile:\n result.append(json.load(infile))\n\n # write the files\n with open(outfilename, 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=4)\n\nif __name__ == \"__main__\":\n print(\"This file is not supposed to be run directly. Run statistics.py instead.\")"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.sqrt",
"numpy.linspace",
"pandas.DataFrame",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca",
"numpy.arange",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"pandas.read_sql",
"matplotlib.pyplot.figure",
"pandas.concat",
"matplotlib.pyplot.title",
"numpy.isnan",
"numpy.arccos",
"matplotlib.pyplot.savefig",
"sklearn.mixture.GaussianMixture",
"numpy.array",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"scipy.stats.norm.pdf",
"matplotlib.pyplot.xlabel"
]
] |
wolframalexa/taming-transformers
|
[
"41732cda0ce9579efba643d516b472e0e9dc7679"
] |
[
"main.py"
] |
[
"import argparse, os, sys, datetime, glob, importlib\nfrom omegaconf import OmegaConf\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torchvision\nfrom torch.utils.data import random_split, DataLoader, Dataset\nimport pytorch_lightning as pl\nfrom pytorch_lightning import seed_everything\nfrom pytorch_lightning.trainer import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor\nfrom pytorch_lightning.utilities.distributed import rank_zero_only\n\nfrom taming.data.utils import custom_collate\n\n\ndef get_obj_from_str(string, reload=False):\n module, cls = string.rsplit(\".\", 1)\n if reload:\n module_imp = importlib.import_module(module)\n importlib.reload(module_imp)\n return getattr(importlib.import_module(module, package=None), cls)\n\n\ndef get_parser(**parser_kwargs):\n def str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\"):\n return True\n elif v.lower() in (\"no\", \"false\", \"f\", \"n\", \"0\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected.\")\n\n parser = argparse.ArgumentParser(**parser_kwargs)\n parser.add_argument(\n \"-n\",\n \"--name\",\n type=str,\n const=True,\n default=\"\",\n nargs=\"?\",\n help=\"postfix for logdir\",\n )\n parser.add_argument(\n \"-r\",\n \"--resume\",\n type=str,\n const=True,\n default=\"\",\n nargs=\"?\",\n help=\"resume from logdir or checkpoint in logdir\",\n )\n parser.add_argument(\n \"-b\",\n \"--base\",\n nargs=\"*\",\n metavar=\"base_config.yaml\",\n help=\"paths to base configs. Loaded from left-to-right. \"\n \"Parameters can be overwritten or added with command-line options of the form `--key value`.\",\n default=list(),\n )\n parser.add_argument(\n \"-t\",\n \"--train\",\n type=str2bool,\n const=True,\n default=False,\n nargs=\"?\",\n help=\"train\",\n )\n parser.add_argument(\n \"--no-test\",\n type=str2bool,\n const=True,\n default=False,\n nargs=\"?\",\n help=\"disable test\",\n )\n parser.add_argument(\"-p\", \"--project\", help=\"name of new or path to existing project\")\n parser.add_argument(\n \"-d\",\n \"--debug\",\n type=str2bool,\n nargs=\"?\",\n const=True,\n default=False,\n help=\"enable post-mortem debugging\",\n )\n parser.add_argument(\n \"-s\",\n \"--seed\",\n type=int,\n default=23,\n help=\"seed for seed_everything\",\n )\n parser.add_argument(\n \"-f\",\n \"--postfix\",\n type=str,\n default=\"\",\n help=\"post-postfix for default name\",\n )\n\n return parser\n\n\ndef nondefault_trainer_args(opt):\n parser = argparse.ArgumentParser()\n parser = Trainer.add_argparse_args(parser)\n args = parser.parse_args([])\n return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))\n\n\ndef instantiate_from_config(config):\n if not \"target\" in config:\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))\n\n\nclass WrappedDataset(Dataset):\n \"\"\"Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset\"\"\"\n def __init__(self, dataset):\n self.data = dataset\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n return self.data[idx]\n\n\nclass DataModuleFromConfig(pl.LightningDataModule):\n def __init__(self, batch_size, train=None, validation=None, test=None,\n wrap=False, num_workers=None):\n super().__init__()\n self.batch_size = batch_size\n self.dataset_configs = dict()\n self.num_workers = num_workers if num_workers is not None else batch_size*2\n if train is not None:\n self.dataset_configs[\"train\"] = train\n self.train_dataloader = self._train_dataloader\n if validation is not None:\n self.dataset_configs[\"validation\"] = validation\n self.val_dataloader = self._val_dataloader\n if test is not None:\n self.dataset_configs[\"test\"] = test\n self.test_dataloader = self._test_dataloader\n self.wrap = wrap\n\n def prepare_data(self):\n for data_cfg in self.dataset_configs.values():\n instantiate_from_config(data_cfg)\n\n def setup(self, stage=None):\n self.datasets = dict(\n (k, instantiate_from_config(self.dataset_configs[k]))\n for k in self.dataset_configs)\n if self.wrap:\n for k in self.datasets:\n self.datasets[k] = WrappedDataset(self.datasets[k])\n\n def _train_dataloader(self):\n return DataLoader(self.datasets[\"train\"], batch_size=self.batch_size,\n num_workers=self.num_workers, shuffle=True, collate_fn=custom_collate)\n\n def _val_dataloader(self):\n return DataLoader(self.datasets[\"validation\"],\n batch_size=self.batch_size,\n num_workers=self.num_workers, collate_fn=custom_collate)\n\n def _test_dataloader(self):\n return DataLoader(self.datasets[\"test\"], batch_size=self.batch_size,\n num_workers=self.num_workers, collate_fn=custom_collate)\n\n\nclass SetupCallback(Callback):\n def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):\n super().__init__()\n self.resume = resume\n self.now = now\n self.logdir = logdir\n self.ckptdir = ckptdir\n self.cfgdir = cfgdir\n self.config = config\n self.lightning_config = lightning_config\n\n def on_pretrain_routine_start(self, trainer, pl_module):\n if trainer.global_rank == 0:\n # Create logdirs and save configs\n os.makedirs(self.logdir, exist_ok=True)\n os.makedirs(self.ckptdir, exist_ok=True)\n os.makedirs(self.cfgdir, exist_ok=True)\n\n# print(\"Project config\")\n# print(self.config.pretty())\n\n OmegaConf.save(self.config,\n os.path.join(self.cfgdir, \"{}-project.yaml\".format(self.now)))\n\n# print(\"Lightning config\")\n# print(self.lightning_config.pretty())\n OmegaConf.save(OmegaConf.create({\"lightning\": self.lightning_config}),\n os.path.join(self.cfgdir, \"{}-lightning.yaml\".format(self.now)))\n\n else:\n # ModelCheckpoint callback created log directory --- remove it\n if not self.resume and os.path.exists(self.logdir):\n dst, name = os.path.split(self.logdir)\n dst = os.path.join(dst, \"child_runs\", name)\n os.makedirs(os.path.split(dst)[0], exist_ok=True)\n try:\n os.rename(self.logdir, dst)\n except FileNotFoundError:\n pass\n\n\nclass ImageLogger(Callback):\n def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True):\n super().__init__()\n self.batch_freq = batch_frequency\n self.max_images = max_images\n self.logger_log_images = {\n pl.loggers.WandbLogger: self._wandb,\n pl.loggers.TestTubeLogger: self._testtube,\n }\n self.log_steps = [2 ** n for n in range(int(np.log2(self.batch_freq)) + 1)]\n if not increase_log_steps:\n self.log_steps = [self.batch_freq]\n self.clamp = clamp\n\n @rank_zero_only\n def _wandb(self, pl_module, images, batch_idx, split):\n raise ValueError(\"No way wandb\")\n grids = dict()\n for k in images:\n grid = torchvision.utils.make_grid(images[k])\n grids[f\"{split}/{k}\"] = wandb.Image(grid)\n pl_module.logger.experiment.log(grids)\n\n @rank_zero_only\n def _testtube(self, pl_module, images, batch_idx, split):\n for k in images:\n grid = torchvision.utils.make_grid(images[k])\n grid = (grid+1.0)/2.0 # -1,1 -> 0,1; c,h,w\n\n tag = f\"{split}/{k}\"\n pl_module.logger.experiment.add_image(\n tag, grid,\n global_step=pl_module.global_step)\n\n @rank_zero_only\n def log_local(self, save_dir, split, images,\n global_step, current_epoch, batch_idx):\n root = os.path.join(save_dir, \"images\", split)\n for k in images:\n grid = torchvision.utils.make_grid(images[k], nrow=4)\n\n grid = (grid+1.0)/2.0 # -1,1 -> 0,1; c,h,w\n grid = grid.transpose(0,1).transpose(1,2).squeeze(-1)\n grid = grid.numpy()\n grid = (grid*255).astype(np.uint8)\n filename = \"{}_gs-{:06}_e-{:06}_b-{:06}.png\".format(\n k,\n global_step,\n current_epoch,\n batch_idx)\n path = os.path.join(root, filename)\n os.makedirs(os.path.split(path)[0], exist_ok=True)\n Image.fromarray(grid).save(path)\n\n def log_img(self, pl_module, batch, batch_idx, split=\"train\"):\n if (self.check_frequency(batch_idx) and # batch_idx % self.batch_freq == 0\n hasattr(pl_module, \"log_images\") and\n callable(pl_module.log_images) and\n self.max_images > 0):\n logger = type(pl_module.logger)\n\n is_train = pl_module.training\n if is_train:\n pl_module.eval()\n\n with torch.no_grad():\n images = pl_module.log_images(batch, split=split, pl_module=pl_module)\n\n for k in images:\n N = min(images[k].shape[0], self.max_images)\n images[k] = images[k][:N]\n if isinstance(images[k], torch.Tensor):\n images[k] = images[k].detach().cpu()\n if self.clamp:\n images[k] = torch.clamp(images[k], -1., 1.)\n\n self.log_local(pl_module.logger.save_dir, split, images,\n pl_module.global_step, pl_module.current_epoch, batch_idx)\n\n logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)\n logger_log_images(pl_module, images, pl_module.global_step, split)\n\n if is_train:\n pl_module.train()\n\n def check_frequency(self, batch_idx):\n if (batch_idx % self.batch_freq) == 0 or (batch_idx in self.log_steps):\n try:\n self.log_steps.pop(0)\n except IndexError:\n pass\n return True\n return False\n\n def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):\n self.log_img(pl_module, batch, batch_idx, split=\"train\")\n\n def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):\n self.log_img(pl_module, batch, batch_idx, split=\"val\")\n\n\n\nif __name__ == \"__main__\":\n # custom parser to specify config files, train, test and debug mode,\n # postfix, resume.\n # `--key value` arguments are interpreted as arguments to the trainer.\n # `nested.key=value` arguments are interpreted as config parameters.\n # configs are merged from left-to-right followed by command line parameters.\n\n # model:\n # base_learning_rate: float\n # target: path to lightning module\n # params:\n # key: value\n # data:\n # target: main.DataModuleFromConfig\n # params:\n # batch_size: int\n # wrap: bool\n # train:\n # target: path to train dataset\n # params:\n # key: value\n # validation:\n # target: path to validation dataset\n # params:\n # key: value\n # test:\n # target: path to test dataset\n # params:\n # key: value\n # lightning: (optional, has sane defaults and can be specified on cmdline)\n # trainer:\n # additional arguments to trainer\n # logger:\n # logger to instantiate\n # modelcheckpoint:\n # modelcheckpoint to instantiate\n # callbacks:\n # callback1:\n # target: importpath\n # params:\n # key: value\n\n now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\")\n\n # add cwd for convenience and to make classes in this file available when\n # running as `python main.py`\n # (in particular `main.DataModuleFromConfig`)\n sys.path.append(os.getcwd())\n\n parser = get_parser()\n parser = Trainer.add_argparse_args(parser)\n\n opt, unknown = parser.parse_known_args()\n if opt.name and opt.resume:\n raise ValueError(\n \"-n/--name and -r/--resume cannot be specified both.\"\n \"If you want to resume training in a new log folder, \"\n \"use -n/--name in combination with --resume_from_checkpoint\"\n )\n if opt.resume:\n if not os.path.exists(opt.resume):\n raise ValueError(\"Cannot find {}\".format(opt.resume))\n if os.path.isfile(opt.resume):\n paths = opt.resume.split(\"/\")\n idx = len(paths)-paths[::-1].index(\"logs\")+1\n logdir = \"/\".join(paths[:idx])\n ckpt = opt.resume\n else:\n assert os.path.isdir(opt.resume), opt.resume\n logdir = opt.resume.rstrip(\"/\")\n ckpt = os.path.join(logdir, \"checkpoints\", \"last.ckpt\")\n\n opt.resume_from_checkpoint = ckpt\n base_configs = sorted(glob.glob(os.path.join(logdir, \"configs/*.yaml\")))\n opt.base = base_configs+opt.base\n _tmp = logdir.split(\"/\")\n nowname = _tmp[_tmp.index(\"logs\")+1]\n else:\n if opt.name:\n name = \"_\"+opt.name\n elif opt.base:\n cfg_fname = os.path.split(opt.base[0])[-1]\n cfg_name = os.path.splitext(cfg_fname)[0]\n name = \"_\"+cfg_name\n else:\n name = \"\"\n nowname = now+name+opt.postfix\n logdir = os.path.join(\"logs\", nowname)\n\n ckptdir = os.path.join(logdir, \"checkpoints\")\n cfgdir = os.path.join(logdir, \"configs\")\n seed_everything(opt.seed)\n\n try:\n # init and save configs\n print(\"opt.base\",opt.base)\n configs = [OmegaConf.load(cfg) for cfg in opt.base]\n cli = OmegaConf.from_dotlist(unknown)\n config = OmegaConf.merge(*configs, cli)\n lightning_config = config.pop(\"lightning\", OmegaConf.create())\n # merge trainer cli with config\n trainer_config = lightning_config.get(\"trainer\", OmegaConf.create())\n # default to ddp\n trainer_config[\"distributed_backend\"] = \"ddp\"\n for k in nondefault_trainer_args(opt):\n trainer_config[k] = getattr(opt, k)\n if not \"gpus\" in trainer_config:\n del trainer_config[\"distributed_backend\"]\n cpu = True\n else:\n gpuinfo = trainer_config[\"gpus\"]\n print(f\"Running on GPUs {gpuinfo}\")\n cpu = False\n trainer_opt = argparse.Namespace(**trainer_config)\n lightning_config.trainer = trainer_config\n\n # model\n model = instantiate_from_config(config.model)\n\n # trainer and callbacks\n trainer_kwargs = dict()\n\n # default logger configs\n # NOTE wandb < 0.10.0 interferes with shutdown\n # wandb >= 0.10.0 seems to fix it but still interferes with pudb\n # debugging (wrongly sized pudb ui)\n # thus prefer testtube for now\n default_logger_cfgs = {\n \"wandb\": {\n \"target\": \"pytorch_lightning.loggers.WandbLogger\",\n \"params\": {\n \"name\": nowname,\n \"save_dir\": logdir,\n \"offline\": opt.debug,\n \"id\": nowname,\n }\n },\n \"testtube\": {\n \"target\": \"pytorch_lightning.loggers.TestTubeLogger\",\n \"params\": {\n \"name\": \"testtube\",\n \"save_dir\": logdir,\n }\n },\n }\n default_logger_cfg = default_logger_cfgs[\"testtube\"]\n logger_cfg = OmegaConf.create()\n logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)\n trainer_kwargs[\"logger\"] = instantiate_from_config(logger_cfg)\n\n # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to\n # specify which metric is used to determine best models\n default_modelckpt_cfg = {\n \"target\": \"pytorch_lightning.callbacks.ModelCheckpoint\",\n \"params\": {\n \"dirpath\": ckptdir,\n \"filename\": \"{epoch:06}\",\n \"verbose\": True,\n \"save_last\": True,\n }\n }\n if hasattr(model, \"monitor\"):\n print(f\"Monitoring {model.monitor} as checkpoint metric.\")\n default_modelckpt_cfg[\"params\"][\"monitor\"] = model.monitor\n default_modelckpt_cfg[\"params\"][\"save_top_k\"] = 3\n\n modelckpt_cfg = OmegaConf.create()\n modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)\n trainer_kwargs[\"checkpoint_callback\"] = instantiate_from_config(modelckpt_cfg)\n\n # add callback which sets up log directory\n default_callbacks_cfg = {\n \"setup_callback\": {\n \"target\": \"main.SetupCallback\",\n \"params\": {\n \"resume\": opt.resume,\n \"now\": now,\n \"logdir\": logdir,\n \"ckptdir\": ckptdir,\n \"cfgdir\": cfgdir,\n \"config\": config,\n \"lightning_config\": lightning_config,\n }\n },\n \"image_logger\": {\n \"target\": \"main.ImageLogger\",\n \"params\": {\n \"batch_frequency\": 750,\n \"max_images\": 4,\n \"clamp\": True\n }\n },\n \"learning_rate_logger\": {\n \"target\": \"main.LearningRateMonitor\",\n \"params\": {\n \"logging_interval\": \"step\",\n #\"log_momentum\": True\n }\n },\n }\n callbacks_cfg = OmegaConf.create()\n callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)\n trainer_kwargs[\"callbacks\"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]\n\n trainer = Trainer.from_argparse_args(trainer_opt, **trainer_kwargs)\n\n # data\n data = instantiate_from_config(config.data)\n # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html\n # calling these ourselves should not be necessary but it is.\n # lightning still takes care of proper multiprocessing though\n data.prepare_data()\n data.setup()\n\n # configure learning rate\n bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate\n if not cpu:\n ngpu = len(lightning_config.trainer.gpus.strip(\",\").split(','))\n else:\n ngpu = 1\n accumulate_grad_batches = 1\n print(f\"accumulate_grad_batches = {accumulate_grad_batches}\")\n lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches\n model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr\n print(\"Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)\".format(\n model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))\n\n # allow checkpointing via USR1\n def melk(*args, **kwargs):\n # run all checkpoint hooks\n if trainer.global_rank == 0:\n print(\"Summoning checkpoint.\")\n ckpt_path = os.path.join(ckptdir, \"last.ckpt\")\n print(\"Checkpoint path:\", ckpt_path)\n trainer.save_checkpoint(ckpt_path)\n\n def divein(*args, **kwargs):\n if trainer.global_rank == 0:\n import pudb; pudb.set_trace()\n\n import signal\n signal.signal(signal.SIGUSR1, melk)\n signal.signal(signal.SIGUSR2, divein)\n\n # run\n if opt.train:\n try:\n trainer.fit(model, data)\n except Exception:\n melk()\n raise\n if not opt.no_test and not trainer.interrupted:\n trainer.test(model, data)\n except Exception:\n if opt.debug and trainer.global_rank==0:\n try:\n import pudb as debugger\n except ImportError:\n import pdb as debugger\n debugger.post_mortem()\n raise\n finally:\n # move newly created debug project to debug_runs\n if opt.debug and not opt.resume and trainer.global_rank==0:\n dst, name = os.path.split(logdir)\n dst = os.path.join(dst, \"debug_runs\", name)\n os.makedirs(os.path.split(dst)[0], exist_ok=True)\n os.rename(logdir, dst)\n"
] |
[
[
"torch.no_grad",
"torch.clamp",
"numpy.log2",
"torch.utils.data.DataLoader"
]
] |
LinkGeoML/EnsembleToponymInterlinking
|
[
"ccfdf2d5d1d901136d7aa73993255e96c6f1a43c"
] |
[
"StringMatching/main.py"
] |
[
"import argparse\r\nimport glob\r\nimport pandas as pd\r\nimport pickle\r\nimport torch\r\nfrom RSModel import RSModel\r\nfrom RSPoolModel import RSPoolModel\r\nfrom RSPenTanhModel import RSPenTanhModel\r\nfrom RSPenTanhPoolModel import RSPenTanhPoolModel\r\nfrom RSHardAttentionModel import RSHardAttentionModel\r\nfrom TransformerModel import TransformerModel\r\nfrom RTransformerModel import RTransformerModel, RMogrifierTransformerModel\r\nfrom TransformerInteractionModel import TransformerInteractionModel\r\nfrom RSPenTanhHardAttentionModel import RSPenTanhHardAttentionModel\r\nfrom MogrifierLSTMModel import MogrifierLSTMModel\r\nfrom SHARNNModel import SHARNNModel\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping\r\nfrom pytorch_lightning import Trainer\r\n\r\ntorch.manual_seed(0)\r\ntorch.backends.cudnn.deterministic=True\r\ntorch.backends.cudnn.benchmark=False\r\n\r\n# Define arguments to be passed by the user #\r\nparser=argparse.ArgumentParser()\r\nparser.add_argument('--model', help='What model')\r\nparser.add_argument('--train', help='What dataset to train on')\r\nparser.add_argument('--test', help='What dataset to test on')\r\nargs=parser.parse_args()\r\n#############################################\r\n\r\nmodels = {'rs':RSModel, 'rs_pool':RSPoolModel, 'rs_pentanh':RSPenTanhModel, 'rs_pentanh_pool':RSPenTanhPoolModel, 'rs_hardatt':RSHardAttentionModel, \\\r\n 'rs_pentanh_hardatt':RSPenTanhHardAttentionModel, 'transformer':TransformerModel, 'r_transformer': RTransformerModel, \\\r\n 'mogrifier_lstm': MogrifierLSTMModel, 'r_mogrifier_transformer': RMogrifierTransformerModel, 'transformer_interaction': TransformerInteractionModel, 'sha_rnn': SHARNNModel }\r\n\r\nmodel = models[args.model](args.model, args.train, args.test)\r\n\r\nearly_stop_callback = EarlyStopping(\r\n monitor='loss',\r\n min_delta=0.00,\r\n patience=3,\r\n verbose=True,\r\n mode='min'\r\n)\r\n\r\ntrainer = Trainer(gpus=1, \\\r\n show_progress_bar=True, \\\r\n max_nb_epochs=20, \\\r\n early_stop_callback=early_stop_callback)\r\n\r\ntry:\r\n model.load_state_dict(torch.load('weights/{}-{}.pt'.format(args.model, args.train)),strict=True)\r\n print(\"Successfully loaded weights\")\r\nexcept:\r\n trainer.fit(model)\r\n\r\n#trainer.fit(model)\r\ntrainer.test(model)\r\n"
] |
[
[
"torch.manual_seed"
]
] |
jegork/tf-pose-estimation
|
[
"d277dcfc372da1d63a55c8fb6538ed3259b795e3"
] |
[
"create_video.py"
] |
[
"import argparse\nimport logging\nimport time\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tf_pose.estimator import TfPoseEstimator\nfrom tf_pose.networks import get_graph_path, model_wh\n\nlogger = logging.getLogger('TfPoseEstimator-Video')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nfps_time = 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='tf-pose-estimation Video')\n parser.add_argument('--video', type=str, default='')\n parser.add_argument('--resolution', type=str, default='432x368', help='network input resolution. default=432x368')\n parser.add_argument('--model', type=str, default='mobilenet_thin', help='cmu / mobilenet_thin / mobilenet_v2_large / mobilenet_v2_small')\n parser.add_argument('--show-process', type=bool, default=False,\n help='for debug purpose, if enabled, speed for inference is dropped.')\n parser.add_argument('--showBG', type=bool, default=True, help='False to show skeleton only.')\n args = parser.parse_args()\n\n logger.debug('initialization %s : %s' % (args.model, get_graph_path(args.model)))\n w, h = model_wh(args.resolution)\n \n out_file = (args.video).split('.')[-2]\n fourcc = cv2.VideoWriter_fourcc(*'MPEG')\n cap = cv2.VideoCapture(args.video)\n width = cap.get(3)\n height = cap.get(4)\n out = cv2.VideoWriter(out_file + '_out.avi', fourcc, 20.0, (int(width), int(height)))\n e = TfPoseEstimator(get_graph_path(args.model), target_size=(int(width), int(height)))\n\n\n if cap.isOpened() is False:\n print(\"Error opening video stream or file\")\n while cap.isOpened():\n ret_val, image = cap.read()\n\n if image is None:\n break\n\n humans = e.inference(image, upsample_size=4.0)\n if not args.showBG:\n image = np.zeros(image.shape)\n image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)\n\n cv2.putText(image, \"FPS: %f\" % (1.0 / (time.time() - fps_time)), (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n out.write(image)\n\n fps_time = time.time()\n \nlogger.debug('finished+')\n"
] |
[
[
"numpy.zeros"
]
] |
ai-se/bellwether-configuration
|
[
"921ec881b17f29ed73bdb5b4510c2a30a6d23ef4"
] |
[
"src/RQ3/metrics.py"
] |
[
"import numpy as np\n\n\ndef rank_diff(actual, predicted):\n actual_ranks = np.argsort(actual).tolist()[0]\n predicted_ranks = predicted[actual_ranks]\n diff = abs(actual_ranks - predicted_ranks)\n return diff\n"
] |
[
[
"numpy.argsort"
]
] |
rionbr/smm4h
|
[
"6009ed7800884ab37b7080c8c825c30f501b6942"
] |
[
"include/termdictparser.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nTerm Dictionary Parser\n==========================\n\nClasses to handle multi-word-token building and the parsing of sentences to extract matched terms.\n\nFor performance, both One-word-terms and multi-word-terms are handled using the `treelib` implementation of a Tree.\n\nRequirements:\n - `treelib`: `pip install treelib`\n\n\"\"\"\n# Copyright (C) 2016 by\n# Rion Brattig Correia <[email protected]>\n# Ian B. Wood <[email protected]>\n# All rights reserved.\n# MIT license.\nfrom treelib import Tree\ntry:\n import re2 as re\nexcept ImportError:\n import re\nelse:\n re.set_fallback_notification(re.FALLBACK_WARNING)\nfrom nltk.tokenize import PunktSentenceTokenizer, TweetTokenizer, sent_tokenize\nfrom nltk.stem import PorterStemmer, WordNetLemmatizer\n\n__author__ = \"\"\"\\n\"\"\".join([\n 'Rion Brattig Correia <[email protected]>',\n 'Ian B. Wood <[email protected]>'\n])\n\n__all__ = ['TermDictionaryParser']\n#\n\nclass Match(object):\n \"\"\"\n \"\"\"\n def __init__(self, id=None, tokens=tuple, si=None, wi=None, ti=None):\n self.id = id\n self.tokens = tokens\n self.si = si # sentence i\n self.wi = wi # token i start\n self.ti = ti # token i end\n\n def __str__(self):\n return u\"<Match(id=%s, tokens=%s>\" % (self.id, self.tokens)\n\n\nclass Sentence(object):\n \"\"\"\n\n \"\"\"\n def __init__(self, text, id=None):\n self.id = id # possible multiple ids\n self.text = self.text_pp = text\n\n def preprocess(self, lower=False, remove_hash=False, remove_mentions=False, remove_url=False, remove_newline=False):\n if lower:\n self.text_pp = self.text_pp.lower()\n if remove_hash:\n self.text_pp = self.text_pp.replace('#', '')\n if remove_mentions:\n self.text_pp = re.sub('@[a-z0-9_]+', '', self.text_pp)\n if remove_url:\n self.text_pp = re.sub(r\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\", '', self.text_pp)\n if remove_newline:\n self.text_pp = self.text_pp.replace('\\r\\n', ' ').replace('\\n', ' ').replace('\\r', ' ')\n return self\n\n def re_tokenize(self, re=r\"[a-zA-Z0-9(-+.)']+\"):\n \"\"\"\n Args:\n re (string): Regular Expression string used to separates the tokens. Default: `[\\w']+`\n\n \"\"\"\n if re is None:\n self.tokens_sentences = [self.text_pp.split()]\n else:\n self.tokens_sentences = re.findall(re, self.text_pp, re.UNICODE)\n return self\n\n def tokenize(self, tokenizer=TweetTokenizer()):\n self.tokens_sentences = [tokenizer.tokenize(t) for t in sent_tokenize(self.text_pp)]\n return self\n\n def stemm(self, stemmer=PorterStemmer(), *args, **kwargs):\n self.tokens_sentences = [[stemmer.stem(token, *args, **kwargs) for token in tokens] for tokens in self.tokens_sentences]\n return self\n\n def lemmatize(self, lemmatizer=WordNetLemmatizer(), *args, **kwargs):\n self.tokens_sentences = [[lemmatizer.lemmatize(token, *args, **kwargs) for token in tokens] for tokens in self.tokens_sentences]\n return self\n\n def match_tokens(self, parser=None):\n self.matches = [Match(id, tokens, si, wi, ti) for (id, tokens, si, wi, ti) in parser.match_tokens(self.tokens_sentences)]\n return self\n\n def has_match(self):\n \"\"\" Returns True if there are matches, False otherwise\"\"\"\n return (True if len(self.matches) else False)\n\n def get_matches(self):\n return self.matches\n\n def get_unique_matches(self):\n seen = set()\n return [seen.add(obj.tokens) or obj for obj in self.matches if obj.tokens not in seen]\n\n def tag_sentence(self, html_tag=\"<match>\\\\1</match>\"):\n \"\"\" Tags the sentence \"\"\"\n if self.has_match():\n matches_sorted = sorted(self.matches, key=lambda x: len(x.tokens), reverse=True)\n tokens = [' '.join(m.tokens) for m in matches_sorted]\n return re.compile(\"(%s)\" % \"|\".join(map(re.escape, tokens)), re.I | re.UNICODE).sub(html_tag, self.text)\n else:\n return self.text\n\n def __str__(self):\n return \"<Sentence(id={id:} text={text:})>\".format(id=self.id,text=self.text)\n\n\nclass TermDictionaryParser(object):\n \"\"\"\n\n \"\"\"\n def __init__(self):\n\n # An extended `treelib` object, called terms\n self.tokens = Tree()\n self.tokens.create_node('root', 'root', data=WordNodeData(id=None, endTermWord=False))\n\n def __str__(self):\n return \"<TermDicionatyParser()>\"\n\n def build_vocabulary(self, sentences=[]):\n \"\"\" Given a list of terms, builds the Vocabulary.\n\n Args:\n sentences (list): A list of Sentence objects\n\n Return:\n Nothing\n \"\"\"\n wtree = self.tokens\n root = self.tokens.get_node('root')\n for sentence in sentences:\n id = sentence.id\n wordlist = [token for tokens in sentence.tokens_sentences for token in tokens]\n\n nodes = list()\n term_size = len(wordlist)\n\n for i, word in enumerate(wordlist, start=1):\n # Parent is root or last inserted node\n parent = root if len(nodes) == 0 else nodes[-1]\n # Is the last word in the term?\n if i < term_size:\n endTermWord = False\n else:\n endTermWord = True\n # NodeIdentifier\n if i == 1:\n identifier = u'-'.join([str(i) + '.' + word])\n else:\n identifier = u'-'.join([nodes[-1].identifier] + [str(i) + '.' + word])\n\n # print '> Identifier:',identifier\n\n # Node already in the tree?\n node = wtree.get_node(identifier)\n if node:\n # Is this node now a endTermWord?\n if endTermWord and not node.data.endTermWord:\n node.data.id = id\n node.data.endTermWord = endTermWord\n else:\n node = wtree.create_node(word,\n identifier,\n parent=parent.identifier,\n data=WordNodeData(id=id if endTermWord else None, endTermWord=endTermWord)\n )\n nodes.append(node)\n\n def make_identifier(self, tokenseq, starti, endi):\n \"\"\"Separate identifier creation \"\"\"\n idstring = ''\n maxi = endi - starti - 1\n for i in range(endi - starti):\n idstring += str(i + 1) + '.' + tokenseq[starti + i]\n if not i == maxi:\n idstring += '-'\n return(idstring)\n # return('-'.join( [str(i)+'.'+x for i,x in enumerate(wordseq, start=1)] ))\n\n def get_node(self, tokenseq, starti, endi):\n \"\"\"Get a tree node from a list of words\"\"\"\n identifier = self.make_identifier(tokenseq, starti, endi)\n return(self.tokens.get_node(identifier))\n\n def in_tree(self, tokenseq, starti, endi):\n \"\"\"Check if a list of words corresponds to a node in the tree\"\"\"\n node = self.get_node(tokenseq, starti, endi)\n return(node is not None)\n\n def is_end_term_word(self, tokenseq, starti, endi):\n \"\"\" Check if the list of words corresponds to a finished phrase \"\"\"\n node = self.get_node(tokenseq, starti, endi)\n return(node.data.endTermWord)\n\n def printout(self, tokenseq, starti, endi, pstarti, pendi):\n \"\"\"For debugging, uncomment printout call\"\"\"\n print([tokenseq[starti + i] for i in range(endi - starti)])\n print([tokenseq[pstarti + i] for i in range(pendi - pstarti)])\n\n def match_tokens(self, tokens_sentences, verbose=False):\n \"\"\"\n Matches one- and multi-words-terms from a tokenized sentence.\n\n Args:\n tokens_sentences (list of lists): the already tokenized sentence of tokens. Use `nltk.tokenize` for best results.\n verbose (bool): prints verbose statements.\n\n Returns:\n ParsedSentences (object)\n\n Note:\n use `<TermDictionaryParser object>.terms.show()` to see the term tree structure.\n\n See also:\n build_vocabulary, extract_terms_from_sentence2\n \"\"\"\n matches = list()\n for si, tokens_sentence in enumerate(tokens_sentences):\n tokenlen = len(tokens_sentence)\n wi = 0\n ti = 0\n pi = 0\n while wi < tokenlen:\n pi += 1\n if pi > tokenlen:\n if wi != ti:\n node = self.get_node(tokens_sentence, wi, ti)\n matches.append((node.data.id, tuple(tokens_sentence[wi:ti]), si, wi, ti))\n wi = ti\n pi = wi\n else:\n wi += 1\n ti += 1\n pi = wi\n else:\n if self.in_tree(tokens_sentence, wi, pi):\n if self.is_end_term_word(tokens_sentence, wi, pi):\n ti = pi\n else:\n if wi != ti:\n node = self.get_node(tokens_sentence, wi, ti)\n matches.append((node.data.id, tuple(tokens_sentence[wi:ti]), si, wi, ti))\n wi = ti\n pi = wi\n else:\n wi += 1\n ti += 1\n pi = wi\n return matches\n\n\nclass WordNodeData(object):\n \"\"\" A simple object to hold end-term-word in the tree nodes.\n Used when there are multiple multi-word terms, and some are complete words withing the tree structure.\n Also included are the original id and type of the term (drug, symp, etc).\n Example: `weight loss` and `weight loss diet` are both terms and belong to the same tree branch.\n \"\"\"\n def __init__(self, endTermWord=False, type=None, id=None):\n self.id = id\n self.endTermWord = endTermWord\n\n\n#\n# DEBug\n#\nif __name__ == '__main__':\n\n import pandas as pd\n tdp = TermDictionaryParser()\n\n print('--- Build Vocabulary ---')\n dfV = pd.DataFrame(\n [\n (1, u'asthma/bronchitis'),\n (2, u'linhaça'), # unicode characteç'\n (u'D03', u'ADHD'), # acym\n (u'D02', u'N.E.E.'), # acym\n (u'DB01', u'fluoxetine'),\n (3, u'weight loss diet'),\n (4, u'weight gain diet'),\n (3, u'losing weight'),\n (3, u'losing weight'),\n (10, u'brain cancer'),\n (10, u'brain cancer carcinoma'),\n (10, u'brain cancer carcinoma twice'),\n (13, u\"breast cancer\"),\n (14, u\"cancer\"),\n (20, u\"partial seizures, complex\"),\n (50, u\"first\"),\n (51, u\"second\"),\n (52, u'third'),\n (53, u'second third'),\n (54, u\"first second third fourth\"),\n ((61, 62, 63), u\"Multi Vitamins\"),\n ], columns=['id', 'text'])\n\n def build_sentences(row):\n return Sentence(id=row['id'], text=row['text']).preprocess(lower=True).re_tokenize(re=None).lemmatize(pos='v')\n\n dfV['sentences'] = dfV.apply(build_sentences, axis=1)\n print(dfV)\n\n tdp.build_vocabulary(dfV['sentences'].values)\n print(tdp.tokens.show(data_property=None))\n\n print('--- Sequence (1) Extraction ---')\n s1 = u\"I am having FLuoXeTiNe high ADHD, ADHD! #LINHAÇA! losing weight but not because I'm doing a weight lossing diet, linhaça. It's my Nerve block back again with FLuoxetine. Perhaps I need to take some multi vitamins. huh nerve. #first. #second.\"\n # s1 = u\"Eu decidi #linhaça o meu amor com todo meu #weight #loss. #first.\"\n s1 = Sentence(s1).preprocess(lower=True, remove_hash=True).re_tokenize(re=None).lemmatize(pos='v').match_tokens(parser=tdp)\n print(s1.tokens_sentences)\n print('S1 Has Matchs: {:b}'.format(s1.has_match()))\n print('S1 (All) Matches:')\n for match in s1.get_matches():\n print(match)\n print('S1 (Unique) Matches')\n for match in s1.get_unique_matches():\n print(match)\n\n print(s1.tag_sentence())\n\n print('--- Sequence (2) Extraction ---')\n \"\"\"\n start = time.time()\n iterations = int(1e3)\n print('max iterations %d'%iterations)\n\n for i in range(iterations):\n if i %1000 == 0:\n print(i)\n s2 = Sentences(u\"I dont have weight any mentions\").preprocess(lower=True).tokenize().match_tokens(parser=tdp)\n s2 = Sentences(u\"Sometimes when you're suffering you forget the people around you but they are suffering with you just in a different way #fibromyalgia #chronicpain #chronicallyill #spoonie #butyoudontlooksick #depression\").tokenize().match_tokens(parser=tdp)\n s2 = Sentences(u\"The grey brain cancer carcinoma twice is for. brain cancer carcinoma three.\").tokenize().match_tokens(parser=tdp)\n s2 = Sentences(u\"Support Women battling Breast Cancer.\").tokenize().match_tokens(parser=tdp)\n s2 = Sentences(u\"I have partial seizures (complex).\").tokenize().match_tokens(parser=tdp)\n s2 = Sentences(u\"I have first second third word\").tokenize().match_tokens(parser=tdp)\n\n end = time.time()\n print(end-start)\n \"\"\"\n"
] |
[
[
"pandas.DataFrame"
]
] |
gachiemchiep/ggcnn
|
[
"0c50aa7600e8a30d44c5c85cebd6e3394a81f30e"
] |
[
"utils/dataset_processing/evaluation.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom .grasp import GraspRectangles, detect_grasps\n\n\ndef plot_output(rgb_img, depth_img, grasp_q_img, grasp_angle_img, no_grasps=1, grasp_width_img=None):\n \"\"\"\n Plot the output of a GG-CNN\n :param rgb_img: RGB Image\n :param depth_img: Depth Image\n :param grasp_q_img: Q output of GG-CNN\n :param grasp_angle_img: Angle output of GG-CNN\n :param no_grasps: Maximum number of grasps to plot\n :param grasp_width_img: (optional) Width output of GG-CNN\n :return:\n \"\"\"\n gs = detect_grasps(grasp_q_img, grasp_angle_img, width_img=grasp_width_img, no_grasps=no_grasps)\n\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(2, 2, 1)\n ax.imshow(rgb_img)\n for g in gs:\n g.plot(ax)\n ax.set_title('RGB')\n ax.axis('off')\n\n ax = fig.add_subplot(2, 2, 2)\n ax.imshow(depth_img, cmap='gray')\n for g in gs:\n g.plot(ax)\n ax.set_title('Depth')\n ax.axis('off')\n\n ax = fig.add_subplot(2, 2, 3)\n plot = ax.imshow(grasp_q_img, cmap='jet', vmin=0, vmax=1)\n ax.set_title('Q')\n ax.axis('off')\n plt.colorbar(plot)\n\n ax = fig.add_subplot(2, 2, 4)\n plot = ax.imshow(grasp_angle_img, cmap='hsv', vmin=-np.pi / 2, vmax=np.pi / 2)\n ax.set_title('Angle')\n ax.axis('off')\n plt.colorbar(plot)\n plt.show()\n\n\ndef calculate_iou_match(grasp_q, grasp_angle, ground_truth_bbs, no_grasps=1, grasp_width=None):\n \"\"\"\n Calculate grasp success using the IoU (Jacquard) metric (e.g. in https://arxiv.org/abs/1301.3592)\n A success is counted if grasp rectangle has a 25% IoU with a ground truth, and is withing 30 degrees.\n :param grasp_q: Q outputs of GG-CNN (Nx300x300x3)\n :param grasp_angle: Angle outputs of GG-CNN\n :param ground_truth_bbs: Corresponding ground-truth BoundingBoxes\n :param no_grasps: Maximum number of grasps to consider per image.\n :param grasp_width: (optional) Width output from GG-CNN\n :return: success\n \"\"\"\n\n if not isinstance(ground_truth_bbs, GraspRectangles):\n gt_bbs = GraspRectangles.load_from_array(ground_truth_bbs)\n else:\n gt_bbs = ground_truth_bbs\n gs = detect_grasps(grasp_q, grasp_angle, width_img=grasp_width, no_grasps=no_grasps)\n for g in gs:\n if g.max_iou(gt_bbs) > 0.25:\n return True\n else:\n return False"
] |
[
[
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
XHChen0528/ConditionalGAN_Develop
|
[
"4ea6d8ea130589bc3ff8f3117660050ba41cdd0f"
] |
[
"components/ConditionalWSConv2d.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#############################################################\n# File: ConditionalWSConv2d.py\n# Created Date: Tuesday October 1st 2019\n# Author: Chen Xuanhong\n# Email: [email protected]\n# Last Modified: Saturday, 5th October 2019 12:21:23 pm\n# Modified By: Chen Xuanhong\n# Copyright (c) 2019 Shanghai Jiao Tong University\n#############################################################\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\nclass ConditionalWSConv2d(nn.Conv2d):\n def __init__(self, in_channels, out_channels, num_classes, kernel_size=3, stride=1,\n padding=0, dilation=1, groups=1, bias=True):\n super(ConditionalWSConv2d, self).__init__(in_channels, out_channels, kernel_size, stride,\n padding, dilation, groups, bias)\n #self.conditionalWeight = nn.Embedding(num_classes, in_channels)\n self.conditionalBias = nn.Embedding(num_classes,out_channels)\n # self.conditionalBias=nn.Linear(num_classes,out_channels*out_channels,bias=False)\n \n self.in_channels = in_channels\n self.out_channels= out_channels\n self.num_classes=num_classes\n #print(num_classes)\n self.kernel_size=kernel_size\n self.weight_g = nn.Parameter(torch.ones(self.weight.size()[0],self.weight.size()[1],self.weight.size()[2],self.weight.size()[3])/9.0, requires_grad=False)\n # self.weight_g = nn.Parameter(torch.ones(self.weight.size()[0],self.weight.size()[1],1,1))\n # self.weight_g=torch.ones(self.weight.size()[0],self.weight.size()[1],self.weight.size()[2],self.weight.size()[3]).div(self.kernel_size[0]**2).cuda()\n self._initialize()\n\n def _initialize(self):\n # init.zeros_(self.conditionalBias.weight.data)\n init.uniform_(self.conditionalBias.weight.data,-1/np.sqrt(self.num_classes),-1/np.sqrt(self.num_classes))\n init.xavier_uniform_(self.weight)\n \n def forward(self, x, c):\n \n weight = self.weight\n weight_mean = weight.mean(dim=1,\n keepdim=True).mean(dim=2,\n keepdim=True).mean(dim=3, keepdim=True)\n weight = weight - weight_mean\n std = weight.view(weight.size(0), -1).std(dim=1).view(-1, 1, 1, 1) + 1e-12\n weight = weight / std.expand_as(weight)\n #print(weight.size())\n # beta = self.conditionalWeight(c)[0]\n if c is not None:\n \n \n X1= F.conv2d(x, weight, self.bias, self.stride,\n self.padding, self.dilation, self.groups)\n X2= F.conv2d(x, self.weight_g, self.bias, self.stride,\n self.padding, self.dilation, self.groups)\n \n gamma = self.conditionalBias(c)\n gamma = gamma.view(gamma.size()[0],gamma.size()[1],1,1)\n # bs,ch,w,h= X2.size()\n # gamma = gamma.view(bs,self.in_channels,self.in_channels)\n # # X2=torch.einsum('ijmn,ij->ijmn',X2,gamma)\n # X2 = X2.view(bs,self.out_channels,-1)\n # X2 = torch.matmul(X2.permute(0,2,1),gamma)\n # X2 = X2.permute(0,2,1).view(bs,ch,w,h)\n X2 = X2 *gamma\n \n return X1+X2"
] |
[
[
"torch.nn.functional.conv2d",
"numpy.sqrt",
"torch.nn.Embedding",
"torch.nn.init.xavier_uniform_"
]
] |
thirschbuechler/didactic-barnacles
|
[
"88d0a2b572aacb2cb45e68bb4f05fa5273224439"
] |
[
"computation/scipy-peaks.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 12 17:48:42 2020\n\n@author: thomas\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom scipy.misc import electrocardiogram\nfrom scipy.signal import find_peaks\n\n \ny = electrocardiogram()[2000:4000]\nprint(np.shape(y))\n#x, _ = find_peaks(y, distance=150)\n#x_peaks, _ = find_peaks(y, distance=150)\nx_peaks, _ = find_peaks(y, distance=150)\n\nplt.plot(y) # ex\nplt.stem(x_peaks,y[x_peaks]) # peaks, ex(peaks)"
] |
[
[
"matplotlib.pyplot.stem",
"scipy.signal.find_peaks",
"matplotlib.pyplot.plot",
"numpy.shape",
"scipy.misc.electrocardiogram"
]
] |
traffic-lights/rlpyt
|
[
"ec4689cddd55d98c037194685cfd6ca8e6785014",
"ec4689cddd55d98c037194685cfd6ca8e6785014"
] |
[
"rlpyt/projects/safe/safety_gym_env.py",
"rlpyt/ul/envs/atari.py"
] |
[
"\n# Requires installing OpenAI gym and safety gym.\n\nimport numpy as np\n\nimport safety_gym\nimport gym\nfrom gym import Wrapper\n\nfrom rlpyt.envs.gym import GymEnvWrapper\nfrom rlpyt.samplers.collections import TrajInfo\n\n# To use: return a dict of keys and default values which sometimes appear in\n# the wrapped env's env_info, so this env always presents those values (i.e.\n# make keys and values keep the same structure and shape at all time steps.)\n# Here, a dict of kwargs to be fed to `sometimes_info` should be passed as an\n# env_kwarg into the `make` function, which should be used as the EnvCls.\ndef sometimes_info(*args, **kwargs):\n # e.g. Feed the env_id.\n # Return a dictionary (possibly nested) of keys: default_values\n # for this env.\n return dict(cost_exception=0, goal_met=False)\n\n\nclass SafetyGymEnvWrapper(Wrapper):\n\n def __init__(self, env, sometimes_info_kwargs, obs_prev_cost):\n super().__init__(env)\n self._sometimes_info = sometimes_info(**sometimes_info_kwargs)\n self._obs_prev_cost = obs_prev_cost\n self._prev_cost = 0. # Concat this into the observation.\n obs = env.reset()\n # Some edited version of safexp envs defines observation space only\n # after reset, so expose it here (what base Wrapper does):\n self.observation_space = env.observation_space\n if isinstance(obs, dict): # and \"vision\" in obs:\n self._prop_keys = [k for k in obs.keys() if k != \"vision\"]\n obs = self.observation(obs)\n prop_shape = obs[\"prop\"].shape\n # if obs_prev_cost:\n # assert len(prop_shape) == 1\n # prop_shape = (prop_shape[0] + 1,)\n obs_space = dict(\n prop=gym.spaces.Box(-1e6, 1e6, prop_shape,\n obs[\"prop\"].dtype))\n if \"vision\" in obs:\n obs_space[\"vision\"] = gym.spaces.Box(0, 1, obs[\"vision\"].shape,\n obs[\"vision\"].dtype)\n # GymWrapper will in turn convert this to rlpyt.spaces.Composite.\n self.observation_space = gym.spaces.Dict(obs_space)\n elif obs_prev_cost:\n if isinstance(obs, dict):\n self.observation_space.spaces[\"prev_cost\"] = gym.spaces.Box(\n -1e6, 1e6, (1,), np.float32)\n else:\n obs_shape = obs.shape\n assert len(obs_shape) == 1\n obs_shape = (obs_shape[0] + 1,)\n self.observation_space = gym.spaces.Box(-1e6, 1e6, obs_shape,\n obs.dtype)\n self._cum_cost = 0.\n\n def step(self, action):\n o, r, d, info = self.env.step(action)\n o = self.observation(o) # Uses self._prev_cost\n self._prev_cost = info.get(\"cost\", 0)\n self._cum_cost += self._prev_cost\n info[\"cum_cost\"] = self._cum_cost\n # Try to make info dict same key structure at every step.\n info = infill_info(info, self._sometimes_info)\n for k, v in info.items():\n if isinstance(v, float):\n info[k] = np.dtype(\"float32\").type(v) # In case computing on.\n # Look inside safexp physics env for this logic on env horizon:\n info[\"timeout\"] = d and (self.env.steps >= self.env.num_steps)\n # info[\"timeout_next\"] = not d and (\n # self.env.steps == self.env.num_steps - 1)\n return o, r, d, info\n\n def reset(self):\n self._prev_cost = 0.\n self._cum_cost = 0.\n return self.observation(self.env.reset())\n\n def observation(self, obs):\n if isinstance(obs, dict): # and \"vision\" in obs:\n # flatten everything else than vision.\n obs_ = dict(\n prop=np.concatenate([obs[k].reshape(-1)\n for k in self._prop_keys])\n )\n if \"vision\" in obs:\n # [H,W,C] --> [C,H,W]\n obs_[\"vision\"] = np.transpose(obs[\"vision\"], (2, 0, 1))\n if self._obs_prev_cost:\n obs_[\"prop\"] = np.append(obs_[\"prop\"], self._prev_cost)\n obs = obs_\n elif self._obs_prev_cost:\n obs = np.append(obs, self._prev_cost)\n return obs\n\n\ndef infill_info(info, sometimes_info):\n for k, v in sometimes_info.items():\n if k not in info:\n info[k] = v\n elif isinstance(v, dict):\n infill_info(info[k], v)\n return info\n\n\ndef safety_gym_make(*args, sometimes_info_kwargs=None, obs_prev_cost=True,\n obs_version=\"default\", **kwargs):\n assert obs_version in [\"default\", \"vision\", \"vision_only\", \"no_lidar\",\n \"no_constraints\"]\n if obs_version != \"default\":\n eid = kwargs[\"id\"] # Must provide as kwarg, not arg.\n names = dict( # Map to my modification in safety-gym suite.\n vision=\"Vision\",\n vision_only=\"Visonly\",\n no_lidar=\"NoLidar\",\n no_constraints=\"NoConstr\",\n )\n name = names[obs_version]\n # e.g. Safexp-PointGoal1-v0 --> Safexp-PointGoal1Vision-v0\n kwargs[\"id\"] = eid[:-3] + name + eid[-3:]\n return GymEnvWrapper(SafetyGymEnvWrapper(\n gym.make(*args, **kwargs),\n sometimes_info_kwargs=sometimes_info_kwargs or dict(),\n obs_prev_cost=obs_prev_cost),\n )\n\n\nclass SafetyGymTrajInfo(TrajInfo):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.Cost = 0\n\n def step(self, observation, action, reward, done, agent_info, env_info):\n super().step(observation, action, reward, done, agent_info, env_info)\n self.Cost += getattr(env_info, \"cost\", 0)\n\n def terminate(self, observation):\n del self.NonzeroRewards\n return super().terminate(observation)\n",
"\nimport numpy as np\nimport cv2\nimport atari_py\nimport os\n\nfrom rlpyt.spaces.int_box import IntBox\nfrom rlpyt.envs.atari.atari_env import AtariEnv\nfrom rlpyt.utils.quick_args import save__init__args\n\n\nclass AtariEnv84(AtariEnv):\n \"\"\"\n Same as built-in AtariEnv except returns standard 84x84 frames.\n\n Actually, can resize the image to whatever square size you want.\n \"\"\"\n\n def __init__(self,\n game=\"pong\",\n frame_skip=4,\n num_img_obs=4,\n clip_reward=True,\n episodic_lives=False, # !\n max_start_noops=30,\n repeat_action_probability=0.25, # !\n horizon=27000,\n obs_size=84, # square resize\n fire_on_reset=True,\n ):\n save__init__args(locals(), underscore=True)\n # ALE\n game_path = atari_py.get_game_path(game)\n if not os.path.exists(game_path):\n raise IOError(\"You asked for game {} but path {} does not \"\n \" exist\".format(game, game_path))\n self.ale = atari_py.ALEInterface()\n self.ale.setFloat(b'repeat_action_probability', repeat_action_probability)\n self.ale.loadROM(game_path)\n\n # Spaces\n self._obs_size = obs_size\n self._action_set = self.ale.getMinimalActionSet()\n self._action_space = IntBox(low=0, high=len(self._action_set))\n obs_shape = (num_img_obs, self._obs_size, self._obs_size)\n self._observation_space = IntBox(low=0, high=256, shape=obs_shape,\n dtype=\"uint8\")\n self._max_frame = self.ale.getScreenGrayscale()\n self._raw_frame_1 = self._max_frame.copy()\n self._raw_frame_2 = self._max_frame.copy()\n self._obs = np.zeros(shape=obs_shape, dtype=\"uint8\")\n \n # Settings\n self._has_fire = \"FIRE\" in self.get_action_meanings()\n self._has_up = \"UP\" in self.get_action_meanings()\n self._horizon = int(horizon)\n self.reset()\n\n def reset(self):\n \"\"\"Performs hard reset of ALE game.\"\"\"\n self.ale.reset_game()\n self._reset_obs()\n self._life_reset()\n for _ in range(np.random.randint(0, self._max_start_noops + 1)):\n self.ale.act(0)\n if self._fire_on_reset:\n self.fire_and_up()\n self._update_obs() # (don't bother to populate any frame history)\n self._step_counter = 0\n return self.get_obs()\n\n def _update_obs(self):\n \"\"\"Max of last two frames; resize to standard 84x84.\"\"\"\n self._get_screen(2)\n np.maximum(self._raw_frame_1, self._raw_frame_2, self._max_frame)\n img = cv2.resize(self._max_frame, (self._obs_size, self._obs_size), cv2.INTER_AREA)\n # NOTE: order OLDEST to NEWEST should match use in frame-wise buffer.\n self._obs = np.concatenate([self._obs[1:], img[np.newaxis]])\n\n def _life_reset(self):\n self.ale.act(0) # (advance from lost life state)\n self._lives = self.ale.lives()\n\n def fire_and_up(self):\n if self._has_fire:\n # TODO: for sticky actions, make sure fire is actually pressed\n self.ale.act(1) # (e.g. needed in Breakout, not sure what others)\n if self._has_up:\n self.ale.act(2) # (not sure if this is necessary, saw it somewhere)\n"
] |
[
[
"numpy.append",
"numpy.dtype",
"numpy.transpose"
],
[
"numpy.concatenate",
"numpy.maximum",
"numpy.zeros",
"numpy.random.randint"
]
] |
joon1170/CreditCard-Fraud
|
[
"6e89b406078441209552f4421077e56075266778"
] |
[
"01_explore.py"
] |
[
"# Certification Project by Joon Kim\n#\n# ## Part 1 - Data Exploration, Feature Selection\n\n# In this module we use Spark in conjunction with some popular Python libraries\n# to explore data and select features we will use in the next module which is model training,\n# scoring and evaluation.\n\n# ## Setup\n# Import some useful packages and modules:\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Create a SparkSession:\nspark = SparkSession.builder.master(\"local\").appName(\"jkim_explore01\").getOrCreate()\n\n\n\n# Load the creditcard data from HDFS:\n\n# df = spark.read.csv(\"jkim/creditcard/\", sep=\",\", header=True, inferSchema=True)\n# Show first 5 lines to see if the delimited lines have been read properly\n# df.show(5)\n\n# And Print schema\n# df.printSchema()\n\n# Define a new schema\nfrom pyspark.sql.types import *\nschema = StructType([\n StructField(\"Time\", DoubleType()),\n StructField(\"V1\", DoubleType()),\n StructField(\"V2\", DoubleType()),\n StructField(\"V3\", DoubleType()),\n StructField(\"V4\", DoubleType()),\n StructField(\"V5\", DoubleType()),\n StructField(\"V6\", DoubleType()),\n StructField(\"V7\", DoubleType()),\n StructField(\"V8\", DoubleType()),\n StructField(\"V9\", DoubleType()),\n StructField(\"V10\", DoubleType()),\n StructField(\"V11\", DoubleType()),\n StructField(\"V12\", DoubleType()),\n StructField(\"V13\", DoubleType()),\n StructField(\"V14\", DoubleType()),\n StructField(\"V15\", DoubleType()),\n StructField(\"V16\", DoubleType()),\n StructField(\"V17\", DoubleType()),\n StructField(\"V18\", DoubleType()),\n StructField(\"V19\", DoubleType()),\n StructField(\"V20\", DoubleType()),\n StructField(\"V21\", DoubleType()),\n StructField(\"V22\", DoubleType()),\n StructField(\"V23\", DoubleType()),\n StructField(\"V24\", DoubleType()),\n StructField(\"V25\", DoubleType()),\n StructField(\"V26\", DoubleType()),\n StructField(\"V27\", DoubleType()),\n StructField(\"V28\", DoubleType()),\n StructField(\"Amount\", DoubleType()),\n StructField(\"Class\", IntegerType())\n])\n\ndf = spark \\\n .read \\\n .format(\"csv\") \\\n .option(\"sep\", \",\") \\\n .option(\"header\", True) \\\n .schema(schema) \\\n .load(\"creditcard/\")\n\ndf.describe(\"Time\",\"Amount\",\"Class\").show()\n\n\n# Run some basic checks on the data - any NULL values?\ndf_nonull = df.dropna()\ndf_nonull.describe(\"Time\",\"Amount\",\"Class\").show()\n \n# Add a new Category Column \"Fraud\"\ndf2 = df.withColumn(\"Fraud\", df.Class == 1)\n\n# Describe the new DataFrame\ndf2.select(\"Time\", \"V1\", \"V2\", \"Amount\", \"Class\", \"Fraud\").show(5)\ndf2.describe(\"Time\", \"V1\", \"V2\", \"Amount\", \"Class\").show()\n \n# Load into Panda Dataframe to visualize summary better. \npdf = df2.toPandas()\n# pdf.describe()\n\n\n# Time Column - View distribution\n# Plot Time with normal, and plot Time with fraud\n# sns.distplot(pdf[\"Time\"], kde=False)\n# sns.distplot(pdf[\"Time\"][pdf.Class == 0], kde=False)\n# sns.distplot(pdf[\"Time\"][pdf.Class == 1], kde=False)\n\n\n# Filter \"Normal\" DataFrame where Class == 0\n# and filter \"Fraudulent\" DataFrame where Class == 1\n\npdf_normal = pdf[pdf.Class == 0]\n# pdf_normal.count()\n\n# Plot distribution of Normal transactions\nsns.jointplot(x=\"Time\", y=\"Amount\", data=pdf_normal, size=12, kind=\"reg\")\n\npdf_fraud = pdf[pdf.Class == 1]\n\n# Plot Distribution of Fraud transactions\nsns.jointplot(x=\"Time\", y=\"Amount\", data=pdf_fraud, size=12, kind=\"reg\")\n\n# FacetGrid\ndef tmp_plot(): # Wrap plot build into function for CDSW\n g = sns.FacetGrid(data=pdf, col=\"Fraud\", sharex=True, size=10)\n g = g.map(plt.scatter, \"Time\", \"Amount\")\ntmp_plot()\n\n\n# Explore each \"V\" features\nfrom pyspark.sql.functions import count, mean\n\nv_list = [\"V1\",\"V2\",\"V3\",\"V4\",\"V5\",\"V6\",\"V7\",\"V8\",\"V9\",\"V10\", \\\n \"V11\",\"V12\",\"V13\",\"V14\",\"V15\",\"V16\",\"V17\",\"V18\",\"V19\",\"V20\", \\\n \"V21\",\"V22\",\"V23\",\"V24\",\"V25\",\"V26\",\"V27\",\"V28\"]\n\ndef explore(vfeatures):\n for v in vfeatures:\n df.rollup(\"Class\").agg(count(v), mean(v)).orderBy(\"Class\").show()\n\nexplore(v_list)\n\n\ndef tmp_plot2(vfeatures):\n for v in vfeatures:\n ax = plt.subplot(111)\n sns.distplot(pdf[v][pdf.Class == 1], bins=50)\n sns.distplot(pdf[v][pdf.Class == 0], bins=50)\n ax.set_xlabel('')\n ax.set_title('Feature: ' + str(v))\n plt.show()\n\ntmp_plot2(v_list)\n \n\n# When visualizing the distribution of data between \"normal\" and \"fraud\" transactions,\n# the following columns (features) show very different distribution between the two\n# transaction types.\n\nfeature_selected = [\"V1\",\"V2\",\"V3\",\"V4\",\"V9\",\"V10\",\"V11\",\"V12\",\"V14\",\"V16\",\"V17\",\"V18\",\"V19\"]\n\n# Save the data for next phase, Machine Learning\ndf2.write.parquet(\"creditcard/exploredata\", mode=\"overwrite\")\n\n# ## Cleanup\n# Stop the SparkSession:\nspark.stop()"
] |
[
[
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
]
] |
tunsmm/fitness_guide
|
[
"42df50c9f35a4345c72e9c7e3868867fc8dfd563"
] |
[
"fitness_guide/menu/services/data/regression_amino.py"
] |
[
"import numpy as np\n\nfrom regression.Regression import LinearRegression\nfrom regression.Optimization import MomentGrad\nfrom regression.Loss import LinearMSE\n\nif __name__ == \"__main__\":\n dataset = np.load('amino_xy_matrix.np', allow_pickle=True)\n data_x = dataset[:, :-1]\n data_y = dataset[:, -1]\n\n regressor = LinearRegression()\n regressor.fit(data_x, data_y, MomentGrad(lossObj=LinearMSE()))\n\n for i in range(10):\n print(data_y[i], regressor.predict(data_x[i]))\n\n regressor.dump('regression_amino_dump.np')\n"
] |
[
[
"numpy.load"
]
] |
dgerod/gesto-prof
|
[
"4c45e1306625831bf5718f3843347d7eb7b58132"
] |
[
"scripts/helpers/preparar_facturas_recibidas.py"
] |
[
"import os\nimport sys\n\n_CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(os.path.dirname(os.path.normpath(_CURRENT_DIRECTORY))))\n\nimport pandas as pd\nfrom scripts.common.configuration import Configuration\n\n\nconfiguration = Configuration()\nfile_path = os.path.join(configuration.get_inputs_directory(), \"classgap_facturas_recibidas.csv\")\n\ncolumn_dates = [\"Fecha\"]\n\ncolumn_types = {\n \"Factura\" : str,\n \"Serie\" : str,\n \"Base\" : float,\n \"IVA\" : float,\n \"Total\" : float}\n\nclassgap_data = pd.read_csv(file_path, sep=\";\", decimal=\".\",\n parse_dates=column_dates, dtype=column_types)\n\n# Nuevo fichero\n\nnum_rows = len(classgap_data[\"Fecha\"])\n\ndata = {}\ndata[\"FECHA CONTABILIZADO\"] = pd.to_datetime(classgap_data[\"Fecha\"]).dt.date\ndata[\"FECHA OPERACIÓN\"] = pd.to_datetime(classgap_data[\"Fecha\"]).dt.date\ndata[\"NÚMERO PROVEEDOR\"] = [\"\"] * num_rows\ndata[\"NÚMERO FACTURA\"] = classgap_data[\"Serie\"] + \"-\" + classgap_data[\"Factura\"]\ndata[\"OPERACIÓN\"] = [\"Factura Recibida\"] * num_rows\ndata[\"CONCEPTO\"] = [\"Otros Servicios\"] * num_rows\ndata[\"IMPORTE BASE\"] = classgap_data[\"Base\"]\ndata[\"% IVA\"] = classgap_data[\"IVA\"]\ndata[\"IMPORTE IVA\"] = classgap_data[\"Total\"] - classgap_data[\"Base\"]\ndata[\"% RETENCIÓN\"] = [0.0] * num_rows\ndata[\"IMPORTE RETENCIÓN\"] = [0.0] * num_rows\ndata[\"IMPORTE TOTAL\"] = classgap_data[\"Total\"]\ndata[\"IMPORTE PENDIENTE\"] = [0.0] * num_rows\ndata[\"ESTADO\"] = [\"Pagado\"] * num_rows\ndata[\"OBSERVACIONES\"] = [\"\"] * num_rows\n\ndf = pd.DataFrame(data)\nprint(data)\n\nfile_path = os.path.join(configuration.get_outputs_directory(), \"facturas_recibidas_solo_classgap.csv\")\ndf.to_csv(file_path, index=False, sep=\";\", decimal=\".\")\n"
] |
[
[
"pandas.read_csv",
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
edurenye/keras-rl2
|
[
"8e1ce5ea9bb335c75775857ef3d36a5b0d8cf9a2"
] |
[
"rl/core.py"
] |
[
"# -*- coding: utf-8 -*-\nimport warnings\nfrom copy import deepcopy\n\nimport numpy as np\nfrom tensorflow.keras.callbacks import History\n\nfrom rl.callbacks import (\n CallbackList,\n TestLogger,\n TrainEpisodeLogger,\n TrainIntervalLogger,\n Visualizer\n)\n\n\nclass Agent(object):\n \"\"\"Abstract base class for all implemented agents.\n\n Each agent interacts with the environment (as defined by the `Env` class) by first observing the\n state of the environment. Based on this observation the agent changes the environment by performing\n an action.\n\n Do not use this abstract base class directly but instead use one of the concrete agents implemented.\n Each agent realizes a reinforcement learning algorithm. Since all agents conform to the same\n interface, you can use them interchangeably.\n\n To implement your own agent, you have to implement the following methods:\n\n - `forward`\n - `backward`\n - `compile`\n - `load_weights`\n - `save_weights`\n - `layers`\n\n # Arguments\n processor (`Processor` instance): See [Processor](#processor) for details.\n \"\"\"\n def __init__(self, processor=None):\n self.processor = processor\n self.training = False\n self.step = 0\n\n def get_config(self):\n \"\"\"Configuration of the agent for serialization.\n\n # Returns\n Dictionnary with agent configuration\n \"\"\"\n return {}\n\n def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1,\n visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000,\n nb_max_episode_steps=None):\n \"\"\"Trains the agent on the given environment.\n\n # Arguments\n env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.\n nb_steps (integer): Number of training steps to be performed.\n action_repetition (integer): Number of times the agent repeats the same action without\n observing the environment again. Setting this to a value > 1 can be useful\n if a single action only has a very small effect on the environment.\n callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances):\n List of callbacks to apply during training. See [callbacks](/callbacks) for details.\n verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging\n visualize (boolean): If `True`, the environment is visualized during training. However,\n this is likely going to slow down training significantly and is thus intended to be\n a debugging instrument.\n nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning\n of each episode using `start_step_policy`. Notice that this is an upper limit since\n the exact number of steps to be performed is sampled uniformly from [0, max_start_steps]\n at the beginning of each episode.\n start_step_policy (`lambda observation: action`): The policy\n to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed.\n log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval.\n nb_max_episode_steps (integer): Number of steps per episode that the agent performs before\n automatically resetting the environment. Set to `None` if each episode should run\n (potentially indefinitely) until the environment signals a terminal state.\n\n # Returns\n A `keras.callbacks.History` instance that recorded the entire training process.\n \"\"\"\n if not self.compiled:\n raise RuntimeError('Your tried to fit your agent but it hasn\\'t been compiled yet. Please call `compile()` before `fit()`.')\n if action_repetition < 1:\n raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition))\n\n self.training = True\n\n callbacks = [] if not callbacks else callbacks[:]\n\n if verbose == 1:\n callbacks += [TrainIntervalLogger(interval=log_interval)]\n elif verbose > 1:\n callbacks += [TrainEpisodeLogger()]\n if visualize:\n callbacks += [Visualizer()]\n history = History()\n callbacks += [history]\n callbacks = CallbackList(callbacks)\n if hasattr(callbacks, 'set_model'):\n callbacks.set_model(self)\n else:\n callbacks._set_model(self)\n callbacks._set_env(env)\n params = {\n 'nb_steps': nb_steps,\n }\n if hasattr(callbacks, 'set_params'):\n callbacks.set_params(params)\n else:\n callbacks._set_params(params)\n self._on_train_begin()\n callbacks.on_train_begin()\n\n episode = np.int16(0)\n self.step = np.int16(0)\n observation = None\n episode_reward = None\n episode_step = None\n did_abort = False\n try:\n while self.step < nb_steps:\n if observation is None: # start of a new episode\n callbacks.on_episode_begin(episode)\n episode_step = np.int16(0)\n episode_reward = np.float32(0)\n\n # Obtain the initial observation by resetting the environment.\n self.reset_states()\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n assert observation is not None\n\n # Perform random starts at beginning of episode and do not record them into the experience.\n # This slightly changes the start position between games.\n nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps)\n for _ in range(nb_random_start_steps):\n if start_step_policy is None:\n action = env.action_space.sample()\n else:\n action = start_step_policy(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n callbacks.on_action_begin(action)\n observation, reward, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, reward, done, info = self.processor.process_step(observation, reward, done, info)\n callbacks.on_action_end(action)\n if done:\n warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps))\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n break\n\n # At this point, we expect to be fully initialized.\n assert episode_reward is not None\n assert episode_step is not None\n assert observation is not None\n\n # Run a single step.\n callbacks.on_step_begin(episode_step)\n # This is were all of the work happens. We first perceive and compute the action\n # (forward step) and then use the reward to improve (backward step).\n action = self.forward(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n reward = np.float32(0)\n accumulated_info = {}\n done = False\n for _ in range(action_repetition):\n callbacks.on_action_begin(action)\n observation, r, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, done, info = self.processor.process_step(observation, r, done, info)\n for key, value in info.items():\n if not np.isreal(value):\n continue\n if key not in accumulated_info:\n accumulated_info[key] = np.zeros_like(value)\n accumulated_info[key] += value\n callbacks.on_action_end(action)\n reward += r\n if done:\n break\n if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1:\n # Force a terminal state.\n done = True\n metrics = self.backward(reward, terminal=done)\n episode_reward += reward\n\n step_logs = {\n 'action': action,\n 'observation': observation,\n 'reward': reward,\n 'metrics': metrics,\n 'episode': episode,\n 'info': accumulated_info,\n }\n callbacks.on_step_end(episode_step, step_logs)\n episode_step += 1\n self.step += 1\n\n if done:\n # We are in a terminal state but the agent hasn't yet seen it. We therefore\n # perform one more forward-backward call and simply ignore the action before\n # resetting the environment. We need to pass in `terminal=False` here since\n # the *next* state, that is the state of the newly reset environment, is\n # always non-terminal by convention.\n self.forward(observation)\n self.backward(0., terminal=False)\n\n # This episode is finished, report and reset.\n episode_logs = {\n 'episode_reward': episode_reward,\n 'nb_episode_steps': episode_step,\n 'nb_steps': self.step,\n }\n callbacks.on_episode_end(episode, episode_logs)\n\n episode += 1\n observation = None\n episode_step = None\n episode_reward = None\n except KeyboardInterrupt:\n # We catch keyboard interrupts here so that training can be be safely aborted.\n # This is so common that we've built this right into this function, which ensures that\n # the `on_train_end` method is properly called.\n did_abort = True\n callbacks.on_train_end(logs={'did_abort': did_abort})\n self._on_train_end()\n\n return history\n\n def test(self, env, nb_episodes=1, action_repetition=1, callbacks=None, visualize=True,\n nb_max_episode_steps=None, nb_max_start_steps=0, start_step_policy=None, verbose=1):\n \"\"\"Callback that is called before training begins.\n\n # Arguments\n env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.\n nb_episodes (integer): Number of episodes to perform.\n action_repetition (integer): Number of times the agent repeats the same action without\n observing the environment again. Setting this to a value > 1 can be useful\n if a single action only has a very small effect on the environment.\n callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances):\n List of callbacks to apply during training. See [callbacks](/callbacks) for details.\n verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging\n visualize (boolean): If `True`, the environment is visualized during training. However,\n this is likely going to slow down training significantly and is thus intended to be\n a debugging instrument.\n nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning\n of each episode using `start_step_policy`. Notice that this is an upper limit since\n the exact number of steps to be performed is sampled uniformly from [0, max_start_steps]\n at the beginning of each episode.\n start_step_policy (`lambda observation: action`): The policy\n to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed.\n log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval.\n nb_max_episode_steps (integer): Number of steps per episode that the agent performs before\n automatically resetting the environment. Set to `None` if each episode should run\n (potentially indefinitely) until the environment signals a terminal state.\n\n # Returns\n A `keras.callbacks.History` instance that recorded the entire training process.\n \"\"\"\n if not self.compiled:\n raise RuntimeError('Your tried to test your agent but it hasn\\'t been compiled yet. Please call `compile()` before `test()`.')\n if action_repetition < 1:\n raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition))\n\n self.training = False\n self.step = 0\n\n callbacks = [] if not callbacks else callbacks[:]\n\n if verbose >= 1:\n callbacks += [TestLogger()]\n if visualize:\n callbacks += [Visualizer()]\n history = History()\n callbacks += [history]\n callbacks = CallbackList(callbacks)\n if hasattr(callbacks, 'set_model'):\n callbacks.set_model(self)\n else:\n callbacks._set_model(self)\n callbacks._set_env(env)\n params = {\n 'nb_episodes': nb_episodes,\n }\n if hasattr(callbacks, 'set_params'):\n callbacks.set_params(params)\n else:\n callbacks._set_params(params)\n\n self._on_test_begin()\n callbacks.on_train_begin()\n for episode in range(nb_episodes):\n callbacks.on_episode_begin(episode)\n episode_reward = 0.\n episode_step = 0\n\n # Obtain the initial observation by resetting the environment.\n self.reset_states()\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n assert observation is not None\n\n # Perform random starts at beginning of episode and do not record them into the experience.\n # This slightly changes the start position between games.\n nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps)\n for _ in range(nb_random_start_steps):\n if start_step_policy is None:\n action = env.action_space.sample()\n else:\n action = start_step_policy(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n callbacks.on_action_begin(action)\n observation, r, done, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, done, info = self.processor.process_step(observation, r, done, info)\n callbacks.on_action_end(action)\n if done:\n warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps))\n observation = deepcopy(env.reset())\n if self.processor is not None:\n observation = self.processor.process_observation(observation)\n break\n\n # Run the episode until we're done.\n done = False\n while not done:\n callbacks.on_step_begin(episode_step)\n\n action = self.forward(observation)\n if self.processor is not None:\n action = self.processor.process_action(action)\n reward = 0.\n accumulated_info = {}\n for _ in range(action_repetition):\n callbacks.on_action_begin(action)\n observation, r, d, info = env.step(action)\n observation = deepcopy(observation)\n if self.processor is not None:\n observation, r, d, info = self.processor.process_step(observation, r, d, info)\n callbacks.on_action_end(action)\n reward += r\n for key, value in info.items():\n if not np.isreal(value):\n continue\n if key not in accumulated_info:\n accumulated_info[key] = np.zeros_like(value)\n accumulated_info[key] += value\n if d:\n done = True\n break\n if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1:\n done = True\n self.backward(reward, terminal=done)\n episode_reward += reward\n\n step_logs = {\n 'action': action,\n 'observation': observation,\n 'reward': reward,\n 'episode': episode,\n 'info': accumulated_info,\n }\n callbacks.on_step_end(episode_step, step_logs)\n episode_step += 1\n self.step += 1\n\n # We are in a terminal state but the agent hasn't yet seen it. We therefore\n # perform one more forward-backward call and simply ignore the action before\n # resetting the environment. We need to pass in `terminal=False` here since\n # the *next* state, that is the state of the newly reset environment, is\n # always non-terminal by convention.\n self.forward(observation)\n self.backward(0., terminal=False)\n\n # Report end of episode.\n episode_logs = {\n 'episode_reward': episode_reward,\n 'nb_steps': episode_step,\n }\n callbacks.on_episode_end(episode, episode_logs)\n callbacks.on_train_end()\n self._on_test_end()\n\n return history\n\n def reset_states(self):\n \"\"\"Resets all internally kept states after an episode is completed.\n \"\"\"\n pass\n\n def forward(self, observation):\n \"\"\"Takes the an observation from the environment and returns the action to be taken next.\n If the policy is implemented by a neural network, this corresponds to a forward (inference) pass.\n\n # Argument\n observation (object): The current observation from the environment.\n\n # Returns\n The next action to be executed in the environment.\n \"\"\"\n raise NotImplementedError()\n\n def backward(self, reward, terminal):\n \"\"\"Updates the agent after having executed the action returned by `forward`.\n If the policy is implemented by a neural network, this corresponds to a weight update using back-prop.\n\n # Argument\n reward (float): The observed reward after executing the action returned by `forward`.\n terminal (boolean): `True` if the new state of the environment is terminal.\n\n # Returns\n List of metrics values\n \"\"\"\n raise NotImplementedError()\n\n def compile(self, optimizer, metrics=[]):\n \"\"\"Compiles an agent and the underlaying models to be used for training and testing.\n\n # Arguments\n optimizer (`keras.optimizers.Optimizer` instance): The optimizer to be used during training.\n metrics (list of functions `lambda y_true, y_pred: metric`): The metrics to run during training.\n \"\"\"\n raise NotImplementedError()\n\n def load_weights(self, filepath):\n \"\"\"Loads the weights of an agent from an HDF5 file.\n\n # Arguments\n filepath (str): The path to the HDF5 file.\n \"\"\"\n raise NotImplementedError()\n\n def save_weights(self, filepath, overwrite=False):\n \"\"\"Saves the weights of an agent as an HDF5 file.\n\n # Arguments\n filepath (str): The path to where the weights should be saved.\n overwrite (boolean): If `False` and `filepath` already exists, raises an error.\n \"\"\"\n raise NotImplementedError()\n\n @property\n def layers(self):\n \"\"\"Returns all layers of the underlying model(s).\n\n If the concrete implementation uses multiple internal models,\n this method returns them in a concatenated list.\n\n # Returns\n A list of the model's layers\n \"\"\"\n raise NotImplementedError()\n\n @property\n def metrics_names(self):\n \"\"\"The human-readable names of the agent's metrics. Must return as many names as there\n are metrics (see also `compile`).\n\n # Returns\n A list of metric's names (string)\n \"\"\"\n return []\n\n def _on_train_begin(self):\n \"\"\"Callback that is called before training begins.\"\n \"\"\"\n pass\n\n def _on_train_end(self):\n \"\"\"Callback that is called after training ends.\"\n \"\"\"\n pass\n\n def _on_test_begin(self):\n \"\"\"Callback that is called before testing begins.\"\n \"\"\"\n pass\n\n def _on_test_end(self):\n \"\"\"Callback that is called after testing ends.\"\n \"\"\"\n pass\n\n\nclass Processor(object):\n \"\"\"Abstract base class for implementing processors.\n\n A processor acts as a coupling mechanism between an `Agent` and its `Env`. This can\n be necessary if your agent has different requirements with respect to the form of the\n observations, actions, and rewards of the environment. By implementing a custom processor,\n you can effectively translate between the two without having to change the underlaying\n implementation of the agent or environment.\n\n Do not use this abstract base class directly but instead use one of the concrete implementations\n or write your own.\n \"\"\"\n\n def process_step(self, observation, reward, done, info):\n \"\"\"Processes an entire step by applying the processor to the observation, reward, and info arguments.\n\n # Arguments\n observation (object): An observation as obtained by the environment.\n reward (float): A reward as obtained by the environment.\n done (boolean): `True` if the environment is in a terminal state, `False` otherwise.\n info (dict): The debug info dictionary as obtained by the environment.\n\n # Returns\n The tupel (observation, reward, done, reward) with with all elements after being processed.\n \"\"\"\n observation = self.process_observation(observation)\n reward = self.process_reward(reward)\n info = self.process_info(info)\n return observation, reward, done, info\n\n def process_observation(self, observation):\n \"\"\"Processes the observation as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n observation (object): An observation as obtained by the environment\n\n # Returns\n Observation obtained by the environment processed\n \"\"\"\n return observation\n\n def process_reward(self, reward):\n \"\"\"Processes the reward as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n reward (float): A reward as obtained by the environment\n\n # Returns\n Reward obtained by the environment processed\n \"\"\"\n return reward\n\n def process_info(self, info):\n \"\"\"Processes the info as obtained from the environment for use in an agent and\n returns it.\n\n # Arguments\n info (dict): An info as obtained by the environment\n\n # Returns\n Info obtained by the environment processed\n \"\"\"\n return info\n\n def process_action(self, action):\n \"\"\"Processes an action predicted by an agent but before execution in an environment.\n\n # Arguments\n action (int): Action given to the environment\n\n # Returns\n Processed action given to the environment\n \"\"\"\n return action\n\n def process_state_batch(self, batch):\n \"\"\"Processes an entire batch of states and returns it.\n\n # Arguments\n batch (list): List of states\n\n # Returns\n Processed list of states\n \"\"\"\n return batch\n\n @property\n def metrics(self):\n \"\"\"The metrics of the processor, which will be reported during training.\n\n # Returns\n List of `lambda y_true, y_pred: metric` functions.\n \"\"\"\n return []\n\n @property\n def metrics_names(self):\n \"\"\"The human-readable names of the agent's metrics. Must return as many names as there\n are metrics (see also `compile`).\n \"\"\"\n return []\n\n\n# Note: the API of the `Env` and `Space` classes are taken from the OpenAI Gym implementation.\n# https://github.com/openai/gym/blob/master/gym/core.py\n\n\nclass Env(object):\n \"\"\"The abstract environment class that is used by all agents. This class has the exact\n same API that OpenAI Gym uses so that integrating with it is trivial. In contrast to the\n OpenAI Gym implementation, this class only defines the abstract methods without any actual\n implementation.\n\n To implement your own environment, you need to define the following methods:\n\n - `step`\n - `reset`\n - `render`\n - `close`\n\n Refer to the [Gym documentation](https://gym.openai.com/docs/#environments).\n \"\"\"\n reward_range = (-np.inf, np.inf)\n action_space = None\n observation_space = None\n\n def step(self, action):\n \"\"\"Run one timestep of the environment's dynamics.\n Accepts an action and returns a tuple (observation, reward, done, info).\n\n # Arguments\n action (object): An action provided by the environment.\n\n # Returns\n observation (object): Agent's observation of the current environment.\n reward (float) : Amount of reward returned after previous action.\n done (boolean): Whether the episode has ended, in which case further step() calls will return undefined results.\n info (dict): Contains auxiliary diagnostic information (helpful for debugging, and sometimes learning).\n \"\"\"\n raise NotImplementedError()\n\n def reset(self):\n \"\"\"\n Resets the state of the environment and returns an initial observation.\n\n # Returns\n observation (object): The initial observation of the space. Initial reward is assumed to be 0.\n \"\"\"\n raise NotImplementedError()\n\n def render(self, mode='human', close=False):\n \"\"\"Renders the environment.\n The set of supported modes varies per environment. (And some\n environments do not support rendering at all.)\n\n # Arguments\n mode (str): The mode to render with.\n close (bool): Close all open renderings.\n \"\"\"\n raise NotImplementedError()\n\n def close(self):\n \"\"\"Override in your subclass to perform any necessary cleanup.\n Environments will automatically close() themselves when\n garbage collected or when the program exits.\n \"\"\"\n raise NotImplementedError()\n\n def seed(self, seed=None):\n \"\"\"Sets the seed for this env's random number generator(s).\n\n # Returns\n Returns the list of seeds used in this env's random number generators\n \"\"\"\n raise NotImplementedError()\n\n def configure(self, *args, **kwargs):\n \"\"\"Provides runtime configuration to the environment.\n This configuration should consist of data that tells your\n environment how to run (such as an address of a remote server,\n or path to your ImageNet data). It should not affect the\n semantics of the environment.\n \"\"\"\n raise NotImplementedError()\n\n def __del__(self):\n self.close()\n\n def __str__(self):\n return '<{} instance>'.format(type(self).__name__)\n\n\nclass Space(object):\n \"\"\"Abstract model for a space that is used for the state and action spaces. This class has the\n exact same API that OpenAI Gym uses so that integrating with it is trivial.\n\n Please refer to [Gym Documentation](https://gym.openai.com/docs/#spaces)\n \"\"\"\n\n def sample(self, seed=None):\n \"\"\"Uniformly randomly sample a random element of this space.\n \"\"\"\n raise NotImplementedError()\n\n def contains(self, x):\n \"\"\"Return boolean specifying if x is a valid member of this space\n \"\"\"\n raise NotImplementedError()\n"
] |
[
[
"numpy.int16",
"numpy.zeros_like",
"numpy.float32",
"tensorflow.keras.callbacks.History",
"numpy.isreal",
"numpy.random.randint"
]
] |
Spiden-data/DeepeR
|
[
"03e2bf135aa692b0df34b6c8baca3dcae3e988ea"
] |
[
"Raman Spectral Denoising/train.py"
] |
[
"import os\r\nimport sys\r\nimport random\r\nimport datetime\r\nimport time\r\nimport shutil\r\nimport argparse\r\nimport warnings\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport scipy.io\r\nimport scipy.signal\r\nimport math\r\nfrom skimage.measure import compare_ssim as sk_ssim\r\n\r\nimport torch\r\nfrom torch import nn\r\nimport torch.nn.parallel\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport torch.distributed as dist\r\nimport torch.utils.data.distributed\r\nimport torch.multiprocessing as mp\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nfrom torchvision import transforms, utils\r\n\r\nimport model, dataset, utilities\r\n\r\n\r\nparser = argparse.ArgumentParser(description='DeNoiser Training')\r\n\r\nparser.add_argument('-path', '--path_to_data', default='./', type=str,\r\n help='directory containing inputs.pkl and outputs.pkl (default: ./)')\r\n\r\nparser.add_argument('-j', '--workers', default=0, type=int, metavar='N',\r\n help='number of data loading workers (default: 0)')\r\nparser.add_argument('--epochs', default=500, type=int, metavar='N',\r\n help='number of total epochs to run (default: 200)')\r\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\r\n help='manual epoch number (useful on restarts)')\r\nparser.add_argument('-b', '--batch-size', default=256, type=int,\r\n metavar='N',\r\n help='mini-batch size (default: 2), this is the total '\r\n 'batch size of all GPUs on the current node when '\r\n 'using Data Parallel or Distributed Data Parallel')\r\nparser.add_argument('--optimizer', default='adam', type=str,\r\n help='optimizer')\r\nparser.add_argument('--lr', '--learning-rate', default=5e-4, type=float,\r\n metavar='LR', help='initial learning rate (default: 5e-4)', dest='lr')\r\nparser.add_argument('--base-lr', '--base-learning-rate', default=5e-6, type=float,\r\n help='base learning rate (default: 5e-6)')\r\nparser.add_argument('--scheduler', default='constant-lr', type=str,\r\n help='scheduler')\r\nparser.add_argument('--batch-norm', action='store_true',\r\n help='apply batch norm')\r\nparser.add_argument('--spectrum-len', default=500, type=int,\r\n help='spectrum length (default: 350)')\r\nparser.add_argument('--seed', default=None, type=int,\r\n help='seed for initializing training. ')\r\nparser.add_argument('--gpu', default=0, type=int,\r\n help='GPU id to use.')\r\nparser.add_argument('--world-size', default=-1, type=int,\r\n help='number of nodes for distributed training')\r\nparser.add_argument('--rank', default=-1, type=int,\r\n help='node rank for distributed training')\r\nparser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,\r\n help='url used to set up distributed training')\r\nparser.add_argument('--dist-backend', default='nccl', type=str,\r\n help='distributed backend')\r\nparser.add_argument('--multiprocessing-distributed', action='store_true',\r\n help='Use multi-processing distributed training to launch '\r\n 'N processes per node, which has N GPUs. This is the '\r\n 'fastest way to use PyTorch for either single node or '\r\n 'multi node data parallel training')\r\n\r\n\r\ndef main():\r\n args = parser.parse_args()\r\n\r\n if args.seed is not None:\r\n random.seed(args.seed)\r\n torch.manual_seed(args.seed)\r\n cudnn.deterministic = True\r\n\r\n if args.dist_url == \"env://\" and args.world_size == -1:\r\n args.world_size = int(os.environ[\"WORLD_SIZE\"])\r\n\r\n args.distributed = args.world_size > 1 or args.multiprocessing_distributed\r\n\r\n ngpus_per_node = torch.cuda.device_count()\r\n\r\n if args.multiprocessing_distributed:\r\n args.world_size = ngpus_per_node * args.world_size\r\n mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\r\n else:\r\n main_worker(args.gpu, ngpus_per_node, args)\r\n\r\ndef main_worker(gpu, ngpus_per_node, args):\r\n args.gpu = gpu\r\n\r\n if args.gpu is not None:\r\n print(\"Use GPU: {} for training\".format(args.gpu))\r\n\r\n if args.distributed:\r\n if args.dist_url == \"env://\" and args.rank == -1:\r\n args.rank = int(os.environ[\"RANK\"])\r\n if args.multiprocessing_distributed:\r\n args.rank = args.rank * ngpus_per_node + gpu\r\n dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\r\n world_size=args.world_size, rank=args.rank)\r\n \r\n # ----------------------------------------------------------------------------------------\r\n # Create model(s) and send to device(s)\r\n # ----------------------------------------------------------------------------------------\r\n net = model.ResUNet(3, args.batch_norm).float()\r\n\r\n if args.distributed:\r\n if args.gpu is not None:\r\n torch.cuda.set_device(args.gpu)\r\n args.batch_size = int(args.batch_size / ngpus_per_node)\r\n args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node)\r\n\r\n net.cuda(args.gpu)\r\n net = torch.nn.parallel.DistributedDataParallel(net, device_ids=[args.gpu])\r\n else:\r\n net.cuda(args.gpu)\r\n net = torch.nn.parallel.DistributedDataParallel(net)\r\n elif args.gpu is not None:\r\n torch.cuda.set_device(args.gpu)\r\n net.cuda(args.gpu)\r\n else:\r\n net.cuda(args.gpu)\r\n net = torch.nn.parallel.DistributedDataParallel(net)\r\n\r\n # ----------------------------------------------------------------------------------------\r\n # Define dataset path and data splits\r\n # ---------------------------------------------------------------------------------------- \r\n #Input_Data = #scipy.io.loadmat(\"\\Path\\To\\Inputs.mat\")\r\n #Output_Data = #scipy.io.loadmat(\"\\Path\\To\\Outputs.mat\")\r\n\r\n Input = utilities.load_obj(f'{args.path_to_data}/inputs') #Input_Data['Inputs']\r\n Output = utilities.load_obj(f'{args.path_to_data}/outputs') # Output_Data['Outputs']\r\n\r\n spectra_num = len(Input)\r\n\r\n train_split = round(0.9 * spectra_num)\r\n val_split = round(0.1 * spectra_num)\r\n\r\n input_train = Input[:train_split]\r\n input_val = Input[train_split:train_split+val_split]\r\n\r\n output_train = Output[:train_split]\r\n output_val = Output[train_split:train_split+val_split]\r\n\r\n # ----------------------------------------------------------------------------------------\r\n # Create datasets (with augmentation) and dataloaders\r\n # ----------------------------------------------------------------------------------------\r\n Raman_Dataset_Train = dataset.RamanDataset(input_train, output_train, batch_size = args.batch_size, spectrum_len = args.spectrum_len,\r\n spectrum_shift=0.1, spectrum_window = False, horizontal_flip = False, mixup = True)\r\n\r\n Raman_Dataset_Val = dataset.RamanDataset(input_val, output_val, batch_size = args.batch_size, spectrum_len = args.spectrum_len)\r\n\r\n train_loader = DataLoader(Raman_Dataset_Train, batch_size = args.batch_size, shuffle = False, num_workers = 0, pin_memory = True)\r\n val_loader = DataLoader(Raman_Dataset_Val, batch_size = args.batch_size, shuffle = False, num_workers = 0, pin_memory = True)\r\n\r\n # ----------------------------------------------------------------------------------------\r\n # Define criterion(s), optimizer(s), and scheduler(s)\r\n # ----------------------------------------------------------------------------------------\r\n criterion = nn.L1Loss().cuda(args.gpu)\r\n criterion_MSE = nn.MSELoss().cuda(args.gpu)\r\n if args.optimizer == \"sgd\":\r\n optimizer = optim.SGD(net.parameters(), lr = args.lr)\r\n elif args.optimizer == \"adamW\":\r\n optimizer = optim.AdamW(net.parameters(), lr = args.lr)\r\n else: # Adam\r\n optimizer = optim.Adam(net.parameters(), lr = args.lr)\r\n\r\n if args.scheduler == \"decay-lr\":\r\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.2)\r\n elif args.scheduler == \"multiplicative-lr\":\r\n lmbda = lambda epoch: 0.985\r\n scheduler = optim.lr_scheduler.MultiplicativeLR(optimizer, lr_lambda=lmbda)\r\n elif args.scheduler == \"cyclic-lr\":\r\n scheduler = optim.lr_scheduler.CyclicLR(optimizer, base_lr = args.base_lr, max_lr = args.lr, mode = 'triangular2', cycle_momentum = False)\r\n elif args.scheduler == \"one-cycle-lr\":\r\n scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr = args.lr, steps_per_epoch=len(train_loader), epochs=args.epochs, cycle_momentum = False)\r\n else: # constant-lr\r\n scheduler = None\r\n\r\n print('Started Training')\r\n print('Training Details:')\r\n #print('Network: {}'.format(args.network))\r\n print('Epochs: {}'.format(args.epochs))\r\n print('Batch Size: {}'.format(args.batch_size))\r\n print('Optimizer: {}'.format(args.optimizer))\r\n print('Scheduler: {}'.format(args.scheduler))\r\n print('Learning Rate: {}'.format(args.lr))\r\n print('Spectrum Length: {}'.format(args.spectrum_len))\r\n\r\n DATE = datetime.datetime.now().strftime(\"%Y_%m_%d\")\r\n\r\n log_dir = \"runs/{}_{}_{}\".format(DATE, args.optimizer, args.scheduler) #, args.network)\r\n models_dir = \"{}_{}_{}.pt\".format(DATE, args.optimizer, args.scheduler) #, args.network)\r\n\r\n writer = SummaryWriter(log_dir = log_dir)\r\n\r\n for epoch in range(args.epochs):\r\n train_loss = train(train_loader, net, optimizer, scheduler, criterion, criterion_MSE, epoch, args)\r\n val_loss = validate(val_loader, net, criterion_MSE, args)\r\n if args.scheduler == \"decay-lr\" or args.scheduler == \"multiplicative-lr\":\r\n scheduler.step()\r\n \r\n writer.add_scalar('Loss/train', train_loss, epoch)\r\n writer.add_scalar('Loss/val', val_loss, epoch)\r\n \r\n torch.save(net.state_dict(), models_dir)\r\n print('Finished Training')\r\n\r\ndef train(dataloader, net, optimizer, scheduler, criterion, criterion_MSE, epoch, args):\r\n \r\n batch_time = utilities.AverageMeter('Time', ':6.3f')\r\n losses = utilities.AverageMeter('Loss', ':.4e')\r\n progress = utilities.ProgressMeter(len(dataloader), [batch_time, losses], prefix=\"Epoch: [{}]\".format(epoch))\r\n\r\n end = time.time()\r\n for i, data in enumerate(dataloader):\r\n inputs = data['input_spectrum']\r\n inputs = inputs.float()\r\n inputs = inputs.cuda(args.gpu)\r\n target = data['output_spectrum']\r\n target = target.float()\r\n target = target.cuda(args.gpu)\r\n\r\n output = net(inputs)\r\n\r\n optimizer.zero_grad()\r\n loss = criterion(output, target)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n if args.scheduler == \"cyclic-lr\" or args.scheduler == \"one-cycle-lr\":\r\n scheduler.step() \r\n\r\n loss_MSE = criterion_MSE(output, target)\r\n losses.update(loss_MSE.item(), inputs.size(0)) \r\n\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n\r\n if i % 400 == 0:\r\n progress.display(i)\r\n return losses.avg\r\n\r\n\r\ndef validate(dataloader, net, criterion_MSE, args):\r\n batch_time = utilities.AverageMeter('Time', ':6.3f')\r\n losses = utilities.AverageMeter('Loss', ':.4e')\r\n progress = utilities.ProgressMeter(len(dataloader), [batch_time, losses], prefix='Validation: ')\r\n\r\n with torch.no_grad():\r\n end = time.time()\r\n for i, data in enumerate(dataloader):\r\n inputs = data['input_spectrum']\r\n inputs = inputs.float()\r\n inputs = inputs.cuda(args.gpu)\r\n target = data['output_spectrum']\r\n target = target.float()\r\n target = target.cuda(args.gpu)\r\n\r\n output = net(inputs)\r\n\r\n loss_MSE = criterion_MSE(output, target)\r\n losses.update(loss_MSE.item(), inputs.size(0))\r\n\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n\r\n if i % 400 == 0:\r\n progress.display(i)\r\n\r\n return losses.avg\r\n\r\n\r\nif __name__ == '__main__':\r\n main()"
] |
[
[
"torch.nn.MSELoss",
"torch.optim.lr_scheduler.CyclicLR",
"torch.distributed.init_process_group",
"torch.multiprocessing.spawn",
"torch.cuda.set_device",
"torch.optim.lr_scheduler.MultiplicativeLR",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.device_count",
"torch.nn.L1Loss",
"torch.nn.parallel.DistributedDataParallel",
"torch.optim.lr_scheduler.StepLR"
]
] |
mdpiper/fortran-explorations
|
[
"a82147365ef8f4325e608c2316842e932a37cf7b"
] |
[
"bmi/bmiheat_ex.py"
] |
[
"\"\"\"An example of calling a Fortran BMI through Cython.\"\"\"\n\nimport numpy as np\nfrom bmi_heat import Heat\n\n\nconfig_file = 'test.cfg'\n\n\nnp.set_printoptions(formatter={'float': '{: 6.1f}'.format})\n\n# Instantiate a model and get its name.\nm = Heat()\nprint(m.get_component_name())\n\n# Initialize the model.\nm.initialize(config_file)\n\n# List the model's echange items.\nprint('Input vars:', m.get_input_var_names())\nprint('Output vars:', m.get_output_var_names())\n\n# Get time information from the model.\nprint('Start time:', m.get_start_time())\nprint('End time:', m.get_end_time())\nprint('Current time:', m.get_current_time())\nprint('Time step:', m.get_time_step())\nprint('Time units:', m.get_time_units())\n\n# Advance the model by one time step.\nm.update()\nprint('Current time:', m.get_current_time())\n\n# Advance the model by a fractional time step.\nm.update_frac(0.75)\nprint('Current time:', m.get_current_time())\n\n# Advance the model until a later time.\nm.update_until(10.0)\nprint('Current time:', m.get_current_time())\n\n# Get the grid_id for the plate_surface__temperature variable.\nvar_name = 'plate_surface__temperature'\nprint('Variable {}'.format(var_name))\ngrid_id = m.get_var_grid(var_name)\nprint(' - grid id:', grid_id)\n\n# Get grid and variable info for plate_surface__temperature.\nprint(' - grid type:', m.get_grid_type(grid_id))\ngrid_rank = m.get_grid_rank(grid_id)\nprint(' - rank:', grid_rank)\ngrid_shape = np.empty(grid_rank, dtype=np.int32)\nm.get_grid_shape(grid_id, grid_shape)\nprint(' - shape:', grid_shape)\ngrid_size = m.get_grid_size(grid_id)\nprint(' - size:', grid_size)\ngrid_spacing = np.empty(grid_rank, dtype=np.float64)\nm.get_grid_spacing(grid_id, grid_spacing)\nprint(' - spacing:', grid_spacing)\ngrid_origin = np.empty(grid_rank, dtype=np.float64)\nm.get_grid_origin(grid_id, grid_origin)\nprint(' - origin:', grid_origin)\nprint(' - variable type:', m.get_var_type(var_name))\nprint(' - units:', m.get_var_units(var_name))\nprint(' - itemsize:', m.get_var_itemsize(var_name))\nprint(' - nbytes:', m.get_var_nbytes(var_name))\n\n# Get the temperature values.\nval = np.empty(grid_shape, dtype=np.float32)\nm.get_value(var_name, val)\nprint(' - values (streamwise):')\nprint(val)\nprint(' - values (gridded):')\nprint(val.reshape(np.roll(grid_shape, 1)))\n\n# Set new temperature values.\nnew = np.arange(grid_size, dtype=np.float32) # 'real*4 in Fortran\nm.set_value(var_name, new)\ncheck = np.empty(grid_shape, dtype=np.float32)\nm.get_value(var_name, check)\nprint(' - new values (set/get, streamwise):');\nprint(check)\n\n# Get a reference to the temperature values and check that it updates.\nprint(' - values (by ref, streamwise) at time {}:'.format(m.get_current_time()))\nref = m.get_value_ptr(var_name)\nprint(ref)\nm.update()\nprint(' - values (by ref, streamwise) at time {}:'.format(m.get_current_time()))\nprint(ref)\n\n# Get the grid_id for the plate_surface__thermal_diffusivity variable.\nvar_name = 'plate_surface__thermal_diffusivity'\nprint('Variable {}'.format(var_name))\ngrid_id = m.get_var_grid(var_name)\nprint(' - grid id:', grid_id)\n\n# Get grid and variable info for plate_surface__thermal_diffusivity.\nprint(' - grid type:', m.get_grid_type(grid_id))\ngrid_rank = m.get_grid_rank(grid_id)\nprint(' - rank:', grid_rank)\nprint(' - size:', m.get_grid_size(grid_id))\ngrid_x = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_x(grid_id, grid_x)\nprint(' - x:', grid_x)\ngrid_y = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_y(grid_id, grid_y)\nprint(' - y:', grid_y)\ngrid_z = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_z(grid_id, grid_z)\nprint(' - z:', grid_z)\ngrid_connectivity = np.empty(max(grid_rank, 1), dtype=np.int32)\nm.get_grid_connectivity(grid_id, grid_connectivity)\nprint(' - connectivity:', grid_connectivity)\ngrid_offset = np.empty(max(grid_rank, 1), dtype=np.int32)\nm.get_grid_offset(grid_id, grid_offset)\nprint(' - offset:', grid_offset)\nprint(' - variable type:', m.get_var_type(var_name))\nprint(' - units:', m.get_var_units(var_name))\nprint(' - itemsize:', m.get_var_itemsize(var_name))\nprint(' - nbytes:', m.get_var_nbytes(var_name))\n\n# Get the diffusivity values.\nval = np.empty(1, dtype=np.float32)\nm.get_value(var_name, val)\nprint(' - values:')\nprint(val)\n\n# Get the grid_id for the model__identification_number variable.\nvar_name = 'model__identification_number'\nprint('Variable {}'.format(var_name))\ngrid_id = m.get_var_grid(var_name)\nprint(' - grid id:', grid_id)\n\n# Get grid and variable info for model__identification_number.\nprint(' - grid type:', m.get_grid_type(grid_id))\ngrid_rank = m.get_grid_rank(grid_id)\nprint(' - rank:', grid_rank)\nprint(' - size:', m.get_grid_size(grid_id))\ngrid_x = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_x(grid_id, grid_x)\nprint(' - x:', grid_x)\ngrid_y = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_y(grid_id, grid_y)\nprint(' - y:', grid_y)\ngrid_z = np.empty(max(grid_rank, 1), dtype=np.float64)\nm.get_grid_z(grid_id, grid_z)\nprint(' - z:', grid_z)\ngrid_connectivity = np.empty(max(grid_rank, 1), dtype=np.int32)\nm.get_grid_connectivity(grid_id, grid_connectivity)\nprint(' - connectivity:', grid_connectivity)\ngrid_offset = np.empty(max(grid_rank, 1), dtype=np.int32)\nm.get_grid_offset(grid_id, grid_offset)\nprint(' - offset:', grid_offset)\nprint(' - variable type:', m.get_var_type(var_name))\nprint(' - units:', m.get_var_units(var_name))\nprint(' - itemsize:', m.get_var_itemsize(var_name))\nprint(' - nbytes:', m.get_var_nbytes(var_name))\n\n# Get the model id.\nval = np.empty(1, dtype=np.int32)\nm.get_value(var_name, val)\nprint(' - values:')\nprint(val)\n\n# Set new model id.\nnew = np.array(42, dtype=np.intc)\nm.set_value(var_name, new)\ncheck = np.empty(1, dtype=np.int32)\nm.get_value(var_name, check)\nprint(' - new values (set/get):');\nprint(check)\n\n# Finalize the model.\nm.finalize()\n\n# Check that number of instances can't exceed N_MODELS=3.\n# a = Heat()\n# b = Heat()\n# c = Heat() # should fail with index=-1\n"
] |
[
[
"numpy.arange",
"numpy.set_printoptions",
"numpy.array",
"numpy.roll",
"numpy.empty"
]
] |
AleksZhuravlyov/dpnm_validation
|
[
"13bdee4b79f9737e3d78caa6b04c98b1c34401db"
] |
[
"sgrid/script.py"
] |
[
"# MIT License\n# \n# Copyright (c) 2020 Aleksandr Zhuravlyov and Zakhar Lanets\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\nimport sys\nimport os\nimport numpy as np\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(current_path))\n\nfrom vtkIO import SGrid\n\npoints_dims = np.array([5, 5, 5], dtype=np.int32)\npoints_origin = np.array([0., 0., 0.], dtype=np.float)\nspacing = np.array([1., 1., 1.], dtype=np.float)\n\nsgrid = SGrid(points_dims, points_origin, spacing)\nprint(\"cells_dims\", sgrid.cells_dims)\nprint()\n\nprint(\"points_dims\", sgrid.points_dims)\nprint(\"spacing\", sgrid.spacing)\nprint(\"points_origin\", sgrid.points_origin)\nprint(\"points_N\", sgrid.points_N)\nprint(\"cells_dims\", sgrid.cells_dims)\nprint(\"cells_N\", sgrid.cells_N)\nprint(\"faces_dims\", sgrid.faces_dims)\nprint(\"faces_N\", sgrid.faces_N)\nprint(\"cell_V\", sgrid.cell_V)\nprint(\"face_S\", sgrid.face_S)\nprint(\"neighbors_faces\", sgrid.neighbors_faces)\nprint(\"neighbors_cells\", sgrid.neighbors_cells)\nprint(\"normals_neighbors_cells\", sgrid.normals_neighbors_cells)\nprint(\"normals_neighbors_faces\", sgrid.normals_neighbors_faces)\n\n\npoints_array1 = np.random.rand(sgrid.points_N)\npoints_array2 = np.random.rand(sgrid.points_N)\npoints_arrays = {\"points_array1\": points_array1, \"points_array2\": points_array2}\nsgrid.points_arrays = points_arrays\n\ncells_array1 = np.random.rand(sgrid.cells_N)\ncells_array2 = np.random.rand(sgrid.cells_N)\ncells_arrays = {\"cells_array1 \": cells_array1, \"cells_array2\": cells_array2}\nsgrid.cells_arrays = cells_arrays\n\nprint(\"points_arrays\", sgrid.points_arrays)\nprint(\"cells_arrays\", sgrid.cells_arrays)\n\nsgrid.save('file_name.vtu')\n\n\nsgridRead = SGrid('file_name.vtu')\nprint()\nprint(\"points_dims\", sgridRead.points_dims)\nprint(\"spacing\", sgridRead.spacing)\nprint(\"points_origin\", sgridRead.points_origin)\nprint(\"points_N\", sgridRead.points_N)\nprint(\"cells_dims\", sgridRead.cells_dims)\nprint(\"cells_N\", sgridRead.cells_N)\nprint(\"cell_V\", sgridRead.cell_V)\nprint(\"face_S\", sgridRead.face_S)\nprint(\"neighbors_faces\", sgridRead.neighbors_faces)\nprint(\"neighbors_cells\", sgridRead.neighbors_cells)\nprint(\"normals_neighbors_cells\", sgridRead.normals_neighbors_cells)\nprint(\"normals_neighbors_faces\", sgridRead.normals_neighbors_faces)\nprint(\"points_arrays\", sgridRead.points_arrays)\nprint(\"cells_arrays\", sgridRead.cells_arrays)\n\nsgridRead.save('read.vtu')\n\n\n\n"
] |
[
[
"numpy.array",
"numpy.random.rand"
]
] |
IgorTavcar/classla
|
[
"5a1246b62eb352af631d4f4593f467e9ccbd3777"
] |
[
"classla/models/charlm.py"
] |
[
"\"\"\"\nEntry point for training and evaluating a character-level neural language model.\n\"\"\"\n\nimport random\nimport argparse\nfrom copy import copy\nfrom collections import Counter\nfrom types import GeneratorType\nimport numpy as np\nimport torch\nimport math\nimport logging\nimport time\nimport os\n\nfrom classla.models.common.char_model import CharacterLanguageModel\nfrom classla.models.pos.vocab import CharVocab\nfrom classla.models.common import utils\nfrom classla.models import _training_logging\n\nlogger = logging.getLogger('classla')\n\ndef repackage_hidden(h):\n \"\"\"Wraps hidden states in new Tensors,\n to detach them from their history.\"\"\"\n if isinstance(h, torch.Tensor):\n return h.detach()\n else:\n return tuple(repackage_hidden(v) for v in h)\n\ndef batchify(data, bsz):\n # Work out how cleanly we can divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1) # batch_first is True\n return data\n\ndef get_batch(source, i, seq_len):\n seq_len = min(seq_len, source.size(1) - 1 - i)\n data = source[:, i:i+seq_len]\n target = source[:, i+1:i+1+seq_len].reshape(-1)\n return data, target\n\ndef build_vocab(path, cutoff=0):\n # Requires a large amount of memeory, but only need to build once\n if os.path.isdir(path):\n # here we need some trick to deal with excessively large files\n # for each file we accumulate the counter of characters, and \n # at the end we simply pass a list of chars to the vocab builder\n counter = Counter()\n filenames = sorted(os.listdir(path))\n for filename in filenames:\n lines = open(path + '/' + filename).readlines()\n for line in lines:\n counter.update(list(line))\n # remove infrequent characters from vocab\n for k in list(counter.keys()):\n if counter[k] < cutoff:\n del counter[k]\n # a singleton list of all characters\n data = [sorted([x[0] for x in counter.most_common()])]\n vocab = CharVocab(data) # skip cutoff argument because this has been dealt with\n else:\n lines = open(path).readlines() # reserve '\\n'\n data = [list(line) for line in lines]\n vocab = CharVocab(data, cutoff=cutoff)\n return vocab\n\ndef load_file(path, vocab, direction):\n lines = open(path).readlines() # reserve '\\n'\n data = list(''.join(lines))\n idx = vocab['char'].map(data)\n if direction == 'backward': idx = idx[::-1]\n return torch.tensor(idx)\n\ndef load_data(path, vocab, direction):\n if os.path.isdir(path):\n filenames = sorted(os.listdir(path))\n for filename in filenames:\n logger.info('Loading data from {}'.format(filename))\n data = load_file(path + '/' + filename, vocab, direction)\n yield data\n else:\n data = load_file(path, vocab, direction)\n yield data\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--train_file', type=str, help=\"Input plaintext file\")\n parser.add_argument('--train_dir', type=str, help=\"If non-emtpy, load from directory with multiple training files\")\n parser.add_argument('--eval_file', type=str, help=\"Input plaintext file for the dev/test set\")\n parser.add_argument('--lang', type=str, help=\"Language\")\n parser.add_argument('--shorthand', type=str, help=\"UD treebank shorthand\")\n\n parser.add_argument('--mode', default='train', choices=['train', 'predict'])\n parser.add_argument('--direction', default='forward', choices=['forward', 'backward'], help=\"Forward or backward language model\")\n\n parser.add_argument('--char_emb_dim', type=int, default=100, help=\"Dimension of unit embeddings\")\n parser.add_argument('--char_hidden_dim', type=int, default=1024, help=\"Dimension of hidden units\")\n parser.add_argument('--char_num_layers', type=int, default=1, help=\"Layers of RNN in the language model\")\n parser.add_argument('--char_dropout', type=float, default=0.05, help=\"Dropout probability\")\n parser.add_argument('--char_unit_dropout', type=float, default=1e-5, help=\"Randomly set an input char to UNK during training\")\n parser.add_argument('--char_rec_dropout', type=float, default=0.0, help=\"Recurrent dropout probability\")\n\n parser.add_argument('--batch_size', type=int, default=100, help=\"Batch size to use\")\n parser.add_argument('--bptt_size', type=int, default=250, help=\"Sequence length to consider at a time\")\n parser.add_argument('--epochs', type=int, default=50, help=\"Total epochs to train the model for\")\n parser.add_argument('--max_grad_norm', type=float, default=0.25, help=\"Maximum gradient norm to clip to\")\n parser.add_argument('--lr0', type=float, default=20, help=\"Initial learning rate\")\n parser.add_argument('--anneal', type=float, default=0.25, help=\"Anneal the learning rate by this amount when dev performance deteriorate\")\n parser.add_argument('--patience', type=int, default=1, help=\"Patience for annealing the learning rate\")\n parser.add_argument('--weight_decay', type=float, default=0.0, help=\"Weight decay\")\n parser.add_argument('--momentum', type=float, default=0.0, help='Momentum for SGD.')\n parser.add_argument('--cutoff', type=int, default=1000, help=\"Frequency cutoff for char vocab. By default we assume a very large corpus.\")\n \n parser.add_argument('--report_steps', type=int, default=50, help=\"Update step interval to report loss\")\n parser.add_argument('--eval_steps', type=int, default=-1, help=\"Update step interval to run eval on dev; set to -1 to eval after each epoch\")\n parser.add_argument('--save_name', type=str, default=None, help=\"File name to save the model\")\n parser.add_argument('--vocab_save_name', type=str, default=None, help=\"File name to save the vocab\")\n parser.add_argument('--save_dir', type=str, default='saved_models/charlm', help=\"Directory to save models in\")\n parser.add_argument('--summary', action='store_true', help='Use summary writer to record progress.')\n parser.add_argument('--cuda', type=bool, default=torch.cuda.is_available())\n parser.add_argument('--cpu', action='store_true', help='Ignore CUDA and run on CPU.')\n parser.add_argument('--seed', type=int, default=1234)\n args = parser.parse_args()\n return args\n\ndef main():\n args = parse_args()\n\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n random.seed(args.seed)\n if args.cpu:\n args.cuda = False\n elif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n args = vars(args)\n logger.info(\"Running {} character-level language model in {} mode\".format(args['direction'], args['mode']))\n \n utils.ensure_dir(args['save_dir'])\n\n if args['mode'] == 'train':\n train(args)\n else:\n evaluate(args)\n\ndef evaluate_epoch(args, vocab, data, model, criterion):\n \"\"\"\n Run an evaluation over entire dataset.\n \"\"\"\n model.eval()\n hidden = None\n total_loss = 0\n if isinstance(data, GeneratorType):\n data = list(data)\n assert len(data) == 1, 'Only support single dev/test file'\n data = data[0]\n batches = batchify(data, args['batch_size'])\n with torch.no_grad():\n for i in range(0, batches.size(1) - 1, args['bptt_size']):\n data, target = get_batch(batches, i, args['bptt_size'])\n lens = [data.size(1) for i in range(data.size(0))]\n if args['cuda']:\n data = data.cuda()\n target = target.cuda()\n\n output, hidden, decoded = model.forward(data, lens, hidden)\n loss = criterion(decoded.view(-1, len(vocab['char'])), target)\n \n hidden = repackage_hidden(hidden)\n total_loss += data.size(1) * loss.data.item()\n return total_loss / batches.size(1)\n\ndef evaluate_and_save(args, vocab, data, model, criterion, scheduler, best_loss, global_step, model_file, writer=None):\n \"\"\"\n Run an evaluation over entire dataset, print progress and save the model if necessary.\n \"\"\"\n start_time = time.time()\n loss = evaluate_epoch(args, vocab, data, model, criterion)\n ppl = math.exp(loss)\n elapsed = int(time.time() - start_time)\n scheduler.step(loss)\n logger.info(\n \"| eval checkpoint @ global step {:10d} | time elapsed {:6d}s | loss {:5.2f} | ppl {:8.2f}\".format(\n global_step,\n elapsed,\n loss,\n ppl,\n )\n )\n if best_loss is None or loss < best_loss:\n best_loss = loss\n model.save(model_file)\n logger.info('new best model saved at step {:10d}.'.format(global_step))\n if writer:\n writer.add_scalar('dev_loss', loss, global_step=global_step)\n writer.add_scalar('dev_ppl', ppl, global_step=global_step)\n return loss, ppl, best_loss\n\ndef train(args):\n model_file = args['save_dir'] + '/' + args['save_name'] if args['save_name'] is not None \\\n else '{}/{}_{}_charlm.pt'.format(args['save_dir'], args['shorthand'], args['direction'])\n vocab_file = args['save_dir'] + '/' + args['vocab_save_name'] if args['vocab_save_name'] is not None \\\n else '{}/{}_vocab.pt'.format(args['save_dir'], args['shorthand'])\n\n if os.path.exists(vocab_file):\n logger.info('Loading existing vocab file')\n vocab = {'char': CharVocab.load_state_dict(torch.load(vocab_file, lambda storage, loc: storage))}\n else:\n logger.info('Building and saving vocab')\n vocab = {'char': build_vocab(args['train_file'] if args['train_dir'] is None else args['train_dir'], cutoff=args['cutoff'])}\n torch.save(vocab['char'].state_dict(), vocab_file)\n logger.info(\"Training model with vocab size: {}\".format(len(vocab['char'])))\n\n model = CharacterLanguageModel(args, vocab, is_forward_lm=True if args['direction'] == 'forward' else False)\n if args['cuda']: model = model.cuda()\n params = [param for param in model.parameters() if param.requires_grad]\n optimizer = torch.optim.SGD(params, lr=args['lr0'], momentum=args['momentum'], weight_decay=args['weight_decay'])\n criterion = torch.nn.CrossEntropyLoss()\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, verbose=True, factor=args['anneal'], patience=args['patience'])\n\n writer = None\n if args['summary']:\n from torch.utils.tensorboard import SummaryWriter\n summary_dir = '{}/{}_summary'.format(args['save_dir'], args['save_name']) if args['save_name'] is not None \\\n else '{}/{}_{}_charlm_summary'.format(args['save_dir'], args['shorthand'], args['direction'])\n writer = SummaryWriter(log_dir=summary_dir)\n \n # evaluate model within epoch if eval_interval is set\n eval_within_epoch = False\n if args['eval_steps'] > 0:\n eval_within_epoch = True\n\n best_loss = None\n global_step = 0\n for epoch in range(1,args['epochs']+1):\n # load train data from train_dir if not empty, otherwise load from file\n if args['train_dir'] is not None:\n train_path = args['train_dir']\n else:\n train_path = args['train_file']\n train_data = load_data(train_path, vocab, args['direction'])\n dev_data = load_file(args['eval_file'], vocab, args['direction']) # dev must be a single file\n\n # run over entire training set\n for data_chunk in train_data:\n batches = batchify(data_chunk, args['batch_size'])\n hidden = None\n total_loss = 0.0\n total_batches = math.ceil((batches.size(1) - 1) / args['bptt_size'])\n iteration, i = 0, 0\n # over the data chunk\n while i < batches.size(1) - 1 - 1:\n model.train()\n global_step += 1\n start_time = time.time()\n bptt = args['bptt_size'] if np.random.random() < 0.95 else args['bptt_size']/ 2.\n # prevent excessively small or negative sequence lengths\n seq_len = max(5, int(np.random.normal(bptt, 5)))\n # prevent very large sequence length, must be <= 1.2 x bptt\n seq_len = min(seq_len, int(args['bptt_size'] * 1.2))\n data, target = get_batch(batches, i, seq_len)\n lens = [data.size(1) for i in range(data.size(0))]\n if args['cuda']:\n data = data.cuda()\n target = target.cuda()\n \n optimizer.zero_grad()\n output, hidden, decoded = model.forward(data, lens, hidden)\n loss = criterion(decoded.view(-1, len(vocab['char'])), target)\n total_loss += loss.data.item()\n loss.backward()\n\n torch.nn.utils.clip_grad_norm_(params, args['max_grad_norm'])\n optimizer.step()\n\n hidden = repackage_hidden(hidden)\n\n if (iteration + 1) % args['report_steps'] == 0:\n cur_loss = total_loss / args['report_steps']\n elapsed = time.time() - start_time\n logger.info(\n \"| epoch {:5d} | {:5d}/{:5d} batches | sec/batch {:.6f} | loss {:5.2f} | ppl {:8.2f}\".format(\n epoch,\n iteration + 1,\n total_batches,\n elapsed / args['report_steps'],\n cur_loss,\n math.exp(cur_loss),\n )\n )\n total_loss = 0.0\n\n iteration += 1\n i += seq_len\n\n # evaluate if necessary\n if eval_within_epoch and global_step % args['eval_steps'] == 0:\n _, _, best_loss = evaluate_and_save(args, vocab, dev_data, model, criterion, scheduler, best_loss, \\\n global_step, model_file, writer)\n\n # if eval_interval isn't provided, run evaluation after each epoch\n if not eval_within_epoch:\n _, _, best_loss = evaluate_and_save(args, vocab, dev_data, model, criterion, scheduler, best_loss, \\\n epoch, model_file, writer) # use epoch in place of global_step for logging\n\n if writer:\n writer.close()\n return\n\ndef evaluate(args):\n model_file = args['save_dir'] + '/' + args['save_name'] if args['save_name'] is not None \\\n else '{}/{}_{}_charlm.pt'.format(args['save_dir'], args['shorthand'], args['direction'])\n\n model = CharacterLanguageModel.load(model_file)\n if args['cuda']: model = model.cuda()\n vocab = model.vocab\n data = load_data(args['eval_file'], vocab, args['direction'])\n criterion = torch.nn.CrossEntropyLoss()\n \n loss = evaluate_epoch(args, vocab, data, model, criterion)\n logger.info(\n \"| best model | loss {:5.2f} | ppl {:8.2f}\".format(\n loss,\n math.exp(loss),\n )\n )\n return\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"numpy.random.random",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.load",
"torch.manual_seed",
"torch.tensor",
"torch.nn.utils.clip_grad_norm_",
"numpy.random.normal",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"torch.optim.SGD"
]
] |
zzs1994/DJsRH
|
[
"6041c2df810723dd0052e2e5b7c6bd33033f0f21"
] |
[
"datasets.py"
] |
[
"import torch\nimport cv2\nimport scipy.io as scio\nfrom PIL import Image\nimport settings\nimport numpy as np\nimport scipy.io as scio\nfrom torchvision import transforms\nimport h5py\n\n\nif settings.DATASET == \"WIKI\":\n\n label_set = scio.loadmat(settings.LABEL_DIR)\n test_txt = np.array(label_set['T_te'], dtype=np.float)\n train_txt = np.array(label_set['T_tr'], dtype=np.float)\n\n\n test_label = []\n with open(settings.TEST_LABEL, 'r') as f:\n for line in f.readlines(): \n test_label.extend([int(line.split()[-1])-1])\n\n test_img_name = []\n with open(settings.TEST_LABEL, 'r') as f:\n for line in f.readlines(): \n test_img_name.extend([line.split()[1]])\n \n\n train_label = []\n with open(settings.TRAIN_LABEL, 'r') as f:\n for line in f.readlines(): \n train_label.extend([int(line.split()[-1])-1])\n\n train_img_name = []\n with open(settings.TRAIN_LABEL, 'r') as f:\n for line in f.readlines(): \n train_img_name.extend([line.split()[1]])\n\n wiki_train_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n wiki_test_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n txt_feat_len = train_txt.shape[1]\n\n\n class WIKI(torch.utils.data.Dataset):\n\n def __init__(self, root, transform=None, target_transform=None, train=True):\n self.root = root\n self.transform = transform\n self.target_transform = target_transform\n self.f_name =['art','biology','geography','history','literature','media','music','royalty','sport','warfare']\n\n if train:\n self.label = train_label\n self.img_name = train_img_name\n self.txt = train_txt\n else:\n self.label = test_label\n self.img_name = test_img_name\n self.txt = test_txt\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n \n path = self.root + '/' + self.f_name[self.label[index]] + '/' + self.img_name[index] + '.jpg'\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = Image.fromarray(img)\n target = self.label[index]\n txt = self.txt[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, txt, target, index\n\n def __len__(self):\n return len(self.label)\n\n\nif settings.DATASET == \"MIRFlickr\":\n \n label_set = scio.loadmat(settings.LABEL_DIR)\n label_set = np.array(label_set['LAll'], dtype=np.float)\n txt_set = scio.loadmat(settings.TXT_DIR)\n txt_set = np.array(txt_set['YAll'], dtype=np.float)\n\n first = True\n for label in range(label_set.shape[1]):\n index = np.where(label_set[:,label] == 1)[0]\n \n N = index.shape[0]\n perm = np.random.permutation(N)\n index = index[perm]\n \n if first:\n test_index = index[:160]\n train_index = index[160:160+400]\n first = False\n else:\n ind = np.array([i for i in list(index) if i not in (list(train_index)+list(test_index))])\n test_index = np.concatenate((test_index, ind[:80]))\n train_index = np.concatenate((train_index, ind[80:80+200]))\n\n\n database_index = np.array([i for i in list(range(label_set.shape[0])) if i not in list(test_index)])\n\n if train_index.shape[0] < 5000:\n pick = np.array([i for i in list(database_index) if i not in list(train_index)])\n N = pick.shape[0]\n perm = np.random.permutation(N)\n pick = pick[perm]\n res = 5000 - train_index.shape[0]\n train_index = np.concatenate((train_index, pick[:res]))\n\n\n indexTest = test_index\n indexDatabase = database_index\n indexTrain = train_index\n\n\n mir_train_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n mir_test_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n txt_feat_len = txt_set.shape[1]\n\n class MIRFlickr(torch.utils.data.Dataset):\n def __init__(self, transform=None, target_transform=None, train=True, database=False):\n self.transform = transform\n self.target_transform = target_transform\n\n if train:\n self.train_labels = label_set[indexTrain]\n self.train_index = indexTrain\n self.txt = txt_set[indexTrain]\n elif database:\n self.train_labels = label_set[indexDatabase]\n self.train_index = indexDatabase\n self.txt = txt_set[indexDatabase]\n else:\n self.train_labels = label_set[indexTest] \n self.train_index = indexTest\n self.txt = txt_set[indexTest]\n\n def __getitem__(self, index):\n\n mirflickr = h5py.File(settings.IMG_DIR, 'r', libver='latest', swmr=True)\n img, target = mirflickr['IAll'][self.train_index[index]], self.train_labels[index]\n img = Image.fromarray(np.transpose(img, (2, 1, 0)))\n mirflickr.close()\n \n txt = self.txt[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, txt, target, index\n\n def __len__(self):\n return len(self.train_labels)\n\nif settings.DATASET == \"NUSWIDE\":\n\n label_set = scio.loadmat(settings.LABEL_DIR)\n label_set = np.array(label_set['LAll'], dtype=np.float)\n txt_file = h5py.File(settings.TXT_DIR)\n txt_set = np.array(txt_file['YAll']).transpose()\n txt_file.close()\n\n\n first = True\n\n for label in range(label_set.shape[1]):\n index = np.where(label_set[:,label] == 1)[0]\n \n N = index.shape[0]\n perm = np.random.permutation(N)\n index = index[perm]\n \n if first:\n test_index = index[:200]\n train_index = index[200:700]\n first = False\n else:\n ind = np.array([i for i in list(index) if i not in (list(train_index)+list(test_index))])\n test_index = np.concatenate((test_index, ind[:200]))\n train_index = np.concatenate((train_index, ind[200:700]))\n\n \n database_index = np.array([i for i in list(range(label_set.shape[0])) if i not in list(test_index)])\n\n indexTest = test_index\n indexDatabase = database_index\n indexTrain = train_index\n\n\n nus_train_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n nus_test_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n txt_feat_len = txt_set.shape[1]\n\n\n class NUSWIDE(torch.utils.data.Dataset):\n\n def __init__(self, transform=None, target_transform=None, train=True, database=False):\n self.transform = transform\n self.target_transform = target_transform\n if train:\n self.train_labels = label_set[indexTrain]\n self.train_index = indexTrain\n self.txt = txt_set[indexTrain]\n elif database:\n self.train_labels = label_set[indexDatabase]\n self.train_index = indexDatabase\n self.txt = txt_set[indexDatabase]\n else:\n self.train_labels = label_set[indexTest] \n self.train_index = indexTest\n self.txt = txt_set[indexTest]\n\n def __getitem__(self, index):\n\n nuswide = h5py.File(settings.IMG_DIR, 'r', libver='latest', swmr=True)\n img, target = nuswide['IAll'][self.train_index[index]], self.train_labels[index]\n img = Image.fromarray(np.transpose(img, (2, 1, 0)))\n nuswide.close()\n \n txt = self.txt[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, txt, target, index\n\n def __len__(self):\n return len(self.train_labels)"
] |
[
[
"scipy.io.loadmat",
"numpy.concatenate",
"numpy.random.permutation",
"numpy.transpose",
"numpy.array",
"numpy.where"
]
] |
huangjunjie-cs/pytorch_geometric_signed_directed-1
|
[
"24b121ff4325d201b30811975bcb6f104a39dc35"
] |
[
"torch_geometric_signed_directed/nn/signed/SSSNET_node_clustering.py"
] |
[
"from typing import Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\n\nfrom .SIMPA import SIMPA\n\nclass SSSNET_node_clustering(nn.Module):\n r\"\"\"The signed graph clustering model from the\n `SSSNET: Semi-Supervised Signed Network Clustering <https://arxiv.org/pdf/2110.06623.pdf>`_ paper.\n \n Args:\n nfeat (int): Number of features.\n hidden (int): Hidden dimensions of the initial MLP.\n nclass (int): Number of clusters.\n dropout (float): Dropout probability.\n hop (int): Number of hops to consider.\n fill_value (float): Value for added self-loops for the positive part of the adjacency matrix.\n directed (bool, optional): Whether the input network is directed or not. (default: :obj:`False`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn an additive bias. (default: :obj:`True`)\n \"\"\"\n\n def __init__(self, nfeat: int, hidden: int, nclass: int, dropout: float, hop: int, fill_value: float,\n directed: bool = False, bias: bool = True):\n super(SSSNET_node_clustering, self).__init__()\n nh1 = hidden\n nh2 = hidden\n self._num_clusters = int(nclass)\n self._simpa = SIMPA(hop, fill_value, directed)\n if bias:\n self._bias = Parameter(torch.FloatTensor(self._num_clusters))\n else:\n self.register_parameter('_bias', None)\n self._relu = nn.ReLU()\n self._dropout = nn.Dropout(p=dropout)\n self._undirected = not directed\n\n if self._undirected:\n self._w_p0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_p1 = Parameter(torch.FloatTensor(nh1, nh2))\n self._w_n0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_n1 = Parameter(torch.FloatTensor(nh1, nh2))\n\n self._W_prob = Parameter(\n torch.FloatTensor(2*nh2, self._num_clusters))\n\n self._reset_parameters_undirected()\n else:\n self._w_sp0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_sp1 = Parameter(torch.FloatTensor(nh1, nh2))\n self._w_sn0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_sn1 = Parameter(torch.FloatTensor(nh1, nh2))\n self._w_tp0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_tp1 = Parameter(torch.FloatTensor(nh1, nh2))\n self._w_tn0 = Parameter(torch.FloatTensor(nfeat, nh1))\n self._w_tn1 = Parameter(torch.FloatTensor(nh1, nh2))\n\n self._W_prob = Parameter(\n torch.FloatTensor(4*nh2, self._num_clusters))\n\n self._reset_parameters_directed()\n\n def _reset_parameters_undirected(self):\n nn.init.xavier_uniform_(self._w_p0, gain=1.414)\n nn.init.xavier_uniform_(self._w_p1, gain=1.414)\n nn.init.xavier_uniform_(self._w_n0, gain=1.414)\n nn.init.xavier_uniform_(self._w_n1, gain=1.414)\n\n if self._bias is not None:\n self._bias.data.fill_(0.0)\n nn.init.xavier_uniform_(self._W_prob, gain=1.414)\n\n def _reset_parameters_directed(self):\n nn.init.xavier_uniform_(self._w_sp0, gain=1.414)\n nn.init.xavier_uniform_(self._w_sp1, gain=1.414)\n nn.init.xavier_uniform_(self._w_sn0, gain=1.414)\n nn.init.xavier_uniform_(self._w_sn1, gain=1.414)\n nn.init.xavier_uniform_(self._w_tp0, gain=1.414)\n nn.init.xavier_uniform_(self._w_tp1, gain=1.414)\n nn.init.xavier_uniform_(self._w_tn0, gain=1.414)\n nn.init.xavier_uniform_(self._w_tn1, gain=1.414)\n\n if self._bias is not None:\n self._bias.data.fill_(0.0)\n nn.init.xavier_uniform_(self._W_prob, gain=1.414)\n\n def forward(self, edge_index_p: torch.LongTensor, edge_weight_p: torch.FloatTensor,\n edge_index_n: torch.LongTensor, edge_weight_n: torch.FloatTensor,\n features: torch.FloatTensor) -> Tuple[torch.FloatTensor,\n torch.FloatTensor, torch.LongTensor, torch.FloatTensor]:\n \"\"\"\n Making a forward pass of the SSSNET.\n\n Arg types:\n * **edge_index_p, edge_index_n** (PyTorch FloatTensor) - Edge indices for positive and negative parts.\n * **edge_weight_p, edge_weight_n** (PyTorch FloatTensor) - Edge weights for positive and nagative parts.\n * **features** (PyTorch FloatTensor) - Input node features, with shape (num_nodes, num_features).\n Return types:\n * **z** (PyTorch FloatTensor) - Embedding matrix, with shape (num_nodes, 2*hidden) for undirected graphs and (num_nodes, 4*hidden) for directed graphs.\n * **output** (PyTorch FloatTensor) - Log of prob, with shape (num_nodes, num_clusters).\n * **predictions_cluster** (PyTorch LongTensor) - Predicted labels.\n * **prob** (PyTorch FloatTensor) - Probability assignment matrix of different clusters, with shape (num_nodes, num_clusters).\n \"\"\"\n if self._undirected:\n # MLP\n x_p = torch.mm(features, self._w_p0)\n x_p = self._relu(x_p)\n x_p = self._dropout(x_p)\n x_p = torch.mm(x_p, self._w_p1)\n\n x_n = torch.mm(features, self._w_n0)\n x_n = self._relu(x_n)\n x_n = self._dropout(x_n)\n x_n = torch.mm(x_n, self._w_n1)\n\n z = self._simpa(edge_index_p, edge_weight_p,\n edge_index_n, edge_weight_n, x_p, x_n)\n else:\n # MLP\n # source positive embedding\n x_sp = torch.mm(features, self._w_sp0)\n x_sp = self._relu(x_sp)\n x_sp = self._dropout(x_sp)\n x_sp = torch.mm(x_sp, self._w_sp1)\n\n # source negative embedding\n x_sn = torch.mm(features, self._w_sn0)\n x_sn = self._relu(x_sn)\n x_sn = self._dropout(x_sn)\n x_sn = torch.mm(x_sn, self._w_sn1)\n\n # target positive embedding\n x_tp = torch.mm(features, self._w_tp0)\n x_tp = self._relu(x_tp)\n x_tp = self._dropout(x_tp)\n x_tp = torch.mm(x_tp, self._w_tp1)\n\n # target negative embedding\n x_tn = torch.mm(features, self._w_tn0)\n x_tn = self._relu(x_tn)\n x_tn = self._dropout(x_tn)\n x_tn = torch.mm(x_tn, self._w_tn1)\n\n z = self._simpa(edge_index_p, edge_weight_p,\n edge_index_n, edge_weight_n, x_sp, x_sn, x_tp, x_tn)\n\n output = torch.mm(z, self._W_prob)\n if self._bias is not None:\n output = output + self._bias # to balance the difference in cluster probabilities\n\n predictions_cluster = torch.argmax(output, dim=1)\n\n prob = F.softmax(output, dim=1)\n\n output = F.log_softmax(output, dim=1)\n\n return F.normalize(z), output, predictions_cluster, prob\n"
] |
[
[
"torch.nn.functional.normalize",
"torch.nn.Dropout",
"torch.mm",
"torch.nn.functional.softmax",
"torch.nn.functional.log_softmax",
"torch.FloatTensor",
"torch.nn.init.xavier_uniform_",
"torch.nn.ReLU",
"torch.argmax"
]
] |
lykzsm/Pytorch-Medical-Classification
|
[
"86c1215612f6d6483ccb5cd061925ba755120f35"
] |
[
"main.py"
] |
[
"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\ndevicess = [0]\nfrom collections import defaultdict\nimport time\nimport argparse\nimport numpy as np\nfrom PIL import Image\nimport torch\nfrom sklearn import metrics\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch import nn\nfrom torchvision import transforms\nimport torch.distributed as dist\nimport math\nimport torchio\nfrom torchio.transforms import (\n ZNormalization,\n)\nfrom tqdm import tqdm\nfrom torchvision import utils\nfrom hparam import hparams as hp\nfrom utils.metric import metric\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau,StepLR,CosineAnnealingLR\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\n\nsource_train_0_dir = hp.source_train_0_dir\nsource_train_1_dir = hp.source_train_1_dir\n\n\nsource_test_0_dir = hp.source_test_0_dir\nsource_test_1_dir = hp.source_test_1_dir\n\n\n\n\ndef parse_training_args(parser):\n \"\"\"\n Parse commandline arguments.\n \"\"\"\n\n parser.add_argument('-o', '--output_dir', type=str, default=hp.output_dir, required=False, help='Directory to save checkpoints')\n parser.add_argument('--latest-checkpoint-file', type=str, default=hp.latest_checkpoint_file, help='Store the latest checkpoint in each epoch')\n\n # training\n training = parser.add_argument_group('training setup')\n training.add_argument('--epochs', type=int, default=hp.total_epochs, help='Number of total epochs to run')\n training.add_argument('--epochs-per-checkpoint', type=int, default=hp.epochs_per_checkpoint, help='Number of epochs per checkpoint')\n training.add_argument('--batch', type=int, default=hp.batch_size, help='batch-size') \n parser.add_argument(\n '-k',\n \"--ckpt\",\n type=str,\n default=hp.ckpt,\n help=\"path to the checkpoints to resume training\",\n )\n parser.add_argument(\"--init-lr\", type=float, default=hp.init_lr, help=\"learning rate\")\n # TODO\n parser.add_argument(\n \"--local_rank\", type=int, default=0, help=\"local rank for distributed training\"\n )\n\n training.add_argument('--amp-run', action='store_true', help='Enable AMP')\n training.add_argument('--cudnn-enabled', default=True, help='Enable cudnn')\n training.add_argument('--cudnn-benchmark', default=True, help='Run cudnn benchmark')\n training.add_argument('--disable-uniform-initialize-bn-weight', action='store_true', help='disable uniform initialization of batchnorm layer weight')\n\n return parser\n\n\n\ndef train():\n\n parser = argparse.ArgumentParser(description='PyTorch Medical Segmentation Training')\n parser = parse_training_args(parser)\n args, _ = parser.parse_known_args()\n\n args = parser.parse_args()\n\n\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.enabled = args.cudnn_enabled\n torch.backends.cudnn.benchmark = args.cudnn_benchmark\n\n\n from data_function import MedData_train\n os.makedirs(args.output_dir, exist_ok=True)\n\n if hp.mode == '2d':\n # from models.two_d.alexnet import alexnet\n # model = alexnet(num_classes=2)\n\n # from models.two_d.densenet import densenet121\n # model = densenet121(num_class=2)\n\n from models.two_d.googlenet import googlenet\n model = googlenet(num_class=2)\n\n # from models.two_d.mobilenet import mobilenet\n # model = mobilenet(class_num=2)\n\n # from models.two_d.nasnet import nasnet\n # model = nasnet(class_num=2)\n\n # from models.two_d.resnet import resnet101\n # model = resnet101(num_classes=2)\n\n # from models.two_d.resnext import resnext101\n # model = resnext101(class_names=2)\n \n # from models.two_d.vggnet import vgg16_bn\n # model = vgg16_bn(num_class=2)\n\n elif hp.mode == '3d':\n\n from models.three_d.resnet3d import generate_model\n model = generate_model(18,n_input_channels=1,n_classes=2)\n\n from models.three_d.resnext3d import generate_model\n model = generate_model(50,n_input_channels=1,n_classes=2)\n\n from models.three_d.densenet3d import generate_model\n model = generate_model(121,n_input_channels=1,num_classes=2)\n\n\n\n\n\n\n\n\n model = torch.nn.DataParallel(model, device_ids=devicess)\n optimizer = torch.optim.Adam(model.parameters(), lr=args.init_lr)\n\n\n # scheduler = ReduceLROnPlateau(optimizer, 'min',factor=0.5, patience=20, verbose=True)\n scheduler = StepLR(optimizer, step_size=hp.scheduer_step_size, gamma=hp.scheduer_gamma)\n # scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=5e-6)\n\n if args.ckpt is not None:\n print(\"load model:\", args.ckpt)\n print(os.path.join(args.output_dir, args.latest_checkpoint_file))\n ckpt = torch.load(os.path.join(args.output_dir, args.latest_checkpoint_file), map_location=lambda storage, loc: storage)\n\n model.load_state_dict(ckpt[\"model\"])\n optimizer.load_state_dict(ckpt[\"optim\"])\n\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.cuda()\n\n # scheduler.load_state_dict(ckpt[\"scheduler\"])\n elapsed_epochs = ckpt[\"epoch\"]\n else:\n elapsed_epochs = 0\n\n model.cuda()\n\n from loss_function import Classification_Loss\n criterion = Classification_Loss().cuda()\n\n\n writer = SummaryWriter(args.output_dir)\n\n\n\n train_dataset = MedData_train(source_train_0_dir,source_train_1_dir)\n train_loader = DataLoader(train_dataset.training_set, \n batch_size=args.batch, \n shuffle=True,\n pin_memory=True,\n drop_last=True)\n\n model.train()\n\n epochs = args.epochs - elapsed_epochs\n iteration = elapsed_epochs * len(train_loader)\n\n\n\n for epoch in range(1, epochs + 1):\n print(\"epoch:\"+str(epoch))\n epoch += elapsed_epochs\n\n num_iters = 0\n\n gts = []\n predicts = []\n for i, batch in enumerate(train_loader):\n \n\n if hp.debug:\n if i >=1:\n break\n\n print(f\"Batch: {i}/{len(train_loader)} epoch {epoch}\")\n\n optimizer.zero_grad()\n\n\n x = batch['source']['data']\n y = batch['label']\n\n x = x.type(torch.FloatTensor).cuda()\n y = y.type(torch.LongTensor).cuda()\n\n if hp.mode == '2d':\n x = x.squeeze(-1)\n x = x[:,:1,:,:]\n\n outputs = model(x)\n\n outputs_logit = outputs.argmax(dim=1)\n\n loss = criterion(outputs, y, model)\n\n num_iters += 1\n loss.backward()\n\n optimizer.step()\n iteration += 1\n\n\n print(\"loss:\"+str(loss.item()))\n writer.add_scalar('Training/Loss', loss.item(),iteration)\n\n predicts.append(outputs_logit.cpu().detach().numpy())\n gts.append(y.cpu().detach().numpy())\n\n\n predicts = np.concatenate(predicts).flatten().astype(np.int16)\n gts = np.concatenate(gts).flatten().astype(np.int16)\n\n print(metrics.confusion_matrix(predicts, gts))\n acc = metrics.accuracy_score(predicts, gts) \n recall = metrics.recall_score(predicts, gts) \n f1 = metrics.f1_score(predicts, gts) \n writer.add_scalar('Training/acc', acc,epoch)\n writer.add_scalar('Training/recall', recall,epoch)\n writer.add_scalar('Training/f1', f1,epoch)\n\n \n scheduler.step()\n\n\n # Store latest checkpoint in each epoch\n torch.save(\n {\n \"model\": model.state_dict(),\n \"optim\": optimizer.state_dict(),\n \"scheduler\":scheduler.state_dict(),\n \"epoch\": epoch,\n\n },\n os.path.join(args.output_dir, args.latest_checkpoint_file),\n )\n\n\n # Save checkpoint\n if epoch % args.epochs_per_checkpoint == 0:\n\n torch.save(\n { \n \"model\": model.state_dict(),\n \"optim\": optimizer.state_dict(),\n \"epoch\": epoch,\n },\n os.path.join(args.output_dir, f\"checkpoint_{epoch:04d}.pt\"),\n ) \n\n writer.close()\n\n\ndef test():\n\n parser = argparse.ArgumentParser(description='PyTorch Medical Segmentation Testing')\n parser = parse_training_args(parser)\n args, _ = parser.parse_known_args()\n\n args = parser.parse_args()\n\n\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.enabled = args.cudnn_enabled\n torch.backends.cudnn.benchmark = args.cudnn_benchmark\n\n from data_function import MedData_test\n\n\n if hp.mode == '2d':\n # from models.two_d.alexnet import alexnet\n # model = alexnet(num_classes=2)\n\n # from models.two_d.densenet import densenet121\n # model = densenet121(num_class=2)\n\n from models.two_d.googlenet import googlenet\n model = googlenet(num_class=2)\n\n # from models.two_d.mobilenet import mobilenet\n # model = mobilenet(class_num=2)\n\n # from models.two_d.nasnet import nasnet\n # model = nasnet(class_num=2)\n\n # from models.two_d.resnet import resnet101\n # model = resnet101(num_classes=2)\n\n # from models.two_d.resnext import resnext101\n # model = resnext101(class_names=2)\n \n # from models.two_d.vggnet import vgg16_bn\n # model = vgg16_bn(num_class=2)\n\n elif hp.mode == '3d':\n\n from models.three_d.resnet3d import generate_model\n model = generate_model(18,n_input_channels=1,n_classes=2)\n\n from models.three_d.resnext3d import generate_model\n model = generate_model(50,n_input_channels=1,n_classes=2)\n\n from models.three_d.densenet3d import generate_model\n model = generate_model(121,n_input_channels=1,num_classes=2)\n\n\n\n\n model = torch.nn.DataParallel(model, device_ids=devicess,output_device=[1])\n\n\n print(\"load model:\", args.ckpt)\n print(os.path.join(args.output_dir, args.latest_checkpoint_file))\n ckpt = torch.load(os.path.join(args.output_dir, args.latest_checkpoint_file), map_location=lambda storage, loc: storage)\n\n model.load_state_dict(ckpt[\"model\"])\n\n\n model.cuda()\n\n test_dataset = MedData_test(source_test_0_dir,source_test_1_dir)\n test_loader = DataLoader(test_dataset.testing_set, \n batch_size=args.batch, \n shuffle=True,\n pin_memory=True,\n drop_last=True)\n\n model.eval()\n\n predicts = []\n gts = []\n for i, batch in enumerate(test_loader):\n \n x = batch['source']['data']\n y = batch['label']\n\n x = x.type(torch.FloatTensor).cuda()\n y = y.type(torch.LongTensor).cuda()\n\n if hp.mode == '2d':\n x = x.squeeze(-1)\n x = x[:,:1,:,:]\n\n outputs = model(x)\n\n outputs_logit = outputs.argmax(dim=1)\n\n predicts.append(outputs_logit.cpu().detach().numpy())\n gts.append(y.cpu().detach().numpy())\n\n predicts = np.concatenate(predicts).flatten().astype(np.int16)\n gts = np.concatenate(gts).flatten().astype(np.int16)\n acc = metrics.accuracy_score(predicts, gts) \n recall = metrics.recall_score(predicts, gts) \n f1 = metrics.f1_score(predicts, gts) \n ## log\n print(\"acc:\"+str(acc))\n print(\"recall:\"+str(recall))\n print(\"f1:\"+str(f1))\n print(metrics.confusion_matrix(predicts, gts))\n\n\n\n\n \n\n\n \n\nif __name__ == '__main__':\n if hp.train_or_test == 'train':\n train()\n elif hp.train_or_test == 'test':\n test()\n"
] |
[
[
"torch.optim.lr_scheduler.StepLR",
"torch.utils.data.DataLoader",
"sklearn.metrics.confusion_matrix",
"torch.is_tensor",
"numpy.concatenate",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"sklearn.metrics.f1_score",
"torch.nn.DataParallel",
"sklearn.metrics.recall_score",
"sklearn.metrics.accuracy_score"
]
] |
ArnaudTurn/cudf
|
[
"e5817349cbcad8a68cf9d2b54d12b097ee1502f6"
] |
[
"python/cudf/cudf/core/column/datetime.py"
] |
[
"# Copyright (c) 2019-2021, NVIDIA CORPORATION.\n\nfrom __future__ import annotations\n\nimport builtins\nimport datetime as dt\nimport locale\nimport re\nfrom locale import nl_langinfo\nfrom numbers import Number\nfrom types import SimpleNamespace\nfrom typing import Any, Mapping, Sequence, Union, cast\n\nimport numpy as np\nimport pandas as pd\n\nimport cudf\nfrom cudf import _lib as libcudf\nfrom cudf._typing import DatetimeLikeScalar, Dtype, DtypeObj, ScalarLike\nfrom cudf.api.types import is_scalar\nfrom cudf.core._compat import PANDAS_GE_120\nfrom cudf.core.buffer import Buffer\nfrom cudf.core.column import (\n ColumnBase,\n as_column,\n column,\n column_empty_like,\n string,\n)\nfrom cudf.utils.utils import _fillna_natwise\n\nif PANDAS_GE_120:\n _guess_datetime_format = pd.core.tools.datetimes.guess_datetime_format\nelse:\n _guess_datetime_format = pd.core.tools.datetimes._guess_datetime_format\n\n# nanoseconds per time_unit\n_numpy_to_pandas_conversion = {\n \"ns\": 1,\n \"us\": 1000,\n \"ms\": 1000000,\n \"s\": 1000000000,\n \"m\": 60000000000,\n \"h\": 3600000000000,\n \"D\": 86400000000000,\n}\n\n_dtype_to_format_conversion = {\n \"datetime64[ns]\": \"%Y-%m-%d %H:%M:%S.%9f\",\n \"datetime64[us]\": \"%Y-%m-%d %H:%M:%S.%6f\",\n \"datetime64[ms]\": \"%Y-%m-%d %H:%M:%S.%3f\",\n \"datetime64[s]\": \"%Y-%m-%d %H:%M:%S\",\n}\n\n_DATETIME_SPECIAL_FORMATS = {\n \"%b\",\n \"%B\",\n \"%A\",\n \"%a\",\n}\n\n_DATETIME_NAMES = [\n nl_langinfo(locale.AM_STR), # type: ignore\n nl_langinfo(locale.PM_STR), # type: ignore\n nl_langinfo(locale.DAY_1),\n nl_langinfo(locale.DAY_2),\n nl_langinfo(locale.DAY_3),\n nl_langinfo(locale.DAY_4),\n nl_langinfo(locale.DAY_5),\n nl_langinfo(locale.DAY_6),\n nl_langinfo(locale.DAY_7),\n nl_langinfo(locale.ABDAY_1),\n nl_langinfo(locale.ABDAY_2),\n nl_langinfo(locale.ABDAY_3),\n nl_langinfo(locale.ABDAY_4),\n nl_langinfo(locale.ABDAY_5),\n nl_langinfo(locale.ABDAY_6),\n nl_langinfo(locale.ABDAY_7),\n nl_langinfo(locale.MON_1),\n nl_langinfo(locale.MON_2),\n nl_langinfo(locale.MON_3),\n nl_langinfo(locale.MON_4),\n nl_langinfo(locale.MON_5),\n nl_langinfo(locale.MON_6),\n nl_langinfo(locale.MON_7),\n nl_langinfo(locale.MON_8),\n nl_langinfo(locale.MON_9),\n nl_langinfo(locale.MON_10),\n nl_langinfo(locale.MON_11),\n nl_langinfo(locale.MON_12),\n nl_langinfo(locale.ABMON_1),\n nl_langinfo(locale.ABMON_2),\n nl_langinfo(locale.ABMON_3),\n nl_langinfo(locale.ABMON_4),\n nl_langinfo(locale.ABMON_5),\n nl_langinfo(locale.ABMON_6),\n nl_langinfo(locale.ABMON_7),\n nl_langinfo(locale.ABMON_8),\n nl_langinfo(locale.ABMON_9),\n nl_langinfo(locale.ABMON_10),\n nl_langinfo(locale.ABMON_11),\n nl_langinfo(locale.ABMON_12),\n]\n\n\nclass DatetimeColumn(column.ColumnBase):\n \"\"\"\n A Column implementation for Date-time types.\n\n Parameters\n ----------\n data : Buffer\n The datetime values\n dtype : np.dtype\n The data type\n mask : Buffer; optional\n The validity mask\n \"\"\"\n\n def __init__(\n self,\n data: Buffer,\n dtype: DtypeObj,\n mask: Buffer = None,\n size: int = None, # TODO: make non-optional\n offset: int = 0,\n null_count: int = None,\n ):\n dtype = cudf.dtype(dtype)\n\n if data.size % dtype.itemsize:\n raise ValueError(\"Buffer size must be divisible by element size\")\n if size is None:\n size = data.size // dtype.itemsize\n size = size - offset\n super().__init__(\n data,\n size=size,\n dtype=dtype,\n mask=mask,\n offset=offset,\n null_count=null_count,\n )\n\n if not (self.dtype.type is np.datetime64):\n raise TypeError(f\"{self.dtype} is not a supported datetime type\")\n\n self._time_unit, _ = np.datetime_data(self.dtype)\n\n def __contains__(self, item: ScalarLike) -> bool:\n try:\n item_as_dt64 = np.datetime64(item, self._time_unit)\n except ValueError:\n # If item cannot be converted to datetime type\n # np.datetime64 raises ValueError, hence `item`\n # cannot exist in `self`.\n return False\n return item_as_dt64.astype(\"int64\") in self.as_numerical\n\n @property\n def time_unit(self) -> str:\n return self._time_unit\n\n @property\n def year(self) -> ColumnBase:\n return self.get_dt_field(\"year\")\n\n @property\n def month(self) -> ColumnBase:\n return self.get_dt_field(\"month\")\n\n @property\n def day(self) -> ColumnBase:\n return self.get_dt_field(\"day\")\n\n @property\n def hour(self) -> ColumnBase:\n return self.get_dt_field(\"hour\")\n\n @property\n def minute(self) -> ColumnBase:\n return self.get_dt_field(\"minute\")\n\n @property\n def second(self) -> ColumnBase:\n return self.get_dt_field(\"second\")\n\n @property\n def weekday(self) -> ColumnBase:\n return self.get_dt_field(\"weekday\")\n\n @property\n def dayofyear(self) -> ColumnBase:\n return self.get_dt_field(\"day_of_year\")\n\n @property\n def day_of_year(self) -> ColumnBase:\n return self.get_dt_field(\"day_of_year\")\n\n def to_pandas(\n self, index: pd.Index = None, nullable: bool = False, **kwargs\n ) -> \"cudf.Series\":\n # Workaround until following issue is fixed:\n # https://issues.apache.org/jira/browse/ARROW-9772\n\n # Pandas supports only `datetime64[ns]`, hence the cast.\n return pd.Series(\n self.astype(\"datetime64[ns]\").to_array(\"NAT\"),\n copy=False,\n index=index,\n )\n\n @property\n def values(self):\n \"\"\"\n Return a CuPy representation of the DateTimeColumn.\n \"\"\"\n raise NotImplementedError(\n \"DateTime Arrays is not yet implemented in cudf\"\n )\n\n def get_dt_field(self, field: str) -> ColumnBase:\n return libcudf.datetime.extract_datetime_component(self, field)\n\n def ceil(self, freq: str) -> ColumnBase:\n return libcudf.datetime.ceil_datetime(self, freq)\n\n def floor(self, freq: str) -> ColumnBase:\n return libcudf.datetime.floor_datetime(self, freq)\n\n def round(self, freq: str) -> ColumnBase:\n return libcudf.datetime.round_datetime(self, freq)\n\n def normalize_binop_value(self, other: DatetimeLikeScalar) -> ScalarLike:\n if isinstance(other, cudf.Scalar):\n return other\n\n if isinstance(other, np.ndarray) and other.ndim == 0:\n other = other.item()\n\n if isinstance(other, dt.datetime):\n other = np.datetime64(other)\n elif isinstance(other, dt.timedelta):\n other = np.timedelta64(other)\n elif isinstance(other, pd.Timestamp):\n other = other.to_datetime64()\n elif isinstance(other, pd.Timedelta):\n other = other.to_timedelta64()\n elif isinstance(other, cudf.DateOffset):\n return other\n if isinstance(other, np.datetime64):\n if np.isnat(other):\n return cudf.Scalar(None, dtype=self.dtype)\n\n other = other.astype(self.dtype)\n return cudf.Scalar(other)\n elif isinstance(other, np.timedelta64):\n other_time_unit = cudf.utils.dtypes.get_time_unit(other)\n\n if other_time_unit not in (\"s\", \"ms\", \"ns\", \"us\"):\n other = other.astype(\"timedelta64[s]\")\n\n if np.isnat(other):\n return cudf.Scalar(None, dtype=other.dtype)\n\n return cudf.Scalar(other)\n elif other is None:\n return cudf.Scalar(other, dtype=self.dtype)\n else:\n raise TypeError(f\"cannot normalize {type(other)}\")\n\n @property\n def as_numerical(self) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\",\n column.build_column(\n data=self.base_data,\n dtype=np.int64,\n mask=self.base_mask,\n offset=self.offset,\n size=self.size,\n ),\n )\n\n @property\n def __cuda_array_interface__(self) -> Mapping[builtins.str, Any]:\n output = {\n \"shape\": (len(self),),\n \"strides\": (self.dtype.itemsize,),\n \"typestr\": self.dtype.str,\n \"data\": (self.data_ptr, False),\n \"version\": 1,\n }\n\n if self.nullable and self.has_nulls:\n\n # Create a simple Python object that exposes the\n # `__cuda_array_interface__` attribute here since we need to modify\n # some of the attributes from the numba device array\n mask = SimpleNamespace(\n __cuda_array_interface__={\n \"shape\": (len(self),),\n \"typestr\": \"<t1\",\n \"data\": (self.mask_ptr, True),\n \"version\": 1,\n }\n )\n output[\"mask\"] = mask\n\n return output\n\n def as_datetime_column(self, dtype: Dtype, **kwargs) -> DatetimeColumn:\n dtype = cudf.dtype(dtype)\n if dtype == self.dtype:\n return self\n return libcudf.unary.cast(self, dtype=dtype)\n\n def as_timedelta_column(\n self, dtype: Dtype, **kwargs\n ) -> \"cudf.core.column.TimeDeltaColumn\":\n raise TypeError(\n f\"cannot astype a datetimelike from {self.dtype} to {dtype}\"\n )\n\n def as_numerical_column(\n self, dtype: Dtype, **kwargs\n ) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\", self.as_numerical.astype(dtype)\n )\n\n def as_string_column(\n self, dtype: Dtype, format=None, **kwargs\n ) -> \"cudf.core.column.StringColumn\":\n if format is None:\n format = _dtype_to_format_conversion.get(\n self.dtype.name, \"%Y-%m-%d %H:%M:%S\"\n )\n if format in _DATETIME_SPECIAL_FORMATS:\n names = as_column(_DATETIME_NAMES)\n else:\n names = cudf.core.column.column_empty(\n 0, dtype=\"object\", masked=False\n )\n if len(self) > 0:\n return string._datetime_to_str_typecast_functions[\n cudf.dtype(self.dtype)\n ](self, format, names)\n else:\n return cast(\n \"cudf.core.column.StringColumn\",\n column.column_empty(0, dtype=\"object\", masked=False),\n )\n\n def _default_na_value(self) -> DatetimeLikeScalar:\n \"\"\"Returns the default NA value for this column\"\"\"\n return np.datetime64(\"nat\", self.time_unit)\n\n def mean(self, skipna=None, dtype=np.float64) -> ScalarLike:\n return pd.Timestamp(\n self.as_numerical.mean(skipna=skipna, dtype=dtype),\n unit=self.time_unit,\n )\n\n def std(\n self, skipna: bool = None, ddof: int = 1, dtype: Dtype = np.float64\n ) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.std(skipna=skipna, ddof=ddof, dtype=dtype)\n * _numpy_to_pandas_conversion[self.time_unit],\n )\n\n def median(self, skipna: bool = None) -> pd.Timestamp:\n return pd.Timestamp(\n self.as_numerical.median(skipna=skipna), unit=self.time_unit\n )\n\n def quantile(\n self, q: Union[float, Sequence[float]], interpolation: str, exact: bool\n ) -> ColumnBase:\n result = self.as_numerical.quantile(\n q=q, interpolation=interpolation, exact=exact\n )\n if isinstance(q, Number):\n return pd.Timestamp(result, unit=self.time_unit)\n return result.astype(self.dtype)\n\n def binary_operator(\n self,\n op: str,\n rhs: Union[ColumnBase, \"cudf.Scalar\"],\n reflect: bool = False,\n ) -> ColumnBase:\n if isinstance(rhs, cudf.DateOffset):\n return rhs._datetime_binop(self, op, reflect=reflect)\n lhs: Union[ScalarLike, ColumnBase] = self\n if op in (\"eq\", \"ne\", \"lt\", \"gt\", \"le\", \"ge\", \"NULL_EQUALS\"):\n out_dtype = cudf.dtype(np.bool_) # type: Dtype\n elif op == \"add\" and pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = cudf.core.column.timedelta._timedelta_add_result_dtype(\n rhs, lhs\n )\n elif op == \"sub\" and pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = cudf.core.column.timedelta._timedelta_sub_result_dtype(\n rhs if reflect else lhs, lhs if reflect else rhs\n )\n elif op == \"sub\" and pd.api.types.is_datetime64_dtype(rhs.dtype):\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n lhs_time_unit = cudf.utils.dtypes.get_time_unit(lhs)\n lhs_unit = units.index(lhs_time_unit)\n rhs_time_unit = cudf.utils.dtypes.get_time_unit(rhs)\n rhs_unit = units.index(rhs_time_unit)\n out_dtype = np.dtype(\n f\"timedelta64[{units[max(lhs_unit, rhs_unit)]}]\"\n )\n else:\n raise TypeError(\n f\"Series of dtype {self.dtype} cannot perform \"\n f\" the operation {op}\"\n )\n\n if reflect:\n lhs, rhs = rhs, lhs\n return libcudf.binaryop.binaryop(lhs, rhs, op, out_dtype)\n\n def fillna(\n self, fill_value: Any = None, method: str = None, dtype: Dtype = None\n ) -> DatetimeColumn:\n if fill_value is not None:\n if cudf.utils.utils._isnat(fill_value):\n return _fillna_natwise(self)\n if is_scalar(fill_value):\n if not isinstance(fill_value, cudf.Scalar):\n fill_value = cudf.Scalar(fill_value, dtype=self.dtype)\n else:\n fill_value = column.as_column(fill_value, nan_as_null=False)\n\n return super().fillna(fill_value, method)\n\n def find_first_value(\n self, value: ScalarLike, closest: bool = False\n ) -> int:\n \"\"\"\n Returns offset of first value that matches\n \"\"\"\n value = pd.to_datetime(value)\n value = column.as_column(value, dtype=self.dtype).as_numerical[0]\n return self.as_numerical.find_first_value(value, closest=closest)\n\n def find_last_value(self, value: ScalarLike, closest: bool = False) -> int:\n \"\"\"\n Returns offset of last value that matches\n \"\"\"\n value = pd.to_datetime(value)\n value = column.as_column(value, dtype=self.dtype).as_numerical[0]\n return self.as_numerical.find_last_value(value, closest=closest)\n\n @property\n def is_unique(self) -> bool:\n return self.as_numerical.is_unique\n\n def isin(self, values: Sequence) -> ColumnBase:\n return cudf.core.tools.datetimes._isin_datetimelike(self, values)\n\n def can_cast_safely(self, to_dtype: Dtype) -> bool:\n if np.issubdtype(to_dtype, np.datetime64):\n\n to_res, _ = np.datetime_data(to_dtype)\n self_res, _ = np.datetime_data(self.dtype)\n\n max_int = np.iinfo(cudf.dtype(\"int64\")).max\n\n max_dist = np.timedelta64(\n self.max().astype(cudf.dtype(\"int64\"), copy=False), self_res\n )\n min_dist = np.timedelta64(\n self.min().astype(cudf.dtype(\"int64\"), copy=False), self_res\n )\n\n self_delta_dtype = np.timedelta64(0, self_res).dtype\n\n if max_dist <= np.timedelta64(max_int, to_res).astype(\n self_delta_dtype\n ) and min_dist <= np.timedelta64(max_int, to_res).astype(\n self_delta_dtype\n ):\n return True\n else:\n return False\n elif to_dtype == cudf.dtype(\"int64\") or to_dtype == cudf.dtype(\"O\"):\n # can safely cast to representation, or string\n return True\n else:\n return False\n\n def _make_copy_with_na_as_null(self):\n \"\"\"Return a copy with NaN values replaced with nulls.\"\"\"\n null = column_empty_like(self, masked=True, newsize=1)\n na_value = np.datetime64(\"nat\", self.time_unit)\n out_col = cudf._lib.replace.replace(\n self,\n column.build_column(\n Buffer(np.array([na_value], dtype=self.dtype).view(\"|u1\")),\n dtype=self.dtype,\n ),\n null,\n )\n return out_col\n\n\ndef binop_offset(lhs, rhs, op):\n if rhs._is_no_op:\n return lhs\n else:\n rhs = rhs._generate_column(len(lhs), op)\n out = libcudf.datetime.add_months(lhs, rhs)\n return out\n\n\ndef infer_format(element: str, **kwargs) -> str:\n \"\"\"\n Infers datetime format from a string, also takes cares for `ms` and `ns`\n \"\"\"\n fmt = _guess_datetime_format(element, **kwargs)\n\n if fmt is not None:\n return fmt\n\n element_parts = element.split(\".\")\n if len(element_parts) != 2:\n raise ValueError(\"Given date string not likely a datetime.\")\n\n # There is possibility that the element is of following format\n # '00:00:03.333333 2016-01-01'\n second_parts = re.split(r\"(\\D+)\", element_parts[1], maxsplit=1)\n subsecond_fmt = \".%\" + str(len(second_parts[0])) + \"f\"\n\n first_part = _guess_datetime_format(element_parts[0], **kwargs)\n # For the case where first_part is '00:00:03'\n if first_part is None:\n tmp = \"1970-01-01 \" + element_parts[0]\n first_part = _guess_datetime_format(tmp, **kwargs).split(\" \", 1)[1]\n if first_part is None:\n raise ValueError(\"Unable to infer the timestamp format from the data\")\n\n if len(second_parts) > 1:\n # \"Z\" indicates Zulu time(widely used in aviation) - Which is\n # UTC timezone that currently cudf only supports. Having any other\n # unsupported timezone will let the code fail below\n # with a ValueError.\n second_parts.remove(\"Z\")\n second_part = \"\".join(second_parts[1:])\n\n if len(second_part) > 1:\n # Only infer if second_parts is not an empty string.\n second_part = _guess_datetime_format(second_part, **kwargs)\n else:\n second_part = \"\"\n\n try:\n fmt = first_part + subsecond_fmt + second_part\n except Exception:\n raise ValueError(\"Unable to infer the timestamp format from the data\")\n\n return fmt\n"
] |
[
[
"numpy.datetime_data",
"pandas.to_datetime",
"pandas.api.types.is_datetime64_dtype",
"numpy.isnat",
"numpy.issubdtype",
"numpy.datetime64",
"numpy.timedelta64",
"pandas.api.types.is_timedelta64_dtype",
"numpy.array",
"pandas.Timestamp"
]
] |
careyjiang/tensorflow_hmm
|
[
"6dad60141a240df8170fb6832c782a7672dfdb8f"
] |
[
"test/test_hmm.py"
] |
[
"from __future__ import print_function\n\nimport pytest\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_hmm import HMMNumpy, HMMTensorflow\n\n\[email protected]\ndef latch_P():\n P = np.array([[0.5, 0.5], [0.0, 1.0]])\n # P = np.array([[0.5, 0.5], [0.5, 0.5]])\n # P = np.array([[0.5, 0.5], [0.0000000001, 0.9999999999]])\n # P = np.array([[0.5, 0.5], [1e-50, 1 - 1e-50]])\n\n for i in range(2):\n for j in range(2):\n print('from', i, 'to', j, P[i, j])\n return P\n\n\[email protected]\ndef hmm_latch(latch_P):\n return HMMNumpy(latch_P)\n\n\[email protected]\ndef fair_P():\n return np.array([[0.5, 0.5], [0.5, 0.5]])\n\n\[email protected]\ndef hmm_fair(fair_P):\n return HMMNumpy(fair_P)\n\n\[email protected]\ndef hmm_tf_fair(fair_P):\n return HMMTensorflow(fair_P)\n\n\[email protected]\ndef hmm_tf_latch(latch_P):\n return HMMTensorflow(latch_P)\n\n\ndef lik(y):\n \"\"\"\n\n given 1d vector of likliehoods length N, return matrix with\n shape (N, 2) where (N, 0) is 1 - y and (N, 1) is y.\n\n given a 2d array of likelihood sequences of size [N, B] where B is the batch\n size, return [B, N, 2] where out[B, N, 0] + out[B, N, 1] = 1\n\n This makes it easy to convert a time series of probabilities\n into 2 states, off/on, for a simple HMM.\n \"\"\"\n\n liklihood = np.array([y, y], float).T\n liklihood[..., 0] = 1 - liklihood[..., 0]\n return liklihood\n\ndef test_tf_hmm_invalid_P_shape():\n with pytest.raises(ValueError):\n HMMTensorflow(np.ones((1, 2)))\n\ndef test_tf_hmm_invalid_P_dimensions():\n with pytest.raises(ValueError):\n HMMTensorflow(np.ones((1,)))\n\ndef test_hmm_tf_fair_forward_backward(hmm_tf_fair, hmm_fair):\n y = lik(np.array([0, 0, 1, 1]))\n\n np_posterior, _, _ = hmm_fair.forward_backward(y)\n print('tf')\n g_posterior, _, _ = hmm_tf_fair.forward_backward(y)\n tf_posterior = np.concatenate(tf.Session().run(g_posterior))\n\n print('np_posterior', np_posterior)\n print('tf_posterior', tf_posterior)\n assert np.isclose(np_posterior, tf_posterior).all()\n\n\ndef test_hmm_tf_fair_forward_backward_multiple_batch(hmm_tf_fair, hmm_fair):\n y = lik(np.array([0, 0, 1, 1]))\n y = np.stack([y] * 3)\n\n np_posterior, _, _ = hmm_fair.forward_backward(y)\n print('tf')\n g_posterior, _, _ = hmm_tf_fair.forward_backward(y)\n tf_posterior = tf.Session().run(g_posterior)\n\n print('np_posterior', np_posterior)\n print('tf_posterior', tf_posterior)\n assert np.isclose(np_posterior, tf_posterior).all()\n\n\ndef test_hmm_tf_latch_forward_backward_multiple_batch(hmm_tf_latch, hmm_latch):\n y = lik(np.array([0, 0, 1, 1]))\n y = np.stack([y] * 3)\n\n np_posterior, np_forward, np_backward = hmm_latch.forward_backward(y)\n print('tf')\n g_posterior, g_forward, g_backward = hmm_tf_latch.forward_backward(y)\n tf_posterior = tf.Session().run(g_posterior)\n tf_forward = tf.Session().run(g_forward)\n tf_backward = tf.Session().run(g_backward)\n\n assert np.isclose(np_forward, tf_forward).all()\n print('np_backward', np_backward)\n print('tf_backward', tf_backward)\n assert np.isclose(np_backward, tf_backward).all()\n print('np_posterior', np_posterior)\n print('tf_posterior', tf_posterior)\n assert np.isclose(np_posterior, tf_posterior).all()\n\ndef test_lik():\n yin = np.array([0, 0.25, 0.5, 0.75, 1])\n y = lik(yin)\n\n assert np.all(y == np.array([\n [1.00, 0.00],\n [0.75, 0.25],\n [0.50, 0.50],\n [0.25, 0.75],\n [0.00, 1.00],\n ]))\n\n\ndef test_hmm_fair_forward_backward(hmm_fair):\n y = lik(np.array([0, 0, 1, 1]))\n\n posterior, f, b = hmm_fair.forward_backward(y)\n\n # if P is filled with 0.5, the only thing that matters is the emission\n # liklihood. assert that the posterior is = the liklihood of y\n for i, yi in enumerate(y):\n liklihood = yi / np.sum(yi)\n assert np.isclose(posterior[i, :], liklihood).all()\n\n # assert that posterior for any given t sums to 1\n assert np.isclose(np.sum(posterior, 1), 1).all()\n\n\ndef test_hmm_latch_two_step_no_noise(hmm_latch):\n for i in range(2):\n for j in range(2):\n y = [i, i, j, j]\n # y = [i, j]\n\n if i == 1 and j == 0:\n continue\n\n print('*'*80)\n print(y)\n states, scores = hmm_latch.viterbi_decode(lik(y))\n\n assert all(states == y)\n\n\ndef test_hmm_tf_partial_forward(hmm_tf_latch, hmm_latch):\n scoress = [\n np.log(np.array([0, 1])),\n np.log(np.array([1, 0])),\n np.log(np.array([0.25, 0.75])),\n np.log(np.array([0.5, 0.5])),\n ]\n\n for scores in scoress:\n tf_ret = tf.Session().run(\n hmm_tf_latch._viterbi_partial_forward(scores)\n )\n np_ret = hmm_latch._viterbi_partial_forward(scores)\n\n assert (tf_ret == np_ret).all()\n\n\ndef test_hmm_tf_partial_forward_batched(hmm_tf_latch, hmm_latch):\n scoress = [\n np.log(np.array([0, 1])),\n np.log(np.array([1, 0])),\n np.log(np.array([0.25, 0.75])),\n np.log(np.array([0.5, 0.5])),\n ]\n\n scores_batch = np.asarray(scoress)\n\n np_res = hmm_latch._viterbi_partial_forward_batched(scores_batch)\n tf_res = tf.Session().run(\n hmm_tf_latch._viterbi_partial_forward_batched(scores_batch)\n )\n\n assert (tf_res == np_res).all()\n\n\ndef test_hmm_partial_forward_batched(hmm_latch):\n scoress = [\n np.log(np.array([0, 1])),\n np.log(np.array([1, 0])),\n np.log(np.array([0.25, 0.75])),\n np.log(np.array([0.5, 0.5])),\n ]\n\n scores_batch = np.array(scoress)\n\n res = [hmm_latch._viterbi_partial_forward(scores) for scores in scoress]\n res_batched = hmm_latch._viterbi_partial_forward_batched(scores_batch)\n\n assert np.all(np.asarray(res) == res_batched)\n\n\ndef test_hmm_tf_viterbi_decode(hmm_tf_latch, hmm_latch):\n ys = [\n lik(np.array([0, 0])),\n lik(np.array([1, 1])),\n lik(np.array([0, 1])),\n lik(np.array([0, 0.25, 0.5, 0.75, 1])),\n ]\n\n for y in ys:\n tf_s_graph, tf_scores_graph = hmm_tf_latch.viterbi_decode(y)\n tf_s, tf_scores = tf.Session().run([tf_s_graph, tf_scores_graph])\n\n np_s, np_scores = hmm_latch.viterbi_decode(y)\n\n assert (tf_s == np_s).all()\n assert (tf_scores == np_scores).all()\n\n\ndef test_hmm_viterbi_decode_batched(hmm_latch):\n ys_T2 = [\n lik(np.array([0, 0])),\n lik(np.array([0, 1])),\n lik(np.array([1, 1])),\n ]\n ys_T5 = [\n lik([0, 0.25, 0.5, 0.75, 1]),\n lik([0, 0.65, 0.5, 0.95, .1]),\n ]\n\n ys_T2_batch = np.asarray(ys_T2)\n ys_T5_batch = np.asarray(ys_T5)\n\n res = [hmm_latch.viterbi_decode(y) for y in ys_T2]\n res_s, res_scores = zip(*res)\n res_s_batch, res_scores_batch = hmm_latch.viterbi_decode_batched(ys_T2_batch)\n assert np.all(np.asarray(res_s) == res_s_batch)\n assert np.all(np.asarray(res_scores) == res_scores_batch)\n\n res = [hmm_latch.viterbi_decode(y) for y in ys_T5]\n res_s, res_scores = zip(*res)\n res_s_batch, res_scores_batch = hmm_latch.viterbi_decode_batched(ys_T5_batch)\n assert np.all(np.asarray(res_s) == res_s_batch)\n assert np.all(np.asarray(res_scores) == res_scores_batch)\n\n\ndef test_hmm_tf_viterbi_decode_batched(hmm_tf_latch, hmm_latch):\n ys_T2_batch = np.asarray([\n lik(np.array([0, 0])),\n lik(np.array([0, 1])),\n lik(np.array([1, 1])),\n ], dtype=np.float32)\n\n ys_T5_batch = np.asarray([\n lik([0, 0.25, 0.5, 0.75, 1]),\n lik([0, 0.65, 0.5, 0.95, .1]),\n lik([0, 0.25, 0.5, 0.75, 1]),\n ], dtype=np.float32)\n\n for y in (ys_T5_batch, ys_T2_batch):\n np_res_s, np_res_scores = hmm_latch.viterbi_decode_batched(y)\n\n y_variable = tf.placeholder(tf.float32, shape=(None, y.shape[1], y.shape[2]))\n tf_s_graph, tf_scores_graph = hmm_tf_latch.viterbi_decode_batched(y_variable)\n init_op = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init_op)\n\n tf_s = session.run(tf_s_graph, {y_variable: y})\n tf_scores = session.run(tf_scores_graph, {y_variable: y})\n\n np.testing.assert_allclose(tf_s, np_res_s)\n np.testing.assert_allclose(tf_scores, np_res_scores)\n\n\ndef test_hmm_tf_viterbi_decode_wrong_shape(hmm_tf_latch, hmm_latch):\n with pytest.raises(ValueError):\n hmm_tf_latch.viterbi_decode([0, 1, 1, 0])\n"
] |
[
[
"numpy.asarray",
"tensorflow.placeholder",
"numpy.stack",
"numpy.ones",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.sum",
"numpy.isclose"
]
] |
SmartDataLab/building_damage_kd
|
[
"45392fff69de818b8d13576de6c413372ca3d0e0"
] |
[
"train50_loc-KD.py"
] |
[
"import os\n\nos.environ[\"MKL_NUM_THREADS\"] = \"1\"\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\"\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\nfrom os import path, makedirs, listdir\nimport sys\nimport numpy as np\n\nnp.random.seed(1)\nimport random\n\nrandom.seed(1)\n\nimport torch\nfrom torch import nn\nfrom torch.backends import cudnn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nimport torch.optim.lr_scheduler as lr_scheduler\nimport time\n\neps = 1e-6\nfrom apex import amp\n\nfrom adamw import AdamW\nfrom losses import dice_round, ComboLoss\n\nimport pandas as pd\nfrom tqdm import tqdm\nimport timeit\nimport cv2\n\nfrom zoo.models import (\n SeResNext50_Unet_Loc,\n SeResNext50_Unet_Loc_KD,\n SeResNext50_Unet_Double,\n)\n\nfrom imgaug import augmenters as iaa\n\nfrom utils import *\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import accuracy_score\n\nimport gc\nfrom emailbox import EmailBot\n\nfrom apex import amp\n\nimport argparse\nfrom mongo_logger import Logger\n\nDB = \"building_damage_kd\"\nCOLLECTION = \"v2_loc\"\nlogger = Logger(DB, COLLECTION)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--mode\", default=\"T-S\", choices=[\"onlyT\", \"onlyS\", \"T-S\", \"TwoTeacher\"]\n)\nparser.add_argument(\"--LWF\", default=0, choices=[0, 1], type=int)\nparser.add_argument(\"--LFL\", default=0, choices=[0, 1], type=int)\nparser.add_argument(\"--clsLFL\", default=0, choices=[0, 1], type=int)\nparser.add_argument(\"--KL\", default=0, choices=[0, 1], type=int)\nparser.add_argument(\"--dataset\", default=\"/data1/su/app/xview2/building_damage_kd/\")\nparser.add_argument(\"--checkpoint_path\", default=\"weights\")\nparser.add_argument(\"--seed\", default=1, type=int)\nparser.add_argument(\"--vis_dev\", default=0, type=int)\nparser.add_argument(\"--batch_size\", default=8, type=int)\nparser.add_argument(\"--val_batch_size\", default=4, type=int)\nparser.add_argument(\"--lr\", default=0.002, type=float)\nparser.add_argument(\"--weight_decay\", default=1e-6, type=float)\nparser.add_argument(\"--theta\", default=1.0, type=float)\nparser.add_argument(\"--alpha\", default=1.0, type=float)\nparser.add_argument(\"--alpha_cls\", default=1.0, type=float)\nparser.add_argument(\"--beta\", default=1.0, type=float)\nparser.add_argument(\"--m\", default=0.2, type=float)\n\nargs = parser.parse_args()\nlogger.add_attr(\"LWF\", args.LWF, \"info\")\nlogger.add_attr(\"LFL\", args.LFL, \"info\")\nlogger.add_attr(\"clsLFL\", args.clsLFL, \"info\")\nlogger.add_attr(\"KL\", args.KL, \"info\")\nlogger.add_attr(\"mode\", args.mode, \"info\")\nlogger.add_attr(\"lr\", args.lr, \"info\")\nlogger.add_attr(\"theta\", args.theta, \"info\")\nlogger.add_attr(\"alpha\", args.alpha, \"info\")\nlogger.add_attr(\"alpha_cls\", args.alpha_cls, \"info\")\nlogger.add_attr(\"beta\", args.beta, \"info\")\nlogger.add_attr(\"m\", args.m, \"info\")\nlogger.add_attr(\"weight_decay\", args.weight_decay, \"info\")\nlogger.insert_into_db(\"info\")\n\nemailbot = EmailBot(\"settings.json\")\nemailbot.sendOne(\n {\n \"title\": \"显卡%s训练任务开始训练loc\" % args.vis_dev,\n \"content\": \"mode=%s,LWF=%s,KL=%s,LFL=%s,clsLFL=%s\"\n % (args.mode, args.LWF, args.KL, args.LFL, args.clsLFL),\n }\n)\ncv2.setNumThreads(0)\ncv2.ocl.setUseOpenCL(False)\n\ntrain_dirs = [\"train\", \"tier3\"]\n\nmodels_folder = args.checkpoint_path\n\ninput_shape = (512, 512)\n\n\nall_files = []\nfor d in train_dirs:\n for f in sorted(listdir(path.join(args.dataset + d, \"images\"))):\n if \"_pre_disaster.png\" in f:\n all_files.append(path.join(args.dataset + d, \"images\", f))\n\n\nclass TrainData(Dataset):\n def __init__(self, train_idxs):\n super().__init__()\n self.train_idxs = train_idxs\n self.elastic = iaa.ElasticTransformation(alpha=(0.25, 1.2), sigma=0.2)\n\n def __len__(self):\n return len(self.train_idxs)\n\n def __getitem__(self, idx):\n _idx = self.train_idxs[idx]\n\n fn = all_files[_idx]\n\n img = cv2.imread(fn, cv2.IMREAD_COLOR)\n\n if random.random() > 0.985:\n img = cv2.imread(\n fn.replace(\"_pre_disaster\", \"_post_disaster\"), cv2.IMREAD_COLOR\n )\n\n msk0 = cv2.imread(fn.replace(\"/images/\", \"/masks/\"), cv2.IMREAD_UNCHANGED)\n\n if random.random() > 0.5:\n img = img[::-1, ...]\n msk0 = msk0[::-1, ...]\n\n if random.random() > 0.05:\n rot = random.randrange(4)\n if rot > 0:\n img = np.rot90(img, k=rot)\n msk0 = np.rot90(msk0, k=rot)\n\n if random.random() > 0.9:\n shift_pnt = (random.randint(-320, 320), random.randint(-320, 320))\n img = shift_image(img, shift_pnt)\n msk0 = shift_image(msk0, shift_pnt)\n\n if random.random() > 0.9:\n rot_pnt = (\n img.shape[0] // 2 + random.randint(-320, 320),\n img.shape[1] // 2 + random.randint(-320, 320),\n )\n scale = 0.9 + random.random() * 0.2\n angle = random.randint(0, 20) - 10\n if (angle != 0) or (scale != 1):\n img = rotate_image(img, angle, scale, rot_pnt)\n msk0 = rotate_image(msk0, angle, scale, rot_pnt)\n\n crop_size = input_shape[0]\n if random.random() > 0.3:\n crop_size = random.randint(\n int(input_shape[0] / 1.1), int(input_shape[0] / 0.9)\n )\n\n bst_x0 = random.randint(0, img.shape[1] - crop_size)\n bst_y0 = random.randint(0, img.shape[0] - crop_size)\n bst_sc = -1\n try_cnt = random.randint(1, 5)\n for i in range(try_cnt):\n x0 = random.randint(0, img.shape[1] - crop_size)\n y0 = random.randint(0, img.shape[0] - crop_size)\n _sc = msk0[y0 : y0 + crop_size, x0 : x0 + crop_size].sum()\n if _sc > bst_sc:\n bst_sc = _sc\n bst_x0 = x0\n bst_y0 = y0\n x0 = bst_x0\n y0 = bst_y0\n img = img[y0 : y0 + crop_size, x0 : x0 + crop_size, :]\n msk0 = msk0[y0 : y0 + crop_size, x0 : x0 + crop_size]\n\n if crop_size != input_shape[0]:\n img = cv2.resize(img, input_shape, interpolation=cv2.INTER_LINEAR)\n msk0 = cv2.resize(msk0, input_shape, interpolation=cv2.INTER_LINEAR)\n\n if random.random() > 0.99:\n img = shift_channels(\n img, random.randint(-5, 5), random.randint(-5, 5), random.randint(-5, 5)\n )\n\n if random.random() > 0.99:\n img = change_hsv(\n img, random.randint(-5, 5), random.randint(-5, 5), random.randint(-5, 5)\n )\n\n if random.random() > 0.99:\n if random.random() > 0.99:\n img = clahe(img)\n elif random.random() > 0.99:\n img = gauss_noise(img)\n elif random.random() > 0.99:\n img = cv2.blur(img, (3, 3))\n elif random.random() > 0.99:\n if random.random() > 0.99:\n img = saturation(img, 0.9 + random.random() * 0.2)\n elif random.random() > 0.99:\n img = brightness(img, 0.9 + random.random() * 0.2)\n elif random.random() > 0.99:\n img = contrast(img, 0.9 + random.random() * 0.2)\n\n if random.random() > 0.999:\n el_det = self.elastic.to_deterministic()\n img = el_det.augment_image(img)\n\n msk = msk0[..., np.newaxis]\n\n msk = (msk > 127) * 1\n\n img = preprocess_inputs(img)\n\n img = torch.from_numpy(img.transpose((2, 0, 1))).float()\n msk = torch.from_numpy(msk.transpose((2, 0, 1))).long()\n\n sample = {\"img\": img, \"msk\": msk, \"fn\": fn}\n return sample\n\n\nclass ValData(Dataset):\n def __init__(self, image_idxs):\n super().__init__()\n self.image_idxs = image_idxs\n\n def __len__(self):\n return len(self.image_idxs)\n\n def __getitem__(self, idx):\n _idx = self.image_idxs[idx]\n\n fn = all_files[_idx]\n\n img = cv2.imread(fn, cv2.IMREAD_COLOR)\n\n msk0 = cv2.imread(fn.replace(\"/images/\", \"/masks/\"), cv2.IMREAD_UNCHANGED)\n\n msk = msk0[..., np.newaxis]\n\n msk = (msk > 127) * 1\n\n img = preprocess_inputs(img)\n\n img = torch.from_numpy(img.transpose((2, 0, 1))).float()\n msk = torch.from_numpy(msk.transpose((2, 0, 1))).long()\n\n sample = {\"img\": img, \"msk\": msk, \"fn\": fn}\n return sample\n\n\ndef validate(model, data_loader):\n global logger\n dices0 = []\n\n _thr = 0.5\n\n with torch.no_grad():\n for i, sample in enumerate(tqdm(data_loader)):\n msks = sample[\"msk\"].numpy()\n imgs = sample[\"img\"].cuda(non_blocking=True)\n t1 = time.time()\n out = model(imgs)\n t2 = time.time()\n logger.add_attr(\"batch_%s\" % i, t2 - t1, \"time_difference\")\n msk_pred = torch.sigmoid(out[:, 0, ...]).cpu().numpy()\n\n for j in range(msks.shape[0]):\n dices0.append(dice(msks[j, 0], msk_pred[j] > _thr))\n\n logger.insert_into_db(\"time_difference\")\n d0 = np.mean(dices0)\n logger.add_attr(\"d0\", d0)\n\n print(\"Val Dice: {}\".format(d0))\n return d0\n\n\ndef evaluate_val_kd(args, data_val, best_score, model, snapshot_name, current_epoch):\n global logger\n model.eval()\n d = validate(model, data_loader=data_val)\n logger.add_attr(\"epoch\", epoch)\n\n if d > best_score:\n torch.save(\n {\n \"epoch\": current_epoch + 1,\n \"state_dict\": model.state_dict(),\n \"best_score\": d,\n },\n path.join(models_folder, snapshot_name + \"_best\"),\n )\n best_score = d\n\n emailbot = EmailBot(\"settings.json\")\n emailbot.sendOne(\n {\n \"title\": \"显卡%s训练任务进行epoch=%s的测试\" % (args.vis_dev, current_epoch),\n \"content\": \"测试分数%s\" % d,\n }\n )\n print(\"score: {}\\tscore_best: {}\".format(d, best_score))\n return best_score\n\n\ndef train_epoch_kd(\n args,\n current_epoch,\n seg_loss,\n models,\n optimizer,\n scheduler,\n train_data_loader,\n):\n model_s, model_t, model_t_cls = models\n theta = args.theta\n alpha = args.alpha\n beta = args.beta\n global logger\n losses = AverageMeter()\n\n dices = AverageMeter()\n\n iterator = tqdm(train_data_loader)\n\n if args.mode == \"onlyT\":\n model_t.train(mode=True)\n elif args.mode == \"onlyS\":\n model_s.train(mode=True)\n else:\n model_s.train(mode=True)\n model_t.eval()\n if args.mode == \"TwoTeacher\":\n model_t_cls.eval()\n\n for i, sample in enumerate(iterator):\n imgs = sample[\"img\"].cuda(non_blocking=True)\n msks = sample[\"msk\"].cuda(non_blocking=True)\n\n if args.mode != \"onlyS\":\n out_t = model_t(imgs)[:, 0, ...]\n soft_out_t = torch.sigmoid(out_t / 2)\n feature_t = model_t.conv1(imgs)\n feature_t = model_t.conv2(feature_t)\n feature_t = model_t.conv3(feature_t)\n feature_t = model_t.conv4(feature_t)\n feature_t = model_t.conv5(feature_t)\n if args.mode != \"onlyT\":\n out_s = model_s(imgs)[:, 0, ...]\n soft_out_s = torch.sigmoid(out_s / 2)\n feature_s = model_s.conv1(imgs)\n feature_s = model_s.conv2(feature_s)\n feature_s = model_s.conv3(feature_s)\n feature_s = model_s.conv4(feature_s)\n feature_s = model_s.conv5(feature_s)\n if args.mode == \"TwoTeacher\":\n # out_t_cls = model_t_cls(imgs)\n # soft_out_t_cls = channel_five2two(F.softmax(out_t_cls, dim=1))[:, 1, ...]\n feature_tmp = model_t_cls.conv1(imgs)\n feature_tmp = model_t_cls.conv2(feature_tmp)\n feature_tmp = model_t_cls.conv3(feature_tmp)\n feature_tmp = model_t_cls.conv4(feature_tmp)\n feature_tmp = model_t_cls.conv5(feature_tmp)\n feature_t_cls = model_t_cls.conv1(imgs)\n feature_t_cls = model_t_cls.conv2(feature_t_cls)\n feature_t_cls = model_t_cls.conv3(feature_t_cls)\n feature_t_cls = model_t_cls.conv4(feature_t_cls)\n feature_t_cls = model_t_cls.conv5(feature_t_cls)\n feature_t_cls = torch.cat([feature_tmp, feature_t_cls], 1)\n\n # parser.add_argument('--loss',default='onlyCls',choices = ['onlyCls','Cls+LWF','Cls+LFL','Cls+LWF+LFL','TwoTeacher'])\n if args.mode in [\"T-S\", \"TwoTeacher\"]:\n loss_seg = seg_loss(soft_out_s, msks)\n loss_cls = -torch.log(\n 1e-9 + soft_out_s * msks + (1 - soft_out_s) * (1 - msks)\n ).mean()\n loss = theta * loss_cls + loss_seg\n\n if args.LWF:\n loss_ko = -(\n (soft_out_t * msks + (1 - soft_out_t) * (1 - msks))\n * torch.log(\n 1e-9 + soft_out_s * msks + (1 - soft_out_s) * (1 - msks)\n )\n ).mean()\n loss += loss_ko * beta\n if args.LFL:\n loss_kf = torch.norm(feature_t - feature_s, p=2, dim=0).mean()\n loss += loss_kf * alpha\n if args.KL:\n soft_out_s = torch.sigmoid(out_s)\n softmax_s = torch.cat(\n ((1 - soft_out_s).unsqueeze(1), soft_out_s.unsqueeze(1)), dim=1\n )\n soft_out_t = torch.sigmoid(out_t)\n softmax_t = torch.cat(\n ((1 - soft_out_t).unsqueeze(1), soft_out_t.unsqueeze(1)), dim=1\n )\n loss_kl = (\n (torch.log(1e-9 + softmax_s) - torch.log(1e-9 + softmax_t))\n * softmax_s\n ).mean()\n loss += loss_kl\n if args.mode == \"TwoTeacher\":\n loss_t_cls = theta * loss_cls\n # if args.LWF:\n # loss_ko_cls = (\n # -(\n # (soft_out_t * msks + (1 - soft_out_t) * (1 - msks))\n # * torch.log(\n # soft_out_s * msks + (1 - soft_out_s) * (1 - msks)\n # )\n # ).mean()\n # / 2.0\n # )\n # loss_t_cls += beta * loss_ko_cls\n if args.clsLFL:\n loss_kf_cls = torch.norm(\n feature_s - feature_t_cls[:, :2048, ...], p=2, dim=0\n ).mean()\n loss_t_cls += args.alpha_cls * loss_kf_cls\n # if args.KL:\n # loss_kl_cls = (\n # (torch.log(softmax_s) - F.log_softmax(out_t_cls, dim=1))\n # * softmax_s\n # ).mean()\n # loss_t_cls += loss_kl_cls\n loss = (1 - args.m) * loss + args.m * loss_t_cls\n with torch.no_grad():\n dice_sc = 1 - dice_round(soft_out_s, msks[:, 0, ...])\n elif args.mode == \"onlyT\":\n loss_seg = seg_loss(soft_out_t, msks)\n loss_cls = -torch.log(\n 1e-9 + soft_out_t * msks + (1 - soft_out_t) * (1 - msks)\n ).mean()\n loss = theta * loss_cls + loss_seg\n\n with torch.no_grad():\n dice_sc = 1 - dice_round(soft_out_t, msks[:, 0, ...])\n else:\n loss_seg = seg_loss(soft_out_s, msks)\n loss_cls = -torch.log(\n 1e-9 + soft_out_s * msks + (1 - soft_out_s) * (1 - msks)\n ).mean()\n loss = theta * loss_cls + loss_seg\n\n with torch.no_grad():\n dice_sc = 1 - dice_round(soft_out_s, msks[:, 0, ...])\n\n losses.update(loss.item(), imgs.size(0))\n\n dices.update(dice_sc, imgs.size(0))\n if not args.LWF:\n loss_ko = torch.tensor(0)\n if not args.LFL:\n loss_kf = torch.tensor(0)\n if not args.KL:\n loss_kl = torch.tensor(0)\n if args.mode == \"T-S\":\n iterator.set_description(\n \"epoch: {}; lr {:.7f}; Loss {loss.val:.4f} ({loss.avg:.4f}),Loss_cls {loss_cls:.4f},Loss_kf {loss_kf:.4f},Loss_ko {loss_ko:.4f},Loss_kl {loss_kl:.4f},Loss_seg {loss_seg:.4f}; Dice {dice.val:.4f} ({dice.avg:.4f})\".format(\n current_epoch,\n scheduler.get_lr()[-1],\n loss=losses,\n loss_cls=theta * loss_cls.item(),\n loss_kf=alpha * loss_kf.item(),\n loss_ko=beta * loss_ko.item(),\n loss_kl=loss_kl.item(),\n loss_seg=loss_seg.item(),\n dice=dices,\n )\n )\n elif args.mode == \"TwoTeacher\":\n\n loss_ko_cls = torch.tensor(0)\n if not args.clsLFL:\n loss_kf_cls = torch.tensor(0)\n\n loss_kl_cls = torch.tensor(0)\n iterator.set_description(\n \"epoch: {}; lr {:.7f}; Loss {loss.val:.4f} ({loss.avg:.4f}),Loss_cls {loss_cls:.4f},Loss_kf {loss_kf:.4f},Loss_ko {loss_ko:.4f},Loss_kl {loss_kl:.4f},Loss_kf_cls {loss_kf_cls:.4f},Loss_ko_cls {loss_ko_cls:.4f},Loss_kl_cls {loss_kl_cls:.4f},Loss_seg {loss_seg:.4f}; Dice {dice.val:.4f} ({dice.avg:.4f})\".format(\n current_epoch,\n scheduler.get_lr()[-1],\n loss=losses,\n loss_cls=theta * loss_cls.item(),\n loss_kf=alpha * loss_kf.item(),\n loss_ko=beta * loss_ko.item(),\n loss_kl=loss_kl.item(),\n loss_kf_cls=alpha * loss_kf_cls.item(),\n loss_ko_cls=beta * loss_ko_cls.item(),\n loss_kl_cls=loss_kl_cls.item(),\n loss_seg=loss_seg.item(),\n dice=dices,\n )\n )\n\n else:\n iterator.set_description(\n \"epoch: {}; lr {:.7f}; Loss {loss.val:.4f}; Dice {dice.val:.4f} ({dice.avg:.4f})\".format(\n current_epoch, scheduler.get_lr()[-1], loss=losses, dice=dices\n )\n )\n\n optimizer.zero_grad()\n\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n # loss.backward()\n torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), 1.1)\n optimizer.step()\n\n scheduler.step(current_epoch)\n\n print(\n \"epoch: {}; lr {:.7f}; Loss {loss.avg:.4f}\".format(\n current_epoch, scheduler.get_lr()[-1], loss=losses\n )\n )\n\n\nif __name__ == \"__main__\":\n t0 = timeit.default_timer()\n\n makedirs(models_folder, exist_ok=True)\n\n seed = args.seed\n vis_dev = args.vis_dev\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(vis_dev)\n\n cudnn.benchmark = True\n\n batch_size = args.batch_size\n val_batch_size = args.val_batch_size\n\n snapshot_name = \"loc_KD_{}_best\".format(logger.log_id)\n\n train_idxs, val_idxs = train_test_split(\n np.arange(len(all_files)), test_size=0.1, random_state=seed\n )\n\n np.random.seed(seed + 123)\n random.seed(seed + 123)\n\n steps_per_epoch = len(train_idxs) // batch_size\n validation_steps = len(val_idxs) // val_batch_size\n\n print(\"steps_per_epoch\", steps_per_epoch, \"validation_steps\", validation_steps)\n\n data_train = TrainData(train_idxs)\n val_train = ValData(val_idxs)\n\n train_data_loader = DataLoader(\n data_train,\n batch_size=batch_size,\n num_workers=5,\n shuffle=True,\n pin_memory=False,\n drop_last=True,\n )\n val_data_loader = DataLoader(\n val_train,\n batch_size=val_batch_size,\n num_workers=5,\n shuffle=False,\n pin_memory=False,\n )\n\n if args.mode == \"onlyT\":\n model_t = SeResNext50_Unet_Loc().cuda()\n elif args.mode == \"onlyS\":\n model_s = SeResNext50_Unet_Loc_KD().cuda()\n else:\n model_s = SeResNext50_Unet_Loc_KD().cuda()\n model_t = SeResNext50_Unet_Loc().cuda()\n if args.mode == \"TwoTeacher\":\n model_t_cls = SeResNext50_Unet_Double().cuda()\n checkpoint = torch.load(\n \"weights/res50_cls_cce_1_tuned_best\", map_location=\"cpu\"\n )\n loaded_dict = checkpoint[\"state_dict\"]\n sd = model_t_cls.state_dict()\n for k in model_t_cls.state_dict():\n if k in loaded_dict and sd[k].size() == loaded_dict[k].size():\n sd[k] = loaded_dict[k]\n loaded_dict = sd\n model_t_cls.load_state_dict(loaded_dict)\n for (\n key,\n value,\n ) in (\n model_t_cls.named_parameters()\n ): # named_parameters()包含网络模块名称 key为模型模块名称 value为模型模块值,可以通过判断模块名称进行对应模块冻结\n value.requires_grad = False\n\n if args.mode != \"onlyT\":\n params = model_s.parameters()\n optimizer = AdamW(params, lr=args.lr, weight_decay=args.weight_decay)\n model_s, optimizer = amp.initialize(model_s, optimizer, opt_level=\"O0\")\n scheduler = lr_scheduler.MultiStepLR(\n optimizer,\n milestones=[4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20],\n gamma=0.5,\n )\n else:\n params = model_t.parameters()\n optimizer = AdamW(params, lr=args.lr, weight_decay=args.weight_decay)\n model_t, optimizer = amp.initialize(model_t, optimizer, opt_level=\"O0\")\n scheduler = lr_scheduler.MultiStepLR(\n optimizer,\n milestones=[4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20],\n gamma=0.5,\n )\n\n seg_loss = ComboLoss({\"dice\": 3.0, \"focal\": 10.0}, per_image=False).cuda()\n\n if args.mode in [\"T-S\", \"TwoTeacher\"]:\n snap_to_load = \"weights/res50_loc_0_tuned_best\"\n checkpoint = torch.load(snap_to_load, map_location=\"cpu\")\n loaded_dict = checkpoint[\"state_dict\"]\n sd = model_t.state_dict()\n for k in model_t.state_dict():\n if k in loaded_dict and sd[k].size() == loaded_dict[k].size():\n sd[k] = loaded_dict[k]\n loaded_dict = sd\n model_t.load_state_dict(loaded_dict)\n print(\n \"loaded checkpoint '{}' (epoch {}, best_score {})\".format(\n snap_to_load, checkpoint[\"epoch\"], checkpoint[\"best_score\"]\n )\n )\n # named_parameters()包含网络模块名称 key为模型模块名称 value为模型模块值,可以通过判断模块名称进行对应模块冻结\n for key, value in model_t.named_parameters():\n value.requires_grad = False\n del loaded_dict\n del sd\n del checkpoint\n\n best_score = 0\n _cnt = -1\n torch.cuda.empty_cache()\n\n if args.mode == \"onlyT\":\n model_train = model_t\n models = (None, model_t, None)\n else:\n model_train = model_s\n if args.mode == \"onlyS\":\n models = (model_s, None, None)\n elif args.mode == \"T-S\":\n models = (model_s, model_t, None)\n else:\n models = (model_s, model_t, model_t_cls)\n\n for epoch in range(30):\n train_epoch_kd(\n args,\n epoch,\n seg_loss,\n models,\n optimizer,\n scheduler,\n train_data_loader,\n )\n if epoch % 2 == 0:\n _cnt += 1\n torch.cuda.empty_cache()\n best_score = evaluate_val_kd(\n args, val_data_loader, best_score, model_train, snapshot_name, epoch\n )\n\n elapsed = timeit.default_timer() - t0\n print(\"Time: {:.3f} min\".format(elapsed / 60))\n emailbot = EmailBot(\"settings.json\")\n emailbot.sendOne(\n {\"title\": \"显卡%s训练任务完成\" % args.vis_dev, \"content\": \"最佳分数%s\" % best_score}\n )\n"
] |
[
[
"torch.optim.lr_scheduler.MultiStepLR",
"numpy.rot90",
"torch.sigmoid",
"torch.norm",
"numpy.random.seed",
"torch.load",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.cuda.empty_cache",
"torch.tensor",
"torch.no_grad",
"numpy.mean",
"torch.log"
]
] |
davebx/ARTDeco
|
[
"1b08583a2e23015f6bc444919b2e10d5fb1bcf19"
] |
[
"ARTDeco/diff_exp_read_in.py"
] |
[
"'''\nModule that contains functions for running diff_exp_read_in mode.\n'''\nimport pandas as pd\nimport numpy as np\nimport os\nimport functools\n\n'''\nDefine a function that can get all of the condition information.\n'''\ndef get_conditions(conditions_file,meta_file):\n\n #Get conditions.\n condition1,condition2 = conditions_file.split('/')[-1].split('-')[:2]\n\n #Load the meta information.\n meta = pd.read_csv(meta_file,sep='\\t')\n meta = meta[meta.Group.isin([condition1,condition2])]\n\n condition1_expts = list(meta[meta.Group == condition1].Experiment)\n condition2_expts = list(meta[meta.Group == condition2].Experiment)\n\n return condition1,condition2,condition1_expts,condition2_expts\n\n'''\nDefine a function that can merge read-in information with differential expression output.\n'''\ndef read_in_diff_exp(read_in_file,meta_file,conditions_file,out_dir):\n\n #Get conditons.\n condition1,condition2,condition1_expts,condition2_expts = get_conditions(conditions_file,meta_file)\n\n #Load expression data.\n read_in_exp = pd.read_csv(read_in_file,sep='\\t')\n\n #Get average count/FPKM information for given experiments by condition.\n keep_cols = ['Gene ID','Transcript ID']\n for suffix in ['Gene Count','Gene FPKM','Read-In Count']:\n condition1_cols = [f'{expt} {suffix}' for expt in condition1_expts]\n read_in_exp[f'{condition1} Average {suffix}'] = read_in_exp[condition1_cols].mean(axis=1)\n keep_cols.append(f'{condition1} Average {suffix}')\n\n condition2_cols = [f'{expt} {suffix}' for expt in condition2_expts]\n read_in_exp[f'{condition2} Average {suffix}'] = read_in_exp[condition2_cols].mean(axis=1)\n keep_cols.append(f'{condition2} Average {suffix}')\n\n read_in_exp = read_in_exp[keep_cols]\n\n #Get the log2 ratio for the gene vs. read-in.\n read_in_exp[condition1+' Read-In vs. Gene'] = np.log2(read_in_exp[condition1+' Average Read-In Count']+1)-\\\n np.log2(read_in_exp[condition1+' Average Gene Count']+1)\n read_in_exp[condition2+' Read-In vs. Gene'] = np.log2(read_in_exp[condition2+' Average Read-In Count']+1)-\\\n np.log2(read_in_exp[condition2+' Average Gene Count']+1)\n\n #Load DESeq2 output.\n diff_exp = pd.read_csv(conditions_file,sep='\\t',index_col=0)\n\n #Merge expression information and DESeq2 output. Format for output.\n read_in_full_info = pd.merge(read_in_exp,diff_exp,left_on='Transcript ID',right_index=True)\n read_in_full_info = read_in_full_info[['Gene ID','Transcript ID','baseMean','log2FoldChange','lfcSE','stat',\n 'pvalue','padj',condition1+' Average Gene Count',\n condition1+' Average Gene FPKM',condition1+' Average Read-In Count',\n condition1+' Read-In vs. Gene',condition2+' Average Gene Count',\n condition2+' Average Gene FPKM',condition2+' Average Read-In Count',\n condition2+' Read-In vs. Gene']]\n\n #Output merged information.\n read_in_full_info.to_csv(os.path.join(out_dir,f'{condition1}-{condition2}-read_in.txt'),sep='\\t',index=False)\n\n'''\nDefine a function that can assign read-in genes for upregulated genes given thresholds for log2 fold change, p-value,\nFPKM, and a read-in threshold.\n'''\ndef assign_read_in_genes(diff_exp_read_in_file,log2FC,pval,FPKM,read_in_threshold,gene_types_file,gene_types,out_dir):\n\n #Get conditions.\n condition1,condition2 = diff_exp_read_in_file.split('/')[-1].split('-')[:2]\n\n #Get upregulated genes.\n diff_exp_read_in = pd.read_csv(diff_exp_read_in_file,sep='\\t')\n upreg = diff_exp_read_in[(diff_exp_read_in.log2FoldChange > log2FC) & (diff_exp_read_in.padj < pval) &\n (diff_exp_read_in[condition1+' Average Gene FPKM'] > FPKM)][\n ['Gene ID','Transcript ID','log2FoldChange','padj',condition1+' Read-In vs. Gene']].copy()\n\n #Make assignments.\n upreg['Assignment'] = 'Primary Induction'\n read_in_index = upreg[upreg[condition1+' Read-In vs. Gene'] > read_in_threshold].index\n upreg.loc[read_in_index,'Assignment'] = 'Read-In'\n\n #Limit gene types.\n gene_types_df = pd.read_csv(gene_types_file, sep='\\t')\n\n if gene_types and len(gene_types_df) > 0:\n gene_types_df = gene_types_df[gene_types_df['Gene Type'].isin(gene_types)]\n upreg = upreg[upreg['Gene ID'].isin(gene_types_df['Gene ID'])]\n\n upreg.to_csv(os.path.join(out_dir,f'{condition1}-{condition2}-read_in_assignment.txt'),sep='\\t',index=False)\n\n'''\nDefine a function that can summarize outputs for read-in assignments using differential expression.\n'''\ndef summarize_diff_exp_read_in_assignments(assignment_files,log2FC,pval,read_in_fpkm,read_in_threshold):\n\n output = 'Summary for read-in assignments using differential expression\\nThresholds are log2 fold change > '+\\\n f'{log2FC}, p-value < {pval}, FPKM > {read_in_fpkm}, and read-in level threshold is {read_in_threshold}\\n'\n\n summary_dfs = []\n for assignment_file in assignment_files:\n df = pd.read_csv(assignment_file,sep='\\t')\n summary = pd.DataFrame(df.groupby('Assignment').count()['Gene ID'])\n summary.columns = [assignment_file.split('/')[-1][:-23]]\n if 'Read-In' not in summary.index:\n summary.loc['Read-In'] = 0\n summary_dfs.append(summary)\n\n output_df = functools.reduce(lambda left,right: pd.merge(left,right,left_index=True,right_index=True),summary_dfs)\n\n return output+'\\n'.join(output_df.to_string().split('\\n'))"
] |
[
[
"numpy.log2",
"pandas.merge",
"pandas.read_csv"
]
] |
Amshra267/BOSCH_A-G_INTERIIT
|
[
"480af2894d91585ba8940b795fd8f20a6caa2998"
] |
[
"main.py"
] |
[
"from copyreg import dispatch_table\nimport os\n\n# comment out below line to enable tensorflow logging outputs\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport time\nimport tensorflow as tf\nimport statistics\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nif len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\nfrom absl import app, flags\nfrom absl.flags import FLAGS\nimport core.utils as utils\nfrom core.yolov4 import filter_boxes\nfrom tensorflow.python.saved_model import tag_constants\nfrom core.config import cfg\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\nfrom datetime import datetime\n# deep sort imports\nfrom deep_sort import preprocessing, nn_matching\nfrom deep_sort.detection import Detection\nfrom deep_sort.tracker import Tracker\nfrom tools import generate_detections as gdet\nimport math\nfrom collections import Counter, defaultdict\nfrom collections import deque\n# import albumentations as A\nfrom PIL import Image as im\nimport onnx\nfrom onnx_tf.backend import prepare\nfrom tensorflow import keras\nimport tensorflow_hub as hub\nfrom scipy import stats as s\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nos.environ[\"TFHUB_DOWNLOAD_PROGRESS\"] = \"True\"\n\n# flags.DEFINE_string('framework', 'tf', '(tf, tflite, trt')\nflags.DEFINE_string('weights', './checkpoints/yolov4-416',\n 'path to weights file')\nflags.DEFINE_integer('size', 416, 'resize images to')\nflags.DEFINE_boolean('tiny', False, 'yolo or yolo-tiny')\nflags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4')\nflags.DEFINE_string('video', 'data/video/test_n.mp4', 'path to input video or set to 0 for webcam')\nflags.DEFINE_string('output', \"outputs/video_results/test1.avi\", 'path to output video')\nflags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file')\nflags.DEFINE_float('iou', 0.45, 'iou threshold')\nflags.DEFINE_float('score', 0.50, 'score threshold')\nflags.DEFINE_float('show', 0, 'to show output')\n\n## Loading models\nprint(\"Started Initial Configurations --------------\")\nSAVED_MODEL_PATH = \"https://tfhub.dev/captain-pool/esrgan-tf2/1\"\nmodel_esrgan = hub.load(SAVED_MODEL_PATH) ##ESRGAN MODEL\nmodel_unet = onnx.load('model_data/unet.onnx') # segmentation model\ngender_model = keras.models.load_model(\"model_data/gender.h5\") # gender model path\nage_model = keras.models.load_model(\"model_data/age.h5\") # age model path\n\nprint(\"Initial configuration finished --------------------\")\n\nprint(\"Outputs will be available in outputs folder\")\n\n\ndef preprocess_image(image_batch):\n \"\"\" Loads images as batches and preprocesses to make it model ready\n Args:\n image_batch: Batches of images\n \"\"\"\n shr_image = tf.convert_to_tensor(image_batch, dtype=tf.float32)\n shr_size = (tf.convert_to_tensor(shr_image.shape[1:-1]) // 4) * 4\n shr_image = tf.image.crop_to_bounding_box(shr_image, 0, 0, shr_size[0], shr_size[1])\n shr_image = tf.cast(shr_image, tf.float32)\n return shr_image\n\n\ndef resize_func(img):\n img = tf.image.resize(\n img, (128, 128), method=tf.image.ResizeMethod.AREA, preserve_aspect_ratio=False,\n antialias=False, name=None\n ) / 255.0\n img = np.transpose(img, (2, 0, 1))\n return img\n\noutputs_ids_age = defaultdict(list)\noutputs_ids_gd = defaultdict(list)\noutputs_show = {}\n\ndef age_gender_pred(images_dict):\n global outputs_show\n file = open(\"outputs/labels.txt\", \"a\")\n tf_rep = prepare(model_unet)\n for id in images_dict:\n id_images = images_dict[id]\n if len(id_images) == 4:\n paths = f\"outputs/persons/person-{id}\"\n if not os.path.exists(paths):\n os.makedirs(paths)\n lr_image = preprocess_image(id_images) # Change path or image accordingly\n hr_image = model_esrgan(lr_image)\n img_batch = np.array(hr_image, dtype='float32')\n # print(img_batch[0, :, :, :].astype(\"uint8\"))\n # print(img_batch[0, :, :, :].min(), img_batch[0, :, :, :].max())\n # cv2.imshow('super resolved image', img_batch[0, :, :, :].astype(\"uint8\"))\n # cv2.waitKey(1)\n encoded_images = tf.map_fn(resize_func, img_batch)\n op = tf_rep.run(np.asarray(encoded_images, dtype=np.float32))\n res = op._0\n res[res > 0.0] = 1\n res[res <= 0.0] = 0\n mean = np.mean(res, axis=0)\n mean1 = mean.copy()\n mean1 = np.moveaxis(mean1, -1, 0)\n mean1 = np.moveaxis(mean1, -1, 1)\n assert mean1.shape[0] == 128\n # plt.imshow(mean1.astype(\"uint8\"))\n assert mean.shape[0] == 1\n ans_gender = gender_model.predict(mean)\n if ans_gender[0][0] >= 0.5:\n # print(\"Male\")\n gd = \"Male\"\n else:\n # print(\"Female\")\n gd = \"Female\"\n ans_age = age_model.predict(mean)\n # print('Age is: {}'.format(int(ans_age[0][0])))\n timing = str(time.time()).split(\".\")[0]\n cv2.imwrite(paths + f\"/{timing}.jpg\", np.array(id_images[0]).astype(np.uint8))\n outputs_ids_age[id].append(int(ans_age[0][0]))\n outputs_ids_gd[id].append(gd)\n images_dict[id].pop(0)\n for id in outputs_ids_age:\n mini = np.percentile(outputs_ids_age[id], q=25)\n maxi = np.percentile(outputs_ids_age[id], q=75)\n median_age = np.median(outputs_ids_age[id])\n try:\n mode_gd = statistics.mode(outputs_ids_gd[id])\n except:\n mode_gd = s.mode(outputs_ids_gd[id])[0]\n outputs_show[id] = (median_age, mode_gd)\n # print(outputs_show)\n # print(f\"Person - {id}, Gender - {mode_gd}, Age Range- ({mini}-{maxi}), Age - {median_age}\\n\")\n file.write(f\"Timestamp - {datetime.now()}, Person - {id}, Gender - {mode_gd}, Age Range- ({mini}-{maxi}), Age - {median_age}\\n\")\n file.close()\n\n\ndef main(_argv):\n global outputs_show\n # Initialising the Keras model to predict Demographics of image\n # model = tf.keras.models.load_model('model_data/New_32CL_5LR_43Epoc')\n\n # Definition of the parameters\n max_cosine_distance = 0.4\n nn_budget = None\n nms_max_overlap = 1.0\n\n # initialize deep sort\n model_filename = 'model_data/mars-small128.pb'\n encoder = gdet.create_box_encoder(model_filename, batch_size=1)\n # calculate cosine distance metric\n metric = nn_matching.NearestNeighborDistanceMetric(\"cosine\", max_cosine_distance, nn_budget)\n # initialize tracker\n tracker = Tracker(metric)\n\n # load configuration for object detector\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n session = InteractiveSession(config=config)\n STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS)\n input_size = 416\n video_path = FLAGS.video\n\n saved_model_loaded = tf.saved_model.load('./checkpoints/yolov4-416', tags=[tag_constants.SERVING])\n infer = saved_model_loaded.signatures['serving_default']\n\n # begin video capture\n try:\n vid = cv2.VideoCapture(int(video_path))\n except:\n vid = cv2.VideoCapture(video_path)\n\n out = None\n\n # get video ready to save locally if flag is set\n if FLAGS.output:\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = 10\n codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)\n out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height))\n\n frame_num = 0\n memory = {}\n cropped_images = defaultdict(list)\n\n # while video is running\n while True:\n return_value, frame = vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n else:\n print('Video has ended or failed, try a different video format!')\n break\n\n frame_num += 1\n # print('Frame #: ', frame_num)\n image_data = cv2.resize(frame, (input_size, input_size))\n image_data = image_data / 255.\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n start_time = time.time()\n batch_data = tf.constant(image_data)\n pred_bbox = infer(batch_data)\n for key, value in pred_bbox.items():\n boxes = value[:, :, 0:4]\n pred_conf = value[:, :, 4:]\n\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\n scores=tf.reshape(\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\n max_output_size_per_class=50,\n max_total_size=50,\n iou_threshold=0.45,\n score_threshold=0.50\n )\n\n # convert data to numpy arrays and slice out unused elements\n num_objects = valid_detections.numpy()[0]\n bboxes = boxes.numpy()[0]\n bboxes = bboxes[0:int(num_objects)]\n scores = scores.numpy()[0]\n scores = scores[0:int(num_objects)]\n classes = classes.numpy()[0]\n classes = classes[0:int(num_objects)]\n\n # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, width, height\n original_h, original_w, _ = frame.shape\n bboxes = utils.format_boxes(bboxes, original_h, original_w)\n\n # store all predictions in one parameter for simplicity when calling functions\n pred_bbox = [bboxes, scores, classes, num_objects]\n\n # read in all class names from config\n class_names = utils.read_class_names(cfg.YOLO.CLASSES)\n\n # by default allow all classes in .names file\n # allowed_classes = list(class_names.values())\n\n # custom allowed classes (uncomment line below to customize tracker for only people)\n allowed_classes = ['person']\n\n # loop through objects and use class index to get class name, allow only classes in allowed_classes list\n names = []\n deleted_indx = []\n for i in range(num_objects):\n class_indx = int(classes[i])\n class_name = class_names[class_indx]\n if class_name not in allowed_classes:\n deleted_indx.append(i)\n else:\n names.append(class_name)\n # print(names)\n names = np.array(names)\n bboxes = np.delete(bboxes, deleted_indx, axis=0)\n scores = np.delete(scores, deleted_indx, axis=0)\n\n # encode yolo detections and feed to tracker\n features = encoder(frame, bboxes)\n detections = [Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in\n zip(bboxes, scores, names, features)]\n\n # initialize color map\n cmap = plt.get_cmap('tab20b')\n colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]\n\n # run non-maxima supression\n boxs = np.array([d.tlwh for d in detections])\n scores = np.array([d.confidence for d in detections])\n classes = np.array([d.class_name for d in detections])\n indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores)\n detections = [detections[i] for i in indices]\n\n # Call the tracker\n tracker.predict()\n tracker.update(detections)\n\n disp = deepcopy(frame)\n\n # update tracks\n for track in tracker.tracks:\n if not track.is_confirmed() or track.time_since_update > 1:\n continue\n bbox = track.to_tlbr()\n class_name = track.get_class()\n \n # Tracking midpoints\n midpoint = track.tlbr_midpoint(bbox)\n\n if track.track_id not in memory: \n cropped_images[track.track_id] = []\n memory[track.track_id] = deque(maxlen=2)\n\n memory[track.track_id].append(midpoint)\n previous_midpoint = memory[track.track_id][0]\n\n # --------------- cropping image ---------\n xmin, ymin, xmax, ymax = bbox\n cropped_img = frame[int(ymin):int(ymax), int(xmin):int(xmax)]\n cropped_img = cv2.cvtColor(cropped_img, cv2.COLOR_BGR2RGB)\n image_data_flat = cropped_img.shape[0] * cropped_img.shape[1]\n if image_data_flat > 120 * 60:\n cropped_img = cv2.resize(cropped_img, (60, 120), cv2.INTER_AREA)\n else:\n cropped_img = cv2.resize(cropped_img, (60, 120), cv2.INTER_LINEAR)\n cropped_images[track.track_id].append(cropped_img)\n\n # draw bbox on screen\n color = colors[int(track.track_id) % len(colors)]\n color = [i * 255 for i in color]\n # cv2.imshow(f\"tracked - {track.track_id}\", frame[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])])\n cv2.rectangle(disp, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)\n cv2.line(disp, midpoint, previous_midpoint, (0, 255, 0), 2)\n # cv2.rectangle(frame, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(class_name)+len(str(\n # track.track_id)))*17, int(bbox[1])), color, -1)\n try:\n cv2.putText(disp, class_name + \"-\" + str(track.track_id) + \" \" + str(outputs_show[track.track_id]), (int(bbox[0]), int(bbox[1] - 10)), 0, 0.5,\n (255, 255, 255), 2)\n # print(\"done\")\n except:\n # print(e)\n pass\n age_gender_pred(cropped_images) # result output\n # calculate frames per second of entire model\n fps = 1.0 / (time.time() - start_time)\n # print(\"FPS: %.2f\" % fps)\n result = np.asarray(disp)\n result = cv2.cvtColor(disp, cv2.COLOR_RGB2BGR)\n \n if FLAGS.show:\n cv2.imshow(\"Output Video\", result)\n\n # if output flag is set, save video file\n if FLAGS.output:\n out.write(result)\n if cv2.waitKey(1) & 0xff == ord('q'): break\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n try:\n app.run(main)\n except SystemExit:\n pass\n"
] |
[
[
"tensorflow.convert_to_tensor",
"tensorflow.keras.models.load_model",
"numpy.linspace",
"numpy.asarray",
"tensorflow.cast",
"matplotlib.pyplot.get_cmap",
"tensorflow.map_fn",
"numpy.mean",
"tensorflow.compat.v1.InteractiveSession",
"numpy.moveaxis",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.shape",
"tensorflow.config.experimental.list_physical_devices",
"numpy.median",
"numpy.delete",
"numpy.transpose",
"numpy.array",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.constant",
"tensorflow.saved_model.load",
"tensorflow.image.crop_to_bounding_box",
"numpy.percentile",
"tensorflow.image.resize",
"scipy.stats.mode"
]
] |
atfkaka/CNTK
|
[
"4370db138aa1e14d9363a8ad055f23b7e7369377"
] |
[
"bindings/python/cntk/ops/functions.py"
] |
[
"from cntk import cntk_py\nfrom ..utils import typemap, sanitize_var_map, value_to_seq\nfrom enum import Enum, unique\nimport numpy as np\n\n\n@unique\nclass CloneMethod(Enum):\n '''\n Describes different ways how :func:`~cntk.ops.functions.Function.clone`\n works.\n '''\n\n share = 'share'\n '''\n Parameters are shared between the Function being cloned and the new clone\n '''\n\n clone = 'clone'\n '''\n New learnable parameters are created and initialied with the current values of the\n corresponding parameters of the Function being cloned\n '''\n\n freeze = 'freeze'\n '''\n Parameters are cloned and made immutable; i.e. Constants in the new clone\n (e.g. for use as a fixed feature extractor)\n '''\n\n\nclass Function(cntk_py.Function):\n '''\n Base class of all primitive tensor operators.\n\n If it has only one output, one can invoke Variable methods on it, which it\n will relay to its only output.\n '''\n\n\n # define input shapes, in-place\n # e.g.\n # model.declare_args(42)\n # pass a list of objects that define the dimensions etc. of the placeholders\n # Currently you can pass either\n def declare_args(self, *arg_types):\n placeholders = self.placeholders # the unbound parameters to fill in\n if len(arg_types) != len(placeholders):\n raise TypeError(\"CNTK Function.declare_inputs() expected {} arguments, got {}\".format(len(placeholders), len(arg_types)))\n def to_input(arg):\n if isinstance(arg, cntk_py.Variable):\n return arg\n else:\n from cntk import input_variable\n return input_variable(arg)\n args = [to_input(arg) for arg in arg_types]\n self.replace_placeholders(dict(zip(placeholders, args)))\n\n\n # call a function, i.e. clone with all placeholders/inputs replaced\n def __call__(self, *args):\n if not isinstance(args, tuple): # normalize single argument into tuple\n args = (args,)\n # flatten args to a list. Note it may be a a tuple or even a nested tree of tuples, e.g. LSTM (x, (h, c))\n def flatten_tuple(args):\n if not isinstance(args, tuple): # not a tuple: singleton; create a singleton tuple\n return (args,)\n from operator import add\n from functools import reduce\n return reduce(add, [(flatten_tuple(item)) for item in args])\n args = list(flatten_tuple(args)) # normalize nested arg tuples into flat tuple --TODO: is there a standard function to do this?\n # TODO: This should not be necessary, or go into Function.replace_placeholders()\n def _output_of(arg): # helper to get the output of an arg; use arg itself if no output() method (that'd be a Variable)\n try:\n return arg.output\n except AttributeError:\n return arg # Variables have no output()\n args = [_output_of(arg) for arg in args] # normalize args to their outputs --BUGBUG: without: \"TypeError: cannot convert value of dictionary to CNTK::Variable \"\n #from cntk.ops import combine\n #args = [combine([arg]) for arg in args] # BUGBUG: without: \"TypeError: cannot convert value of dictionary to CNTK::Variable \"\n placeholders = self.placeholders # the unbound parameters to fill in\n if len(args) != len(placeholders):\n raise TypeError(\"CNTK Function expected {} arguments, got {}\".format(len(placeholders), len(args)))\n return self.clone(CloneMethod.share, dict(zip(placeholders, args)))\n\n # forward function composition (other o self)\n def __rshift__(self, other):\n return other(self)\n\n # backward function composition (self o other)\n def __lshift__(self, other):\n return self(other)\n\n def __getattr__(self, name):\n try:\n return self.__dict__[name]\n except KeyError:\n if len(self.outputs) == 1:\n return getattr(self.output, name)\n\n raise AttributeError(\"'%s' object has no attribute '%s'\" %\n (type(self), name))\n\n @property\n @typemap\n def arguments(self):\n '''\n List of all input variables of the Function that are not of type Parameter or Constant\n '''\n return super(Function, self).arguments()\n\n @property\n @typemap\n def attributes(self):\n '''\n List of the attributes of the function\n '''\n return super(Function, self).attributes()\n\n @typemap\n def clone(self, method, substitutions=None):\n '''\n Clones the function. The parameters of the Function are either cloned,\n shared or frozen as specified by the method argument and any variable\n substitutions requested are applied in the cloned Function instance.\n\n Args:\n method (:class:`CloneMethod`): one of\n\n * 'clone': the returned function gets its own copy of parameters (default)\n * 'share': the returned function shares its parameters with this function\n * 'freeze': parameters are cloned and made immutable (constant).\n\n substitutions (dict): a dictionary mapping variables in this\n function to variables in the cloned function\n\n Returns:\n :class:`~cntk.ops.functions.Function`: the cloned Function\n '''\n method = getattr(cntk_py,\n 'ParameterCloningMethod_' + CloneMethod(method).name.capitalize())\n if substitutions is None:\n substitutions = {}\n return super(Function, self).clone(method, substitutions)\n\n @property\n @typemap\n def constants(self):\n '''\n List of all `Constant` variables of this :class:`~cntk.ops.functions.Function`\n '''\n return super(Function, self).constants()\n\n def eval(self, arguments=None, device=None):\n '''\n Evaluate the node using the specified ``arguments`` as input.\n\n Args:\n arguments: maps variables to their input data. The interpretation depends on\n the input type:\n\n * dict: keys are input variable or names, and values are the input data.\n * any other type: if node has an unique input, ``arguments`` is mapped to this input.\n For nodes with more than one input, only dict is allowed.\n In both cases, every every sample in the data will be interpreted\n as a new sequence. To mark samples as continuations of the\n previous sequence, specify ``arguments`` as `tuple`: the\n first element will be used as ``arguments``, and the second one will\n be used as a list of bools, denoting whether a sequence is a new\n one (`True`) or a continuation of the previous one (`False`).\n Data should be either NumPy arrays or a\n :class:`~cntk.io.MinibatchData` instance.\n device (:class:`~cntk.device.DeviceDescriptor`): the device descriptor that\n contains the type and id of the device on which the computation is\n to be performed.\n\n Returns:\n `bool`: `True` if updates have been performed\n '''\n\n _, output_map = self.forward(arguments, self.outputs, device=device)\n\n if len(output_map) > 1:\n return output_map\n else:\n return list(output_map.values())[0]\n\n @typemap\n def forward(self, arguments, outputs, keep_for_backward=None, device=None):\n '''\n Computes the values of speficied variables in ``outputs``, using values\n provided in ``arguments`` that correspond to each input `Variable` of\n the function whose ``is_input`` is `True`.\n\n Example:\n >>> v = C.input_variable(shape=(3,))\n >>> f = C.reciprocal(v)\n >>> _, fv = f.forward({v:[[1, 2, 4]]}, [f.output])\n >>> list(fv.values())[0]\n array([[[ 1. , 0.5 , 0.25]]], dtype=float32)\n\n Args:\n arguments: maps variables to their\n input data. The interpretation depends on the input type:\n\n * dict: keys are input variable or names, and values are the input data.\n * any other type: if node has an unique input, ``arguments`` is mapped to this input.\n For nodes with more than one input, only dict is allowed.\n In both cases, every every sample in the data will be interpreted\n as a new sequence. To mark samples as continuations of the\n previous sequence, specify ``arguments`` as ``tuple``: the\n first element will be used as ``arguments``, and the second one will\n be used as a list of bools, denoting whether a sequence is a new\n one (`True`) or a continuation of the previous one (`False`).\n Data should be either NumPy arrays or a\n :class:`~cntk.io.MinibatchData` instance.\n outputs (iterable): outputs to fetch values for.\n keep_for_backward (set, default `None`): the subset of the\n Function's output variables for which gradients shall be calculated\n in a subsequent backward call. If `None`, the returned state will\n be `None` and a subsequent call to :func:`backward` will not be\n possible.\n device (:class:`~cntk.device.DeviceDescriptor`, default `None`): the device\n descriptor that contains the type and id of the device on which the\n computation is. If `None`, the default device is used.\n\n Returns:\n A tuple (BackpropState, map of outputs to NumPy arrays). The\n BackpropState is a handle taken by :func:`backward`.\n '''\n if device is None:\n from cntk import DeviceDescriptor\n device = DeviceDescriptor.use_default_device()\n\n in_var_map = sanitize_var_map(self.arguments, arguments,\n None, device)\n output_map = {v: None for v in outputs}\n keep_for_backward = set(keep_for_backward or {})\n\n state = super(Function, self)._forward(in_var_map, output_map, device,\n keep_for_backward)\n\n for k in output_map:\n output_map[k] = value_to_seq(output_map[k])\n\n return state, output_map\n\n @typemap\n def backward(self, state, root_gradients, variables):\n '''\n Backpropagates supplied ``root_gradients`` for one or more of the output\n variables of the Function, to calculate gradients with respect to\n ``variables``. Formally, multiplies the values of ``root_gradients`` by\n the Jacobian of the Function and returns the subset of the output that\n corresponds to ``variables``.\n\n Example:\n >>> # compute the value and the derivative of the sigmoid at 0\n >>> v = C.input_variable(shape=(1,), needs_gradient=True)\n >>> f = C.sigmoid(v)\n >>> df, fv = f.forward({v:[[0]]}, [f.output], set([f.output]))\n >>> value = list(fv.values())[0]\n >>> grad = f.backward(df, {f.output: np.ones_like(value)}, set([v]))\n >>> value\n array([[[ 0.5]]], dtype=float32)\n >>> list(grad.values())[0]\n array([[[ 0.25]]], dtype=float32)\n\n Args:\n state (BackPropState): state obtained from a previous call to the\n func:`cntk.ops.Function.forward` method on this Function for the\n computation that this gradient backpropagation corresponds to.\n root_gradients (dict): the gradients that will be backpropagated\n variables (set): a list of input variables with respect to which\n the gradients have to be computed.\n\n Returns:\n dict: mapping of ``variables`` to NumPy arrays\n '''\n device = state.device()\n root_gradients = sanitize_var_map(self.outputs, root_gradients,\n None, device)\n\n var_gradients = dict((var, None) for var in variables)\n\n self._backward(state, root_gradients, var_gradients)\n\n for var, value in var_gradients.items():\n var_gradients[var] = value_to_seq(value)\n\n return var_gradients\n\n @typemap\n def grad(self, at, wrt=None, device=None):\n '''\n Computes the gradient of this Function at location ``at`` with respect to ``wrt``.\n The Function must have a single output.\n\n Example:\n >>> x = C.input_variable(shape=(1,), needs_gradient=True)\n >>> y = C.sqrt(x)\n >>> a = np.asarray([1,4,16],dtype=np.float32).reshape(3,1,1)\n >>> y.grad({x:a})\n [array([[[ 0.5 ]],\n <BLANKLINE>\n [[ 0.25 ]],\n <BLANKLINE>\n [[ 0.125]]], dtype=float32)]\n\n Args:\n at (dict) : mapping of the Function's arguments to values\n wrt (list optional): list of Variables with respect to which the\n gradient will be computed. If omitted, the gradients with\n respect to all arguments will be computed. If a variable\n is repeated in this list, the gradient will be repeated\n in the output as a shallow copy.\n\n Returns:\n list: list containing the gradients in the same order as\n the variables in ``wrt``. Each element has the same shape as\n ``wrt`` including dynamic axes (such as the minibatch axis).\n '''\n\n if len(self.outputs) != 1 :\n raise InvalidArgumentException('function must return a single tensor')\n\n if wrt is None:\n wrt = self.arguments\n\n unique_wrt = set(wrt)\n output = [self.output]\n df, f = self.forward(at, output, set(output), device)\n ones = {self.output: np.ones_like(v) for v in f.values()}\n grad_dict = self.backward(df, ones, unique_wrt)\n return [grad_dict[v] for v in wrt]\n\n @property\n @typemap\n def inputs(self):\n '''\n List of all input variables of this function.\n '''\n return super(Function, self).inputs()\n\n @property\n def name(self):\n '''\n Name of this function\n '''\n return super(Function, self).name()\n\n @property\n def op_name(self):\n '''\n Name of the operation that this Function performs\n '''\n return super(Function, self).op_name()\n\n\n @property\n @typemap\n def output(self):\n '''\n The single output variable if there is only one, or raises an exception.\n '''\n return super(Function, self).output()\n\n @property\n @typemap\n def outputs(self):\n '''\n List consisting of all output variables of this function.\n '''\n return super(Function, self).outputs()\n\n @property\n @typemap\n def parameters(self):\n '''\n List of all parameter variables of this function.\n '''\n return super(Function, self).parameters()\n\n @property\n @typemap\n def placeholders(self):\n '''\n List of all placeholders variables of this function.\n '''\n return super(Function, self).placeholders()\n\n @typemap\n def replace_placeholders(self, substitutions):\n '''\n In-place replace specified placeholders in the Function graph with the\n specified replacements in the map.\n\n Args:\n substitutions (dict): map from placeholder to variables\n\n Returns:\n :class:`Function`: itself\n '''\n return super(Function, self).replace_placeholders(substitutions)\n\n @typemap\n def replace_placeholder(self, substitution):\n '''\n In-place replace the only placeholder in the function graph with the\n specified substitution.\n\n Args:\n substitution (:class:`~cntk.ops.variables.Variable`): the variable\n that will replace the placeholder\n\n Returns:\n :class:`Function`: itself\n\n :raises ExceptionType: when the function has multiple placeholders.\n '''\n return super(Function, self).replace_placeholder(substitution)\n\n @typemap\n def save_model(self, filename, use_legacy_format=True):\n '''\n Save this function graph into a model file\n\n Args:\n filename (str): model path\n use_legacy_format (str): if 'True', model is stored using legacy format.\n Otherwise, it's stored using protobuf-based protocol serialization.\n '''\n return super(Function, self).save_model(filename, use_legacy_format)\n\n @typemap\n def restore_model(self, filename):\n '''\n Restore the models parameters from a saved model file\n\n Args:\n filename (str): saved model path\n\n Returns:\n `None`: this method only has the side-effect of loading the model parameters from the file\n '''\n return super(Function, self).restore_model(filename)\n\n @property\n @typemap\n def root_function(self):\n '''\n The primitive function at the root of the graph of functions underlying this function.\n '''\n return super(Function, self).root_function()\n\n @property\n @typemap\n def uid(self):\n '''\n The internally generated unique name of the function.\n '''\n return super(Function, self).uid()\n\n"
] |
[
[
"numpy.ones_like"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.