repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
MECH3750/2021-Tutorials | [
"e813f2a97d9b71ad0e304a35e8c66d21ed63ee0c"
]
| [
"Week_01/ict01FirstDerivatives.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 26 21:30:23 2021\n\n@author: uqcleon4\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Define functions and their derivatives\ndef f1(x):\n return x*x*x\n\ndef f2(x):\n return 3*x*x - 2*x\n\ndef f3(x):\n return np.sin(x)\n\ndef f1Prime(x):\n return 3*x*x\n\ndef f2Prime(x):\n return 6*x - 2\n\ndef f3Prime(x):\n return np.cos(x)\n\n# Create arrays for x and f(x)\nh = 0.1\nx = np.arange(-5,6,h,dtype=float)\nf = f1(x)\n\n# Calculate the forward, backward and central differences\nforwardD = np.empty_like(f)\nforwardD[:-1] = (f[1:]-f[:-1])/h\n\nbackwardD = np.empty_like(f)\nbackwardD[1:] = (f[1:]-f[:-1])/h\n\ncentralD = np.empty_like(f)\ncentralD[1:-1] = (f[2:]-f[:-2])/(2*h)\n\n# Calculate the error associated with each difference approach\nfd = f1Prime(x)\nerrors = np.zeros((3,x.size))\nerrors[0,:-1] = (fd[:-1]-forwardD[:-1])\nerrors[1,1:] = (fd[1:]-backwardD[1:])\nerrors[2,1:-1] = (fd[1:-1]-centralD[1:-1])\n\n# Plot the function and each derivative approximation\nfig,(ax1,ax2) = plt.subplots(2,1,sharey=False)\nax1.plot(x, f,\n x[:-1], forwardD[:-1], '-.',\n x[1:], backwardD[1:], ':',\n x[1:-1], centralD[1:-1], '--')\nax1.set(xlabel=\"x\", ylabel=\"f(x) and f'(x)\")\nax1.legend([\"f\", \"forwardD\",\"backwardD\", \"centralD\"])\nax1.grid()\n\nax2.plot(x[:-1], errors[0,:-1], '-.',\n x[1:], errors[1,1:], ':',\n x[1:-1], errors[2,1:-1], '--')\nax2.set(xlabel=\"x\", ylabel=\"Error in f'(x)\")\nax2.legend([\"forwardD\",\"backwardD\", \"centralD\"])\nax2.grid()\n\nplt.show()\n"
]
| [
[
"numpy.sin",
"numpy.zeros",
"matplotlib.pyplot.subplots",
"numpy.arange",
"numpy.cos",
"matplotlib.pyplot.show",
"numpy.empty_like"
]
]
|
allswellthatsmaxwell/surrogates | [
"840e011459aa690f30dc1816c19f50c7ee75db37"
]
| [
"surrogates/ch01_problem01.py"
]
| [
"# AUTOGENERATED! DO NOT EDIT! File to edit: ch01_problem01.ipynb (unless otherwise specified).\n\n__all__ = ['length', 'DataManager', 'attach_std', 'plot_scatter', 'plot_predictions_actual',\n 'plot_predictions_residuals', 'plot_predictions', 'wires_facet_theme']\n\n# Cell\n#export\nfrom nbdev.showdoc import *\nimport pandas as pd\nimport numpy as np\nimport plotnine as pn\nfrom typing import List\nfrom sklearn.linear_model import LinearRegression\n\n# Cell\n\ndef length(x: pd.Series):\n return np.sqrt(np.sum(np.square(x)))\n\n\nclass DataManager:\n def __init__(self, data: pd.DataFrame = None, response=\"pstren\",\n datafile=\"http://bobby.gramacy.com/surrogates/wire.csv\"):\n self.data = data\n if self.data is None:\n self.data = pd.read_csv(datafile)\n self.data.columns = [s.strip() for s in self.data.columns]\n self.response: str = response\n self.predictors: List[str] = self._get_predictors()\n self.normalized = False\n self.hypercubed = False\n self.orig_lengths = {}\n\n\n def spawn(self, new_data: pd.DataFrame):\n new = DataManager(data=new_data.copy(), response=self.response)\n new.orig_mean = self.orig_mean\n new.orig_std = self.orig_std\n new.orig_lengths = self.orig_lengths.copy()\n return new\n\n\n def _get_predictors(self) -> List[str]:\n return [colname for colname in self.data.columns if colname != self.response]\n\n\n def predictors_to_hypercube(self):\n \"\"\" Scales each predictor to length 1. \"\"\"\n if self.hypercubed:\n raise AssertionError(\"Predictors already scaled to hypercube.\")\n for colname in self.predictors:\n try:\n # Use the original if it exists.\n # Useful for spawned managers - they'll use the\n # parent original lengths.\n orig_length = self.orig_lengths[colname]\n except KeyError:\n orig_length = length(self.data[colname])\n self.orig_lengths[colname] = orig_length\n self.data[colname] /= orig_length\n self.hypercubed = True\n\n\n def normalize_response(self):\n \"\"\"\n Scales the response to a mean of 0 and standard deviation of 1.\n \"\"\"\n if self.normalized:\n raise AssertionError(\"Response already scaled to (mean, std) = (0, 1).\")\n self.orig_mean = np.mean(self.data[self.response])\n self.orig_std = np.std(self.data[self.response])\n self.data[self.response] -= self.orig_mean\n self.data[self.response] /= self.orig_std\n self.normalized = True\n\n\n def unscale_prediction(self, pred: float):\n return pred * self.orig_std + self.orig_mean\n\n\n\n def make_quadratic_variables_wide(self) -> pd.DataFrame:\n \"\"\"\n Returns a matrix with one column per variable combination, i.e.\n all the cross-multiplications. Also with one column per original variable.\n \"\"\"\n interactions = {}\n for i, coli in enumerate(self.predictors):\n interactions[coli] = self.data[coli]\n for j in range(i, len(self.predictors)):\n colj = self.predictors[j]\n interactions[f\"{coli}*{colj}\"] = self.data[coli] * self.data[colj]\n return pd.DataFrame(interactions)\n\n\n def make_quadratic_variables_long(self, wide=None):\n if wide is None:\n wide = self.make_quadratic_variables_wide()\n dfs = []\n idx = range(wide.shape[0])\n for colname in wide.columns:\n df = pd.DataFrame({'val': wide[colname]})\n df['var'] = colname\n df['response'] = self.data[self.response]\n dfs.append(df)\n return pd.concat(dfs)[['var', 'val', 'response']]\n\n\n def make_grid(self, x1_name, x2_name) -> pd.DataFrame:\n \"\"\"\n Makes a dataframe with the columns (var, x1, x2, self.response),\n where var is some string variable combination (e.g. s * t), x1 is the value\n of s, x2 is the value of t, and self.response is the value of the response\n at that actual s, t combination in the data.\n \"\"\"\n df = self.data[[x1_name, x2_name, self.response]]\n df.columns = ['x1', 'x2', self.response]\n\n df['var'] = f\"{x1_name}*{x2_name}\"\n return df.drop_duplicates()\n\n\n def make_grids(self) -> pd.DataFrame:\n \"\"\"\n Applies make_grid for every variable combination in the data.\n \"\"\"\n dfs = []\n icols = self.predictors\n for i in range(len(self.predictors)):\n dfs.append(self.make_grid(self.predictors[i], self.predictors[i]))\n for j in range(i - 1, len(self.predictors)):\n df = self.make_grid(self.predictors[i], self.predictors[j])\n dfs.append(df)\n return pd.concat(dfs)\n\n\n def get_linear_slopes(self, grids_df):\n \"\"\"\n Returns a dataframe with each variable in grids_df, and the size\n of each linear slope when a predictor on only that variable\n is fit to this manager's data.\n \"\"\"\n slope_rows = []\n for name, df in grids_df.groupby('var'):\n model = LinearRegression()\n X = pd.DataFrame(df['x1'] * df['x2']).values\n y = df[self.response].values\n model.fit(X, y)\n assert len(model.coef_) == 1\n slope = model.coef_[0]\n row = (name, slope)\n slope_rows.append(row)\n\n for name in self.predictors:\n df = grids_df[grids_df['var'] == f\"{name}*{name}\"]\n df = df.iloc[0:self.data.shape[0], :]\n\n if df.shape[0] != self.data.shape[0]:\n print(df)\n raise AssertionError(f\"got {df.shape[0]} rows but expected {self.data.shape[0]}\")\n X, y = pd.DataFrame(df['x1']).values, df[self.response].values\n model = LinearRegression().fit(X, y)\n assert len(model.coef_) == 1\n slope_rows.append((name, model.coef_[0]))\n slopes_df = pd.DataFrame(slope_rows, columns=['var', 'slope'])\n slopes_df['abs_slope'] = slopes_df['slope'].abs()\n return slopes_df.sort_values('abs_slope', ascending=False)\n\n\nwires_facet_theme = pn.theme(\n subplots_adjust={'hspace': 0.25},\n figure_size=(18, 15))\n\n\ndef attach_std(pred_df: pd.DataFrame, variance: np.array) -> None:\n pred_df['lb'] = pred_df['pred'] - np.sqrt(variance)\n pred_df['ub'] = pred_df['pred'] + np.sqrt(variance)\n\n\ndef plot_scatter(dat, figsize=(16, 12)):\n return (\n pn.ggplot(dat, pn.aes(x='val', y='response')) +\n pn.geom_point() +\n pn.geom_smooth(method='lm') +\n pn.facet_wrap(\"var\", scales='free_x') +\n pn.theme_bw() +\n pn.theme(figure_size=figsize, subplots_adjust={'hspace': 0.25}))\n\n\ndef plot_predictions_actual(pred_df, figsize):\n return (\n pn.ggplot(pred_df, pn.aes(x='y', y='pred')) +\n pn.geom_point() +\n pn.geom_ribbon(pn.aes(ymin='lb', ymax='ub'), alpha=0.3) +\n pn.geom_abline(slope=1, intercept=0) +\n pn.theme_bw() +\n pn.theme(figure_size=figsize))\n\n\ndef plot_predictions_residuals(pred_df, figsize):\n return (\n pn.ggplot(pred_df, pn.aes(x='y', y='resid')) +\n pn.geom_point() +\n pn.geom_hline(yintercept=0) +\n pn.theme_bw() +\n pn.theme(figure_size=figsize))\n\n\ndef plot_predictions(pred_df, figsize):\n actual = plot_predictions_actual(pred_df, figsize) + pn.ggtitle('actuals')\n display(actual);\n resid = plot_predictions_residuals(pred_df, figsize) + pn.ggtitle('residuals')\n display(resid);"
]
| [
[
"numpy.square",
"sklearn.linear_model.LinearRegression",
"pandas.DataFrame",
"numpy.mean",
"numpy.std",
"numpy.sqrt",
"pandas.concat",
"pandas.read_csv"
]
]
|
originalpkbims/dash-apps | [
"ea84cbd3e7227fb3de40cd16000838dd088343c7"
]
| [
"src/apps/tco2_dashboard/helpers.py"
]
| [
"import pandas as pd\nimport datetime as dt\nimport os\nimport json\n\n\ndef pct_change(first, second):\n diff = second - first\n change = 0\n try:\n if diff > 0:\n change = (diff / first) * 100\n elif diff < 0:\n diff = first - second\n change = -((diff / first) * 100)\n except ZeroDivisionError:\n return float('inf')\n return change\n\n\ndef add_px_figure(pxfig, layout, row, col):\n for trace in pxfig[\"data\"]:\n layout.append_trace(trace, row=row, col=col)\n\n\ndef drop_duplicates(df):\n df = df.drop_duplicates(subset=['Token Address'], keep='first')\n df = df.reset_index(drop=True)\n return df\n\n\ndef date_manipulations(df):\n if not(df.empty):\n if \"Vintage\" in df.columns:\n df[\"Vintage\"] = pd.to_datetime(\n df[\"Vintage\"], unit='s').dt.tz_localize(None).dt.year\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], unit='s').dt.tz_localize(\n None).dt.floor('D').dt.date\n datelist = pd.date_range(start=df[\"Date\"].min()+pd.DateOffset(-1),\n end=pd.to_datetime('today'), freq='d')\n df_date = pd.DataFrame()\n df_date[\"Date_continous\"] = datelist\n df_date[\"Date_continous\"] = pd.to_datetime(df_date[\"Date_continous\"], unit='s').dt.tz_localize(\n None).dt.floor('D').dt.date\n df = df.merge(df_date, how='right', left_on='Date',\n right_on='Date_continous').reset_index(drop=True)\n df[\"Date\"] = df[\"Date_continous\"]\n for i in df.columns:\n if \"Quantity\" in i:\n df[i] = df[i].fillna(0)\n else:\n df[i] = df[i].fillna(\"missing\")\n df[i] = df[i].replace(\"\", \"missing\")\n return df\n\n\ndef date_manipulations_verra(df):\n if not(df.empty):\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], unit='s').dt.tz_localize(\n None).dt.floor('D').dt.date\n datelist = pd.date_range(start=df[\"Date\"].min()+pd.DateOffset(-1),\n end=pd.to_datetime('today'), freq='d')\n df_date = pd.DataFrame()\n df_date[\"Date_continous\"] = datelist\n df_date[\"Date_continous\"] = pd.to_datetime(df_date[\"Date_continous\"], unit='s').dt.tz_localize(\n None).dt.floor('D').dt.date\n df = df.merge(df_date, how='right', left_on='Date',\n right_on='Date_continous').reset_index(drop=True)\n df[\"Date\"] = df[\"Date_continous\"]\n for i in df.columns:\n if \"Quantity\" in i:\n df[i] = df[i].fillna(0)\n else:\n df[i] = df[i].fillna(\"missing\")\n df[i] = df[i].replace(\"\", \"missing\")\n return df\n\n\ndef black_list_manipulations(df):\n # Dropping rows where Region = \"\", these tokenized carbon credits are black-listed\n # Black listed because their methodology = \"AM0001\"\n df = df[df[\"Region\"] != \"\"].reset_index()\n return df\n\n\ndef bridge_manipulations(df, bridge):\n # Filter dataframe based on bridge\n df = df[df[\"Bridge\"] == bridge].reset_index()\n return df\n\n\ndef merge_verra(df, df_verra, merge_columns, drop_columns):\n df[\"Project ID Key\"] = df[\"Project ID\"].astype(str).str[4:]\n df_verra[\"ID\"] = df_verra[\"ID\"].astype(str)\n df_verra = df_verra[merge_columns]\n df_verra = df_verra.drop_duplicates(\n subset=['ID']).reset_index(drop=True)\n for i in drop_columns:\n if i in df.columns:\n df = df.drop(columns=i)\n df = df.merge(df_verra, how='left', left_on=\"Project ID Key\",\n right_on='ID', suffixes=('', '_Verra'))\n\n return df\n\n# def merge_verra_mco2(df, df_verra, merge_columns, drop_columns):\n# # df[\"Project ID Key\"] = df[\"Project ID\"].astype(str).str[4:]\n# df_verra = df_verra[merge_columns]\n# for i in drop_columns:\n# if i in df.columns:\n# df = df.drop(columns=i)\n# df = df.merge(df_verra, how='left', left_on=\"Serial Number\",\n# right_on='Serial Number', suffixes=('', '_Verra'))\n# return df\n\n\ndef region_manipulations(df):\n df['Region'] = df['Region'].replace('South Korea', 'Korea, Republic of')\n # Belize country credits are categorized under Latin America. Confirmed this with Verra Registry\n df['Region'] = df['Region'].replace('Latin America', 'Belize')\n df['Region'] = df['Region'].replace('Oceania', 'Indonesia')\n df['Region'] = df['Region'].replace('Asia', 'Cambodia')\n return df\n\n\ndef subsets(df):\n\n # 7-day, last 7-day, 30-day and last 30 day time\n current_time = dt.datetime.combine(dt.date.today(), dt.datetime.min.time())\n seven_day_start = current_time - dt.timedelta(days=7)\n last_seven_day_start = seven_day_start - dt.timedelta(days=7)\n thirty_day_start = current_time - dt.timedelta(days=30)\n last_thirty_day_start = thirty_day_start - dt.timedelta(days=30)\n\n # Seven day pool subsets\n sd_pool = df[(df[\"Date\"] <= current_time.date()) &\n (df[\"Date\"] > seven_day_start.date())]\n last_sd_pool = df[(df[\"Date\"] <= seven_day_start.date())\n & (df[\"Date\"] > last_seven_day_start.date())]\n # # Thirty day pool subsets\n td_pool = df[(df[\"Date\"] <= current_time.date()) &\n (df[\"Date\"] > thirty_day_start.date())]\n last_td_pool = df[(df[\"Date\"] <= thirty_day_start.date())\n & (df[\"Date\"] > last_thirty_day_start.date())]\n\n return sd_pool, last_sd_pool, td_pool, last_td_pool\n\n\ndef filter_df_by_pool(df, pool_address):\n df[\"Pool\"] = df[\"Pool\"].str.lower()\n df = df[(df[\"Pool\"] == pool_address)].reset_index()\n return df\n\n\ndef verra_manipulations(df_verra):\n df_verra['Vintage'] = df_verra['Vintage Start']\n df_verra['Vintage'] = pd.to_datetime(\n df_verra[\"Vintage Start\"]).dt.tz_localize(None).dt.year\n df_verra['Quantity'] = df_verra['Quantity Issued']\n df_verra['Retirement/Cancellation Date'] = pd.to_datetime(\n df_verra['Retirement/Cancellation Date'])\n df_verra['Date'] = df_verra['Retirement/Cancellation Date']\n df_verra.loc[df_verra['Retirement Details'].str.contains(\n 'TOUCAN').fillna(False), 'Toucan'] = True\n df_verra['Toucan'] = df_verra['Toucan'].fillna(False)\n df_verra.loc[df_verra['Retirement Details'].str.contains(\n 'C3T').fillna(False), 'C3'] = True\n df_verra['C3'] = df_verra['C3'].fillna(False)\n df_verra_c3 = df_verra.query('C3')\n df_verra_toucan = df_verra.query('Toucan')\n return df_verra, df_verra_toucan, df_verra_c3\n\n\ndef verra_retired(df_verra, df_bridged_mco2):\n df_verra['Issuance Date'] = pd.to_datetime(df_verra['Issuance Date'])\n df_verra['Retirement/Cancellation Date'] = pd.to_datetime(\n df_verra['Retirement/Cancellation Date'])\n df_verra['Days to Retirement'] = (\n df_verra['Retirement/Cancellation Date'] - df_verra['Issuance Date']).dt.days\n df_verra.loc[df_verra['Days to Retirement'] > 0, 'Status'] = 'Retired'\n df_verra['Status'] = df_verra['Status'].fillna('Available')\n lst_sn = list(df_bridged_mco2['Serial Number'])\n df_verra.loc[df_verra['Serial Number'].isin(lst_sn), 'Moss'] = True\n df_verra['Moss'] = df_verra['Moss'].fillna(False)\n df_verra_retired = df_verra.query('~Toucan & ~C3 & ~Moss')\n df_verra_retired = df_verra_retired[df_verra_retired['Status'] == 'Retired']\n df_verra_retired = df_verra_retired.reset_index(drop=True)\n return df_verra_retired\n\n\ndef mco2_verra_manipulations(df_mco2_bridged):\n df_mco2_bridged = df_mco2_bridged[df_mco2_bridged['Project ID'] != 'missing']\n df_mco2_bridged[\"Quantity\"] = df_mco2_bridged[\"Quantity\"].astype(int)\n pat = r'VCS-(?P<id>\\d+)'\n repl = (\n lambda m: '[VCS-' + m.group(\n 'id') + '](https://registry.verra.org/app/projectDetail/VCS/' + m.group('id') + ')')\n df_mco2_bridged['Project ID'] = df_mco2_bridged['Project ID'].astype(str).str.replace(\n pat, repl, regex=True)\n return df_mco2_bridged\n\n\ndef filter_carbon_pool(pool_address, *dfs):\n filtered = []\n for df in dfs:\n filtered.append(filter_df_by_pool(df, pool_address))\n\n return filtered\n\n\ndef filter_pool_quantity(df, quantity_column):\n filtered = df[df[quantity_column] > 0]\n filtered[\"Quantity\"] = filtered[quantity_column]\n filtered = filtered[[\n 'Project ID', 'Vintage', 'Quantity', 'Country', 'Name', 'Project Type',\n 'Methodology', 'Token Address'\n ]]\n pat = r'VCS-(?P<id>\\d+)'\n repl = (\n lambda m: '[VCS-' + m.group(\n 'id') + '](https://registry.verra.org/app/projectDetail/VCS/' + m.group('id') + ')'\n )\n filtered['Project ID'] = filtered['Project ID'].str.replace(\n pat, repl, regex=True)\n filtered['View on PolygonScan'] = '[' + 'Click Here' + \\\n '](https://polygonscan.com/address/' + filtered['Token Address'] + ')'\n return filtered\n\n\ndef read_csv(filename):\n '''READ a csv file from the 'data' folder'''\n script_dir = os.path.dirname(__file__)\n file_dir = os.path.join(script_dir, 'data')\n df = pd.read_csv(os.path.join(file_dir, filename), thousands=',')\n\n return df\n\n\ndef to_csv(df, filename):\n '''Write a dataframe to a csv file in 'data' folder'''\n script_dir = os.path.dirname(__file__)\n file_dir = os.path.join(script_dir, 'data')\n df.to_csv(os.path.join(file_dir, filename), escapechar='\\\\')\n\n\ndef dump_to_json(data, filename):\n script_dir = os.path.dirname(__file__)\n file_dir = os.path.join(script_dir, 'data')\n with open(os.path.join(file_dir, filename), 'w') as outfile:\n json_string = json.dumps(data)\n json.dump(json_string, outfile)\n\n\ndef read_from_json(filename):\n script_dir = os.path.dirname(__file__)\n file_dir = os.path.join(script_dir, 'data')\n with open(os.path.join(file_dir, filename)) as json_file:\n data = json.load(json_file)\n data = json.loads(data)\n return data\n\n\ndef adjust_mco2_bridges(df, df_tx):\n df_tx = df_tx[['Date', 'Tx Address']]\n df = df.merge(df_tx, how='left', left_on='Original Tx Address',\n right_on='Tx Address', suffixes=('', '_new')).reset_index(drop=True)\n df.loc[df[\"Original Tx Address\"] != '0x0000000000000000000000000000000000000000000000000000000000000000', 'Date'] \\\n = df.loc[df[\"Original Tx Address\"] !=\n '0x0000000000000000000000000000000000000000000000000000000000000000', 'Date_new']\n df = df.drop(columns=['Tx Address', 'Date_new'])\n return df\n"
]
| [
[
"pandas.to_datetime",
"pandas.DataFrame",
"pandas.DateOffset"
]
]
|
gwarmstrong/microsetta-public-api | [
"53fe464aef6df13edb48a781bad6fe6f42f7251b"
]
| [
"microsetta_public_api/utils/testing.py"
]
| [
"import functools\nimport json\nimport types\nimport tempfile\nfrom unittest.case import TestCase\nfrom unittest.mock import patch\nimport pandas as pd\nimport numpy as np\nimport biom\nfrom qiime2 import Metadata, Artifact\n\n\nimport microsetta_public_api\nimport microsetta_public_api.server\nimport microsetta_public_api.utils._utils\nfrom microsetta_public_api import config\nfrom microsetta_public_api.resources import resources\nfrom microsetta_public_api.resources_alt import resources_alt\nfrom microsetta_public_api.config import ConfigElementVisitor, Element\n\n\nclass MockMetadataElement(Element):\n\n def __init__(self, instance):\n super().__init__()\n self.instance = instance\n\n def accept(self, visitor):\n self.data = self.instance\n\n\nclass TrivialVisitor(ConfigElementVisitor):\n\n def visit(self, element):\n element.data = element\n\n visit_alpha = visit\n visit_taxonomy = visit\n visit_pcoa = visit\n visit_metadata = visit\n visit_beta = visit\n\n\nclass TempfileTestCase(TestCase):\n\n def setUp(self):\n self._tempfiles = []\n\n def create_tempfile(self, **named_temporary_file_kwargs):\n # See the docs here for kwargs:\n # https://docs.python.org/3/library/tempfile.html\n new_tempfile = tempfile.NamedTemporaryFile(\n **named_temporary_file_kwargs)\n self._tempfiles.append(new_tempfile)\n return new_tempfile\n\n def tearDown(self):\n for tempfile_ in self._tempfiles:\n tempfile_.close()\n\n\nclass FlaskTests(TestCase):\n\n def setUp(self):\n\n self.app, self.client = self.build_app_test_client()\n self.app_context = self.app.app.app_context\n\n @staticmethod\n def build_app_test_client():\n app = microsetta_public_api.server.build_app()\n client = app.app.test_client()\n return app, client\n\n def assertStatusCode(self, exp_code, response):\n try:\n status_code = response.status_code\n self.assertEqual(exp_code, status_code)\n except AssertionError:\n raise AssertionError(f'{exp_code} != {status_code}'\n f'\\nRecieved response data: {response.data}')\n\n\ndef _copy_func(f, name=None):\n \"\"\"\n Based on https://stackoverflow.com/q/13503079\n \"\"\"\n g = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,\n argdefs=f.__defaults__, closure=f.__closure__)\n g = functools.update_wrapper(g, f)\n g.__kwdefaults__ = f.__kwdefaults__\n return g\n\n\nclass MockedResponse(str):\n\n def __init__(self, data):\n super().__init__()\n self.data = data\n\n def __eq__(self, other):\n if isinstance(other, MockedResponse):\n return self.data == other.data\n else:\n return self.data == other\n\n\ndef mocked_jsonify(*args, **kwargs):\n \"\"\"Can be used to replace flask.jsonify, since it does not work\n outside of a application context\n\n From the flask docs:\n 1. Single argument: Passed straight through to dumps\n 2. Multiple arguments: converted to array and passed to dumps\n 3. Multiple kwargs: converted to a dict and passed to dumps\n 4. Both args and kwargs: behavior undefined and will throw an exception\n\n Additionally, a _MockedWebResponse object the\n \"\"\"\n # need to return an object so its attributes can be set (like in get_alpha)\n def dump(data):\n return MockedResponse(json.dumps(data))\n if len(args) == 1 and len(kwargs) == 0:\n return dump(*args)\n elif len(args) > 1 and len(kwargs) == 0:\n return dump([arg for arg in args])\n elif len(args) == 0 and len(kwargs) > 0:\n return dump(kwargs)\n else:\n raise TypeError(f\"mocked_jsonify got an unexpected combination of \"\n f\"args and kwargs. Got args={args}, kwargs={kwargs}.\")\n\n\nclass MockedJsonifyTestCase(TestCase):\n\n def setUp(self):\n if isinstance(self.jsonify_to_patch, str):\n self.jsonify_patcher = patch(\n self.jsonify_to_patch,\n new=mocked_jsonify,\n )\n self.mock_jsonify = self.jsonify_patcher.start()\n else:\n self.jsonify_patcher = [patch(jsonify_, new=mocked_jsonify) for\n jsonify_ in self.jsonify_to_patch]\n self.mock_jsonify = [patcher.start() for\n patcher in self.jsonify_patcher]\n\n def tearDown(self):\n if isinstance(self.mock_jsonify, list):\n for patcher in self.jsonify_patcher:\n patcher.stop()\n else:\n self.jsonify_patcher.stop()\n\n\nclass ConfigTestCase(TestCase):\n\n def setUp(self):\n self._config_copy = config.resources.copy()\n self._resources_copy = resources.copy()\n self._resources_alt_copy = resources_alt.copy()\n\n def tearDown(self):\n config.resources = self._config_copy\n resources.clear()\n dict.update(resources, self._resources_copy)\n resources_alt.clear()\n resources_alt.update(self._resources_alt_copy)\n\n\nclass TestDatabase:\n def __init__(self, n_samples=2000, seed=None):\n np.random.seed(seed)\n sample_set = [f'sample-{i + 1:04d}' for i in range(n_samples)]\n age_categories = np.array(['30s', '40s', '50s'])\n bmi_categories = np.array(['Normal', 'Overweight', 'Underweight'])\n\n self.faith_pd_data = pd.Series(np.random.normal(6, 1.5, n_samples),\n index=sample_set, name='faith_pd')\n\n self.taxonomy_greengenes_df = pd.DataFrame(\n [['feature-1', 'k__a; p__b; o__c', 0.123],\n ['feature-2', 'k__a; p__b; o__c; f__d; g__e', 0.34],\n ['feature-3', 'k__a; p__f; o__g; f__h', 0.678]],\n columns=['Feature ID', 'Taxon', 'Confidence'])\n self.taxonomy_greengenes_df.set_index('Feature ID', inplace=True)\n\n self.table = biom.Table(\n np.random.multinomial(5, [1/3.] * 3, size=n_samples).transpose(),\n ['feature-1', 'feature-2', 'feature-3'],\n sample_set)\n\n self.metadata_table = pd.DataFrame(\n {\n 'age_cat': np.random.choice(age_categories,\n len(sample_set)),\n 'bmi_cat': np.random.choice(bmi_categories,\n len(sample_set)),\n }, index=pd.Series(sample_set,\n name='#SampleID')\n )\n\n self._tempfiles = []\n\n def create_tempfile(self, **named_temporary_file_kwargs):\n new_tempfile = tempfile.NamedTemporaryFile(\n **named_temporary_file_kwargs)\n self._tempfiles = []\n return new_tempfile\n\n def __enter__(self):\n self.start()\n\n def start(self):\n self.metadata_file = self.create_tempfile(suffix='.txt')\n metadata_path = self.metadata_file.name\n Metadata(self.metadata_table).save(metadata_path)\n self.faith_pd_file = self.create_tempfile(suffix='.qza')\n faith_pd_path = self.faith_pd_file.name\n faith_pd_artifact = Artifact.import_data(\n \"SampleData[AlphaDiversity]\", self.faith_pd_data,\n )\n faith_pd_artifact.save(faith_pd_path)\n self.taxonomy_file = self.create_tempfile(suffix='.qza')\n taxonomy_path = self.taxonomy_file.name\n imported_artifact = Artifact.import_data(\n \"FeatureData[Taxonomy]\", self.taxonomy_greengenes_df\n )\n imported_artifact.save(taxonomy_path)\n self.table_file = self.create_tempfile(suffix='.qza')\n table_path = self.table_file.name\n imported_artifact = Artifact.import_data(\n \"FeatureTable[Frequency]\", self.table\n )\n imported_artifact.save(table_path)\n config.resources.update({'metadata': metadata_path,\n 'alpha_resources': {\n 'faith-pd': faith_pd_path,\n },\n 'table_resources': {\n 'greengenes': {\n 'table': table_path,\n 'feature-data-taxonomy':\n taxonomy_path,\n }\n },\n })\n resources.update(config.resources)\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return self.stop()\n\n def stop(self):\n for file_ in self._tempfiles:\n file_.close()\n config.resources.clear()\n resources.clear()\n return True\n"
]
| [
[
"numpy.random.normal",
"numpy.array",
"numpy.random.seed",
"pandas.DataFrame",
"pandas.Series",
"numpy.random.multinomial"
]
]
|
simonaxelrod/chemprop | [
"1c1090fb894c9f951f5c85600d447af52c7d7a8b"
]
| [
"chemprop/args.py"
]
| [
"import json\nimport os\nfrom tempfile import TemporaryDirectory\nimport pickle\nfrom typing import List, Optional, Tuple\nfrom typing_extensions import Literal\n\nimport torch\nfrom tap import Tap # pip install typed-argument-parser (https://github.com/swansonk14/typed-argument-parser)\n\nfrom chemprop.data import set_cache_mol\nfrom chemprop.features import get_available_features_generators\n\n\nMetric = Literal['auc', 'prc-auc', 'rmse', 'mae', 'mse', 'r2', 'accuracy', 'cross_entropy', 'binary_cross_entropy']\n\n\ndef get_checkpoint_paths(checkpoint_path: Optional[str] = None,\n checkpoint_paths: Optional[List[str]] = None,\n checkpoint_dir: Optional[str] = None,\n ext: str = '.pt') -> Optional[List[str]]:\n \"\"\"\n Gets a list of checkpoint paths either from a single checkpoint path or from a directory of checkpoints.\n\n If :code:`checkpoint_path` is provided, only collects that one checkpoint.\n If :code:`checkpoint_paths` is provided, collects all of the provided checkpoints.\n If :code:`checkpoint_dir` is provided, walks the directory and collects all checkpoints.\n A checkpoint is any file ending in the extension ext.\n\n :param checkpoint_path: Path to a checkpoint.\n :param checkpoint_paths: List of paths to checkpoints.\n :param checkpoint_dir: Path to a directory containing checkpoints.\n :param ext: The extension which defines a checkpoint file.\n :return: A list of paths to checkpoints or None if no checkpoint path(s)/dir are provided.\n \"\"\"\n if sum(var is not None for var in [checkpoint_dir, checkpoint_path, checkpoint_paths]) > 1:\n raise ValueError('Can only specify one of checkpoint_dir, checkpoint_path, and checkpoint_paths')\n\n if checkpoint_path is not None:\n return [checkpoint_path]\n\n if checkpoint_paths is not None:\n return checkpoint_paths\n\n if checkpoint_dir is not None:\n checkpoint_paths = []\n\n for root, _, files in os.walk(checkpoint_dir):\n for fname in files:\n if fname.endswith(ext):\n checkpoint_paths.append(os.path.join(root, fname))\n\n if len(checkpoint_paths) == 0:\n raise ValueError(f'Failed to find any checkpoints with extension \"{ext}\" in directory \"{checkpoint_dir}\"')\n\n return checkpoint_paths\n\n return None\n\n\nclass CommonArgs(Tap):\n \"\"\":class:`CommonArgs` contains arguments that are used in both :class:`TrainArgs` and :class:`PredictArgs`.\"\"\"\n\n smiles_columns: List[str] = None\n \"\"\"List of names of the columns containing SMILES strings. \n By default, uses the first :code:`number_of_molecules` columns.\"\"\"\n number_of_molecules: int = 1\n \"\"\"Number of molecules in each input to the model.\n This must equal the length of :code:`smiles_column` (if not :code:`None`).\"\"\"\n checkpoint_dir: str = None\n \"\"\"Directory from which to load model checkpoints (walks directory and ensembles all models that are found).\"\"\"\n checkpoint_path: str = None\n \"\"\"Path to model checkpoint (:code:`.pt` file).\"\"\"\n checkpoint_paths: List[str] = None\n \"\"\"List of paths to model checkpoints (:code:`.pt` files).\"\"\"\n no_cuda: bool = False\n \"\"\"Turn off cuda (i.e., use CPU instead of GPU).\"\"\"\n gpu: int = None\n \"\"\"Which GPU to use.\"\"\"\n features_generator: List[str] = None\n \"\"\"Method(s) of generating additional features.\"\"\"\n features_path: List[str] = None\n \"\"\"Path(s) to features to use in FNN (instead of features_generator).\"\"\"\n no_features_scaling: bool = False\n \"\"\"Turn off scaling of features.\"\"\"\n max_data_size: int = None\n \"\"\"Maximum number of data points to load.\"\"\"\n num_workers: int = 8 \n \"\"\"Number of workers for the parallel data loading (0 means sequential).\"\"\"\n batch_size: int = 50\n \"\"\"Batch size.\"\"\"\n atom_descriptors: Literal['feature', 'descriptor'] = None\n \"\"\"\n Custom extra atom descriptors.\n :code:`feature`: used as atom features to featurize a given molecule. \n :code:`descriptor`: used as descriptor and concatenated to the machine learned atomic representation.\n \"\"\"\n atom_descriptors_path: str = None\n \"\"\"Path to the extra atom descriptors.\"\"\"\n no_cache_mol: bool = False\n \"\"\"\n Whether to not cache the RDKit molecule for each SMILES string to reduce memory usage (cached by default).\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(CommonArgs, self).__init__(*args, **kwargs)\n self._atom_features_size = 0\n self._atom_descriptors_size = 0\n\n @property\n def device(self) -> torch.device:\n \"\"\"The :code:`torch.device` on which to load and process data and models.\"\"\"\n if not self.cuda:\n return torch.device('cpu')\n\n return torch.device('cuda', self.gpu)\n\n @device.setter\n def device(self, device: torch.device) -> None:\n self.cuda = device.type == 'cuda'\n self.gpu = device.index\n\n @property\n def cuda(self) -> bool:\n \"\"\"Whether to use CUDA (i.e., GPUs) or not.\"\"\"\n return not self.no_cuda and torch.cuda.is_available()\n\n @cuda.setter\n def cuda(self, cuda: bool) -> None:\n self.no_cuda = not cuda\n\n @property\n def features_scaling(self) -> bool:\n \"\"\"Whether to apply normalization with a :class:`~chemprop.data.scaler.StandardScaler` to the additional molecule-level features.\"\"\"\n return not self.no_features_scaling\n\n @property\n def atom_features_size(self) -> int:\n \"\"\"The size of the atom features.\"\"\"\n return self._atom_features_size\n\n @atom_features_size.setter\n def atom_features_size(self, atom_features_size: int) -> None:\n self._atom_features_size = atom_features_size\n\n @property\n def atom_descriptors_size(self) -> int:\n \"\"\"The size of the atom descriptors.\"\"\"\n return self._atom_descriptors_size\n\n @atom_descriptors_size.setter\n def atom_descriptors_size(self, atom_descriptors_size: int) -> None:\n self._atom_descriptors_size = atom_descriptors_size\n\n def add_arguments(self) -> None:\n self.add_argument('--gpu', choices=list(range(torch.cuda.device_count())))\n self.add_argument('--features_generator', choices=get_available_features_generators())\n\n def process_args(self) -> None:\n # Load checkpoint paths\n self.checkpoint_paths = get_checkpoint_paths(\n checkpoint_path=self.checkpoint_path,\n checkpoint_paths=self.checkpoint_paths,\n checkpoint_dir=self.checkpoint_dir,\n )\n\n # Validate features\n if self.features_generator is not None and 'rdkit_2d_normalized' in self.features_generator and self.features_scaling:\n raise ValueError('When using rdkit_2d_normalized features, --no_features_scaling must be specified.')\n\n if self.smiles_columns is None:\n self.smiles_columns = [None] * self.number_of_molecules\n elif len(self.smiles_columns) != self.number_of_molecules:\n raise ValueError('Length of smiles_columns must match number_of_molecules.')\n\n # Validate atom descriptors\n if (self.atom_descriptors is None) != (self.atom_descriptors_path is None):\n raise ValueError('If atom_descriptors is specified, then an atom_descriptors_path must be provided '\n 'and vice versa.')\n\n if self.atom_descriptors is not None and self.number_of_molecules > 1:\n raise NotImplementedError('Atom descriptors are currently only supported with one molecule '\n 'per input (i.e., number_of_molecules = 1).')\n\n set_cache_mol(not self.no_cache_mol)\n\n\nclass TrainArgs(CommonArgs):\n \"\"\":class:`TrainArgs` includes :class:`CommonArgs` along with additional arguments used for training a Chemprop model.\"\"\"\n\n # General arguments\n data_path: str\n \"\"\"Path to data CSV file.\"\"\"\n target_columns: List[str] = None\n \"\"\"\n Name of the columns containing target values.\n By default, uses all columns except the SMILES column and the :code:`ignore_columns`.\n \"\"\"\n ignore_columns: List[str] = None\n \"\"\"Name of the columns to ignore when :code:`target_columns` is not provided.\"\"\"\n dataset_type: Literal['regression', 'classification', 'multiclass']\n \"\"\"Type of dataset. This determines the loss function used during training.\"\"\"\n multiclass_num_classes: int = 3\n \"\"\"Number of classes when running multiclass classification.\"\"\"\n separate_val_path: str = None\n \"\"\"Path to separate val set, optional.\"\"\"\n separate_test_path: str = None\n \"\"\"Path to separate test set, optional.\"\"\"\n split_type: Literal['random', 'scaffold_balanced', 'predetermined', 'crossval', 'cv', 'index_predetermined'] = 'random'\n \"\"\"Method of splitting the data into train/val/test.\"\"\"\n split_sizes: Tuple[float, float, float] = (0.8, 0.1, 0.1)\n \"\"\"Split proportions for train/validation/test sets.\"\"\"\n num_folds: int = 1\n \"\"\"Number of folds when performing cross validation.\"\"\"\n folds_file: str = None\n \"\"\"Optional file of fold labels.\"\"\"\n val_fold_index: int = None\n \"\"\"Which fold to use as val for leave-one-out cross val.\"\"\"\n test_fold_index: int = None\n \"\"\"Which fold to use as test for leave-one-out cross val.\"\"\"\n crossval_index_dir: str = None\n \"\"\"Directory in which to find cross validation index files.\"\"\"\n crossval_index_file: str = None\n \"\"\"Indices of files to use as train/val/test. Overrides :code:`--num_folds` and :code:`--seed`.\"\"\"\n seed: int = 0\n \"\"\"\n Random seed to use when splitting data into train/val/test sets.\n When :code`num_folds > 1`, the first fold uses this seed and all subsequent folds add 1 to the seed.\n \"\"\"\n pytorch_seed: int = 0\n \"\"\"Seed for PyTorch randomness (e.g., random initial weights).\"\"\"\n metric: Metric = None\n \"\"\"\n Metric to use during evaluation. It is also used with the validation set for early stopping.\n Defaults to \"auc\" for classification and \"rmse\" for regression.\n \"\"\"\n extra_metrics: List[Metric] = []\n \"\"\"Additional metrics to use to evaluate the model. Not used for early stopping.\"\"\"\n save_dir: str = None\n \"\"\"Directory where model checkpoints will be saved.\"\"\"\n save_smiles_splits: bool = False\n \"\"\"Save smiles for each train/val/test splits for prediction convenience later.\"\"\"\n test: bool = False\n \"\"\"Whether to skip training and only test the model.\"\"\"\n quiet: bool = False\n \"\"\"Skip non-essential print statements.\"\"\"\n log_frequency: int = 10\n \"\"\"The number of batches between each logging of the training loss.\"\"\"\n show_individual_scores: bool = False\n \"\"\"Show all scores for individual targets, not just average, at the end.\"\"\"\n cache_cutoff: float = 10000\n \"\"\"\n Maximum number of molecules in dataset to allow caching.\n Below this number, caching is used and data loading is sequential.\n Above this number, caching is not used and data loading is parallel.\n Use \"inf\" to always cache.\n \"\"\"\n save_preds: bool = False\n \"\"\"Whether to save test split predictions during training.\"\"\"\n\n # Model arguments\n bias: bool = False\n \"\"\"Whether to add bias to linear layers.\"\"\"\n hidden_size: int = 300\n \"\"\"Dimensionality of hidden layers in MPN.\"\"\"\n depth: int = 3\n \"\"\"Number of message passing steps.\"\"\"\n mpn_shared: bool = False\n \"\"\"Whether to use the same message passing neural network for all input molecules\n Only relevant if :code:`number_of_molecules > 1`\"\"\"\n dropout: float = 0.0\n \"\"\"Dropout probability.\"\"\"\n activation: Literal['ReLU', 'LeakyReLU', 'PReLU', 'tanh', 'SELU', 'ELU'] = 'ReLU'\n \"\"\"Activation function.\"\"\"\n atom_messages: bool = False\n \"\"\"Centers messages on atoms instead of on bonds.\"\"\"\n undirected: bool = False\n \"\"\"Undirected edges (always sum the two relevant bond vectors).\"\"\"\n ffn_hidden_size: int = None\n \"\"\"Hidden dim for higher-capacity FFN (defaults to hidden_size).\"\"\"\n ffn_num_layers: int = 2\n \"\"\"Number of layers in FFN after MPN encoding.\"\"\"\n features_only: bool = False\n \"\"\"Use only the additional features in an FFN, no graph network.\"\"\"\n separate_val_features_path: List[str] = None\n \"\"\"Path to file with features for separate val set.\"\"\"\n separate_test_features_path: List[str] = None\n \"\"\"Path to file with features for separate test set.\"\"\"\n config_path: str = None\n \"\"\"\n Path to a :code:`.json` file containing arguments. Any arguments present in the config file\n will override arguments specified via the command line or by the defaults.\n \"\"\"\n ensemble_size: int = 1\n \"\"\"Number of models in ensemble.\"\"\"\n aggregation: Literal['mean', 'sum', 'norm'] = 'mean'\n \"\"\"Aggregation scheme for atomic vectors into molecular vectors\"\"\"\n aggregation_norm: int = 100\n \"\"\"For norm aggregation, number by which to divide summed up atomic features\"\"\"\n\n # Training arguments\n epochs: int = 30\n \"\"\"Number of epochs to run.\"\"\"\n warmup_epochs: float = 2.0\n \"\"\"\n Number of epochs during which learning rate increases linearly from :code:`init_lr` to :code:`max_lr`.\n Afterwards, learning rate decreases exponentially from :code:`max_lr` to :code:`final_lr`.\n \"\"\"\n init_lr: float = 1e-4\n \"\"\"Initial learning rate.\"\"\"\n max_lr: float = 1e-3\n \"\"\"Maximum learning rate.\"\"\"\n final_lr: float = 1e-4\n \"\"\"Final learning rate.\"\"\"\n grad_clip: float = None\n \"\"\"Maximum magnitude of gradient during training.\"\"\"\n class_balance: bool = False\n \"\"\"Trains with an equal number of positives and negatives in each batch.\"\"\"\n\n def __init__(self, *args, **kwargs) -> None:\n super(TrainArgs, self).__init__(*args, **kwargs)\n self._task_names = None\n self._crossval_index_sets = None\n self._task_names = None\n self._num_tasks = None\n self._features_size = None\n self._train_data_size = None\n\n @property\n def metrics(self) -> List[str]:\n \"\"\"The list of metrics used for evaluation. Only the first is used for early stopping.\"\"\"\n return [self.metric] + self.extra_metrics\n\n @property\n def minimize_score(self) -> bool:\n \"\"\"Whether the model should try to minimize the score metric or maximize it.\"\"\"\n return self.metric in {'rmse', 'mae', 'mse', 'cross_entropy', 'binary_cross_entropy'}\n\n @property\n def use_input_features(self) -> bool:\n \"\"\"Whether the model is using additional molecule-level features.\"\"\"\n return self.features_generator is not None or self.features_path is not None\n\n @property\n def num_lrs(self) -> int:\n \"\"\"The number of learning rates to use (currently hard-coded to 1).\"\"\"\n return 1\n\n @property\n def crossval_index_sets(self) -> List[List[List[int]]]:\n \"\"\"Index sets used for splitting data into train/validation/test during cross-validation\"\"\"\n return self._crossval_index_sets\n\n @property\n def task_names(self) -> List[str]:\n \"\"\"A list of names of the tasks being trained on.\"\"\"\n return self._task_names\n\n @task_names.setter\n def task_names(self, task_names: List[str]) -> None:\n self._task_names = task_names\n\n @property\n def num_tasks(self) -> int:\n \"\"\"The number of tasks being trained on.\"\"\"\n return len(self.task_names) if self.task_names is not None else 0\n\n @property\n def features_size(self) -> int:\n \"\"\"The dimensionality of the additional molecule-level features.\"\"\"\n return self._features_size\n\n @features_size.setter\n def features_size(self, features_size: int) -> None:\n self._features_size = features_size\n\n @property\n def train_data_size(self) -> int:\n \"\"\"The size of the training data set.\"\"\"\n return self._train_data_size\n\n @train_data_size.setter\n def train_data_size(self, train_data_size: int) -> None:\n self._train_data_size = train_data_size\n\n def process_args(self) -> None:\n super(TrainArgs, self).process_args()\n\n global temp_dir # Prevents the temporary directory from being deleted upon function return\n\n # Load config file\n if self.config_path is not None:\n with open(self.config_path) as f:\n config = json.load(f)\n for key, value in config.items():\n setattr(self, key, value)\n\n # Create temporary directory as save directory if not provided\n if self.save_dir is None:\n temp_dir = TemporaryDirectory()\n self.save_dir = temp_dir.name\n\n # Fix ensemble size if loading checkpoints\n if self.checkpoint_paths is not None and len(self.checkpoint_paths) > 0:\n self.ensemble_size = len(self.checkpoint_paths)\n\n # Process and validate metric and loss function\n if self.metric is None:\n if self.dataset_type == 'classification':\n self.metric = 'auc'\n elif self.dataset_type == 'multiclass':\n self.metric = 'cross_entropy'\n else:\n self.metric = 'rmse'\n\n if self.metric in self.extra_metrics:\n raise ValueError(f'Metric {self.metric} is both the metric and is in extra_metrics. '\n f'Please only include it once.')\n\n for metric in self.metrics:\n if not ((self.dataset_type == 'classification' and metric in ['auc', 'prc-auc', 'accuracy', 'binary_cross_entropy']) or\n (self.dataset_type == 'regression' and metric in ['rmse', 'mae', 'mse', 'r2']) or\n (self.dataset_type == 'multiclass' and metric in ['cross_entropy', 'accuracy'])):\n raise ValueError(f'Metric \"{metric}\" invalid for dataset type \"{self.dataset_type}\".')\n\n # Validate class balance\n if self.class_balance and self.dataset_type != 'classification':\n raise ValueError('Class balance can only be applied if the dataset type is classification.')\n\n # Validate features\n if self.features_only and not (self.features_generator or self.features_path):\n raise ValueError('When using features_only, a features_generator or features_path must be provided.')\n\n # Handle FFN hidden size\n if self.ffn_hidden_size is None:\n self.ffn_hidden_size = self.hidden_size\n\n # Handle MPN variants\n if self.atom_messages and self.undirected:\n raise ValueError('Undirected is unnecessary when using atom_messages '\n 'since atom_messages are by their nature undirected.')\n\n # Validate split type settings\n if not (self.split_type == 'predetermined') == (self.folds_file is not None) == (self.test_fold_index is not None):\n raise ValueError('When using predetermined split type, must provide folds_file and test_fold_index.')\n\n if not (self.split_type == 'crossval') == (self.crossval_index_dir is not None):\n raise ValueError('When using crossval split type, must provide crossval_index_dir.')\n\n if not (self.split_type in ['crossval', 'index_predetermined']) == (self.crossval_index_file is not None):\n raise ValueError('When using crossval or index_predetermined split type, must provide crossval_index_file.')\n\n if self.split_type in ['crossval', 'index_predetermined']:\n with open(self.crossval_index_file, 'rb') as rf:\n self._crossval_index_sets = pickle.load(rf)\n self.num_folds = len(self.crossval_index_sets)\n self.seed = 0\n\n # Test settings\n if self.test:\n self.epochs = 0\n\n\nclass PredictArgs(CommonArgs):\n \"\"\":class:`PredictArgs` includes :class:`CommonArgs` along with additional arguments used for predicting with a Chemprop model.\"\"\"\n\n test_path: str\n \"\"\"Path to CSV file containing testing data for which predictions will be made.\"\"\"\n preds_path: str\n \"\"\"Path to CSV file where predictions will be saved.\"\"\"\n as_featurizer: bool = False\n \"\"\"Use model to create fingerprint instead of predictions\"\"\"\n\n @property\n def ensemble_size(self) -> int:\n \"\"\"The number of models in the ensemble.\"\"\"\n return len(self.checkpoint_paths)\n\n def process_args(self) -> None:\n super(PredictArgs, self).process_args()\n\n if self.checkpoint_paths is None or len(self.checkpoint_paths) == 0:\n raise ValueError('Found no checkpoints. Must specify --checkpoint_path <path> or '\n '--checkpoint_dir <dir> containing at least one checkpoint.')\n\n\nclass InterpretArgs(CommonArgs):\n \"\"\":class:`InterpretArgs` includes :class:`CommonArgs` along with additional arguments used for interpreting a trained Chemprop model.\"\"\"\n\n data_path: str\n \"\"\"Path to data CSV file.\"\"\"\n batch_size: int = 500\n \"\"\"Batch size.\"\"\"\n property_id: int = 1\n \"\"\"Index of the property of interest in the trained model.\"\"\"\n rollout: int = 20\n \"\"\"Number of rollout steps.\"\"\"\n c_puct: float = 10.0\n \"\"\"Constant factor in MCTS.\"\"\"\n max_atoms: int = 20\n \"\"\"Maximum number of atoms in rationale.\"\"\"\n min_atoms: int = 8\n \"\"\"Minimum number of atoms in rationale.\"\"\"\n prop_delta: float = 0.5\n \"\"\"Minimum score to count as positive.\"\"\"\n\n def process_args(self) -> None:\n super(InterpretArgs, self).process_args()\n\n if self.features_path is not None:\n raise ValueError('Cannot use --features_path <path> for interpretation since features '\n 'need to be computed dynamically for molecular substructures. '\n 'Please specify --features_generator <generator>.')\n\n if self.checkpoint_paths is None or len(self.checkpoint_paths) == 0:\n raise ValueError('Found no checkpoints. Must specify --checkpoint_path <path> or '\n '--checkpoint_dir <dir> containing at least one checkpoint.')\n\n\nclass HyperoptArgs(TrainArgs):\n \"\"\":class:`HyperoptArgs` includes :class:`TrainArgs` along with additional arguments used for optimizing Chemprop hyperparameters.\"\"\"\n\n num_iters: int = 20\n \"\"\"Number of hyperparameter choices to try.\"\"\"\n config_save_path: str\n \"\"\"Path to :code:`.json` file where best hyperparameter settings will be written.\"\"\"\n log_dir: str = None\n \"\"\"(Optional) Path to a directory where all results of the hyperparameter optimization will be written.\"\"\"\n\n\nclass SklearnTrainArgs(TrainArgs):\n \"\"\":class:`SklearnTrainArgs` includes :class:`TrainArgs` along with additional arguments for training a scikit-learn model.\"\"\"\n\n model_type: Literal['random_forest', 'svm']\n \"\"\"scikit-learn model to use.\"\"\"\n class_weight: Literal['balanced'] = None\n \"\"\"How to weight classes (None means no class balance).\"\"\"\n single_task: bool = False\n \"\"\"Whether to run each task separately (needed when dataset has null entries).\"\"\"\n radius: int = 2\n \"\"\"Morgan fingerprint radius.\"\"\"\n num_bits: int = 2048\n \"\"\"Number of bits in morgan fingerprint.\"\"\"\n num_trees: int = 500\n \"\"\"Number of random forest trees.\"\"\"\n\n\nclass SklearnPredictArgs(Tap):\n \"\"\":class:`SklearnPredictArgs` contains arguments used for predicting with a trained scikit-learn model.\"\"\"\n\n test_path: str\n \"\"\"Path to CSV file containing testing data for which predictions will be made.\"\"\"\n smiles_columns: List[str] = None\n \"\"\"List of names of the columns containing SMILES strings. \n By default, uses the first :code:`number_of_molecules` columns.\"\"\"\n number_of_molecules: int = 1\n \"\"\"Number of molecules in each input to the model.\n This must equal the length of :code:`smiles_column` (if not :code:`None`).\"\"\"\n preds_path: str\n \"\"\"Path to CSV file where predictions will be saved.\"\"\"\n checkpoint_dir: str = None\n \"\"\"Path to directory containing model checkpoints (:code:`.pkl` file)\"\"\"\n checkpoint_path: str = None\n \"\"\"Path to model checkpoint (:code:`.pkl` file)\"\"\"\n checkpoint_paths: List[str] = None\n \"\"\"List of paths to model checkpoints (:code:`.pkl` files)\"\"\"\n\n def process_args(self) -> None:\n\n if self.smiles_columns is None:\n self.smiles_columns = [None] * self.number_of_molecules\n elif len(self.smiles_columns) != self.number_of_molecules:\n raise ValueError('Length of smiles_columns must match number_of_molecules.')\n\n # Load checkpoint paths\n self.checkpoint_paths = get_checkpoint_paths(\n checkpoint_path=self.checkpoint_path,\n checkpoint_paths=self.checkpoint_paths,\n checkpoint_dir=self.checkpoint_dir,\n ext='.pkl'\n )\n"
]
| [
[
"torch.device",
"torch.cuda.is_available",
"torch.cuda.device_count"
]
]
|
lyronctk/quant-noisier-speech | [
"cf47a0f1542e51b1ad7c3d43e0266c3592a222f9"
]
| [
"src/models/tasks.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass TaskTypePredictor(nn.Module):\n\n def __init__(self, input_dim, task_type_num_classes):\n super().__init__()\n self.task_fc = nn.Linear(input_dim, task_type_num_classes)\n self.task_type_num_classes = task_type_num_classes\n\n def forward(self, inputs):\n task_logits = self.task_fc(inputs)\n task_log_probs = F.log_softmax(task_logits, dim=1)\n return task_log_probs\n \n def get_loss(self, log_probs, targets):\n return F.nll_loss(log_probs, targets)\n\n\nclass DialogActsPredictor(nn.Module):\n\n def __init__(self, input_dim, num_dialog_acts):\n super().__init__()\n self.dialogacts_fc = nn.Linear(input_dim, num_dialog_acts)\n self.num_dialog_acts = num_dialog_acts\n\n def forward(self, inputs):\n dialogacts_logits = self.dialogacts_fc(inputs)\n # one person can have multiple dialog actions\n dialogacts_probs = torch.sigmoid(dialogacts_logits)\n return dialogacts_probs\n\n def get_loss(self, probs, targets):\n # probs : batch_size x num_dialog_acts\n # targets : batch_size x num_dialog_acts\n return F.binary_cross_entropy(probs.view(-1), targets.view(-1).float())\n\n\nclass SentimentPredictor(nn.Module):\n\n def __init__(self, input_dim, sentiment_num_classes):\n super().__init__()\n self.sentiment_fc = nn.Linear(input_dim, sentiment_num_classes)\n self.sentiment_num_classes = sentiment_num_classes\n\n def forward(self, inputs):\n sentiment_logits = self.sentiment_fc(inputs)\n sentiment_log_probs = F.log_softmax(sentiment_logits, dim=1)\n return sentiment_log_probs\n\n def get_loss(self, pred_log_probs, target_probs):\n # pred_logits : batch_size x num_sentiment_class\n # target_logits : batch_size x num_sentiment_class\n xentropy = -torch.sum(target_probs * pred_log_probs, dim=1)\n return torch.mean(xentropy)\n\n\nclass SpeakerIdPredictor(nn.Module):\n\n def __init__(self, input_dim, num_speaker_ids):\n super().__init__()\n self.speaker_id_fc = nn.Linear(input_dim, num_speaker_ids)\n self.num_speaker_ids = num_speaker_ids\n\n def forward(self, inputs):\n speaker_id_logits = self.speaker_id_fc(inputs)\n speaker_id_log_probs = F.log_softmax(speaker_id_logits, dim=1)\n return speaker_id_log_probs\n\n def get_loss(self, log_probs, targets):\n return F.nll_loss(log_probs, targets)\n"
]
| [
[
"torch.nn.Linear",
"torch.sigmoid",
"torch.nn.functional.log_softmax",
"torch.nn.functional.nll_loss",
"torch.mean",
"torch.sum"
]
]
|
victor-axelsson/SimAPI | [
"0d4511ae75d35f10a5ca2b9feb41af193cce9639"
]
| [
"helpers/cache/cache.py"
]
| [
"\"\"\"\nThe MIT License (MIT)\nCopyright (c) 2018 Victor Axelsson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER D\n\"\"\" \n\nimport pickle\nimport os.path\nimport numpy as np\n\nclass Cache: \n\n\tdef pickleIt(self, variable, name):\n\t\tpickle.dump(variable, open( name, \"wb\" ))\n\n\tdef loadPickle(self, name):\n\t\treturn pickle.load(open( name, \"rb\" ))\n\n\tdef loadIfExists(self, name):\n\t\tif os.path.isfile(name):\n\t\t\treturn self.loadPickle(name), True\n\t\telse:\n\t\t\treturn None, False\n\n\tdef loadNPIfExists(self, name):\n\t\tif os.path.isfile(name):\n\t\t\treturn np.load(name), True\n\t\telse:\n\t\t\treturn None, False\n\n\tdef lazyCache(self, name, callable, args=None):\n\t\tif os.path.isfile(name):\n\t\t\treturn self.loadPickle(name), True\n\t\telse:\n\t\t\tdata = callable(**args)\n\t\t\tself.pickleIt(data, name)\n\t\t\treturn data, False\n"
]
| [
[
"numpy.load"
]
]
|
ydlstartx/gluon-cv | [
"0645707fdc4d90210b216ec8b023e2c4e4332a5c"
]
| [
"scripts/tracking/test.py"
]
| [
"\"\"\" SiamRPN test\nCode adapted from https://github.com/STVIR/pysot\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport argparse\nimport os\nimport numpy as np\nimport mxnet as mx\nfrom gluoncv.model_zoo.siamrpn.siamrpn_tracker import SiamRPNTracker as build_tracker\nfrom gluoncv.data.otb.tracking import OTBTracking as OTBDataset\nfrom gluoncv.model_zoo.siamrpn.siamrpn_tracker import get_axis_aligned_bbox\nfrom gluoncv.model_zoo import get_model\nfrom gluoncv.utils.filesystem import try_import_cv2\n\ndef parse_args():\n \"\"\"parameter test.\"\"\"\n parser = argparse.ArgumentParser(description='siamrpn tracking test result')\n parser.add_argument('--dataset', default='OTB2015', type=str, help='dataset name')\n parser.add_argument('--dataset_root', type=str, default='~/.mxnet/datasets/OTB2015',\n help='dataset_root')\n parser.add_argument('--model_path', type=str, help='path of models to eval')\n parser.add_argument('--results_path', type=str, help='results path')\n parser.add_argument('--video', default='', type=str,\n help='eval one special video')\n parser.add_argument('--vis', action='store_true',\n help='whether visualzie result')\n parser.add_argument('--mode', type=str, default='hybrid',\n help='mode in which to train the model.options are symbolic, hybrid')\n parser.add_argument('--num_gpus', type=int, default=0,\n help='number of gpus to use.')\n parser.add_argument('--model_name', type=str, default='siamrpn_alexnet_v2_otb',\n help='name of model.')\n parser.add_argument('--batch-size', type=int, default=32,\n help='training batch size per device (CPU/GPU).')\n parser.add_argument('--num_workers', default=4, type=int,\n help='number of preprocessing workers')\n parser.add_argument('--pretrained', action='store_true', default='True',\n help='enable using pretrained model from gluon.')\n opt = parser.parse_args()\n return opt\ndef main():\n \"\"\"SiamRPN test.\n\n function\n ----------\n record the output of the model. The output information of each video is recorded in the txt\n corresponding to the video name.\n if you want to evaluation, you need to python benchmark.py according to txt of text result.\n Currently only supports test OTB 2015 dataset\n\n Parameters\n ----------\n dataset_root : str, default '~/mxnet/datasets/OTB2015'\n Path to folder test the dataset.\n model_path : str, Path of test model .\n results_path: str, Path to store txt of test reslut .\n \"\"\"\n opt = parse_args()\n if opt.use_gpu:\n ctx = mx.gpu()\n else:\n ctx = mx.cpu()\n # dataloader\n dataset = OTBDataset(name=opt.dataset, dataset_root=opt.dataset_root, load_img=False)\n net = get_model(opt.model_name, pretrained=True)\n net.collect_params().reset_ctx(ctx)\n if opt.mode == 'hybrid':\n net.hybridize(static_alloc=True, static_shape=True)\n if not opt.model_path:\n net.load_parameters(opt.model_path, ctx=ctx)\n print('Pre-trained model %s is successfully loaded.' % (opt.model_path))\n else:\n print('Pre-trained model is successfully loaded from the model zoo.')\n # bulid tracker\n tracker = build_tracker(net)\n # record the output of the model.\n test(dataset, tracker, opt, ctx)\n\ndef test(dataset, tracker, opt, ctx):\n \"\"\"SiamRPN test.\"\"\"\n cv2 = try_import_cv2()\n for v_idx, video in enumerate(dataset):\n if opt.video != '':\n if video.name != opt.video:\n continue\n toc = 0\n pred_bboxes = []\n scores = []\n track_times = []\n for idx, (img, gt_bbox) in enumerate(video):\n tic = cv2.getTickCount()\n if idx == 0:\n x_max, y_max, gt_w, gt_t = get_axis_aligned_bbox(np.array(gt_bbox))\n gt_bbox_ = [x_max-(gt_w-1)/2, y_max-(gt_t-1)/2, gt_w, gt_t]\n tracker.init(img, gt_bbox_, ctx)\n pred_bbox = gt_bbox_\n scores.append(None)\n pred_bboxes.append(pred_bbox)\n else:\n outputs = tracker.track(img, ctx)\n pred_bbox = outputs['bbox']\n pred_bboxes.append(pred_bbox)\n scores.append(outputs['best_score'])\n toc += cv2.getTickCount() - tic\n track_times.append((cv2.getTickCount() - tic)/cv2.getTickFrequency())\n if idx == 0:\n cv2.destroyAllWindows()\n if opt.vis and idx > 0:\n gt_bbox = list(map(int, gt_bbox))\n pred_bbox = list(map(int, pred_bbox))\n cv2.rectangle(img, (gt_bbox[0], gt_bbox[1]),\n (gt_bbox[0]+gt_bbox[2], gt_bbox[1]+gt_bbox[3]),\n (0, 255, 0), 3)\n cv2.rectangle(img, (pred_bbox[0], pred_bbox[1]),\n (pred_bbox[0]+pred_bbox[2], pred_bbox[1]+pred_bbox[3]),\n (0, 255, 255), 3)\n cv2.putText(img, str(idx), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)\n cv2.imshow(video.name, img)\n cv2.waitKey(1)\n toc /= cv2.getTickFrequency()\n model_path = os.path.join(opt.results_path, opt.dataset,\n opt.model_path.split('/')[-1].split('.')[0])\n if not os.path.isdir(model_path):\n os.makedirs(model_path)\n with open(os.path.join(model_path, '{}.txt'.format(video.name)), 'w') as f_w:\n for per_pbbox in pred_bboxes:\n f_w.write(','.join([str(i) for i in per_pbbox])+'\\n')\n print('({:3d}) Video: {:12s} Time: {:5.1f}s Speed: {:3.1f}fps'.format\n (v_idx+1, video.name, toc, len(video) / toc))\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"numpy.array"
]
]
|
nunorc/astromlp-models | [
"32356d50f9aa45c123df51cdaffb5547c4791248"
]
| [
"f2r/train.py"
]
| [
"\nimport sys, os\nimport tensorflow as tf\nimport mlflow.keras\n\nfrom astromlp.sdss.helper import Helper\nfrom astromlp.sdss.utils import train_val_test_split, history_fit_plots, my_callbacks\nfrom astromlp.sdss.datagen import DataGen\n\nimport f2r\n\nmlflow.tensorflow.autolog(log_models=False)\nmlflow.set_tag('model', 'f2r')\n\nepochs = 20\nbatch_size = 64\nloss = 'mse'\noptimizer = 'adam'\nds = '../../sdss-gs'\n\nif len(sys.argv)>1:\n epochs = int(sys.argv[1])\n batch_size = int(sys.argv[2])\n loss = sys.argv[3]\n optimizer = sys.argv[4]\n ds = sys.argv[5]\n\n# data helper for sdss-gs\nhelper = Helper(ds=ds)\n\n# optimizers\nopt = tf.keras.optimizers.Adam()\nif optimizer == 'rmsprop':\n opt = tf.keras.optimizers.RMSprop()\n\n# ids and datagens\nids = helper.ids_list(has_fits=True)\nids_train, ids_val, ids_test = train_val_test_split(ids)\ntrain_gen = DataGen(ids_train, x=['fits'], y=['redshift'], batch_size=batch_size, helper=helper)\nval_gen = DataGen(ids_val, x=['fits'], y=['redshift'], batch_size=batch_size, helper=helper)\ntest_gen = DataGen(ids_test, x=['fits'], y=['redshift'], batch_size=batch_size, helper=helper)\nmlflow.log_param('dataset_size', len(ids))\n\n# model, compile and fit\nmodel = f2r.model()\nmodel.compile(optimizer=opt, loss=loss, metrics=['mean_squared_error', 'mean_absolute_error'])\nhistory = model.fit(train_gen, validation_data=val_gen,\n epochs=epochs, batch_size=batch_size,\n callbacks=my_callbacks(), verbose=1)\n\n# evaluate\nscore = model.evaluate(test_gen, batch_size=batch_size, return_dict=True)\n\n# save model\nmodel.save('../model_store/f2r')\n\n# save history plots\nhistory_fit_plots(model.name, history, base_dir='../model_plots')\n\n"
]
| [
[
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.optimizers.RMSprop"
]
]
|
xujun05/nzl | [
"6633777b901359bb053d46ea920281da016b9bf4"
]
| [
"zipline/examples/buy_and_hold.py"
]
| [
"#!/usr/bin/env python\n#\n# Copyright 2015 Quantopian, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom zipline.api import order, symbol\nfrom zipline.finance import commission\n\nstocks = ['AAPL', 'MSFT']\n\n\ndef initialize(context):\n context.has_ordered = False\n context.stocks = stocks\n\n # Explicitly set the commission to the \"old\" value until we can\n # rebuild example data.\n # github.com/quantopian/zipline/blob/master/tests/resources/\n # rebuild_example_data#L105\n context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))\n\n\ndef handle_data(context, data):\n if not context.has_ordered:\n for stock in context.stocks:\n order(symbol(stock), 100)\n context.has_ordered = True\n\n\ndef _test_args():\n \"\"\"Extra arguments to use when zipline's automated tests run this example.\n \"\"\"\n import pandas as pd\n\n return {\n 'start': pd.Timestamp('2008', tz='utc'),\n 'end': pd.Timestamp('2013', tz='utc'),\n }\n"
]
| [
[
"pandas.Timestamp"
]
]
|
jozef-piechaczek/github-roles-miner | [
"959053eca402fef8c8ef964e86dd1304ea192748"
]
| [
"step4_model/src/tasks.py"
]
| [
"import itertools\nfrom threading import Thread\n\nfrom sklearn.multioutput import ClassifierChain\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom data import *\nfrom utils import *\n\n\n# RQ.1: How accurate are machine learning classifiers in identifying technical roles?\n\n\n# noinspection DuplicatedCode\ndef task1():\n run_classification(X, Y)\n\ndef run_classification(_x, _y):\n def classify_in_thread(name, thread_id, results, clf):\n log(f\"Begin of {name}\")\n scores, folds = classify(_x, _y, skf, clf, average=\"micro\", name=name)\n results[thread_id] = (name, scores, folds)\n log(f\"End of {name}\")\n\n _results = [None] * 4\n\n _threads = [\n Thread(target=classify_in_thread, args=(\"Random Forest\", 0, _results, rf_clf)),\n Thread(target=classify_in_thread, args=(\"Native Bayes\", 1, _results, nb_clf)),\n Thread(target=classify_in_thread, args=(\"Baseline\", 2, _results, baseline_clf)),\n Thread(target=classify_in_thread, args=(\"GradientBoost\", 3, _results, gb_clf))\n ]\n\n for t in _threads:\n t.start()\n\n for t in _threads:\n t.join()\n\n for r in _results:\n if r is not None:\n print(f\"******** {r[0]} ********\")\n classify_report(r[1], _y.columns)\n\n\n# RQ.2: What are the most relevant features to identify technical roles?\n\n\ndef task2():\n var_imp = feature_importances_rank(X, Y, clone(rf))\n\n var_imp[\"order\"] = var_imp.groupby(\"role\").rank(\n method=\"first\", ascending=False)\n var_imp[var_imp.category == \"Dependency\"].groupby(\"role\").tail(10)\n\n p = top_10_features(var_imp)\n ggsave(plot=p, filename=\"ex2 wykres top 10\", path=PLOTS_OUT)\n\n for r in Y.columns:\n features_df = build_histogram_data(X, Y, var_imp, r)\n p = plot_histogram_data(features_df, r)\n ggsave(plot=p, filename=\"ex2 wykres - \" + r, path=PLOTS_OUT)\n\n\n# RQ.3: Do technical roles influence each other during classification?\n\ndef task3():\n Y_rq3 = Y.loc[:, :]\n permutations = itertools.permutations(range(0, Y_rq3.shape[1]))\n\n iterations = []\n for i, p in enumerate(permutations, start=1):\n p = list(p)\n order = np.array(Y_rq3.columns.tolist())[p]\n print(f\"============= {order} =============\", flush=True)\n\n chain_clf = ClassifierChain(rf, order=list(p), random_state=SEED)\n cc_scores, _ = classify(X, Y_rq3, skf, chain_clf, average=\"micro\")\n classify_report(cc_scores, Y_rq3)\n\n iteration = {i: r for i, r in enumerate(order)}\n iteration.update({\n \"index\": i,\n \"precision\": cc_scores[\"precision\"],\n \"recall\": cc_scores[\"recall\"],\n \"f1\": cc_scores[\"f1\"],\n \"auc\": cc_scores[\"auc\"],\n \"jaccard\": cc_scores[\"jaccard\"],\n \"hamming_loss\": cc_scores[\"hamming_loss\"]\n })\n for role in list(Y_rq3.columns):\n iteration.update({\n f\"precision_{role}\": cc_scores[f\"precision_{role}\"],\n f\"recall_{role}\": cc_scores[f\"recall_{role}\"],\n f\"f1_{role}\": cc_scores[f\"f1_{role}\"],\n })\n iterations.append(iteration)\n\n br_scores, br_folds = classify(X, Y, skf, rf_clf, average=\"micro\")\n cc_dataset = build_cc_data(iterations, br_scores)\n\n cc_general = cc_dataset[np.any([\n cc_dataset.metric == \"Precision\",\n cc_dataset.metric == \"Recall\",\n cc_dataset.metric == \"F1\",\n cc_dataset.metric == \"AUC\",\n cc_dataset.metric == \"Jaccard\",\n cc_dataset.metric == \"Hamming Loss\"\n ], axis=0)]\n\n cc_by_role = cc_dataset[np.any([\n cc_dataset.metric.str.contains(\"Backend\"),\n cc_dataset.metric.str.contains(\"Frontend\"),\n cc_dataset.metric.str.contains(\"Mobile\"),\n cc_dataset.metric.str.contains(\"DevOps\"),\n cc_dataset.metric.str.contains(\"DataScientist\")\n ], axis=0)]\n\n p = (ggplot(cc_general, aes(x=\"index\", y=\"value\"))\n + geom_line()\n + geom_hline(yintercept=0, linetype=\"dashed\")\n + facet_wrap(\"~ metric\", ncol=2)\n + labs(x=\"Classifier Chains permutations\", y=\"Metric value\")\n + theme_bw())\n ggsave(plot=p, filename=\"ex3 wykres 1\", path=PLOTS_OUT)\n\n p = (ggplot(cc_by_role, aes(x=\"index\", y=\"value\"))\n + geom_line()\n + geom_hline(yintercept=0, linetype=\"dashed\")\n + facet_wrap(\"~ metric\", ncol=3)\n + labs(x=\"Classifier Chains permutations\", y=\"Metric value\")\n + theme_bw())\n ggsave(plot=p, filename=\"ex3 wykres 2\", path=PLOTS_OUT)\n\n\n# RQ.4 How effectively can we identify full-stack developers?\n\ndef task4():\n run_classification(X_fs, Y_fs)\n\n #****** FullStack - bez uwzględnienia Backend i Frontend *****\n #******** Random Forest ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.40 0.02 0.03 0.07 362\n #Frontend 0.85 0.53 0.65 0.56 743\n #Mobile 0.83 0.28 0.42 0.44 388\n #DevOps 0.67 0.06 0.11 0.19 133\n #DataScientist 0.92 0.60 0.72 0.73 186\n #FullStack 0.86 0.62 0.72 0.60 972\n #\n #Total: 0.86 0.44 0.58 0.43\n #AUC: 0.73\n #Jaccard: 0.41\n #Hamming Loss: 0.13\n\n #******** Native Bayes ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.23 0.23 0.22 0.09 362\n #Frontend 0.44 0.84 0.58 0.33 743\n #Mobile 0.28 0.63 0.39 0.24 388\n #DevOps 0.14 0.54 0.22 0.19 133\n #DataScientist 0.40 0.85 0.54 0.53 186\n #FullStack 0.47 0.64 0.55 0.14 972\n #\n #Total: 0.37 0.65 0.47 0.25\n #AUC: 0.52\n #Jaccard: 0.31\n #Hamming Loss: 0.29\n\n #******** Baseline ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.17 0.16 0.17 0.02 362\n #Frontend 0.34 0.32 0.32 0.03 743\n #Mobile 0.17 0.16 0.16 0.00 388\n #DevOps 0.05 0.04 0.04 -0.01 133\n #DataScientist 0.09 0.07 0.08 0.01 186\n #FullStack 0.46 0.46 0.46 0.08 972\n #\n #Total: 0.31 0.30 0.30 0.02\n #AUC: 0.37\n #Jaccard: 0.18\n #Hamming Loss: 0.27\n\n #******** GradientBoost ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.55 0.11 0.18 0.20 362\n #Frontend 0.80 0.58 0.67 0.57 743\n #Mobile 0.78 0.39 0.52 0.49 388\n #DevOps 0.58 0.25 0.34 0.35 133\n #DataScientist 0.84 0.69 0.76 0.74 186\n #FullStack 0.87 0.64 0.74 0.61 972\n #\n #Total: 0.82 0.51 0.62 0.49\n #AUC: 0.74\n #Jaccard: 0.45\n #Hamming Loss: 0.12\n\n\n fs_roles = [\"Backend\", \"Frontend\"]\n Y_fs.loc[Y_fs.FullStack == 1, fs_roles] = 1\n\n run_classification(X_fs, Y_fs)\n\n #******** Random Forest ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.74 0.79 0.76 0.46 1265\n #Frontend 0.81 0.94 0.87 0.52 1617\n #Mobile 0.83 0.28 0.42 0.44 388\n #DevOps 0.67 0.06 0.11 0.19 133\n #DataScientist 0.92 0.60 0.72 0.73 186\n #FullStack 0.86 0.62 0.72 0.60 972\n #\n #Total: 0.80 0.73 0.77 0.49\n #AUC: 0.86\n #Jaccard: 0.62\n #Hamming Loss: 0.15\n\n #******** Native Bayes ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.62 0.50 0.55 0.14 1265\n #Frontend 0.82 0.84 0.83 0.42 1617\n #Mobile 0.28 0.63 0.39 0.24 388\n #DevOps 0.14 0.54 0.22 0.19 133\n #DataScientist 0.40 0.85 0.54 0.53 186\n #FullStack 0.47 0.64 0.55 0.14 972\n #\n #Total: 0.53 0.68 0.60 0.28\n #AUC: 0.64\n #Jaccard: 0.43\n #Hamming Loss: 0.30\n\n #******** Baseline ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.50 0.52 0.51 -0.08 1265\n #Frontend 0.69 0.71 0.70 0.00 1617\n #Mobile 0.17 0.16 0.16 0.00 388\n #DevOps 0.05 0.04 0.04 -0.01 133\n #DataScientist 0.09 0.07 0.08 0.01 186\n #FullStack 0.46 0.46 0.46 0.08 972\n #\n #Total: 0.51 0.51 0.51 -0.00\n #AUC: 0.59\n #Jaccard: 0.34\n #Hamming Loss: 0.32\n\n #******** GradientBoost ********\n #Role Precision Recall F1 MCC Support\n #Backend 0.79 0.71 0.75 0.48 1265\n #Frontend 0.83 0.91 0.87 0.54 1617\n #Mobile 0.77 0.39 0.52 0.49 388\n #DevOps 0.62 0.24 0.32 0.35 133\n #DataScientist 0.82 0.68 0.74 0.73 186\n #FullStack 0.87 0.65 0.74 0.62 972\n #\n #Total: 0.82 0.73 0.77 0.53\n #AUC: 0.88\n #Jaccard: 0.63\n #Hamming Loss: 0.14\n\n\n\n\ndef task5():\n # ******** Nearest Neighbors ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.33 0.13 0.18 0.07 362\n # Frontend 0.64 0.75 0.69 0.37 743\n # Mobile 0.53 0.27 0.36 0.25 388\n # DevOps 0.38 0.05 0.09 0.12 133\n # DataScientist 0.73 0.43 0.53 0.51 186\n #\n # Total: 0.59 0.44 0.50 0.26\n # AUC: 0.53\n # Jaccard: 0.34\n # Hamming Loss: 0.20\n # ******** Tuned(F1) Nearest Neighbors ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.34 0.05 0.09 0.06 362\n # Frontend 0.65 0.81 0.72 0.43 743\n # Mobile 0.64 0.23 0.33 0.28 388\n # DevOps 0.30 0.02 0.04 0.07 133\n # DataScientist 0.83 0.37 0.50 0.52 186\n #\n # Total: 0.65 0.43 0.52 0.27\n # AUC: 0.56\n # Jaccard: 0.35\n # Hamming Loss: 0.19\n # ******** Tuned(MCC) Nearest Neighbors ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.31 0.10 0.15 0.06 362\n # Frontend 0.65 0.78 0.71 0.41 743\n # Mobile 0.59 0.27 0.36 0.28 388\n # DevOps 0.45 0.04 0.07 0.12 133\n # DataScientist 0.79 0.43 0.54 0.54 186\n #\n # Total: 0.62 0.44 0.52 0.28\n # AUC: 0.55\n # Jaccard: 0.35\n # Hamming Loss: 0.19\n # ******** Neural Network ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.39 0.29 0.32 0.17 362\n # Frontend 0.74 0.78 0.75 0.53 743\n # Mobile 0.60 0.49 0.53 0.41 388\n # DevOps 0.40 0.25 0.30 0.27 133\n # DataScientist 0.76 0.64 0.68 0.65 186\n #\n # Total: 0.64 0.56 0.59 0.41\n # AUC: 0.56\n # Jaccard: 0.42\n # Hamming Loss: 0.18\n # ******** Tuned(F1) Neural Network ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.40 0.23 0.29 0.16 362\n # Frontend 0.74 0.75 0.74 0.51 743\n # Mobile 0.71 0.46 0.55 0.47 388\n # DevOps 0.54 0.21 0.28 0.28 133\n # DataScientist 0.81 0.64 0.72 0.69 186\n #\n # Total: 0.68 0.53 0.60 0.42\n # AUC: 0.64\n # Jaccard: 0.43\n # Hamming Loss: 0.17\n # ******** Tuned(MCC) Neural Network ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.43 0.30 0.35 0.20 362\n # Frontend 0.74 0.74 0.74 0.51 743\n # Mobile 0.61 0.50 0.54 0.42 388\n # DevOps 0.52 0.27 0.34 0.33 133\n # DataScientist 0.84 0.68 0.74 0.72 186\n #\n # Total: 0.66 0.56 0.60 0.44\n # AUC: 0.63\n # Jaccard: 0.43\n # Hamming Loss: 0.17\n # ******** Random Forest ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.53 0.08 0.13 0.13 362\n # Frontend 0.75 0.79 0.77 0.55 743\n # Mobile 0.85 0.38 0.53 0.49 388\n # DevOps 0.67 0.09 0.15 0.22 133\n # DataScientist 0.89 0.67 0.76 0.74 186\n #\n # Total: 0.77 0.49 0.60 0.43\n # AUC: 0.72\n # Jaccard: 0.43\n # Hamming Loss: 0.15\n # ******** Publication Random Forest ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.55 0.07 0.12 0.14 362\n # Frontend 0.74 0.81 0.77 0.56 743\n # Mobile 0.86 0.40 0.54 0.51 388\n # DevOps 0.55 0.09 0.14 0.20 133\n # DataScientist 0.90 0.67 0.76 0.75 186\n #\n # Total: 0.78 0.50 0.61 0.43\n # AUC: 0.73\n # Jaccard: 0.44\n # Hamming Loss: 0.15\n # ******** Tuned(F1) Random Forest ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.41 0.43 0.42 0.24 362\n # Frontend 0.76 0.81 0.78 0.58 743\n # Mobile 0.65 0.62 0.63 0.52 388\n # DevOps 0.52 0.46 0.47 0.44 133\n # DataScientist 0.73 0.80 0.76 0.73 186\n #\n # Total: 0.65 0.67 0.66 0.50\n # AUC: 0.73\n # Jaccard: 0.49\n # Hamming Loss: 0.16\n # ******** Tuned(MCC) Random Forest ********\n # Role Precision Recall F1 MCC Support\n # Backend 0.50 0.33 0.39 0.27 362\n # Frontend 0.77 0.80 0.78 0.58 743\n # Mobile 0.72 0.58 0.64 0.55 388\n # DevOps 0.69 0.29 0.39 0.40 133\n # DataScientist 0.78 0.77 0.77 0.74 186\n #\n # Total: 0.71 0.62 0.66 0.51\n # AUC: 0.74\n # Jaccard: 0.50\n # Hamming Loss: 0.15\n \n\n names = [\n \"Nearest Neighbors\",\n \"Tuned(F1) Nearest Neighbors\",\n \"Tuned(MCC) Nearest Neighbors\",\n \"Neural Network\",\n \"Tuned(F1) Neural Network\",\n \"Tuned(MCC) Neural Network\",\n \"Random Forest\",\n \"Publication Random Forest\",\n \"Tuned(F1) Random Forest\",\n \"Tuned(MCC) Random Forest\",\n ]\n\n classifiers = [\n KNeighborsClassifier(n_jobs=-1),\n KNeighborsClassifier(p=2, n_neighbors=14, weights=\"distance\", n_jobs=-1),\n KNeighborsClassifier(p=2, n_neighbors=8, weights=\"distance\", leaf_size=20, n_jobs=-1),\n MLPClassifier(random_state=SEED),\n MLPClassifier(random_state=SEED, alpha=0.05, learning_rate_init=0.001, activation=\"logistic\",\n hidden_layer_sizes=(25,)),\n MLPClassifier(random_state=SEED, solver='adam', learning_rate='constant', hidden_layer_sizes=(30, 10),\n alpha=1e-04, activation=\"logistic\", max_iter=200, ),\n RandomForestClassifier(random_state=SEED, n_jobs=-1),\n RandomForestClassifier(random_state=SEED, n_jobs=-1, n_estimators=500),\n RandomForestClassifier(random_state=SEED, n_jobs=-1, bootstrap=False, class_weight='balanced',\n criterion='entropy', max_depth=11, max_features=0.1, max_leaf_nodes=33,\n min_samples_leaf=4, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=980,\n oob_score=False, warm_start=False),\n RandomForestClassifier(random_state=SEED, n_jobs=-1, bootstrap=False, class_weight='balanced',\n criterion='entropy', max_depth=None, max_features=0.1, max_leaf_nodes=110,\n max_samples=None, min_samples_leaf=3, min_samples_split=2, min_weight_fraction_leaf=0.0,\n n_estimators=1000, oob_score=False, warm_start=False)\n ]\n\n classifiers = map(lambda c: OneVsRestClassifier(c), classifiers)\n\n for name, clf in zip(names, classifiers):\n scores, _ = classify(X, Y, skf, clf, average=\"micro\", name=name)\n\n print(f\"******** {name} ********\")\n classify_report(scores, Y.columns)\n\n\ndef tuning():\n # best score: 0.2784\n # best param: {'estimator__weights': 'distance', 'estimator__p': 2, 'estimator__n_neighbors': 8,\n # 'estimator__leaf_size': 20, 'estimator__algorithm': 'auto'}\n\n clf = OneVsRestClassifier(KNeighborsClassifier(n_jobs=-1))\n NN_grid = {\n \"estimator__weights\": [\"distance\"],\n \"estimator__n_neighbors\": [8],\n \"estimator__algorithm\": [\"auto\"],\n \"estimator__p\": [2],\n \"estimator__leaf_size\": [10, 20, 30, 40, 70]\n }\n #optimize_for_random(\"Nearest Neighbors\", X, Y, clf, skf, NN_grid, mcc_ave_scorer(), 400, SEED)\n optimize_for_grid(\"Nearest Neighbors\", X, Y, clf, skf, NN_grid, mcc_ave_scorer())\n\n # best score: 0.4435\n # best param: {'estimator__solver': 'adam', 'estimator__max_iter': 200, 'estimator__learning_rate': 'constant',\n # 'estimator__hidden_layer_sizes': (30,15), 'estimator__alpha': 0.0001, 'estimator__activation': 'logistic'}\n\n clf = OneVsRestClassifier(MLPClassifier(random_state=SEED))\n MLP_grid = {\n 'estimator__hidden_layer_sizes': [(20,), (100,), (30, 15,)],\n 'estimator__activation': ['identity', 'logistic', 'tanh', 'relu'],\n 'estimator__solver': ['adam'],\n 'estimator__alpha': [0.0001],\n 'estimator__learning_rate': ['constant', 'adaptive', 'invscaling'],\n 'estimator__max_iter': [150, 200, 250, 300],\n }\n optimize_for_random(\"Neural Network\", X, Y, clf, skf, MLP_grid, mcc_ave_scorer(), 50, SEED)\n #optimize_for_grid(\"Neural Network\", X, Y, clf, skf, MLP_grid, mcc_ave_scorer())\n\n # best score: 0.5083\n # best param: {'estimator__bootstrap': False, 'estimator__class_weight': 'balanced', 'estimator__criterion': 'entropy',\n # 'estimator__max_depth': None, 'estimator__max_features': 0.1, 'estimator__max_leaf_nodes': 110,\n # 'estimator__min_samples_leaf': 3, 'estimator__min_samples_split': 2,\n # 'estimator__min_weight_fraction_leaf': 0.0, 'estimator__n_estimators': 1000}\n\n clf = OneVsRestClassifier(RandomForestClassifier(random_state=SEED, n_jobs=-1))\n RF_grid = {\n 'estimator__class_weight': ['balanced'],\n 'estimator__criterion': ['entropy'],\n 'estimator__bootstrap': [False],\n 'estimator__max_features': ['auto', 0.1],\n 'estimator__max_depth': [None, 9, 11, 13, 15],\n 'estimator__max_leaf_nodes': [30, 110, 130],\n 'estimator__min_samples_leaf': [2, 3, 4],\n 'estimator__min_samples_split': [2],\n 'estimator__min_weight_fraction_leaf': [0.0],\n 'estimator__n_estimators': [500, 550, 950],\n }\n optimize_for_random(\"Random Forest\", X, Y, clf, skf, RF_grid, mcc_ave_scorer(), 50, SEED)\n # optimize_for_grid(\"Random Forest\", X, Y, clf, skf, RF_grid, mcc_ave_scorer())\n"
]
| [
[
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.neural_network.MLPClassifier"
]
]
|
naver-ai/calm | [
"d77b46a047e1b27614b1624d031d52463acbfea0"
]
| [
"eval_remove_classify.py"
]
| [
"\"\"\"\nCALM\nCopyright (c) 2021-present NAVER Corp.\nMIT license\n\"\"\"\n\nimport os\nimport pickle\nimport torch\n\nfrom util import get_scoremaps\nfrom util import get_baseline\nfrom util import resize_scoremaps\nfrom util import get_topk_to_zero_mask\nfrom util import random_mask_generator\nfrom main import Trainer\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\n_ERASE_K_LIST = [1e-1, 3e-1, 5e-1, 7e-1, 9e-1]\n\ndef _get_correctness(tester, inputs, targets):\n with torch.no_grad():\n outputs = tester.model(inputs)['probs']\n preds = outputs.max(dim=1)[1].cpu().eq(targets).tolist()\n return preds\n\n\ndef main():\n tester = Trainer()\n tester.model.eval()\n\n device = tester.device\n dataset_name = tester.args.dataset_name\n data_loader = tester.loaders['test']\n\n measures = {'preds': [],\n 'preds-topk': {erase_k: [] for erase_k in _ERASE_K_LIST},\n 'preds-random': {erase_k: [] for erase_k in _ERASE_K_LIST}}\n\n process = tester.args.score_map_process\n if tester.args.attribution_method == 'CALM_EM':\n process += '_EM'\n elif tester.args.attribution_method == 'CALM_ML':\n process += '_ML'\n\n print(f'start! {process}')\n\n for enum, (inputs, targets, _) in enumerate(data_loader):\n inputs = inputs.to(device)\n baselines = get_baseline('zero', inputs, device)\n preds = _get_correctness(tester, inputs, targets)\n measures['preds'] += preds\n\n scoremaps = get_scoremaps(tester, inputs, targets, dataset_name)\n scoremaps = resize_scoremaps(scoremaps).to(device)\n\n for erase_method in ['topk', 'random']:\n for erase_idx, erase_k in enumerate(_ERASE_K_LIST):\n if erase_method == 'topk':\n masks = get_topk_to_zero_mask(scoremaps, erase_k, device)\n elif erase_method == 'random':\n masks = random_mask_generator(inputs, device, erase_k)\n else:\n raise ValueError('Error!')\n inputs_masked = inputs * masks + baselines * (1 - masks)\n preds_masked = _get_correctness(tester, inputs_masked, targets)\n measures[f'preds-{erase_method}'][erase_k] += preds_masked\n\n if (enum + 1) % 50 == 0:\n print(f'Iteration: {enum + 1}')\n\n with open(f'{tester.args.log_folder}/measure_{process}.pickle', 'wb') as f:\n pickle.dump(measures, f)\n\n for k in _ERASE_K_LIST:\n ratio = sum(measures['preds-topk'][k]) / sum(\n measures['preds-random'][k])\n print(f'erase_k: {k}, prediction ratio w.r.t. random erase: '\n f'{ratio:.04f}')\n\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"torch.no_grad"
]
]
|
tobyfrancis/pymicro | [
"5c2ed0bb6990463ea6ee59586c9f59cd9b7b13ba"
]
| [
"examples/plotting/field_pole_figure.py"
]
| [
"from pymicro.crystal.microstructure import *\nfrom pymicro.crystal.texture import *\nfrom matplotlib import pyplot as plt, colors, colorbar, cm\n\nif __name__ == '__main__':\n '''This example demonstrate how a field can be used to color each\n symbol on the pole figure with the :py:meth:~`pymicro.crystal.texture.set_map_field`\n method.\n '''\n orientations = Orientation.read_euler_txt('../data/orientation_set.inp')\n micro = Microstructure(name='field')\n for i in range(600):\n micro.grains.append(Grain(i, orientations[i + 1]))\n\n # load strain from dat files\n strain_field = np.genfromtxt('../data/strain_avg_per_grain.dat')[19, ::2]\n\n # build custom pole figures\n pf = PoleFigure(microstructure=micro)\n pf.mksize = 8\n pf.set_map_field('strain', strain_field, field_min_level=0.015, field_max_level=0.025)\n fig = plt.figure()\n # direct PF\n ax1 = fig.add_axes([0.05, 0.05, 0.8, 0.9], aspect='equal')\n pf.plot_pf(ax=ax1)\n plt.title('111 pole figure, cubic elasticity')\n\n # to add the color bar\n ax2 = fig.add_axes([0.8, 0.05, 0.05, 0.9])\n norm = colors.Normalize(vmin=0.015, vmax=0.025)\n cb = colorbar.ColorbarBase(ax2, cmap=cm.hot, norm=norm, orientation='vertical')\n cb.set_label('Average strain (mm/mm)')\n\n image_name = os.path.splitext(__file__)[0] + '.png'\n print('writting %s' % image_name)\n plt.savefig('%s' % image_name, format='png')\n\n from matplotlib import image\n\n image.thumbnail(image_name, 'thumb_' + image_name, 0.2)\n"
]
| [
[
"matplotlib.image.thumbnail",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.colors.Normalize",
"matplotlib.colorbar.ColorbarBase"
]
]
|
isadorafaggiani/Deteccao | [
"fa8c286a7e2e338a8e4eaca39e8bd029169de9e6"
]
| [
"exibicao.py"
]
| [
"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nsns.set_theme()\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport tkinter as tk\nfrom tkinter import filedialog as fd\nfrom datetime import datetime, timedelta\nfrom scipy.stats import iqr\n\ndef freedman_diaconis_rule(coords):\n\n data_x = coords[:,1]\n bin_width_x = 2.0 * iqr(data_x) / np.power(len(data_x), 1.0/3.0)\n bin_count_x = int(np.ceil((np.max(data_x) - np.min(data_x)) / bin_width_x))\n print(f'bin_width_x = {bin_width_x}\\tbin_count_x = {bin_count_x}')\n\n data_y = coords[:,2]\n bin_width_y = 2.0 * iqr(data_y) / np.power(len(data_y), 1.0/3.0)\n bin_count_y = int(np.ceil((np.max(data_y) - np.min(data_y)) / bin_width_y))\n print(f'bin_width_y = {bin_width_y}\\tbin_count_y = {bin_count_y}')\n\n return bin_count_x,bin_count_y\n\ndef exibir(coords):\n\n print('Showing heatmap.')\n bin_count_x,bin_count_y = freedman_diaconis_rule(coords)\n colors = np.random.rand(len(coords))\n fig = px.density_heatmap(coords, x=coords[:,1], y=coords[:,2], nbinsx=bin_count_x, nbinsy=bin_count_y)\n fig.show()\n\n #print('Showing pizza plot.')\n #labels = ['Left_Gaze', 'Right_Gaze']\n #values = [contadorLeft, contadorRight]\n #fig = go.Figure(data=[go.Pie(labels=labels, values=values)])\n #fig.show()\n"
]
| [
[
"scipy.stats.iqr",
"numpy.max",
"numpy.min"
]
]
|
idahopotato1/notebooks | [
"453598a48f984ea379379c27ec8883cb6d99da83"
]
| [
"notebooks/twitter/util/utils.py"
]
| [
"import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom statsmodels.stats.stattools import durbin_watson\nfrom statsmodels.tsa.api import VAR\nfrom statsmodels.tsa.stattools import adfuller\nimport scipy.stats as stats\nimport numpy as np\n\n\ndef augmented_dickey_fuller_statistics(\n coin, feature_name, time_series, diff_order, _diff\n):\n \"\"\"\n This function recursively applies adfuller on the time-series if p-value is less than 0.05, hence rejecting the below null hypothesis.\n\n Null hypothesis: Unit root is not detected (stationary time-series)\n\n Args:\n coin: The cryptocurrency the time-series belongs to\n feature_name: The name of the time-series\n time_series: The time-series to be test for stationary\n diff_order: The number of time the time-series has been differenced\n _diff: Dataframe containing all the differenced iteration of the time-series\n\n Returns:\n _diff: All the differenced iteration of the time-series\n time_series: The final-series which is stationary.\n \"\"\"\n\n global full_diff_df\n result = adfuller(time_series)\n if result[1] < 0.05:\n return _diff, time_series\n else:\n print(\n coin,\n feature_name,\n \"p-value: %f\" % result[1],\n \"There is unit root (Cannot reject null hypothesis) - Repeat differencing\",\n )\n\n diff_order += 1\n differencing = time_series.diff()\n\n diff_df = differencing.reset_index()\n diff_df[\"order\"] = diff_order\n diff_df.set_index([\"coin_symbol\", \"date\", \"order\"], inplace=True)\n axis = 1 if feature_name in diff_df.columns else 0\n _diff = pd.concat([_diff, diff_df], axis=axis, join=\"outer\")\n\n return augmented_dickey_fuller_statistics(\n coin, feature_name, differencing.dropna(), diff_order, _diff\n )\n\n\ndef transform_gc_date(\n coin, gc_test_result, c, r, maxlag, grangercausalitytests_df, verbose\n):\n \"\"\"\n This function transform the Granger Causality test results into columns of vectors for loading into atoti.\n\n Args:\n coin: The cryptocurrency the time-series belongs to\n gc_test_result: The test results of the grangercausalitytest\n c: The name of the feature that was tested to see if it Granger caused r\n r: The name of the feature that was tested to see if it is Granger caused by c\n maxlag: number of lags applied for the grangercausalitytest\n verbose: print debug statement if True\n\n Returns:\n Dataframe containing the Grangercausalitytest results transformed into vectors for each test:\n - ssr_ftest\n - ssr_chi2test\n - lrtest\n - params_ftest\n \"\"\"\n for test in [\"ssr_ftest\", \"ssr_chi2test\", \"lrtest\", \"params_ftest\"]:\n result = {\"coin_symbol\": coin, \"x\": c, \"y\": r, \"Test name\": test}\n\n p_values = [round(gc_test_result[i + 1][0][test][1], 4) for i in range(maxlag)]\n\n # we store the p-values for each test and each lag\n result[\"p-value\"] = p_values # \";\".join(map(str, p_values))\n\n f_chi2 = [round(gc_test_result[i + 1][0][test][0], 4) for i in range(maxlag)]\n\n if test in [\"ssr_chi2test\", \"lrtest\"]:\n result[\"chi2\"] = f_chi2 # \";\".join(map(str, f_chi2))\n\n df_chi = [\n round(gc_test_result[i + 1][0][test][2], 4) for i in range(maxlag)\n ]\n result[\"df\"] = df_chi # \";\".join(map(str, df_chi))\n else:\n result[\"F\"] = f_chi2 # \";\".join(map(str, f_chi2))\n df_denom = [\n round(gc_test_result[i + 1][0][test][2], 4) for i in range(maxlag)\n ]\n result[\"df_denom\"] = df_denom # \";\".join(map(str, df_denom))\n\n df_num = [\n round(gc_test_result[i + 1][0][test][3], 4) for i in range(maxlag)\n ]\n result[\"df_num\"] = df_num # \";\".join(map(str, df_num))\n\n if verbose:\n print(f\"{test} --- Y = {r}, X = {c}, P Values = {p_values}\")\n\n grangercausalitytests_df = grangercausalitytests_df.append(\n result, ignore_index=True\n )\n\n return grangercausalitytests_df\n\n\ndef autocorrelation(value):\n \"\"\"\n This function prints the criteria for autocorrelation with Durbin watson\n \"\"\"\n if value < 1.5:\n print(\"Positive correlation detected\")\n elif value > 2.5:\n print(\"Negative correlation detected\")\n else:\n print(\"No correlation detected\")\n\n\ndef adjust(val, length=6):\n \"\"\"\n This function left align the numerical value for printing purpose\n \"\"\"\n return str(val).ljust(length)\n\n\ndef forecast_accuracy(forecast, actual):\n \"\"\"\n This function computes the statistical measures of accuracy of the forecast.\n\n Args:\n forecast: forecasted results\n actual: actual values\n\n Returns:\n - mape: mean absolute percentage error (the better the prediction, the lower the value)\n - me: mean error\n - mae: mean absolute error\n - rmse: root mean squared error\n - corr: correlation\n - minmax: min max accuracy (the better the prediction, the higher the value - 1 for perfect model)\n \"\"\"\n\n mape = np.mean(np.abs(forecast - actual) / np.abs(actual)) # MAPE\n me = np.mean(forecast - actual) # ME\n mae = np.mean(np.abs(forecast - actual)) # MAE\n mpe = np.mean((forecast - actual) / actual) # MPE\n rmse = np.mean((forecast - actual) ** 2) ** 0.5 # RMSE\n corr = np.corrcoef(forecast, actual)[0, 1] # corr\n mins = np.amin(np.stack((forecast, actual), axis=1), axis=1)\n maxs = np.amax(np.stack((forecast, actual), axis=1), axis=1)\n minmax = 1 - np.mean(mins / maxs) # minmax\n return {\n \"mape\": mape,\n \"me\": me,\n \"mae\": mae,\n \"mpe\": mpe,\n \"rmse\": rmse,\n \"corr\": corr,\n \"minmax\": minmax,\n }\n\n\ndef var_forecast(coin, data_stats, train_data, actual_df, nobs, verbose=False):\n \"\"\"\n This function performs the following:\n - forecast the time-series using VAR\n - durbin watson testing on the residual from the model\n - obtain normaltest, kurtosis and skewness of the residual from the model\n - compute the forecast accuracy\n\n The number of days forecast is the minimum value between the lag order and the nobs.\n\n Args:\n coin: The cryptocurrency the time-series belongs to\n data_stats: The data_stats dataframe for storing the durbin_watson, norm_stat, norm_p, kurtosis and skewness value\n train_data: Train data containing the features for VAR forecast\n actual_df: The actual value to be compared against the forecasted results\n nobs: Number of observations to forecast\n verbose: To print the debugging statements\n\n Returns:\n fitted_df: Dataframe containing residual of the features\n data_stats: Dataframe containing durbin_watson, norm_stat, norm_p, kurtosis and skewness value\n accuracy_prod: measures of accuracy for the forecast\n pred_df: predicted results\n \"\"\"\n # standardizing features\n scal = StandardScaler()\n df_scaled = pd.DataFrame(\n scal.fit_transform(train_data.values),\n columns=train_data.columns,\n index=train_data.index,\n )\n\n mod = VAR(df_scaled, freq=\"D\")\n\n selected_orders = mod.select_order().selected_orders\n max_lag = selected_orders[\"aic\"]\n res = mod.fit(maxlags=max_lag, ic=\"aic\")\n\n if verbose:\n print(coin, res.summary())\n\n fitted_df = res.resid.rename(columns={\"Returns\": \"Returns residual\"})[\n \"Returns residual\"\n ]\n # check for auto-correlation of the residual\n out = durbin_watson(res.resid)\n\n # collect the auto-correlatio results to be loaded into atoti later on\n for col, val in zip(df_scaled.columns, out):\n\n # get the residual values\n metric = res.resid[col]\n stat, p = stats.normaltest(metric)\n kurtosis = stats.kurtosis(metric)\n skewness = stats.skew(metric)\n\n data_stats.loc[\n (data_stats[\"coin_symbol\"] == coin) & (data_stats[\"metric_name\"] == col),\n [\"durbin_watson\", \"norm_stat\", \"norm_p\", \"kurtosis\", \"skewness\"],\n ] = [val, stat, p, kurtosis, skewness]\n\n if verbose:\n print(\n \"+++++++++++++ data_stats\",\n data_stats.loc[\n (data_stats[\"coin_symbol\"] == coin)\n & (data_stats[\"metric_name\"] == col)\n ],\n )\n\n autocorrelation(val)\n\n # Get the lag order\n lag_order = res.k_ar\n\n if lag_order > 0:\n # Forecasting\n input_data = df_scaled.values[-lag_order:]\n # take the minimal forecast between the lag order and the number of observations required\n forecast_steps = lag_order if lag_order < nobs else nobs\n pred = res.forecast(y=input_data, steps=forecast_steps)\n pred_transform = scal.inverse_transform(pred)\n\n # we generate index from the last date for a period equivalent to the size of the forecast\n last_date = df_scaled.tail(1).index.get_level_values(\"date\").to_pydatetime()[0]\n date_indices = pd.date_range(\n start=last_date, periods=(forecast_steps + 1), closed=\"right\"\n )\n pred_df = pd.DataFrame(\n pred_transform,\n index=date_indices,\n columns=df_scaled.columns,\n ).reset_index()\n\n accuracy_prod = forecast_accuracy(\n pred_df[\"Returns\"].values, actual_df[\"Returns\"][:forecast_steps]\n )\n accuracy_prod = pd.DataFrame(accuracy_prod, index=[coin])\n accuracy_prod[\"lag_order\"] = lag_order\n accuracy_prod[\"Observations\"] = forecast_steps\n\n if verbose:\n for k, v in accuracy_prod.items():\n print(adjust(k), \": \", v)\n\n pred_df[\"coin_symbol\"] = coin\n pred_df[\"Subset\"] = \"Test\"\n pred_df.rename(columns={\"index\": \"date\"}, inplace=True)\n\n fitted_df = fitted_df.reset_index()\n fitted_df[\"coin_symbol\"] = coin\n fitted_df[\"Subset\"] = \"Train\"\n fitted_df[\"date\"] = fitted_df[\"date\"].apply(lambda x: x.strftime(\"%Y-%m-%d\"))\n\n pred_df[\"Price\"] = np.nan\n fitted_df[\"date\"] = pd.to_datetime(fitted_df[\"date\"])\n\n return (\n fitted_df[[\"date\", \"coin_symbol\", \"Returns residual\"]],\n data_stats.loc[~data_stats[\"norm_stat\"].isnull()],\n accuracy_prod,\n pred_df[[\"date\", \"coin_symbol\", \"Returns\", \"Price\"]].copy(),\n )\n"
]
| [
[
"pandas.to_datetime",
"scipy.stats.normaltest",
"sklearn.preprocessing.StandardScaler",
"pandas.DataFrame",
"pandas.date_range",
"numpy.mean",
"scipy.stats.skew",
"numpy.stack",
"numpy.abs",
"pandas.concat",
"numpy.corrcoef",
"scipy.stats.kurtosis"
]
]
|
pravee2019/Movielense | [
"795ab794937e6c858d5d04b09c9f4bed8998ead4"
]
| [
"grading.py"
]
| [
"#!/usr/bin/env python\n\nimport pandas as pd\n\nsubmission = pd.read_csv('submission.csv') # Learner's submission File\nrubric = pd.read_csv('rubric.csv') # Rubric from edX\n\n\n# If the learner's answer equal to rubric in each row, get 1 points\n\nScore=[]\nmatches=0\nfor x,y in zip(submission.rating, rubric.rating):\n if x == y: \n matches += 1\n\n# Calculate the final grade for accuracy to 4 decimal places\n \nScore.append(round(matches/rubric.shape[0],4)) \n \nprint('The accuracy for this learner is', Score[0]*100.00)\n"
]
| [
[
"pandas.read_csv"
]
]
|
benfknzen/ml-agents | [
"d76bea75a2eb9b0b9429bd912cc7f72686a9896e"
]
| [
"ml-agents/mlagents/trainers/buffer.py"
]
| [
"import numpy as np\nimport h5py\nfrom typing import List, BinaryIO\n\nfrom mlagents_envs.exception import UnityException\n\n\nclass BufferException(UnityException):\n \"\"\"\n Related to errors with the Buffer.\n \"\"\"\n\n pass\n\n\nclass AgentBuffer(dict):\n \"\"\"\n AgentBuffer contains a dictionary of AgentBufferFields. Each agent has his own AgentBuffer.\n The keys correspond to the name of the field. Example: state, action\n \"\"\"\n\n class AgentBufferField(list):\n \"\"\"\n AgentBufferField is a list of numpy arrays. When an agent collects a field, you can add it to his\n AgentBufferField with the append method.\n \"\"\"\n\n def __init__(self):\n self.padding_value = 0\n super().__init__()\n\n def __str__(self):\n return str(np.array(self).shape)\n\n def append(self, element: np.ndarray, padding_value: float = 0.0) -> None:\n \"\"\"\n Adds an element to this list. Also lets you change the padding\n type, so that it can be set on append (e.g. action_masks should\n be padded with 1.)\n :param element: The element to append to the list.\n :param padding_value: The value used to pad when get_batch is called.\n \"\"\"\n super().append(element)\n self.padding_value = padding_value\n\n def extend(self, data: np.ndarray) -> None:\n \"\"\"\n Adds a list of np.arrays to the end of the list of np.arrays.\n :param data: The np.array list to append.\n \"\"\"\n self += list(np.array(data))\n\n def set(self, data):\n \"\"\"\n Sets the list of np.array to the input data\n :param data: The np.array list to be set.\n \"\"\"\n # Make sure we convert incoming data to float32 if it's a float\n dtype = None\n if data is not None and len(data) and isinstance(data[0], float):\n dtype = np.float32\n self[:] = []\n self[:] = list(np.array(data, dtype=dtype))\n\n def get_batch(\n self,\n batch_size: int = None,\n training_length: int = 1,\n sequential: bool = True,\n ) -> np.ndarray:\n \"\"\"\n Retrieve the last batch_size elements of length training_length\n from the list of np.array\n :param batch_size: The number of elements to retrieve. If None:\n All elements will be retrieved.\n :param training_length: The length of the sequence to be retrieved. If\n None: only takes one element.\n :param sequential: If true and training_length is not None: the elements\n will not repeat in the sequence. [a,b,c,d,e] with training_length = 2 and\n sequential=True gives [[0,a],[b,c],[d,e]]. If sequential=False gives\n [[a,b],[b,c],[c,d],[d,e]]\n \"\"\"\n if sequential:\n # The sequences will not have overlapping elements (this involves padding)\n leftover = len(self) % training_length\n # leftover is the number of elements in the first sequence (this sequence might need 0 padding)\n if batch_size is None:\n # retrieve the maximum number of elements\n batch_size = len(self) // training_length + 1 * (leftover != 0)\n # The maximum number of sequences taken from a list of length len(self) without overlapping\n # with padding is equal to batch_size\n if batch_size > (len(self) // training_length + 1 * (leftover != 0)):\n raise BufferException(\n \"The batch size and training length requested for get_batch where\"\n \" too large given the current number of data points.\"\n )\n if batch_size * training_length > len(self):\n padding = np.array(self[-1], dtype=np.float32) * self.padding_value\n return np.array(\n [padding] * (training_length - leftover) + self[:],\n dtype=np.float32,\n )\n else:\n return np.array(\n self[len(self) - batch_size * training_length :],\n dtype=np.float32,\n )\n else:\n # The sequences will have overlapping elements\n if batch_size is None:\n # retrieve the maximum number of elements\n batch_size = len(self) - training_length + 1\n # The number of sequences of length training_length taken from a list of len(self) elements\n # with overlapping is equal to batch_size\n if (len(self) - training_length + 1) < batch_size:\n raise BufferException(\n \"The batch size and training length requested for get_batch where\"\n \" too large given the current number of data points.\"\n )\n tmp_list: List[np.ndarray] = []\n for end in range(len(self) - batch_size + 1, len(self) + 1):\n tmp_list += self[end - training_length : end]\n return np.array(tmp_list, dtype=np.float32)\n\n def reset_field(self) -> None:\n \"\"\"\n Resets the AgentBufferField\n \"\"\"\n self[:] = []\n\n def __init__(self):\n self.last_brain_info = None\n self.last_take_action_outputs = None\n super().__init__()\n\n def __str__(self):\n return \", \".join([\"'{0}' : {1}\".format(k, str(self[k])) for k in self.keys()])\n\n def reset_agent(self) -> None:\n \"\"\"\n Resets the AgentBuffer\n \"\"\"\n for k in self.keys():\n self[k].reset_field()\n self.last_brain_info = None\n self.last_take_action_outputs = None\n\n def __getitem__(self, key):\n if key not in self.keys():\n self[key] = self.AgentBufferField()\n return super().__getitem__(key)\n\n def check_length(self, key_list: List[str]) -> bool:\n \"\"\"\n Some methods will require that some fields have the same length.\n check_length will return true if the fields in key_list\n have the same length.\n :param key_list: The fields which length will be compared\n \"\"\"\n if len(key_list) < 2:\n return True\n length = None\n for key in key_list:\n if key not in self.keys():\n return False\n if (length is not None) and (length != len(self[key])):\n return False\n length = len(self[key])\n return True\n\n def shuffle(self, sequence_length: int, key_list: List[str] = None) -> None:\n \"\"\"\n Shuffles the fields in key_list in a consistent way: The reordering will\n be the same across fields.\n :param key_list: The fields that must be shuffled.\n \"\"\"\n if key_list is None:\n key_list = list(self.keys())\n if not self.check_length(key_list):\n raise BufferException(\n \"Unable to shuffle if the fields are not of same length\"\n )\n s = np.arange(len(self[key_list[0]]) // sequence_length)\n np.random.shuffle(s)\n for key in key_list:\n tmp: List[np.ndarray] = []\n for i in s:\n tmp += self[key][i * sequence_length : (i + 1) * sequence_length]\n self[key][:] = tmp\n\n def make_mini_batch(self, start: int, end: int) -> \"AgentBuffer\":\n \"\"\"\n Creates a mini-batch from buffer.\n :param start: Starting index of buffer.\n :param end: Ending index of buffer.\n :return: Dict of mini batch.\n \"\"\"\n mini_batch = AgentBuffer()\n for key in self:\n mini_batch[key] = self[key][start:end]\n return mini_batch\n\n def sample_mini_batch(\n self, batch_size: int, sequence_length: int = 1\n ) -> \"AgentBuffer\":\n \"\"\"\n Creates a mini-batch from a random start and end.\n :param batch_size: number of elements to withdraw.\n :param sequence_length: Length of sequences to sample.\n Number of sequences to sample will be batch_size/sequence_length.\n \"\"\"\n num_seq_to_sample = batch_size // sequence_length\n mini_batch = AgentBuffer()\n buff_len = self.num_experiences\n num_sequences_in_buffer = buff_len // sequence_length\n start_idxes = (\n np.random.randint(num_sequences_in_buffer, size=num_seq_to_sample)\n * sequence_length\n ) # Sample random sequence starts\n for i in start_idxes:\n for key in self:\n mini_batch[key].extend(self[key][i : i + sequence_length])\n return mini_batch\n\n def save_to_file(self, file_object: BinaryIO) -> None:\n \"\"\"\n Saves the AgentBuffer to a file-like object.\n \"\"\"\n with h5py.File(file_object, \"w\") as write_file:\n for key, data in self.items():\n write_file.create_dataset(key, data=data, dtype=\"f\", compression=\"gzip\")\n\n def load_from_file(self, file_object: BinaryIO) -> None:\n \"\"\"\n Loads the AgentBuffer from a file-like object.\n \"\"\"\n with h5py.File(file_object, \"r\") as read_file:\n for key in list(read_file.keys()):\n self[key] = AgentBuffer.AgentBufferField()\n # extend() will convert the numpy array's first dimension into list\n self[key].extend(read_file[key][()])\n\n def truncate(self, max_length: int, sequence_length: int = 1) -> None:\n \"\"\"\n Truncates the buffer to a certain length.\n\n This can be slow for large buffers. We compensate by cutting further than we need to, so that\n we're not truncating at each update. Note that we must truncate an integer number of sequence_lengths\n param: max_length: The length at which to truncate the buffer.\n \"\"\"\n current_length = self.num_experiences\n # make max_length an integer number of sequence_lengths\n max_length -= max_length % sequence_length\n if current_length > max_length:\n for _key in self.keys():\n self[_key] = self[_key][current_length - max_length :]\n\n def resequence_and_append(\n self,\n target_buffer: \"AgentBuffer\",\n key_list: List[str] = None,\n batch_size: int = None,\n training_length: int = None,\n ) -> None:\n \"\"\"\n Takes in a batch size and training length (sequence length), and appends this AgentBuffer to target_buffer\n properly padded for LSTM use. Optionally, use key_list to restrict which fields are inserted into the new\n buffer.\n :param target_buffer: The buffer which to append the samples to.\n :param key_list: The fields that must be added. If None: all fields will be appended.\n :param batch_size: The number of elements that must be appended. If None: All of them will be.\n :param training_length: The length of the samples that must be appended. If None: only takes one element.\n \"\"\"\n if key_list is None:\n key_list = list(self.keys())\n if not self.check_length(key_list):\n raise BufferException(\n \"The length of the fields {0} were not of same length\".format(key_list)\n )\n for field_key in key_list:\n target_buffer[field_key].extend(\n self[field_key].get_batch(\n batch_size=batch_size, training_length=training_length\n )\n )\n\n @property\n def num_experiences(self) -> int:\n \"\"\"\n The number of agent experiences in the AgentBuffer, i.e. the length of the buffer.\n\n An experience consists of one element across all of the fields of this AgentBuffer.\n Note that these all have to be the same length, otherwise shuffle and append_to_update_buffer\n will fail.\n \"\"\"\n if self.values():\n return len(next(iter(self.values())))\n else:\n return 0\n"
]
| [
[
"numpy.array",
"numpy.random.randint",
"numpy.random.shuffle"
]
]
|
ayushbaid/cloudy-cycle-gans | [
"dfd8481d739ad033d40bbe4ac01b5d0fce4df9f2"
]
| [
"utils/buffer.py"
]
| [
"import random\n\nimport torch\n\nfrom torch.autograd import Variable\n\n\nclass ImageBuffer(object):\n '''\n Implement the image buffer to be used in training\n\n With p=0.35, return the input images; otherwise return data from buffer and replace them with input\n '''\n # TODO: write tests\n\n def __init__(self, buffer_size, is_cuda):\n self.buffer_size = buffer_size\n self.buffer_list = []\n self.is_cuda = is_cuda\n\n def get(self, input_images):\n '''\n Args:\n * input_images: list of images\n\n '''\n result = []\n\n for image in input_images.data:\n image = torch.unsqueeze(image, 0)\n if len(self.buffer_list) < self.buffer_size:\n # buffer is not full yet\n self.buffer_list.append(image)\n result.append(image)\n else:\n p = random.uniform(0, 1) > 0.35 # simulating coin toss\n\n if p:\n # fetch value from the buffer\n idx = random.randint(0, self.buffer_size-1)\n result.append(self.buffer_list[idx])\n self.buffer_list[idx] = image\n else:\n result.append(image)\n\n # return the result as a single tensor\n if self.is_cuda:\n return Variable(torch.cat(result, 0).cuda())\n else:\n return Variable(torch.cat(result, 0))\n"
]
| [
[
"torch.cat",
"torch.unsqueeze"
]
]
|
Dhairya1510/pre_react_hover_net | [
"81b1cbe3930a07892b79004eca140ff8a5c0ae76"
]
| [
"dataloader/train_loader.py"
]
| [
"import csv\nimport glob\nimport os\nimport re\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio\nimport torch.utils.data\n\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom misc.utils import cropping_center\n\nfrom .augs import (\n add_to_brightness,\n add_to_contrast,\n add_to_hue,\n add_to_saturation,\n gaussian_blur,\n median_blur,\n)\n\n\n####\nclass FileLoader(torch.utils.data.Dataset):\n \"\"\"Data Loader. Loads images from a file list and \n performs augmentation with the albumentation library.\n After augmentation, horizontal and vertical maps are \n generated.\n\n Args:\n file_list: list of filenames to load\n input_shape: shape of the input [h,w] - defined in config.py\n mask_shape: shape of the output [h,w] - defined in config.py\n mode: 'train' or 'valid'\n \n \"\"\"\n\n # TODO: doc string\n\n def __init__(\n self,\n img_path,\n ann_path,\n indices=None,\n with_type=False,\n input_shape=None,\n mask_shape=None,\n run_mode=\"train\",\n setup_augmentor=True,\n target_gen_func=None,\n ):\n assert input_shape is not None and mask_shape is not None\n self.run_mode = run_mode\n self.imgs = np.load(img_path, mmap_mode='r')\n self.anns = np.load(ann_path, mmap_mode='r')\n\n self.indices = (\n indices if indices is not None\n else np.arange(0, self.imgs.shape[0])\n )\n\n self.with_type = with_type\n self.mask_shape = mask_shape\n self.input_shape = input_shape\n self.id = 0\n self.target_gen_func = target_gen_func[0]\n self.target_gen_kwargs = target_gen_func[1]\n if setup_augmentor:\n self.setup_augmentor(0, 0)\n return\n\n def setup_augmentor(self, worker_id, seed):\n self.augmentor = self.__get_augmentation(self.run_mode, seed)\n self.shape_augs = iaa.Sequential(self.augmentor[0])\n self.input_augs = iaa.Sequential(self.augmentor[1])\n self.id = self.id + worker_id\n return\n\n def __len__(self):\n return len(self.indices)\n\n def __getitem__(self, idx):\n idx = self.indices[idx]\n\n # RGB images\n img = np.array(self.imgs[idx]).astype(\"uint8\")\n # instance ID map and type map\n ann = np.array(self.anns[idx]).astype(\"int32\")\n\n if self.shape_augs is not None:\n shape_augs = self.shape_augs.to_deterministic()\n img = shape_augs.augment_image(img)\n ann = shape_augs.augment_image(ann)\n\n if self.input_augs is not None:\n input_augs = self.input_augs.to_deterministic()\n img = input_augs.augment_image(img)\n\n img = cropping_center(img, self.input_shape)\n feed_dict = {\"img\": img}\n\n inst_map = ann[..., 0] # HW1 -> HW\n if self.with_type:\n type_map = (ann[..., 1]).copy()\n type_map = cropping_center(type_map, self.mask_shape)\n feed_dict[\"tp_map\"] = type_map\n\n target_dict = self.target_gen_func(\n inst_map, self.mask_shape, **self.target_gen_kwargs\n )\n feed_dict.update(target_dict)\n\n return feed_dict\n\n def __get_augmentation(self, mode, rng):\n if mode == \"train\":\n shape_augs = [\n # * order = ``0`` -> ``cv2.INTER_NEAREST``\n # * order = ``1`` -> ``cv2.INTER_LINEAR``\n # * order = ``2`` -> ``cv2.INTER_CUBIC``\n # * order = ``3`` -> ``cv2.INTER_CUBIC``\n # * order = ``4`` -> ``cv2.INTER_CUBIC``\n # ! for pannuke v0, no rotation or translation,\n # ! just flip to avoid mirror padding\n # iaa.Affine(\n # # scale images to 80-120% of their size,\n # # individually per axis\n # scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n # # translate by -A to +A percent (per axis)\n # translate_percent={\n # \"x\": (-0.01, 0.01), \"y\": (-0.01, 0.01)},\n # shear=(-5, 5), # shear by -5 to +5 degrees\n # rotate=(-179, 179), # rotate by -179 to +179 degrees\n # order=0, # use nearest neighbour\n # backend=\"cv2\", # opencv for fast processing\n # seed=rng,\n # ),\n # set position to 'center' for center crop\n # else 'uniform' for random crop\n iaa.CropToFixedSize(\n self.input_shape[0],\n self.input_shape[1],\n position=\"center\"\n ),\n iaa.Fliplr(0.5, seed=rng),\n iaa.Flipud(0.5, seed=rng),\n ]\n\n input_augs = [\n iaa.OneOf(\n [\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: gaussian_blur(*args, max_ksize=3),\n ),\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: median_blur(*args, max_ksize=3),\n ),\n iaa.AdditiveGaussianNoise(\n loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5\n ),\n ]\n ),\n iaa.Sequential(\n [\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: add_to_hue(*args, range=(-8, 8)),\n ),\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: add_to_saturation(\n *args, range=(-0.2, 0.2)\n ),\n ),\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: add_to_brightness(\n *args, range=(-26, 26)\n ),\n ),\n iaa.Lambda(\n seed=rng,\n func_images=lambda *args: add_to_contrast(\n *args, range=(0.75, 1.25)\n ),\n ),\n ],\n random_order=True,\n ),\n ]\n else:\n shape_augs = [\n # set position to 'center' for center crop\n # else 'uniform' for random crop\n iaa.CropToFixedSize(\n self.input_shape[0], self.input_shape[1], position=\"center\"\n )\n ]\n input_augs = []\n\n return shape_augs, input_augs\n"
]
| [
[
"numpy.array",
"numpy.arange",
"numpy.load"
]
]
|
alex-medvedev-msc/ukb_loader | [
"4940f3859eb1cc167bd768def97ce8d55c14892b"
]
| [
"src/ukb_loader/load.py"
]
| [
"import numpy\nimport pandas\nfrom typing import List, Tuple\nimport zarr\nimport os\n\n\nclass UKBDataLoader():\n def __init__(self, data_dir: str, split: str, phenotype_id: str, features: List[str], array_agg_func='mean') -> None:\n \n self.dataset = zarr.open_group(os.path.join(data_dir, split), mode='r')\n self.train, self.val, self.test = self.dataset['train'], self.dataset['val'], self.dataset['test']\n self.columns = self.train.columns[:]\n\n if '-' in phenotype_id:\n raise ValueError(f'- should not be in {phenotype_id}, we need only a field id without any assessments and array numbers')\n self.phenotype_id = phenotype_id\n\n for f in features:\n if '-' in f:\n raise ValueError(f'Feature {f} should not contain -, we need only a field id without any assessments and array numbers')\n\n self.features = features\n if array_agg_func is not None and array_agg_func not in ['mean', 'max']:\n raise ValueError(f'array_agg_func must be one of the [None, \"mean\", \"max\"]')\n self.agg_func = array_agg_func\n\n def _find_assessment_columns(self, column):\n # 50-1.0 = {phenotype_id}-{assessment_id}.{array_id}\n to_find = column + '-'\n assessment_number = 0\n array_number = 0\n found = []\n for i, col in enumerate(self.columns):\n if col[:len(to_find)] == to_find:\n found.append(i)\n a = int(col[len(to_find)])\n if a > assessment_number:\n assessment_number = a\n \n array_c = int(col[len(to_find) + 2:])\n if array_c > array_number:\n array_number = array_c\n \n return found, assessment_number + 1, array_number + 1\n\n def _get_arrayed_target(self, chunk, target_cols, array_count) -> numpy.ndarray:\n total_targets = []\n for array_index in range(array_count):\n cols = target_cols[array_index*array_count: (array_index + 1)*array_count]\n targets = chunk[:, cols]\n if self.agg_func == 'max':\n targets = numpy.nanmax(targets, axis=1)\n elif self.agg_func == 'mean':\n targets = numpy.nanmean(targets, axis=1)\n else:\n pass\n # no aggregation\n total_targets.append(targets)\n\n return numpy.column_stack(total_targets)\n\n def _process_chunk(self, chunk, target_cols, feature_descriptions: List[Tuple], assessment_count: int, array_count: int):\n if array_count > 1:\n targets = self._get_arrayed_target(chunk, target_cols, array_count)\n else:\n targets = chunk[:, target_cols]\n assessment_indices = targets.shape[1] - numpy.argmax(numpy.flip(~numpy.isnan(targets), axis=1), axis=1) - 1\n true_target = targets[numpy.arange(targets.shape[0]), assessment_indices].reshape(-1, 1)\n # ugly hack for arrayed target without aggregation\n # for example PCA componenets, field 22009-0.{1-40}\n if array_count > 1 and self.agg_func is None:\n assessment_indices = assessment_indices // array_count\n true_target = targets\n features = []\n for f_cols, _, f_array_count in feature_descriptions:\n f = chunk[:, f_cols]\n if len(f_cols) == 1: # for features like sex\n features.append(f.reshape(-1, 1))\n elif self.agg_func is None and f_array_count > 1:\n features.append(f)\n else:\n features.append(f[numpy.arange(f.shape[0]), assessment_indices].reshape(-1, 1))\n \n features = numpy.hstack(features)\n return true_target, features\n\n def _load_real_value_target(self, dataset, feature_descriptions: List[Tuple]):\n target_cols, assessment_count, array_count = self._find_assessment_columns(self.phenotype_id)\n\n data = dataset['dataset']\n\n targets, all_features = [], []\n for start in range(0, data.shape[0], data.chunks[0]):\n\n chunk = data[start:start + data.chunks[0]]\n target, features = self._process_chunk(chunk, target_cols, feature_descriptions, assessment_count, array_count)\n targets.append(target)\n all_features.append(features)\n\n targets = numpy.vstack(targets)\n all_features = numpy.vstack(all_features)\n mask = ~numpy.isnan(targets)[:, 0]\n return targets[mask], all_features[mask], mask\n\n def _load(self, dataset):\n feature_descriptions = [self._find_assessment_columns(feature) for feature in self.features]\n targets, features, mask = self._load_real_value_target(dataset, feature_descriptions)\n\n data = numpy.concatenate([features, targets], axis=1)\n eid = dataset['eid'][:][mask]\n pheno_columns = [self.phenotype_id]\n if targets.shape[1] > 1:\n pheno_columns = [f'{self.phenotype_id}-0.{i}' for i in range(1, targets.shape[1] + 1)]\n feature_columns = []\n for feature_name, feature_desc in zip(self.features, feature_descriptions):\n arr_count = feature_desc[2]\n if arr_count > 1:\n feature_columns += [f'{feature_name}-0.{i}' for i in range(1, arr_count)]\n else:\n feature_columns.append(feature_name)\n frame = pandas.DataFrame(data=data, columns=feature_columns + pheno_columns, index=eid.squeeze(1) if len(eid.shape) == 2 else eid)\n return frame\n\n def load_train(self) -> pandas.DataFrame:\n return self._load(self.train)\n\n def load_val(self) -> pandas.DataFrame:\n return self._load(self.val)\n\n def load_test(self) -> pandas.DataFrame:\n return self._load(self.test)\n\n\nclass BinaryICDLoader():\n def __init__(self, data_dir: str, split: str, phenotype_col: str, features: List[str], icd10_code: str, array_agg_func='mean') -> None:\n \n self.dataset = zarr.open_group(os.path.join(data_dir, split), mode='r')\n self.train, self.val, self.test = self.dataset['train'], self.dataset['val'], self.dataset['test']\n self.columns = self.train.columns[:]\n self.str_columns = self.train.str_columns[:]\n\n if '-' in phenotype_col:\n raise ValueError(f'- should not be in {phenotype_col}, we need only a field id without any assessments and array numbers')\n self.phenotype_col = phenotype_col\n self.icd10_code = icd10_code\n\n for f in features:\n if '-' in f:\n raise ValueError(f'Feature {f} should not contain -, we need only a field id without any assessments and array numbers')\n\n if array_agg_func is not None and array_agg_func not in ['mean', 'max']:\n raise ValueError(f'array_agg_func must be one of the [None, \"mean\", \"max\"]')\n self.agg_func = array_agg_func\n\n self.features = features\n\n def _find_assessment_columns(self, column):\n # 50-1.0 = {phenotype_id}-{assessment_id}.{array_id}\n to_find = column + '-'\n assessment_number = 0\n array_number = 0\n found = []\n for i, col in enumerate(self.columns):\n if col[:len(to_find)] == to_find:\n found.append(i)\n a = int(col[len(to_find)])\n if a > assessment_number:\n assessment_number = a\n \n array_c = int(col[len(to_find) + 2:])\n if array_c > array_number:\n array_number = array_c\n \n return found, assessment_number + 1, array_number + 1\n\n def _find_arrayed_target_columns(self, column):\n to_find = column + '-'\n found = [[]]\n for i, col in enumerate(self.str_columns):\n if col[:len(to_find)] == to_find:\n assessment = int(col[len(to_find)]) # should always be 0\n found[assessment].append(i)\n \n return found\n\n def _process_chunk(self, str_chunk, chunk, target_cols, feature_descriptions):\n codes = []\n codes_na = []\n for i, assessment_cols in enumerate(target_cols):\n targets = str_chunk[:, assessment_cols]\n code_na = (targets == '').sum(axis=1) == targets.shape[1]\n codes_na.append(code_na)\n code_in = (targets == self.icd10_code).sum(axis=1) > 0\n codes.append(code_in.reshape(-1, 1))\n\n codes = numpy.hstack(codes)\n codes_na = numpy.hstack(codes_na)\n assessment_indices = numpy.argmax(codes, axis=1)\n true_target = (codes.sum(axis=1) > 0).astype(int).reshape(-1, 1)\n\n features = []\n for f_cols, _, f_array_count in feature_descriptions:\n f = chunk[:, f_cols]\n if len(f_cols) == 1: # for features like sex\n features.append(f.reshape(-1, 1))\n elif self.agg_func is None and f_array_count > 1:\n features.append(f)\n else:\n features.append(f[numpy.arange(f.shape[0]), assessment_indices].reshape(-1, 1))\n \n features = numpy.hstack(features)\n return true_target[~codes_na], features[~codes_na], codes_na\n\n def _load_binary_icd_target(self, dataset, feature_descriptions):\n target_cols = self._find_arrayed_target_columns(self.phenotype_col)\n data = dataset['dataset']\n str_data = dataset['str_dataset']\n targets, all_features, mask = [], [], []\n for start in range(0, data.shape[0], data.chunks[0]):\n\n chunk = data[start:start + data.chunks[0]]\n str_chunk = str_data[start: start + data.chunks[0]]\n target, features, codes_na = self._process_chunk(str_chunk, chunk, target_cols, feature_descriptions)\n targets.append(target)\n all_features.append(features)\n mask.append(codes_na)\n\n targets = numpy.vstack(targets)\n all_features = numpy.vstack(all_features)\n mask = numpy.hstack(mask)\n return targets, all_features, mask\n\n def _load(self, dataset):\n feature_descriptions = [self._find_assessment_columns(feature) for feature in self.features]\n targets, features, mask = self._load_binary_icd_target(dataset, feature_descriptions)\n\n feature_columns = []\n for feature_name, feature_desc in zip(self.features, feature_descriptions):\n arr_count = feature_desc[2]\n if arr_count > 1:\n feature_columns += [f'{feature_name}-0.{i}' for i in range(1, arr_count)]\n else:\n feature_columns.append(feature_name)\n\n eid = dataset['eid'][:][~mask]\n data = numpy.concatenate([features, targets], axis=1)\n frame = pandas.DataFrame(data=data, columns=feature_columns + [self.phenotype_col], index=eid.squeeze(1) if len(eid.shape) == 2 else eid)\n return frame\n\n def load_train(self) -> pandas.DataFrame:\n return self._load(self.train)\n\n def load_val(self) -> pandas.DataFrame:\n return self._load(self.val)\n\n def load_test(self) -> pandas.DataFrame:\n return self._load(self.test)\n\n\nclass BinarySDLoader():\n def __init__(self, data_dir: str, split: str, phenotype_col: str, features: List[str], sd_code: int, na_as_false: False, array_agg_func='mean') -> None:\n \n self.dataset = zarr.open_group(os.path.join(data_dir, split), mode='r')\n self.train, self.val, self.test = self.dataset['train'], self.dataset['val'], self.dataset['test']\n self.columns = self.train.columns[:]\n self.na_as_false = na_as_false\n\n if '-' in phenotype_col:\n raise ValueError(f'- should not be in {phenotype_col}, we need only a field id without any assessments and array numbers')\n self.phenotype_col = phenotype_col\n self.sd_code = sd_code\n\n for f in features:\n if '-' in f:\n raise ValueError(f'Feature {f} should not contain -, we need only a field id without any assessments and array numbers')\n\n if array_agg_func is not None and array_agg_func not in ['mean', 'max']:\n raise ValueError(f'array_agg_func must be one of the [None, \"mean\", \"max\"]')\n self.agg_func = array_agg_func\n \n self.features = features\n\n def _find_assessment_columns(self, column):\n to_find = column + '-'\n found = []\n for i, col in enumerate(self.columns):\n if col[:len(to_find)] == to_find:\n found.append(i)\n \n return found\n\n def _find_arrayed_target_columns(self, column):\n to_find = column + '-'\n found = [[] for i in range(3)] # number of assessments\n for i, col in enumerate(self.columns):\n if col[:len(to_find)] == to_find:\n assessment = int(col[len(to_find)])\n if assessment >= len(found):\n continue \n found[assessment].append(i)\n \n return found\n\n def _process_chunk(self, chunk, target_cols, feature_descriptions):\n codes = []\n codes_na = []\n for i, assessment_cols in enumerate(target_cols):\n targets = chunk[:, assessment_cols]\n code_na = numpy.isnan(targets).sum(axis=1) == targets.shape[1]\n codes_na.append(code_na.reshape(-1, 1))\n code_in = (targets == self.sd_code).sum(axis=1) > 0\n codes.append(code_in.reshape(-1, 1))\n\n codes = numpy.hstack(codes)\n codes_na = numpy.hstack(codes_na)\n\n codes_na = (codes_na.sum(axis=1) == codes_na.shape[1])\n assessment_indices = numpy.argmax(codes, axis=1)\n true_target = (codes.sum(axis=1) > 0).astype(int).reshape(-1, 1)\n\n features = []\n for f_cols, _, f_array_count in feature_descriptions:\n f = chunk[:, f_cols]\n if len(f_cols) == 1: # for features like sex\n features.append(f.reshape(-1, 1))\n elif self.agg_func is None and f_array_count > 1:\n features.append(f)\n else:\n features.append(f[numpy.arange(f.shape[0]), assessment_indices].reshape(-1, 1))\n \n features = numpy.hstack(features)\n if self.na_as_false:\n true_target[codes_na] = 0\n return true_target, features, codes_na\n else:\n return true_target[~codes_na], features[~codes_na], codes_na\n\n def _load_binary_sd_target(self, dataset, feature_descriptions):\n target_cols = self._find_arrayed_target_columns(self.phenotype_col)\n data = dataset['dataset']\n targets, all_features, mask = [], [], []\n for start in range(0, data.shape[0], data.chunks[0]):\n\n chunk = data[start:start + data.chunks[0]]\n target, features, codes_na = self._process_chunk(chunk, target_cols, feature_descriptions)\n targets.append(target)\n all_features.append(features)\n mask.append(codes_na)\n\n targets = numpy.vstack(targets)\n all_features = numpy.vstack(all_features)\n mask = numpy.hstack(mask)\n return targets, all_features, mask\n\n def _load(self, dataset):\n feature_descriptions = [self._find_assessment_columns(feature) for feature in self.features]\n targets, features, mask = self._load_binary_sd_target(dataset, feature_descriptions)\n if self.na_as_false:\n eid = dataset['eid'][:]\n else:\n eid = dataset['eid'][:][~mask]\n\n feature_columns = []\n for feature_name, feature_desc in zip(self.features, feature_descriptions):\n arr_count = feature_desc[2]\n if arr_count > 1:\n feature_columns += [f'{feature_name}-0.{i}' for i in range(1, arr_count)]\n else:\n feature_columns.append(feature_name)\n data = numpy.concatenate([features, targets], axis=1)\n frame = pandas.DataFrame(data=data, columns=feature_columns + [self.phenotype_col], index=eid.squeeze(1) if len(eid.shape) == 2 else eid)\n return frame\n\n def load_train(self) -> pandas.DataFrame:\n return self._load(self.train)\n\n def load_val(self) -> pandas.DataFrame:\n return self._load(self.val)\n\n def load_test(self) -> pandas.DataFrame:\n return self._load(self.test)\n"
]
| [
[
"numpy.concatenate",
"numpy.isnan",
"numpy.nanmean",
"numpy.argmax",
"numpy.arange",
"numpy.hstack",
"numpy.column_stack",
"numpy.nanmax",
"numpy.vstack"
]
]
|
hoanghungict/TensorFlow-Deep-Learning-Projects | [
"27d0bd456ea1e28823d4a03b996776a8107bb2a1"
]
| [
"Chapter05/6_rnn_stock_price_tensorboard.py"
]
| [
"import datetime\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom evaluate_ts import evaluate_ts\nfrom tensorflow.contrib import rnn\nfrom tools import fetch_stock_price, format_dataset\n\ntf.reset_default_graph()\ntf.set_random_seed(101)\nnp.random.seed(101)\n\n# Settings for the dataset creation\nsymbol = \"MSFT\"\ntime_dimension = 20\ntrain_size = 252\ntest_size = 252 - time_dimension\n\n# Settings for tensorflow\ntf_logdir = \"./logs/tf/stock_price_lstm\"\nos.makedirs(tf_logdir, exist_ok=1)\nlearning_rate = 0.001\noptimizer = tf.train.AdagradOptimizer\nn_epochs = 100\nn_embeddings = 128\n\nif True: # prod values\n learning_rate = 0.1\n n_epochs = 5000\n n_embeddings = 256\n\n# Fetch the values, and prepare the train/test split\nstock_values = fetch_stock_price(symbol, datetime.date(2015, 1, 1), datetime.date(2016, 12, 31))\nminibatch_cos_X, minibatch_cos_y = format_dataset(stock_values, time_dimension)\n\ntrain_X = minibatch_cos_X[:train_size, :].astype(np.float32)\ntrain_y = minibatch_cos_y[:train_size].reshape((-1, 1)).astype(np.float32)\ntest_X = minibatch_cos_X[train_size:, :].astype(np.float32)\ntest_y = minibatch_cos_y[train_size:].reshape((-1, 1)).astype(np.float32)\n\ntrain_X_ts = train_X[:, :, np.newaxis]\ntest_X_ts = test_X[:, :, np.newaxis]\n\n# Here, the tensorflow code\nX_tf = tf.placeholder(\"float\", shape=(None, time_dimension, 1), name=\"X\")\ny_tf = tf.placeholder(\"float\", shape=(None, 1), name=\"y\")\n\n\n# Here the model: a LSTM\ndef RNN(x, weights, biases):\n with tf.name_scope(\"LSTM\"):\n x_ = tf.unstack(x, time_dimension, 1)\n lstm_cell = rnn.BasicLSTMCell(n_embeddings)\n outputs, _ = rnn.static_rnn(lstm_cell, x_, dtype=tf.float32)\n return tf.add(biases, tf.matmul(outputs[-1], weights))\n\n\n# Store layers weight & bias\nweights = tf.Variable(tf.truncated_normal([n_embeddings, 1], mean=0.0, stddev=10.0), name=\"weights\")\nbiases = tf.Variable(tf.zeros([1]), name=\"bias\")\n\n# Model, cost and optimizer\ny_pred = RNN(X_tf, weights, biases)\nwith tf.name_scope(\"cost\"):\n cost = tf.reduce_mean(tf.square(y_tf - y_pred))\n train_op = optimizer(learning_rate).minimize(cost)\n tf.summary.scalar(\"MSE\", cost)\n\nwith tf.name_scope(\"mae\"):\n mae_cost = tf.reduce_mean(tf.abs(y_tf - y_pred))\n tf.summary.scalar(\"mae\", mae_cost)\n\nwith tf.Session() as sess:\n writer = tf.summary.FileWriter(tf_logdir, sess.graph)\n merged = tf.summary.merge_all()\n sess.run(tf.global_variables_initializer())\n\n # For each epoch, the whole training set is feeded into the tensorflow graph\n for i in range(n_epochs):\n summary, train_cost, _ = sess.run([merged, cost, train_op], feed_dict={X_tf: train_X_ts, y_tf: train_y})\n writer.add_summary(summary, i)\n if i%100 == 0:\n print(\"Training iteration\", i, \"MSE\", train_cost)\n\n # After the training, let's check the performance on the test set\n test_cost, y_pr = sess.run([cost, y_pred], feed_dict={X_tf: test_X_ts, y_tf: test_y})\n print(\"Test dataset:\", test_cost)\n\n # Evaluate the results\n evaluate_ts(test_X, test_y, y_pr)\n\n # How does the predicted look like?\n plt.plot(range(len(stock_values)), stock_values, 'b')\n plt.plot(range(len(stock_values)-test_size, len(stock_values)), y_pr, 'r--')\n plt.xlabel(\"Days\")\n plt.ylabel(\"Predicted and true values\")\n plt.title(\"Predicted (Red) VS Real (Blue)\")\n plt.show()\n\n# Now, launch the tensorboard with the command:\n# tensorboard --logdir=./logs/tf/stock_price_lstm\n# and open your browser to: http://127.0.0.1:6006\n"
]
| [
[
"tensorflow.contrib.rnn.BasicLSTMCell",
"tensorflow.matmul",
"tensorflow.global_variables_initializer",
"tensorflow.set_random_seed",
"tensorflow.abs",
"tensorflow.zeros",
"tensorflow.summary.scalar",
"tensorflow.Session",
"matplotlib.pyplot.title",
"tensorflow.truncated_normal",
"tensorflow.placeholder",
"tensorflow.name_scope",
"tensorflow.contrib.rnn.static_rnn",
"tensorflow.summary.merge_all",
"matplotlib.pyplot.show",
"tensorflow.unstack",
"numpy.random.seed",
"matplotlib.pyplot.xlabel",
"tensorflow.reset_default_graph",
"matplotlib.pyplot.ylabel",
"tensorflow.summary.FileWriter",
"tensorflow.square"
]
]
|
chensming/HeyConstitution | [
"f208127d4428d887d427f6f73360aa02e944229b"
]
| [
"mini-program/model/imageClassification/TongueClassification.py"
]
| [
"import torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\nfrom torchvision import datasets, transforms, models\nfrom torchvision.datasets import ImageFolder\nimport torchvision.models as models\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport os\n\nbatch_size = 100\ntest_batch_size = 10\nmini_batch_size = 10\nepochs = 20\nlr = 0.005\ngamma = 0.7\nno_cuda = True\nseed = 1\nlog_interval = 10\nsave_model = True\nclass_num=8\ncriterion = nn.CrossEntropyLoss() # 交叉熵\nbase_dirs = ['pinghe/', 'qixu/', 'qiyu/', 'shire/', 'tanshi/', 'xueyu/', 'yangxu/', 'yinxu/']\nclasses = ['pinghe', 'qixu', 'qiyu', 'shire', 'tanshi', 'xueyu', 'yangxu', 'yinxu']\ntrain_root = \"./drive/My Drive/data/dataset3/mask/\"\ntest_root = \"./drive/My Drive/data/dataset3/mask/\"\nmodel_path = 'res01.pt'\nimg_path = '1_1.jpg'\n\n\n\n\n\ndef default_loader(path):\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n preprocess = transforms.Compose([transforms.ToTensor(), normalize])\n\n img_pil = Image.open(path)\n img_tensor = preprocess(img_pil)\n return img_tensor\n\n\nclass MyDataset(Dataset):\n def __init__(self, root, base_dirs, loader=default_loader):\n self.image_label_list, self.image_path_list = self.read_file(root, base_dirs)\n self.root = root\n self.base_dirs = base_dirs\n self.len = len(self.image_label_list)\n self.loader = loader\n\n def __getitem__(self, i):\n index = i\n label = self.image_label_list[index]\n path = self.image_path_list[index]\n img = self.loader(path)\n return img, label\n\n def __len__(self):\n data_len = len(self.image_label_list)\n return data_len\n\n # 返回标签列表、目录列表\n def read_file(self, root, base_dirs):\n image_label_list = []\n image_path_list = []\n\n for i in range(len(base_dirs)):\n dir = root + base_dirs[i]\n listImages = [dir + Image for Image in (os.listdir(dir))]\n for file in listImages:\n image_label_list.append(i)\n image_path_list.append(file)\n\n return image_label_list, image_path_list\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, padding=1)\n self.conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, padding=1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(91875, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\n\ndef train(model, device, train_loader, optimizer, epoch):\n model.train()\n tot_loss = 0.0\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n\n # forward backward\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n tot_loss += loss.item()\n\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n tot_loss = 0.0\n\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0.0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target)\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef main():\n use_cuda = not no_cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n torch.manual_seed(seed)\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n train_loader = torch.utils.data.DataLoader(MyDataset(train_root, base_dirs),\n batch_size=batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(MyDataset(test_root, base_dirs),\n batch_size=test_batch_size, shuffle=True, **kwargs)\n '''\n model =Net().to(device) \n '''\n\n model = models.resnet18(pretrained=True)\n model.fc = nn.Linear(512, 8)\n model = model.to(device)\n\n # 交叉熵\n criterion = nn.CrossEntropyLoss()\n # momentumSGD\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)\n\n # scheduler = StepLR(optimizer, step_size=1, gamma=gamma)\n for epoch in range(1, epochs + 1):\n train(model, device, train_loader, optimizer, epoch)\n test(model, device, test_loader)\n # scheduler.step()\n\n if save_model:\n torch.save(model.state_dict(), \"res01.pt\")\n\n\ndef predict(model_path, img_path, class_name):\n # 环境\n use_cuda = not no_cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n preprocess = transforms.Compose([transforms.ToTensor(), normalize])\n img_pil = Image.open(img_path)\n img = preprocess(img_pil)\n img = img.unsqueeze(0)\n img = img.to(device)\n\n model = torch.load(model_path)\n model = model.to(device)\n model.eval()\n with torch.no_grad():\n py = model(img)\n _, predicted = torch.max(py, 1) # 获取分类结果\n classIndex_ = predicted[0]\n\n print('预测结果:类{} {}'.format(classIndex_, class_name[classIndex_]))\n\n\n\n\n\n\n\n\n"
]
| [
[
"torch.nn.Linear",
"torch.device",
"torch.flatten",
"torch.max",
"torch.no_grad",
"torch.nn.functional.log_softmax",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"torch.load",
"torch.nn.functional.relu",
"torch.nn.functional.max_pool2d",
"torch.nn.Dropout2d",
"torch.nn.CrossEntropyLoss"
]
]
|
leomariga/py3DRanSAC | [
"9eda322a6ec81074ad171185e44f2a7e8ec2d583"
]
| [
"pyransac3d/plane.py"
]
| [
"import random\n\nimport numpy as np\n\n\nclass Plane:\n \"\"\"\n Implementation of planar RANSAC.\n\n Class for Plane object, which finds the equation of a infinite plane using RANSAC algorithim.\n\n Call `fit(.)` to randomly take 3 points of pointcloud to verify inliers based on a threshold.\n\n \n\n ---\n \"\"\"\n\n def __init__(self):\n self.inliers = []\n self.equation = []\n\n def fit(self, pts, thresh=0.05, minPoints=100, maxIteration=1000):\n \"\"\"\n Find the best equation for a plane.\n\n :param pts: 3D point cloud as a `np.array (N,3)`.\n :param thresh: Threshold distance from the plane which is considered inlier.\n :param maxIteration: Number of maximum iteration which RANSAC will loop over.\n :returns:\n - `self.equation`: Parameters of the plane using Ax+By+Cy+D `np.array (1, 4)`\n - `self.inliers`: points from the dataset considered inliers\n\n ---\n \"\"\"\n n_points = pts.shape[0]\n best_eq = []\n best_inliers = []\n\n for it in range(maxIteration):\n\n # Samples 3 random points\n id_samples = random.sample(range(0, n_points), 3)\n pt_samples = pts[id_samples]\n\n # We have to find the plane equation described by those 3 points\n # We find first 2 vectors that are part of this plane\n # A = pt2 - pt1\n # B = pt3 - pt1\n\n vecA = pt_samples[1, :] - pt_samples[0, :]\n vecB = pt_samples[2, :] - pt_samples[0, :]\n\n # Now we compute the cross product of vecA and vecB to get vecC which is normal to the plane\n vecC = np.cross(vecA, vecB)\n\n # The plane equation will be vecC[0]*x + vecC[1]*y + vecC[0]*z = -k\n # We have to use a point to find k\n vecC = vecC / np.linalg.norm(vecC)\n k = -np.sum(np.multiply(vecC, pt_samples[1, :]))\n plane_eq = [vecC[0], vecC[1], vecC[2], k]\n\n # Distance from a point to a plane\n # https://mathworld.wolfram.com/Point-PlaneDistance.html\n pt_id_inliers = [] # list of inliers ids\n dist_pt = (\n plane_eq[0] * pts[:, 0] + plane_eq[1] * pts[:, 1] + plane_eq[2] * pts[:, 2] + plane_eq[3]\n ) / np.sqrt(plane_eq[0] ** 2 + plane_eq[1] ** 2 + plane_eq[2] ** 2)\n\n # Select indexes where distance is biggers than the threshold\n pt_id_inliers = np.where(np.abs(dist_pt) <= thresh)[0]\n if len(pt_id_inliers) > len(best_inliers):\n best_eq = plane_eq\n best_inliers = pt_id_inliers\n self.inliers = best_inliers\n self.equation = best_eq\n\n return self.equation, self.inliers\n"
]
| [
[
"numpy.linalg.norm",
"numpy.multiply",
"numpy.abs",
"numpy.sqrt",
"numpy.cross"
]
]
|
royvelich/deep-signature | [
"48f05d3e8482f92094158ed4265fcdf2d76569f2"
]
| [
"applets/playgrounds/plots_playground.py"
]
| [
"# python peripherals\nimport random\nimport os\nimport sys\nimport math\nsys.path.insert(1, os.path.join(sys.path[0], '../..'))\n\n# numpy\nimport numpy\n\n# pandas\nimport pandas\n\n# ipython\nfrom IPython.display import display, HTML\n\n# matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport matplotlib.lines\n\n# pytorch\nimport torch\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.utils.data.sampler import SequentialSampler\nfrom torch.utils.data import DataLoader\n\n# deep signature\nfrom deep_signature.utils import utils\nfrom deep_signature.data_generation.curve_generation import LevelCurvesGenerator\nfrom deep_signature.data_manipulation import curve_processing\nfrom deep_signature.nn.datasets import DeepSignatureTupletsDataset\nfrom deep_signature.nn.networks import DeepSignatureArcLengthNet\nfrom deep_signature.nn.networks import DeepSignatureCurvatureNet\nfrom deep_signature.nn.losses import ContrastiveLoss\nfrom deep_signature.nn.trainers import ModelTrainer\nfrom deep_signature.data_manipulation import curve_sampling\nfrom deep_signature.data_manipulation import curve_processing\nfrom deep_signature.linalg import euclidean_transform\nfrom deep_signature.linalg import affine_transform\n\n# common\nfrom common import settings\nfrom common import utils as common_utils\n\n# notebooks\nfrom notebooks.utils import utils as notebook_utils\n\n\n\n\n\n\n# plt.style.use(\"dark_background\")\n\ntransform_type = 'euclidean'\n\nif transform_type == 'euclidean':\n level_curves_arclength_tuplets_dir_path = settings.level_curves_euclidean_arclength_tuplets_dir_path\n level_curves_arclength_tuplets_results_dir_path = settings.level_curves_euclidean_arclength_tuplets_results_dir_path\nelif transform_type == 'equiaffine':\n level_curves_arclength_tuplets_dir_path = settings.level_curves_equiaffine_arclength_tuplets_dir_path\n level_curves_arclength_tuplets_results_dir_path = settings.level_curves_equiaffine_arclength_tuplets_results_dir_path\nelif transform_type == 'affine':\n level_curves_arclength_tuplets_dir_path = settings.level_curves_affine_arclength_tuplets_dir_path\n level_curves_arclength_tuplets_results_dir_path = settings.level_curves_affine_arclength_tuplets_results_dir_path\n\nif transform_type == 'euclidean':\n level_curves_curvature_tuplets_dir_path = settings.level_curves_euclidean_curvature_tuplets_dir_path\n level_curves_curvature_tuplets_results_dir_path = settings.level_curves_euclidean_curvature_tuplets_results_dir_path\nelif transform_type == 'equiaffine':\n level_curves_curvature_tuplets_dir_path = settings.level_curves_equiaffine_curvature_tuplets_dir_path\n level_curves_curvature_tuplets_results_dir_path = settings.level_curves_equiaffine_curvature_tuplets_results_dir_path\nelif transform_type == 'affine':\n level_curves_curvature_tuplets_dir_path = settings.level_curves_affine_curvature_tuplets_dir_path\n level_curves_curvature_tuplets_results_dir_path = settings.level_curves_affine_curvature_tuplets_results_dir_path\n\n\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# constants\ntrue_arclength_colors = ['#FF8C00', '#444444']\npredicted_arclength_colors = ['#AA0000', '#00AA00']\nsample_colors = ['#AA0000', '#00AA00']\ncurve_colors = ['#AA0000', '#00AA00']\n\nlimit = 5\nstep = 60\ncomparison_curves_count = 1\n\nsection_supporting_points_count = 20\nneighborhood_supporting_points_count = 3\n\ncurvature_sample_points = 2*neighborhood_supporting_points_count + 1\narclength_sample_points = section_supporting_points_count\n\nsampling_ratio = 0.2\nanchors_ratio = 0.2\n\ndevice = torch.device('cuda')\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# constants\ntrue_arclength_colors = ['#FF8C00', '#444444']\npredicted_arclength_colors = ['#AA0000', '#00AA00']\nsample_colors = ['#AA0000', '#00AA00']\ncurve_colors = ['#AA0000', '#00AA00', '#0000AA']\nlimit = 1\nfactor_extraction_limit = -2\n# step = settings.arclength_default_supporting_points_count - 1\nstep = 10\ncomparison_curves_count = 2\nsampling_ratio = 0.6\nanchors_ratio = 0.2\n\ndevice = torch.device('cuda')\n\n# if we're in the equiaffine case, snap 'step' to the closest mutiple of 3 (from above)\n# if transform_type == \"equiaffine\":\n# step = int(3 * numpy.ceil(step / 3))\n\n# package settings\ntorch.set_default_dtype(torch.float64)\nnumpy.random.seed(60)\n\n# create models\narclength_model = DeepSignatureArcLengthNet(sample_points=settings.arclength_default_supporting_points_count).cuda()\ncurvature_model = DeepSignatureCurvatureNet(sample_points=settings.curvature_default_sample_points_count).cuda()\n\n# load arclength model state\nlatest_subdir = common_utils.get_latest_subdirectory(level_curves_arclength_tuplets_results_dir_path)\nresults = numpy.load(f\"{latest_subdir}/results.npy\", allow_pickle=True).item()\narclength_model.load_state_dict(torch.load(results['model_file_path'], map_location=device))\narclength_model.eval()\n\n# load curvature model state\nlatest_subdir = common_utils.get_latest_subdirectory(level_curves_curvature_tuplets_results_dir_path)\nresults = numpy.load(f\"{latest_subdir}/results.npy\", allow_pickle=True).item()\ncurvature_model.load_state_dict(torch.load(results['model_file_path'], map_location=device))\ncurvature_model.eval()\n\n# load curves (+ shuffle)\n# curves_train = LevelCurvesGenerator.load_curves(dir_path=settings.level_curves_dir_path_train)\n# curves_validation = LevelCurvesGenerator.load_curves(dir_path=settings.level_curves_dir_path_validation)\ncurves = LevelCurvesGenerator.load_curves(dir_path=settings.level_curves_dir_path_test)\n\n# print(len(curves_train))\n# print(len(curves_validation))\n# print(len(curves_test))\n\nnumpy.random.shuffle(curves)\ncurves_limited = curves[:limit]\nfactor_extraction_curves = curves[factor_extraction_limit:]\n\n# create color map\ncolor_map = plt.get_cmap('rainbow', limit)\n\n# generate curve records\ncurve_records = notebook_utils.generate_curve_records(\n arclength_model=arclength_model,\n curvature_model=curvature_model,\n curves=curves_limited,\n factor_extraction_curves=factor_extraction_curves,\n transform_type=transform_type,\n comparison_curves_count=comparison_curves_count,\n sampling_ratio=sampling_ratio,\n anchors_ratio=anchors_ratio,\n step=step,\n neighborhood_supporting_points_count=settings.curvature_default_supporting_points_count,\n section_supporting_points_count=settings.arclength_default_supporting_points_count)\n\n# notebook_utils.plot_curve_signature_comparisons(\n# curve_records=curve_records,\n# curve_colors=curve_colors)\n#\n# notebook_utils.plot_curve_arclength_records(\n# curve_records=curve_records,\n# true_arclength_colors=true_arclength_colors,\n# predicted_arclength_colors=predicted_arclength_colors,\n# sample_colors=sample_colors)\n"
]
| [
[
"torch.device",
"numpy.random.seed",
"matplotlib.pyplot.get_cmap",
"numpy.load",
"numpy.random.shuffle",
"torch.load",
"torch.set_default_dtype"
]
]
|
NeuroDataDesign/pyautomagic | [
"f03af3f4f0cf859c11d03623d9d2b51f1546b6d7"
]
| [
"tests/pyautomagic/test_performEOGRegression.py"
]
| [
"import logging\n\nimport numpy as np\nimport pytest\n\n\ndef performEOGRegression(eeg, eog, *args):\n \"\"\"Performs linear regression to remove EOG artifact from the EEG data\n\n Parameters\n ----------\n eeg: np.ndarray\n EEG signal with the EOG artifacts\n eog: np.ndarray\n EOG signal\n *args\n variable length argument list\n\n Returns\n -------\n clean_eeg: np.ndarray\n Cleaned EEG signal from EEG artifacts\n\n \"\"\"\n # checks if EOG Regression should be skipped or not depending on the function arguments\n if len(args[0]) == 0:\n logging.warning('EOG regression skipped')\n return\n\n size_eeg = np.shape(eeg)\n size_eog = np.shape(eog)\n dimension = len(size_eog)\n # resizing the EOG array so that its pseudoinverse can be calculated\n if dimension == 1:\n eog.resize((1, size_eog[0]))\n eeg_t = np.transpose(eeg)\n eog_t = np.transpose(eog)\n # performing pseudoinverse\n pseudoinv = np.linalg.pinv(np.dot(np.transpose(eog_t), eog_t))\n inv = np.dot(pseudoinv, np.transpose(eog_t))\n subtract_eog = np.dot(eog_t, np.dot(inv, eeg_t))\n # subtracting the EOG noise from the EEG signal\n clean_eeg = np.transpose(np.subtract(eeg_t, subtract_eog))\n return clean_eeg\n\n\ndef test_performEOGRegression():\n eeg=np.array([[1, 2, 4, 0.8], [0.1, 0.2, 0.4, 0.9]])\n eog=np.array([[9, 10, 11, 12], [10, 12, 3, 4]])\n assert np.array_equal(np.round(performEOGRegression(eeg, eog, {\"PerformEOGRegression\": \"Yes\"}), 2), np.round(np.array([[-0.42197603, 0.47275097, 1.71501431, -1.64957357], [-0.07695577, 0.04392939, -0.2369535, 0.23831638]]),2))\n\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.shape",
"numpy.subtract",
"numpy.transpose"
]
]
|
iArunava/IMDB-Sentiment-Analysis-using-PyTorch | [
"cb026d32a928f8a21ed20c726bd86285e7bc0b04"
]
| [
"train.py"
]
| [
"import os\nimport subprocess\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom string import punctuation\nfrom collections import Counter\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom SentimentRNN import SentimentRNN\nfrom test import test\n\ndef train(FLAGS):\n # download the files if needed\n print ('[INFO]Checking if the data is present...')\n if not os.path.exists(FLAGS.dataset + 'labels.txt') or \\\n not os.path.exists(FLAGS.dataset + 'reviews.txt'):\n print ('[INFO]Files not found!')\n print ('[INFO]Starting to download files...')\n subprocess.call(['./dataset/download.sh'])\n print ('[INFO]Files downloaded successfully!')\n else:\n print ('[INFO]Files found!!')\n\n # read the data\n print ('[INFO]Reading the datasets...')\n with open(FLAGS.dataset + 'reviews.txt', 'r') as f:\n reviews = f.read()\n with open(FLAGS.dataset + 'labels.txt', 'r') as f:\n labels = f.read()\n print ('[INFO]Dataset read!')\n \n print ('[INFO]Starting to preprocess the data...')\n # preprocess data\n features, encoded_labels, vocab_to_int = preprocess(reviews, labels, FLAGS.seq_length)\n print ('[INFO]Preprocessing data complete')\n \n \n # Split the data\n print ('[INFO]Splitting the Dataset into Train, Validation and Test set')\n # Get the split fraction\n split_frac = FLAGS.split_frac\n\n # Get the data for training set\n tr_idx = int(len(features) * split_frac)\n train_x, train_y = features[: tr_idx], np.array(encoded_labels[: tr_idx])\n\n # Get the data for validation set\n va_idx = tr_idx + int(len(features[tr_idx : ]) * 0.5)\n val_x, val_y = features[tr_idx : va_idx], np.array(encoded_labels[tr_idx : va_idx])\n\n # Get the test data\n test_x, test_y = features[va_idx : ], np.array(encoded_labels[va_idx : ])\n print ('[INFO]Splitting the dataset complete!')\n\n # Create DataLoaders\n print ('[INFO]Creating DataLoaders from each train, val and test dataset')\n ## Create the TensorDatasets\n train_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))\n valid_data = TensorDataset(torch.from_numpy(val_x), torch.from_numpy(val_y))\n test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))\n\n ## DataLoaders\n batch_size = FLAGS.batch_size\n train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)\n valid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)\n test_loader = DataLoader(valid_data, shuffle=False, batch_size=batch_size)\n \n print ('[INFO]Creating DataLoaders Complete!')\n\n # Set the hyperparamters\n print ('[INFO]Setting Hyperparameters...')\n vocab_size = len(vocab_to_int) + 1\n output_size = 1\n embedding_dim = FLAGS.embedding_dim\n hidden_dim = FLAGS.hidden_dim\n n_layers = FLAGS.n_layers\n lr = FLAGS.learning_rate\n epochs = FLAGS.epochs\n counter = 0\n print_every = FLAGS.print_every\n clip = FLAGS.clip\n print ('[INFO]Hyperparameters set successfully!')\n \n # Instantiate the network\n print ('[INFO] Instatiating the network')\n net = SentimentRNN(vocab_size, embedding_dim, hidden_dim, n_layers)\n print (net)\n print ('[INFO]Model Instantiated!')\n\n # Setup loss and optimizer\n criterion = nn.BCELoss()\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n print ('[INFO]Loss and Optimizer set!')\n\n test(net, test_loader, criterion, optimizer, batch_size)\n ### Training Process ###\n print ('[INFO] Starting Training...')\n\n # Move the model to cuda if is_available\n if (net.train_on_gpu):\n net.cuda()\n\n # Since we are Training\n net.train()\n\n for e in range(epochs):\n # Initialize the hidden state\n h = net.init_hidden(batch_size)\n\n # batch loop\n for inputs, labels in train_loader:\n counter += 1\n\n # Moving the inputs and labels to cuda\n if (net.train_on_gpu):\n inputs, labels = inputs.cuda(), labels.cuda()\n\n\n # Creating new variables for the hidden state\n h = tuple([each.data for each in h])\n\n # zero accumulated gradients\n net.zero_grad()\n\n # Get the output\n output, h = net(inputs, h)\n\n # Calculate the loss and perform backprop\n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n\n # Clip the gradients\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n optimizer.step()\n \n print ('.', end='')\n\n # Loss stats\n if counter % print_every == 0:\n # Get validation loss\n val_h = net.init_hidden(batch_size)\n val_losses = []\n net.eval()\n for inputs, labels in valid_loader:\n\n val_h = tuple([each.data for each in val_h])\n\n if (net.train_on_gpu):\n inputs, labels = inputs.cuda(), labels.cuda()\n\n output, val_h = net(inputs, val_h)\n val_loss = criterion(output.squeeze(), labels.float())\n\n val_losses.append(val_loss.item())\n\n net.train()\n \n print ()\n print (\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:6f}...\".format(loss.item()),\n \"Val_Loss: {:6f}\".format(np.mean(val_losses)))\n\n \n print ()\n print ('[INFO]Training Process Complete!')\n\n print ('[INFO]Starting Testing process...')\n test(net, test_loader, criterion, optimizer, batch_size)\n print ('[INFO]Testing process complete!')\n\n\n\ndef preprocess(reviews, labels, seq_length):\n # Making all the characters lowercase to ease for model understanding\n reviews = reviews.lower()\n\n # Getting rid of all the punctuations in the reviews\n all_text = ''.join([c for c in reviews if c not in punctuation])\n\n # Create reviews list by splitting with newlines\n reviews_split = all_text.split('\\n')\n\n # Join all reviews with a ' '\n all_text = ' '.join(reviews_split)\n\n # Now create a list of words by splitting by ' ' to create the vocabulary\n words = all_text.split()\n\n # Build a dictionary that maps words to integers\n # Count occurance of each word\n vocab_count = Counter(words)\n # Sort the vocab in the decreasing order of the times each word is used\n vocab = sorted(vocab_count, key=vocab_count.get, reverse=True)\n # Assign integers to each word\n vocab_to_int = {word : ii for ii, word in enumerate(vocab, 1)}\n\n # Tokenize each review\n reviews_ints = []\n for review in reviews_split:\n reviews_ints.append([vocab_to_int[word] for word in review.split()])\n\n print ('[INFO] Unique words in the vocab: {}'.format(len(vocab_to_int)))\n\n # Encoding the labels\n encoded_labels = [1 if label == 'positive' else 0 for label in labels.split('\\n')]\n\n # Remove outliers\n # Removing 0 length reviews\n # Getting the idxs for non 0 length reviews\n non_zero_idx = [ii for ii, review in enumerate(reviews_ints) if len(review) != 0]\n # Removing 0 length reviews\n reviews_ints = [reviews_ints[ii] for ii in non_zero_idx]\n encoded_labels = [encoded_labels[ii] for ii in non_zero_idx]\n\n print ('[INFO]Number of reviews left after removing 0 length reviews {}'.format(len(non_zero_idx)))\n\n # Pad the features\n features = pad_features(reviews_ints, seq_length)\n\n # A few tests to make life easy\n assert len(features) == len(reviews_ints)\n assert len(features[0]) == seq_length\n\n return features, encoded_labels, vocab_to_int\n\n\ndef pad_features(reviews_ints, seq_length):\n \"\"\"\n Return features of reviews_ints, where each review is padded with 0s or truncated\n to the input seq_length\n \"\"\"\n features = np.zeros((len(reviews_ints), seq_length), dtype=int)\n for ii, rint in enumerate(reviews_ints):\n features[ii, -len(rint) : ] = rint[: seq_length]\n\n return features\n\ndef save_model(net, model_name='SentimentRNNmodel', extra='1'):\n checkpoint = {\n 'epoch' : 4,\n 'state_dict': net.state_dict()\n }\n torch.save(checkpoint, model_name + str(extra) + '.pth')\n print ('Model saved successfully!')\n"
]
| [
[
"numpy.array",
"numpy.mean",
"torch.from_numpy",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss"
]
]
|
raymondng76/sgnlp | [
"f09eada90ef5b1ee979901e5c14413d32e758049"
]
| [
"sgnlp/models/lsr/train.py"
]
| [
"\"\"\"\nTraining or finetuning a LSR model on DocRED dataset.\n\"\"\"\nimport argparse\nimport csv\nimport json\nimport logging\nimport os\n\nimport numpy as np\nimport torch\nfrom sklearn import metrics\nfrom torch.utils.data.dataloader import DataLoader, default_collate\nfrom transformers import set_seed\n\nfrom .config import LsrConfig\nfrom .modeling import LsrModel, LsrModelOutput\nfrom .preprocess import LsrPreprocessor\nfrom .utils import h_t_idx_generator\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass LsrMetrics:\n \"\"\"\n For calculating metrics for LsrModel.\n Computes precision, recall, f1, auc for precision vs recall, and the optimal prediction threshold (theta).\n This is modified from the original.\n The original additionally computes an ignore score which ignores facts seen in training set.\n \"\"\"\n\n def __init__(self, num_relations):\n self.num_relations = num_relations\n\n self.test_result = []\n self.total_recall = 0\n\n def add_batch(self, model_output: LsrModelOutput, batch_data):\n predict_re = torch.sigmoid(model_output.prediction)\n predict_re = predict_re.data.cpu().numpy()\n\n for i, label in enumerate(batch_data['labels']):\n self.total_recall += len(label)\n\n vertex_set_length = batch_data['entity_num_list'][i] # the number of entities in each instance.\n for j, (h_idx, t_idx) in enumerate(h_t_idx_generator(vertex_set_length)):\n for r in range(1, self.num_relations):\n result_tuple = (\n (h_idx, t_idx, r) in label,\n float(predict_re[i, j, r]),\n )\n self.test_result.append(result_tuple)\n\n def compute(self, input_theta=None):\n \"\"\"\n Computes metrics based on data added so far.\n\n Args:\n input_theta (`optional`, `float`):\n Prediction threshold. Provide a value between 0 to 1 if you want to compute the precision and recall\n for that specific threshold. Otherwise the optimal based on f1 score will be computed for you.\n \"\"\"\n # Sorts in descending order by predicted value\n self.test_result.sort(key=lambda x: x[1], reverse=True)\n\n precision = []\n recall = []\n correct = 0\n w = 0\n if self.total_recall == 0:\n self.total_recall = 1 # for test\n\n for i, item in enumerate(self.test_result):\n correct += item[0]\n recall.append(float(correct) / (i + 1))\n precision.append(float(correct) / self.total_recall)\n if input_theta is not None and item[1] > input_theta:\n w = i\n\n precision = np.asarray(precision, dtype='float32')\n recall = np.asarray(recall, dtype='float32')\n f1_arr = (2 * precision * recall / (precision + recall + 1e-20))\n auc = metrics.auc(x=precision, y=recall)\n\n if input_theta is None:\n f1 = f1_arr.max()\n f1_pos = f1_arr.argmax()\n best_theta = self.test_result[f1_pos][1]\n return best_theta, f1, precision[f1_pos], recall[f1_pos], auc\n else:\n return input_theta, f1_arr[w], precision[w], recall[w], auc\n\n\nclass DocredDataset(torch.utils.data.Dataset):\n def __init__(self, json_file, preprocessor):\n self.data = json.load(open(json_file))\n self.preprocessed_data = preprocessor(self.data)\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n instance = {}\n for key in self.preprocessed_data.keys():\n instance[key] = self.preprocessed_data[key][idx]\n return instance\n\n\ndef lsr_collate_fn(batch):\n \"\"\"\n Manually processes labels and uses default for the rest.\n \"\"\"\n labels = []\n for instance in batch:\n labels_instance = instance.pop(\"labels\")\n labels.append(labels_instance)\n\n collated_data = default_collate(batch)\n\n collated_data[\"labels\"] = labels\n return collated_data\n\n\nclass MyAdagrad(torch.optim.Optimizer):\n \"\"\"\n Modification of the Adagrad optimizer that allows to specify an initial\n accumulator value. This mimics the behavior of the default Adagrad implementation\n in Tensorflow. The default PyTorch Adagrad uses 0 for initial accumulator value.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-2)\n lr_decay (float, optional): learning rate decay (default: 0)\n init_accu_value (float, optional): initial accumulater value.\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n \"\"\"\n\n def __init__(self, params, lr=1e-2, lr_decay=0, init_accu_value=0.1, weight_decay=0):\n defaults = dict(lr=lr, lr_decay=lr_decay, init_accu_value=init_accu_value, \\\n weight_decay=weight_decay)\n super(MyAdagrad, self).__init__(params, defaults)\n\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = 0\n state['sum'] = torch.ones(p.data.size()).type_as(p.data) * \\\n init_accu_value\n\n def share_memory(self):\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['sum'].share_memory_()\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n\n grad = p.grad.data\n state = self.state[p]\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n if p.grad.data.is_sparse:\n raise RuntimeError(\"weight_decay option is not compatible with sparse gradients \")\n grad = grad.add(group['weight_decay'], p.data)\n\n clr = group['lr'] / (1 + (state['step'] - 1) * group['lr_decay'])\n\n if p.grad.data.is_sparse:\n grad = grad.coalesce() # the update is non-linear so indices must be unique\n grad_indices = grad._indices()\n grad_values = grad._values()\n size = torch.Size([x for x in grad.size()])\n\n def make_sparse(values):\n constructor = type(p.grad.data)\n if grad_indices.dim() == 0 or values.dim() == 0:\n return constructor()\n return constructor(grad_indices, values, size)\n\n state['sum'].add_(make_sparse(grad_values.pow(2)))\n std = state['sum']._sparse_mask(grad)\n std_values = std._values().sqrt_().add_(1e-10)\n p.data.add_(-clr, make_sparse(grad_values / std_values))\n else:\n state['sum'].addcmul_(1, grad, grad)\n std = state['sum'].sqrt().add_(1e-10)\n p.data.addcdiv_(-clr, grad, std)\n\n return loss\n\n\ndef get_optimizer(name, parameters, lr, l2=0):\n if name == 'sgd':\n return torch.optim.SGD(parameters, lr=lr, weight_decay=l2)\n elif name in ['adagrad', 'myadagrad']:\n # use custom adagrad to allow for init accumulator value\n return MyAdagrad(parameters, lr=lr, init_accu_value=0.1, weight_decay=l2)\n elif name == 'adam':\n return torch.optim.Adam(parameters, lr, weight_decay=l2)\n elif name == 'adamw':\n return torch.optim.AdamW(parameters, lr=lr, weight_decay=l2)\n elif name == 'adamax':\n return torch.optim.Adamax(parameters, weight_decay=l2)\n elif name == 'adadelta':\n return torch.optim.Adadelta(parameters, lr=lr, weight_decay=l2)\n else:\n raise Exception(\"Unsupported optimizer: {}\".format(name))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Train a relation extraction model based on latent structure refinement.\")\n\n parser.add_argument(\"--train_file\", type=str, required=True, help=\"A json file containing the training data.\")\n parser.add_argument(\"--validation_file\", type=str, default=None, help=\"A json file containing the validation data.\")\n parser.add_argument(\"--output_dir\", type=str, default=None, help=\"Output directory path.\")\n parser.add_argument(\"--metadata_dir\", type=str, required=True, help=\"Path to docred metadata directory.\")\n\n # Model arguments\n parser.add_argument(\"--model_weights_path\", type=str, default=None,\n help=\"Provide a path to model weights if you want to finetune from a checkpoint.\")\n parser.add_argument(\"--model_config_path\", type=str, default=None,\n help=\"Provide a config if you want to override the defaults. \"\n \"To use bert encoder layer, specify in config file.\")\n parser.add_argument(\"--pretrained_embeddings_path\", type=str, default=None,\n help=\"Provide a path to pretrained embeddings if you want to want to use them.\")\n\n # Training arguments\n parser.add_argument('--lr', type=float, default=1e-3, help='Applies to sgd and adagrad.')\n parser.add_argument('--lr_decay', type=float, default=0.98, help='Learning rate decay rate.')\n parser.add_argument('--decay_epoch', type=int, default=20, help='Decay learning rate after this epoch.')\n parser.add_argument('--evaluate_epoch', type=int, default=30, help='Evaluate after this epoch.')\n parser.add_argument('--optim', choices=['sgd', 'adagrad', 'adam', 'adamw', 'adamax'], default='adam',\n help='Choice of optimizer.')\n parser.add_argument('--weight_decay', type=float, default=0, help='L2 weight decay.')\n parser.add_argument('--num_epoch', type=int, default=200, help='Number of total training epochs.')\n parser.add_argument('--batch_size', type=int, default=20, help='Training batch size.')\n parser.add_argument('--max_grad_norm', type=float, default=5.0, help='Gradient clipping.')\n\n parser.add_argument('--seed', type=int, default=0, help=\"A seed for reproducible training.\")\n parser.add_argument('--use_gpu', type=bool, default=True, help=\"Whether you want to use GPU for training.\")\n\n parser.add_argument('--use_wandb', type=bool, default=False, help=\"Whether to use wandb to monitor training.\")\n parser.add_argument('--wandb_run_name', type=str, default=None, help=\"Wandb run name.\")\n\n args = parser.parse_args()\n\n return args\n\n\ndef train_model(args):\n logger.info(f\"Training arguments: {vars(args)}\")\n\n # Defaults to cpu if gpu is unavailable\n device = torch.device(\"cuda\") if args.use_gpu and torch.cuda.is_available() else torch.device(\"cpu\")\n logger.info(f\"Using device: {device}\")\n\n # Make output dir, save training args, create metrics files\n if args.output_dir is not None:\n os.makedirs(args.output_dir, exist_ok=True)\n os.makedirs(os.path.join(args.output_dir, 'best_f1'), exist_ok=True)\n os.makedirs(os.path.join(args.output_dir, 'final'), exist_ok=True)\n\n with open(os.path.join(args.output_dir, 'training_args.json'), \"w\") as fp:\n json.dump(vars(args), fp, sort_keys=True, indent=4)\n\n # create metric output files\n train_metrics_file = os.path.join(args.output_dir, 'train_metrics.csv')\n val_metrics_file = os.path.join(args.output_dir, 'val_metrics.csv')\n fieldnames = ['epoch', 'loss', 'best_theta', 'f1', 'precision', 'recall', 'auc']\n\n with open(train_metrics_file, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n\n with open(val_metrics_file, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n\n if args.seed is not None:\n set_seed(args.seed)\n\n # Load config if provided else initialize with defaults\n if args.model_config_path:\n config = LsrConfig.from_json_file(json_file=args.model_config_path)\n else:\n config = LsrConfig()\n\n # Load model weights if provided\n if args.model_weights_path:\n model = LsrModel.from_pretrained(args.model_weights_path, config=config)\n else:\n model = LsrModel(config)\n\n if args.use_wandb:\n import wandb\n wandb.init(project=\"lsr\", name=args.wandb_run_name)\n wandb.watch(model, log=\"all\")\n\n # Note: this will override the provided model weights\n if args.pretrained_embeddings_path is not None and not config.use_bert:\n pretrained_embeddings = np.load(args.pretrained_embeddings_path)\n model.load_pretrained_word_embedding(pretrained_word_embedding=pretrained_embeddings)\n\n # Set to training device\n model.to(device=device)\n\n # Load dataset\n # Set to cpu initially (for preprocessing entire dataset first)\n logger.info(\"Preprocessing datasets...\")\n rel2id_path = os.path.join(args.metadata_dir, \"rel2id.json\")\n word2id_path = os.path.join(args.metadata_dir, \"word2id.json\")\n ner2id_path = os.path.join(args.metadata_dir, \"ner2id.json\")\n train_preprocessor = LsrPreprocessor(rel2id_path=rel2id_path, word2id_path=word2id_path, ner2id_path=ner2id_path,\n is_train=True, device=torch.device(\"cpu\"), config=config)\n val_preprocessor = LsrPreprocessor(rel2id_path=rel2id_path, word2id_path=word2id_path, ner2id_path=ner2id_path,\n device=torch.device(\"cpu\"), config=config)\n train_dataset = DocredDataset(json_file=args.train_file, preprocessor=train_preprocessor)\n val_dataset = DocredDataset(json_file=args.validation_file, preprocessor=val_preprocessor)\n\n train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=args.batch_size, collate_fn=lsr_collate_fn)\n val_dataloader = DataLoader(val_dataset, shuffle=True, batch_size=args.batch_size, collate_fn=lsr_collate_fn)\n\n # Optimizer and parameters\n if config.use_bert:\n other_params = [p for name, p in model.named_parameters() if\n p.requires_grad and not name.startswith(\"bert\")]\n optimizer = torch.optim.Adam([\n {\"params\": other_params, \"lr\": args.lr},\n {\"params\": model.bert.parameters(), \"lr\": 1e-5},\n ], lr=args.lr)\n else:\n parameters = [p for p in model.parameters() if p.requires_grad]\n optimizer = get_optimizer(args.optim, parameters, args.lr)\n\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, args.lr_decay)\n\n best_f1 = 0\n\n for epoch in range(args.num_epoch):\n logger.info(f\"Epoch: {epoch + 1}/{args.num_epoch}, lr: {optimizer.param_groups[0]['lr']}\")\n\n train_metrics = LsrMetrics(num_relations=config.num_relations)\n total_epoch_train_loss = 0\n model.train()\n for step, batch in enumerate(train_dataloader):\n for key, value in batch.items():\n if isinstance(value, torch.Tensor):\n batch[key] = value.to(device=device)\n\n outputs = model(**batch)\n\n # Backpropagation\n loss = outputs.loss\n # TODO: Remove debug logs below\n if np.isnan(loss.item()):\n logger.info(\"Skipping backward prop.\")\n continue\n\n optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n optimizer.step()\n\n # Track metrics\n total_epoch_train_loss += loss.item()\n train_metrics.add_batch(model_output=outputs, batch_data=batch)\n\n # Compute metrics and log at end of epoch\n best_theta, f1, precision, recall, auc = train_metrics.compute()\n avg_epoch_train_loss = total_epoch_train_loss / (step + 1)\n logger.info(f\"Train loss: {avg_epoch_train_loss:.3f}, best theta: {best_theta:.3f}, \"\n f\"f1: {f1:.3f}, precision: {precision:.3f}, recall: {recall:.3f}, auc: {auc:.5f}\")\n\n if args.use_wandb:\n wandb.log({\n \"train_loss\": avg_epoch_train_loss,\n \"train_best_theta\": best_theta,\n \"train_f1\": f1,\n \"train_precision\": precision,\n \"train_recall\": recall,\n \"train_auc\": auc\n }, step=epoch)\n\n # Write train metrics\n if args.output_dir is not None:\n with open(train_metrics_file, 'a') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writerow({'epoch': epoch + 1, 'loss': avg_epoch_train_loss, 'best_theta': best_theta, 'f1': f1,\n 'precision': precision, 'recall': recall, 'auc': auc})\n\n if epoch + 1 >= args.evaluate_epoch:\n val_metrics = LsrMetrics(num_relations=config.num_relations)\n total_epoch_val_loss = 0\n model.eval()\n for step, batch in enumerate(val_dataloader):\n for key, value in batch.items():\n if isinstance(value, torch.Tensor):\n batch[key] = value.to(device=device)\n\n outputs = model(**batch)\n\n # Track metrics\n total_epoch_val_loss += loss.item()\n val_metrics.add_batch(model_output=outputs, batch_data=batch)\n\n # Compute metrics and log at end of epoch\n best_theta, f1, precision, recall, auc = val_metrics.compute()\n avg_epoch_val_loss = total_epoch_val_loss / (step + 1)\n logger.info(f\"Val loss: {avg_epoch_val_loss:.3f}, best theta: {best_theta:.3f}, \"\n f\"f1: {f1:.3f}, precision: {precision:.3f}, recall: {recall:.3f}, auc: {auc:.5f}\")\n\n if args.use_wandb:\n wandb.log({\n \"val_loss\": avg_epoch_val_loss,\n \"val_best_theta\": best_theta,\n \"val_f1\": f1,\n \"val_precision\": precision,\n \"val_recall\": recall,\n \"val_auc\": auc\n }, step=epoch)\n\n # Write val metrics\n if args.output_dir is not None:\n with open(val_metrics_file, 'a') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writerow(\n {'epoch': epoch + 1, 'loss': avg_epoch_val_loss, 'best_theta': best_theta, 'f1': f1,\n 'precision': precision, 'recall': recall, 'auc': auc})\n\n # Save best model so far\n if args.output_dir is not None and f1 > best_f1:\n logger.info(\"Best f1 so far, saving model.\")\n best_f1 = f1\n model.save_pretrained(os.path.join(args.output_dir, 'best_f1'))\n\n if epoch + 1 >= args.decay_epoch:\n if args.optim == 'adam' and optimizer.param_groups[0]['lr'] > 1e-4:\n scheduler.step()\n\n # Save final model\n if args.output_dir is not None:\n logger.info(\"Saving final model.\")\n model.save_pretrained(os.path.join(args.output_dir, 'final'))\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n train_model(args)\n"
]
| [
[
"torch.sigmoid",
"torch.device",
"torch.optim.AdamW",
"torch.utils.data.dataloader.DataLoader",
"numpy.asarray",
"torch.optim.SGD",
"torch.optim.lr_scheduler.ExponentialLR",
"numpy.load",
"torch.optim.Adam",
"torch.optim.Adadelta",
"torch.optim.Adamax",
"torch.cuda.is_available",
"sklearn.metrics.auc",
"torch.utils.data.dataloader.default_collate"
]
]
|
kaniblu/pytorch-skipthoughts | [
"6ce13492dc6d4f0378ead8ec5aadb151cc79d93f"
]
| [
"src/torchst/model.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.init as I\nimport torch.nn.utils.rnn as R\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom torchsru import SRU\n\n\ndef pad_batch(x, n, after=True):\n pad_shape = x.data.shape[1:]\n pad = x.data.new(n, *pad_shape).zero_()\n pad = Variable(pad)\n l = [x, pad] if after else [pad, x]\n x = torch.cat(l)\n\n return x\n\n\ndef init_gru(cell, gain=1):\n cell.reset_parameters()\n\n # orthogonal initialization of recurrent weights\n for _, hh, _, _ in cell.all_weights:\n for i in range(0, hh.size(0), cell.hidden_size):\n I.orthogonal(hh[i:i + cell.hidden_size], gain=gain)\n\n\ndef init_lstm(cell, gain=1):\n init_gru(cell, gain)\n\n # positive forget gate bias (Jozefowicz et al., 2015)\n for _, _, ih_b, hh_b in cell.all_weights:\n l = len(ih_b)\n ih_b[l // 4:l // 2].data.fill_(1.0)\n hh_b[l // 4:l // 2].data.fill_(1.0)\n\n\ndef init_rnn_cell(cell, gain=1):\n if isinstance(cell, nn.LSTM):\n init_lstm(cell, gain)\n elif isinstance(cell, nn.GRU):\n init_gru(cell, gain)\n else:\n cell.reset_parameters()\n\n\ndef flatten_hidden_direction(h, directions=1):\n if directions < 2:\n return h\n else:\n layers = h.size(0) // directions\n batch_size, hidden_size = h.size()[1:]\n h = h.view(layers, directions, batch_size, hidden_size)\n h = h.permute(0, 2, 3, 1).contiguous()\n h = h.view(layers, batch_size, directions * hidden_size)\n\n return h.contiguous()\n\n\nclass CombinedCell(nn.Module):\n def __init__(self, rnn_cell_cls, input_size, hidden_size, num_layers,\n dropout, batch_first):\n super(CombinedCell, self).__init__()\n\n self.rnn_cell_cls = rnn_cell_cls\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.dropout = dropout\n self.batch_first = batch_first\n\n params = dict(\n input_size=input_size,\n num_layers=num_layers,\n dropout=dropout,\n batch_first=batch_first\n )\n\n self.uni_hidden_size = hidden_size // 2\n self.bi_hidden_size = hidden_size // 2 // 2\n\n self.uni_cell = rnn_cell_cls(\n bidirectional=False,\n hidden_size=self.uni_hidden_size,\n **params\n )\n\n self.bi_cell = rnn_cell_cls(\n bidirectional=True,\n hidden_size=self.bi_hidden_size,\n **params\n )\n\n def reset_parameters(self):\n init_rnn_cell(self.uni_cell)\n init_rnn_cell(self.bi_cell)\n\n def forward(self, *args, **kwargs):\n o_u, h_u = self.uni_cell(*args, **kwargs)\n o_b, h_b = self.bi_cell(*args, **kwargs)\n\n assert (isinstance(h_u, tuple) and isinstance(h_b, tuple)) or \\\n (not isinstance(h_u, tuple) and not isinstance(h_b, tuple))\n\n if isinstance(h_u, tuple):\n # flatten direction\n h_b = [flatten_hidden_direction(x, 2) for x in h_b]\n h = tuple(torch.cat([x_u, x_b], 2) for x_u, x_b in zip(h_u, h_b))\n else:\n h_b = flatten_hidden_direction(h_b, 2)\n h = torch.cat([h_u, h_b], 2)\n\n assert (isinstance(o_u, R.PackedSequence) and isinstance(o_b, R.PackedSequence)) or \\\n (not isinstance(o_u, R.PackedSequence) and not isinstance(o_b, R.PackedSequence))\n\n is_packed = isinstance(o_u, R.PackedSequence)\n\n if is_packed:\n o_u, lens_u = R.pad_packed_sequence(o_u, self.batch_first)\n o_b, _ = R.pad_packed_sequence(o_b, self.batch_first)\n else:\n lens_u = None\n\n o = torch.cat([o_u, o_b], 2)\n\n if is_packed:\n o = R.pack_padded_sequence(o, lens_u, self.batch_first)\n\n return o, h\n\n\nclass MultiContextSkipThoughts(nn.Module):\n @staticmethod\n def get_cell_cls(rnn_cell):\n if rnn_cell == \"lstm\":\n cell_cls = nn.LSTM\n elif rnn_cell == \"gru\":\n cell_cls = nn.GRU\n elif rnn_cell == \"sru\":\n cell_cls = SRU\n else:\n raise ValueError(\"Unrecognized rnn cell: {}\".format(rnn_cell))\n\n return cell_cls\n\n def __init__(self, vocab, word_dim, hidden_dim, n_layers, n_decoders,\n encoder_direction=\"uni\",\n batch_first=True,\n dropout_prob=0.0,\n reverse_encoder=False,\n encoder_cell=\"gru\",\n decoder_cell=\"gru\",\n conditional_decoding=False):\n super(MultiContextSkipThoughts, self).__init__()\n\n self.is_cuda = False\n self.vocab = vocab\n self.vocab_size = vocab_size = len(vocab)\n self.word_dim = word_dim\n self.hidden_dim = hidden_dim\n self.reverse_encoder = reverse_encoder\n self.conditional_decoding = conditional_decoding\n self.encoder_direction = encoder_direction\n\n if self.encoder_direction == \"uni\":\n self.bidirectional = False\n elif self.encoder_direction == \"bi\":\n self.bidirectional = True\n elif self.encoder_direction == \"combine\":\n self.bidirectional = None\n else:\n raise ValueError(\"Unrecognized direction: {}\".format(\n self.encoder_direction\n ))\n\n self.encoder_cell_type = encoder_cell\n self.decoder_cell_type = decoder_cell\n self.batch_first = batch_first\n self.dropout_prob = dropout_prob\n self.n_layers = n_layers\n self.n_decoders = n_decoders\n self.bos_idx = vocab[vocab.bos]\n self.eos_idx = vocab[vocab.eos]\n self.pad_idx = vocab[vocab.pad]\n self.n_directions = 2 if self.bidirectional else 1\n self.encoder_hidden_size = hidden_dim // self.n_directions // n_layers\n self.decoder_hidden_size = hidden_dim // n_layers\n\n self.embeddings = nn.Embedding(vocab_size, word_dim,\n padding_idx=self.pad_idx)\n self.W_i = nn.Linear(word_dim, hidden_dim)\n self.W_o = nn.Linear(self.encoder_hidden_size * self.n_directions,\n word_dim)\n\n enc_cls = self.get_cell_cls(encoder_cell)\n dec_cls = self.get_cell_cls(decoder_cell)\n\n encoder_params = dict(\n input_size=self.hidden_dim,\n hidden_size=self.encoder_hidden_size,\n num_layers=self.n_layers,\n dropout=dropout_prob,\n batch_first=True\n )\n\n if self.encoder_direction != \"combine\":\n encoder_params[\"bidirectional\"] = self.bidirectional\n self.encoder = enc_cls(**encoder_params)\n else:\n self.encoder = CombinedCell(\n enc_cls, **encoder_params\n )\n\n if self.conditional_decoding:\n dec_input_size = hidden_dim * 2\n else:\n dec_input_size = hidden_dim\n\n for i in range(n_decoders):\n decoder = dec_cls(input_size=dec_input_size,\n hidden_size=self.decoder_hidden_size,\n num_layers=n_layers,\n bidirectional=False,\n dropout=dropout_prob,\n batch_first=True)\n\n setattr(self, \"decoder{}\".format(i), decoder)\n\n def cuda(self, *args, **kwargs):\n ret = super(MultiContextSkipThoughts, self).cuda(*args, **kwargs)\n\n self.is_cuda = True\n\n return ret\n\n def cpu(self, *args, **kwargs):\n ret = super(MultiContextSkipThoughts, self).cpu(*args, **kwargs)\n\n self.is_cuda = False\n\n return ret\n\n def reset_parameters(self):\n I.normal(self.embeddings.weight.data, mean=0, std=0.01)\n I.xavier_normal(self.W_i.weight.data)\n I.xavier_normal(self.W_o.weight.data)\n\n init_rnn_cell(self.encoder)\n\n for i in range(self.n_decoders):\n decoder = getattr(self, \"decoder{}\".format(i))\n init_rnn_cell(decoder)\n\n def compose_decoder_hidden(self, cell_type, c, batch_size):\n if cell_type == \"lstm\":\n h = c.data.new(self.n_layers,\n batch_size, self.decoder_hidden_size).zero_()\n h = Variable(h)\n\n return (h, c)\n elif cell_type == \"gru\":\n return c\n elif cell_type == \"sru\":\n return c\n else:\n raise ValueError(\"Unrecognized cell type: {}\".format(\n cell_type\n ))\n\n def extract_hidden_state(self, cell_type, h):\n if cell_type == \"lstm\":\n return h[1]\n elif cell_type == \"gru\":\n return h\n elif cell_type == \"sru\":\n return h\n else:\n raise ValueError(\"Unrecognized cell type: {}\".format(\n cell_type\n ))\n\n def encode(self, x, x_lens):\n x = self.embeddings(x)\n return self._encode_embed(x, x_lens)\n\n def encode_embed(self, x, x_lens):\n \"\"\"Encodes raw word embeddings\n\n Arguments:\n x: [batch_size, seq_len, word_dim] FloatTensor\n x_lens: [batch_size] LongTensor\n \"\"\"\n return self._encode_embed(x, x_lens)\n\n def _run_rnn_packed(self, cell, x, x_lens, h=None):\n x_packed = R.pack_padded_sequence(x, x_lens,\n batch_first=self.batch_first)\n\n # Following line does not improve memory usage or computation efficiency\n # as claimed by pyTorch warning messages\n # cell.flatten_parameters()\n\n if h is not None:\n output, h = cell(x_packed, h)\n else:\n output, h = cell(x_packed)\n\n output, _ = R.pad_packed_sequence(output, batch_first=self.batch_first)\n\n return output, h\n\n def reverse_sequence(self, x, x_lens):\n batch_size, seq_len, word_dim = x.size()\n\n inv_idx = Variable(torch.arange(seq_len - 1, -1, -1).long())\n shift_idx = Variable(torch.arange(0, seq_len).long())\n\n if x.is_cuda:\n inv_idx = inv_idx.cuda(x.get_device())\n shift_idx = shift_idx.cuda(x.get_device())\n\n inv_idx = inv_idx.unsqueeze(0).unsqueeze(-1).expand_as(x)\n shift_idx = shift_idx.unsqueeze(0).unsqueeze(-1).expand_as(x)\n shift = (seq_len + (-1 * x_lens)).unsqueeze(-1).unsqueeze(-1).expand_as(x)\n shift_idx = shift_idx + shift\n shift_idx = shift_idx.clamp(0, seq_len - 1)\n\n x = x.gather(1, inv_idx)\n x = x.gather(1, shift_idx)\n\n return x\n\n def _encode_embed(self, x, x_lens):\n batch_size, seq_len, word_embed = x.size()\n\n if self.reverse_encoder:\n x = self.reverse_sequence(x, x_lens)\n\n x = x.view(-1, self.word_dim)\n x = F.tanh(self.W_i(x))\n x_enc = x.view(-1, seq_len, self.hidden_dim)\n\n _, h_n = self._run_rnn_packed(self.encoder, x_enc, x_lens.data.tolist())\n h_n = self.extract_hidden_state(self.encoder_cell_type, h_n)\n h_n = h_n.transpose(1, 0).contiguous().view(-1, self.hidden_dim)\n\n return h_n\n\n def _decode(self, dec_idx, h, x, x_lens):\n h_enc = h\n batch_size, seq_len = x.size()\n\n decoder = getattr(self, \"decoder{}\".format(dec_idx))\n\n assert decoder is not None\n\n h = h.view(-1, self.n_layers, self.decoder_hidden_size)\n h = h.transpose(1, 0).contiguous()\n h = self.compose_decoder_hidden(self.decoder_cell_type, h, batch_size)\n\n x = self.embeddings(x)\n x = x.view(-1, self.word_dim)\n x = F.tanh(self.W_i(x))\n x = x.view(batch_size, seq_len, self.hidden_dim)\n\n if self.conditional_decoding:\n h_exp = h_enc.unsqueeze(1).expand_as(x)\n x = torch.cat([x, h_exp], 2)\n\n o, h = self._run_rnn_packed(decoder, x, x_lens.data.tolist(), h)\n\n if o.size(1) < seq_len:\n pad = o.data.new(o.size(0), seq_len - o.size(1), o.size(2)).fill_(0)\n pad = Variable(pad)\n o = torch.cat([o, pad], 1)\n\n o = o.contiguous()\n o = o.view(-1, self.decoder_hidden_size)\n o = self.W_o(o)\n logits = torch.mm(o, self.embeddings.weight.t())\n logits = logits.view(batch_size, seq_len, self.vocab_size)\n\n return logits\n\n def forward(self, x, x_lens, ys, ys_lens, xys_idx):\n x = self.embeddings(x)\n h = self._encode_embed(x, x_lens)\n\n if self.batch_first:\n ys = ys.transpose(1, 0)\n ys_lens = ys_lens.transpose(1, 0)\n xys_idx = xys_idx.transpose(1, 0)\n\n logits_list = []\n\n for dec_idx, (y, y_lens, xy_idx) in enumerate(\n zip(ys, ys_lens, xys_idx)):\n h_dec = torch.index_select(h, 0, xy_idx)\n logits = self._decode(dec_idx, h_dec, y, y_lens)\n\n nil_batches = len(h_dec) - len(logits)\n if nil_batches:\n logits = pad_batch(logits, nil_batches, True)\n\n logits_list.append(logits.unsqueeze(0))\n\n logits = torch.cat(logits_list)\n\n if self.batch_first:\n logits = logits.transpose(1, 0)\n\n return logits, h\n\n\nclass SkipThoughts(MultiContextSkipThoughts):\n def __init__(self, *args, **kwargs):\n super(SkipThoughts, self).__init__(*args, n_decoders=2, **kwargs)\n\n\ndef sequence_mask(lens, max_len=None):\n batch_size = lens.size(0)\n\n if max_len is None:\n max_len = lens.max().data[0]\n\n ranges = torch.arange(0, max_len).long()\n ranges = ranges.unsqueeze(0).expand(batch_size, max_len)\n ranges = Variable(ranges)\n\n if lens.data.is_cuda:\n ranges = ranges.cuda()\n\n lens_exp = lens.unsqueeze(1).expand_as(ranges)\n mask = ranges < lens_exp\n\n return mask\n\n\ndef compute_loss(logits, y, lens):\n batch_size, seq_len, vocab_size = logits.size()\n logits = logits.view(batch_size * seq_len, vocab_size)\n y = y.view(-1)\n\n logprobs = F.log_softmax(logits)\n losses = -torch.gather(logprobs, 1, y.unsqueeze(-1))\n losses = losses.view(batch_size, seq_len)\n mask = sequence_mask(lens, seq_len).float()\n losses = losses * mask\n loss_batch = losses.sum() / len(lens)\n loss_step = losses.sum() / lens.sum().float()\n\n return loss_batch, loss_step"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.init.orthogonal",
"torch.arange",
"torch.nn.init.xavier_normal",
"torch.autograd.Variable",
"torch.nn.functional.log_softmax",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.nn.init.normal",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.index_select",
"torch.nn.Embedding"
]
]
|
happyxuwork/neural-networks-and-deep-learning | [
"f20353d9ff076699908675f67ecd3d7285caf160"
]
| [
"fig/valley2.py"
]
| [
"\"\"\"valley2.py\n~~~~~~~~~~~~~\n\nPlots a function of two variables to minimize. The function is a\nfairly generic valley function.\n\nNote that this is a duplicate of valley.py, but omits labels on the\naxis. It's bad practice to duplicate in this way, but I had\nconsiderable trouble getting matplotlib to update a graph in the way I\nneeded (adding or removing labels), so finally fell back on this as a\nkludge solution.\n\n\"\"\"\n\n#### Libraries\n# Third party libraries\nfrom matplotlib.ticker import LinearLocator\n# Note that axes3d is not explicitly used in the code, but is needed\n# to register the 3d plot type correctly\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport numpy\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nX = numpy.arange(-1, 1, 0.1)\nY = numpy.arange(-1, 1, 0.1)\nX, Y = numpy.meshgrid(X, Y)\nZ = X ** 2 + Y ** 2\n\ncolortuple = ('w', 'b')\ncolors = numpy.empty(X.shape, dtype=str)\nfor x in xrange(len(X)):\n for y in xrange(len(Y)):\n colors[x, y] = colortuple[(x + y) % 2]\n\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,\n linewidth=0)\n\nax.set_xlim3d(-1, 1)\nax.set_ylim3d(-1, 1)\nax.set_zlim3d(0, 2)\nax.w_xaxis.set_major_locator(LinearLocator(3))\nax.w_yaxis.set_major_locator(LinearLocator(3))\nax.w_zaxis.set_major_locator(LinearLocator(3))\nax.text(1.79, 0, 1.62, \"$C$\", fontsize=20)\n\nplt.show()\n"
]
| [
[
"numpy.empty",
"matplotlib.pyplot.figure",
"matplotlib.ticker.LinearLocator",
"numpy.arange",
"matplotlib.pyplot.show",
"numpy.meshgrid"
]
]
|
jack9950/reports | [
"5b113ddfb57914936438b8e6e594be02956e26d6"
]
| [
"surveyemail.py"
]
| [
"import csv\nimport os\nfrom surveyemaildata import agent_list\nimport pandas as pd\nimport numpy as np\n\n\n\n# fileLocation = 'C:\\\\Users\\\\Jackson.Ndiho\\\\Documents\\\\Sales\\\\MTD Detail - Jackson_18633_1504894770_2017-09-01_2017-09-08.csv'\nfileLocation = 'C:\\\\Users\\\\Jackson.Ndiho\\\\Documents\\\\Sales\\\\sales-funnel.xlsx'\n\ndf = pd.read_excel(fileLocation)\n# print(df.head())\n\ndf[\"Status\"] = df[\"Status\"].astype(\"category\")\ndf[\"Status\"].cat.set_categories([\"won\",\"pending\",\"presented\",\"declined\"],inplace=True)\nprint(pd.pivot_table(df,index=[\"Name\"]))\n\n# # print('current directory: ', os.getcwd())\n# dataFile = open('C:\\\\Users\\\\Jackson.Ndiho\\\\Documents\\\\Sales\\\\MTD Detail - Jackson_18633_1504894770_2017-09-01_2017-09-08.csv')\n# fileReader = csv.reader(dataFile)\n# # print(list(fileReader))\n# # for row in fileReader:\n# # \tprint('Row #', str(fileReader.line_num), row[2], '\\n')\n\n# data = list(fileReader)\n# data.pop(0)\n# # print(data)\n\n# agentData = []\n\n# #After loop below, each agent Data item will have the format:\n# #[AgentName, (Overall Experience (CSAT), Agent Satisfaction (ASAT), \n# # Effort: Made Easy (CE)), Supervisor]\n# for row in data:\n# \tagentName = row[2].upper()\n# \tCSAT = int(row[7])\n# \tASAT = int(row[13])\n# \teffort = int(row[8])\n# \tSupervisor = agent_list[agentName]\n\n# \tagentData.append([agentName, CSAT, ASAT, effort, Supervisor])\n\n# # print(len(data))\n\n\n# agentData.sort()\n\n# # for agent in agentData:\n# # \tprint(agent)\n\n# overallExperience = []\n"
]
| [
[
"pandas.read_excel",
"pandas.pivot_table"
]
]
|
vincentlui/megae | [
"16b8d29377e3180447b03cb8f5120e9e086ad56d",
"16b8d29377e3180447b03cb8f5120e9e086ad56d"
]
| [
"envs/goalgan/ant_maze/__init__.py",
"envs/goalgridworld/goal_grid.py"
]
| [
"# Copyright (c) 2019, salesforce.com, inc.\n# All rights reserved.\n# SPDX-License-Identifier: MIT\n# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT\n\nfrom envs.goalgan.ant_maze.create_maze_env import create_maze_env\n\nimport gym\nimport numpy as np\nimport torch\nfrom gym.utils import seeding\n\nGOAL_GRID = [np.array([3.25, 3.25]), np.array([3.25, 3.75]), np.array([3.25, 4.25]), np.array([3.25, 4.75]), np.array([3.75, 3.25]), np.array([3.75, 3.75]), \nnp.array([3.75, 4.25]), np.array([3.75, 4.75]), np.array([4.25, 3.25]), np.array([4.25, 3.75]), np.array([4.25, 4.25]), np.array([4.25, 4.75]), \nnp.array([4.75, 3.25]), np.array([4.75, 3.75]), np.array([4.75, 4.25]), np.array([4.75, 4.75]), np.array([1.25, 3.25]), np.array([1.25, 3.75]), \nnp.array([1.25, 4.25]), np.array([1.25, 4.75]), np.array([1.75, 3.25]), np.array([1.75, 3.75]), np.array([1.75, 4.25]), np.array([1.75, 4.75]), \nnp.array([2.25, 3.25]), np.array([2.25, 3.75]), np.array([2.25, 4.25]), np.array([2.25, 4.75]), np.array([2.75, 3.25]), np.array([2.75, 3.75]), \nnp.array([2.75, 4.25]), np.array([2.75, 4.75]), np.array([3.25, 1.25]), np.array([3.25, 1.75]), np.array([3.25, 2.25]), np.array([3.25, 2.75]), \nnp.array([3.75, 1.25]), np.array([3.75, 1.75]), np.array([3.75, 2.25]), np.array([3.75, 2.75]), np.array([4.25, 1.25]), np.array([4.25, 1.75]), \nnp.array([4.25, 2.25]), np.array([4.25, 2.75]), np.array([4.75, 1.25]), np.array([4.75, 1.75]), np.array([4.75, 2.25]), np.array([4.75, 2.75]), \nnp.array([-0.75, 3.25]), np.array([-0.75, 3.75]), np.array([-0.75, 4.25]), np.array([-0.75, 4.75]), np.array([-0.25, 3.25]), np.array([-0.25, 3.75]), \nnp.array([-0.25, 4.25]), np.array([-0.25, 4.75]), np.array([0.25, 3.25]), np.array([0.25, 3.75]), np.array([0.25, 4.25]), np.array([0.25, 4.75]), \nnp.array([0.75, 3.25]), np.array([0.75, 3.75]), np.array([0.75, 4.25]), np.array([0.75, 4.75]), np.array([ 3.25, -0.75]), np.array([ 3.25, -0.25]), \nnp.array([3.25, 0.25]), np.array([3.25, 0.75]), np.array([ 3.75, -0.75]), np.array([ 3.75, -0.25]), np.array([3.75, 0.25]), np.array([3.75, 0.75]), \nnp.array([ 4.25, -0.75]), np.array([ 4.25, -0.25]), np.array([4.25, 0.25]), np.array([4.25, 0.75]), np.array([ 4.75, -0.75]), np.array([ 4.75, -0.25]), \nnp.array([4.75, 0.25]), np.array([4.75, 0.75]), np.array([ 1.25, -0.75]), np.array([ 1.25, -0.25]), np.array([1.25, 0.25]), np.array([1.25, 0.75]), \nnp.array([ 1.75, -0.75]), np.array([ 1.75, -0.25]), np.array([1.75, 0.25]), np.array([1.75, 0.75]), np.array([ 2.25, -0.75]), np.array([ 2.25, -0.25]), \nnp.array([2.25, 0.25]), np.array([2.25, 0.75]), np.array([ 2.75, -0.75]), np.array([ 2.75, -0.25]), np.array([2.75, 0.25]), np.array([2.75, 0.75]), \nnp.array([-0.75, -0.75]), np.array([-0.75, -0.25]), np.array([-0.75, 0.25]), np.array([-0.75, 0.75]), np.array([-0.25, -0.75]), np.array([-0.25, -0.25]), \nnp.array([-0.25, 0.25]), np.array([-0.25, 0.75]), np.array([ 0.25, -0.75]), np.array([ 0.25, -0.25]), np.array([0.25, 0.25]), np.array([0.25, 0.75]), \nnp.array([ 0.75, -0.75]), np.array([ 0.75, -0.25]), np.array([0.75, 0.25]), np.array([0.75, 0.75])]\n\nclass AntMazeEnv(gym.GoalEnv):\n \"\"\"Wraps the GoalGan Env in a gym goal env.\"\"\"\n def __init__(self, eval=False):\n\n\n self.done_env = False\n self.dist_threshold = 0.5\n state_dims = 30\n \n self.goal_dims = [0, 1]\n self.eval_dims = [0, 1]\n if eval:\n self.done_env = True\n\n self.maze = create_maze_env('AntMaze') # this returns a gym environment\n self.seed()\n self.max_steps = 500\n\n self.action_space = self.maze.action_space\n observation_space = gym.spaces.Box(-np.inf, np.inf, (state_dims,)) \n goal_space = gym.spaces.Box(-np.inf, np.inf, (len(self.goal_dims),)) # first few coords of state\n self.observation_space = gym.spaces.Dict({\n 'observation': observation_space,\n 'desired_goal': goal_space,\n 'achieved_goal': goal_space\n })\n self.num_steps = 0\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n self.maze.wrapped_env.seed(seed)\n return [seed]\n\n def sample_goal(self):\n idx = self.np_random.choice(len(GOAL_GRID))\n return GOAL_GRID[idx].astype(np.float32)\n\n def step(self, action):\n next_state, _, _, _ = self.maze.step(action)\n next_state = next_state.astype(np.float32)\n\n s_xy = next_state[self.goal_dims]\n reward = self.compute_reward(s_xy, self.g_xy, None)\n info = {}\n self.num_steps += 1\n \n is_success = np.allclose(0., reward)\n done = is_success and self.done_env\n info['is_success'] = is_success\n if self.num_steps >= self.max_steps and not done:\n done = True\n info['TimeLimit.truncated'] = True\n\n obs = {\n 'observation': next_state,\n 'achieved_goal': s_xy,\n 'desired_goal': self.g_xy,\n }\n \n return obs, reward, done, info\n\n def reset(self): \n self.num_steps = 0\n\n ## Not exactly sure why we are reseeding here, but it's what the SR env does\n _ = self.maze.wrapped_env.seed(self.np_random.randint(np.iinfo(np.int32).max))\n s = self.maze.reset().astype(np.float32)\n _ = self.maze.wrapped_env.seed(self.np_random.randint(np.iinfo(np.int32).max))\n self.g_xy = self.sample_goal()\n\n return {\n 'observation': s,\n 'achieved_goal': s[self.goal_dims],\n 'desired_goal': self.g_xy,\n }\n\n def render(self):\n self.maze.render()\n\n def compute_reward(self, achieved_goal, desired_goal, info):\n if len(achieved_goal.shape) == 2:\n ag = achieved_goal[:,self.eval_dims]\n dg = desired_goal[:,self.eval_dims]\n else:\n ag = achieved_goal[self.eval_dims]\n dg = desired_goal[self.eval_dims]\n d = np.linalg.norm(ag - dg, axis=-1)\n return -(d >= self.dist_threshold).astype(np.float32)",
"import os\nimport numpy as np\nimport random\nfrom enum import IntEnum\nimport matplotlib.pyplot as plt\n\nimport gym\nfrom gym import error, spaces\nfrom gym.utils import seeding\n\nclass GoalGridWorldEnv(gym.GoalEnv):\n \"\"\"\n A simple 2D grid world environment with goal-oriented reward.\n Compatible with the OpenAI GoalEnv class.\n Observations are a dict of 'observation', 'achieved_goal', and 'desired goal'\n \"\"\"\n\n class Actions(IntEnum):\n # Move\n left = 0\n down = 1\n right = 2\n up = 3\n\n class ObjectTypes(IntEnum):\n # Object types\n empty = 0\n agent = 1\n wall = 2\n lava = 3\n\n MOVE_DIRECTION = [[0,-1],[1,0],[0,1],[-1,0]] # up, right, down, left\n\n def __init__(self, grid_size=16, max_step=100, grid_file=None, random_init_loc=True, \\\n agent_loc_file=None, goal_file=None, seed=1337):\n # Action enumeration\n self.actions = GoalGridWorldEnv.Actions\n\n # Actions are discrete integer values\n self.action_space = spaces.Discrete(len(self.actions))\n\n # Object types\n self.objects = GoalGridWorldEnv.ObjectTypes\n\n # Whether to change initialization of the agent\n self.random_init_loc = random_init_loc\n\n # Environment configuration\n self.grid_size = grid_size\n self.max_step = max_step\n\n self.end_of_game = False\n\n if grid_file:\n curr_abs_path = os.path.dirname(os.path.abspath(__file__))\n rel_path = os.path.join(curr_abs_path, \"grid_samples\", grid_file)\n if os.path.exists(rel_path):\n grid_file = rel_path\n self.grid = np.loadtxt(grid_file, delimiter=',')\n # Overwrite grid size if necessary\n self.grid_size_0 = self.grid.shape[0]\n self.grid_size_1 = self.grid.shape[1]\n else:\n print(\"Cannot find path: {}\".format(rel_path))\n else:\n # Generate an empty grid\n self.grid = np.zeros((self.grid_size_0, self.grid_size_1), dtype=np.int)\n\n # Sample the agent\n self.goal_loc = self._sample_goal_loc()\n self.goal = np.copy(self.grid)\n self.goal[self.goal_loc[0], self.goal_loc[1]] = self.objects.agent\n\n if goal_file:\n # Load the goal_file, which is a 0/1 mask for where we can sample goals from\n curr_abs_path = os.path.dirname(os.path.abspath(__file__))\n rel_path = os.path.join(curr_abs_path, \"grid_samples\", goal_file)\n if os.path.exists(rel_path):\n goal_file = rel_path\n self.goal_mask = np.loadtxt(goal_file, delimiter=',')\n # Check that the size of the goal mask is the same as grid size\n assert(self.goal_mask.shape[0] == self.grid.shape[0])\n assert (self.goal_mask.shape[1] == self.grid.shape[1])\n else:\n print(\"Cannot find path: {}\".format(rel_path))\n else:\n self.goal_mask = None\n\n if agent_loc_file:\n # Load the goal_file, which is a 0/1 mask for where we can sample goals from\n curr_abs_path = os.path.dirname(os.path.abspath(__file__))\n rel_path = os.path.join(curr_abs_path, \"grid_samples\", agent_loc_file)\n if os.path.exists(rel_path):\n agent_loc_file = rel_path\n self.agent_mask = np.loadtxt(goal_file, delimiter=',')\n # Check that the size of the goal mask is the same as grid size\n assert (self.agent_mask.shape[0] == self.grid.shape[0])\n assert (self.agent_mask.shape[1] == self.grid.shape[1])\n else:\n print(\"Cannot find path: {}\".format(rel_path))\n else:\n self.agent_mask = None\n\n # Set agent initial location\n if self.random_init_loc:\n self.agent_pos = self._sample_agent_loc()\n else:\n self.agent_pos = [0,0]\n\n # Observations are dictionaries containing an\n # grid observation, achieved and desired goals\n observation_space = spaces.Box(\n low=0,\n high=1,\n shape=(self.grid_size_0, self.grid_size_1, len(self.objects)),\n dtype='uint8'\n )\n self.observation_space = spaces.Dict({\n 'observation': observation_space,\n 'desired_goal': observation_space,\n 'achieved_goal': observation_space\n })\n\n self.num_step = 0\n\n\n\n # Env methods\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def reset(self):\n self.end_of_game = False\n self.num_step = 0\n if self.random_init_loc:\n self.agent_pos = self._sample_goal_loc()\n else:\n self.agent_pos = [0,0]\n self.goal_loc = self._sample_goal_loc()\n self.goal = np.copy(self.grid)\n self.goal[self.goal_loc[0], self.goal_loc[1]] = self.objects.agent\n\n return self._get_obs()\n\n def step(self, action):\n \"\"\"\n Taking a step in the environment.\n\n :param action:\n :return:\n \"\"\"\n # assert self.action_space.contains(action)\n # Take action, get reward, get observation\n self._take_action(action)\n obs = self._get_obs()\n info = {}\n reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info)\n\n self.num_step += 1\n\n if reward == 1.0 or self.num_step == self.max_step or self.end_of_game:\n done = 1\n else:\n done = 0\n\n return obs, reward, done, info\n\n def _take_action(self, action):\n \"\"\"\n Performs the action on the grid. Updates the grid information.\n\n :param action:\n :return:\n \"\"\"\n # Move the agent in that direction\n new_agent_pos = self._get_new_position(action)\n\n # Check if this position is a wall\n if self.grid[new_agent_pos[0], new_agent_pos[1]] != self.objects.wall:\n self.agent_pos = new_agent_pos\n\n # Set end of game if agent goes into lava\n if self.grid[self.agent_pos[0],self.agent_pos[1]] == self.objects.lava:\n self.end_of_game = True\n\n return\n\n def _get_new_position(self, action):\n \"\"\"\n Apply the action to change the agent's position\n\n :param action:\n :return:\n \"\"\"\n new_agent_pos = [self.agent_pos[0] + self.MOVE_DIRECTION[action][0],\n self.agent_pos[1] + self.MOVE_DIRECTION[action][1]]\n\n # Check if the new location is out of boundary\n if new_agent_pos[0] < 0 or new_agent_pos[1] < 0 \\\n or new_agent_pos[0] > (self.grid_size_0 - 1) or new_agent_pos[1] > (self.grid_size_1 - 1):\n return self.agent_pos\n else:\n return new_agent_pos\n\n def _get_reward(self):\n if self.agent_pos[0] == self.goal_loc[0] and self.agent_pos[1] == self.goal_loc[1]:\n return 1.0\n else:\n return 0.0\n\n def _get_obs(self):\n \"\"\"\n Return the observation as a dictionary of observation and goals\n\n :return:\n \"\"\"\n obs = {\n 'observation': self._get_state(self.grid),\n 'desired_goal': self.one_hot(self.goal, len(self.objects)),\n 'achieved_goal': self._get_state(self.grid)\n }\n return obs\n\n def _get_state(self, grid, use_one_hot=True):\n \"\"\"\n Get the grid information.\n\n :return:\n \"\"\"\n # Convert to one-hot representation: [NxNxK] where N is the size of grid and K is number of object types\n state = np.copy(grid)\n\n # Set the agent's position on the grid\n state[self.agent_pos[0],self.agent_pos[1]] = self.objects.agent\n\n if use_one_hot:\n state = self.one_hot(state, len(self.objects))\n\n return state\n\n def _sample_goal(self):\n \"\"\"\n Sample an achievable state for the agent's goal\n\n :return:\n \"\"\"\n pass\n\n def _sample_goal_loc(self):\n \"\"\"\n Generate a goal location. Make sure that it is not a wall location,\n or is valid according to the goal_file\n :return:\n \"\"\"\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n\n if self.goal_mask is not None:\n # Make sure that the sampled goal is a valid goal according to the mask\n while self.goal_mask[coord_1, coord_2] != 1:\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n else:\n # Make sure that the sampled goal position is empty\n while self.grid[coord_1,coord_2] != self.objects.empty:\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n\n return coord_1, coord_2\n\n def _sample_agent_loc(self):\n \"\"\"\n Generate a agent location. Make sure that it is not a wall location,\n or is valid according to the agent_loc_file\n :return:\n \"\"\"\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n\n if self.agent_mask is not None:\n # Make sure that the sampled goal is a valid goal according to the mask\n while self.agent_mask[coord_1, coord_2] != 1:\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n else:\n # Make sure that the sampled goal position is empty\n while self.grid[coord_1,coord_2] != self.objects.empty:\n coord_1 = random.randint(0, self.grid_size_0 - 1) # TODO: Make it dependent on the seed\n coord_2 = random.randint(0, self.grid_size_1 - 1)\n\n return coord_1, coord_2\n\n def render(self, mode='human'):\n columns = 2\n rows = 1\n plt.clf()\n\n imgs = [self._get_state(self.grid, use_one_hot=False), self.goal]\n titles = [\"Observation\", \"Goal\"]\n for i in range(1, columns * rows + 1):\n ax = plt.subplot(rows, columns, i)\n ax.set_title(titles[i-1])\n plt.imshow(imgs[i-1])\n\n plt.figtext(0.5, 0.1, 'Time step: {}'.format(self.num_step), horizontalalignment='center')\n\n plt.pause(0.01)\n plt.clim(0, 10)\n plt.show(block=False)\n\n return\n\n def compute_reward(self, achieved_goal, desired_goal, info):\n \"\"\"Compute the step reward. This externalizes the reward function and makes\n it dependent on an a desired goal and the one that was achieved. If you wish to include\n additional rewards that are independent of the goal, you can include the necessary values\n to derive it in info and compute it accordingly.\n Args:\n achieved_goal (object): the goal that was achieved during execution\n desired_goal (object): the desired goal that we asked the agent to attempt to achieve\n info (dict): an info dictionary with additional information\n Returns:\n float: The reward that corresponds to the provided achieved goal w.r.t. to the desired\n goal. Note that the following should always hold true:\n ob, reward, done, info = env.step()\n assert reward == env.compute_reward(ob['achieved_goal'], ob['goal'], info)\n \"\"\"\n if np.sum((achieved_goal - desired_goal)**2) > 0:\n return 0.0\n else:\n return 1.0\n\n def one_hot(self, vec, size):\n flattened = vec.flatten()\n oh = np.eye(size)[flattened.astype(int)]\n oh = oh.reshape(self.grid_size_0, self.grid_size_1, size)\n return oh\n\n"
]
| [
[
"numpy.iinfo",
"numpy.allclose",
"numpy.array",
"numpy.linalg.norm"
],
[
"matplotlib.pyplot.clim",
"numpy.zeros",
"numpy.sum",
"numpy.copy",
"numpy.eye",
"numpy.loadtxt",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot"
]
]
|
ZeayW/graph-contrastive-learning | [
"b8952b677ec30110f8a616ba7162ae738d5d4052"
]
| [
"util/t-SNE.py"
]
| [
"# yellowbrick.text.tsne\n# Implements TSNE visualizations of documents in 2D space.\n#\n# Author: Benjamin Bengfort\n# Author: Rebecca Bilbro\n# Created: Mon Feb 20 06:33:29 2017 -0500\n#\n# Copyright (C) 2016 The scikit-yb developers\n# For license information, see LICENSE.txt\n#\n# ID: tsne.py [6aa9198] [email protected] $\n\n\"\"\"\nImplements TSNE visualizations of documents in 2D space.\n\"\"\"\n\n##########################################################################\n## Imports\n##########################################################################\n\nimport numpy as np\n\nfrom collections import defaultdict\n\nfrom yellowbrick.draw import manual_legend\nfrom yellowbrick.text.base import TextVisualizer\nfrom yellowbrick.style.colors import resolve_colors\nfrom yellowbrick.exceptions import YellowbrickValueError\n\nfrom sklearn.manifold import TSNE\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import TruncatedSVD, PCA\n\n##########################################################################\n## Quick Methods\n##########################################################################\n\n\ndef tsne(\n X,\n y=None,\n ax=None,\n decompose=\"svd\",\n decompose_by=50,\n labels=None,\n colors=None,\n colormap=None,\n alpha=0.7,\n show=True,\n **kwargs\n):\n \"\"\"\n Display a projection of a vectorized corpus in two dimensions using TSNE,\n a nonlinear dimensionality reduction method that is particularly well\n suited to embedding in two or three dimensions for visualization as a\n scatter plot. TSNE is widely used in text analysis to show clusters or\n groups of documents or utterances and their relative proximities.\n\n Parameters\n ----------\n\n X : ndarray or DataFrame of shape n x m\n A matrix of n instances with m features representing the corpus of\n vectorized documents to visualize with tsne.\n\n y : ndarray or Series of length n\n An optional array or series of target or class values for instances.\n If this is specified, then the points will be colored according to\n their class. Often cluster labels are passed in to color the documents\n in cluster space, so this method is used both for classification and\n clustering methods.\n\n ax : matplotlib axes\n The axes to plot the figure on.\n\n decompose : string or None\n A preliminary decomposition is often used prior to TSNE to make the\n projection faster. Specify `\"svd\"` for sparse data or `\"pca\"` for\n dense data. If decompose is None, the original data set will be used.\n\n decompose_by : int\n Specify the number of components for preliminary decomposition, by\n default this is 50; the more components, the slower TSNE will be.\n\n labels : list of strings\n The names of the classes in the target, used to create a legend.\n\n colors : list or tuple of colors\n Specify the colors for each individual class\n\n colormap : string or matplotlib cmap\n Sequential colormap for continuous target\n\n alpha : float, default: 0.7\n Specify a transparency where 1 is completely opaque and 0 is completely\n transparent. This property makes densely clustered points more visible.\n\n show : bool, default: True\n If True, calls ``show()``, which in turn calls ``plt.show()`` however you cannot\n call ``plt.savefig`` from this signature, nor ``clear_figure``. If False, simply\n calls ``finalize()``\n\n kwargs : dict\n Pass any additional keyword arguments to the TSNE transformer.\n\n Example\n --------\n >>> from yellowbrick.text.tsne import tsne\n >>> from sklearn.feature_extraction.text import TfidfVectorizer\n >>> from yellowbrick.datasets import load_hobbies\n >>> corpus = load_hobbies()\n >>> tfidf = TfidfVectorizer()\n >>> X = tfidf.fit_transform(corpus.data)\n >>> y = corpus.target\n >>> tsne(X, y)\n\n Returns\n -------\n visualizer: TSNEVisualizer\n Returns the fitted, finalized visualizer\n \"\"\"\n # Instantiate the visualizer\n visualizer = TSNEVisualizer(\n ax=ax,\n decompose=decompose,\n decompose_by=decompose_by,\n labels=labels,\n colors=colors,\n colormap=colormap,\n alpha=alpha,\n **kwargs\n )\n\n # Fit and transform the visualizer (calls draw)\n visualizer.fit(X, y, **kwargs)\n\n if show:\n visualizer.show()\n else:\n visualizer.finalize()\n\n # Return the visualizer object\n return visualizer\n\n##########################################################################\n## TSNEVisualizer\n##########################################################################\n\n\nclass TSNEVisualizer(TextVisualizer):\n \"\"\"\n Display a projection of a vectorized corpus in two dimensions using TSNE,\n a nonlinear dimensionality reduction method that is particularly well\n suited to embedding in two or three dimensions for visualization as a\n scatter plot. TSNE is widely used in text analysis to show clusters or\n groups of documents or utterances and their relative proximities.\n\n TSNE will return a scatter plot of the vectorized corpus, such that each\n point represents a document or utterance. The distance between two points\n in the visual space is embedded using the probability distribution of\n pairwise similarities in the higher dimensionality; thus TSNE shows\n clusters of similar documents and the relationships between groups of\n documents as a scatter plot.\n\n TSNE can be used with either clustering or classification; by specifying\n the ``classes`` argument, points will be colored based on their similar\n traits. For example, by passing ``cluster.labels_`` as ``y`` in ``fit()``, all\n points in the same cluster will be grouped together. This extends the\n neighbor embedding with more information about similarity, and can allow\n better interpretation of both clusters and classes.\n\n For more, see https://lvdmaaten.github.io/tsne/\n\n Parameters\n ----------\n\n ax : matplotlib axes\n The axes to plot the figure on.\n\n decompose : string or None, default: ``'svd'``\n A preliminary decomposition is often used prior to TSNE to make the\n projection faster. Specify ``\"svd\"`` for sparse data or ``\"pca\"`` for\n dense data. If None, the original data set will be used.\n\n decompose_by : int, default: 50\n Specify the number of components for preliminary decomposition, by\n default this is 50; the more components, the slower TSNE will be.\n\n labels : list of strings\n The names of the classes in the target, used to create a legend.\n Labels must match names of classes in sorted order.\n\n colors : list or tuple of colors\n Specify the colors for each individual class\n\n colormap : string or matplotlib cmap\n Sequential colormap for continuous target\n\n random_state : int, RandomState instance or None, optional, default: None\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by np.random. The random state is applied to the preliminary\n decomposition as well as tSNE.\n\n alpha : float, default: 0.7\n Specify a transparency where 1 is completely opaque and 0 is completely\n transparent. This property makes densely clustered points more visible.\n\n kwargs : dict\n Pass any additional keyword arguments to the TSNE transformer.\n \"\"\"\n\n # NOTE: cannot be np.nan\n NULL_CLASS = None\n\n def __init__(\n self,\n ax=None,\n decompose=\"svd\",\n decompose_by=50,\n labels=None,\n classes=None,\n colors=None,\n colormap=None,\n random_state=None,\n alpha=0.7,\n **kwargs\n ):\n\n # Visual Parameters\n self.alpha = alpha\n self.labels = labels\n self.colors = colors\n self.colormap = colormap\n self.random_state = random_state\n\n # Fetch TSNE kwargs from kwargs by popping only keys belonging to TSNE params\n tsne_kwargs = {\n key: kwargs.pop(key) for key in TSNE().get_params() if key in kwargs\n }\n self.transformer_ = self.make_transformer(decompose, decompose_by, tsne_kwargs)\n\n # Call super at the end so that size and title are set correctly\n super(TSNEVisualizer, self).__init__(ax=ax, **kwargs)\n\n def make_transformer(self, decompose=\"svd\", decompose_by=50, tsne_kwargs={}):\n \"\"\"\n Creates an internal transformer pipeline to project the data set into\n 2D space using TSNE, applying an pre-decomposition technique ahead of\n embedding if necessary. This method will reset the transformer on the\n class, and can be used to explore different decompositions.\n\n Parameters\n ----------\n\n decompose : string or None, default: ``'svd'``\n A preliminary decomposition is often used prior to TSNE to make\n the projection faster. Specify ``\"svd\"`` for sparse data or ``\"pca\"``\n for dense data. If decompose is None, the original data set will\n be used.\n\n decompose_by : int, default: 50\n Specify the number of components for preliminary decomposition, by\n default this is 50; the more components, the slower TSNE will be.\n\n Returns\n -------\n\n transformer : Pipeline\n Pipelined transformer for TSNE projections\n \"\"\"\n\n # TODO: detect decompose by inferring from sparse matrix or dense or\n # If number of features > 50 etc.\n decompositions = {\"svd\": TruncatedSVD, \"pca\": PCA}\n\n if decompose and decompose.lower() not in decompositions:\n raise YellowbrickValueError(\n \"'{}' is not a valid decomposition, use {}, or None\".format(\n decompose, \", \".join(decompositions.keys())\n )\n )\n\n # Create the pipeline steps\n steps = []\n\n # Add the pre-decomposition\n if decompose:\n klass = decompositions[decompose]\n steps.append(\n (\n decompose,\n klass(n_components=decompose_by, random_state=self.random_state),\n )\n )\n\n # Add the TSNE manifold\n steps.append(\n (\n \"tsne\",\n TSNE(n_components=2, random_state=self.random_state, **tsne_kwargs),\n )\n )\n\n # return the pipeline\n return Pipeline(steps)\n\n def fit(self, X, y=None, **kwargs):\n \"\"\"\n The fit method is the primary drawing input for the TSNE projection\n since the visualization requires both X and an optional y value. The\n fit method expects an array of numeric vectors, so text documents must\n be vectorized before passing them to this method.\n\n Parameters\n ----------\n X : ndarray or DataFrame of shape n x m\n A matrix of n instances with m features representing the corpus of\n vectorized documents to visualize with tsne.\n\n y : ndarray or Series of length n\n An optional array or series of target or class values for\n instances. If this is specified, then the points will be colored\n according to their class. Often cluster labels are passed in to\n color the documents in cluster space, so this method is used both\n for classification and clustering methods.\n\n kwargs : dict\n Pass generic arguments to the drawing method\n\n Returns\n -------\n self : instance\n Returns the instance of the transformer/visualizer\n \"\"\"\n\n # Store the classes we observed in y\n if y is not None:\n self.classes_ = np.unique(y)\n elif y is None and self.labels is not None:\n self.classes_ = np.array([self.labels[0]])\n else:\n self.classes_ = np.array([self.NULL_CLASS])\n print(self.classes_)\n # Fit our internal transformer and transform the data.\n vecs = self.transformer_.fit_transform(X)\n self.n_instances_ = vecs.shape[0]\n print(vecs)\n # Draw the vectors\n self.draw(vecs, y, **kwargs)\n\n # Fit always returns self.\n return self\n\n def draw(self, points, target=None, **kwargs):\n \"\"\"\n Called from the fit method, this method draws the TSNE scatter plot,\n from a set of decomposed points in 2 dimensions. This method also\n accepts a third dimension, target, which is used to specify the colors\n of each of the points. If the target is not specified, then the points\n are plotted as a single cloud to show similar documents.\n \"\"\"\n # Resolve the labels with the classes\n labels = self.labels if self.labels is not None else self.classes_\n if len(labels) != len(self.classes_):\n raise YellowbrickValueError(\n (\n \"number of supplied labels ({}) does not \"\n \"match the number of classes ({})\"\n ).format(len(labels), len(self.classes_))\n )\n\n # Create the color mapping for the labels.\n self.color_values_ = resolve_colors(\n n_colors=len(labels), colormap=self.colormap, colors=self.colors\n )\n colors = dict(zip(labels, self.color_values_))\n\n # Transform labels into a map of class to label\n labels = dict(zip(self.classes_, labels))\n\n # Expand the points into vectors of x and y for scatter plotting,\n # assigning them to their label if the label has been passed in.\n # Additionally, filter classes not specified directly by the user.\n series = defaultdict(lambda: {\"x\": [], \"y\": []})\n\n if target is not None:\n for t, point in zip(target, points):\n label = labels[t]\n series[label][\"x\"].append(point[0])\n series[label][\"y\"].append(point[1])\n else:\n label = self.classes_[0]\n for x, y in points:\n series[label][\"x\"].append(x)\n series[label][\"y\"].append(y)\n\n # Plot the points\n for label, points in series.items():\n self.ax.scatter(\n points[\"x\"], points[\"y\"], c=colors[label], alpha=self.alpha, label=label\n )\n\n return self.ax\n\n def finalize(self, **kwargs):\n \"\"\"\n Finalize the drawing by adding a title and legend, and removing the\n axes objects that do not convey information about TNSE.\n \"\"\"\n self.set_title(\"TSNE Projection of {} Documents\".format(self.n_instances_))\n\n # Remove the ticks\n self.ax.set_yticks([])\n self.ax.set_xticks([])\n\n # Add the legend outside of the figure box.\n if not all(self.classes_ == np.array([self.NULL_CLASS])):\n box = self.ax.get_position()\n self.ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n manual_legend(\n self,\n self.classes_,\n self.color_values_,\n loc=\"center left\",\n bbox_to_anchor=(1, 0.5),\n )\n\n\n#from yellowbrick.text import TSNEVisualizer\nimport yellowbrick\nfrom yellowbrick import download\n\nimport torch as th\nimport pickle\n\n\ndevice = th.device(\"cuda\" if th.cuda.is_available() else \"cpu\")\nwith open('../embedding/data.pkl','rb') as f:\n emebddings,labels = pickle.load(f)\n\nemebddings=emebddings.cpu().numpy()\nlabels=labels.cpu().numpy()\nprint('embeddings:',emebddings[:10])\nprint('labels:',labels[:10])\nprint(emebddings.shape,labels.shape)\n#corpus = load_corpus('./data/hobbies')\n# tfidf = TfidfVectorizer()\n# print(corpus.data[0])\n# docs = tfidf.fit_transform(corpus.data)\n# labels = corpus.target\n# print(docs.shape)\n#\n# print(len(labels))\ntsne = TSNEVisualizer()\ntsne.fit(emebddings, labels)\ntsne.show()\ntsne.poof()"
]
| [
[
"numpy.array",
"sklearn.manifold.TSNE",
"torch.cuda.is_available",
"sklearn.pipeline.Pipeline",
"numpy.unique"
]
]
|
Maqingyang/track_3d_human | [
"fd85f07a9a42df52b1f7dbe06f5752f0a91b5777"
]
| [
"demo_mot.py"
]
| [
"\"\"\"\nDemo code\n\nTo run our method, you need a bounding box around the person. The person needs to be centered inside the bounding box and the bounding box should be relatively tight. You can either supply the bounding box directly or provide an [OpenPose](https://github.com/CMU-Perceptual-Computing-Lab/openpose) detection file. In the latter case we infer the bounding box from the detections.\n\nIn summary, we provide 3 different ways to use our demo code and models:\n1. Provide only an input image (using ```--img```), in which case it is assumed that it is already cropped with the person centered in the image.\n2. Provide an input image as before, together with the OpenPose detection .json (using ```--openpose```). Our code will use the detections to compute the bounding box and crop the image.\n3. Provide an image and a bounding box (using ```--bbox```). The expected format for the json file can be seen in ```examples/im1010_bbox.json```.\n\nExample with OpenPose detection .json\n```\npython3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png --openpose=examples/im1010_openpose.json\n```\nExample with predefined Bounding Box\n```\npython3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png --bbox=examples/im1010_bbox.json\n```\nExample with cropped and centered image\n```\npython3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png\n```\n\nRunning the previous command will save the results in ```examples/im1010_{shape,shape_side}.png```. The file ```im1010_shape.png``` shows the overlayed reconstruction of human shape. We also render a side view, saved in ```im1010_shape_side.png```.\n\"\"\"\n\nimport torch\nfrom torchvision.transforms import Normalize\nimport numpy as np\nimport cv2\nimport argparse\nimport json\n\nfrom models import hmr, SMPL\nfrom utils.imutils import crop, uncrop\nfrom utils.renderer import Renderer\nimport config\nimport constants\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--checkpoint', default=\"data/model_checkpoint.pt\", help='Path to pretrained checkpoint')\n\n\ndef bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2):\n \"\"\"Get center and scale for bounding box from openpose detections.\"\"\"\n with open(openpose_file, 'r') as f:\n keypoints = json.load(f)['people'][0]['pose_keypoints_2d']\n keypoints = np.reshape(np.array(keypoints), (-1,3))\n valid = keypoints[:,-1] > detection_thresh\n valid_keypoints = keypoints[valid][:,:-1]\n center = valid_keypoints.mean(axis=0)\n bbox_size = (valid_keypoints.max(axis=0) - valid_keypoints.min(axis=0)).max()\n # adjust bounding box tightness\n scale = bbox_size / 200.0\n scale *= rescale\n return center, scale\n\ndef bbox_from_json(bbox_file):\n \"\"\"Get center and scale of bounding box from bounding box annotations.\n The expected format is [top_left(x), top_left(y), width, height].\n \"\"\"\n with open(bbox_file, 'r') as f:\n bbox = np.array(json.load(f)['bbox']).astype(np.float32)\n ul_corner = bbox[:2]\n center = ul_corner + 0.5 * bbox[2:]\n width = max(bbox[2], bbox[3])\n scale = width / 200.0\n # make sure the bounding box is rectangular\n return center, scale\n\n\n\ndef process_image(img_file, bbox_file, openpose_file, input_res=224):\n \"\"\"Read image, do preprocessing and possibly crop it according to the bounding box.\n If there are bounding box annotations, use them to crop the image.\n If no bounding box is specified but openpose detections are available, use them to get the bounding box.\n \"\"\"\n normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)\n img = cv2.imread(img_file)[:,:,::-1].copy() # PyTorch does not support negative stride at the moment\n # img (H,W,RGB)\n if bbox_file is None and openpose_file is None:\n # Assume that the person is centerered in the image\n height = img.shape[0]\n width = img.shape[1]\n center = np.array([width // 2, height // 2])\n scale = max(height, width) / 200\n else:\n if bbox_file is not None:\n center, scale = bbox_from_json(bbox_file)\n elif openpose_file is not None:\n center, scale = bbox_from_openpose(openpose_file)\n img = crop(img, center, scale, (input_res, input_res))\n img = img.astype(np.float32) / 255.\n img = torch.from_numpy(img).permute(2,0,1)\n # img(RGB,H,W)\n norm_img = normalize_img(img.clone())[None]\n return img, norm_img\n\ndef process_MOT_image(img, bbox, input_res=224):\n \"\"\"Read image, do preprocessing and possibly crop it according to the bounding box.\n If there are bounding box annotations, use them to crop the image.\n If no bounding box is specified but openpose detections are available, use them to get the bounding box.\n \"\"\"\n normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)\n # img (H,W,RGB)\n\n\n ul_corner = bbox[:2]\n center = ul_corner + 0.5 * bbox[2:]\n width = max(bbox[2], bbox[3])\n scale = width / 200.0\n img = crop(img, center, scale, (input_res, input_res))\n img = img.astype(np.float32) / 255.\n img = torch.from_numpy(img).permute(2,0,1)\n # img(RGB,H,W)\n norm_img = normalize_img(img.clone())[None]\n return img, norm_img\n\n\nimport sys\nsys.path.append(\"/project/tracking_wo_bnw/src\")\nfrom tracktor.datasets.factory import Datasets\nimport os.path as osp\n\ndef read_from_MOT():\n dataset = \"mot17_train_FRCNN17\"\n detections = \"FRCNN\"\n for db in Datasets(dataset):\n for frame,v in enumerate(db,1):\n im_path = v['img_path']\n im_name = osp.basename(im_path)\n # im_output = osp.join(output_dir, im_name)\n im = cv2.imread(im_path)\n im = im[:, :, (2, 1, 0)] \n dets = v['dets'].cpu().numpy()\n return im, dets\n\nif __name__ == '__main__':\n args = parser.parse_args()\n \n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n \n # Load pretrained model\n model = hmr(config.SMPL_MEAN_PARAMS).to(device)\n checkpoint = torch.load(args.checkpoint)\n model.load_state_dict(checkpoint['model'], strict=False)\n\n # Load SMPL model\n smpl = SMPL(config.SMPL_MODEL_DIR,\n batch_size=1,\n create_transl=False).to(device)\n model.eval()\n\n # Setup renderer for visualization\n renderer = Renderer(focal_length=constants.FOCAL_LENGTH, img_res=constants.IMG_RES, faces=smpl.faces)\n\n\n # Preprocess input image and generate predictions\n img, dets = read_from_MOT()\n dets[:,2:4] -= dets[:,0:2]# point-point to point-size\n bbox = dets[4]\n img, norm_img = process_MOT_image(img,bbox, input_res=constants.IMG_RES)\n with torch.no_grad():\n pred_rotmat, pred_betas, pred_camera = model(norm_img.to(device))\n pred_output = smpl(betas=pred_betas, body_pose=pred_rotmat[:,1:], global_orient=pred_rotmat[:,0].unsqueeze(1), pose2rot=False)\n pred_vertices = pred_output.vertices\n \n # Calculate camera parameters for rendering\n camera_translation = torch.stack([pred_camera[:,1], pred_camera[:,2], 2*constants.FOCAL_LENGTH/(constants.IMG_RES * pred_camera[:,0] +1e-9)],dim=-1)\n camera_translation = camera_translation[0].cpu().numpy()\n pred_vertices = pred_vertices[0].cpu().numpy()\n img = img.permute(1,2,0).cpu().numpy()\n\n \n # Render parametric shape\n img_shape = renderer(pred_vertices, camera_translation, img)\n \n # Render side views\n aroundy = cv2.Rodrigues(np.array([0, np.radians(90.), 0]))[0]\n center = pred_vertices.mean(axis=0)\n rot_vertices = np.dot((pred_vertices - center), aroundy) + center\n \n # Render non-parametric shape\n img_shape_side = renderer(rot_vertices, camera_translation, np.ones_like(img))\n\n outfile = \"mot\"\n\n # Save reconstructions\n cv2.imwrite(outfile + '_shape.png', 255 * img_shape[:,:,::-1])\n cv2.imwrite(outfile + '_shape_side.png', 255 * img_shape_side[:,:,::-1])\n"
]
| [
[
"torch.device",
"numpy.array",
"numpy.dot",
"torch.stack",
"numpy.ones_like",
"torch.no_grad",
"torch.from_numpy",
"numpy.radians",
"torch.cuda.is_available",
"torch.load"
]
]
|
ztfmars/OpenCV_Tutorial | [
"2c9cf57f469dfec2aca8356f59f7473e5a506988"
]
| [
"py_simple/15.傅里叶变换/15多个正弦曲线-相位.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 11 07:38:43 2018\n\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx=np.arange(0,2*np.pi*8,0.01)\ny=3*np.sin(0.8*x)+7*np.sin(1/3*x+2)+2*np.sin(0.2*x+3)\n\ny1=3*np.sin(0.8*x)\ny2=7*np.sin(0.5*x+2)\ny3=2*np.sin(0.2*x+3)\n\nplt.subplot(221)\nplt.plot(y)\nplt.subplot(222)\nplt.plot(y1)\nplt.subplot(223)\nplt.plot(y2)\nplt.subplot(224)\nplt.plot(y3)\n#plt.figure()\n#plt.plot(y)\nplt.show()"
]
| [
[
"numpy.sin",
"matplotlib.pyplot.plot",
"numpy.arange",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplot"
]
]
|
MSimoncelli/phono3py | [
"b28b45a025c279833e9269e5d91330c75d3f6ae0"
]
| [
"phono3py/api_phono3py.py"
]
| [
"\"\"\"Phono3py main class.\"\"\"\n# Copyright (C) 2016 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phono3py.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport warnings\n\nimport numpy as np\nfrom phonopy.harmonic.displacement import (\n directions_to_displacement_dataset,\n get_least_displacements,\n)\nfrom phonopy.harmonic.force_constants import get_fc2 as get_phonopy_fc2\nfrom phonopy.harmonic.force_constants import (\n set_permutation_symmetry,\n set_translational_invariance,\n symmetrize_compact_force_constants,\n symmetrize_force_constants,\n)\nfrom phonopy.interface.fc_calculator import get_fc2\nfrom phonopy.structure.atoms import PhonopyAtoms\nfrom phonopy.structure.cells import (\n get_primitive,\n get_primitive_matrix,\n get_supercell,\n guess_primitive_matrix,\n shape_supercell_matrix,\n)\nfrom phonopy.structure.dataset import get_displacements_and_forces\nfrom phonopy.structure.symmetry import Symmetry\nfrom phonopy.units import VaspToTHz\n\nfrom phono3py.conductivity.direct_solution import get_thermal_conductivity_LBTE\nfrom phono3py.conductivity.rta import get_thermal_conductivity_RTA\nfrom phono3py.interface.fc_calculator import get_fc3\nfrom phono3py.interface.phono3py_yaml import Phono3pyYaml\nfrom phono3py.phonon3.dataset import get_displacements_and_forces_fc3\nfrom phono3py.phonon3.displacement_fc3 import (\n direction_to_displacement,\n get_third_order_displacements,\n)\nfrom phono3py.phonon3.fc3 import cutoff_fc3_by_zero\nfrom phono3py.phonon3.fc3 import get_fc3 as get_phono3py_fc3\nfrom phono3py.phonon3.fc3 import (\n set_permutation_symmetry_compact_fc3,\n set_permutation_symmetry_fc3,\n set_translational_invariance_compact_fc3,\n set_translational_invariance_fc3,\n)\nfrom phono3py.phonon3.imag_self_energy import (\n get_imag_self_energy,\n write_imag_self_energy,\n)\nfrom phono3py.phonon3.interaction import Interaction\nfrom phono3py.phonon3.real_self_energy import (\n get_real_self_energy,\n write_real_self_energy,\n)\nfrom phono3py.phonon3.spectral_function import run_spectral_function\nfrom phono3py.phonon.grid import BZGrid\nfrom phono3py.version import __version__\n\n\nclass Phono3py:\n \"\"\"Phono3py main class.\n\n Attributes\n ----------\n version\n calculator\n fc3 : getter and setter\n fc2 : getter and setter\n force_constants\n sigma : getter and setter\n sigma_cutoff : getter and setter\n nac_params : getter and setter\n dynamical_matrix\n primitive\n unitcell\n supercell\n phonon_supercell\n phonon_primitive\n symmetry\n primitive_symmetry\n phonon_supercell_symmetry\n supercell_matrix\n phonon_supercell_matrix\n primitive_matrix\n unit_conversion_factor\n dataset : getter and setter\n phonon_dataset : getter and setter\n band_indices : getter and setter\n phonon_supercells_with_displacements\n supercells_with_displacements\n mesh_numbers : getter and setter\n thermal_conductivity\n displacements : getter and setter\n forces : getter and setter\n phonon_displacements : getter and setter\n phonon_forces : getter and setter\n phph_interaction\n\n \"\"\"\n\n def __init__(\n self,\n unitcell: PhonopyAtoms,\n supercell_matrix=None,\n primitive_matrix=None,\n phonon_supercell_matrix=None,\n masses=None,\n band_indices=None,\n sigmas=None,\n sigma_cutoff=None,\n cutoff_frequency=1e-4,\n frequency_factor_to_THz=VaspToTHz,\n is_symmetry=True,\n is_mesh_symmetry=True,\n use_grg=False,\n SNF_coordinates=\"reciprocal\",\n symmetrize_fc3q=None,\n store_dense_gp_map=True,\n store_dense_svecs=True,\n symprec=1e-5,\n calculator=None,\n log_level=0,\n lapack_zheev_uplo=None,\n ):\n \"\"\"Init method.\n\n Parameters\n ----------\n unitcell : PhonopyAtoms, optional\n Input unit cell.\n supercell_matrix : array_like, optional\n Supercell matrix multiplied to input cell basis vectors.\n shape=(3, ) or (3, 3), where the former is considered a diagonal\n matrix. The elements have to be given by integers.\n Although the default is None, which results in identity\n matrix, it is recommended to give `supercell_matrix` explicitly.\n primitive_matrix : array_like or str, optional\n Primitive matrix multiplied to input cell basis vectors. Default is\n the identity matrix.\n When given as array_like, shape=(3, 3), dtype=float.\n When 'F', 'I', 'A', 'C', or 'R' is given instead of a 3x3 matrix,\n the primitive matrix defined at\n https://spglib.github.io/spglib/definition.html\n is used.\n When 'auto' is given, the centring type ('F', 'I', 'A', 'C', 'R',\n or primitive 'P') is automatically chosen.\n phonon_supercell_matrix : array_like, optional\n Supercell matrix used for fc2. In phono3py, supercell matrix for\n fc3 and fc2 can be different to support longer range interaction of\n fc2 than that of fc3. Unless setting this, supercell_matrix is\n used. This is only valide when unitcell or unitcell_filename is\n given. Default is None.\n masses : Deprecated.\n Use Phono3py.masses attribute after instanciation.\n band_indices : Deprecated.\n Use Phono3py.band_indices attribute after instanciation.\n sigmas : Deprecated.\n Use Phono3py.sigmas attribute after instanciation.\n sigma_cutoff : Deprecated.\n Use Phono3py.sigma_cutoff attribute after instanciation.\n cutoff_frequency : float, optional\n Phonon frequency below this value is ignored when the cutoff is\n needed for the computation. Default is 1e-4.\n frequency_factor_to_THz : float, optional\n Phonon frequency unit conversion factor. Unless specified, default\n unit conversion factor for each calculator is used.\n is_symmetry : bool, optional\n Use crystal symmetry in most calculations when True. Default is\n True.\n is_mesh_symmetry : bool, optional\n Use crystal symmetry in reciprocal space grid handling when True.\n Default is True.\n use_grg : bool, optional\n Use generalized regular grid when True. Default is False.\n SNF_coordinates : str, optional\n `reciprocal` or `direct`.\n Space of coordinates to generate grid generating matrix either in direct\n or reciprocal space. The default is `reciprocal`.\n symmetrize_fc3q : Deprecated.\n See Phono3py.init_phph_interaction().\n store_dense_gp_map : bool, optional\n Use dense format of BZ grid system. Default is True.\n store_dense_svecs : bool, optional\n Shortest vectors are stored in the dense array format. This is\n expected to be always True. Setting False is for rough\n compatibility with v1.x. Default is True.\n symprec : float, optional\n Tolerance used to find crystal symmetry. Default is 1e-5.\n calculator : str, optional.\n Calculator used for computing forces. This is used to switch\n the set of physical units. Default is None, which is equivalent\n to \"vasp\".\n log_level : int, optional\n Verbosity control. Default is 0. This can be 0, 1, or 2.\n lapack_zheev_uplo : Deprecated.\n See Phono3py.init_phph_interaction().\n\n \"\"\"\n self._symprec = symprec\n self._frequency_factor_to_THz = frequency_factor_to_THz\n self._is_symmetry = is_symmetry\n self._is_mesh_symmetry = is_mesh_symmetry\n self._use_grg = use_grg\n self._SNF_coordinates = SNF_coordinates\n self._store_dense_gp_map = store_dense_gp_map\n self._store_dense_svecs = store_dense_svecs\n self._cutoff_frequency = cutoff_frequency\n self._calculator = calculator\n self._log_level = log_level\n\n # Create supercell and primitive cell\n self._unitcell = unitcell\n self._supercell_matrix = np.array(\n shape_supercell_matrix(supercell_matrix), dtype=\"int_\", order=\"C\"\n )\n pmat = self._determine_primitive_matrix(primitive_matrix)\n self._primitive_matrix = pmat\n self._nac_params = None\n if phonon_supercell_matrix is not None:\n self._phonon_supercell_matrix = np.array(\n shape_supercell_matrix(phonon_supercell_matrix), dtype=\"int_\", order=\"C\"\n )\n else:\n self._phonon_supercell_matrix = None\n self._supercell = None\n self._primitive = None\n self._phonon_supercell = None\n self._phonon_primitive = None\n self._build_supercell()\n self._build_primitive_cell()\n self._build_phonon_supercell()\n self._build_phonon_primitive_cell()\n\n self._sigmas = [\n None,\n ]\n self._sigma_cutoff = None\n\n # Grid\n self._bz_grid = None\n\n # Set supercell, primitive, and phonon supercell symmetries\n self._symmetry = None\n self._primitive_symmetry = None\n self._phonon_supercell_symmetry = None\n self._search_symmetry()\n self._search_primitive_symmetry()\n self._search_phonon_supercell_symmetry()\n\n # Displacements and supercells\n self._supercells_with_displacements = None\n self._dataset = None\n self._phonon_dataset = None\n self._phonon_supercells_with_displacements = None\n\n # Thermal conductivity\n # conductivity_RTA or conductivity_LBTE class instance\n self._thermal_conductivity = None\n\n # Imaginary part of self energy at frequency points\n self._gammas = None\n self._scattering_event_class = None\n\n # Frequency shift (real part of bubble diagram)\n self._real_self_energy = None\n\n self._grid_points = None\n self._frequency_points = None\n self._temperatures = None\n\n # Other variables\n self._fc2 = None\n self._fc3 = None\n\n # Setup interaction\n self._interaction = None\n self._band_indices = None\n self._band_indices_flatten = None\n self._set_band_indices()\n\n if masses is not None:\n warnings.warn(\n \"Phono3py init parameter of masses is deprecated. \"\n \"Use Phono3py.masses attribute instead.\",\n DeprecationWarning,\n )\n self.masses = masses\n\n if band_indices is not None:\n warnings.warn(\n \"Phono3py init parameter of band_indices is deprecated. \"\n \"Use Phono3py.band_indices attribute instead.\",\n DeprecationWarning,\n )\n self.band_indices = band_indices\n\n if sigmas is not None:\n warnings.warn(\n \"Phono3py init parameter of sigmas is deprecated. \"\n \"Use Phono3py.sigmas attribute instead.\",\n DeprecationWarning,\n )\n self.sigmas = sigmas\n\n if sigma_cutoff is not None:\n warnings.warn(\n \"Phono3py init parameter of sigma_cutoff is deprecated. \"\n \"Use Phono3py.sigma_cutoff attribute instead.\",\n DeprecationWarning,\n )\n self.sigma_cutoff = sigma_cutoff\n\n if symmetrize_fc3q is not None:\n warnings.warn(\n \"Phono3py init parameter of symmetrize_fc3q is deprecated. \"\n \"Set this at Phono3py.init_phph_interaction().\",\n DeprecationWarning,\n )\n self._symmetrize_fc3q = symmetrize_fc3q\n else:\n self._symmetrize_fc3q = None\n\n if lapack_zheev_uplo is not None:\n warnings.warn(\n \"Phono3py init parameter of lapack_zheev_uplo is deprecated. \"\n \"Set this at Phono3py.init_phph_interaction().\",\n DeprecationWarning,\n )\n self._lapack_zheev_uplo = lapack_zheev_uplo\n else:\n self._lapack_zheev_uplo = None\n\n @property\n def version(self):\n \"\"\"Return phono3py release version number.\n\n str\n Phono3py release version number\n\n \"\"\"\n return __version__\n\n def get_version(self):\n \"\"\"Return phono3py release version number.\"\"\"\n warnings.warn(\n \"Phono3py.get_version() is deprecated.\"\n \"Use Phono3py.version attribute instead.\",\n DeprecationWarning,\n )\n return self.version\n\n @property\n def calculator(self):\n \"\"\"Return calculator interface name.\n\n str\n Calculator name such as 'vasp', 'qe', etc.\n\n \"\"\"\n return self._calculator\n\n @property\n def fc3(self):\n \"\"\"Setter and getter of third order force constants (fc3).\n\n ndarray\n fc3 shape is either (supercell, supecell, supercell, 3, 3, 3) or\n (primitive, supercell, supecell, 3, 3, 3),\n where 'supercell' and 'primitive' indicate number of atoms in\n these cells.\n\n \"\"\"\n return self._fc3\n\n @fc3.setter\n def fc3(self, fc3):\n self._fc3 = fc3\n\n def get_fc3(self):\n \"\"\"Return third order force constants (fc3).\"\"\"\n warnings.warn(\n \"Phono3py.get_fc3() is deprecated.\" \"Use Phono3py.fc3 attribute instead.\",\n DeprecationWarning,\n )\n return self.fc3\n\n def set_fc3(self, fc3):\n \"\"\"Set fc3.\"\"\"\n warnings.warn(\n \"Phono3py.set_fc3() is deprecated.\" \"Use Phono3py.fc3 attribute instead.\",\n DeprecationWarning,\n )\n self.fc3 = fc3\n\n @property\n def fc2(self):\n \"\"\"Setter and getter of second order force constants (fc2).\n\n ndarray\n fc2 shape is either (supercell, supecell, 3, 3) or\n (primitive, supecell, 3, 3),\n where 'supercell' and 'primitive' indicate number of atoms in\n these cells.\n\n \"\"\"\n return self._fc2\n\n @fc2.setter\n def fc2(self, fc2):\n self._fc2 = fc2\n\n def get_fc2(self):\n \"\"\"Return second order force constants (fc2).\"\"\"\n warnings.warn(\n \"Phono3py.get_fc2() is deprecated.\" \"Use Phono3py.fc2 attribute instead.\",\n DeprecationWarning,\n )\n return self.fc2\n\n def set_fc2(self, fc2):\n \"\"\"Set fc2.\"\"\"\n warnings.warn(\n \"Phono3py.set_fc2() is deprecated.\" \"Use Phono3py.fc2 attribute instead.\",\n DeprecationWarning,\n )\n self.fc2 = fc2\n\n @property\n def force_constants(self):\n \"\"\"Return fc2. This is same as the getter attribute `fc2`.\"\"\"\n return self.fc2\n\n @property\n def sigmas(self):\n \"\"\"Setter and getter of smearing widths.\n\n list\n The float values are given as the standard deviations of Gaussian\n function. If None is given as an element of this list, linear\n tetrahedron method is used instead of smearing method.\n\n \"\"\"\n return self._sigmas\n\n @sigmas.setter\n def sigmas(self, sigmas):\n if sigmas is None:\n self._sigmas = [\n None,\n ]\n elif isinstance(sigmas, float) or isinstance(sigmas, int):\n self._sigmas = [\n float(sigmas),\n ]\n else:\n self._sigmas = []\n for s in sigmas:\n if isinstance(s, float) or isinstance(s, int):\n self._sigmas.append(float(s))\n elif s is None:\n self._sigmas.append(None)\n\n @property\n def sigma_cutoff(self):\n \"\"\"Setter and getter of Smearing cutoff width.\n\n This is given as a multiple of the standard deviation.\n\n float\n For example, if this value is 5, the tail of the Gaussian function\n is cut at 5 sigma.\n\n \"\"\"\n return self._sigma_cutoff\n\n @sigma_cutoff.setter\n def sigma_cutoff(self, sigma_cutoff):\n self._sigma_cutoff = sigma_cutoff\n\n @property\n def nac_params(self):\n \"\"\"Setter and getter of parameters for non-analytical term correction.\n\n dict\n Parameters used for non-analytical term correction\n 'born': ndarray\n Born effective charges\n shape=(primitive cell atoms, 3, 3), dtype='double', order='C'\n 'factor': float\n Unit conversion factor\n 'dielectric': ndarray\n Dielectric constant tensor\n shape=(3, 3), dtype='double', order='C'\n\n \"\"\"\n return self._nac_params\n\n @nac_params.setter\n def nac_params(self, nac_params):\n self._nac_params = nac_params\n if self._interaction is not None:\n self._init_dynamical_matrix()\n\n def get_nac_params(self):\n \"\"\"Return NAC parameters.\"\"\"\n warnings.warn(\n \"Phono3py.get_nac_params() is deprecated.\"\n \"Use Phono3py.nac_params attribute instead.\",\n DeprecationWarning,\n )\n return self.nac_params\n\n def set_nac_params(self, nac_params):\n \"\"\"Set NAC parameters.\"\"\"\n warnings.warn(\n \"Phono3py.set_nac_params() is deprecated.\"\n \"Use Phono3py.nac_params attribute instead.\",\n DeprecationWarning,\n )\n self.nac_params = nac_params\n\n @property\n def dynamical_matrix(self):\n \"\"\"Return DynamicalMatrix instance.\n\n This is not dynamical matrices but the instance of DynamicalMatrix\n class.\n\n \"\"\"\n if self._interaction is None:\n return None\n else:\n return self._interaction.dynamical_matrix\n\n @property\n def primitive(self):\n \"\"\"Return primitive cell.\n\n Primitive\n Primitive cell.\n\n \"\"\"\n return self._primitive\n\n def get_primitive(self):\n \"\"\"Return primitive cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_primitive() is deprecated.\"\n \"Use Phono3py.primitive attribute instead.\",\n DeprecationWarning,\n )\n return self.primitive\n\n @property\n def unitcell(self):\n \"\"\"Return Unit cell.\n\n PhonopyAtoms\n Unit cell.\n\n \"\"\"\n return self._unitcell\n\n def get_unitcell(self):\n \"\"\"Return Unit cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_unitcell() is deprecated.\"\n \"Use Phono3py.unitcell attribute instead.\",\n DeprecationWarning,\n )\n return self.unitcell\n\n @property\n def supercell(self):\n \"\"\"Return supercell.\n\n Supercell\n Supercell.\n\n \"\"\"\n return self._supercell\n\n def get_supercell(self):\n \"\"\"Return supercell.\"\"\"\n warnings.warn(\n \"Phono3py.get_supercell() is deprecated.\"\n \"Use Phono3py.supercell attribute instead.\",\n DeprecationWarning,\n )\n return self.supercell\n\n @property\n def phonon_supercell(self):\n \"\"\"Return supercell for fc2.\n\n Supercell\n Supercell for fc2.\n\n \"\"\"\n return self._phonon_supercell\n\n def get_phonon_supercell(self):\n \"\"\"Return supercell for fc2.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_supercell() is deprecated.\"\n \"Use Phono3py.phonon_supercell attribute instead.\",\n DeprecationWarning,\n )\n return self.phonon_supercell\n\n @property\n def phonon_primitive(self):\n \"\"\"Return primitive cell for fc2.\n\n Primitive\n Primitive cell for fc2. This should be the same as the primitive\n cell for fc3, but this is created from supercell for fc2 and\n can be not numerically perfectly identical.\n\n \"\"\"\n return self._phonon_primitive\n\n def get_phonon_primitive(self):\n \"\"\"Return primitive cell for fc2.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_primitive() is deprecated.\"\n \"Use Phono3py.phonon_primitive attribute instead.\",\n DeprecationWarning,\n )\n return self.phonon_primitive\n\n @property\n def symmetry(self):\n \"\"\"Return symmetry of supercell.\n\n Symmetry\n Symmetry of supercell\n\n \"\"\"\n return self._symmetry\n\n def get_symmetry(self):\n \"\"\"Return symmetry of supercell.\"\"\"\n warnings.warn(\n \"Phono3py.get_symmetry() is deprecated.\"\n \"Use Phono3py.symmetry attribute instead.\",\n DeprecationWarning,\n )\n return self.symmetry\n\n @property\n def primitive_symmetry(self):\n \"\"\"Return symmetry of primitive cell.\n\n Symmetry\n Symmetry of primitive cell.\n\n \"\"\"\n return self._primitive_symmetry\n\n def get_primitive_symmetry(self):\n \"\"\"Return symmetry of primitive cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_primitive_symmetry() is deprecated.\"\n \"Use Phono3py.primitive_symmetry attribute instead.\",\n DeprecationWarning,\n )\n return self.primitive_symmetry\n\n @property\n def phonon_supercell_symmetry(self):\n \"\"\"Return symmetry of supercell for fc2.\n\n Symmetry\n Symmetry of supercell for fc2 (phonon_supercell).\n\n \"\"\"\n return self._phonon_supercell_symmetry\n\n def get_phonon_supercell_symmetry(self):\n \"\"\"Return symmetry of supercell for fc2.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_supercell_symmetry() is deprecated.\"\n \"Use Phono3py.phonon_supercell_symmetry attribute instead.\",\n DeprecationWarning,\n )\n return self.phonon_supercell_symmetry\n\n @property\n def supercell_matrix(self):\n \"\"\"Return transformation matrix to supercell cell from unit cell.\n\n ndarray\n Supercell matrix with respect to unit cell.\n shape=(3, 3), dtype='int_', order='C'\n\n \"\"\"\n return self._supercell_matrix\n\n def get_supercell_matrix(self):\n \"\"\"Return transformation matrix to supercell cell from unit cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_supercell_matrix() is deprecated.\"\n \"Use Phono3py.supercell_matrix attribute instead.\",\n DeprecationWarning,\n )\n return self.supercell_matrix\n\n @property\n def phonon_supercell_matrix(self):\n \"\"\"Return transformation matrix to phonon supercell from unit cell.\n\n ndarray\n Supercell matrix with respect to unit cell.\n shape=(3, 3), dtype='int_', order='C'\n\n \"\"\"\n return self._phonon_supercell_matrix\n\n def get_phonon_supercell_matrix(self):\n \"\"\"Return transformation matrix to phonon supercell from unit cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_supercell_matrix() is deprecated.\"\n \"Use Phono3py.phonon_supercell_matrix attribute instead.\",\n DeprecationWarning,\n )\n return self.phonon_supercell_matrix\n\n @property\n def primitive_matrix(self):\n \"\"\"Return transformation matrix to primitive cell from unit cell.\n\n ndarray\n Primitive matrix with respect to unit cell.\n shape=(3, 3), dtype='double', order='C'\n\n \"\"\"\n return self._primitive_matrix\n\n def get_primitive_matrix(self):\n \"\"\"Return transformation matrix to primitive cell from unit cell.\"\"\"\n warnings.warn(\n \"Phono3py.get_primitive_matrix() is deprecated.\"\n \"Use Phono3py.primitive_matrix attribute instead.\",\n DeprecationWarning,\n )\n return self.primitive_matrix\n\n @property\n def unit_conversion_factor(self):\n \"\"\"Return phonon frequency unit conversion factor.\n\n float\n Phonon frequency unit conversion factor. This factor\n converts sqrt(<force>/<distance>/<AMU>)/2pi/1e12 to THz\n (ordinary frequency).\n\n \"\"\"\n return self._frequency_factor_to_THz\n\n def set_displacement_dataset(self, dataset):\n \"\"\"Set displacement-force dataset.\"\"\"\n warnings.warn(\n \"Phono3py.set_displacement_dataset() is deprecated.\"\n \"Use Phono3py.dataset attribute instead.\",\n DeprecationWarning,\n )\n self._dataset = dataset\n\n @property\n def dataset(self):\n \"\"\"Setter and getter of displacement-force dataset.\n\n dict\n Displacements in supercells. There are two types of formats.\n Type 1. Two atomic displacement in each supercell:\n {'natom': number of atoms in supercell,\n 'first_atoms': [\n {'number': atom index of first displaced atom,\n 'displacement': displacement in Cartesian coordinates,\n 'forces': forces on atoms in supercell,\n 'id': displacement id (1, 2,...,n_first_atoms)\n 'second_atoms': [\n {'number': atom index of second displaced atom,\n 'displacement': displacement in Cartesian coordinates},\n 'forces': forces on atoms in supercell,\n 'pair_distance': distance between paired atoms,\n 'included': with cutoff pair distance in displacement\n pair generation, this indicates if this\n pair displacements is included to compute\n fc3 or not,\n 'id': displacement id. (n_first_atoms + 1, ...)\n ... ] }, ... ] }\n Type 2. All atomic displacements in each supercell:\n {'displacements': ndarray, dtype='double', order='C',\n shape=(supercells, atoms in supercell, 3)\n 'forces': ndarray, dtype='double',, order='C',\n shape=(supercells, atoms in supercell, 3)}\n In type 2, displacements and forces can be given by numpy array\n with different shape but that can be reshaped to\n (supercells, natom, 3).\n\n In addition, 'duplicates' and 'cutoff_distance' can exist in this\n dataset in displacement pair generation. 'duplicates' gives\n duplicated supercell ids as pairs.\n\n \"\"\"\n return self._dataset\n\n @dataset.setter\n def dataset(self, dataset):\n self._dataset = dataset\n\n @property\n def displacement_dataset(self):\n \"\"\"Return displacement-force dataset.\"\"\"\n warnings.warn(\n \"Phono3py.displacement_dataset is deprecated.\" \"Use Phono3py.dataset.\",\n DeprecationWarning,\n )\n return self.dataset\n\n def get_displacement_dataset(self):\n \"\"\"Return displacement-force dataset.\"\"\"\n warnings.warn(\n \"Phono3py.get_displacement_dataset() is deprecated.\"\n \"Use Phono3py.dataset.\",\n DeprecationWarning,\n )\n return self.displacement_dataset\n\n @property\n def phonon_dataset(self):\n \"\"\"Setter and getter of displacement-force dataset for fc2.\n\n dict\n Displacements in supercells. There are two types of formats.\n Type 1. Two atomic displacement in each supercell:\n {'natom': number of atoms in supercell,\n 'first_atoms': [\n {'number': atom index of first displaced atom,\n 'displacement': displacement in Cartesian coordinates,\n 'forces': forces on atoms in supercell} ... ]}\n Type 2. All atomic displacements in each supercell:\n {'displacements': ndarray, dtype='double', order='C',\n shape=(supercells, atoms in supercell, 3)\n 'forces': ndarray, dtype='double',, order='C',\n shape=(supercells, atoms in supercell, 3)}\n In type 2, displacements and forces can be given by numpy array\n with different shape but that can be reshaped to\n (supercells, natom, 3).\n\n \"\"\"\n return self._phonon_dataset\n\n @phonon_dataset.setter\n def phonon_dataset(self, dataset):\n self._phonon_dataset = dataset\n\n @property\n def phonon_displacement_dataset(self):\n \"\"\"Return phonon dispalcement-force dataset.\"\"\"\n warnings.warn(\n \"Phono3py.phonon_displacement_dataset is deprecated.\"\n \"Use Phono3py.phonon_dataset.\",\n DeprecationWarning,\n )\n return self._phonon_dataset\n\n def get_phonon_displacement_dataset(self):\n \"\"\"Return phonon dispalcement-force dataset.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_displacement_dataset() is deprecated.\"\n \"Use Phono3py.phonon_dataset.\",\n DeprecationWarning,\n )\n return self.phonon_displacement_dataset\n\n @property\n def band_indices(self):\n \"\"\"Setter and getter of band indices.\n\n array_like\n List of band indices specified to select specific bands\n to computer ph-ph interaction related properties.\n\n \"\"\"\n return self._band_indices\n\n @band_indices.setter\n def band_indices(self, band_indices):\n self._set_band_indices(band_indices=band_indices)\n\n def set_band_indices(self, band_indices):\n \"\"\"Set band indices.\"\"\"\n warnings.warn(\n \"Phono3py.set_band_indices() is deprecated.\"\n \"Use Phono3py.band_indices attribute instead.\",\n DeprecationWarning,\n )\n self.band_indices = band_indices\n\n def _set_band_indices(self, band_indices=None):\n if band_indices is None:\n num_band = len(self._primitive) * 3\n self._band_indices = [np.arange(num_band, dtype=\"int_\")]\n else:\n self._band_indices = band_indices\n self._band_indices_flatten = np.hstack(self._band_indices).astype(\"int_\")\n\n @property\n def masses(self):\n \"\"\"Setter and getter of atomic masses of primitive cell.\"\"\"\n return self._primitive.masses\n\n @masses.setter\n def masses(self, masses):\n if masses is None:\n return\n p_masses = np.array(masses)\n self._primitive.masses = p_masses\n p2p_map = self._primitive.p2p_map\n s_masses = p_masses[[p2p_map[x] for x in self._primitive.s2p_map]]\n self._supercell.masses = s_masses\n u2s_map = self._supercell.u2s_map\n u_masses = s_masses[u2s_map]\n self._unitcell.masses = u_masses\n self._phonon_primitive.masses = p_masses\n p2p_map = self._phonon_primitive.p2p_map\n s_masses = p_masses[[p2p_map[x] for x in self._phonon_primitive.s2p_map]]\n self._phonon_supercell.masses = s_masses\n\n @property\n def supercells_with_displacements(self):\n \"\"\"Return supercells with displacements.\n\n list of PhonopyAtoms\n Supercells with displacements generated by\n Phono3py.generate_displacements.\n\n \"\"\"\n if self._supercells_with_displacements is None:\n self._build_supercells_with_displacements()\n return self._supercells_with_displacements\n\n def get_supercells_with_displacements(self):\n \"\"\"Return supercells with displacements.\"\"\"\n warnings.warn(\n \"Phono3py.get_supercells_with_displacements() is deprecated.\"\n \"Use Phono3py.supercells_with_displacements attribute instead.\",\n DeprecationWarning,\n )\n return self.supercells_with_displacements\n\n @property\n def phonon_supercells_with_displacements(self):\n \"\"\"Return supercells with displacements for fc2.\n\n list of PhonopyAtoms\n Supercells with displacements generated by\n Phono3py.generate_displacements.\n\n \"\"\"\n if self._phonon_supercells_with_displacements is None:\n if self._phonon_dataset is not None:\n self._phonon_supercells_with_displacements = (\n self._build_phonon_supercells_with_displacements(\n self._phonon_supercell, self._phonon_dataset\n )\n )\n return self._phonon_supercells_with_displacements\n\n def get_phonon_supercells_with_displacements(self):\n \"\"\"Return supercells with displacements for fc2.\"\"\"\n warnings.warn(\n \"Phono3py.get_phonon_supercells_with_displacements() \"\n \"is deprecated. Use Phono3py.phonon_supercells_with_displacements \"\n \"attribute instead.\",\n DeprecationWarning,\n )\n return self.phonon_supercells_with_displacements\n\n @property\n def mesh_numbers(self):\n \"\"\"Setter and getter of sampling mesh numbers in reciprocal space.\"\"\"\n if self._bz_grid is None:\n return None\n else:\n return self._bz_grid.D_diag\n\n @mesh_numbers.setter\n def mesh_numbers(self, mesh_numbers):\n self._set_mesh_numbers(mesh_numbers)\n\n @property\n def thermal_conductivity(self):\n \"\"\"Return thermal conductivity class instance.\"\"\"\n return self._thermal_conductivity\n\n def get_thermal_conductivity(self):\n \"\"\"Return thermal conductivity class instance.\"\"\"\n warnings.warn(\n \"Phono3py.get_thermal_conductivity() is deprecated.\"\n \"Use Phono3py.thermal_conductivity attribute instead.\",\n DeprecationWarning,\n )\n return self.thermal_conductivity\n\n @property\n def displacements(self):\n \"\"\"Setter and getter displacements in supercells.\n\n getter : ndarray\n Displacements of all atoms of all supercells in Cartesian\n coordinates.\n shape=(supercells, natom, 3), dtype='double', order='C'\n\n setter : array_like\n Atomic displacements of all atoms of all supercells.\n shape=(supercells, natom, 3).\n\n If type-1 displacement dataset for fc2 exists already, type-2\n displacement dataset is newly created and information of\n forces is abandoned. If type-1 displacement dataset for fc2\n exists already information of forces is preserved.\n\n \"\"\"\n dataset = self._dataset\n\n if \"first_atoms\" in dataset:\n num_scells = len(dataset[\"first_atoms\"])\n for disp1 in dataset[\"first_atoms\"]:\n num_scells += len(disp1[\"second_atoms\"])\n displacements = np.zeros(\n (num_scells, self._supercell.get_number_of_atoms(), 3),\n dtype=\"double\",\n order=\"C\",\n )\n i = 0\n for disp1 in dataset[\"first_atoms\"]:\n displacements[i, disp1[\"number\"]] = disp1[\"displacement\"]\n i += 1\n for disp1 in dataset[\"first_atoms\"]:\n for disp2 in disp1[\"second_atoms\"]:\n displacements[i, disp2[\"number\"]] = disp2[\"displacement\"]\n i += 1\n elif \"forces\" in dataset or \"displacements\" in dataset:\n displacements = dataset[\"displacements\"]\n else:\n raise RuntimeError(\"displacement dataset has wrong format.\")\n\n return displacements\n\n @displacements.setter\n def displacements(self, displacements):\n dataset = self._dataset\n disps = np.array(displacements, dtype=\"double\", order=\"C\")\n natom = self._supercell.get_number_of_atoms()\n if disps.ndim != 3 or disps.shape[1:] != (natom, 3):\n raise RuntimeError(\"Array shape of displacements is incorrect.\")\n\n if \"first_atoms\" in dataset:\n dataset = {\"displacements\": disps}\n elif \"displacements\" in dataset or \"forces\" in dataset:\n dataset[\"displacements\"] = disps\n\n @property\n def forces(self):\n \"\"\"Setter and getter of forces in displacement dataset.\n\n A set of atomic forces in displaced supercells. The order of\n displaced supercells has to match with that in displacement dataset.\n shape=(displaced supercells, atoms in supercell, 3)\n\n getter : ndarray\n\n setter : array_like\n The order of supercells used for calculating forces has to\n be the same order of supercells_with_displacements.\n\n \"\"\"\n dataset = self._dataset\n if \"forces\" in dataset:\n return dataset[\"forces\"]\n elif \"first_atoms\" in dataset:\n num_scells = len(dataset[\"first_atoms\"])\n for disp1 in dataset[\"first_atoms\"]:\n num_scells += len(disp1[\"second_atoms\"])\n forces = np.zeros(\n (num_scells, self._supercell.get_number_of_atoms(), 3),\n dtype=\"double\",\n order=\"C\",\n )\n i = 0\n for disp1 in dataset[\"first_atoms\"]:\n forces[i] = disp1[\"forces\"]\n i += 1\n for disp1 in dataset[\"first_atoms\"]:\n for disp2 in disp1[\"second_atoms\"]:\n forces[i] = disp2[\"forces\"]\n i += 1\n return forces\n else:\n raise RuntimeError(\"displacement dataset has wrong format.\")\n\n @forces.setter\n def forces(self, forces_fc3):\n forces = np.array(forces_fc3, dtype=\"double\", order=\"C\")\n dataset = self._dataset\n if \"first_atoms\" in dataset:\n i = 0\n for disp1 in dataset[\"first_atoms\"]:\n disp1[\"forces\"] = forces[i]\n i += 1\n for disp1 in dataset[\"first_atoms\"]:\n for disp2 in disp1[\"second_atoms\"]:\n disp2[\"forces\"] = forces[i]\n i += 1\n elif \"displacements\" in dataset or \"forces\" in dataset:\n dataset[\"forces\"] = forces\n\n @property\n def phonon_displacements(self):\n \"\"\"Setter and getter of displacements in supercells for fc2.\n\n Displacements of all atoms of all supercells in Cartesian\n coordinates.\n shape=(supercells, natom, 3), dtype='double', order='C'\n\n getter : ndarray\n\n setter : array_like\n If type-1 displacement dataset for fc2 exists already, type-2\n displacement dataset is newly created and information of\n forces is abandoned. If type-1 displacement dataset for fc2\n exists already information of forces is preserved.\n\n \"\"\"\n if self._phonon_dataset is None:\n raise RuntimeError(\"phonon_displacement_dataset does not exist.\")\n\n dataset = self._phonon_dataset\n if \"first_atoms\" in dataset:\n num_scells = len(dataset[\"first_atoms\"])\n natom = self._phonon_supercell.get_number_of_atoms()\n displacements = np.zeros((num_scells, natom, 3), dtype=\"double\", order=\"C\")\n for i, disp1 in enumerate(dataset[\"first_atoms\"]):\n displacements[i, disp1[\"number\"]] = disp1[\"displacement\"]\n elif \"forces\" in dataset or \"displacements\" in dataset:\n displacements = dataset[\"displacements\"]\n else:\n raise RuntimeError(\"displacement dataset has wrong format.\")\n\n return displacements\n\n @phonon_displacements.setter\n def phonon_displacements(self, displacements):\n if self._phonon_dataset is None:\n raise RuntimeError(\"phonon_displacement_dataset does not exist.\")\n\n dataset = self._phonon_dataset\n disps = np.array(displacements, dtype=\"double\", order=\"C\")\n natom = self._phonon_supercell.get_number_of_atoms()\n if disps.ndim != 3 or disps.shape[1:] != (natom, 3):\n raise RuntimeError(\"Array shape of displacements is incorrect.\")\n\n if \"first_atoms\" in dataset:\n dataset = {\"displacements\": disps}\n elif \"displacements\" in dataset or \"forces\" in dataset:\n dataset[\"displacements\"] = disps\n\n @property\n def phonon_forces(self):\n \"\"\"Setter and getter of forces in displacement dataset for fc2.\n\n A set of atomic forces in displaced supercells. The order of\n displaced supercells has to match with that in phonon displacement\n dataset.\n shape=(displaced supercells, atoms in supercell, 3)\n\n getter : ndarray\n\n setter : array_like\n The order of supercells used for calculating forces has to\n be the same order of phonon_supercells_with_displacements.\n\n \"\"\"\n if self._phonon_dataset is None:\n raise RuntimeError(\"phonon_displacement_dataset does not exist.\")\n\n dataset = self._phonon_dataset\n if \"forces\" in dataset:\n return dataset[\"forces\"]\n elif \"first_atoms\" in dataset:\n num_scells = len(dataset[\"first_atoms\"])\n forces = np.zeros(\n (num_scells, self._phonon_supercell.get_number_of_atoms(), 3),\n dtype=\"double\",\n order=\"C\",\n )\n for i, disp1 in enumerate(dataset[\"first_atoms\"]):\n forces[i] = disp1[\"forces\"]\n return forces\n else:\n raise RuntimeError(\"displacement dataset has wrong format.\")\n\n @phonon_forces.setter\n def phonon_forces(self, forces_fc2):\n if self._phonon_dataset is None:\n raise RuntimeError(\"phonon_displacement_dataset does not exist.\")\n\n forces = np.array(forces_fc2, dtype=\"double\", order=\"C\")\n dataset = self._phonon_dataset\n if \"first_atoms\" in dataset:\n i = 0\n for i, disp1 in enumerate(dataset[\"first_atoms\"]):\n disp1[\"forces\"] = forces[i]\n i += 1\n elif \"displacements\" in dataset or \"forces\" in dataset:\n dataset[\"forces\"] = forces\n\n @property\n def phph_interaction(self):\n \"\"\"Return Interaction instance.\"\"\"\n return self._interaction\n\n def get_phph_interaction(self):\n \"\"\"Return Interaction instance.\"\"\"\n warnings.warn(\n \"Phono3py.get_phph_interaction() is deprecated.\"\n \"Use Phono3py.phph_interaction attribute instead.\",\n DeprecationWarning,\n )\n return self.phph_interaction\n\n @property\n def detailed_gammas(self):\n \"\"\"Return detailed gamma.\"\"\"\n return self._detailed_gammas\n\n @property\n def grid(self):\n \"\"\"Return Brillouin zone grid information.\n\n BZGrid\n An instance of BZGrid used for entire phono3py calculation.\n\n \"\"\"\n return self._bz_grid\n\n def init_phph_interaction(\n self,\n nac_q_direction=None,\n constant_averaged_interaction=None,\n frequency_scale_factor=None,\n symmetrize_fc3q=False,\n lapack_zheev_uplo=\"L\",\n ):\n \"\"\"Initialize ph-ph interaction calculation.\n\n This method creates an instance of Interaction class, which\n is necessary to run ph-ph interaction calculation.\n The input data such as grids, force constants, etc, are\n stored to be ready for the calculation.\n\n Note\n ----\n fc3 and fc2, and optionally nac_params have to be set before calling\n this method. fc3 and fc2 can be made either from sets of forces\n and displacements of supercells or be set simply via attributes.\n\n Parameters\n ----------\n nac_q_direction : array_like, optional\n Direction of q-vector watching from Gamma point used for\n non-analytical term correction. This is effective only at q=0\n (physically q->0). The direction is given in crystallographic\n (fractional) coordinates.\n shape=(3,), dtype='double'.\n Default value is None, which means this feature is not used.\n constant_averaged_interaction : float, optional\n Ph-ph interaction strength array is replaced by a scalar value.\n Default is None, which means this feature is not used.\n frequency_scale_factor : float, optional\n All phonon frequences are scaled by this value. Default is None,\n which means phonon frequencies are not scaled.\n symmetrize_fc3q : bool, optional\n fc3 in phonon space is symmetrized by permutation symmetry.\n Default is False.\n lapack_zheev_uplo : str, optional\n 'L' or 'U'. Default is 'L'. This is passed to LAPACK zheev\n used for phonon solver.\n\n \"\"\"\n if self.mesh_numbers is None:\n msg = \"Phono3py.mesh_numbers of instance has to be set.\"\n raise RuntimeError(msg)\n\n if self._fc2 is None:\n msg = \"Phono3py.fc2 of instance is not found.\"\n raise RuntimeError(msg)\n\n if self._symmetrize_fc3q is None:\n _symmetrize_fc3q = symmetrize_fc3q\n else:\n _symmetrize_fc3q = self._symmetrize_fc3q\n\n if self._lapack_zheev_uplo is None:\n _lapack_zheev_uplo = lapack_zheev_uplo\n else:\n _lapack_zheev_uplo = self._lapack_zheev_uplo\n\n self._interaction = Interaction(\n self._primitive,\n self._bz_grid,\n self._primitive_symmetry,\n fc3=self._fc3,\n band_indices=self._band_indices_flatten,\n constant_averaged_interaction=constant_averaged_interaction,\n frequency_factor_to_THz=self._frequency_factor_to_THz,\n frequency_scale_factor=frequency_scale_factor,\n cutoff_frequency=self._cutoff_frequency,\n is_mesh_symmetry=self._is_mesh_symmetry,\n symmetrize_fc3q=_symmetrize_fc3q,\n lapack_zheev_uplo=_lapack_zheev_uplo,\n )\n self._interaction.nac_q_direction = nac_q_direction\n self._init_dynamical_matrix()\n\n def set_phonon_data(self, frequencies, eigenvectors, grid_address):\n \"\"\"Set phonon frequencies and eigenvectors in Interaction instance.\n\n Harmonic phonon information is stored in Interaction instance. For\n example, this information store in a file is read and passed to\n Phono3py instance by using this method. The grid_address is used\n for the consistency check.\n\n Parameters\n ----------\n frequencies : array_like\n Phonon frequencies.\n shape=(num_grid_points, num_band), dtype='double', order='C'\n eigenvectors : array_like\n Phonon eigenvectors\n shape=(num_grid_points, num_band, num_band)\n dtype='complex128', order='C'\n grid_address : array_like\n Grid point addresses by integers. The first dimension may not be\n prod(mesh) because it includes Brillouin zone boundary. The detail\n is found in the docstring of\n phono3py.phonon3.triplets.get_triplets_at_q.\n shape=(num_grid_points, 3), dtype=int\n\n \"\"\"\n if self._interaction is not None:\n self._interaction.set_phonon_data(frequencies, eigenvectors, grid_address)\n\n def get_phonon_data(self):\n \"\"\"Get phonon frequencies and eigenvectors in Interaction instance.\n\n Harmonic phonon information is stored in Interaction instance. This\n information can be obtained. The grid_address returned give the\n q-points locations with respect to reciprocal basis vectors by\n integers in the way that\n q_points = grid_address / np.array(mesh, dtype='double').\n\n Returns\n -------\n tuple\n (frequencies, eigenvectors, grid_address)\n See more details at the docstring of set_phonon_data.\n\n \"\"\"\n if self._interaction is not None:\n freqs, eigvecs, _ = self._interaction.get_phonons()\n return freqs, eigvecs, self._interaction.bz_grid.addresses\n else:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n def run_phonon_solver(self, grid_points=None):\n \"\"\"Run harmonic phonon calculation on grid points.\n\n Parameters\n ----------\n grid_points : array_like or None, optional\n A list of grid point indices of Phono3py.grid.addresses.\n Specifying None runs all phonons on the grid points unless\n those phonons were already calculated. Normally phonons at\n [0, 0, 0] point is already calculated before calling this method.\n Phonon calculations are performed automatically when needed\n internally for ph-ph calculation. Therefore calling this method\n is not necessary in most cases.\n The phonon results are obtained by Phono3py.get_phonon_data().\n\n \"\"\"\n if self._interaction is not None:\n self._interaction.run_phonon_solver(grid_points=grid_points)\n else:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n def generate_displacements(\n self,\n distance=0.03,\n cutoff_pair_distance=None,\n is_plusminus=\"auto\",\n is_diagonal=True,\n ):\n \"\"\"Generate displacement dataset in supercell for fc3.\n\n This systematically generates single and pair atomic displacements\n in supercells to calculate fc3 considering crystal symmetry.\n When this method is called, existing cache of supercells with\n displacements for fc3 are removed.\n\n For fc3, two atoms are displaced for each configuration\n considering crystal symmetry. The first displacement is chosen\n in the perfect supercell, and the second displacement in the\n displaced supercell. The first displacements are taken along\n the basis vectors of the supercell. This is because the\n symmetry is expected to be less broken by the introduced first\n displacement, and as the result, the number of second\n displacements may become smaller than the case that the first\n atom is displaced not along the basis vectors.\n\n Note\n ----\n When phonon_supercell_matrix is not given, fc2 is also\n computed from the same set of the displacements for fc3 and\n respective supercell forces. When phonon_supercell_matrix is\n set, the displacements in phonon_supercell are generated unless\n those already exist.\n\n Parameters\n ----------\n distance : float, optional\n Constant displacement Euclidean distance. Default is 0.03.\n cutoff_pair_distance : float, optional\n This is used as a cutoff Euclidean distance to determine if\n each pair of displacements is considered to calculate fc3 or not.\n Default is None, which means cutoff is not used.\n is_plusminus : True, False, or 'auto', optional\n With True, atomis are displaced in both positive and negative\n directions. With False, only one direction. With 'auto',\n mostly equivalent to is_plusminus=True, but only one direction\n is chosen when the displacements in both directions are\n symmetrically equivalent. Default is 'auto'.\n is_diagonal : Bool, optional\n With False, the second displacements are made along the basis\n vectors of the supercell. With True, direction not along the basis\n vectors can be chosen when the number of the displacements\n may be reduced.\n\n \"\"\"\n direction_dataset = get_third_order_displacements(\n self._supercell,\n self._symmetry,\n is_plusminus=is_plusminus,\n is_diagonal=is_diagonal,\n )\n self._dataset = direction_to_displacement(\n direction_dataset,\n distance,\n self._supercell,\n cutoff_distance=cutoff_pair_distance,\n )\n self._supercells_with_displacements = None\n\n if self._phonon_supercell_matrix is not None and self._phonon_dataset is None:\n self.generate_fc2_displacements(\n distance=distance, is_plusminus=is_plusminus, is_diagonal=False\n )\n\n def generate_fc2_displacements(\n self, distance=0.03, is_plusminus=\"auto\", is_diagonal=False\n ):\n \"\"\"Generate displacement dataset in phonon supercell for fc2.\n\n This systematically generates single atomic displacements\n in supercells to calculate phonon_fc2 considering crystal symmetry.\n When this method is called, existing cache of supercells with\n displacements for fc2 are removed.\n\n Note\n ----\n is_diagonal=False is chosen as the default setting intentionally\n to be consistent to the first displacements of the fc3 pair\n displacemets in supercell.\n\n Parameters\n ----------\n distance : float, optional\n Constant displacement Euclidean distance. Default is 0.03.\n is_plusminus : True, False, or 'auto', optional\n With True, atomis are displaced in both positive and negative\n directions. With False, only one direction. With 'auto',\n mostly equivalent to is_plusminus=True, but only one direction\n is chosen when the displacements in both directions are\n symmetrically equivalent. Default is 'auto'.\n is_diagonal : Bool, optional\n With False, the displacements are made along the basis\n vectors of the supercell. With True, direction not along the basis\n vectors can be chosen when the number of the displacements\n may be reduced. Default is False.\n\n \"\"\"\n if self._phonon_supercell_matrix is None:\n msg = (\n \"phonon_supercell_matrix is not set. \"\n \"This method is used to generate displacements to \"\n \"calculate phonon_fc2.\"\n )\n raise RuntimeError(msg)\n\n phonon_displacement_directions = get_least_displacements(\n self._phonon_supercell_symmetry,\n is_plusminus=is_plusminus,\n is_diagonal=is_diagonal,\n )\n self._phonon_dataset = directions_to_displacement_dataset(\n phonon_displacement_directions, distance, self._phonon_supercell\n )\n self._phonon_supercells_with_displacements = None\n\n def produce_fc3(\n self,\n symmetrize_fc3r=False,\n is_compact_fc=False,\n fc_calculator=None,\n fc_calculator_options=None,\n ):\n \"\"\"Calculate fc3 from displacements and forces.\n\n Parameters\n ----------\n symmetrize_fc3r : bool\n Only for type 1 displacement_dataset, translational and\n permutation symmetries are applied after creating fc3. This\n symmetrization is not very sophisticated and can break space\n group symmetry, but often useful. If better symmetrization is\n expected, it is recommended to use external force constants\n calculator such as ALM. Default is False.\n is_compact_fc : bool\n fc3 shape is\n False: (supercell, supercell, supecell, 3, 3, 3)\n True: (primitive, supercell, supecell, 3, 3, 3)\n where 'supercell' and 'primitive' indicate number of atoms in these\n cells. Default is False.\n fc_calculator : str or None\n Force constants calculator given by str.\n fc_calculator_options : dict\n Options for external force constants calculator.\n\n \"\"\"\n disp_dataset = self._dataset\n\n if fc_calculator is not None:\n disps, forces = get_displacements_and_forces_fc3(disp_dataset)\n fc2, fc3 = get_fc3(\n self._supercell,\n self._primitive,\n disps,\n forces,\n fc_calculator=fc_calculator,\n fc_calculator_options=fc_calculator_options,\n is_compact_fc=is_compact_fc,\n log_level=self._log_level,\n )\n else:\n if \"displacements\" in disp_dataset:\n msg = (\n \"fc_calculator has to be set to produce force \"\n \"constans from this dataset.\"\n )\n raise RuntimeError(msg)\n fc2, fc3 = get_phono3py_fc3(\n self._supercell,\n self._primitive,\n disp_dataset,\n self._symmetry,\n is_compact_fc=is_compact_fc,\n verbose=self._log_level,\n )\n if symmetrize_fc3r:\n if is_compact_fc:\n set_translational_invariance_compact_fc3(fc3, self._primitive)\n set_permutation_symmetry_compact_fc3(fc3, self._primitive)\n if self._fc2 is None:\n symmetrize_compact_force_constants(fc2, self._primitive)\n else:\n set_translational_invariance_fc3(fc3)\n set_permutation_symmetry_fc3(fc3)\n if self._fc2 is None:\n symmetrize_force_constants(fc2)\n\n # Set fc2 and fc3\n self._fc3 = fc3\n\n # Normally self._fc2 is overwritten in produce_fc2\n if self._fc2 is None:\n self._fc2 = fc2\n\n def produce_fc2(\n self,\n symmetrize_fc2=False,\n is_compact_fc=False,\n fc_calculator=None,\n fc_calculator_options=None,\n ):\n \"\"\"Calculate fc2 from displacements and forces.\n\n Parameters\n ----------\n symmetrize_fc2 : bool\n Only for type 1 displacement_dataset, translational and\n permutation symmetries are applied after creating fc3. This\n symmetrization is not very sophisticated and can break space\n group symmetry, but often useful. If better symmetrization is\n expected, it is recommended to use external force constants\n calculator such as ALM. Default is False.\n is_compact_fc : bool\n fc2 shape is\n False: (supercell, supecell, 3, 3)\n True: (primitive, supecell, 3, 3)\n where 'supercell' and 'primitive' indicate number of atoms in these\n cells. Default is False.\n fc_calculator : str or None\n Force constants calculator given by str.\n fc_calculator_options : dict\n Options for external force constants calculator.\n\n \"\"\"\n if self._phonon_dataset is None:\n disp_dataset = self._dataset\n else:\n disp_dataset = self._phonon_dataset\n\n if is_compact_fc:\n p2s_map = self._phonon_primitive.p2s_map\n else:\n p2s_map = None\n\n if fc_calculator is not None:\n disps, forces = get_displacements_and_forces(disp_dataset)\n self._fc2 = get_fc2(\n self._phonon_supercell,\n self._phonon_primitive,\n disps,\n forces,\n fc_calculator=fc_calculator,\n fc_calculator_options=fc_calculator_options,\n atom_list=p2s_map,\n log_level=self._log_level,\n )\n else:\n if \"displacements\" in disp_dataset:\n msg = (\n \"fc_calculator has to be set to produce force \"\n \"constans from this dataset for fc2.\"\n )\n raise RuntimeError(msg)\n self._fc2 = get_phonopy_fc2(\n self._phonon_supercell,\n self._phonon_supercell_symmetry,\n disp_dataset,\n atom_list=p2s_map,\n )\n if symmetrize_fc2:\n if is_compact_fc:\n symmetrize_compact_force_constants(\n self._fc2, self._phonon_primitive\n )\n else:\n symmetrize_force_constants(self._fc2)\n\n def cutoff_fc3_by_zero(self, cutoff_distance, fc3=None):\n \"\"\"Set zero to fc3 elements out of cutoff distance.\n\n Note\n ----\n fc3 is overwritten.\n\n Parameters\n ----------\n cutoff_distance : float\n After creating force constants, fc elements where any pair\n distance in atom triplets larger than cutoff_distance are set zero.\n\n \"\"\"\n if fc3 is None:\n _fc3 = self._fc3\n else:\n _fc3 = fc3\n cutoff_fc3_by_zero(\n _fc3,\n self._supercell,\n cutoff_distance,\n p2s_map=self._primitive.p2s_map,\n symprec=self._symprec,\n )\n\n def set_permutation_symmetry(self):\n \"\"\"Enforce permutation symmetry to fc2 and fc3.\"\"\"\n if self._fc2 is not None:\n set_permutation_symmetry(self._fc2)\n if self._fc3 is not None:\n set_permutation_symmetry_fc3(self._fc3)\n\n def set_translational_invariance(self):\n \"\"\"Enforce translation invariance.\n\n This subtracts drift divided by number of elements in each row and\n column.\n\n \"\"\"\n if self._fc2 is not None:\n set_translational_invariance(self._fc2)\n if self._fc3 is not None:\n set_translational_invariance_fc3(self._fc3)\n\n def run_imag_self_energy(\n self,\n grid_points,\n temperatures,\n frequency_points=None,\n frequency_step=None,\n num_frequency_points=None,\n num_points_in_batch=None,\n frequency_points_at_bands=False,\n scattering_event_class=None,\n write_txt=False,\n write_gamma_detail=False,\n keep_gamma_detail=False,\n output_filename=None,\n ):\n \"\"\"Calculate imaginary part of self-energy of bubble diagram (Gamma).\n\n Pi = Delta - i Gamma.\n\n Parameters\n ----------\n grid_points : array_like\n Grid-point indices where imaginary part of self-energies are\n caclculated.\n dtype=int, shape=(grid_points,)\n temperatures : array_like\n Temperatures where imaginary part of self-energies are calculated.\n dtype=float, shape=(temperatures,)\n frequency_points : array_like, optional\n Frequency sampling points. Default is None. With\n frequency_points_at_bands=False and frequency_points is None,\n num_frequency_points or frequency_step is used to generate uniform\n frequency sampling points.\n dtype=float, shape=(frequency_points,)\n frequency_step : float, optional\n Uniform pitch of frequency sampling points. Default is None. This\n results in using num_frequency_points.\n num_frequency_points: Int, optional\n Number of sampling sampling points to be used instead of\n frequency_step. This number includes end points. Default is None,\n which gives 201.\n num_points_in_batch: int, optional\n Number of sampling points in one batch. This is for the frequency\n sampling mode and the sampling points are divided into batches.\n Lager number provides efficient use of multi-cores but more\n memory demanding. Default is None, which give the number of 10.\n frequency_points_at_bands : bool, optional\n Phonon band frequencies are used as frequency points when True.\n Default is False.\n scattering_event_class : int, optional\n Specific choice of scattering event class, 1 or 2 that is specified\n 1 or 2, respectively. The result is stored in gammas. Therefore\n usual gammas are not stored in the variable. Default is None, which\n doesn't specify scattering_event_class.\n write_txt : bool, optional\n Frequency points and imaginary part of self-energies are written\n into text files.\n write_gamma_detail : bool, optional\n Detailed gammas are written into a file in hdf5. Default is False.\n keep_gamma_detail : bool, optional\n With True, detailed gammas are stored. Default is False.\n output_filename : str\n This string is inserted in the output file names.\n\n \"\"\"\n if self._interaction is None:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n if temperatures is None:\n self._temperatures = [\n 300.0,\n ]\n else:\n self._temperatures = temperatures\n self._grid_points = grid_points\n self._scattering_event_class = scattering_event_class\n vals = get_imag_self_energy(\n self._interaction,\n grid_points,\n temperatures,\n sigmas=self._sigmas,\n frequency_points=frequency_points,\n frequency_step=frequency_step,\n frequency_points_at_bands=frequency_points_at_bands,\n num_frequency_points=num_frequency_points,\n num_points_in_batch=num_points_in_batch,\n scattering_event_class=scattering_event_class,\n write_gamma_detail=write_gamma_detail,\n return_gamma_detail=keep_gamma_detail,\n output_filename=output_filename,\n log_level=self._log_level,\n )\n if keep_gamma_detail:\n (self._frequency_points, self._gammas, self._detailed_gammas) = vals\n else:\n self._frequency_points, self._gammas = vals\n\n if write_txt:\n self._write_imag_self_energy(output_filename=output_filename)\n\n return vals\n\n def write_imag_self_energy(self, filename=None):\n \"\"\"Write imaginary part of self energy to a file.\"\"\"\n warnings.warn(\n \"Phono3py.write_imag_self_energy is deprecated.\"\n \"Use Phono3py.run_imag_self_energy with write_txt=True.\",\n DeprecationWarning,\n )\n self._write_imag_self_energy(output_filename=filename)\n\n def _write_imag_self_energy(self, output_filename=None):\n write_imag_self_energy(\n self._gammas,\n self.mesh_numbers,\n self._grid_points,\n self._band_indices,\n self._frequency_points,\n self._temperatures,\n self._sigmas,\n scattering_event_class=self._scattering_event_class,\n output_filename=output_filename,\n is_mesh_symmetry=self._is_mesh_symmetry,\n log_level=self._log_level,\n )\n\n def run_real_self_energy(\n self,\n grid_points,\n temperatures,\n frequency_points_at_bands=False,\n frequency_points=None,\n frequency_step=None,\n num_frequency_points=None,\n epsilons=None,\n write_txt=False,\n write_hdf5=False,\n output_filename=None,\n ):\n \"\"\"Calculate real-part of self-energy of bubble diagram (Delta).\n\n Pi = Delta - i Gamma.\n\n Parameters\n ----------\n grid_points : array_like\n Grid-point indices where real part of self-energies are\n caclculated.\n dtype=int, shape=(grid_points,)\n temperatures : array_like\n Temperatures where real part of self-energies are calculated.\n dtype=float, shape=(temperatures,)\n frequency_points_at_bands : bool, optional\n With False, frequency shifts are calculated at frquency sampling\n points. When True, they are done at the phonon frequencies.\n Default is False.\n frequency_points : array_like, optional\n Frequency sampling points. Default is None. In this case,\n num_frequency_points or frequency_step is used to generate uniform\n frequency sampling points.\n dtype=float, shape=(frequency_points,)\n frequency_step : float, optional\n Uniform pitch of frequency sampling points. Default is None. This\n results in using num_frequency_points.\n num_frequency_points: Int, optional\n Number of sampling sampling points to be used instead of\n frequency_step. This number includes end points. Default is None,\n which gives 201.\n epsilons : array_like\n Smearing widths to computer principal part. When multiple values\n are given frequency shifts for those values are returned.\n dtype=float, shape=(epsilons,)\n write_txt : bool, optional\n Frequency points and real part of self-energies are written\n into text files.\n write_hdf5 : bool\n Results are stored in hdf5 files independently at grid points,\n epsilons, and temperatures.\n output_filename : str\n This string is inserted in the output file names.\n\n \"\"\"\n if self._interaction is None:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n if epsilons is not None:\n _epsilons = epsilons\n else:\n if len(self._sigmas) == 1 and self._sigmas[0] is None:\n _epsilons = None\n elif self._sigmas[0] is None:\n _epsilons = self._sigmas[1:]\n else:\n _epsilons = self._sigmas\n\n # (epsilon, grid_point, temperature, band)\n frequency_points, deltas = get_real_self_energy(\n self._interaction,\n grid_points,\n temperatures,\n epsilons=_epsilons,\n frequency_points=frequency_points,\n frequency_step=frequency_step,\n num_frequency_points=num_frequency_points,\n frequency_points_at_bands=frequency_points_at_bands,\n write_hdf5=write_hdf5,\n output_filename=output_filename,\n log_level=self._log_level,\n )\n\n if write_txt:\n write_real_self_energy(\n deltas,\n self.mesh_numbers,\n grid_points,\n self._band_indices,\n frequency_points,\n temperatures,\n _epsilons,\n output_filename=output_filename,\n is_mesh_symmetry=self._is_mesh_symmetry,\n log_level=self._log_level,\n )\n\n return frequency_points, deltas\n\n def run_spectral_function(\n self,\n grid_points,\n temperatures,\n frequency_points=None,\n frequency_step=None,\n num_frequency_points=None,\n num_points_in_batch=None,\n write_txt=False,\n write_hdf5=False,\n output_filename=None,\n ):\n \"\"\"Frequency shift from lowest order diagram is calculated.\n\n Parameters\n ----------\n grid_points : array_like\n Grid-point indices where imag-self-energeis are caclculated.\n dtype=int, shape=(grid_points,)\n temperatures : array_like\n Temperatures where imag-self-energies are calculated.\n dtype=float, shape=(temperatures,)\n frequency_points : array_like, optional\n Frequency sampling points. Default is None. In this case,\n num_frequency_points or frequency_step is used to generate uniform\n frequency sampling points.\n dtype=float, shape=(frequency_points,)\n frequency_step : float, optional\n Uniform pitch of frequency sampling points. Default is None. This\n results in using num_frequency_points.\n num_frequency_points: Int, optional\n Number of sampling sampling points to be used instead of\n frequency_step. This number includes end points. Default is None,\n which gives 201.\n num_points_in_batch: int, optional\n Number of sampling points in one batch. This is for the frequency\n sampling mode and the sampling points are divided into batches.\n Lager number provides efficient use of multi-cores but more\n memory demanding. Default is None, which give the number of 10.\n write_txt : bool, optional\n Frequency points and spectral functions are written\n into text files. Default is False.\n write_hdf5 : bool\n Results are stored in hdf5 files independently at grid points,\n epsilons. Default is False.\n output_filename : str\n This string is inserted in the output file names.\n\n \"\"\"\n if self._interaction is None:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n self._spectral_function = run_spectral_function(\n self._interaction,\n grid_points,\n temperatures=temperatures,\n sigmas=self._sigmas,\n frequency_points=frequency_points,\n frequency_step=frequency_step,\n num_frequency_points=num_frequency_points,\n num_points_in_batch=num_points_in_batch,\n band_indices=self._band_indices,\n write_txt=write_txt,\n write_hdf5=write_hdf5,\n output_filename=output_filename,\n log_level=self._log_level,\n )\n\n def run_thermal_conductivity(\n self,\n is_LBTE=False,\n temperatures=None,\n is_isotope=False,\n mass_variances=None,\n grid_points=None,\n boundary_mfp=None, # in micrometre\n solve_collective_phonon=False,\n use_ave_pp=False,\n is_reducible_collision_matrix=False,\n is_kappa_star=True,\n gv_delta_q=None, # for group velocity\n is_full_pp=False,\n pinv_cutoff=1.0e-8, # for pseudo-inversion of collision matrix\n pinv_solver=0, # solver of pseudo-inversion of collision matrix\n write_gamma=False,\n read_gamma=False,\n is_N_U=False,\n conductivity_type=None,\n write_kappa=False,\n write_gamma_detail=False,\n write_collision=False,\n read_collision=False,\n write_pp=False,\n read_pp=False,\n write_LBTE_solution=False,\n compression=\"gzip\",\n input_filename=None,\n output_filename=None,\n ):\n \"\"\"Run thermal conductivity calculation.\n\n Parameters\n ----------\n is_LBTE : bool, optional, default is False\n RTA (False) or direct solution (True).\n temperatures : array_like, optional, default is None\n Temperatures at which thermal conductivity is calculated.\n shape=(temperature_points, ), dtype='double'.\n With None,\n `is_LBTE=False` gives temperatures=[0, 10, ..., 1000].\n `is_LBTE=True` gives temperatures=[300, ].\n is_isotope : bool, optional, default is False\n With or without isotope scattering.\n mass_variances : array_like, optional, default is None\n Mass variances for isotope scattering calculation. When None,\n the values stored in phono3py are used with `is_isotope=True`.\n shape(atoms_in_primitive, ), dtype='double'.\n grid_points : array_like, optional, default is None\n List of grid point indices where mode thermal conductivities are\n calculated. With None, all the grid points that are necessary\n for thermal conductivity are set internally.\n shape(num_grid_points, ), dtype='int_'.\n boundary_mfp : float, optiona, default is None\n Mean free path in micrometre to calculate simple boundary\n scattering contribution to thermal conductivity.\n None gives 1 metre, which is supposed negligible contribution,\n but this value is used to avoid divergence of phonon lifetime.\n solve_collective_phonon : bool, optional, default is False\n This is an option for the feature under development.\n use_ave_pp : bool, optional, default is False\n RTA only (`is_LBTE=False`). Averaged phonon-phonon interaction\n strength is used to calculate phonon lifetime. This does not\n reduce computational demand, but may be used to model thermal\n conductivity for analyze the calculation results.\n is_reducible_collision_matrix : bool, optional, default is False\n Direct solution only (`is_LBTE=True`). This is an experimental\n option. With True, full collision matrix is created and solved.\n is_kappa_star : bool, optional, default is True\n With true, symmetry is considered when sampling grid points\n at which mode thermal conductivities are calculated.\n gv_delta_q : float, optional, default is None, # for group velocity\n With non-analytical correction, group velocity is calculated\n by central finite difference method. This value gives the distance\n in both directions in 1/Angstrom. The default value will be 1e-5.\n is_full_pp : bool, optional, default is False\n With True, full elements of phonon-phonon interaction strength\n are computed. However with tetrahedron method, part of them are\n known to be zero and unnecessary to calculation. With False,\n those elements are not calculated, by which considerable\n improve of efficiency is expected.\n With smearing method, even if this is set False, full elements\n are computed unless `sigma_cutoff` is specified.\n pinv_cutoff : float, optional, default is 1.0e-8\n Direct solution only (`is_LBTE=True`). This is used as a criterion\n to judge the eigenvalues are considered as zero or not in\n pseudo-inversion of collision matrix.\n pinv_solver : int, optional, default is 0\n Direct solution only (`is_LBTE=True`). Choice of solver of\n pseudo-inversion of collision matrix. 0 means the default choice.\n 1. Lapacke dsyev: Smaller memory consumption than dsyevd, but\n slower. This is the default solver when MKL LAPACKE is\n integrated or scipy is not installed.\n 2. Lapacke dsyevd: Larger memory consumption than dsyev, but\n faster. This is not recommended because sometimes a wrong\n result is obtained.\n 3. Numpy’s dsyevd (linalg.eigh). This is not recommended\n because sometimes a wrong result is obtained.\n 4. Scipy’s dsyev: This is the default solver when scipy is\n installed and MKL LAPACKE is not integrated.\n 5. Scipy’s dsyevd. This is not recommended because sometimes\n a wrong result is obtained.\n The solver choices other than --pinv-solver=1 and\n --pinv-solver=4 are dangerous and not recommend.\n write_gamma : bool, optional, default is False\n RTA only (`is_LBTE=False`). With True, Write mode thermal\n conductivity properties into files at each grid point. With\n `band_indices` or multiple `sigmas` is specified, the files\n are made for each of them, too.\n read_gamma : bool, optional, default is False\n RTA only (`is_LBTE=False`). With True, dead files created by\n `write_gamma=True` instead of calculating phonon-phonon\n interaction strength and imaginary parts of self-energy.\n is_N_U : bool, optional, default is False\n RTA only (`is_LBTE=False`). With True, categorization of normal\n and Umklapp scattering is made and imaginary parts of self energy\n for them are separated.\n conductivity_type : str, optional\n \"wigner\", \"kubo\", or None. Default is None.\n write_kappa : bool, optional, default is False\n With True, thermal conductivity and related properties are\n written into a file. With multiple `sigmas`, respective files\n are created.\n write_gamma_detail : bool, optional, default is False\n RTA only (`is_LBTE=False`). With True, detailed information of\n imaginary parts of self energy is stored into files such as\n those made by `write_gamma`.\n write_collision : bool, optional, default is False\n Direct solution only (`is_LBTE=True`). With True, collision matrix\n is written into a file. With multiple `sigmas` specified,\n respective files are created. Be careful that this file can be\n huge.\n read_collision : bool, optional, default is False\n Direct solution only (`is_LBTE=True`). With True, collision matrix\n is read from a file.\n write_pp : bool, optional, default is False\n With True, phonon-phonon interaction strength is written into\n files at each grid point. This option assumes single value is in\n `sigmas`.\n read_pp : bool, optional, default is False\n With True, phonon-phonon interaction strength is read from files.\n write_LBTE_solution : bool, optional, default is False\n Direct solution only (`is_LBTE=True`). With True, eigenvectors of\n collision matrix is written in a file as the row vectors except\n unless `pinv_solver=3` (for this, column vectors). With multiple\n `sigmas` specified, respective files are created. Be careful that\n this file can be huge.\n compression: str, optional, default is \"gzip\"\n When writing results into files in hdf5, large data are compressed\n by this options. See the detail at h5py documentation.\n input_filename : str, optiona, default is None\n When specified, the string is inserted before filename extension\n in reading files.\n output_filename=None\n When specified, the string is inserted before filename extension\n in writing files.\n\n \"\"\"\n if self._interaction is None:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n if is_LBTE:\n if temperatures is None:\n _temperatures = [\n 300,\n ]\n else:\n _temperatures = temperatures\n self._thermal_conductivity = get_thermal_conductivity_LBTE(\n self._interaction,\n temperatures=_temperatures,\n sigmas=self._sigmas,\n sigma_cutoff=self._sigma_cutoff,\n is_isotope=is_isotope,\n mass_variances=mass_variances,\n grid_points=grid_points,\n boundary_mfp=boundary_mfp,\n solve_collective_phonon=solve_collective_phonon,\n is_reducible_collision_matrix=is_reducible_collision_matrix,\n is_kappa_star=is_kappa_star,\n gv_delta_q=gv_delta_q,\n is_full_pp=is_full_pp,\n conductivity_type=conductivity_type,\n pinv_cutoff=pinv_cutoff,\n pinv_solver=pinv_solver,\n write_collision=write_collision,\n read_collision=read_collision,\n write_kappa=write_kappa,\n write_pp=write_pp,\n read_pp=read_pp,\n write_LBTE_solution=write_LBTE_solution,\n compression=compression,\n input_filename=input_filename,\n output_filename=output_filename,\n log_level=self._log_level,\n )\n else:\n if temperatures is None:\n _temperatures = np.arange(0, 1001, 10, dtype=\"double\")\n else:\n _temperatures = temperatures\n self._thermal_conductivity = get_thermal_conductivity_RTA(\n self._interaction,\n temperatures=_temperatures,\n sigmas=self._sigmas,\n sigma_cutoff=self._sigma_cutoff,\n is_isotope=is_isotope,\n mass_variances=mass_variances,\n grid_points=grid_points,\n boundary_mfp=boundary_mfp,\n use_ave_pp=use_ave_pp,\n is_kappa_star=is_kappa_star,\n gv_delta_q=gv_delta_q,\n is_full_pp=is_full_pp,\n is_N_U=is_N_U,\n conductivity_type=conductivity_type,\n write_gamma=write_gamma,\n read_gamma=read_gamma,\n write_kappa=write_kappa,\n write_pp=write_pp,\n read_pp=read_pp,\n write_gamma_detail=write_gamma_detail,\n compression=compression,\n input_filename=input_filename,\n output_filename=output_filename,\n log_level=self._log_level,\n )\n\n def save(self, filename=\"phono3py_params.yaml\", settings=None):\n \"\"\"Save parameters in Phono3py instants into file.\n\n Parameters\n ----------\n filename: str, optional\n File name. Default is \"phono3py_params.yaml\"\n settings: dict, optional\n It is described which parameters are written out. Only\n the settings expected to be updated from the following\n default settings are needed to be set in the dictionary.\n The possible parameters and their default settings are:\n {'force_sets': False,\n 'displacements': True,\n 'force_constants': False,\n 'born_effective_charge': True,\n 'dielectric_constant': True}\n\n \"\"\"\n ph3py_yaml = Phono3pyYaml(settings=settings)\n ph3py_yaml.set_phonon_info(self)\n with open(filename, \"w\") as w:\n w.write(str(ph3py_yaml))\n\n ###################\n # private methods #\n ###################\n def _search_symmetry(self):\n self._symmetry = Symmetry(self._supercell, self._symprec, self._is_symmetry)\n\n def _search_primitive_symmetry(self):\n self._primitive_symmetry = Symmetry(\n self._primitive, self._symprec, self._is_symmetry\n )\n if len(self._symmetry.pointgroup_operations) != len(\n self._primitive_symmetry.pointgroup_operations\n ): # noqa E129\n print(\n \"Warning: point group symmetries of supercell and primitive\"\n \"cell are different.\"\n )\n\n def _search_phonon_supercell_symmetry(self):\n if self._phonon_supercell_matrix is None:\n self._phonon_supercell_symmetry = self._symmetry\n else:\n self._phonon_supercell_symmetry = Symmetry(\n self._phonon_supercell, self._symprec, self._is_symmetry\n )\n\n def _build_supercell(self):\n self._supercell = get_supercell(\n self._unitcell, self._supercell_matrix, self._symprec\n )\n\n def _build_primitive_cell(self):\n \"\"\"Create primitive cell.\n\n primitive_matrix:\n Relative axes of primitive cell to the input unit cell.\n Relative axes to the supercell is calculated by:\n supercell_matrix^-1 * primitive_matrix\n Therefore primitive cell lattice is finally calculated by:\n (supercell_lattice * (supercell_matrix)^-1 * primitive_matrix)^T\n\n \"\"\"\n self._primitive = self._get_primitive_cell(\n self._supercell, self._supercell_matrix, self._primitive_matrix\n )\n\n def _build_phonon_supercell(self):\n \"\"\"Create phonon supercell for fc2.\n\n phonon_supercell:\n This supercell is used for harmonic phonons (frequencies,\n eigenvectors, group velocities, ...)\n phonon_supercell_matrix:\n Different supercell size can be specified.\n\n \"\"\"\n if self._phonon_supercell_matrix is None:\n self._phonon_supercell = self._supercell\n else:\n self._phonon_supercell = get_supercell(\n self._unitcell, self._phonon_supercell_matrix, self._symprec\n )\n\n def _build_phonon_primitive_cell(self):\n if self._phonon_supercell_matrix is None:\n self._phonon_primitive = self._primitive\n else:\n self._phonon_primitive = self._get_primitive_cell(\n self._phonon_supercell,\n self._phonon_supercell_matrix,\n self._primitive_matrix,\n )\n if (\n self._primitive is not None\n and (self._primitive.numbers != self._phonon_primitive.numbers).any()\n ):\n print(\" Primitive cells for fc2 and fc3 can be different.\")\n raise RuntimeError\n\n def _build_phonon_supercells_with_displacements(\n self, supercell: PhonopyAtoms, displacement_dataset\n ):\n supercells = []\n magmoms = supercell.magnetic_moments\n masses = supercell.masses\n numbers = supercell.numbers\n lattice = supercell.cell\n\n for disp1 in displacement_dataset[\"first_atoms\"]:\n disp_cart1 = disp1[\"displacement\"]\n positions = supercell.positions\n positions[disp1[\"number\"]] += disp_cart1\n supercells.append(\n PhonopyAtoms(\n numbers=numbers,\n masses=masses,\n magnetic_moments=magmoms,\n positions=positions,\n cell=lattice,\n )\n )\n\n return supercells\n\n def _build_supercells_with_displacements(self):\n supercells = []\n magmoms = self._supercell.magnetic_moments\n masses = self._supercell.masses\n numbers = self._supercell.numbers\n lattice = self._supercell.cell\n\n supercells = self._build_phonon_supercells_with_displacements(\n self._supercell, self._dataset\n )\n\n for disp1 in self._dataset[\"first_atoms\"]:\n disp_cart1 = disp1[\"displacement\"]\n for disp2 in disp1[\"second_atoms\"]:\n if \"included\" in disp2:\n included = disp2[\"included\"]\n else:\n included = True\n if included:\n positions = self._supercell.positions\n positions[disp1[\"number\"]] += disp_cart1\n positions[disp2[\"number\"]] += disp2[\"displacement\"]\n supercells.append(\n PhonopyAtoms(\n numbers=numbers,\n masses=masses,\n magnetic_moments=magmoms,\n positions=positions,\n cell=lattice,\n )\n )\n else:\n supercells.append(None)\n\n self._supercells_with_displacements = supercells\n\n def _get_primitive_cell(self, supercell, supercell_matrix, primitive_matrix):\n inv_supercell_matrix = np.linalg.inv(supercell_matrix)\n if primitive_matrix is None:\n t_mat = inv_supercell_matrix\n else:\n t_mat = np.dot(inv_supercell_matrix, primitive_matrix)\n\n return get_primitive(\n supercell, t_mat, self._symprec, store_dense_svecs=self._store_dense_svecs\n )\n\n def _determine_primitive_matrix(self, primitive_matrix):\n pmat = get_primitive_matrix(primitive_matrix, symprec=self._symprec)\n if isinstance(pmat, str) and pmat == \"auto\":\n return guess_primitive_matrix(self._unitcell, symprec=self._symprec)\n else:\n return pmat\n\n def _set_mesh_numbers(self, mesh):\n # initialization related to mesh\n self._interaction = None\n\n self._bz_grid = BZGrid(\n mesh,\n lattice=self._primitive.cell,\n symmetry_dataset=self._primitive_symmetry.dataset,\n is_time_reversal=self._is_symmetry,\n use_grg=self._use_grg,\n force_SNF=False,\n SNF_coordinates=self._SNF_coordinates,\n store_dense_gp_map=self._store_dense_gp_map,\n )\n\n def _init_dynamical_matrix(self):\n if self._interaction is None:\n msg = (\n \"Phono3py.init_phph_interaction has to be called \"\n \"before running this method.\"\n )\n raise RuntimeError(msg)\n\n self._interaction.init_dynamical_matrix(\n self._fc2,\n self._phonon_supercell,\n self._phonon_primitive,\n nac_params=self._nac_params,\n )\n freqs, _, _ = self.get_phonon_data()\n gp_Gamma = self._bz_grid.gp_Gamma\n if np.sum(freqs[gp_Gamma] < self._cutoff_frequency) < 3:\n for i, f in enumerate(freqs[gp_Gamma, :3]):\n if not (f < self._cutoff_frequency):\n freqs[gp_Gamma, i] = 0\n print(\"=\" * 26 + \" Warning \" + \"=\" * 26)\n print(\n \" Phonon frequency of band index %d at Gamma \"\n \"is calculated to be %f.\" % (i + 1, f)\n )\n print(\" But this frequency is forced to be zero.\")\n print(\"=\" * 61)\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.zeros",
"numpy.sum",
"numpy.arange",
"numpy.hstack",
"numpy.linalg.inv"
]
]
|
matthewjones372/winning-ticket-search | [
"17b5e5dbb35c31de37232418ce53dd712ade5619"
]
| [
"lottery/metrics/DataLogger.py"
]
| [
"import csv\nimport os\nfrom typing import Mapping, List\n\nimport pandas as pd\n\n\nclass DataLogger:\n def __init__(self, headers: List[str], file_name: str, base_path: str):\n self.base_path = base_path\n self.file_name = file_name\n self.file_path = os.path.join(self.base_path, self.file_name)\n self.headers = headers\n\n def write(self, row: Mapping[str, any]):\n return self.write_rows([row])\n\n def write_rows(self, rows: List[Mapping[str, any]], map_headers=True):\n file_exists = os.path.exists(self.file_path)\n mode = \"a\" if file_exists else \"w\"\n with open(self.file_path, mode, newline=\"\", encoding=\"UTF8\") as fp:\n writer = csv.DictWriter(fp, fieldnames=self.headers)\n\n if not file_exists:\n writer.writeheader()\n\n mapped_rows = (\n [dict(zip(self.headers, row)) for row in rows] if map_headers else rows\n )\n writer.writerows(mapped_rows)\n\n def load(self):\n with open(self.file_path) as fp:\n return pd.read_csv(fp)\n"
]
| [
[
"pandas.read_csv"
]
]
|
shmillo/SimplePythonExamples | [
"1ed23af998220448c510cebc03af5ccdbd37a131"
]
| [
"simplePhysics/DiscreteGradient/1D/oneDimensionalGradient.py"
]
| [
"import matplotlib.pyplot as mplt\nimport numpy as np\n\ndef f(x):\n return x**2.0\n\ndef oneDGradient(vals, dx):\n\n n = len(vals)\n grad = [0.0] * n\n\n #forward difference for outer bounds\n grad[0] = (vals[1] - vals[0]) / dx\n for i in range(1, n - 1):\n #central difference now that data is available\n grad[i] = (vals[i + 1] - vals[i - 1]) / (2.0 * dx)\n #forward difference for outer bounds\n grad[n - 1] = (vals[n - 1] - vals[n - 2]) / dx\n\n return grad\n\n#########################################\n\n#dimensions\nNx = 21; # Number of X-grid points\ndx = 1.0; # x coordinate grid spacing \n\n########## sanity check against numpy ##\n\n#establish X axis\nX = np.arange(0, Nx, dx)\n#compute function LUT\nfx = X**2.0\n#compute derivative in 1D\ndFdX = np.gradient(fx, dx)\n\n########## my implementation ##########\n\ntestData = [0.0] * Nx \n\nx = 0\nfor i in range(Nx):\n #function LUT\n testData[i] = f(x)\n #x axis\n x += dx\n\n#computer gradient\ngradientData = oneDGradient( testData, dx )\n\n#########################################\n \nfig, (ax1, ax2) = mplt.subplots(2)\n\nax1.plot(testData, label = 'my implementation')\nax1.plot(gradientData)\nax1.legend( bbox_to_anchor = (1.0, 1), loc = 'upper right' )\n\nax2.plot(fx, label = 'numpy implementation')\nax2.plot(dFdX)\nax2.legend( bbox_to_anchor = (1.0, 1), loc = 'upper right' )\n\nmplt.show()\n\n"
]
| [
[
"numpy.gradient",
"numpy.arange",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
]
|
touqir14/Scipy_dev | [
"38ff2a484d6d268de8f0fb745fafa9ac3acb98bb"
]
| [
"LP_presolve/_matrix_compress.py"
]
| [
"import numpy as np\nimport random\nimport time\nfrom scipy.sparse import random as sparse_random\nfrom scipy import stats\nimport rref\nimport scipy.linalg.interpolative as ID\nfrom scipy.linalg import qr\n# import rref_cy.rref_cy as rref\n\ndef _build_magical_graph(num_nodes_X, num_groups_Y):\n \"\"\"\n Builds a magical graph. A magical graph is a bipartite graph\n generated by randomly adding edges between the nodes of two\n identical sets such that the degree of each node is at most 2.\n Additionally, one of the set (Y) needs to be partitioned into\n num_groups_Y number of partitions such that the total edge\n connections is 2 * |X| / num_groups_Y, where X is the other set.\n The nodes are denoted by integers.\n\n Parameters\n ----------\n\n num_nodes_X : (Integer)\n Refers to the total number of columns of matrix A\n which is to be compressed by _matrix_compressor\n\n num_groups_Y : (Integer)\n Refers to the number of columns the newly compressed\n matrix B needs to have. Matrix B is generated from _matrix_compressor\n based on the input matrix A such that\n min(rank_A, num_groups_Y) = min(rank_B, num_groups_Y).\n\n\n Returns\n ----------\n\n Y_edges : (2D array)\n Its dimension is [num_groups_Y, 2*num_nodes_X_new] such that num_nodes_X_new\n is either num_nodes_X or an expanded number of nodes to ensure that\n num_nodes_X_new is a multiple of num_groups_Y.\n num_nodes_X_new is the maximum number nodes that each parition of Y can\n contain. Y_edges[i,:] contains all the nodes of X that are connected to the\n nodes within partition 'i' of Y.\n\n num_group_edges : (1D array)\n num_group_edges[i] contains the total number of edges of the nodes within\n partition 'i' of Y.\n\n \"\"\"\n\n if num_nodes_X % num_groups_Y == 0:\n size_groups_Y = int(num_nodes_X / num_groups_Y)\n num_nodes_X_new = num_nodes_X\n else:\n size_groups_Y = int(num_nodes_X / num_groups_Y) + 1\n num_nodes_X_new = num_nodes_X + \\\n num_groups_Y - (num_nodes_X % num_groups_Y)\n\n # One side of the bipartite graph\n X1_edges = -1 * np.ones(num_nodes_X_new, dtype=int)\n # The other side of the bipartite graph\n X2_edges = -1 * np.ones(num_nodes_X_new, dtype=int)\n # At most degree of 2 for each node within the groups\n Y_edges = np.zeros((num_groups_Y, 2 * size_groups_Y), dtype=int)\n num_group_edges = np.zeros(num_groups_Y, dtype=int)\n\n # _build_perfect_matching1(X1_edges, X2_edges, num_nodes_X, num_nodes_X_new)\n _build_perfect_matching2(X1_edges, X2_edges)\n\n idx_col = 0\n for i in range(num_nodes_X_new):\n x1 = X1_edges[i]\n x2 = X2_edges[i]\n idx_row = i // size_groups_Y\n\n if x1 == x2:\n if x1 != -1:\n Y_edges[idx_row, idx_col] = x1\n idx_col += 1\n else:\n if x1 != -1:\n Y_edges[idx_row, idx_col] = x1\n idx_col += 1\n if x2 != -1:\n Y_edges[idx_row, idx_col] = x2\n idx_col += 1\n\n if i % size_groups_Y == size_groups_Y - 1:\n if idx_col <= Y_edges.shape[1] - 1:\n Y_edges[idx_row, idx_col] = -1\n\n num_group_edges[idx_row] = idx_col\n idx_col = 0\n\n # print(Y_edges)\n return Y_edges, num_group_edges\n\n\ndef _build_perfect_matching1(X1_edges, X2_edges, num_nodes_X, num_nodes_X_new):\n \"\"\"\n Builds two perfect matching based on a fully connected graph composed on num_nodes_X_new\n number of nodes. The function randomly samples the edges within the two perfect\n matchings X1 and X2. After execution, X1_edges[i], corresponding to X1, denotes the node\n with which node i has an undirected edge. The same rule applies to X2_edges.\n With this algorithm, the union of the two matchings is not guaranteed to contain all\n the nodes in X. Also, this algorithm only permits nodes that are within the original\n X (and not the expanded X) within the matchings.\n\n Parameters\n ----------\n\n X1_edges: (1D numpy array)\n X1_edges[i] denotes the node that node i will be matched with within perfect matching X1.\n X1_edges[i] = -1 if i is not connected with any edge.\n\n X2_edges: (1D numpy array)\n X2_edges[i] denotes the node that node i will be matched with within perfect matching X2\n X2_edges[i] = -1 if i is not connected with any edge.\n\n num_nodes_X: (Integer)\n Denotes the original number of nodes of X\n\n num_nodes_X_new: (Integer)\n Denotes the number of nodes of expanded X (See \"_build_magical_graph\" function)\n\n Returns\n -------\n None\n\n \"\"\"\n\n X1_edge_pairs = np.arange(num_nodes_X_new)\n X2_edge_pairs = np.arange(num_nodes_X_new)\n\n np.random.shuffle(X1_edge_pairs)\n np.random.shuffle(X2_edge_pairs)\n\n for i in range(int(len(X1_edge_pairs) / 2)):\n x1_first, x1_second = X1_edge_pairs[2 * i], X1_edge_pairs[2 * i + 1]\n x2_first, x2_second = X2_edge_pairs[2 * i], X2_edge_pairs[2 * i + 1]\n\n if x1_first < num_nodes_X and x1_second < num_nodes_X:\n X1_edges[x1_first] = x1_second\n X1_edges[x1_second] = x1_first\n\n if x2_first < num_nodes_X and x2_second < num_nodes_X:\n X2_edges[x2_first] = x2_second\n X2_edges[x2_second] = x2_first\n\n return\n\n\ndef _build_perfect_matching2(X1_edges, X2_edges):\n \"\"\"\n Builds two perfect matchings (See function _build_perfect_matching1). This algorithm on the\n other hand produces two randomly generated perfect matchings such that their union contains\n all the nodes within expanded X.\n\n Parameters\n --------\n X1_edges: (1D numpy array)\n See _build_perfect_matching1 function\n\n X2_edges: (1D numpy array)\n See _build_perfect_matching1 function\n\n Returns\n -------\n\n None\n\n \"\"\"\n\n edge_pairs = np.arange(len(X1_edges))\n np.random.shuffle(edge_pairs)\n turn1 = True\n\n for i in range(len(edge_pairs)): \n\n if i == len(edge_pairs) - 1:\n # i is the last node\n x1, x2 = edge_pairs[0], edge_pairs[i] \n else:\n x1, x2 = edge_pairs[i], edge_pairs[i + 1]\n\n if turn1:\n X1_edges[x1] = x2\n X1_edges[x2] = x1\n turn1 = False\n else:\n X2_edges[x1] = x2\n X2_edges[x2] = x1\n turn1 = True\n return\n\n\ndef _check_overlapping_union(Y_edges, num_group_edges, num_nodes_X):\n \"\"\"\n A utility function for checking whether the edge set within Y contains all the nodes\n in X (or its expansion) and whether there exists nodes in X (or its expansion) that\n are common within the edge set of the partitions of Y.\n\n Parameters\n ----------\n\n Y_edges : (2D numpy array)\n (See the Returns in function _build_magical_graph)\n\n num_group_edges\n (See the Returns in function _build_magical_graph)\n\n num_nodes_X\n Number of nodes of original X (or its expansion).\n\n Returns\n -------\n\n None\n\n \"\"\"\n\n node_set = set()\n intersection = False\n for i in range(Y_edges.shape[0]):\n nodes = set(list(Y_edges[i, 0:num_group_edges[i]]))\n if len(node_set.intersection(node_set)) != 0:\n intersection = True\n\n node_set = node_set.union(nodes)\n\n if len(node_set) == num_nodes_X:\n print(\"Contains all elements\")\n else:\n print(\n \"DOES NOT contain all elements\",\n \"..num of nodes:\",\n len(node_set),\n \"num_nodes_X:\",\n num_nodes_X)\n if intersection:\n print(\"Has overlapping\")\n\n\ndef _build_matrix_rank_k(row, col, k):\n \"\"\"\n Builds a random matrix A (2D numpy array) of shape=(row,col) with rank k.\n\n Parameters\n ----------\n\n row: (Integer)\n Number of rows of A\n\n col: (Integer)\n Number of columns of A\n\n Returns\n -------\n\n A : (2D array)\n Random matrix with rank k of shape=(row,col).\n\n \"\"\"\n\n # a = np.random.rand(row, col)\n a = np.random.uniform(low=-1000, high=1000, size=(row, col))\n # a = np.random.uniform(low=-10, high=10, size=(row, col))\n # a = np.random.uniform(low=-20, high=20, size=(row, col))\n\n # rvs = stats.uniform(loc=-10, scale=20).rvs\n # a = sparse_random(row, col, density=0.0001, data_rvs=rvs).A\n\n u, s, vh = np.linalg.svd(a, full_matrices=True)\n smat = np.zeros((row, col))\n smat[:k, :k] = np.diag(np.ones((k)))\n A = np.dot(u, np.dot(smat, vh))\n return A\n\n\ndef _hash_columns(total_columns, k):\n \"\"\"\n Randomly maps new extra columns to old columns such that (total_columns + extra columns)\n is a multiple of k.\n\n Parameters\n --------\n\n total_columns : (Integer)\n Original number of columns of matrix A used within _matrix_compressor\n\n k : (Integer)\n The new number of collumns of the compressed matrix B (See _matrix_compressor).\n\n Returns\n -------\n\n hash_array : (1D numpy array)\n hash_array[i] = i if i is one of the original columns of A, otherwise hash_array[i] = j such\n that j is one of the original columns of A.\n\n \"\"\"\n\n extra_columns = k - (total_columns % k)\n if extra_columns == k:\n extra_columns = 0\n toAdd = random.sample(range(total_columns), extra_columns)\n hash_array = np.array(list(range(total_columns)) + toAdd)\n return hash_array\n\n\ndef _matrix_compressor(A, K, gen_neighbours=False, info_dict=None):\n \"\"\"\n For compressing input matrix A of shape=(m,n) to matrix B of shape(m,k) such that\n min(rank(A),K) = min(rank(B),K)\n\n Parameters\n ----------\n\n A : (2D numpy array)\n Matrix to compress\n\n K : (Integer)\n K (<n) is the number of collumns of the newly compressed matrix B\n\n Returns\n -------\n\n B : (2D numpy array)\n The compressed matrix of shape = (m,n) such that min(rank(A),K) = min(rank(B),K)\n\n \"\"\"\n\n # F_set = set(A.flat) # Elements of the field (F)\n # t1 = time.time()\n # t0 = t1\n F_set = range(1, 100)\n hash_array = _hash_columns(A.shape[1], K)\n graph, num_edges = _build_magical_graph(hash_array.shape[0], K)\n # Vector of random c values\n C = np.array(random.choices(list(F_set), k=num_edges.sum()))\n B = np.zeros((A.shape[0], K))\n # print(-1, time.time() - t1)\n\n if gen_neighbours: \n num_edge = num_edges[0]\n info_dict['neighbours'] = np.zeros((K, num_edge), dtype=int)\n\n c_idx = 0\n for i in range(B.shape[1]):\n num_edge = num_edges[i]\n if num_edge > 0:\n # t1 = time.time()\n idxs_col = graph[i, 0:num_edge]\n idxs_col = hash_array[idxs_col]\n # print(-2, time.time() - t1)\n # B[:,i] is the random linear combination of the collumns of A\n # based on C values.\n # t1 = time.time()\n B[:, i] = A[:, idxs_col].dot(C[c_idx:c_idx + num_edge])\n c_idx += num_edge\n # print(-3, time.time() - t1)\n\n # t1 = time.time()\n if gen_neighbours: info_dict['neighbours'][i,:] = idxs_col\n # print(-3, time.time() - t1) \n # T = T.union(set(idxs_col.flat))\n # print(\"For \", i,\"th collumn in B, A collumns: \", idxs_col)\n\n # print(len(T))\n # print(-4, time.time() - t0)\n return B\n\n\ndef compute_rank(A):\n \"\"\"\n Computes rank of input matrix A.\n\n Parameters\n ----------\n\n A : (2D numpy array)\n Matrix for which rank will be computed\n\n Returns\n -------\n\n rank : (Integer)\n rank of A.\n\n \"\"\"\n\n row, col = A.shape\n max_rank = min(A.shape)\n start = 0\n end = max_rank\n rank = 0\n mid = 0\n\n while True:\n if end - start == 1:\n mid = end\n else:\n mid = int((end - start) / 2) + start\n\n k = mid\n B = _matrix_compressor(A, k)\n C = _matrix_compressor(B.T, k)\n rank_C = np.linalg.matrix_rank(C)\n\n if k > rank_C:\n rank = rank_C\n break\n elif k == rank_C:\n if k == end:\n rank = max_rank\n break\n else:\n start = mid\n\n return rank\n\n\ndef auto_compress_matrix(A):\n \"\"\"\n Denoting r = rank(A), it compresses A into B with r collumns such that rank(B) = r.\n\n Parameters\n ----------\n\n A : (2D numpy array)\n Input matrix of shape (m,n)\n\n Returns\n -------\n\n B : (2D numpy array)\n The compressed matrix of shape (m,r) with rank r.\n\n \"\"\"\n\n estimated_rank = compute_rank(A)\n B = _matrix_compressor(A, estimated_rank)\n return B\n\n\ndef test_compute_rank(\n rank_range,\n A_shape,\n num_runs,\n accept_threshold=False,\n logs=False):\n \"\"\"\n For testing compute_rank function. The function tests compute_rank by enumerating through\n the range of values within rank_range and num_runs and generating. For every configuration\n it generates A.\n\n Parameters\n ----------\n\n rank_range : (list)\n Composed of two elements such that 1st denotes the starting point of a range of rank values\n and the 2nd denotes the upper limit of that range. The rank corresponds to the generated \n matrix A.\n\n A_shape: (list)\n A_shape = A.shape\n\n num_runs : (list)\n Composed of two elements similar to rank_range for denoting the range of number of runs \n for each rank values.\n\n accept_threshold : (Boolean/float)\n If set to false, the function will not perform assertion checks. If given a number in [0,100],\n it will assert whether the percentage of correct outputs is at least of this value.\n\n logs : (Boolean)\n For indicating whether information about A rank, computed rank and run number is shown for each\n configuration\n\n Returns\n -------\n\n None\n \"\"\"\n\n print(\"Running test_compute_rank ...\")\n\n results = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1),\n dtype=int)\n\n for rank in range(rank_range[0], rank_range[1] + 1):\n for run in range(num_runs):\n A = _build_matrix_rank_k(A_shape[0], A_shape[1], rank)\n estimated_rank = compute_rank(A)\n\n if logs:\n print(\n \"A rank:\", rank,\n \"estimated rank:\", estimated_rank,\n \"num_run:\", run + 1\n )\n\n if rank == estimated_rank:\n results[run, rank - rank_range[0]] = 1\n\n success_percent = results.mean() * 100\n print(\"(From test_compute_rank) Success %: \", success_percent)\n if accept_threshold is not False:\n assert(success_percent >= accept_threshold)\n return\n\n\ndef test_matrix_compressor(\n k_range,\n rank_range,\n A_shape,\n num_runs,\n accept_threshold=False,\n logs=False):\n \"\"\"\n Function similar to test_compute_rank for testing _matrix_compressor function whether min(rank(A),k) = min(rank(B),k)\n for every enumeration (See test_compute_rank). Also includes range of k values.\n\n Parameters\n ----------\n\n k_range : (list)\n Composed of two elements such that 1st denotes the starting point of a range of k values\n and the 2nd denotes the upper limit of that range. k corresponds to the number of columns of B (Compressed matrix)\n\n rank_range : (list)\n See test_compute_rank\n\n A_shape : (list)\n A_shape = A.shape\n\n num_runs : (list)\n See test_compute_rank.\n\n accept_threshold : (Boolean/float)\n See test_compute_rank.\n\n logs : (Boolean)\n See test_compute_rank.\n\n Returns\n -------\n\n None\n \"\"\"\n\n print(\"Running test_matrix_compressor ...\")\n\n results = np.zeros(\n (num_runs, k_range[1] - k_range[0] + 1, rank_range[1] - rank_range[0] + 1),\n dtype=int)\n\n for k in range(k_range[0], k_range[1] + 1):\n for rank in range(rank_range[0], rank_range[1] + 1):\n for run in range(num_runs):\n A = _build_matrix_rank_k(A_shape[0], A_shape[1], rank)\n B = _matrix_compressor(A, k)\n # print(\"total entries of A: \", A.shape[0]*A.shape[1])\n # print(\"total entries of B: \", B.shape[0]*B.shape[1])\n # print(\"Number of non_zeros for A:\",np.count_nonzero(A))\n # print(\"Number of non zeros for B:\",np.count_nonzero(B))\n rank_B = np.linalg.matrix_rank(B)\n\n if logs:\n print(\n \"A rank: \", rank,\n \"B rank:\", rank_B,\n \". k:\", k,\n \". num_run:\", run + 1\n )\n\n if rank_B == min(rank, k):\n results[run, k - k_range[0], rank - rank_range[0]] = 1\n\n success_percent = results.mean() * 100\n print(\"(From test_matrix_compressor) Success %: \", success_percent)\n if accept_threshold is not False:\n assert(success_percent >= accept_threshold)\n return\n\n\ndef test_auto_compress_matrix(\n rank_range,\n A_shape,\n num_runs,\n accept_threshold=False,\n logs=False):\n \"\"\"\n Function similar to test_compute_rank for testing auto_compress_matrix function whether the compressed matrix B\n is of shape (m,r) with rank(B) = r, where r = rank(A) for every enumeration (See test_compute_rank).\n\n Parameters\n ----------\n\n k_range : (list)\n Composed of two elements such that 1st denotes the starting point of a range of k values\n and the 2nd denotes the upper limit of that range. k corresponds to the number of columns of B (Compressed matrix)\n\n rank_range : (list)\n See test_compute_rank\n\n A_shape : (list)\n A_shape = A.shape\n\n num_runs : (list)\n See test_compute_rank.\n\n accept_threshold : (Boolean/float)\n See test_compute_rank.\n\n logs : (Boolean)\n See test_compute_rank.\n\n Returns\n -------\n\n None\n \"\"\"\n\n print(\"Running test_auto_compress_matrix ...\")\n\n results = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1),\n dtype=int)\n\n for rank in range(rank_range[0], rank_range[1] + 1):\n for run in range(num_runs):\n A = _build_matrix_rank_k(A_shape[0], A_shape[1], rank)\n B = auto_compress_matrix(A)\n B_rank = np.linalg.matrix_rank(B)\n\n if logs:\n print(\n \"A rank:\", rank,\n \". B rank:\", B_rank,\n \"B cols:\", B.shape[1],\n \"num_run:\", run + 1\n )\n print(\"RREF of A.T :\", compute_rref(A.T))\n print(\"RREF of B.T :\", compute_rref(B.T))\n\n if (rank == B_rank) and (rank == B.shape[1]):\n results[run, rank - rank_range[0]] = 1\n\n success_percent = results.mean() * 100\n print(\"(From test_auto_compress_matrix) Success %: \", success_percent)\n if accept_threshold is not False:\n assert(success_percent >= accept_threshold)\n return\n\n\ndef test_RREF(\n rank_range,\n A_shape,\n num_runs,\n accept_threshold=False,\n logs=False):\n \"\"\"\n Function similar to test_compute_rank for testing auto_compress_matrix function whether the compressed matrix B\n is of shape (m,r) with rank(B) = r, where r = rank(A) for every enumeration (See test_compute_rank).\n\n Parameters\n ----------\n\n k_range : (list)\n Composed of two elements such that 1st denotes the starting point of a range of k values\n and the 2nd denotes the upper limit of that range. k corresponds to the number of columns of B (Compressed matrix)\n\n rank_range : (list)\n See test_compute_rank\n\n A_shape : (list)\n A_shape = A.shape\n\n num_runs : (list)\n See test_compute_rank.\n\n accept_threshold : (Boolean/float)\n See test_compute_rank.\n\n logs : (Boolean)\n See test_compute_rank.\n\n Returns\n -------\n\n None\n \"\"\"\n\n print(\"Running test_RREF ...\")\n\n results = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1),\n dtype=int)\n\n for rank in range(rank_range[0], rank_range[1] + 1):\n for run in range(num_runs):\n A = _build_matrix_rank_k(A_shape[0], A_shape[1], rank)\n B = auto_compress_matrix(A)\n B_rank = np.linalg.matrix_rank(B)\n\n A_rref, A_rank = compute_rref(A.T)\n B_rref, B_rank = compute_rref(B.T)\n\n if logs:\n print(\n \"A rank:\", rank,\n \". B rank:\", B_rank,\n \"B cols:\", B.shape[1],\n \"num_run:\", run + 1\n )\n print(\"RREF of A.T : \\n\", A_rref)\n print(\"RREF of B.T : \\n\", B_rref)\n\n if A_rank != rank: print(\"Wrong RREF for A.T\")\n if B_rank != B_rank : print(\"Wrong RREF for B.T\")\n\n if np.allclose(A_rref[:rank,:], B_rref, atol=1e-5, rtol=0):\n results[run, rank - rank_range[0]] = 1\n else:\n print(\"Not same RREF for rank: \",rank)\n\n # if np.allclose(A_rref[:rank,:], B_rref, atol=1e-03, rtol=0) or (A_rank != rank or B_rank != B_rank):\n # results[run, rank - rank_range[0]] = 1\n # else:\n # print(\"RREF of A.T : \\n\", A_rref, \"\\n rank of A_rref:\", A_rank)\n # print(\"RREF of B.T : \\n\", B_rref, \"\\n rank of B_rref:\", B_rank)\n\n\n success_percent = results.mean() * 100\n print(\"(From test_RREF) Success %: \", success_percent)\n if accept_threshold is not False:\n assert(success_percent >= accept_threshold)\n return\n\n\ndef compute_rref(A):\n\n M = rref.rref(A)\n M_array = M[0]\n # M_rank = M[1].shape[0]\n M_rank = len(M[1])\n return M_array, M_rank\n\n\ndef extract_independent_columns_ID(A, rank):\n if rank == 'randomized_rank':\n rank = compute_rank(A)\n elif rank == 'exact_rank':\n rank = exact_rank(A, eps=10**-5)\n\n col_idxs,_ = ID.interp_decomp(A, eps_or_k=rank, rand=True)\n\n return col_idxs[:rank]\n\ndef extract_independent_rows_ID(A, rank):\n return extract_independent_columns_ID(A.T, rank)\n\ndef exact_rank(A, eps=10**-6):\n R = qr(A, mode='r', pivoting=True, check_finite=False)\n rank = 0\n for i in range(min(R[0].shape)):\n rank += 1\n if abs(R[0][i,i]) < eps:\n return i\n return rank\n # return ID.estimate_rank(A, eps=10**-3)\n\ndef extract_independent_columns_hybrid_ID(A, c=4, k=None):\n\n # t1 = time.time()\n if k is None: k = compute_rank(A)\n # print(1, time.time() - t1)\n\n # t1 = time.time()\n A_reduced = _matrix_compressor(A.T, k).T\n # print(2, time.time() - t1)\n\n A_prime = A_reduced\n info_dict = {}\n T = list(range(A.shape[1]))\n i = 0\n\n while True:\n if c*k >= A_prime.shape[1]:\n # t1 = time.time()\n independent_columns = [T[i] for i in extract_independent_columns_ID(A_prime, k)]\n # print(3, time.time() - t1)\n return A[:, independent_columns], independent_columns\n\n # t1 = time.time()\n B = _matrix_compressor(A_prime, c*k, gen_neighbours=True, info_dict=info_dict)\n S = extract_independent_columns_ID(B, k)\n T = [T[i] for i in list(set(info_dict['neighbours'][S, :].flat))]\n A_prime = A_reduced[:, T]\n # print(B.shape, A_prime.shape, i, time.time() - t1)\n i +=1\n\ndef extract_independent_rows_hybrid_ID(A,c=4,k=None):\n return extract_independent_columns_hybrid_ID(A.T, c, k)\n\ndef _build_matrix_rank_k_FAST(rows, cols, rank, really_fast=False):\n\n A = np.random.normal(size=(rows, cols))\n if rank >= min(cols, rows):\n return A\n else:\n if really_fast:\n # A[:, rank:] = A[:, 0].reshape(A.shape[0], 1) \n rank -= 1\n A[:, rank:] = 1.1 \n else:\n for i in range(rank, cols):\n A[:, i] = A[:, :rank].dot(np.random.normal(size=(rank)))\n\n return A\n # t1 = time.time()\n # computed_rank = exact_rank(A, eps=10**-5)\n # print(\"Target rank: \", rank, \" rank of A: \", computed_rank, \"time took: \", time.time() - t1)\n # print(\"Target rank: \", rank, \" rank of A: \", np.linalg.matrix_rank(A))\n\n\ndef test_extract_independent_columns_hybrid_ID(\n rank_range,\n A_shape,\n num_runs,\n accept_threshold=False,\n logs=False):\n\n print(\"Running test_extract_independent_columns_hybrid_ID ...\")\n\n results = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1),\n dtype=int)\n\n time_spent_1 = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1))\n\n time_spent_2 = np.zeros(\n (num_runs, rank_range[1] - rank_range[0] + 1))\n\n for rank in range(rank_range[0], rank_range[1] + 1):\n for run in range(num_runs):\n correct = False\n # A = _build_matrix_rank_k(A_shape[0], A_shape[1], rank)\n A = _build_matrix_rank_k_FAST(A_shape[0], A_shape[1], rank, really_fast=False)\n \n t1 = time.time()\n cols2 = extract_independent_columns_ID(A, rank=rank)\n time_spent_2[run, rank - rank_range[0]] = time.time() - t1\n\n t1 = time.time()\n _, cols1 = extract_independent_columns_hybrid_ID(A, k=rank)\n time_spent_1[run, rank - rank_range[0]] = time.time() - t1\n \n rank_cols1 = exact_rank(A[:, cols1])\n rank_cols2 = exact_rank(A[:, cols2])\n # rank_cols2 = rank_cols1\n\n if (rank_cols1 == rank) and (rank_cols2 == rank):\n correct = True\n\n if logs:\n print(\"Run: \",run, \" Ranks: \", rank, rank_cols1, rank_cols2)\n print(\"time taken for extract_independent_columns_hybrid_ID function:\", time_spent_1[run, rank - rank_range[0]])\n print(\"time taken for extract_independent_columns_ID function:\", time_spent_2[run, rank - rank_range[0]])\n if not correct:\n print(\"Rank from extract_independent_columns_hybrid_ID:\", rank_cols1)\n print(\"Rank from extract_independent_columns_ID:\", rank_cols2)\n\n results[run, rank - rank_range[0]] = correct\n\n success_percent = results.mean() * 100\n print(\"(From test_auto_compress_matrix) Success %: \", success_percent)\n print(\"Average time taken for extract_independent_columns_hybrid_ID function: \", time_spent_1.mean())\n print(\"Average time taken for extract_independent_columns_ID function: \", time_spent_2.mean())\n\n if accept_threshold is not False:\n assert(success_percent >= accept_threshold)\n return\n\n\n\nif __name__ == \"__main__\":\n\n random.seed(int(time.time()))\n np.random.seed(int(time.time()))\n\n # test_matrix_compressor([3, 3], [3, 3], [6, 6], 1, logs=False)\n\n # test_matrix_compressor([1, 30], [1, 30], [30, 50], 10, logs=False)\n # test_compute_rank([1, 30], [30, 50], 100, logs=False)\n # test_auto_compress_matrix([1, 30], [30, 50], 5, logs=False)\n\n # test_auto_compress_matrix([1, 3], [3, 5], 5, logs=True)\n # test_RREF([1, 30], [30, 50], 100, logs=False)\n\n\n # k = 10\n # A = _build_matrix_rank_k(100,100, k)\n # A = _build_matrix_rank_k(10,10, 10).astype(dtype=np.double)\n \n # t1 = time.time()\n # compute_rref(A)\n # print(time.time() - t1)\n\n # r = np.random.rand(10000,1)\n # A = np.random.rand(10000,10000) \n # t1 = time.time()\n # A.dot(r)\n # A.dot(r)\n # A.dot(r)\n # print(time.time() - t1)\n\n\n # t1 = time.time()\n # info_dict = {}\n # _ = _matrix_compressor(A, 4*k, gen_neighbours=True, info_dict=info_dict)\n # print(time.time() - t1)\n # print(info_dict['neighbours'])\n\n # t1 = time.time() \n # _ = auto_compress_matrix(A)\n # print(time.time() - t1)\n\n # t1 = time.time() \n # _ = compute_rank(A)\n # print(time.time() - t1)\n\n # t1 = time.time() \n # _ = np.linalg.matrix_rank(A)\n # print(time.time() - t1)\n\n\n # _build_matrix_rank_k_FAST(100,100,32)\n # _build_matrix_rank_k_FAST(100,100,2)\n # _build_matrix_rank_k_FAST(10,100,5)\n # _build_matrix_rank_k_FAST(100,10,5)\n # _build_matrix_rank_k_FAST(100000,1000,100)\n\n test_extract_independent_columns_hybrid_ID([10, 10], [1000, 1000], 1, logs=True)\n # test_extract_independent_columns_hybrid_ID([50, 50], [1000000, 100], 1, logs=True)"
]
| [
[
"numpy.random.normal",
"numpy.dot",
"numpy.linalg.matrix_rank",
"numpy.zeros",
"numpy.ones",
"scipy.linalg.interpolative.interp_decomp",
"numpy.random.shuffle",
"numpy.allclose",
"numpy.random.uniform",
"numpy.arange",
"scipy.linalg.qr",
"numpy.linalg.svd"
]
]
|
adrielyeung/computational-physics | [
"c34c881b2e6ff29aebce6d0eb6d8d8404648ec71"
]
| [
"Test2.py"
]
| [
"import Matrix_2 as M2\r\nimport imp\r\nimp.reload(M2)\r\nimport numpy as np\r\nimport scipy as sp\r\n\r\nA = np.matrix([[2,1,0,0,0],[3,8,4,0,0],[0,9,20,10,0],[0,0,22,51,-25],[0,0,0,-55,60]],dtype=float)\r\n\r\nprint(M2.LU(A, False))\r\n\r\n#[[ 2. 1. 0. 0. 0. ]\r\n# [ 1.5 6.5 4. 0. 0. ]\r\n# [ 0. 1.38461538 14.46153846 10. 0. ]\r\n# [ 0. 0. 1.5212766 35.78723404 -25. ]\r\n# [ 0. 0. 0. -1.53686088 21.578478 ]]\r\n\r\nL, U = M2.LU(A)\r\nprint(L, U)\r\n\r\n#[[ 1. 0. 0. 0. 0. ]\r\n# [ 1.5 1. 0. 0. 0. ]\r\n# [ 0. 1.38461538 1. 0. 0. ]\r\n# [ 0. 0. 1.5212766 1. 0. ]\r\n# [ 0. 0. 0. -1.53686088 1. ]]\r\n#[[ 2. 1. 0. 0. 0. ]\r\n# [ 0. 6.5 4. 0. 0. ]\r\n# [ 0. 0. 14.46153846 10. 0. ]\r\n# [ 0. 0. 0. 35.78723404 -25. ]\r\n# [ 0. 0. 0. 0. 21.578478 ]]\r\n\r\n# Check to see if L*U = A\r\n\r\nprint(np.dot(L, U))\r\n\r\n#[[ 2. 1. 0. 0. 0.]\r\n# [ 3. 8. 4. 0. 0.]\r\n# [ 0. 9. 20. 10. 0.]\r\n# [ 0. 0. 22. 51. -25.]\r\n# [ 0. 0. 0. -55. 60.]]\r\n\r\n# Check with scipy function (permute_l = True means the permutation matrix is \r\n# multiplied into L so A = (PL)*U)\r\n\r\nsp.linalg.lu(A, permute_l = True)\r\n\r\n# Using this function, the L and U matrices returned multiply to give the actual\r\n# matrix. Although using scipy.linalg.lu gives a different result because there\r\n# is pivoting. After selecting permute_l = True, the two matrices matched.\r\n\r\nprint(M2.det(A))\r\n\r\nprint(np.linalg.det(A))\r\n\r\n# Returns 145180.0 for given matrix, which matches the value calculated by numpy.\r\n\r\nb = np.array([2,5,-4,8,9], dtype=float)\r\nx = M2.solve(A, b)\r\nprint(x)\r\n\r\n# x = [ 0.33764981 1.32470037 -1.6526381 1.71304587 1.72029205]\r\n\r\nprint(np.dot(A, x))\r\n\r\n# [[ 2. 5. -4. 8. 9.]]\r\n\r\nAin = M2.inv(A)\r\nprint(Ain)\r\n\r\n# Returns array([[ 0.71180603, -0.14120402, 0.04642513, -0.0165312 , -0.006888 ],\r\n# [-0.42361207, 0.28240805, -0.09285025, 0.03306241, 0.013776 ],\r\n# [ 0.31336961, -0.20891307, 0.15088166, -0.05372641, -0.022386 ],\r\n# [-0.24548836, 0.16365891, -0.1181981 , 0.07769665, 0.03237361],\r\n# [-0.225031 , 0.15002066, -0.10834826, 0.07122193, 0.04634247]])\r\n\r\nprint(np.dot(A, Ain))\r\n\r\n#[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\r\n# 0.00000000e+00]\r\n# [ -2.22044605e-16 1.00000000e+00 0.00000000e+00 -2.77555756e-17\r\n# 0.00000000e+00]\r\n# [ 3.33066907e-16 1.11022302e-16 1.00000000e+00 0.00000000e+00\r\n# -1.38777878e-17]\r\n# [ 7.49400542e-16 -1.38777878e-15 9.99200722e-16 1.00000000e+00\r\n# -2.35922393e-16]\r\n# [ 3.33066907e-16 1.55431223e-15 -1.33226763e-15 4.44089210e-16\r\n# 1.00000000e+00]]\r\n\r\n# All off-diagonal elements are of order e-15 to e-17 so negligible\r\n# so this has multiplied with A to give the identity matrix."
]
| [
[
"numpy.array",
"numpy.matrix",
"numpy.dot",
"numpy.linalg.det",
"scipy.linalg.lu"
]
]
|
Anthony-MostlyHarmless/trimesh | [
"0379562aac88bb53fc658ce722d2aeb28d62eb23"
]
| [
"trimesh/nsphere.py"
]
| [
"\"\"\"\nnsphere.py\n--------------\n\nFunctions for fitting and minimizing nspheres (circles, spheres,\nhyperspheres, etc.)\n\"\"\"\nimport numpy as np\n\nfrom . import convex\n\nfrom .constants import log, tol\n\ntry:\n from scipy import spatial\n from scipy.optimize import leastsq\nexcept ImportError:\n log.warning('No scipy!')\n\n\ndef minimum_nsphere(obj):\n \"\"\"\n Compute the minimum n- sphere for a mesh or a set of points.\n\n Uses the fact that the minimum n- sphere will be centered at one of\n the vertices of the furthest site voronoi diagram, which is n*log(n)\n but should be pretty fast due to using the scipy/qhull implementations\n of convex hulls and voronoi diagrams.\n\n Parameters\n ----------\n obj: Trimesh object OR\n (n,d) float, set of points\n\n Returns\n ----------\n center: (d) float, center of n- sphere\n radius: float, radius of n-sphere\n \"\"\"\n # reduce the input points or mesh to the vertices of the convex hull\n # since we are computing the furthest site voronoi diagram this reduces\n # the input complexity substantially and returns the same value\n points = convex.hull_points(obj)\n\n # we are scaling the mesh to a unit cube\n # this used to pass qhull_options 'QbB' to Voronoi however this had a bug somewhere\n # to avoid this we scale to a unit cube ourselves inside this function\n points_min = points.min(axis=0)\n points_scale = points.ptp(axis=0).max()\n points = (points - points_min) / points_scale\n\n # if all of the points are on an n-sphere already the voronoi\n # method will fail so we check a least squares fit before\n # bothering to compute the voronoi diagram\n fit_C, fit_R, fit_E = fit_nsphere(points)\n # return fit radius and center to global scale\n fit_R = (((points - fit_C)**2).sum(axis=1).max() ** .5) * points_scale\n fit_C = (fit_C * points_scale) + points_min\n\n if fit_E < 1e-6:\n log.debug('Points were on an n-sphere, returning fit')\n return fit_C, fit_R\n\n # calculate a furthest site voronoi diagram\n # this will fail if the points are ALL on the surface of\n # the n-sphere but hopefully the least squares check caught those cases\n # , qhull_options='QbB Pp')\n voronoi = spatial.Voronoi(points, furthest_site=True)\n\n # find the maximum radius^2 point for each of the voronoi vertices\n # this is worst case quite expensive, but we have used quick convex\n # hull methods to reduce n for this operation\n # we are doing comparisons on the radius^2 value so as to only do a sqrt\n # once\n r2 = np.array([((points - v)**2).sum(axis=1).max()\n for v in voronoi.vertices])\n # we want the smallest sphere, so we take the min of the radii options\n r2_idx = r2.argmin()\n center_v = voronoi.vertices[r2_idx]\n\n # return voronoi radius and center to global scale\n radius_v = np.sqrt(r2[r2_idx]) * points_scale\n center_v = (center_v * points_scale) + points_min\n\n if radius_v > fit_R:\n return fit_C, fit_R\n return center_v, radius_v\n\n\ndef fit_nsphere(points, prior=None):\n \"\"\"\n Fit an n-sphere to a set of points using least squares.\n\n Parameters\n ---------\n points: (n,d) set of points\n prior: (d,) float, best guess for center of nsphere\n\n Returns\n ---------\n center: (d), location of center\n radius: float, mean radius across circle\n error: float, peak to peak value of deviation from mean radius\n \"\"\"\n\n def residuals(center):\n radii_sq = ((points - center)**2).sum(axis=1)\n residuals = radii_sq - radii_sq.mean()\n return residuals\n\n if prior is None:\n center_guess = np.mean(points, axis=0)\n else:\n center_guess = prior\n\n center_result, return_code = leastsq(residuals, center_guess, gtol=1e-8)\n if not (return_code in [1, 2, 3, 4]):\n raise ValueError('Least square fit failed!')\n\n radii = np.linalg.norm(points - center_result, axis=1)\n radius = radii.mean()\n error = radii.ptp()\n return center_result, radius, error\n\n\ndef is_nsphere(points):\n \"\"\"\n Check if a list of points is an nsphere.\n\n Parameters\n -----------\n points: (n,dimension) float, points in space\n\n Returns\n -----------\n check: bool, True if input points are on an nsphere\n \"\"\"\n center, radius, error = fit_nsphere(points)\n check = error < tol.merge\n return check\n"
]
| [
[
"scipy.spatial.Voronoi",
"numpy.linalg.norm",
"numpy.mean",
"scipy.optimize.leastsq",
"numpy.sqrt"
]
]
|
agemagician/transformers | [
"666220fc6417505607148ffb19d172d5732e860a",
"666220fc6417505607148ffb19d172d5732e860a"
]
| [
"tests/test_modeling_tf_dpr.py",
"src/transformers/testing_utils.py"
]
| [
"# coding=utf-8\n# Copyright 2020 Huggingface\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport tempfile\nimport unittest\n\nfrom transformers import is_tf_available\nfrom transformers.testing_utils import require_tf, slow\n\nfrom .test_configuration_common import ConfigTester\nfrom .test_modeling_tf_common import TFModelTesterMixin, ids_tensor\n\n\nif is_tf_available():\n import numpy\n import tensorflow as tf\n\n from transformers import (\n TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,\n TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,\n TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,\n BertConfig,\n DPRConfig,\n TFDPRContextEncoder,\n TFDPRQuestionEncoder,\n TFDPRReader,\n )\n\n\nclass TFDPRModelTester:\n def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=5,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n projection_dim=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.projection_dim = projection_dim\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n\n input_mask = None\n if self.use_input_mask:\n input_mask = ids_tensor(\n [self.batch_size, self.seq_length], vocab_size=2\n ) # follow test_modeling_tf_ctrl.py\n\n token_type_ids = None\n if self.use_token_type_ids:\n token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)\n\n sequence_labels = None\n token_labels = None\n choice_labels = None\n if self.use_labels:\n sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)\n token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)\n choice_labels = ids_tensor([self.batch_size], self.num_choices)\n\n config = BertConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_hidden_layers=self.num_hidden_layers,\n num_attention_heads=self.num_attention_heads,\n intermediate_size=self.intermediate_size,\n hidden_act=self.hidden_act,\n hidden_dropout_prob=self.hidden_dropout_prob,\n attention_probs_dropout_prob=self.attention_probs_dropout_prob,\n max_position_embeddings=self.max_position_embeddings,\n type_vocab_size=self.type_vocab_size,\n is_decoder=False,\n initializer_range=self.initializer_range,\n )\n config = DPRConfig(projection_dim=self.projection_dim, **config.to_dict())\n\n return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n\n def create_and_check_dpr_context_encoder(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = TFDPRContextEncoder(config=config)\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)\n result = model(input_ids, token_type_ids=token_type_ids)\n result = model(input_ids)\n self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))\n\n def create_and_check_dpr_question_encoder(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = TFDPRQuestionEncoder(config=config)\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)\n result = model(input_ids, token_type_ids=token_type_ids)\n result = model(input_ids)\n self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))\n\n def create_and_check_dpr_reader(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = TFDPRReader(config=config)\n result = model(input_ids, attention_mask=input_mask)\n\n self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertEqual(result.relevance_logits.shape, (self.batch_size,))\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n ) = config_and_inputs\n inputs_dict = {\"input_ids\": input_ids}\n return config, inputs_dict\n\n\n@require_tf\nclass TFDPRModelTest(TFModelTesterMixin, unittest.TestCase):\n\n all_model_classes = (\n (\n TFDPRContextEncoder,\n TFDPRQuestionEncoder,\n TFDPRReader,\n )\n if is_tf_available()\n else ()\n )\n\n test_resize_embeddings = False\n test_missing_keys = False\n test_pruning = False\n test_head_masking = False\n\n def setUp(self):\n self.model_tester = TFDPRModelTester(self)\n self.config_tester = ConfigTester(self, config_class=DPRConfig, hidden_size=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_dpr_context_encoder_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_dpr_context_encoder(*config_and_inputs)\n\n def test_dpr_question_encoder_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_dpr_question_encoder(*config_and_inputs)\n\n def test_dpr_reader_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_dpr_reader(*config_and_inputs)\n\n @slow\n def test_model_from_pretrained(self):\n for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = TFDPRContextEncoder.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = TFDPRContextEncoder.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = TFDPRQuestionEncoder.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = TFDPRReader.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n @slow\n def test_saved_model_with_attentions_output(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n config.output_attentions = True\n\n encoder_seq_length = getattr(self.model_tester, \"encoder_seq_length\", self.model_tester.seq_length)\n encoder_key_length = getattr(self.model_tester, \"key_length\", encoder_seq_length)\n\n for model_class in self.all_model_classes:\n print(model_class)\n class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)\n model = model_class(config)\n num_out = len(model(class_inputs_dict))\n model._saved_model_inputs_spec = None\n model._set_save_spec(class_inputs_dict)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n tf.saved_model.save(model, tmpdirname)\n model = tf.keras.models.load_model(tmpdirname)\n outputs = model(class_inputs_dict)\n\n if self.is_encoder_decoder:\n output = outputs[\"encoder_attentions\"] if isinstance(outputs, dict) else outputs[-1]\n else:\n output = outputs[\"attentions\"] if isinstance(outputs, dict) else outputs[-1]\n\n attentions = [t.numpy() for t in output]\n self.assertEqual(len(outputs), num_out)\n self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)\n self.assertListEqual(\n list(attentions[0].shape[-3:]),\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n )\n\n\n@require_tf\nclass TFDPRModelIntegrationTest(unittest.TestCase):\n @slow\n def test_inference_no_head(self):\n model = TFDPRQuestionEncoder.from_pretrained(\"facebook/dpr-question_encoder-single-nq-base\")\n\n input_ids = tf.constant(\n [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]\n ) # [CLS] hello, is my dog cute? [SEP]\n output = model(input_ids)[0] # embedding shape = (1, 768)\n # compare the actual values for a slice.\n expected_slice = tf.constant(\n [\n [\n 0.03236253,\n 0.12753335,\n 0.16818509,\n 0.00279786,\n 0.3896933,\n 0.24264945,\n 0.2178971,\n -0.02335227,\n -0.08481959,\n -0.14324117,\n ]\n ]\n )\n self.assertTrue(numpy.allclose(output[:, :10].numpy(), expected_slice.numpy(), atol=1e-4))\n",
"import inspect\nimport logging\nimport os\nimport re\nimport shutil\nimport sys\nimport tempfile\nimport unittest\nfrom distutils.util import strtobool\nfrom io import StringIO\nfrom pathlib import Path\n\nfrom .file_utils import (\n _datasets_available,\n _faiss_available,\n _flax_available,\n _sentencepiece_available,\n _tf_available,\n _tokenizers_available,\n _torch_available,\n _torch_tpu_available,\n)\nfrom .integrations import _has_optuna, _has_ray\n\n\nSMALL_MODEL_IDENTIFIER = \"julien-c/bert-xsmall-dummy\"\nDUMMY_UNKWOWN_IDENTIFIER = \"julien-c/dummy-unknown\"\nDUMMY_DIFF_TOKENIZER_IDENTIFIER = \"julien-c/dummy-diff-tokenizer\"\n# Used to test Auto{Config, Model, Tokenizer} model_type detection.\n\n\ndef parse_flag_from_env(key, default=False):\n try:\n value = os.environ[key]\n except KeyError:\n # KEY isn't set, default to `default`.\n _value = default\n else:\n # KEY is set, convert it to True or False.\n try:\n _value = strtobool(value)\n except ValueError:\n # More values are supported, but let's keep the message simple.\n raise ValueError(\"If set, {} must be yes or no.\".format(key))\n return _value\n\n\ndef parse_int_from_env(key, default=None):\n try:\n value = os.environ[key]\n except KeyError:\n _value = default\n else:\n try:\n _value = int(value)\n except ValueError:\n raise ValueError(\"If set, {} must be a int.\".format(key))\n return _value\n\n\n_run_slow_tests = parse_flag_from_env(\"RUN_SLOW\", default=False)\n_run_pt_tf_cross_tests = parse_flag_from_env(\"RUN_PT_TF_CROSS_TESTS\", default=False)\n_run_custom_tokenizers = parse_flag_from_env(\"RUN_CUSTOM_TOKENIZERS\", default=False)\n_run_pipeline_tests = parse_flag_from_env(\"RUN_PIPELINE_TESTS\", default=False)\n_tf_gpu_memory_limit = parse_int_from_env(\"TF_GPU_MEMORY_LIMIT\", default=None)\n\n\ndef is_pt_tf_cross_test(test_case):\n \"\"\"\n Decorator marking a test as a test that control interactions between PyTorch and TensorFlow.\n\n PT+TF tests are skipped by default and we can run only them by setting RUN_PT_TF_CROSS_TESTS environment variable\n to a truthy value and selecting the is_pt_tf_cross_test pytest mark.\n\n \"\"\"\n if not _run_pt_tf_cross_tests or not _torch_available or not _tf_available:\n return unittest.skip(\"test is PT+TF test\")(test_case)\n else:\n try:\n import pytest # We don't need a hard dependency on pytest in the main library\n except ImportError:\n return test_case\n else:\n return pytest.mark.is_pt_tf_cross_test()(test_case)\n\n\ndef is_pipeline_test(test_case):\n \"\"\"\n Decorator marking a test as a pipeline test.\n\n Pipeline tests are skipped by default and we can run only them by setting RUN_PIPELINE_TESTS environment variable\n to a truthy value and selecting the is_pipeline_test pytest mark.\n\n \"\"\"\n if not _run_pipeline_tests:\n return unittest.skip(\"test is pipeline test\")(test_case)\n else:\n try:\n import pytest # We don't need a hard dependency on pytest in the main library\n except ImportError:\n return test_case\n else:\n return pytest.mark.is_pipeline_test()(test_case)\n\n\ndef slow(test_case):\n \"\"\"\n Decorator marking a test as slow.\n\n Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.\n\n \"\"\"\n if not _run_slow_tests:\n return unittest.skip(\"test is slow\")(test_case)\n else:\n return test_case\n\n\ndef custom_tokenizers(test_case):\n \"\"\"\n Decorator marking a test for a custom tokenizer.\n\n Custom tokenizers require additional dependencies, and are skipped by default. Set the RUN_CUSTOM_TOKENIZERS\n environment variable to a truthy value to run them.\n \"\"\"\n if not _run_custom_tokenizers:\n return unittest.skip(\"test of custom tokenizers\")(test_case)\n else:\n return test_case\n\n\ndef require_torch(test_case):\n \"\"\"\n Decorator marking a test that requires PyTorch.\n\n These tests are skipped when PyTorch isn't installed.\n\n \"\"\"\n if not _torch_available:\n return unittest.skip(\"test requires PyTorch\")(test_case)\n else:\n return test_case\n\n\ndef require_tf(test_case):\n \"\"\"\n Decorator marking a test that requires TensorFlow.\n\n These tests are skipped when TensorFlow isn't installed.\n\n \"\"\"\n if not _tf_available:\n return unittest.skip(\"test requires TensorFlow\")(test_case)\n else:\n return test_case\n\n\ndef require_flax(test_case):\n \"\"\"\n Decorator marking a test that requires JAX & Flax\n\n These tests are skipped when one / both are not installed\n\n \"\"\"\n if not _flax_available:\n test_case = unittest.skip(\"test requires JAX & Flax\")(test_case)\n return test_case\n\n\ndef require_sentencepiece(test_case):\n \"\"\"\n Decorator marking a test that requires SentencePiece.\n\n These tests are skipped when SentencePiece isn't installed.\n\n \"\"\"\n if not _sentencepiece_available:\n return unittest.skip(\"test requires SentencePiece\")(test_case)\n else:\n return test_case\n\n\ndef require_tokenizers(test_case):\n \"\"\"\n Decorator marking a test that requires 🤗 Tokenizers.\n\n These tests are skipped when 🤗 Tokenizers isn't installed.\n\n \"\"\"\n if not _tokenizers_available:\n return unittest.skip(\"test requires tokenizers\")(test_case)\n else:\n return test_case\n\n\ndef require_torch_multi_gpu(test_case):\n \"\"\"\n Decorator marking a test that requires a multi-GPU setup (in PyTorch).\n\n These tests are skipped on a machine without multiple GPUs.\n\n To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k \"multi_gpu\"\n \"\"\"\n if not _torch_available:\n return unittest.skip(\"test requires PyTorch\")(test_case)\n\n import torch\n\n if torch.cuda.device_count() < 2:\n return unittest.skip(\"test requires multiple GPUs\")(test_case)\n else:\n return test_case\n\n\ndef require_torch_non_multi_gpu(test_case):\n \"\"\"\n Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).\n \"\"\"\n if not _torch_available:\n return unittest.skip(\"test requires PyTorch\")(test_case)\n\n import torch\n\n if torch.cuda.device_count() > 1:\n return unittest.skip(\"test requires 0 or 1 GPU\")(test_case)\n else:\n return test_case\n\n\n# this is a decorator identical to require_torch_non_multi_gpu, but is used as a quick band-aid to\n# allow all of examples to be run multi-gpu CI and it reminds us that tests decorated with this one\n# need to be ported and aren't so by design.\nrequire_torch_non_multi_gpu_but_fix_me = require_torch_non_multi_gpu\n\n\ndef require_torch_tpu(test_case):\n \"\"\"\n Decorator marking a test that requires a TPU (in PyTorch).\n \"\"\"\n if not _torch_tpu_available:\n return unittest.skip(\"test requires PyTorch TPU\")\n else:\n return test_case\n\n\nif _torch_available:\n # Set env var CUDA_VISIBLE_DEVICES=\"\" to force cpu-mode\n import torch\n\n torch_device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nelse:\n torch_device = None\n\n\ndef require_torch_gpu(test_case):\n \"\"\"Decorator marking a test that requires CUDA and PyTorch. \"\"\"\n if torch_device != \"cuda\":\n return unittest.skip(\"test requires CUDA\")(test_case)\n else:\n return test_case\n\n\ndef require_datasets(test_case):\n \"\"\"Decorator marking a test that requires datasets.\"\"\"\n\n if not _datasets_available:\n return unittest.skip(\"test requires `datasets`\")(test_case)\n else:\n return test_case\n\n\ndef require_faiss(test_case):\n \"\"\"Decorator marking a test that requires faiss.\"\"\"\n if not _faiss_available:\n return unittest.skip(\"test requires `faiss`\")(test_case)\n else:\n return test_case\n\n\ndef require_optuna(test_case):\n \"\"\"\n Decorator marking a test that requires optuna.\n\n These tests are skipped when optuna isn't installed.\n\n \"\"\"\n if not _has_optuna:\n return unittest.skip(\"test requires optuna\")(test_case)\n else:\n return test_case\n\n\ndef require_ray(test_case):\n \"\"\"\n Decorator marking a test that requires Ray/tune.\n\n These tests are skipped when Ray/tune isn't installed.\n\n \"\"\"\n if not _has_ray:\n return unittest.skip(\"test requires Ray/tune\")(test_case)\n else:\n return test_case\n\n\ndef get_gpu_count():\n \"\"\"\n Return the number of available gpus (regardless of whether torch or tf is used)\n \"\"\"\n if _torch_available:\n import torch\n\n return torch.cuda.device_count()\n elif _tf_available:\n import tensorflow as tf\n\n return len(tf.config.list_physical_devices(\"GPU\"))\n else:\n return 0\n\n\ndef get_tests_dir(append_path=None):\n \"\"\"\n Args:\n append_path: optional path to append to the tests dir path\n\n Return:\n The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is\n joined after the `tests` dir the former is provided.\n\n \"\"\"\n # this function caller's __file__\n caller__file__ = inspect.stack()[1][1]\n tests_dir = os.path.abspath(os.path.dirname(caller__file__))\n if append_path:\n return os.path.join(tests_dir, append_path)\n else:\n return tests_dir\n\n\n#\n# Helper functions for dealing with testing text outputs\n# The original code came from:\n# https://github.com/fastai/fastai/blob/master/tests/utils/text.py\n\n# When any function contains print() calls that get overwritten, like progress bars,\n# a special care needs to be applied, since under pytest -s captured output (capsys\n# or contextlib.redirect_stdout) contains any temporary printed strings, followed by\n# \\r's. This helper function ensures that the buffer will contain the same output\n# with and without -s in pytest, by turning:\n# foo bar\\r tar mar\\r final message\n# into:\n# final message\n# it can handle a single string or a multiline buffer\ndef apply_print_resets(buf):\n return re.sub(r\"^.*\\r\", \"\", buf, 0, re.M)\n\n\ndef assert_screenout(out, what):\n out_pr = apply_print_resets(out).lower()\n match_str = out_pr.find(what.lower())\n assert match_str != -1, f\"expecting to find {what} in output: f{out_pr}\"\n\n\nclass CaptureStd:\n \"\"\"\n Context manager to capture:\n stdout, clean it up and make it available via obj.out stderr, and make it available via obj.err\n\n init arguments: - out - capture stdout: True/False, default True - err - capture stdout: True/False, default\n True\n\n Examples::\n\n with CaptureStdout() as cs:\n print(\"Secret message\")\n print(f\"captured: {cs.out}\")\n\n import sys\n with CaptureStderr() as cs:\n print(\"Warning: \", file=sys.stderr)\n print(f\"captured: {cs.err}\")\n\n # to capture just one of the streams, but not the other\n with CaptureStd(err=False) as cs:\n print(\"Secret message\")\n print(f\"captured: {cs.out}\")\n # but best use the stream-specific subclasses\n\n \"\"\"\n\n def __init__(self, out=True, err=True):\n if out:\n self.out_buf = StringIO()\n self.out = \"error: CaptureStd context is unfinished yet, called too early\"\n else:\n self.out_buf = None\n self.out = \"not capturing stdout\"\n\n if err:\n self.err_buf = StringIO()\n self.err = \"error: CaptureStd context is unfinished yet, called too early\"\n else:\n self.err_buf = None\n self.err = \"not capturing stderr\"\n\n def __enter__(self):\n if self.out_buf:\n self.out_old = sys.stdout\n sys.stdout = self.out_buf\n\n if self.err_buf:\n self.err_old = sys.stderr\n sys.stderr = self.err_buf\n\n return self\n\n def __exit__(self, *exc):\n if self.out_buf:\n sys.stdout = self.out_old\n self.out = apply_print_resets(self.out_buf.getvalue())\n\n if self.err_buf:\n sys.stderr = self.err_old\n self.err = self.err_buf.getvalue()\n\n def __repr__(self):\n msg = \"\"\n if self.out_buf:\n msg += f\"stdout: {self.out}\\n\"\n if self.err_buf:\n msg += f\"stderr: {self.err}\\n\"\n return msg\n\n\n# in tests it's the best to capture only the stream that's wanted, otherwise\n# it's easy to miss things, so unless you need to capture both streams, use the\n# subclasses below (less typing). Or alternatively, configure `CaptureStd` to\n# disable the stream you don't need to test.\n\n\nclass CaptureStdout(CaptureStd):\n \"\"\" Same as CaptureStd but captures only stdout \"\"\"\n\n def __init__(self):\n super().__init__(err=False)\n\n\nclass CaptureStderr(CaptureStd):\n \"\"\" Same as CaptureStd but captures only stderr \"\"\"\n\n def __init__(self):\n super().__init__(out=False)\n\n\nclass CaptureLogger:\n \"\"\"\n Context manager to capture `logging` streams\n\n Args:\n - logger: 'logging` logger object\n\n Results:\n The captured output is available via `self.out`\n\n Example::\n\n >>> from transformers import logging\n >>> from transformers.testing_utils import CaptureLogger\n\n >>> msg = \"Testing 1, 2, 3\"\n >>> logging.set_verbosity_info()\n >>> logger = logging.get_logger(\"transformers.models.bart.tokenization_bart\")\n >>> with CaptureLogger(logger) as cl:\n ... logger.info(msg)\n >>> assert cl.out, msg+\"\\n\"\n \"\"\"\n\n def __init__(self, logger):\n self.logger = logger\n self.io = StringIO()\n self.sh = logging.StreamHandler(self.io)\n self.out = \"\"\n\n def __enter__(self):\n self.logger.addHandler(self.sh)\n return self\n\n def __exit__(self, *exc):\n self.logger.removeHandler(self.sh)\n self.out = self.io.getvalue()\n\n def __repr__(self):\n return f\"captured: {self.out}\\n\"\n\n\nclass TestCasePlus(unittest.TestCase):\n \"\"\"\n This class extends `unittest.TestCase` with additional features.\n\n Feature 1: A set of fully resolved important file and dir path accessors.\n\n In tests often we need to know where things are relative to the current test file, and it's not trivial since the\n test could be invoked from more than one directory or could reside in sub-directories with different depths. This\n class solves this problem by sorting out all the basic paths and provides easy accessors to them:\n\n * ``pathlib`` objects (all fully resolved):\n\n - ``test_file_path`` - the current test file path (=``__file__``)\n - ``test_file_dir`` - the directory containing the current test file\n - ``tests_dir`` - the directory of the ``tests`` test suite\n - ``examples_dir`` - the directory of the ``examples`` test suite\n - ``repo_root_dir`` - the directory of the repository\n - ``src_dir`` - the directory of ``src`` (i.e. where the ``transformers`` sub-dir resides)\n\n * stringified paths---same as above but these return paths as strings, rather than ``pathlib`` objects:\n\n - ``test_file_path_str``\n - ``test_file_dir_str``\n - ``tests_dir_str``\n - ``examples_dir_str``\n - ``repo_root_dir_str``\n - ``src_dir_str``\n\n Feature 2: Flexible auto-removable temporary dirs which are guaranteed to get removed at the end of test.\n\n 1. Create a unique temporary dir:\n\n ::\n\n def test_whatever(self):\n tmp_dir = self.get_auto_remove_tmp_dir()\n\n ``tmp_dir`` will contain the path to the created temporary dir. It will be automatically removed at the end of the\n test.\n\n\n 2. Create a temporary dir of my choice, ensure it's empty before the test starts and don't\n empty it after the test.\n\n ::\n\n def test_whatever(self):\n tmp_dir = self.get_auto_remove_tmp_dir(\"./xxx\")\n\n This is useful for debug when you want to monitor a specific directory and want to make sure the previous tests\n didn't leave any data in there.\n\n 3. You can override the first two options by directly overriding the ``before`` and ``after`` args, leading to the\n following behavior:\n\n ``before=True``: the temporary dir will always be cleared at the beginning of the test.\n\n ``before=False``: if the temporary dir already existed, any existing files will remain there.\n\n ``after=True``: the temporary dir will always be deleted at the end of the test.\n\n ``after=False``: the temporary dir will always be left intact at the end of the test.\n\n Note 1: In order to run the equivalent of ``rm -r`` safely, only subdirs of the project repository checkout are\n allowed if an explicit ``tmp_dir`` is used, so that by mistake no ``/tmp`` or similar important part of the\n filesystem will get nuked. i.e. please always pass paths that start with ``./``\n\n Note 2: Each test can register multiple temporary dirs and they all will get auto-removed, unless requested\n otherwise.\n\n Feature 3: Get a copy of the ``os.environ`` object that sets up ``PYTHONPATH`` specific to the current test suite.\n This is useful for invoking external programs from the test suite - e.g. distributed training.\n\n\n ::\n def test_whatever(self):\n env = self.get_env()\n\n \"\"\"\n\n def setUp(self):\n # get_auto_remove_tmp_dir feature:\n self.teardown_tmp_dirs = []\n\n # figure out the resolved paths for repo_root, tests, examples, etc.\n self._test_file_path = inspect.getfile(self.__class__)\n path = Path(self._test_file_path).resolve()\n self._test_file_dir = path.parents[0]\n for up in [1, 2, 3]:\n tmp_dir = path.parents[up]\n if (tmp_dir / \"src\").is_dir() and (tmp_dir / \"tests\").is_dir():\n break\n if tmp_dir:\n self._repo_root_dir = tmp_dir\n else:\n raise ValueError(f\"can't figure out the root of the repo from {self._test_file_path}\")\n self._tests_dir = self._repo_root_dir / \"tests\"\n self._examples_dir = self._repo_root_dir / \"examples\"\n self._src_dir = self._repo_root_dir / \"src\"\n\n @property\n def test_file_path(self):\n return self._test_file_path\n\n @property\n def test_file_path_str(self):\n return str(self._test_file_path)\n\n @property\n def test_file_dir(self):\n return self._test_file_dir\n\n @property\n def test_file_dir_str(self):\n return str(self._test_file_dir)\n\n @property\n def tests_dir(self):\n return self._tests_dir\n\n @property\n def tests_dir_str(self):\n return str(self._tests_dir)\n\n @property\n def examples_dir(self):\n return self._examples_dir\n\n @property\n def examples_dir_str(self):\n return str(self._examples_dir)\n\n @property\n def repo_root_dir(self):\n return self._repo_root_dir\n\n @property\n def repo_root_dir_str(self):\n return str(self._repo_root_dir)\n\n @property\n def src_dir(self):\n return self._src_dir\n\n @property\n def src_dir_str(self):\n return str(self._src_dir)\n\n def get_env(self):\n \"\"\"\n Return a copy of the ``os.environ`` object that sets up ``PYTHONPATH`` correctly, depending on the test suite\n it's invoked from. This is useful for invoking external programs from the test suite - e.g. distributed\n training.\n\n It always inserts ``./src`` first, then ``./tests`` or ``./examples`` depending on the test suite type and\n finally the preset ``PYTHONPATH`` if any (all full resolved paths).\n\n \"\"\"\n env = os.environ.copy()\n paths = [self.src_dir_str]\n if \"/examples\" in self.test_file_dir_str:\n paths.append(self.examples_dir_str)\n else:\n paths.append(self.tests_dir_str)\n paths.append(env.get(\"PYTHONPATH\", \"\"))\n\n env[\"PYTHONPATH\"] = \":\".join(paths)\n return env\n\n def get_auto_remove_tmp_dir(self, tmp_dir=None, before=None, after=None):\n \"\"\"\n Args:\n tmp_dir (:obj:`string`, `optional`):\n if :obj:`None`:\n\n - a unique temporary path will be created\n - sets ``before=True`` if ``before`` is :obj:`None`\n - sets ``after=True`` if ``after`` is :obj:`None`\n else:\n\n - :obj:`tmp_dir` will be created\n - sets ``before=True`` if ``before`` is :obj:`None`\n - sets ``after=False`` if ``after`` is :obj:`None`\n before (:obj:`bool`, `optional`):\n If :obj:`True` and the :obj:`tmp_dir` already exists, make sure to empty it right away if :obj:`False`\n and the :obj:`tmp_dir` already exists, any existing files will remain there.\n after (:obj:`bool`, `optional`):\n If :obj:`True`, delete the :obj:`tmp_dir` at the end of the test if :obj:`False`, leave the\n :obj:`tmp_dir` and its contents intact at the end of the test.\n\n Returns:\n tmp_dir(:obj:`string`): either the same value as passed via `tmp_dir` or the path to the auto-selected tmp\n dir\n \"\"\"\n if tmp_dir is not None:\n\n # defining the most likely desired behavior for when a custom path is provided.\n # this most likely indicates the debug mode where we want an easily locatable dir that:\n # 1. gets cleared out before the test (if it already exists)\n # 2. is left intact after the test\n if before is None:\n before = True\n if after is None:\n after = False\n\n # using provided path\n path = Path(tmp_dir).resolve()\n\n # to avoid nuking parts of the filesystem, only relative paths are allowed\n if not tmp_dir.startswith(\"./\"):\n raise ValueError(\n f\"`tmp_dir` can only be a relative path, i.e. `./some/path`, but received `{tmp_dir}`\"\n )\n\n # ensure the dir is empty to start with\n if before is True and path.exists():\n shutil.rmtree(tmp_dir, ignore_errors=True)\n\n path.mkdir(parents=True, exist_ok=True)\n\n else:\n # defining the most likely desired behavior for when a unique tmp path is auto generated\n # (not a debug mode), here we require a unique tmp dir that:\n # 1. is empty before the test (it will be empty in this situation anyway)\n # 2. gets fully removed after the test\n if before is None:\n before = True\n if after is None:\n after = True\n\n # using unique tmp dir (always empty, regardless of `before`)\n tmp_dir = tempfile.mkdtemp()\n\n if after is True:\n # register for deletion\n self.teardown_tmp_dirs.append(tmp_dir)\n\n return tmp_dir\n\n def tearDown(self):\n\n # get_auto_remove_tmp_dir feature: remove registered temp dirs\n for path in self.teardown_tmp_dirs:\n shutil.rmtree(path, ignore_errors=True)\n self.teardown_tmp_dirs = []\n\n\ndef mockenv(**kwargs):\n \"\"\"\n this is a convenience wrapper, that allows this:\n\n @mockenv(RUN_SLOW=True, USE_TF=False) def test_something(): run_slow = os.getenv(\"RUN_SLOW\", False) use_tf =\n os.getenv(\"USE_TF\", False)\n \"\"\"\n return unittest.mock.patch.dict(os.environ, kwargs)\n\n\n# --- pytest conf functions --- #\n\n# to avoid multiple invocation from tests/conftest.py and examples/conftest.py - make sure it's called only once\npytest_opt_registered = {}\n\n\ndef pytest_addoption_shared(parser):\n \"\"\"\n This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there.\n\n It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest`\n option.\n\n \"\"\"\n option = \"--make-reports\"\n if option not in pytest_opt_registered:\n parser.addoption(\n option,\n action=\"store\",\n default=False,\n help=\"generate report files. The value of this option is used as a prefix to report names\",\n )\n pytest_opt_registered[option] = 1\n\n\ndef pytest_terminal_summary_main(tr, id):\n \"\"\"\n Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current\n directory. The report files are prefixed with the test suite name.\n\n This function emulates --duration and -rA pytest arguments.\n\n This function is to be called from `conftest.py` via `pytest_terminal_summary` wrapper that has to be defined\n there.\n\n Args:\n - tr: `terminalreporter` passed from `conftest.py`\n - id: unique id like `tests` or `examples` that will be incorporated into the final reports\n filenames - this is needed as some jobs have multiple runs of pytest, so we can't have them overwrite each other.\n\n NB: this functions taps into a private _pytest API and while unlikely, it could break should\n pytest do internal changes - also it calls default internal methods of terminalreporter which\n can be hijacked by various `pytest-` plugins and interfere.\n\n \"\"\"\n from _pytest.config import create_terminal_writer\n\n if not len(id):\n id = \"tests\"\n\n config = tr.config\n orig_writer = config.get_terminal_writer()\n orig_tbstyle = config.option.tbstyle\n orig_reportchars = tr.reportchars\n\n dir = \"reports\"\n Path(dir).mkdir(parents=True, exist_ok=True)\n report_files = {\n k: f\"{dir}/{id}_{k}.txt\"\n for k in [\n \"durations\",\n \"errors\",\n \"failures_long\",\n \"failures_short\",\n \"failures_line\",\n \"passes\",\n \"stats\",\n \"summary_short\",\n \"warnings\",\n ]\n }\n\n # custom durations report\n # note: there is no need to call pytest --durations=XX to get this separate report\n # adapted from https://github.com/pytest-dev/pytest/blob/897f151e/src/_pytest/runner.py#L66\n dlist = []\n for replist in tr.stats.values():\n for rep in replist:\n if hasattr(rep, \"duration\"):\n dlist.append(rep)\n if dlist:\n dlist.sort(key=lambda x: x.duration, reverse=True)\n with open(report_files[\"durations\"], \"w\") as f:\n durations_min = 0.05 # sec\n f.write(\"slowest durations\\n\")\n for i, rep in enumerate(dlist):\n if rep.duration < durations_min:\n f.write(f\"{len(dlist)-i} durations < {durations_min} secs were omitted\")\n break\n f.write(f\"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}\\n\")\n\n def summary_failures_short(tr):\n # expecting that the reports were --tb=long (default) so we chop them off here to the last frame\n reports = tr.getreports(\"failed\")\n if not reports:\n return\n tr.write_sep(\"=\", \"FAILURES SHORT STACK\")\n for rep in reports:\n msg = tr._getfailureheadline(rep)\n tr.write_sep(\"_\", msg, red=True, bold=True)\n # chop off the optional leading extra frames, leaving only the last one\n longrepr = re.sub(r\".*_ _ _ (_ ){10,}_ _ \", \"\", rep.longreprtext, 0, re.M | re.S)\n tr._tw.line(longrepr)\n # note: not printing out any rep.sections to keep the report short\n\n # use ready-made report funcs, we are just hijacking the filehandle to log to a dedicated file each\n # adapted from https://github.com/pytest-dev/pytest/blob/897f151e/src/_pytest/terminal.py#L814\n # note: some pytest plugins may interfere by hijacking the default `terminalreporter` (e.g.\n # pytest-instafail does that)\n\n # report failures with line/short/long styles\n config.option.tbstyle = \"auto\" # full tb\n with open(report_files[\"failures_long\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_failures()\n\n # config.option.tbstyle = \"short\" # short tb\n with open(report_files[\"failures_short\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n summary_failures_short(tr)\n\n config.option.tbstyle = \"line\" # one line per error\n with open(report_files[\"failures_line\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_failures()\n\n with open(report_files[\"errors\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_errors()\n\n with open(report_files[\"warnings\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_warnings() # normal warnings\n tr.summary_warnings() # final warnings\n\n tr.reportchars = \"wPpsxXEf\" # emulate -rA (used in summary_passes() and short_test_summary())\n with open(report_files[\"passes\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_passes()\n\n with open(report_files[\"summary_short\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.short_test_summary()\n\n with open(report_files[\"stats\"], \"w\") as f:\n tr._tw = create_terminal_writer(config, f)\n tr.summary_stats()\n\n # restore:\n tr._tw = orig_writer\n tr.reportchars = orig_reportchars\n config.option.tbstyle = orig_tbstyle\n\n\n# --- distributed testing functions --- #\n\n# adapted from https://stackoverflow.com/a/59041913/9201239\nimport asyncio # noqa\n\n\nclass _RunOutput:\n def __init__(self, returncode, stdout, stderr):\n self.returncode = returncode\n self.stdout = stdout\n self.stderr = stderr\n\n\nasync def _read_stream(stream, callback):\n while True:\n line = await stream.readline()\n if line:\n callback(line)\n else:\n break\n\n\nasync def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> _RunOutput:\n if echo:\n print(\"\\nRunning: \", \" \".join(cmd))\n\n p = await asyncio.create_subprocess_exec(\n cmd[0],\n *cmd[1:],\n stdin=stdin,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n env=env,\n )\n\n # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe\n # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait\n #\n # If it starts hanging, will need to switch to the following code. The problem is that no data\n # will be seen until it's done and if it hangs for example there will be no debug info.\n # out, err = await p.communicate()\n # return _RunOutput(p.returncode, out, err)\n\n out = []\n err = []\n\n def tee(line, sink, pipe, label=\"\"):\n line = line.decode(\"utf-8\").rstrip()\n sink.append(line)\n if not quiet:\n print(label, line, file=pipe)\n\n # XXX: the timeout doesn't seem to make any difference here\n await asyncio.wait(\n [\n _read_stream(p.stdout, lambda l: tee(l, out, sys.stdout, label=\"stdout:\")),\n _read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label=\"stderr:\")),\n ],\n timeout=timeout,\n )\n return _RunOutput(await p.wait(), out, err)\n\n\ndef execute_subprocess_async(cmd, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput:\n\n loop = asyncio.get_event_loop()\n result = loop.run_until_complete(\n _stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo)\n )\n\n cmd_str = \" \".join(cmd)\n if result.returncode > 0:\n stderr = \"\\n\".join(result.stderr)\n raise RuntimeError(\n f\"'{cmd_str}' failed with returncode {result.returncode}\\n\\n\"\n f\"The combined stderr from workers follows:\\n{stderr}\"\n )\n\n # check that the subprocess actually did run and produced some output, should the test rely on\n # the remote side to do the testing\n if not result.stdout and not result.stderr:\n raise RuntimeError(f\"'{cmd_str}' produced no output.\")\n\n return result\n"
]
| [
[
"tensorflow.constant",
"tensorflow.saved_model.save",
"tensorflow.keras.models.load_model"
],
[
"tensorflow.config.list_physical_devices",
"torch.cuda.is_available",
"torch.cuda.device_count"
]
]
|
Covac/WaveRNN | [
"a9758caf30022064c604438a0766cad25046c5eb"
]
| [
"models/tacotron.py"
]
| [
"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pathlib import Path\nfrom typing import Union\n\n\nclass HighwayNetwork(nn.Module):\n def __init__(self, size):\n super().__init__()\n self.W1 = nn.Linear(size, size)\n self.W2 = nn.Linear(size, size)\n self.W1.bias.data.fill_(0.)\n\n def forward(self, x):\n x1 = self.W1(x)\n x2 = self.W2(x)\n g = torch.sigmoid(x2)\n y = g * F.relu(x1) + (1. - g) * x\n return y\n\n\nclass Encoder(nn.Module):\n def __init__(self, embed_dims, num_chars, cbhg_channels, K, num_highways, dropout):\n super().__init__()\n self.embedding = nn.Embedding(num_chars, embed_dims)\n self.pre_net = PreNet(embed_dims)\n self.cbhg = CBHG(K=K, in_channels=cbhg_channels, channels=cbhg_channels,\n proj_channels=[cbhg_channels, cbhg_channels],\n num_highways=num_highways)\n\n def forward(self, x):\n x = self.embedding(x)\n x = self.pre_net(x)\n x.transpose_(1, 2)\n x = self.cbhg(x)\n return x\n\n\nclass BatchNormConv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel, relu=True):\n super().__init__()\n self.conv = nn.Conv1d(in_channels, out_channels, kernel, stride=1, padding=kernel // 2, bias=False)\n self.bnorm = nn.BatchNorm1d(out_channels)\n self.relu = relu\n\n def forward(self, x):\n x = self.conv(x)\n x = F.relu(x) if self.relu is True else x\n return self.bnorm(x)\n\n\nclass CBHG(nn.Module):\n def __init__(self, K, in_channels, channels, proj_channels, num_highways):\n super().__init__()\n\n # List of all rnns to call `flatten_parameters()` on\n self._to_flatten = []\n\n self.bank_kernels = [i for i in range(1, K + 1)]\n self.conv1d_bank = nn.ModuleList()\n for k in self.bank_kernels:\n conv = BatchNormConv(in_channels, channels, k)\n self.conv1d_bank.append(conv)\n\n self.maxpool = nn.MaxPool1d(kernel_size=2, stride=1, padding=1)\n\n self.conv_project1 = BatchNormConv(len(self.bank_kernels) * channels, proj_channels[0], 3)\n self.conv_project2 = BatchNormConv(proj_channels[0], proj_channels[1], 3, relu=False)\n\n # Fix the highway input if necessary\n if proj_channels[-1] != channels:\n self.highway_mismatch = True\n self.pre_highway = nn.Linear(proj_channels[-1], channels, bias=False)\n else:\n self.highway_mismatch = False\n\n self.highways = nn.ModuleList()\n for i in range(num_highways):\n hn = HighwayNetwork(channels)\n self.highways.append(hn)\n\n self.rnn = nn.GRU(channels, channels, batch_first=True, bidirectional=True)\n self._to_flatten.append(self.rnn)\n\n # Avoid fragmentation of RNN parameters and associated warning\n self._flatten_parameters()\n\n def forward(self, x):\n # Although we `_flatten_parameters()` on init, when using DataParallel\n # the model gets replicated, making it no longer guaranteed that the\n # weights are contiguous in GPU memory. Hence, we must call it again\n self._flatten_parameters()\n\n # Save these for later\n residual = x\n seq_len = x.size(-1)\n conv_bank = []\n\n # Convolution Bank\n for conv in self.conv1d_bank:\n c = conv(x) # Convolution\n conv_bank.append(c[:, :, :seq_len])\n\n # Stack along the channel axis\n conv_bank = torch.cat(conv_bank, dim=1)\n\n # dump the last padding to fit residual\n x = self.maxpool(conv_bank)[:, :, :seq_len]\n\n # Conv1d projections\n x = self.conv_project1(x)\n x = self.conv_project2(x)\n\n # Residual Connect\n x = x + residual\n\n # Through the highways\n x = x.transpose(1, 2)\n if self.highway_mismatch is True:\n x = self.pre_highway(x)\n for h in self.highways: x = h(x)\n\n # And then the RNN\n x, _ = self.rnn(x)\n return x\n\n def _flatten_parameters(self):\n \"\"\"Calls `flatten_parameters` on all the rnns used by the WaveRNN. Used\n to improve efficiency and avoid PyTorch yelling at us.\"\"\"\n [m.flatten_parameters() for m in self._to_flatten]\n\nclass PreNet(nn.Module):\n def __init__(self, in_dims, fc1_dims=256, fc2_dims=128, dropout=0.5):\n super().__init__()\n self.fc1 = nn.Linear(in_dims, fc1_dims)\n self.fc2 = nn.Linear(fc1_dims, fc2_dims)\n self.p = dropout\n\n def forward(self, x):\n x = self.fc1(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n x = self.fc2(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n return x\n\n\nclass Attention(nn.Module):\n def __init__(self, attn_dims):\n super().__init__()\n self.W = nn.Linear(attn_dims, attn_dims, bias=False)\n self.v = nn.Linear(attn_dims, 1, bias=False)\n\n def forward(self, encoder_seq_proj, query, t):\n\n # print(encoder_seq_proj.shape)\n # Transform the query vector\n query_proj = self.W(query).unsqueeze(1)\n\n # Compute the scores\n u = self.v(torch.tanh(encoder_seq_proj + query_proj))\n scores = F.softmax(u, dim=1)\n\n return scores.transpose(1, 2)\n\n\nclass LSA(nn.Module):\n def __init__(self, attn_dim, kernel_size=31, filters=32):\n super().__init__()\n self.conv = nn.Conv1d(2, filters, padding=(kernel_size - 1) // 2, kernel_size=kernel_size, bias=False)\n self.L = nn.Linear(filters, attn_dim, bias=True)\n self.W = nn.Linear(attn_dim, attn_dim, bias=True)\n self.v = nn.Linear(attn_dim, 1, bias=False)\n self.cumulative = None\n self.attention = None\n\n def init_attention(self, encoder_seq_proj):\n device = next(self.parameters()).device # use same device as parameters\n b, t, c = encoder_seq_proj.size()\n self.cumulative = torch.zeros(b, t, device=device)\n self.attention = torch.zeros(b, t, device=device)\n\n def forward(self, encoder_seq_proj, query, t):\n\n if t == 0: self.init_attention(encoder_seq_proj)\n\n processed_query = self.W(query).unsqueeze(1)\n\n location = torch.cat([self.cumulative.unsqueeze(1), self.attention.unsqueeze(1)], dim=1)\n processed_loc = self.L(self.conv(location).transpose(1, 2))\n\n u = self.v(torch.tanh(processed_query + encoder_seq_proj + processed_loc))\n u = u.squeeze(-1)\n\n # Smooth Attention\n scores = torch.sigmoid(u) / torch.sigmoid(u).sum(dim=1, keepdim=True)\n # scores = F.softmax(u, dim=1)\n self.attention = scores\n self.cumulative += self.attention\n\n return scores.unsqueeze(-1).transpose(1, 2)\n\n\nclass Decoder(nn.Module):\n # Class variable because its value doesn't change between classes\n # yet ought to be scoped by class because its a property of a Decoder\n max_r = 20\n def __init__(self, n_mels, decoder_dims, lstm_dims):\n super().__init__()\n self.register_buffer('r', torch.tensor(1, dtype=torch.int))\n self.n_mels = n_mels\n self.prenet = PreNet(n_mels)\n self.attn_net = LSA(decoder_dims)\n self.attn_rnn = nn.GRUCell(decoder_dims + decoder_dims // 2, decoder_dims)\n self.rnn_input = nn.Linear(2 * decoder_dims, lstm_dims)\n self.res_rnn1 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.res_rnn2 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.mel_proj = nn.Linear(lstm_dims, n_mels * self.max_r, bias=False)\n\n def zoneout(self, prev, current, p=0.1):\n device = next(self.parameters()).device # Use same device as parameters\n mask = torch.zeros(prev.size(), device=device).bernoulli_(p)\n return prev * mask + current * (1 - mask)\n\n def forward(self, encoder_seq, encoder_seq_proj, prenet_in,\n hidden_states, cell_states, context_vec, t):\n\n # Need this for reshaping mels\n batch_size = encoder_seq.size(0)\n\n # Unpack the hidden and cell states\n attn_hidden, rnn1_hidden, rnn2_hidden = hidden_states\n rnn1_cell, rnn2_cell = cell_states\n\n # PreNet for the Attention RNN\n prenet_out = self.prenet(prenet_in)\n\n # Compute the Attention RNN hidden state\n attn_rnn_in = torch.cat([context_vec, prenet_out], dim=-1)\n attn_hidden = self.attn_rnn(attn_rnn_in.squeeze(1), attn_hidden)\n\n # Compute the attention scores\n scores = self.attn_net(encoder_seq_proj, attn_hidden, t)\n\n # Dot product to create the context vector\n context_vec = scores @ encoder_seq\n context_vec = context_vec.squeeze(1)\n\n # Concat Attention RNN output w. Context Vector & project\n x = torch.cat([context_vec, attn_hidden], dim=1)\n x = self.rnn_input(x)\n\n # Compute first Residual RNN\n rnn1_hidden_next, rnn1_cell = self.res_rnn1(x, (rnn1_hidden, rnn1_cell))\n if self.training:\n rnn1_hidden = self.zoneout(rnn1_hidden, rnn1_hidden_next)\n else:\n rnn1_hidden = rnn1_hidden_next\n x = x + rnn1_hidden\n\n # Compute second Residual RNN\n rnn2_hidden_next, rnn2_cell = self.res_rnn2(x, (rnn2_hidden, rnn2_cell))\n if self.training:\n rnn2_hidden = self.zoneout(rnn2_hidden, rnn2_hidden_next)\n else:\n rnn2_hidden = rnn2_hidden_next\n x = x + rnn2_hidden\n\n # Project Mels\n mels = self.mel_proj(x)\n mels = mels.view(batch_size, self.n_mels, self.max_r)[:, :, :self.r]\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n cell_states = (rnn1_cell, rnn2_cell)\n\n return mels, scores, hidden_states, cell_states, context_vec\n\n\nclass Tacotron(nn.Module):\n def __init__(self, embed_dims, num_chars, encoder_dims, decoder_dims, n_mels, fft_bins, postnet_dims,\n encoder_K, lstm_dims, postnet_K, num_highways, dropout, stop_threshold):\n super().__init__()\n self.n_mels = n_mels\n self.lstm_dims = lstm_dims\n self.decoder_dims = decoder_dims\n self.encoder = Encoder(embed_dims, num_chars, encoder_dims,\n encoder_K, num_highways, dropout)\n self.encoder_proj = nn.Linear(decoder_dims, decoder_dims, bias=False)\n self.decoder = Decoder(n_mels, decoder_dims, lstm_dims)\n self.postnet = CBHG(postnet_K, n_mels, postnet_dims, [256, 80], num_highways)\n self.post_proj = nn.Linear(postnet_dims * 2, fft_bins, bias=False)\n\n self.init_model()\n self.num_params()\n\n self.register_buffer('step', torch.zeros(1, dtype=torch.long))\n self.register_buffer('stop_threshold', torch.tensor(stop_threshold, dtype=torch.float32))\n\n @property\n def r(self):\n return self.decoder.r.item()\n\n @r.setter\n def r(self, value):\n self.decoder.r = self.decoder.r.new_tensor(value, requires_grad=False)\n\n def forward(self, x, m, generate_gta=False):\n device = next(self.parameters()).device # use same device as parameters\n\n self.step += 1\n\n if generate_gta:\n self.eval()\n else:\n self.train()\n\n batch_size, _, steps = m.size()\n\n # Initialise all hidden states and pack into tuple\n attn_hidden = torch.zeros(batch_size, self.decoder_dims, device=device)\n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n\n # Initialise all lstm cell states and pack into tuple\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n cell_states = (rnn1_cell, rnn2_cell)\n\n # <GO> Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels, device=device)\n\n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims, device=device)\n\n # Project the encoder outputs to avoid\n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x)\n encoder_seq_proj = self.encoder_proj(encoder_seq)\n\n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n\n # Run the decoder loop\n for t in range(0, steps, self.r):\n prenet_in = m[:, :, t - 1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in,\n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n\n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n\n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n linear = linear.transpose(1, 2)\n\n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n # attn_scores = attn_scores.cpu().data.numpy()\n\n return mel_outputs, linear, attn_scores\n\n def generate(self, x, steps=2000):\n self.eval()\n device = next(self.parameters()).device # use same device as parameters\n\n batch_size = 1\n x = torch.as_tensor(x, dtype=torch.long, device=device).unsqueeze(0)\n\n # Need to initialise all hidden states and pack into tuple for tidyness\n attn_hidden = torch.zeros(batch_size, self.decoder_dims, device=device)\n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n\n # Need to initialise all lstm cell states and pack into tuple for tidyness\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n cell_states = (rnn1_cell, rnn2_cell)\n\n # Need a <GO> Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels, device=device)\n\n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims, device=device)\n\n # Project the encoder outputs to avoid\n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x)\n encoder_seq_proj = self.encoder_proj(encoder_seq)\n\n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n\n # Run the decoder loop\n for t in range(0, steps, self.r):\n prenet_in = mel_outputs[-1][:, :, -1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in,\n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n # Stop the loop if silent frames present\n if (mel_frames < self.stop_threshold).all() and t > 10: break\n\n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n\n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n\n\n linear = linear.transpose(1, 2)[0].cpu().data.numpy()\n mel_outputs = mel_outputs[0].cpu().data.numpy()\n\n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n attn_scores = attn_scores.cpu().data.numpy()[0]\n\n self.train()\n\n return mel_outputs, linear, attn_scores\n\n def init_model(self):\n for p in self.parameters():\n if p.dim() > 1: nn.init.xavier_uniform_(p)\n\n def get_step(self):\n return self.step.data.item()\n\n def reset_step(self):\n # assignment to parameters or buffers is overloaded, updates internal dict entry\n self.step = self.step.data.new_tensor([0])\n\n def log(self, path, msg):\n with open(path, 'a') as f:\n print(msg, file=f)\n\n def load(self, path: Union[str, Path]):\n # Use device of model params as location for loaded state\n device = next(self.parameters()).device\n state_dict = torch.load(path, map_location=device)\n\n # Backwards compatibility with old saved models\n if 'r' in state_dict and not 'decoder.r' in state_dict:\n self.r = state_dict['r']\n\n self.load_state_dict(state_dict, strict=False)\n\n def save(self, path: Union[str, Path]):\n # No optimizer argument because saving a model should not include data\n # only relevant in the training process - it should only be properties\n # of the model itself. Let caller take care of saving optimzier state.\n torch.save(self.state_dict(), path)\n\n def num_params(self, print_out=True):\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000\n if print_out:\n print('Trainable Parameters: %.3fM' % parameters)\n return parameters\n"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.GRU",
"torch.nn.ModuleList",
"torch.load",
"torch.nn.MaxPool1d",
"torch.sigmoid",
"torch.nn.Conv1d",
"torch.tensor",
"torch.nn.functional.relu",
"torch.as_tensor",
"torch.zeros",
"torch.nn.LSTMCell",
"torch.nn.functional.dropout",
"torch.nn.functional.softmax",
"torch.nn.GRUCell",
"torch.nn.init.xavier_uniform_",
"torch.nn.BatchNorm1d",
"torch.tanh",
"torch.nn.Embedding"
]
]
|
winsphinx/covid-us | [
"d4715b186747211dc41d2130237be8dd9791a520"
]
| [
"covid.py"
]
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os\nimport re\nfrom concurrent.futures import ProcessPoolExecutor\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pmdarima import arima\nfrom pmdarima.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\n\n\ndef adjust_date(s):\n t = s.split(\"/\")\n return f\"20{t[2]}-{int(t[0]):02d}-{int(t[1]):02d}\"\n\n\ndef adjust_name(s):\n return re.sub(r\"\\*|\\,|\\(|\\)|\\*|\\ |\\'\", \"_\", s)\n\n\ndef draw(province):\n draw_(province, True)\n draw_(province, False)\n\n\ndef draw_(province, isDaily):\n # 模型训练\n model = arima.AutoARIMA(\n start_p=0,\n max_p=4,\n d=None,\n start_q=0,\n max_q=1,\n start_P=0,\n max_P=1,\n D=None,\n start_Q=0,\n max_Q=1,\n m=7,\n seasonal=True,\n test=\"kpss\",\n trace=True,\n error_action=\"ignore\",\n suppress_warnings=True,\n stepwise=True,\n )\n if isDaily:\n data = df[province].diff().dropna()\n model.fit(data)\n else:\n data = df[province]\n model.fit(data)\n\n # 模型验证\n train, test = train_test_split(data, train_size=0.8)\n pred_test = model.predict_in_sample(start=train.shape[0], dynamic=False)\n validating = pd.Series(pred_test, index=test.index)\n r2 = r2_score(test, pred_test)\n\n # 开始预测\n pred, pred_ci = model.predict(n_periods=14, return_conf_int=True)\n idx = pd.date_range(data.index.max() + pd.Timedelta(\"1D\"), periods=14, freq=\"D\")\n forecasting = pd.Series(pred, index=idx)\n\n # 绘图呈现\n plt.figure(figsize=(24, 6))\n\n plt.plot(data.index, data, label=\"Actual Value\", color=\"blue\")\n plt.plot(validating.index, validating, label=\"Check Value\", color=\"orange\")\n plt.plot(forecasting.index, forecasting, label=\"Predict Value\", color=\"red\")\n # plt.fill_between(forecasting.index, pred_ci[:, 0], pred_ci[:, 1], color=\"black\", alpha=.25)\n\n plt.legend()\n plt.ticklabel_format(style=\"plain\", axis=\"y\")\n # plt.rcParams[\"font.sans-serif\"] = [\"Microsoft YaHei\"]\n if isDaily:\n plt.title(\n f\"Daily Confirmed Cases Forecasting - {province}\\nARIMA {model.model_.order}x{model.model_.seasonal_order} (R2 = {r2:.6f})\"\n )\n plt.savefig(\n os.path.join(\"figures\", f\"covid-{adjust_name(province)}-daily.svg\"),\n bbox_inches=\"tight\",\n )\n plt.close()\n else:\n plt.title(\n f\"Accumulative Confirmed Cases Forecasting - {province}\\nARIMA {model.model_.order}x{model.model_.seasonal_order} (R2 = {r2:.6f})\"\n )\n plt.savefig(\n os.path.join(\"figures\", f\"covid-{adjust_name(province)}.svg\"),\n bbox_inches=\"tight\",\n )\n plt.close()\n\n\nif __name__ == \"__main__\":\n # 准备数据\n df = (\n pd.read_csv(\n \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv\"\n )\n .drop(\n columns=[\n \"UID\",\n \"iso2\",\n \"iso3\",\n \"code3\",\n \"FIPS\",\n \"Admin2\",\n \"Country_Region\",\n \"Lat\",\n \"Long_\",\n \"Combined_Key\",\n ]\n )\n .groupby(\"Province_State\")\n .sum()\n .transpose()\n .drop(columns=[\"Diamond Princess\", \"Grand Princess\"])\n )\n df.index = pd.DatetimeIndex(df.index.map(adjust_date))\n\n provinces = df.columns.to_list()\n\n # 线程池\n with ProcessPoolExecutor() as pool:\n pool.map(draw, provinces)\n pool.shutdown(wait=True)\n\n # 编制索引\n with codecs.open(\"README.md\", \"w\", \"utf-8\") as f:\n f.write(\"# COVID-19 Forecasting\\n\\n\")\n f.write(\n \"[](https://github.com/winsphinx/covid-us/actions/workflows/build.yml)\\n\"\n )\n f.write(\n \"[](https://github.com/winsphinx/covid-us/actions/workflows/check.yml)\\n\"\n )\n f.write(\n \"[](https://github.com/CSSEGISandData/COVID-19)\\n\"\n )\n for province in provinces:\n f.write(f\"## {province}\\n\\n\")\n f.write(f\"}.svg)\\n\\n\")\n f.write(f\"}-daily.svg)\\n\\n\")\n"
]
| [
[
"pandas.Timedelta",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"pandas.Series",
"sklearn.metrics.r2_score",
"pandas.read_csv",
"matplotlib.pyplot.ticklabel_format"
]
]
|
Bhaskers-Blu-Org2/solution-accelerator-many-models | [
"cef1226195313fecaabce9f107544befbb3b8125"
]
| [
"Custom_Script/scripts/timeseries_utilities.py"
]
| [
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline\n\n\nclass ColumnDropper(TransformerMixin, BaseEstimator):\n \"\"\"\n Transformer for dropping columns from a dataframe.\n \"\"\"\n def __init__(self, drop_columns):\n assert isinstance(drop_columns, list), \"Expected drop_columns input to be a list\"\n self.drop_columns = drop_columns\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n return X.drop(columns=self.drop_columns, errors='ignore')\n\n\nclass SimpleCalendarFeaturizer(TransformerMixin, BaseEstimator):\n \"\"\"\n Transformer for adding a simple calendar feature derived from the input time index.\n For demonstration purposes, the transform creates a feature for week of the year.\n \"\"\"\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n return X.assign(Week_Year=X.index.weekofyear.values)\n\n\nclass SimpleLagger(TransformerMixin, BaseEstimator):\n \"\"\"\n Simple lagging transform that creates lagged values of the target column.\n This transform uses information known at fit time to create lags at transform time\n to maintain lag feature continuity across train/test splits.\n \"\"\"\n\n def __init__(self, target_column_name, lag_orders=None):\n my_lag_orders = lag_orders if lag_orders is not None else [1]\n assert isinstance(my_lag_orders, list) and min(my_lag_orders) > 0, \\\n 'Expected lag_orders to be a list of integers all greater than zero'\n self.target_column_name = target_column_name\n self.lag_orders = my_lag_orders\n\n def fit(self, X, y=None):\n \"\"\"\n Fit the lagger transform.\n This transform caches the tail of the training data up to the maximum lag order\n so that lag features can be created on test data.\n \"\"\"\n assert self.target_column_name in X.columns, \\\n \"Target column is missing from the input dataframe.\"\n\n X_fit = X.sort_index(ascending=True)\n max_lag_order = max(self.lag_orders)\n self._train_tail = X_fit.iloc[-max_lag_order:]\n self._column_order = self._train_tail.columns\n\n return self\n\n def transform(self, X):\n \"\"\"\n Create lag features of the target for the input data.\n The transform uses data cached at fit time, if necessary, to provide\n continuity of lag features.\n \"\"\"\n X_trans = X.copy()\n added_target = False\n if self.target_column_name not in X_trans.columns:\n X_trans[self.target_column_name] = np.nan\n added_target = True\n\n # decide if we need to use the training cache i.e. are we in a test scenario?\n train_latest = self._train_tail.index.max()\n X_earliest = X_trans.index.min()\n if train_latest < X_earliest:\n # X data is later than the training period - append the cached tail of training data\n X_trans = pd.concat((self._train_tail, X_trans[self._column_order]))\n\n # Ensure data is sorted by time before making lags\n X_trans.sort_index(ascending=True, inplace=True)\n\n # Make the lag features\n for lag_order in self.lag_orders:\n X_trans['lag_' + str(lag_order)] = X_trans[self.target_column_name].shift(lag_order)\n\n # Return transformed dataframe with the same time range as X\n if added_target:\n X_trans.drop(columns=[self.target_column_name], inplace=True)\n return X_trans.loc[X.index]\n\n\nclass SklearnWrapper(BaseEstimator):\n \"\"\"\n Wrapper class around an sklearn model.\n This wrapper formats DataFrame input for scikit-learn regression estimators.\n \"\"\"\n def __init__(self, sklearn_model, target_column_name):\n self.sklearn_model = sklearn_model\n self.target_column_name = target_column_name\n\n def fit(self, X, y=None):\n \"\"\"\n Fit the sklearn model on the input dataframe.\n \"\"\"\n assert self.target_column_name in X.columns, \\\n \"Target column is missing from the input dataframe.\"\n\n # Drop rows with missing values and check that we still have data left\n X_fit = X.dropna()\n assert len(X_fit) > 0, 'Training dataframe is empty after dropping NA values'\n\n # Check that data is all numeric type\n # This simple pipeline does not handle categoricals or other non-numeric types\n full_col_set = set(X_fit.columns)\n numeric_col_set = set(X_fit.select_dtypes(include=[np.number]).columns)\n assert full_col_set == numeric_col_set, \\\n ('Found non-numeric columns {} in the input dataframe. Please drop them prior to modeling.'\n .format(full_col_set - numeric_col_set))\n\n # Fit the scikit model\n y_fit = X_fit.pop(self.target_column_name)\n self._column_order = X_fit.columns\n self.sklearn_model.fit(X_fit.values, y_fit.values)\n return self\n\n def transform(self, X):\n \"\"\"\n Identity transform for fit_transform pipelines.\n \"\"\"\n return X\n\n def predict(self, X):\n \"\"\"\n Predict on the input dataframe.\n Return a Pandas Series with time in the index\n \"\"\"\n # Check the column set in input is compatible with fitted model\n input_col_set = set(X.columns) - set([self.target_column_name])\n assert input_col_set == set(self._column_order), \\\n 'Input columns {} do not match expected columns {}'.format(input_col_set, self._column_order)\n\n X_pred = X.drop(columns=[self.target_column_name], errors='ignore')[self._column_order]\n X_pred.dropna(inplace=True)\n assert len(X_pred) > 0, 'Prediction dataframe is empty after dropping NA values'\n y_raw = self.sklearn_model.predict(X_pred.values)\n return pd.Series(data=y_raw, index=X_pred.index)\n\n\nclass SimpleForecaster(TransformerMixin):\n \"\"\"\n Forecasting class for a simple, 1-step ahead forecaster.\n This class encapsulates fitting a transform pipeline with an sklearn regression estimator\n and producing in-sample and out-of-sample forecasts.\n Out-of-sample forecasts apply the model recursively over the prediction set to produce forecasts\n at any horizon.\n\n The forecaster assumes that the time-series data is regularly sampled on a contiguous interval;\n it does not handle missing values.\n \"\"\"\n\n def __init__(self, transform_steps, estimator, target_column_name, time_column_name):\n assert estimator is not None, \"Estimator cannot be None.\"\n assert transform_steps is None or isinstance(transform_steps, list), \\\n \"transform_steps should be a list\"\n estimator_step = ('estimator', SklearnWrapper(estimator, target_column_name))\n steps = transform_steps + [estimator_step] if transform_steps is not None else [estimator_step]\n self.pipeline = Pipeline(steps=steps)\n\n self.target_column_name = target_column_name\n self.time_column_name = time_column_name\n\n def _recursive_forecast(self, X):\n \"\"\"\n Apply the trained model resursively for out-of-sample predictions.\n \"\"\"\n X_fcst = X.sort_index(ascending=True)\n if self.target_column_name not in X_fcst.columns:\n X_fcst[self.target_column_name] = np.nan\n\n forecasts = pd.Series(np.nan, index=X_fcst.index)\n for fcst_date in X_fcst.index.get_level_values(self.time_column_name):\n # Get predictions on an expanding window ending on the current forecast date\n y_fcst = self.pipeline.predict(X_fcst[X_fcst.index <= fcst_date])\n\n # Set the current forecast\n forecasts.loc[fcst_date] = y_fcst.loc[fcst_date]\n\n # Set the actual value to the forecast value so that lag features can be made on next iteration\n X_fcst.loc[fcst_date, self.target_column_name] = y_fcst.loc[fcst_date]\n\n return forecasts\n\n def fit(self, X):\n \"\"\"\n Fit the forecasting pipeline.\n This method assumes the target is a column in the input, X.\n \"\"\"\n assert list(X.index.names) == [self.time_column_name], \\\n \"Expected time column to comprise input dataframe index.\"\n self._latest_training_date = X.index.max()\n self.pipeline.fit(X)\n return self\n\n def transform(self, X):\n \"\"\"\n Transform the data through the pipeline.\n \"\"\"\n return self.pipeline.transform(X)\n\n def forecast(self, X):\n \"\"\"\n Make forecasts over the prediction frame, X.\n X can contain in-sample and out-of-sample data.\n For out-of-sample data, the 1-step-ahead model is recursively applied.\n\n Returns forecasts for the target in a pd.Series object with the same time index as X.\n np.nan values will be returned for dates where a forecast could not be found.\n \"\"\"\n assert list(X.index.names) == [self.time_column_name], \\\n \"Expected time column to comprise input dataframe index.\"\n # Get in-sample forecasts if requested\n X_insamp = X[X.index <= self._latest_training_date]\n forecasts_insamp = pd.Series()\n if len(X_insamp) > 0:\n forecasts_insamp = self.pipeline.predict(X_insamp)\n\n # Get out-of-sample forecasts\n X_fcst = X[X.index > self._latest_training_date]\n forecasts = pd.Series()\n if len(X_fcst) > 0:\n # Need to iterate/recurse 1-step forecasts here\n forecasts = self._recursive_forecast(X_fcst)\n forecasts = pd.concat((forecasts_insamp, forecasts))\n\n return forecasts.reindex(X.index)\n"
]
| [
[
"pandas.concat",
"sklearn.pipeline.Pipeline",
"pandas.Series"
]
]
|
Jirka-Mayer/BachelorThesis | [
"b5333cb0ac5f6defa8e78573f8da6bcbf97b2bad"
]
| [
"mashcima/debug.py"
]
| [
"import numpy as np\nimport cv2\n\n\ndef show_images(images, row_length=5):\n \"\"\"For debugging - shows many images in a single plot\"\"\"\n import matplotlib.pyplot as plt\n\n n_total = len(images)\n n_rows = n_total // row_length + 1\n n_cols = min(n_total, row_length)\n fig = plt.figure()\n for i, img in enumerate(images):\n plt.subplot(n_rows, n_cols, i+1)\n #plt.imshow(img, cmap='gray', interpolation='nearest')\n plt.imshow(img)\n # Let's remove the axis labels, they clutter the image.\n for ax in fig.axes:\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n ax.set_yticks([])\n ax.set_xticks([])\n plt.show()\n\n\ndef draw_cross(\n img: np.ndarray,\n x: int, y: int,\n size: int = 10,\n thickness: int = 2,\n color: any = 0.5\n) -> np.ndarray:\n \"\"\"Draws a cross into an image\"\"\"\n cv2.line(\n img,\n (x - size, y + size),\n (x + size, y - size),\n thickness=thickness,\n color=color\n )\n cv2.line(\n img,\n (x - size, y - size),\n (x + size, y + size),\n thickness=thickness,\n color=color\n )\n return img\n"
]
| [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure"
]
]
|
jsuarez5341/PettingZoo | [
"0cef616c311c59b592d8639dfe586fba4a9a61a0"
]
| [
"pettingzoo/butterfly/pistonball/pistonball.py"
]
| [
"import math\nimport os\n\nimport gym\nimport numpy as np\nimport pygame\nimport pymunk\nimport pymunk.pygame_util\nfrom gym.utils import EzPickle, seeding\n\nfrom pettingzoo import AECEnv\nfrom pettingzoo.utils import agent_selector, wrappers\nfrom pettingzoo.utils.conversions import parallel_wrapper_fn\n\nfrom .manual_control import manual_control\n\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'\n\n_image_library = {}\n\n\ndef get_image(path):\n from os import path as os_path\n cwd = os_path.dirname(__file__)\n image = pygame.image.load(cwd + '/' + path)\n sfc = pygame.Surface(image.get_size(), flags=pygame.SRCALPHA)\n sfc.blit(image, (0, 0))\n return sfc\n\n\ndef env(**kwargs):\n env = raw_env(**kwargs)\n if env.continuous:\n env = wrappers.ClipOutOfBoundsWrapper(env)\n else:\n env = wrappers.AssertOutOfBoundsWrapper(env)\n env = wrappers.OrderEnforcingWrapper(env)\n return env\n\n\nparallel_env = parallel_wrapper_fn(env)\n\n\nclass raw_env(AECEnv, EzPickle):\n\n metadata = {'render.modes': ['human', \"rgb_array\"], 'name': \"pistonball_v4\"}\n\n def __init__(self, n_pistons=20, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125):\n EzPickle.__init__(self, n_pistons, time_penalty, continuous, random_drop, random_rotate, ball_mass, ball_friction, ball_elasticity, max_cycles)\n self.n_pistons = n_pistons\n self.piston_head_height = 11\n self.piston_width = 40\n self.piston_height = 40\n self.piston_body_height = 23\n self.piston_radius = 5\n self.wall_width = 40\n self.ball_radius = 40\n self.screen_width = (2 * self.wall_width) + (self.piston_width * self.n_pistons)\n self.screen_height = 560\n y_high = self.screen_height - self.wall_width - self.piston_body_height\n y_low = self.wall_width\n obs_height = y_high - y_low\n\n assert self.piston_width == self.wall_width, \"Wall width and piston width must be equal for observation calculation\"\n assert self.n_pistons > 1, \"n_pistons must be greater than 1\"\n\n self.agents = [\"piston_\" + str(r) for r in range(self.n_pistons)]\n self.possible_agents = self.agents[:]\n self.agent_name_mapping = dict(zip(self.agents, list(range(self.n_pistons))))\n self._agent_selector = agent_selector(self.agents)\n\n self.observation_spaces = dict(\n zip(self.agents, [gym.spaces.Box(low=0, high=255, shape=(obs_height, self.piston_width * 3, 3), dtype=np.uint8)] * self.n_pistons))\n self.continuous = continuous\n if self.continuous:\n self.action_spaces = dict(zip(self.agents, [gym.spaces.Box(low=-1, high=1, shape=(1,))] * self.n_pistons))\n else:\n self.action_spaces = dict(zip(self.agents, [gym.spaces.Discrete(3)] * self.n_pistons))\n self.state_space = gym.spaces.Box(low=0, high=255, shape=(self.screen_height, self.screen_width, 3), dtype=np.uint8)\n\n pygame.init()\n pymunk.pygame_util.positive_y_is_up = False\n\n self.renderOn = False\n self.screen = pygame.Surface((self.screen_width, self.screen_height))\n self.max_cycles = max_cycles\n\n self.piston_sprite = get_image('piston.png')\n self.piston_body_sprite = get_image('piston_body.png')\n self.background = get_image('background.png')\n self.random_drop = random_drop\n self.random_rotate = random_rotate\n\n self.pistonList = []\n self.pistonRewards = [] # Keeps track of individual rewards\n self.recentFrameLimit = 20 # Defines what \"recent\" means in terms of number of frames.\n self.recentPistons = set() # Set of pistons that have touched the ball recently\n self.time_penalty = time_penalty\n self.local_ratio = 0 # TODO: this was a bad idea and the logic this uses should be removed at some point\n self.ball_mass = ball_mass\n self.ball_friction = ball_friction\n self.ball_elasticity = ball_elasticity\n\n self.done = False\n\n self.pixels_per_position = 4\n self.n_piston_positions = 16\n\n self.screen.fill((0, 0, 0))\n self.draw_background()\n # self.screen.blit(self.background, (0, 0))\n\n self.render_rect = pygame.Rect(\n self.wall_width, # Left\n self.wall_width, # Top\n self.screen_width - (2 * self.wall_width), # Width\n self.screen_height - (2 * self.wall_width) - self.piston_body_height # Height\n )\n\n # Blit background image if ball goes out of bounds. Ball radius is 40\n self.valid_ball_position_rect = pygame.Rect(\n self.render_rect.left + self.ball_radius, # Left\n self.render_rect.top + self.ball_radius, # Top\n self.render_rect.width - (2 * self.ball_radius), # Width\n self.render_rect.height - (2 * self.ball_radius) # Height\n )\n\n self.frames = 0\n\n self.has_reset = False\n self.closed = False\n self.seed()\n\n def observation_space(self, agent):\n return self.observation_spaces[agent]\n\n def action_space(self, agent):\n return self.action_spaces[agent]\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n\n def observe(self, agent):\n observation = pygame.surfarray.pixels3d(self.screen)\n i = self.agent_name_mapping[agent]\n # Set x bounds to include 40px left and 40px right of piston\n x_high = self.wall_width + self.piston_width * (i + 2)\n x_low = self.wall_width + self.piston_width * (i - 1)\n y_high = self.screen_height - self.wall_width - self.piston_body_height\n y_low = self.wall_width\n cropped = np.array(observation[x_low:x_high, y_low:y_high, :])\n observation = np.rot90(cropped, k=3)\n observation = np.fliplr(observation)\n return observation\n\n def state(self):\n '''\n Returns an observation of the global environment\n '''\n state = pygame.surfarray.pixels3d(self.screen).copy()\n state = np.rot90(state, k=3)\n state = np.fliplr(state)\n return state\n\n def enable_render(self):\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n\n self.renderOn = True\n # self.screen.blit(self.background, (0, 0))\n self.draw_background()\n self.draw()\n\n def close(self):\n if not self.closed:\n self.closed = True\n if self.renderOn:\n self.screen = pygame.Surface((self.screen_width, self.screen_height))\n self.renderOn = False\n pygame.event.pump()\n pygame.display.quit()\n\n def add_walls(self):\n top_left = (self.wall_width, self.wall_width)\n top_right = (self.screen_width - self.wall_width, self.wall_width)\n bot_left = (self.wall_width, self.screen_height - self.wall_width)\n bot_right = (self.screen_width - self.wall_width, self.screen_height - self.wall_width)\n walls = [\n pymunk.Segment(self.space.static_body, top_left, top_right, 1), # Top wall\n pymunk.Segment(self.space.static_body, top_left, bot_left, 1), # Left wall\n pymunk.Segment(self.space.static_body, bot_left, bot_right, 1), # Bottom wall\n pymunk.Segment(self.space.static_body, top_right, bot_right, 1) # Right\n ]\n for wall in walls:\n wall.friction = .64\n self.space.add(wall)\n\n def add_ball(self, x, y, b_mass, b_friction, b_elasticity):\n mass = b_mass\n radius = 40\n inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))\n body = pymunk.Body(mass, inertia)\n body.position = x, y\n # radians per second\n if self.random_rotate:\n body.angular_velocity = self.np_random.uniform(-6 * math.pi, 6 * math.pi)\n shape = pymunk.Circle(body, radius, (0, 0))\n shape.friction = b_friction\n shape.elasticity = b_elasticity\n self.space.add(body, shape)\n return body\n\n def add_piston(self, space, x, y):\n piston = pymunk.Body(body_type=pymunk.Body.KINEMATIC)\n piston.position = x, y\n segment = pymunk.Segment(piston, (0, 0), (self.piston_width - (2 * self.piston_radius), 0), self.piston_radius)\n segment.friction = .64\n segment.color = pygame.color.THECOLORS[\"blue\"]\n space.add(piston, segment)\n return piston\n\n def move_piston(self, piston, v):\n\n def cap(y):\n maximum_piston_y = self.screen_height - self.wall_width - (self.piston_height - self.piston_head_height)\n if y > maximum_piston_y:\n y = maximum_piston_y\n elif y < maximum_piston_y - (self.n_piston_positions * self.pixels_per_position):\n y = maximum_piston_y - (self.n_piston_positions * self.pixels_per_position)\n return y\n\n piston.position = (piston.position[0], cap(piston.position[1] - v * self.pixels_per_position))\n\n def reset(self):\n self.space = pymunk.Space(threaded=False)\n self.add_walls()\n # self.space.threads = 2\n self.space.gravity = (0.0, 750.0)\n self.space.collision_bias = .0001\n self.space.iterations = 10 # 10 is default in PyMunk\n\n self.pistonList = []\n maximum_piston_y = self.screen_height - self.wall_width - (self.piston_height - self.piston_head_height)\n for i in range(self.n_pistons):\n # Multiply by 0.5 to use only the lower half of possible positions\n possible_y_displacements = np.arange(0, .5 * self.pixels_per_position * self.n_piston_positions, self.pixels_per_position)\n piston = self.add_piston(\n self.space,\n self.wall_width + self.piston_radius + self.piston_width * i, # x position\n maximum_piston_y - self.np_random.choice(possible_y_displacements) # y position\n )\n piston.velociy = 0\n self.pistonList.append(piston)\n\n self.horizontal_offset = 0\n self.vertical_offset = 0\n horizontal_offset_range = 30\n vertical_offset_range = 15\n if self.random_drop:\n self.vertical_offset = self.np_random.randint(-vertical_offset_range, vertical_offset_range + 1)\n self.horizontal_offset = self.np_random.randint(-horizontal_offset_range, horizontal_offset_range + 1)\n ball_x = (self.screen_width\n - self.wall_width\n - self.ball_radius\n - horizontal_offset_range\n + self.horizontal_offset)\n ball_y = (self.screen_height\n - self.wall_width\n - self.piston_body_height\n - self.ball_radius\n - (0.5 * self.pixels_per_position * self.n_piston_positions)\n - vertical_offset_range\n + self.vertical_offset)\n\n # Ensure ball starts somewhere right of the left wall\n ball_x = max(ball_x, self.wall_width + self.ball_radius + 1)\n\n self.ball = self.add_ball(ball_x, ball_y, self.ball_mass, self.ball_friction, self.ball_elasticity)\n self.ball.angle = 0\n self.ball.velocity = (0, 0)\n if self.random_rotate:\n self.ball.angular_velocity = self.np_random.uniform(-6 * math.pi, 6 * math.pi)\n\n self.lastX = int(self.ball.position[0] - self.ball_radius)\n self.distance = self.lastX - self.wall_width\n\n self.draw_background()\n self.draw()\n\n self.agents = self.possible_agents[:]\n\n self._agent_selector.reinit(self.agents)\n self.agent_selection = self._agent_selector.next()\n\n self.has_reset = True\n self.done = False\n self.rewards = dict(zip(self.agents, [0 for _ in self.agents]))\n self._cumulative_rewards = dict(zip(self.agents, [0 for _ in self.agents]))\n self.dones = dict(zip(self.agents, [False for _ in self.agents]))\n self.infos = dict(zip(self.agents, [{} for _ in self.agents]))\n\n self.frames = 0\n\n def draw_background(self):\n outer_walls = pygame.Rect(\n 0, # Left\n 0, # Top\n self.screen_width, # Width\n self.screen_height, # Height\n )\n outer_wall_color = (58, 64, 65)\n pygame.draw.rect(self.screen, outer_wall_color, outer_walls)\n inner_walls = pygame.Rect(\n self.wall_width / 2, # Left\n self.wall_width / 2, # Top\n self.screen_width - self.wall_width, # Width\n self.screen_height - self.wall_width, # Height\n )\n inner_wall_color = (68, 76, 77)\n pygame.draw.rect(self.screen, inner_wall_color, inner_walls)\n self.draw_pistons()\n\n def draw_pistons(self):\n piston_color = (65, 159, 221)\n x_pos = self.wall_width\n for piston in self.pistonList:\n self.screen.blit(self.piston_body_sprite, (x_pos, self.screen_height - self.wall_width - self.piston_body_height))\n # Height is the size of the blue part of the piston. 6 is the piston base height (the gray part at the bottom)\n height = self.screen_height - self.wall_width - self.piston_body_height - (piston.position[1] + self.piston_radius) + (self.piston_body_height - 6)\n body_rect = pygame.Rect(\n piston.position[0] + self.piston_radius + 1, # +1 to match up to piston graphics\n piston.position[1] + self.piston_radius + 1,\n 18,\n height\n )\n pygame.draw.rect(self.screen, piston_color, body_rect)\n x_pos += self.piston_width\n\n def draw(self):\n # redraw the background image if ball goes outside valid position\n if not self.valid_ball_position_rect.collidepoint(self.ball.position):\n # self.screen.blit(self.background, (0, 0))\n self.draw_background()\n\n ball_x = int(self.ball.position[0])\n ball_y = int(self.ball.position[1])\n\n color = (255, 255, 255)\n pygame.draw.rect(self.screen, color, self.render_rect)\n color = (65, 159, 221)\n pygame.draw.circle(self.screen, color, (ball_x, ball_y), self.ball_radius)\n\n line_end_x = ball_x + (self.ball_radius - 1) * np.cos(self.ball.angle)\n line_end_y = ball_y + (self.ball_radius - 1) * np.sin(self.ball.angle)\n color = (58, 64, 65)\n pygame.draw.line(self.screen, color, (ball_x, ball_y), (line_end_x, line_end_y), 3) # 39 because it kept sticking over by 1 at 40\n\n for piston in self.pistonList:\n self.screen.blit(self.piston_sprite, (piston.position[0] - self.piston_radius, piston.position[1] - self.piston_radius))\n self.draw_pistons()\n\n def get_nearby_pistons(self):\n # first piston = leftmost\n nearby_pistons = []\n ball_pos = int(self.ball.position[0] - self.ball_radius)\n closest = abs(self.pistonList[0].position.x - ball_pos)\n closest_piston_index = 0\n for i in range(self.n_pistons):\n next_distance = abs(self.pistonList[i].position.x - ball_pos)\n if next_distance < closest:\n closest = next_distance\n closest_piston_index = i\n\n if closest_piston_index > 0:\n nearby_pistons.append(closest_piston_index - 1)\n nearby_pistons.append(closest_piston_index)\n if closest_piston_index < self.n_pistons - 1:\n nearby_pistons.append(closest_piston_index + 1)\n\n return nearby_pistons\n\n def get_local_reward(self, prev_position, curr_position):\n local_reward = .5 * (prev_position - curr_position)\n return local_reward\n\n def render(self, mode=\"human\"):\n if mode == 'human' and not self.renderOn:\n # sets self.renderOn to true and initializes display\n self.enable_render()\n\n self.draw_background()\n self.draw()\n\n observation = np.array(pygame.surfarray.pixels3d(self.screen))\n if mode == 'human':\n pygame.display.flip()\n return np.transpose(observation, axes=(1, 0, 2)) if mode == \"rgb_array\" else None\n\n def step(self, action):\n if self.dones[self.agent_selection]:\n return self._was_done_step(action)\n\n action = np.asarray(action)\n agent = self.agent_selection\n if self.continuous:\n self.move_piston(self.pistonList[self.agent_name_mapping[agent]], action)\n else:\n self.move_piston(self.pistonList[self.agent_name_mapping[agent]], action - 1)\n\n self.space.step(1 / 20.0)\n if self._agent_selector.is_last():\n ball_min_x = int(self.ball.position[0] - self.ball_radius)\n if ball_min_x <= self.wall_width + 1:\n self.done = True\n self.draw()\n local_reward = self.get_local_reward(self.lastX, ball_min_x)\n # Opposite order due to moving right to left\n global_reward = (100 / self.distance) * (self.lastX - ball_min_x)\n if not self.done:\n global_reward += self.time_penalty\n total_reward = [global_reward * (1 - self.local_ratio)] * self.n_pistons # start with global reward\n local_pistons_to_reward = self.get_nearby_pistons()\n for index in local_pistons_to_reward:\n total_reward[index] += local_reward * self.local_ratio\n self.rewards = dict(zip(self.agents, total_reward))\n self.lastX = ball_min_x\n self.frames += 1\n else:\n self._clear_rewards()\n\n if self.frames >= self.max_cycles:\n self.done = True\n # Clear the list of recent pistons for the next reward cycle\n if self.frames % self.recentFrameLimit == 0:\n self.recentPistons = set()\n if self._agent_selector.is_last():\n self.dones = dict(zip(self.agents, [self.done for _ in self.agents]))\n\n self.agent_selection = self._agent_selector.next()\n self._cumulative_rewards[agent] = 0\n self._accumulate_rewards()\n\n# Game art created by J K Terry\n"
]
| [
[
"numpy.rot90",
"numpy.array",
"numpy.sin",
"numpy.asarray",
"numpy.arange",
"numpy.transpose",
"numpy.cos",
"numpy.fliplr"
]
]
|
stellaraccident/jax | [
"655a3e79c23060e87595d4a52dc595352fa29c9b"
]
| [
"docs/autodidax.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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# jupyter:\n# jupytext:\n# formats: ipynb,md:myst,py\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.10.0\n# kernelspec:\n# display_name: Python 3\n# name: python3\n# ---\n\n# [](https://colab.research.google.com/github/google/jax/blob/main/docs/autodidax.ipynb)\n\n\n# # Autodidax: JAX core from scratch\n#\n# Ever want to learn how JAX works, but the implementation seemed impenetrable?\n# Well, you're in luck! By reading this tutorial, you'll learn every big idea in\n# JAX's core system. You'll even get clued into our weird jargon!\n#\n# **This is a work-in-progress draft.** There are some important ingredients\n# missing, still to come in parts 5 and 6 (and more?). There are also some\n# simplifications here that we haven't yet applied to the main system, but we\n# will.\n\n# ## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap`\n#\n# We want to transform functions that look like this:\n#\n# ```python\n# def f(x):\n# y = sin(x) * 2.\n# z = - y + x\n# return z\n# ```\n#\n# Think of functions like `sin` and the arithmetic operations underlying the\n# infix operators (`mul`, `add`, and `neg`) as primitive operations, meaning\n# atomic units of processing rather than compositions.\n#\n# \"Transform\" means \"interpret differently.\" Instead of standard interpretation\n# where we apply primitive operations to numerical inputs to produce numerical\n# outputs, we want to override primitive application and let different values\n# flow through our program. For example, we might want to replace the\n# application of every primitive with an application of [its JVP\n# rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\n# and let primal-tangent pairs flow through our program. Moreover, we want to be\n# able to compose multiple transformations, leading to stacks of interpreters.\n\n# ### JAX core machinery\n#\n# We can implement stacks of interpreters and even have them all discharge on\n# the fly as we execute the Python function to be transformed. To start, let's\n# define these primitives so that we can intercept their application:\n\n\n# +\nfrom typing import NamedTuple\n\nclass Primitive(NamedTuple):\n name: str\n\nadd_p = Primitive('add')\nmul_p = Primitive('mul')\nneg_p = Primitive(\"neg\")\nsin_p = Primitive(\"sin\")\ncos_p = Primitive(\"cos\")\nreduce_sum_p = Primitive(\"reduce_sum\")\ngreater_p = Primitive(\"greater\")\nless_p = Primitive(\"less\")\ntranspose_p = Primitive(\"transpose\")\nbroadcast_p = Primitive(\"broadcast\")\n\ndef add(x, y): return bind1(add_p, x, y)\ndef mul(x, y): return bind1(mul_p, x, y)\ndef neg(x): return bind1(neg_p, x)\ndef sin(x): return bind1(sin_p, x)\ndef cos(x): return bind1(cos_p, x)\ndef reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis)\ndef greater(x, y): return bind1(greater_p, x, y)\ndef less(x, y): return bind1(less_p, x, y)\ndef transpose(x, perm): return bind1(transpose_p, perm=perm)\ndef broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes)\n\ndef bind1(prim, *args, **params):\n out, = bind(prim, *args, **params)\n return out\n# -\n\n# We'll set up array data types and infix operator methods in a moment.\n#\n# A `Primitive` is just an object with a name, to which we attach our\n# interpretation rules (one for each transformation). The `bind` function is our\n# interception point: it'll figure out which transformation rule to apply, based\n# on how the arguments are boxed in tracers and what interpreters are active.\n#\n# The functions that user code calls, like `add` and `sin`, are just wrappers\n# around calls to `bind`. These wrappers let us control how arguments are passed\n# to `bind`, and in particular we follow a handy internal convention: when we\n# call `bind`, we pass values representing array data as positional arguments,\n# and we pass metadata like the `axis` argument to `sum_p` via keyword. This\n# calling convention simplifies some core logic (since e.g. instances of the\n# `Tracer` class to be defined below can only occur in positional arguments to\n# `bind`). The wrappers can also provide docstrings!\n#\n# We represent active interpreters as a stack. The stack is just a simple\n# `list`, and each element is a container with an integer level (corresponding\n# to the element's height in the stack), an interpreter type (which we'll call a\n# `trace_type`), and an optional field for any global data the interpreter\n# needs. We call each element a `MainTrace`, though maybe \"Interpreter\" would be\n# more descriptive.\n\n# +\nfrom contextlib import contextmanager\nfrom typing import Type, List, Tuple, Sequence, Optional, Any\n\nclass MainTrace(NamedTuple):\n level: int\n trace_type: Type['Trace']\n global_data: Optional[Any]\n\ntrace_stack: List[MainTrace] = []\ndynamic_trace: Optional[MainTrace] = None # to be employed in Part 3\n\n@contextmanager\ndef new_main(trace_type: Type['Trace'], global_data=None):\n level = len(trace_stack)\n main = MainTrace(level, trace_type, global_data)\n trace_stack.append(main)\n\n try:\n yield main\n finally:\n trace_stack.pop()\n# -\n\n# When we're about to apply a transformation, we'll push another interpreter\n# onto the stack using `new_main`. Then, as we apply primitives in the function,\n# we can think of the `bind` first being interpreted by the trace at the top of\n# the stack (i.e. with the highest level). If that first interpreter itself\n# binds other primitives in its interpretation rule for the primitive, like how\n# the JVP rule of `sin_p` might bind `cos_p` and `mul_p`, then those `bind`\n# calls will be handled by the interpreter at the next level down.\n#\n# What goes at the bottom of the interpreter stack? At the bottom, we know all\n# the transformation interpreters are finished, and we just want to do standard\n# evaluation. So at the bottom we'll put an evaluation interpreter.\n#\n# Let's sketch out the interface for interpreters, which is based on the `Trace`\n# and `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps\n# carrying some extra context data used by the interpreter. A `Trace` handles\n# boxing up values into `Tracers` and also handles primitive application.\n\nclass Trace:\n main: MainTrace\n\n def __init__(self, main: MainTrace) -> None:\n self.main = main\n\n def pure(self, val): assert False # must override\n def lift(self, val): assert False # must override\n\n def process_primitive(self, primitive, tracers, params):\n assert False # must override\n\n# The first two methods are about boxing up values in `Tracer`s, which are the\n# objects that flow through the Python programs we transform. The last method is\n# the callback we'll use to interpret primitive application.\n#\n# The `Trace` itself doesn't contain any data, other than a reference to its\n# corresponding `MainTrace` instance. In fact, multiple instances of a `Trace`\n# might be created and discarded during an application of a transformation,\n# whereas only a single `MainTrace` instance is created per application of a\n# transformation.\n#\n# As for `Tracer`s themselves, each one carries an abstract value (and forwards\n# infix operators to it), and the rest is up to the transformation. (The\n# relationship between `Tracer`s and `AbstractValue`s is that there's one\n# `Tracer` per transformation, and at least one `AbstractValue` per base type,\n# like arrays.)\n\n# +\nimport numpy as np\n\nclass Tracer:\n _trace: Trace\n\n __array_priority__ = 1000\n\n @property\n def aval(self):\n assert False # must override\n\n def full_lower(self):\n return self # default implementation\n\n def __neg__(self): return self.aval._neg(self)\n def __add__(self, other): return self.aval._add(self, other)\n def __radd__(self, other): return self.aval._radd(self, other)\n def __mul__(self, other): return self.aval._mul(self, other)\n def __rmul__(self, other): return self.aval._rmul(self, other)\n def __gt__(self, other): return self.aval._gt(self, other)\n def __lt__(self, other): return self.aval._lt(self, other)\n def __bool__(self): return self.aval._bool(self)\n def __nonzero__(self): return self.aval._nonzero(self)\n\n def __getattr__(self, name):\n try:\n return getattr(self.aval, name)\n except AttributeError:\n raise AttributeError(f\"{self.__class__.__name__} has no attribute {name}\")\n\ndef swap(f): return lambda x, y: f(y, x)\n\n# +\nclass ShapedArray:\n array_abstraction_level = 1\n shape: Tuple[int]\n dtype: np.dtype\n\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = dtype\n\n @property\n def ndim(self):\n return len(self.shape)\n\n _neg = staticmethod(neg)\n _add = staticmethod(add)\n _radd = staticmethod(swap(add))\n _mul = staticmethod(mul)\n _rmul = staticmethod(swap(mul))\n _gt = staticmethod(greater)\n _lt = staticmethod(less)\n\n @staticmethod\n def _bool(tracer):\n raise Exception(\"ShapedArray can't be unambiguously converted to bool\")\n\n @staticmethod\n def _nonzero(tracer):\n raise Exception(\"ShapedArray can't be unambiguously converted to bool\")\n\n def str_short(self):\n return f'{self.dtype.name}[{\",\".join(str(d) for d in self.shape)}]'\n\n def __hash__(self):\n return hash((self.shape, self.dtype))\n\n def __eq__(self, other):\n return (type(self) is type(other) and\n self.shape == other.shape and self.dtype == other.dtype)\n\n def __repr__(self):\n return f\"ShapedArray(shape={self.shape}, dtype={self.dtype})\"\n\nclass ConcreteArray(ShapedArray):\n array_abstraction_level = 2\n val: np.ndarray\n\n def __init__(self, val):\n self.val = val\n self.shape = val.shape\n self.dtype = val.dtype\n\n @staticmethod\n def _bool(tracer):\n return bool(tracer.aval.val)\n\n @staticmethod\n def _nonzero(tracer):\n return bool(tracer.aval.val)\n\ndef get_aval(x):\n if isinstance(x, Tracer):\n return x.aval\n elif type(x) in jax_types:\n return ConcreteArray(np.asarray(x))\n else:\n raise TypeError(x)\n\njax_types = {bool, int, float,\n np.bool_, np.int32, np.int64, np.float32, np.float64, np.ndarray}\n# -\n\n# Notice that we actually have two `AbstractValue`s for arrays, representing\n# different levels of abstraction. A `ShapedArray` represents the set of all\n# possible arrays with a given shape and dtype. A `ConcreteArray` represents a\n# singleton set consisting of a single array value.\n#\n# Now that we've set up the interpreter stack, the Trace/Tracer API for\n# interpreters, and abstract values, we can come back to implement `bind`:\n\ndef bind(prim, *args, **params):\n top_trace = find_top_trace(args)\n tracers = [full_raise(top_trace, arg) for arg in args]\n outs = top_trace.process_primitive(prim, tracers, params)\n return [full_lower(out) for out in outs]\n\n# The main action is that we call `find_top_trace` to figure out which\n# interpreter should handle this primitive application. We then call that top\n# trace's `process_primitive` so that the trace can apply its interpretation\n# rule. The calls to `full_raise` just ensure that the inputs are boxed in the\n# top trace's `Tracer` instances, and the call to `full_lower` is an optional\n# optimization so that we unbox values out of `Tracer`s as much as possible.\n\n# +\nimport operator as op\n\ndef find_top_trace(xs) -> Trace:\n top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)),\n default=trace_stack[0], key=op.attrgetter('level'))\n if dynamic_trace and dynamic_trace.level > top_main.level:\n top_main = dynamic_trace\n return top_main.trace_type(top_main)\n# -\n\n# In words, ignoring the `dynamic_trace` step until Part 3, `find_top_trace`\n# returns the highest-level interpreter associated with the `Tracer`s on its\n# inputs, and otherwise returns the interpreter at the bottom of the stack\n# (which is always an evaluation trace, at least for now). This is a deviation\n# from the description above, where we always start by running the interpreter\n# at the top of the stack and then work our way down, applying every interpreter\n# in the stack. Instead, we're only applying an interpreter when the input\n# arguments to a primitive bind are boxed in a `Tracer` corresponding to that\n# interpreter. This optimization lets us skip irrelevant transformations, but\n# bakes in an assumption that transformations mostly follow data dependence\n# (except for the special bottom-of-the-stack interpreter, which interprets\n# everything).\n#\n# An alternative would be to have every interpreter in the stack interpret every\n# operation. That's worth exploring! JAX is designed around data dependence in\n# large part because that's so natural for automatic differentiation, and JAX's\n# roots are in autodiff. But it may be over-fit.\n\n# +\ndef full_lower(val: Any):\n if isinstance(val, Tracer):\n return val.full_lower()\n else:\n return val\n\ndef full_raise(trace: Trace, val: Any) -> Tracer:\n if not isinstance(val, Tracer):\n assert type(val) in jax_types\n return trace.pure(val)\n level = trace.main.level\n if val._trace.main is trace.main:\n return val\n elif val._trace.main.level < level:\n return trace.lift(val)\n elif val._trace.main.level > level:\n raise Exception(f\"Can't lift level {val._trace.main.level} to {level}.\")\n else: # val._trace.level == level\n raise Exception(f\"Different traces at same level: {val._trace}, {trace}.\")\n# -\n\n# The logic in `full_raise` serves to box values into `Tracer`s for a particular\n# `Trace`, calling different methods on the `Trace` based on context:\n# `Trace.pure` is called on non-`Tracer` constants, and `Trace.lift` is called\n# for values that are already `Tracer`s from a lower-level interpreter. These\n# two methods could share the same implementation, but by distinguishing them in\n# the core logic we can provide more information to the `Trace` subclass.\n#\n# That's it for the JAX core! Now we can start adding interpreters.\n\n# ### Evaluation interpreter\n#\n# We'll start with the simplest interpreter: the evaluation interpreter that\n# will sit at the bottom of the interpreter stack.\n\n# +\nclass EvalTrace(Trace):\n pure = lift = lambda self, x: x # no boxing in Tracers needed\n\n def process_primitive(self, primitive, tracers, params):\n return impl_rules[primitive](*tracers, **params)\n\ntrace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack\n\n# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\nimpl_rules = {}\n\nimpl_rules[add_p] = lambda x, y: [np.add(x, y)]\nimpl_rules[mul_p] = lambda x, y: [np.multiply(x, y)]\nimpl_rules[neg_p] = lambda x: [np.negative(x)]\nimpl_rules[sin_p] = lambda x: [np.sin(x)]\nimpl_rules[cos_p] = lambda x: [np.cos(x)]\nimpl_rules[reduce_sum_p] = lambda x, *, axis: [np.sum(x, axis)]\nimpl_rules[greater_p] = lambda x, y: [np.greater(x, y)]\nimpl_rules[less_p] = lambda x, y: [np.less(x, y)]\nimpl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)]\n\ndef broadcast_impl(x, *, shape, axes):\n for axis in sorted(axes):\n x = np.expand_dims(x, axis)\n return [np.broadcast_to(x, shape)]\nimpl_rules[broadcast_p] = broadcast_impl\n# -\n\n# With this interpreter, we can evaluate user functions:\n\n# +\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\nprint(f(3.0))\n# -\n\n# Woo! Like going around in a big circle. But the point of this indirection is\n# that now we can add some real transformations.\n\n# ### Forward-mode autodiff with `jvp`\n#\n# First, a few helper functions:\n\n# +\ndef zeros_like(val):\n aval = get_aval(val)\n return np.zeros(aval.shape, aval.dtype)\n\ndef unzip2(pairs):\n lst1, lst2 = [], []\n for x1, x2 in pairs:\n lst1.append(x1)\n lst2.append(x2)\n return lst1, lst2\n\nmap_ = map\ndef map(f, *xs):\n return list(map_(f, *xs))\n\nzip_ = zip\ndef zip(*args):\n fst, *rest = args = map(list, args)\n n = len(fst)\n for arg in rest:\n assert len(arg) == n\n return list(zip_(*args))\n# -\n\n# The `Tracer` for forward-mode autodiff carries a primal-tangent pair. The\n# `Trace` applies JVP rules.\n\n# +\nclass JVPTracer(Tracer):\n def __init__(self, trace, primal, tangent):\n self._trace = trace\n self.primal = primal\n self.tangent = tangent\n\n @property\n def aval(self):\n return get_aval(self.primal)\n\nclass JVPTrace(Trace):\n pure = lift = lambda self, val: JVPTracer(self, val, zeros_like(val))\n\n def process_primitive(self, primitive, tracers, params):\n primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\n jvp_rule = jvp_rules[primitive]\n primal_outs, tangent_outs = jvp_rule(primals_in, tangents_in, **params)\n return [JVPTracer(self, x, t) for x, t in zip(primal_outs, tangent_outs)]\n\njvp_rules = {}\n# -\n\n# Notice both `lift` and `sublift` package a value into a `JVPTracer` with the\n# minimal amount of context, which is a zero tangent value.\n#\n# Let's add some JVP rules for primitives:\n\n# +\ndef add_jvp(primals, tangents):\n (x, y), (x_dot, y_dot) = primals, tangents\n return [x + y], [x_dot + y_dot]\njvp_rules[add_p] = add_jvp\n\ndef mul_jvp(primals, tangents):\n (x, y), (x_dot, y_dot) = primals, tangents\n return [x * y], [x_dot * y + x * y_dot]\njvp_rules[mul_p] = mul_jvp\n\ndef sin_jvp(primals, tangents):\n (x,), (x_dot,) = primals, tangents\n return [sin(x)], [cos(x) * x_dot]\njvp_rules[sin_p] = sin_jvp\n\ndef cos_jvp(primals, tangents):\n (x,), (x_dot,) = primals, tangents\n return [cos(x)], [-sin(x) * x_dot]\njvp_rules[cos_p] = cos_jvp\n\ndef neg_jvp(primals, tangents):\n (x,), (x_dot,) = primals, tangents\n return [neg(x)], [neg(x_dot)]\njvp_rules[neg_p] = neg_jvp\n\ndef reduce_sum_jvp(primals, tangents, *, axis):\n (x,), (x_dot,) = primals, tangents\n return [reduce_sum(x, axis)], [reduce_sum(x_dot, axis)]\njvp_rules[reduce_sum_p] = reduce_sum_jvp\n\ndef greater_jvp(primals, tangents):\n (x, y), _ = primals, tangents\n out_primal = greater(x, y)\n return [out_primal], [zeros_like(out_primal)]\njvp_rules[greater_p] = greater_jvp\n\ndef less_jvp(primals, tangents):\n (x, y), _ = primals, tangents\n out_primal = less(x, y)\n return [out_primal], [zeros_like(out_primal)]\njvp_rules[less_p] = less_jvp\n# -\n\n# Finally, we add a transformation API to kick off the trace:\n\ndef jvp_v1(f, primals, tangents):\n with new_main(JVPTrace) as main:\n trace = JVPTrace(main)\n tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)]\n out = f(*tracers_in)\n tracer_out = full_raise(trace, out)\n primal_out, tangent_out = tracer_out.primal, tracer_out.tangent\n return primal_out, tangent_out\n\n# And with that, we can differentiate!\n\nx = 3.0\ny, sin_deriv_at_3 = jvp_v1(sin, (x,), (1.0,))\nprint(sin_deriv_at_3)\nprint(cos(3.0))\n\n# +\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\nx, xdot = 3., 1.\ny, ydot = jvp_v1(f, (x,), (xdot,))\nprint(y)\nprint(ydot)\n\n# +\ndef deriv(f):\n return lambda x: jvp_v1(f, (x,), (1.,))[1]\n\nprint(deriv(sin)(3.))\nprint(deriv(deriv(sin))(3.))\nprint(deriv(deriv(deriv(sin)))(3.))\nprint(deriv(deriv(deriv(deriv(sin))))(3.))\n\n# +\ndef f(x):\n if x > 0.: # Python control flow\n return 2. * x\n else:\n return x\n\nprint(deriv(f)(3.))\nprint(deriv(f)(-3.))\n# -\n\n# ## Pytrees and flattening user functions' inputs and outputs\n\n# A limitation with `jvp_v1` is that it assumes the user function accepts arrays\n# as positional arguments and produces a single array as output. What if it\n# produced a list as output? Or accepted nested containers as inputs? It would\n# be a pain to deal with all the possible containers in inputs and outputs at\n# every layer of the stack. Instead, we can wrap the user function so that the\n# wrapped version accepts arrays as inputs and returns a flat list of arrays as\n# output. The wrapper just needs to unflatten its input, call the user function,\n# and flatten the output.\n#\n# Here's how we'd like to write `jvp`, assuming the user always gives us\n# functions that take arrays as inputs and produces a flat list of arrays as\n# outputs:\n\ndef jvp_flat(f, primals, tangents):\n with new_main(JVPTrace) as main:\n trace = JVPTrace(main)\n tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)]\n outs = f(*tracers_in)\n tracers_out = [full_raise(trace, out) for out in outs]\n primals_out, tangents_out = unzip2((t.primal, t.tangent) for t in tracers_out)\n return primals_out, tangents_out\n\n# To support user functions that have arbitrary containers in the inputs and\n# outputs, here's how we'd write the user-facing `jvp` wrapper:\n\ndef jvp(f, primals, tangents):\n primals_flat, in_tree = tree_flatten(primals)\n tangents_flat, in_tree2 = tree_flatten(tangents)\n if in_tree != in_tree2: raise TypeError\n f, out_tree = flatten_fun(f, in_tree)\n primals_out_flat, tangents_out_flat = jvp_flat(f, primals_flat, tangents_flat)\n primals_out = tree_unflatten(out_tree(), primals_out_flat)\n tangents_out = tree_unflatten(out_tree(), tangents_out_flat)\n return primals_out, tangents_out\n\n# Notice that we had to plumb the tree structure of the user function output\n# back to the caller of `flatten_fun`. That information isn't available until we\n# actually run the user function, so `flatten_fun` just returns a reference to a\n# mutable cell, represented as a thunk. These side-effects are safe because we\n# always run the user function exactly once. (This safe regime is the reason for\n# the \"linear\" name in `linear_util.py`, in the sense of [linear\n# types](https://en.wikipedia.org/wiki/Substructural_type_system).)\n#\n# All that remains is to write `tree_flatten`, `tree_unflatten`, and\n# `flatten_fun`.\n\n# + tags=[\"hide-input\"]\ndef flatten_fun(f, in_tree):\n store = Store()\n\n def flat_fun(*args_flat):\n pytree_args = tree_unflatten(in_tree, args_flat)\n out = f(*pytree_args)\n out_flat, out_tree = tree_flatten(out)\n store.set_value(out_tree)\n return out_flat\n\n return flat_fun, store\n\nclass Empty: pass\nempty = Empty()\n\nclass Store:\n val = empty\n\n def set_value(self, val):\n assert self.val is empty\n self.val = val\n\n def __call__(self):\n return self.val\n\n# + tags=[\"hide-input\"]\nimport itertools as it\nfrom typing import Callable, Type, Hashable, Dict, Iterable, Iterator\n\nclass NodeType(NamedTuple):\n name: str\n to_iterable: Callable\n from_iterable: Callable\n\ndef register_pytree_node(ty: Type, to_iter: Callable, from_iter: Callable\n ) -> None:\n node_types[ty] = NodeType(str(ty), to_iter, from_iter)\n\nnode_types: Dict[Type, NodeType] = {}\nregister_pytree_node(tuple, lambda t: (None, t), lambda _, xs: tuple(xs))\nregister_pytree_node(list, lambda l: (None, l), lambda _, xs: list(xs))\nregister_pytree_node(dict,\n lambda d: map(tuple, unzip2(sorted(d.items()))),\n lambda keys, vals: dict(zip(keys, vals)))\n\nclass PyTreeDef(NamedTuple):\n node_type: NodeType\n node_metadata: Hashable\n child_treedefs: Tuple['PyTreeDef']\n\nclass Leaf: pass\nleaf = Leaf()\n\ndef tree_flatten(x: Any) -> Tuple[List[Any], PyTreeDef]:\n children_iter, treedef = _tree_flatten(x)\n return list(children_iter), treedef\n\ndef _tree_flatten(x: Any) -> Tuple[Iterable, PyTreeDef]:\n node_type = node_types.get(type(x))\n if node_type:\n node_metadata, children = node_type.to_iterable(x)\n children_flat, child_trees = unzip2(map(_tree_flatten, children))\n flattened = it.chain.from_iterable(children_flat)\n return flattened, PyTreeDef(node_type, node_metadata, tuple(child_trees))\n else:\n return [x], leaf\n\ndef tree_unflatten(treedef: PyTreeDef, xs: List[Any]) -> Any:\n return _tree_unflatten(treedef, iter(xs))\n\ndef _tree_unflatten(treedef: PyTreeDef, xs: Iterator) -> Any:\n if treedef is leaf:\n return next(xs)\n else:\n children = (_tree_unflatten(t, xs) for t in treedef.child_treedefs)\n return treedef.node_type.from_iterable(treedef.node_metadata, children)\n# -\n\n# With this pytree-handling `jvp` implementation, we can now handle arbitrary\n# input and output containers. That'll come in handy with future transformations\n# too!\n\n# +\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return {'hi': z, 'there': [x, y]}\n\nx, xdot = 3., 1.\ny, ydot = jvp(f, (x,), (xdot,))\nprint(y)\nprint(ydot)\n# -\n\n# ### Vectorized batching with `vmap`\n#\n# First, a couple helper functions, one for producing mapped abstract values\n# from unmapped ones (by removing an axis), and one for moving batch dimensions\n# around:\n\n# +\ndef mapped_aval(batch_dim, aval):\n shape = list(aval.shape)\n del shape[batch_dim]\n return ShapedArray(tuple(shape), aval.dtype)\n\ndef move_batch_axis(axis_size, src, dst, x):\n if src is not_mapped:\n target_shape = list(np.shape(x))\n target_shape.insert(dst, axis_size)\n return broadcast(x, target_shape, [dst])\n elif src == dst:\n return x\n else:\n return moveaxis(x, src, dst)\n\ndef moveaxis(x, src: int, dst: int):\n perm = [i for i in range(np.ndim(x)) if i != src]\n perm.insert(dst, src)\n return transpose(x, perm)\n# -\n\n# The `Tracer` for vectorized batching carries a batched value and an optional\n# integer indicating which axis (if any) is the batch axis.\n\n# +\nfrom typing import Union\n\nclass NotMapped: pass\nnot_mapped = NotMapped()\n\nBatchAxis = Union[NotMapped, int]\n\nclass BatchTracer(Tracer):\n def __init__(self, trace, val, batch_dim: BatchAxis):\n self._trace = trace\n self.val = val\n self.batch_dim = batch_dim\n\n @property\n def aval(self):\n if self.batch_dim is not_mapped:\n return get_aval(self.val)\n else:\n return mapped_aval(self.batch_dim, get_aval(self.val))\n\n def full_lower(self):\n if self.batch_dim is not_mapped:\n return full_lower(self.val)\n else:\n return self\n\nclass BatchTrace(Trace):\n pure = lift = lambda self, val: BatchTracer(self, val, not_mapped)\n\n def process_primitive(self, primitive, tracers, params):\n vals_in, bdims_in = unzip2((t.val, t.batch_dim) for t in tracers)\n vmap_rule = vmap_rules[primitive]\n val_outs, bdim_outs = vmap_rule(self.axis_size, vals_in, bdims_in, **params)\n return [BatchTracer(self, x, bd) for x, bd in zip(val_outs, bdim_outs)]\n\n @property\n def axis_size(self):\n return self.main.global_data\n\nvmap_rules = {}\n# -\n\n# Here we've implemented the optional `Tracer.full_lower` method, which lets us\n# peel off a batching tracer if it's not needed because it doesn't represent a\n# batched value.\n#\n# For `BatchTrace`, analogous to `JVPTrace`, the methods `pure` and `lift` just\n# box a value in a `BatchTracer` with the minimal amount of context, which in\n# this case is a `batch_dim` taking the sentinel value `not_mapped`. Notice we\n# use the `MainTrace`'s interpreter-global data field to store the batch axis\n# size.\n#\n# Next we can define batching interpreter rules for each primitive:\n\n# +\nfrom functools import partial\n\ndef binop_batching_rule(op, axis_size, vals_in, dims_in):\n (x, y), (x_bdim, y_bdim) = vals_in, dims_in\n if x_bdim != y_bdim:\n if x_bdim is not_mapped:\n x = move_batch_axis(axis_size, x_bdim, y_bdim, x)\n x_bdim = y_bdim\n else:\n y = move_batch_axis(axis_size, y_bdim, x_bdim, y)\n return [op(x, y)], [x_bdim]\nvmap_rules[add_p] = partial(binop_batching_rule, add)\nvmap_rules[mul_p] = partial(binop_batching_rule, mul)\n\ndef vectorized_unop_batching_rule(op, axis_size, vals_in, dims_in):\n (x,), (x_bdim,) = vals_in, dims_in\n return [op(x)], [x_bdim]\nvmap_rules[sin_p] = partial(vectorized_unop_batching_rule, sin)\nvmap_rules[cos_p] = partial(vectorized_unop_batching_rule, cos)\nvmap_rules[neg_p] = partial(vectorized_unop_batching_rule, neg)\n\ndef reduce_sum_batching_rule(axis_size, vals_in, dims_in, *, axis):\n (x,), (x_bdim,) = vals_in, dims_in\n new_axis = axis + (x_bdim <= axis)\n out_bdim = x_bdim - (new_axis < x_bdim)\n return [reduce_sum(x, new_axis)], [out_bdim]\nvmap_rules[reduce_sum_p] = reduce_sum_batching_rule\n# -\n\n# Finally, we add a transformation API to kick off the trace:\n\n# +\ndef vmap_flat(f, in_axes, *args):\n axis_size, = {x.shape[ax] for x, ax in zip(args, in_axes)\n if ax is not not_mapped}\n with new_main(BatchTrace, axis_size) as main:\n trace = BatchTrace(main)\n tracers_in = [BatchTracer(trace, x, ax) if ax is not None else x\n for x, ax in zip(args, in_axes)]\n outs = f(*tracers_in)\n tracers_out = [full_raise(trace, out) for out in outs]\n vals_out, bdims_out = unzip2((t.val, t.batch_dim) for t in tracers_out)\n outs_transposed = [move_batch_axis(axis_size, bdim, 0, val_out)\n for val_out, bdim in zip(vals_out, bdims_out)]\n return outs_transposed\n\ndef vmap(f, in_axes):\n def batched_f(*args):\n args_flat, in_tree = tree_flatten(args)\n in_axes_flat, in_tree2 = tree_flatten(in_axes)\n if in_tree != in_tree2: raise TypeError\n f_flat, out_tree = flatten_fun(f, in_tree)\n outs_flat = vmap_flat(f_flat, in_axes_flat, *args_flat)\n return tree_unflatten(out_tree(), outs_flat)\n return batched_f\n\n# +\ndef add_one_to_a_scalar(scalar):\n assert np.ndim(scalar) == 0\n return 1 + scalar\n\nvector_in = np.arange(3.)\nvector_out = vmap(add_one_to_a_scalar, (0,))(vector_in)\n\nprint(vector_in)\nprint(vector_out)\n\n# +\ndef jacfwd(f, x):\n pushfwd = lambda v: jvp(f, (x,), (v,))[1]\n vecs_in = np.eye(np.size(x)).reshape(np.shape(x) * 2)\n return vmap(pushfwd, (0,))(vecs_in)\n\ndef f(x):\n return sin(x)\n\njacfwd(f, np.arange(3.))\n# -\n\n# That's it for `jvp` and `vmap`!\n\n\n# ## Part 2: Jaxprs\n#\n# The next transformations on the horizon are `jit` for just-in-time\n# compilation and `vjp` for reverse-mode autodiff. (`grad` is just a small\n# wrapper around `vjp`.) Whereas `jvp` and `vmap` only needed each `Tracer` to\n# carry a little bit of extra context, for both `jit` and `vjp` we need much\n# richer context: we need to represent _programs_. That is, we need jaxprs!\n#\n# Jaxprs are JAX's internal intermediate representation of programs. They are\n# explicitly typed, functional, first-order, and in ANF form. We need a\n# program representation for `jit` because the purpose of `jit` is to stage\n# computation out of Python. For any computation we want to stage out, we need\n# to be able to represent it as data, and build it up as we trace a Python\n# function. Similarly, `vjp` needs a way to represent the computation for the\n# backward pass of reverse-mode autodiff. We use the same jaxpr program\n# representation for both needs.\n#\n# (Building a program representation is the most\n# [free](https://en.wikipedia.org/wiki/Free_object) kind of\n# trace-transformation, and so except for issues around handling native Python\n# control flow, any transformation could be implemented by first tracing to a\n# jaxpr and then interpreting the jaxpr.)\n\n# ### Jaxpr data strutures\n#\n# The jaxpr term syntax is roughly:\n#\n# ```\n# jaxpr ::=\n# { lambda <binder> , ... .\n# let <eqn>\n# ...\n# in ( <atom> , ... ) }\n#\n# binder ::= <var>:<array_type>\n# var ::= a | b | c | ...\n# atom ::= <var> | <literal>\n# literal ::= <int32> | <int64> | <float32> | <float64>\n#\n# eqn ::= <binder> , ... = <primitive> [ <params> ] <atom> , ...\n# ```\n#\n# The syntax of types is:\n#\n# ```\n# jaxpr_type ::= [ <array_type> , ... ] -> [ <array_type> , ... ]\n# array_type ::= <dtype>[<shape>]\n# dtype ::= f32 | f64 | i32 | i64\n# shape ::= <int> , ...\n# ```\n#\n# How do we represent these as Python data structures? We reuse ShapedArrays to\n# represent types, and we can represent the term syntax with a few Python\n# structs:\n\n# +\nfrom typing import Set\n\nclass Var:\n aval: ShapedArray\n def __init__(self, aval): self.aval = aval\n\nclass Lit:\n val: Any\n aval: ShapedArray\n\n def __init__(self, val):\n self.aval = aval = raise_to_shaped(get_aval(val))\n self.val = np.array(val, aval.dtype)\n\nAtom = Union[Var, Lit]\n\nclass JaxprEqn(NamedTuple):\n primitive: Primitive\n inputs: List[Atom]\n params: Dict[str, Any]\n out_binders: List[Var]\n\nclass Jaxpr(NamedTuple):\n in_binders: List[Var]\n eqns: List[JaxprEqn]\n outs: List[Atom]\n\n def __hash__(self): return id(self)\n __eq__ = op.is_\n\ndef raise_to_shaped(aval):\n return ShapedArray(aval.shape, aval.dtype)\n# -\n\n# Type-checking a jaxpr involves checking that there are no unbound variables,\n# that variables are only bound once, and that for each equation the type of\n# the primitive application matches the type of the output binders.\n\n\n# +\nclass JaxprType(NamedTuple):\n in_types: List[ShapedArray]\n out_types: List[ShapedArray]\n\n def __repr__(self):\n in_types = ', '.join(aval.str_short() for aval in self.in_types)\n out_types = ', '.join(aval.str_short() for aval in self.out_types)\n return f'({in_types}) -> ({out_types})'\n\ndef typecheck_jaxpr(jaxpr: Jaxpr) -> JaxprType:\n env: Set[Var] = set()\n\n for v in jaxpr.in_binders:\n if v in env: raise TypeError\n env.add(v)\n\n for eqn in jaxpr.eqns:\n in_types = [typecheck_atom(env, x) for x in eqn.inputs]\n out_types = abstract_eval_rules[eqn.primitive](*in_types, **eqn.params)\n for out_binder, out_type in zip(eqn.out_binders, out_types):\n if not out_type == out_binder.aval: raise TypeError\n for out_binder in eqn.out_binders:\n if out_binder in env: raise TypeError\n env.add(out_binder)\n\n in_types = [v.aval for v in jaxpr.in_binders]\n out_types = [typecheck_atom(env, x) for x in jaxpr.outs]\n return JaxprType(in_types, out_types)\n\ndef typecheck_atom(env: Set[Var], x: Atom) -> ShapedArray:\n if isinstance(x, Var):\n if x not in env: raise TypeError(\"unbound variable\")\n return x.aval\n elif isinstance(x, Lit):\n return raise_to_shaped(get_aval(x.val))\n else:\n assert False\n# -\n\n# We can apply the function represented by a jaxpr to arguments with a simple\n# interpreter.\n\n# +\ndef eval_jaxpr(jaxpr: Jaxpr, args: List[Any]) -> List[Any]:\n env: Dict[Var, Any] = {}\n\n def read(x: Atom) -> Any:\n return env[x] if type(x) is Var else x.val\n\n def write(v: Var, val: Any) -> None:\n assert v not in env # single-assignment\n env[v] = val\n\n map(write, jaxpr.in_binders, args)\n for eqn in jaxpr.eqns:\n in_vals = map(read, eqn.inputs)\n outs = bind(eqn.primitive, *in_vals, **eqn.params)\n map(write, eqn.out_binders, outs)\n return map(read, jaxpr.outs)\n\ndef jaxpr_as_fun(jaxpr: Jaxpr):\n return lambda *args: eval_jaxpr(jaxpr, args)\n# -\n\n# By using `bind` in the interpreter, this interpreter itself is traceable.\n\n# ### Building jaxprs with tracing\n#\n# Now that we have jaxprs as a data structure, we need ways to produce these\n# from tracing Python code. In general there are two variants of how we trace to\n# a jaxpr; `jit` uses one and `vjp` uses the other. We'll start with the one\n# used by `jit`, which is also used by control flow primitives like `lax.cond`,\n# `lax.while_loop`, and `lax.scan`.\n\n# +\ndef split_list(lst: List[Any], n: int) -> Tuple[List[Any], List[Any]]:\n assert 0 <= n <= len(lst)\n return lst[:n], lst[n:]\n\ndef partition_list(bs: List[bool], l: List[Any]) -> Tuple[List[Any], List[Any]]:\n assert len(bs) == len(l)\n lists = lst1, lst2 = [], []\n for b, x in zip(bs, l):\n lists[b].append(x)\n return lst1, lst2\n\n# +\n# NB: the analogous class in JAX is called 'DynamicJaxprTracer'\nclass JaxprTracer(Tracer):\n __slots__ = ['aval']\n aval: ShapedArray\n\n def __init__(self, trace, aval):\n self._trace = trace\n self.aval = aval\n\n# NB: the analogous class in JAX is called 'DynamicJaxprTrace'\nclass JaxprTrace(Trace):\n def new_arg(self, aval: ShapedArray) -> JaxprTracer:\n aval = raise_to_shaped(aval)\n tracer = self.builder.new_tracer(self, aval)\n self.builder.tracer_to_var[id(tracer)] = Var(aval)\n return tracer\n\n def get_or_make_const_tracer(self, val: Any) -> JaxprTracer:\n tracer = self.builder.const_tracers.get(id(val))\n if tracer is None:\n tracer = self.builder.new_tracer(self, raise_to_shaped(get_aval(val)))\n self.builder.add_const(tracer, val)\n return tracer\n pure = lift = get_or_make_const_tracer\n\n def process_primitive(self, primitive, tracers, params):\n avals_in = [t.aval for t in tracers]\n avals_out = abstract_eval_rules[primitive](*avals_in, **params)\n out_tracers = [self.builder.new_tracer(self, a) for a in avals_out]\n inputs = [self.builder.getvar(t) for t in tracers]\n outvars = [self.builder.add_var(t) for t in out_tracers]\n self.builder.add_eqn(JaxprEqn(primitive, inputs, params, outvars))\n return out_tracers\n\n @property\n def builder(self):\n return self.main.global_data\n\n# NB: in JAX, we instead attach abstract eval rules to Primitive instances\nabstract_eval_rules = {}\n# -\n\n# Notice that we keep as interpreter-global data a builder object, which keeps\n# track of variables, constants, and eqns as we build up the jaxpr.\n\nclass JaxprBuilder:\n eqns: List[JaxprEqn]\n tracer_to_var: Dict[int, Var]\n const_tracers: Dict[int, JaxprTracer]\n constvals: Dict[Var, Any]\n tracers: List[JaxprTracer]\n\n def __init__(self):\n self.eqns = []\n self.tracer_to_var = {}\n self.const_tracers = {}\n self.constvals = {}\n self.tracers = []\n\n def new_tracer(self, trace: JaxprTrace, aval: ShapedArray) -> JaxprTracer:\n tracer = JaxprTracer(trace, aval)\n self.tracers.append(tracer)\n return tracer\n\n def add_eqn(self, eqn: JaxprEqn) -> None:\n self.eqns.append(eqn)\n\n def add_var(self, tracer: JaxprTracer) -> Var:\n assert id(tracer) not in self.tracer_to_var\n var = self.tracer_to_var[id(tracer)] = Var(tracer.aval)\n return var\n\n def getvar(self, tracer: JaxprTracer) -> Var:\n var = self.tracer_to_var.get(id(tracer))\n assert var is not None\n return var\n\n def add_const(self, tracer: JaxprTracer, val: Any) -> Var:\n var = self.add_var(tracer)\n self.const_tracers[id(val)] = tracer\n self.constvals[var] = val\n return var\n\n def build(self, in_tracers: List[JaxprTracer], out_tracers: List[JaxprTracer]\n ) -> Tuple[Jaxpr, List[Any]]:\n constvars, constvals = unzip2(self.constvals.items())\n t2v = lambda t: self.tracer_to_var[id(t)]\n in_binders = constvars + [t2v(t) for t in in_tracers]\n out_vars = [t2v(t) for t in out_tracers]\n jaxpr = Jaxpr(in_binders, self.eqns, out_vars)\n typecheck_jaxpr(jaxpr)\n jaxpr, constvals = _inline_literals(jaxpr, constvals)\n return jaxpr, constvals\n\ndef _inline_literals(jaxpr: Jaxpr, consts: List[Any]) -> Tuple[Jaxpr, List[Any]]:\n const_binders, other_binders = split_list(jaxpr.in_binders, len(consts))\n scalars = [type(x) in jax_types and not get_aval(x).shape for x in consts]\n new_const_binders, lit_binders = partition_list(scalars, const_binders)\n new_consts, lit_vals = partition_list(scalars, consts)\n literals = dict(zip(lit_binders, map(Lit, lit_vals)))\n new_eqns = [JaxprEqn(eqn.primitive, [literals.get(x, x) for x in eqn.inputs],\n eqn.params, eqn.out_binders) for eqn in jaxpr.eqns]\n new_outs = [literals.get(x, x) for x in jaxpr.outs]\n new_jaxpr = Jaxpr(new_const_binders + other_binders, new_eqns, new_outs)\n typecheck_jaxpr(new_jaxpr)\n return new_jaxpr, new_consts\n\n# The rules we need for `JaxprTrace.process_primitive` are essentially typing\n# rules for primitive applications: given the primitive, its parameters, and\n# types for the inputs, the rule must produce a type for the output, which is\n# then packaged with the output `JaxprTracer`. We can use abstract evaluation\n# rules for this same purpose, even though they can be more general (since\n# abstract evaluation rules must accept ConcreteArray inputs, and since they\n# need only return an upper bound on the set of possible outputs, they can\n# produce ConcreteArray outputs as well). We'll reuse these abstract evaluation\n# rules for the other jaxpr-producing trace machinery, where the potential extra\n# generality is useful.\n\n# +\ndef binop_abstract_eval(x: ShapedArray, y: ShapedArray) -> List[ShapedArray]:\n if not isinstance(x, ShapedArray) or not isinstance(y, ShapedArray):\n raise TypeError\n if raise_to_shaped(x) != raise_to_shaped(y): raise TypeError\n return [ShapedArray(x.shape, x.dtype)]\n\nabstract_eval_rules[add_p] = binop_abstract_eval\nabstract_eval_rules[mul_p] = binop_abstract_eval\n\ndef compare_abstract_eval(x: ShapedArray, y: ShapedArray) -> List[ShapedArray]:\n if not isinstance(x, ShapedArray) or not isinstance(y, ShapedArray):\n raise TypeError\n if x.shape != y.shape: raise TypeError\n return [ShapedArray(x.shape, np.dtype('bool'))]\nabstract_eval_rules[greater_p] = compare_abstract_eval\nabstract_eval_rules[less_p] = compare_abstract_eval\n\ndef vectorized_unop_abstract_eval(x: ShapedArray) -> List[ShapedArray]:\n return [ShapedArray(x.shape, x.dtype)]\n\nabstract_eval_rules[sin_p] = vectorized_unop_abstract_eval\nabstract_eval_rules[cos_p] = vectorized_unop_abstract_eval\nabstract_eval_rules[neg_p] = vectorized_unop_abstract_eval\n\ndef reduce_sum_abstract_eval(x: ShapedArray, *, axis: int) -> List[ShapedArray]:\n new_shape = [d for i, d in enumerate(x.shape) if i != axis]\n return [ShapedArray(tuple(new_shape), x.dtype)]\nabstract_eval_rules[reduce_sum_p] = reduce_sum_abstract_eval\n\ndef broadcast_abstract_eval(x: ShapedArray, *, shape: Sequence[int],\n axes: Sequence[int]) -> List[ShapedArray]:\n return [ShapedArray(tuple(shape), x.dtype)]\nabstract_eval_rules[broadcast_p] = broadcast_abstract_eval\n# -\n\n# To check our implementation of jaxprs, we can add a `make_jaxpr`\n# transformation and a pretty-printer:\n\n# +\nfrom functools import lru_cache\n\n@lru_cache() # ShapedArrays are hashable\ndef make_jaxpr_v1(f, *avals_in):\n avals_in, in_tree = tree_flatten(avals_in)\n f, out_tree = flatten_fun(f, in_tree)\n\n builder = JaxprBuilder()\n with new_main(JaxprTrace, builder) as main:\n trace = JaxprTrace(main)\n tracers_in = [trace.new_arg(aval) for aval in avals_in]\n outs = f(*tracers_in)\n tracers_out = [full_raise(trace, out) for out in outs]\n jaxpr, consts = builder.build(tracers_in, tracers_out)\n return jaxpr, consts, out_tree()\n\n# + tags=[\"hide-input\"]\nfrom collections import defaultdict\nimport string\n\nclass PPrint:\n lines: List[Tuple[int, str]]\n\n def __init__(self, lines):\n self.lines = lines\n\n def indent(self, indent: int) -> 'PPrint':\n return PPrint([(indent + orig_indent, s) for orig_indent, s in self.lines])\n\n def __add__(self, rhs: 'PPrint') -> 'PPrint':\n return PPrint(self.lines + rhs.lines)\n\n def __rshift__(self, rhs: 'PPrint') -> 'PPrint':\n if not rhs.lines: return self\n if not self.lines: return rhs\n indent, s = self.lines[-1]\n indented_block = rhs.indent(indent + len(s))\n common_line = s + ' ' * rhs.lines[0][0] + rhs.lines[0][1]\n return PPrint(self.lines[:-1]\n + [(indent, common_line)]\n + indented_block.lines[1:])\n\n def __str__(self) -> str:\n return '\\n'.join(' ' * indent + s for indent, s in self.lines)\n\ndef pp(s: Any) -> PPrint:\n return PPrint([(0, line) for line in str(s).splitlines()])\n\ndef vcat(ps: List[PPrint]) -> PPrint:\n return sum(ps, pp(''))\n\ndef pp_jaxpr(jaxpr: Jaxpr):\n namegen = (''.join(s) for r in it.count(1)\n for s in it.permutations(string.ascii_lowercase, r))\n names = defaultdict(lambda: next(namegen))\n in_binders = ', '.join(var_str(names, x) for x in jaxpr.in_binders)\n eqns = vcat([pp_eqn(names, e) for e in jaxpr.eqns])\n outs = ', '.join(names[v] if isinstance(v, Var) else str(v.val)\n for v in jaxpr.outs)\n return (pp(f'{{ lambda {in_binders} .') +\n ((pp('let ') >> eqns) + pp(f'in ( {outs} ) }}')).indent(2))\n\ndef var_str(names: Dict[Var, str], v: Var) -> str:\n return f'{names[v]}:{v.aval.str_short()}'\n\ndef pp_eqn(names: Dict[Var, str], eqn: JaxprEqn) -> PPrint:\n lhs = pp(' '.join(var_str(names, v) for v in eqn.out_binders))\n rhs = (pp(eqn.primitive.name) >> pp_params(eqn.params) >>\n pp(' '.join(names[x] if isinstance(x, Var) else str(x.val)\n for x in eqn.inputs)))\n return lhs >> pp(' = ') >> rhs\n\ndef pp_params(params: Dict[str, Any]) -> PPrint:\n items = sorted(params.items())\n if items:\n return pp(' [ ') >> vcat([pp(f'{k}={v}') for k, v in items]) >> pp(' ] ')\n else:\n return pp(' ')\n\nJaxpr.__repr__ = lambda self: str(pp_jaxpr(self))\n# -\n\njaxpr, consts, _ = make_jaxpr_v1(lambda x: 2. * x, raise_to_shaped(get_aval(3.)))\nprint(jaxpr)\nprint(typecheck_jaxpr(jaxpr))\n\n# But there's a limitation here: because of how `find_top_trace` operates by\n# data dependence, `make_jaxpr_v1` can't stage out all the primitive operations\n# performed by the Python callable it's given. For example:\n\njaxpr, consts, _ = make_jaxpr_v1(lambda: mul(2., 2.))\nprint(jaxpr)\n\n# This is precisely the issue that\n# [omnistaging](https://github.com/google/jax/pull/3370) fixed.\n# We want to ensure that the `JaxprTrace` started by `make_jaxpr` is always\n# applied, regardless of whether any inputs to `bind` are boxed in corresponding\n# `JaxprTracer` instances. We can achieve this by employing the `dynamic_trace`\n# global defined in Part 1:\n\n# +\n@contextmanager\ndef new_dynamic(main: MainTrace):\n global dynamic_trace\n prev_dynamic_trace, dynamic_trace = dynamic_trace, main\n try:\n yield\n finally:\n dynamic_trace = prev_dynamic_trace\n\n@lru_cache()\ndef make_jaxpr(f: Callable, *avals_in: ShapedArray,\n ) -> Tuple[Jaxpr, List[Any], PyTreeDef]:\n avals_in, in_tree = tree_flatten(avals_in)\n f, out_tree = flatten_fun(f, in_tree)\n\n builder = JaxprBuilder()\n with new_main(JaxprTrace, builder) as main:\n with new_dynamic(main):\n trace = JaxprTrace(main)\n tracers_in = [trace.new_arg(aval) for aval in avals_in]\n outs = f(*tracers_in)\n tracers_out = [full_raise(trace, out) for out in outs]\n jaxpr, consts = builder.build(tracers_in, tracers_out)\n return jaxpr, consts, out_tree()\n\njaxpr, consts, _ = make_jaxpr(lambda: mul(2., 2.))\nprint(jaxpr)\n# -\n\n# Using `dynamic_trace` this way is conceptually the same as stashing the\n# current interpreter stack and starting a new one with the `JaxprTrace` at the\n# bottom. That is, no interpreters lower in the stack than the `dynamic_trace`\n# are applied (since `JaxprTrace.process_primitive` doesn't call `bind`), though\n# if the Python callable being traced to a jaxpr itself uses transformations\n# then those can be pushed onto the interpreter stack above the `JaxprTrace`.\n# But temporarily stashing the interpreter stack would break up the system\n# state. The `dynamic_trace` tag achieves the same goals while keeping the\n# system state simpler.\n\n# That's it for jaxprs! With jaxprs in hand, we can implement the remaining\n# major JAX features.\n\n\n# ## Part 3: `jit`, simplified\n#\n# While `jit` has a transformation-like API in that it accepts a Python callable\n# as an argument, under the hood it's really a higher-order primitive rather\n# than a transformation. A primitive is _higher-order_ when it's parameterized\n# by a function.\n\n# ### On-the-fly (\"final style\") and staged (\"initial style\") processing\n#\n# There are two options for how to handle higher-order primitives. Each requires\n# a different approach to tracing and engenders different tradeoffs:\n# 1. **On-the-fly processing, where `bind` takes a Python callable as an\n# argument.** We defer forming a jaxpr until as late as possible, namely\n# until we're running the final interpreter at the bottom of the interpreter\n# stack. That way we can swap a `JaxprTrace` in at the bottom of the\n# interpreter stack and thus stage out rather than execute all primitive\n# operations. With this approach, transformations in the stack get applied as\n# we execute the Python callable as usual. This approach can be very tricky\n# to implement, but it's as general as possible because it allows\n# higher-order primitives not to raise the abstraction level of their\n# arguments and thus allows data-dependent Python control flow. We refer to\n# this approach as using a \"final-style higher-order primitive\" employing the\n# discharge-at-tracing-time \"final-style transformations\" we've used so far.\n# 2. **Staged processing, where `bind` takes a jaxpr as an argument.** Before we\n# call `bind`, in the primitive wrapper we can just use `make_jaxpr` to form\n# a jaxpr up-front and be done with the Python callable entirely. In this\n# case, `make_jaxpr` puts its `JaxprTrace` at the top of the interpreter\n# stack, and no transformations lower in the stack, which might enter via\n# closed-over Tracers, are applied to the Python callable as we trace it.\n# (Transformations applied within the Python callable are applied as usual,\n# being added to the stack above the JaxprTrace.) Instead, the\n# transformations lower in the stack are later applied to the call primitive,\n# and the call primitive's rules must then transform the jaxpr itself.\n# Because we trace to a jaxpr up-front, this approach can't support\n# data-dependent Python control flow, but it is more straightforward to\n# implement. We refer to this kind of higher-order primitive as an\n# \"initial-style higher-order primitive\", and say that its jaxpr-processing\n# transformation rules are \"initial-style transformation rules.\"\n#\n# The latter approach fits for `jit` because we don't need to support\n# data-dependent Python control flow in the user-provided Python callable, as\n# the whole purpose of `jit` is to stage computation out of Python to be\n# executed by XLA. (In contrast, `custom_jvp` is a higher-order primitive in\n# which we want to support data-dependent Python control flow.)\n#\n# Historically, we started using the \"initial-style\" and \"final-style\"\n# terminology after reading the [typed tagless final\n# interpreters](http://okmij.org/ftp/tagless-final/index.html) paper, and\n# jokingly referring to JAX as an implementation of \"untyped tagful final\n# interpreters.\" We don't claim to carry over (or understand) any deep meaning\n# behind these terms; we loosely use \"initial style\" to mean \"build an AST and\n# then transform it\", and we use \"final style\" to mean \"transform as we trace.\"\n# But it's just imprecise yet sticky jargon.\n\n# With the initial-style approach, here's the user-facing `jit` wrapper:\n\n# +\ndef jit(f):\n def f_jitted(*args):\n avals_in = [raise_to_shaped(get_aval(x)) for x in args]\n jaxpr, consts, out_tree = make_jaxpr(f, *avals_in)\n outs = bind(xla_call_p, *consts, *args, jaxpr=jaxpr, num_consts=len(consts))\n return tree_unflatten(out_tree, outs)\n return f_jitted\n\nxla_call_p = Primitive('xla_call')\n# -\n\n# With any new primitive, we need to give it transformation rules, starting with\n# its evaluation rule. When we evaluate an application of the `xla_call`\n# primitive, we want to stage out out the computation to XLA. That involves\n# translating the jaxpr to an XLA HLO program, transferring the argument values\n# to the XLA device, executing the XLA program, and transferring back the\n# results. We'll cache the XLA HLO compilation so that for each `jit`ted\n# function it only needs to be performed once per argument shape and dtype\n# signature.\n#\n# First, some utilities.\n\nclass IDHashable:\n val: Any\n\n def __init__(self, val):\n self.val = val\n\n def __hash__(self) -> int:\n return id(self.val)\n\n def __eq__(self, other):\n return type(other) is IDHashable and id(self.val) == id(other.val)\n\n# Next, we'll define the evaluation rule for `xla_call`:\n\n# +\nfrom jax.lib import xla_bridge as xb\nfrom jax.lib import xla_client as xc\nxe = xc._xla\nxops = xc._xla.ops\n\ndef xla_call_impl(*args, jaxpr: Jaxpr, num_consts: int):\n consts, args = args[:num_consts], args[num_consts:]\n hashable_consts = tuple(map(IDHashable, consts))\n execute = xla_callable(IDHashable(jaxpr), hashable_consts)\n return execute(*args)\nimpl_rules[xla_call_p] = xla_call_impl\n\n@lru_cache()\ndef xla_callable(hashable_jaxpr: IDHashable, hashable_consts: Tuple[IDHashable]):\n jaxpr: Jaxpr = hashable_jaxpr.val\n typecheck_jaxpr(jaxpr)\n consts = [x.val for x in hashable_consts]\n in_avals = [v.aval for v in jaxpr.in_binders[len(consts):]]\n c = xb.make_computation_builder('xla_call')\n xla_consts = _xla_consts(c, consts)\n xla_params = _xla_params(c, in_avals)\n outs = jaxpr_subcomp(c, jaxpr, xla_consts + xla_params)\n out = xops.Tuple(c, outs)\n compiled = xb.get_backend(None).compile(c.build(out))\n return partial(execute_compiled, compiled, [v.aval for v in jaxpr.outs])\n\ndef _xla_consts(c: xe.XlaBuilder, consts: List[Any]) -> List[xe.XlaOp]:\n unique_consts = {id(cnst): cnst for cnst in consts}\n xla_consts = {\n id_: xops.ConstantLiteral(c, cnst) for id_, cnst in unique_consts.items()}\n return [xla_consts[id(cnst)] for cnst in consts]\n\ndef _xla_params(c: xe.XlaBuilder, avals_in: List[ShapedArray]) -> List[xe.XlaOp]:\n return [xb.parameter(c, i, _xla_shape(a)) for i, a in enumerate(avals_in)]\n\ndef _xla_shape(aval: ShapedArray) -> xe.Shape:\n return xc.Shape.array_shape(xc.dtype_to_etype(aval.dtype), aval.shape)\n# -\n\n# The main action is in `xla_callable`, which compiles a jaxpr into an XLA HLO\n# program using `jaxpr_subcomp`, then returns a callable which executes the\n# compiled program:\n\n# +\ndef jaxpr_subcomp(c: xe.XlaBuilder, jaxpr: Jaxpr, args: List[xe.XlaOp]\n ) -> xe.XlaOp:\n env: Dict[Var, xe.XlaOp] = {}\n\n def read(x: Atom) -> xe.XlaOp:\n return env[x] if type(x) is Var else xb.constant(c, x.val, False)\n\n def write(v: Var, val: xe.XlaOp) -> None:\n env[v] = val\n\n map(write, jaxpr.in_binders, args)\n for eqn in jaxpr.eqns:\n in_avals = [x.aval for x in eqn.inputs]\n in_vals = map(read, eqn.inputs)\n rule = xla_translations[eqn.primitive]\n out_vals = rule(c, in_avals, in_vals, **eqn.params)\n map(write, eqn.out_binders, out_vals)\n return map(read, jaxpr.outs)\n\ndef execute_compiled(compiled, out_avals, *args):\n input_bufs = [input_handlers[type(x)](x) for x in args]\n out_bufs = compiled.execute(input_bufs)\n return [handle_result(aval, buf) for aval, buf in zip(out_avals, out_bufs)]\n\ndefault_input_handler = xb.get_backend(None).buffer_from_pyval\ninput_handlers = {ty: default_input_handler for ty in\n [bool, int, float, np.ndarray, np.float64, np.float32]}\n\ndef handle_result(aval: ShapedArray, buf):\n del aval # Unused for now.\n return buf.to_py()\n\nxla_translations = {}\n# -\n\n# Notice that `jaxpr_subcomp` has the structure of a simple interpreter. That's\n# a common pattern: the way we process jaxprs is usually with an interpreter.\n# And as with any interpreter, we need an interpretation rule for each\n# primitive:\n\n# +\ndef direct_translation(op, c, in_avals, in_vals):\n del c, in_avals\n return [op(*in_vals)]\n\nxla_translations[add_p] = partial(direct_translation, xops.Add)\nxla_translations[mul_p] = partial(direct_translation, xops.Mul)\nxla_translations[neg_p] = partial(direct_translation, xops.Neg)\nxla_translations[sin_p] = partial(direct_translation, xops.Sin)\nxla_translations[cos_p] = partial(direct_translation, xops.Cos)\nxla_translations[greater_p] = partial(direct_translation, xops.Gt)\nxla_translations[less_p] = partial(direct_translation, xops.Lt)\n\ndef reduce_sum_translation(c, in_avals, in_vals, *, axis):\n (x_aval,), (x,) = in_avals, in_vals\n zero = xops.ConstantLiteral(c, np.array(0, x_aval.dtype))\n subc = xb.make_computation_builder('add')\n shape = _xla_shape(ShapedArray((), x_aval.dtype))\n xops.Add(xops.Parameter(subc, 0, shape), xops.Parameter(subc, 1, shape))\n return [xops.Reduce(c, [x], [zero], subc.build(), [axis])]\nxla_translations[reduce_sum_p] = reduce_sum_translation\n\ndef broadcast_translation(c, in_avals, in_vals, *, shape, axes):\n x, = in_vals\n dims_complement = [i for i in range(len(shape)) if i not in axes]\n return [xops.BroadcastInDim(x, shape, dims_complement)]\nxla_translations[broadcast_p] = broadcast_translation\n# -\n\n# With that, we can now use `jit` to stage out, compile, and execute programs\n# with XLA!\n\n@jit\ndef f(x, y):\n print('tracing!')\n return sin(x) * cos(y)\n\nz = f(3., 4.) # 'tracing!' prints the first time\nprint(z)\n\nz = f(4., 5.) # 'tracing!' doesn't print, compilation cache hit!\nprint(z)\n\n# +\n@jit\ndef f(x):\n return reduce_sum(x, axis=0)\n\nprint(f(np.array([1., 2., 3.])))\n\n# +\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\ndef deriv(f):\n return lambda x: jvp(f, (x,), (1.,))[1]\n\nprint( deriv(deriv(f))(3.))\nprint(jit(deriv(deriv(f)))(3.))\n# -\n\n# Instead of implementing `jit` to first trace to a jaxpr and then to lower the\n# jaxpr to XLA HLO, it might appear that we could have skipped the jaxpr step\n# and just lowered to HLO while tracing. That is, perhaps we could have instead\n# implemented `jit` with a `Trace` and `Tracer` that appended to the XLA HLO\n# graph incrementally on each primitive bind. That's correct for now, but won't\n# be possible when we introduce compiled SPMD computations because there we must\n# know the number of replicas needed before compiling the program.\n\n# We haven't yet defined any transformation rules for `xla_call_p` other than\n# its evaluation rule. That is, we can't yet do `vmap`-of-`jit` or\n# `jvp`-of-`jit` or even `jit`-of`-jit`. Instead `jit` has to be at the \"top\n# level.\" Let's fix that!\n\n# +\ndef xla_call_jvp_rule(primals, tangents, *, jaxpr, num_consts):\n del num_consts # Unused.\n new_jaxpr, new_consts = jvp_jaxpr(jaxpr)\n outs = bind(xla_call_p, *new_consts, *primals, *tangents, jaxpr=new_jaxpr,\n num_consts=len(new_consts))\n n = len(outs) // 2\n primals_out, tangents_out = outs[:n], outs[n:]\n return primals_out, tangents_out\njvp_rules[xla_call_p] = xla_call_jvp_rule\n\n@lru_cache()\ndef jvp_jaxpr(jaxpr: Jaxpr) -> Tuple[Jaxpr, List[Any]]:\n def jvp_traceable(*primals_and_tangents):\n n = len(primals_and_tangents) // 2\n primals, tangents = primals_and_tangents[:n], primals_and_tangents[n:]\n return jvp(jaxpr_as_fun(jaxpr), primals, tangents)\n\n in_avals = [v.aval for v in jaxpr.in_binders]\n new_jaxpr, new_consts, _ = make_jaxpr(jvp_traceable, *in_avals, *in_avals)\n return new_jaxpr, new_consts\n\n# +\ndef xla_call_vmap_rule(axis_size, vals_in, dims_in, *, jaxpr, num_consts):\n del num_consts # Unused.\n new_jaxpr, new_consts = vmap_jaxpr(jaxpr, axis_size, tuple(dims_in))\n outs = bind(xla_call_p, *new_consts, *vals_in, jaxpr=new_jaxpr,\n num_consts=len(new_consts))\n return outs, [0] * len(outs)\nvmap_rules[xla_call_p] = xla_call_vmap_rule\n\n@lru_cache()\ndef vmap_jaxpr(jaxpr: Jaxpr, axis_size: int, bdims_in: Tuple[BatchAxis, ...]\n ) -> Tuple[Jaxpr, List[Any]]:\n vmap_traceable = vmap(jaxpr_as_fun(jaxpr), tuple(bdims_in))\n in_avals = [unmapped_aval(axis_size, d, v.aval)\n for v, d in zip(jaxpr.in_binders, bdims_in)]\n new_jaxpr, new_consts, _ = make_jaxpr(vmap_traceable, *in_avals)\n return new_jaxpr, new_consts\n\ndef unmapped_aval(axis_size: int, batch_dim: BatchAxis, aval: ShapedArray\n ) -> ShapedArray:\n if batch_dim is not_mapped:\n return aval\n else:\n shape = list(aval.shape)\n shape.insert(batch_dim, axis_size)\n return ShapedArray(tuple(shape), aval.dtype)\n\n# +\ndef xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts):\n del num_consts # Unused.\n jaxpr_type = typecheck_jaxpr(jaxpr)\n if not all(t1 == t2 for t1, t2 in zip(jaxpr_type.in_types, in_types)):\n raise TypeError\n return jaxpr_type.out_types\nabstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule\n\ndef xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\n del num_consts # Only used at top-level.\n # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\n subc = xb.make_computation_builder('inner xla_call')\n xla_params = _xla_params(subc, in_avals)\n outs = jaxpr_subcomp(subc, jaxpr, xla_params)\n subc = subc.build(xops.Tuple(subc, outs))\n return destructure_tuple(c, xops.Call(c, subc, in_vals))\nxla_translations[xla_call_p] = xla_call_translation\n\ndef destructure_tuple(c, tup):\n num_elements = len(c.get_shape(tup).tuple_shapes())\n return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\n\n# +\n@jit\ndef f(x):\n print('tracing!')\n y = sin(x) * 2.\n z = - y + x\n return z\n\nx, xdot = 3., 1.\ny, ydot = jvp(f, (x,), (xdot,))\nprint(y)\nprint(ydot)\n# -\n\ny, ydot = jvp(f, (x,), (xdot,)) # 'tracing!' not printed\n\nys = vmap(f, (0,))(np.arange(3.))\nprint(ys)\n\n# One piece missing is device memory persistence for arrays. That is, we've\n# defined `handle_result` to transfer results back to CPU memory as NumPy\n# arrays, but it's often preferable to avoid transferring results just to\n# transfer them back for the next operation. We can do that by introducing a\n# `DeviceArray` class, which can wrap XLA buffers and otherwise duck-type\n# `numpy.ndarray`s:\n\n# +\ndef handle_result(aval: ShapedArray, buf): # noqa: F811\n return DeviceArray(aval, buf)\n\nclass DeviceArray:\n buf: Any\n aval: ShapedArray\n\n def __init__(self, aval, buf):\n self.aval = aval\n self.buf = buf\n\n dtype = property(lambda self: self.aval.dtype)\n shape = property(lambda self: self.aval.shape)\n ndim = property(lambda self: self.aval.ndim)\n\n def __array__(self): return self.buf.to_py()\n def __repr__(self): return repr(self.buf.to_py())\n def __str__(self): return str(self.buf.to_py())\n\n _neg = staticmethod(neg)\n _add = staticmethod(add)\n _radd = staticmethod(add)\n _mul = staticmethod(mul)\n _rmul = staticmethod(mul)\n _gt = staticmethod(greater)\n _lt = staticmethod(less)\ninput_handlers[DeviceArray] = lambda x: x.buf\n\njax_types.add(DeviceArray)\n\n# +\n@jit\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\nx, xdot = 3., 1.\ny, ydot = jvp(f, (x,), (xdot,))\nprint(y)\nprint(ydot)\n# -\n\n# ## Part 4: `linearize` and `vjp` (and `grad`!)\n#\n# The `linearize` and `vjp` autodiff functions are built on `jvp`, but involve\n# jaxprs as well. That's because both involve staging out, or delaying,\n# computation.\n\n# ### `linearize`\n#\n# In the case of `linearize`, we want to stage out the linear part of a `jvp`\n# computation. That is, if we have `jvp : (a -> b) -> (a, T a) -> (b, T b)`,\n# then we write `linearize : (a -> b) -> a -> (b, T a -o T b)`, using `T a` to\n# mean \"the tangent type of `a`\" and using the \"lollipop\" `-o` rather than the\n# arrow `->` to indicate a _linear_ function. We define the semantics of\n# `linearize` in terms of `jvp` too:\n# ```python\n# y, f_lin = linearize(f, x)\n# y_dot = f_lin(x_dot)\n# ```\n# gives the same result for `(y, y_dot)` as\n# ```\n# y, y_dot = jvp(f, (x,), (x_dot,))\n# ```\n# where the application of `f_lin` does not redo any of the linearization work.\n# We'll represent the delayed linear part `f_lin : T a -o T b` as a jaxpr.\n#\n# Tangentially, now that we have linear arrows `-o`, we can provide a slightly\n# more informative type for `jvp`:\n# ```\n# jvp : (a -> b) -> (UnrestrictedUse a, T a) -o (UnrestrictedUse b, T b)\n# ```\n# Here we're writing `UnrestrictedUse` just to indicate that we have a special\n# pair where the first element can be used in an unrestricted (nonlinear) way.\n# In conjunction with the linear arrow, this notation is just meant to express\n# that the function `jvp f` uses its first input in a nonlinear way but its\n# second input in a linear way, producing a corresponding nonlinear output\n# (which can be used in a nonlinear way) paired with a linear output. This more\n# refined type signature encodes the data dependencies in `jvp f`, which are\n# useful for partial evaluation.\n#\n# To build the `f_lin` jaxpr from a JVP, we need to perform partial evaluation:\n# we evaluate all the primal values as we trace, but stage the tangent\n# computations into a jaxpr. This is our second way to build jaxprs. But where\n# `make_jaxpr` and its underlying `JaxprTrace`/`JaxprTracer` interpreters aim\n# to stage out every primitive bind, this second approach stages out only those\n# primitive binds with a data dependence on tangent inputs.\n#\n# First, some utilities:\n\n# +\ndef split_half(lst: List[Any]) -> Tuple[List[Any], List[Any]]:\n assert not len(lst) % 2\n return split_list(lst, len(lst) // 2)\n\ndef merge_lists(which: List[bool], l1: List[Any], l2: List[Any]) -> List[Any]:\n l1, l2 = iter(l1), iter(l2)\n out = [next(l2) if b else next(l1) for b in which]\n assert next(l1, None) is next(l2, None) is None\n return out\n# -\n\n# Next, we'll write `linearize` by combining `jvp` together with a general\n# partial evaluation transformation, to be added next:\n\n# +\ndef linearize_flat(f, *primals_in):\n pvals_in = ([PartialVal.known(x) for x in primals_in] +\n [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in])\n def f_jvp(*primals_tangents_in):\n primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in))\n return [*primals_out, *tangents_out]\n jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in)\n primal_pvals, _ = split_half(pvals_out)\n assert all(pval.is_known for pval in primal_pvals)\n primals_out = [pval.const for pval in primal_pvals]\n f_lin = lambda *tangents: eval_jaxpr(jaxpr, [*consts, *tangents])\n return primals_out, f_lin\n\ndef linearize(f, *primals_in):\n primals_in_flat, in_tree = tree_flatten(primals_in)\n f, out_tree = flatten_fun(f, in_tree)\n primals_out_flat, f_lin_flat = linearize_flat(f, *primals_in_flat)\n primals_out = tree_unflatten(out_tree(), primals_out_flat)\n\n def f_lin(*tangents_in):\n tangents_in_flat, in_tree2 = tree_flatten(tangents_in)\n if in_tree != in_tree2: raise TypeError\n tangents_out_flat = f_lin_flat(*tangents_in_flat)\n return tree_unflatten(out_tree(), tangents_out_flat)\n\n return primals_out, f_lin\n\ndef vspace(aval: ShapedArray) -> ShapedArray:\n return raise_to_shaped(aval) # TODO handle integers?\n# -\n\n# Now we turn to the general partial evaluation transformation. The goal is to\n# accept a Python callable and a list of inputs, some known and some unknown,\n# and to produce (1) all the outputs which can be computed from the known\n# inputs, together with (2) a jaxpr representing the part of the Python\n# callable's computation which can only be performed after the remaining inputs\n# are known.\n#\n# This transformation is tricky to summarize in a type signature. If we\n# assume the input function's type signature is `(a1, a2) -> (b1, b2)`, where\n# `a1` and `a2` represent the known and unknown inputs, respectively, and where\n# `b1` only has a data dependency on `a1` while `b2` has some data dependency on\n# `a2`, then we might write\n#\n# ```\n# partial_eval : ((a1, a2) -> (b1, b2)) -> a1 -> exists r. (b1, r, (r, a2) -> b2)\n# ```\n#\n# In words, given values for the inputs of type `a1`, `partial_eval` produces\n# the outputs of type `b1` along with \"residual\" values of\n# existentially-quantified type `r` representing the intermediates required to\n# complete the computation in the second stage. It also produces a function of\n# type `(r, a2) -> b2` which accepts the residual values as well as the\n# remaining inputs and produces the remaining outputs.\n#\n# We like to think of partial evaluation as \"unzipping\" one computation into\n# two. For example, consider this jaxpr:\n# ```\n# { lambda a:float64[] .\n# let b:float64[] = sin a\n# c:float64[] = neg b\n# in ( c ) }\n# ```\n# A jaxpr for the JVP would look like:\n# ```\n# { lambda a:float64[] b:float64[] .\n# let c:float64[] = sin a\n# d:float64[] = cos a\n# e:float64[] = mul d b\n# f:float64[] = neg c\n# g:float64[] = neg e\n# in ( f, g ) }\n# ```\n# If we imagine applying partial evaluation to this jaxpr with the first input\n# known and the second unknown, we end up 'unzipping' the JVP jaxpr into primal\n# and tangent jaxprs:\n# ```\n# { lambda a:float64[] .\n# let c:float64[] = sin a\n# d:float64[] = cos a\n# f:float64[] = neg c\n# in ( f, d ) }\n# ```\n# ```\n# { lambda d:float64[] b:float64[] .\n# let e:float64[] = mul d b\n# g:float64[] = neg e\n# in ( g ) }\n# ```\n# This second jaxpr is represents the linear computation that we want from\n# `linearize`.\n#\n# However, unlike in this jaxpr example, we want the computation on known values\n# to occur while evaluating the input Python callable. That is, rather than\n# forming a jaxpr for the entire function `(a1, a2) -> (b1, b2)`, staging all\n# operations out of Python first before sorting out what can be evaluated now\n# and what must be delayed, we want only to form a jaxpr for those operations\n# that _must_ be delayed due to a dependence on unknown inputs. In the context\n# of automatic differentiation, this is the feature ultimately enables us to\n# handle functions like `grad(lambda x: x**2 if x > 0 else 0.)`. Python control\n# flow works because partial evaluation keeps the primal computation in Python.\n# As a consequence, our `Trace` and `Tracer` subclasses must on the fly sort out\n# what can be evaluated and what must be staged out into a jaxpr.\n#\n# First, we start with a `PartialVal` class, which represents a value that can\n# be either known or unknown:\n\nclass PartialVal(NamedTuple):\n aval: ShapedArray\n const: Optional[Any]\n\n @classmethod\n def known(cls, val: Any):\n return PartialVal(get_aval(val), val)\n\n @classmethod\n def unknown(cls, aval: ShapedArray):\n return PartialVal(aval, None)\n\n is_known = property(lambda self: self.const is not None)\n is_unknown = property(lambda self: self.const is None)\n\n# Partial evaluation will take a list of `PartialVal`s representing inputs, and\n# return a list of `PartialVal` outputs along with a jaxpr representing the\n# delayed computation:\n\ndef partial_eval_flat(f: Callable, pvals_in: List[PartialVal]\n ) -> Tuple[Jaxpr, List[PartialVal], List[Any]]:\n with new_main(PartialEvalTrace) as main:\n trace = PartialEvalTrace(main)\n tracers_in = [trace.new_arg(pval) for pval in pvals_in]\n outs = f(*tracers_in)\n tracers_out = [full_raise(trace, out) for out in outs]\n pvals_out = [t.pval for t in tracers_out]\n unk_tracers_in = [t for t in tracers_in if t.pval.is_unknown]\n unk_tracers_out = [t for t in tracers_out if t.pval.is_unknown]\n jaxpr, consts = tracers_to_jaxpr(unk_tracers_in, unk_tracers_out)\n return jaxpr, pvals_out, consts\n\n# Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This\n# interpreter will build a jaxpr on the fly while tracking data dependencies. To\n# do so, it builds a bipartite directed acyclic graph (DAG) between\n# `PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe`\n# nodes, representing formulas for how to compute some values from others. One\n# kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\n# application, but we also have recipe types for constants and lambda binders:\n\n# +\nfrom weakref import ref, ReferenceType\n\nclass LambdaBindingRecipe(NamedTuple):\n pass\n\nclass ConstRecipe(NamedTuple):\n val: Any\n\nclass JaxprEqnRecipe(NamedTuple):\n prim: Primitive\n tracers_in: List['PartialEvalTracer']\n params: Dict[str, Any]\n avals_out: List[ShapedArray]\n tracer_refs_out: List['ReferenceType[PartialEvalTracer]']\n\nJaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe]\n\n\n# -\n\nclass PartialEvalTracer(Tracer):\n pval: PartialVal\n recipe: Optional[JaxprRecipe]\n\n def __init__(self, trace, pval, recipe):\n self._trace = trace\n self.pval = pval\n self.recipe = recipe\n\n aval = property(lambda self: self.pval.aval)\n\n def full_lower(self):\n if self.pval.is_known:\n return full_lower(self.pval.const)\n return self\n\n# The `PartialEvalTrace` contains the logic for constructing the graph of\n# `JaxprRecipe`s and `PartialEvalTracer`s. Each argument corresponds to a\n# `LambdaBindingRecipe` leaf node, and each constant is a `ConstRecipe` leaf\n# node holding a reference to the constant. All other tracers and recipes come\n# from `process_primitive`, which forms tracers with `JaxprEqnRecipe`s.\n#\n# For most primitives, the `process_primitive` logic is straightforward: if all\n# inputs are known then we can bind the primitive on the known values\n# (evaluating it in Python) and avoid forming tracers corresponding to the\n# output. If instead any input is unknown then we instead stage out into a\n# `JaxprEqnRecipe` representing the primitive application. To build the tracers\n# representing unknown outputs, we need avals, which get from the abstract eval\n# rules. (Notice that tracers reference `JaxprEqnRecipe`s, and `JaxprEqnRecipe`s\n# reference tracers; we avoid circular garbage by using weakrefs.)\n#\n# That `process_primitive` logic applies to most primitives, but `xla_call_p`\n# requires recursive treatment. So we special-case its rule in a\n# `partial_eval_rules` dict.\n\n# +\nclass PartialEvalTrace(Trace):\n def new_arg(self, pval: PartialVal) -> Any:\n return PartialEvalTracer(self, pval, LambdaBindingRecipe())\n\n def lift(self, val: Any) -> PartialEvalTracer:\n return PartialEvalTracer(self, PartialVal.known(val), None)\n pure = lift\n\n def instantiate_const(self, tracer: PartialEvalTracer) -> PartialEvalTracer:\n if tracer.pval.is_unknown:\n return tracer\n else:\n pval = PartialVal.unknown(raise_to_shaped(tracer.aval))\n return PartialEvalTracer(self, pval, ConstRecipe(tracer.pval.const))\n\n def process_primitive(self, primitive, tracers, params):\n if all(t.pval.is_known for t in tracers):\n return bind(primitive, *map(full_lower, tracers), **params)\n rule = partial_eval_rules.get(primitive)\n if rule: return rule(self, tracers, **params)\n tracers_in = [self.instantiate_const(t) for t in tracers]\n avals_in = [t.aval for t in tracers_in]\n avals_out = abstract_eval_rules[primitive](*avals_in, **params)\n tracers_out = [PartialEvalTracer(self, PartialVal.unknown(aval), None)\n for aval in avals_out]\n eqn = JaxprEqnRecipe(primitive, tracers_in, params, avals_out,\n map(ref, tracers_out))\n for t in tracers_out: t.recipe = eqn\n return tracers_out\n\npartial_eval_rules = {}\n# -\n\n# Now that we can build graph representations of jaxprs with `PartialEvalTrace`,\n# we need a mechanism to convert the graph representation to a standard jaxpr.\n# The jaxpr corresponds to a topological sort of the graph.\n\n# +\ndef tracers_to_jaxpr(tracers_in: List[PartialEvalTracer],\n tracers_out: List[PartialEvalTracer]):\n tracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in}\n constvar_to_val = {}\n constid_to_var = {}\n processed_eqns = set()\n eqns = []\n for t in toposort(tracers_out, tracer_parents):\n if isinstance(t.recipe, LambdaBindingRecipe):\n assert id(t) in set(map(id, tracers_in))\n elif isinstance(t.recipe, ConstRecipe):\n val = t.recipe.val\n var = constid_to_var.get(id(val))\n if var is None:\n aval = raise_to_shaped(get_aval(val))\n var = tracer_to_var[id(t)] = constid_to_var[id(val)] = Var(aval)\n constvar_to_val[var] = val\n elif isinstance(t.recipe, JaxprEqnRecipe):\n if id(t.recipe) not in processed_eqns:\n eqns.append(recipe_to_eqn(tracer_to_var, t.recipe))\n processed_eqns.add(id(t.recipe))\n else:\n raise TypeError(t.recipe)\n\n constvars, constvals = unzip2(constvar_to_val.items())\n in_binders = constvars + [tracer_to_var[id(t)] for t in tracers_in]\n out_vars = [tracer_to_var[id(t)] for t in tracers_out]\n jaxpr = Jaxpr(in_binders, eqns, out_vars)\n typecheck_jaxpr(jaxpr)\n return jaxpr, constvals\n\ndef recipe_to_eqn(tracer_to_var: Dict[int, Var], recipe: JaxprEqnRecipe\n ) -> JaxprEqn:\n inputs = [tracer_to_var[id(t)] for t in recipe.tracers_in]\n out_binders = [Var(aval) for aval in recipe.avals_out]\n for t_ref, var in zip(recipe.tracer_refs_out, out_binders):\n if t_ref() is not None: tracer_to_var[id(t_ref())] = var\n return JaxprEqn(recipe.prim, inputs, recipe.params, out_binders)\n\ndef tracer_parents(t: PartialEvalTracer) -> List[PartialEvalTracer]:\n return t.recipe.tracers_in if isinstance(t.recipe, JaxprEqnRecipe) else []\n\n# + tags=[\"hide-input\"]\ndef toposort(out_nodes: List[Any], parents: Callable[[Any], List[Any]]):\n if not out_nodes: return []\n out_nodes = remove_duplicates(out_nodes)\n\n child_counts = {}\n stack = list(out_nodes)\n while stack:\n node = stack.pop()\n if id(node) in child_counts:\n child_counts[id(node)] += 1\n else:\n child_counts[id(node)] = 1\n stack.extend(parents(node))\n for node in out_nodes:\n child_counts[id(node)] -= 1\n\n sorted_nodes = []\n childless_nodes = [node for node in out_nodes if not child_counts[id(node)]]\n while childless_nodes:\n node = childless_nodes.pop()\n sorted_nodes.append(node)\n for parent in parents(node):\n if child_counts[id(parent)] == 1:\n childless_nodes.append(parent)\n else:\n child_counts[id(parent)] -= 1\n\n sorted_nodes = sorted_nodes[::-1]\n check_toposort(sorted_nodes, parents)\n return sorted_nodes\n\ndef remove_duplicates(lst):\n seen = set()\n return [x for x in lst if id(x) not in seen and not seen.add(id(x))]\n\ndef check_toposort(nodes: List[Any], parents: Callable[[Any], List[Any]]):\n seen = set()\n for node in nodes:\n assert all(id(parent) in seen for parent in parents(node))\n seen.add(id(node))\n# -\n\n# Now we can linearize!\n\ny, sin_lin = linearize(sin, 3.)\nprint(y, sin(3.))\nprint(sin_lin(1.), cos(3.))\n\n# To handle `linearize`-of-`jit`, we still need to write a partial evaluation\n# rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to\n# perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\n#\n# There are actually two rules to write: one for trace-time partial evaluation,\n# which we'll call `xla_call_partial_eval`, and one for partial evaluation of\n# jaxprs, which we'll call `xla_call_peval_eqn`.\n\n# +\ndef xla_call_partial_eval(trace, tracers, *, jaxpr, num_consts):\n del num_consts # Unused.\n in_unknowns = [not t.pval.is_known for t in tracers]\n jaxpr1, jaxpr2, out_unknowns, num_res = partial_eval_jaxpr(jaxpr, in_unknowns)\n known_tracers, unknown_tracers = partition_list(in_unknowns, tracers)\n known_vals = [t.pval.const for t in known_tracers]\n outs1_res = bind(xla_call_p, *known_vals, jaxpr=jaxpr1, num_consts=0)\n outs1, res = split_list(outs1_res, len(jaxpr1.outs) - num_res)\n res_tracers = [trace.instantiate_const(full_raise(trace, x)) for x in res]\n outs2 = [PartialEvalTracer(trace, PartialVal.unknown(v.aval), None)\n for v in jaxpr2.outs]\n eqn = JaxprEqnRecipe(xla_call_p, res_tracers + unknown_tracers,\n dict(jaxpr=jaxpr2, num_consts=0),\n [v.aval for v in jaxpr2.outs], map(ref, outs2))\n for t in outs2: t.recipe = eqn\n return merge_lists(out_unknowns, outs1, outs2)\npartial_eval_rules[xla_call_p] = xla_call_partial_eval\n\ndef partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool],\n instantiate: Optional[List[bool]] = None,\n ) -> Tuple[Jaxpr, Jaxpr, List[bool], int]:\n env: Dict[Var, bool] = {}\n residuals: Set[Var] = set()\n\n def read(v: Atom) -> bool:\n return type(v) is Var and env[v]\n\n def write(unk: bool, v: Var) -> None:\n env[v] = unk\n\n def new_res(x: Atom) -> Atom:\n if type(x) is Var: residuals.add(x)\n return x\n\n eqns1, eqns2 = [], []\n map(write, in_unknowns, jaxpr.in_binders)\n for eqn in jaxpr.eqns:\n unks_in = map(read, eqn.inputs)\n rule = partial_eval_jaxpr_rules.get(eqn.primitive)\n if rule:\n eqn1, eqn2, unks_out, res = rule(unks_in, eqn)\n eqns1.append(eqn1); eqns2.append(eqn2); residuals.update(res)\n map(write, unks_out, eqn.out_binders)\n elif any(unks_in):\n inputs = [v if unk else new_res(v) for unk, v in zip(unks_in, eqn.inputs)]\n eqns2.append(JaxprEqn(eqn.primitive, inputs, eqn.params, eqn.out_binders))\n map(partial(write, True), eqn.out_binders)\n else:\n eqns1.append(eqn)\n map(partial(write, False), eqn.out_binders)\n out_unknowns = map(read, jaxpr.outs)\n if instantiate is not None:\n for v, uk, inst in zip(jaxpr.outs, out_unknowns, instantiate):\n if inst and not uk: new_res(v)\n out_unknowns = map(op.or_, out_unknowns, instantiate)\n\n residuals, num_res = list(residuals), len(residuals)\n\n ins1, ins2 = partition_list(in_unknowns, jaxpr.in_binders)\n outs1, outs2 = partition_list(out_unknowns, jaxpr.outs)\n\n jaxpr1 = Jaxpr(ins1, eqns1, outs1 + residuals)\n jaxpr2 = Jaxpr(residuals + ins2, eqns2, outs2)\n typecheck_partial_eval_jaxpr(jaxpr, in_unknowns, out_unknowns, jaxpr1, jaxpr2)\n\n return jaxpr1, jaxpr2, out_unknowns, num_res\n\ndef typecheck_partial_eval_jaxpr(jaxpr, unks_in, unks_out, jaxpr1, jaxpr2):\n jaxprty = typecheck_jaxpr(jaxpr) # (a1, a2) -> (b1, b2 )\n jaxpr1ty = typecheck_jaxpr(jaxpr1) # a1 -> (b1, res)\n jaxpr2ty = typecheck_jaxpr(jaxpr2) # (res, a2) -> b2\n\n a1, a2 = partition_list(unks_in, jaxprty.in_types)\n b1, b2 = partition_list(unks_out, jaxprty.out_types)\n b1_, res = split_list(jaxpr1ty.out_types, len(b1))\n res_, a2_ = split_list(jaxpr2ty.in_types, len(res))\n b2_ = jaxpr2ty.out_types\n\n if jaxpr1ty.in_types != a1: raise TypeError\n if jaxpr2ty.out_types != b2: raise TypeError\n if b1 != b1_: raise TypeError\n if res != res_: raise TypeError\n if a2 != a2_: raise TypeError\n if b2 != b2_: raise TypeError\n\npartial_eval_jaxpr_rules = {}\n\ndef xla_call_peval_eqn(unks_in: List[bool], eqn: JaxprEqn,\n ) -> Tuple[JaxprEqn, JaxprEqn, List[bool], List[Atom]]:\n jaxpr = eqn.params['jaxpr']\n jaxpr1, jaxpr2, unks_out, num_res = partial_eval_jaxpr(jaxpr, unks_in)\n ins1, ins2 = partition_list(unks_in, eqn.inputs)\n outs1, outs2 = partition_list(unks_out, eqn.out_binders)\n residuals, _ = split_list(jaxpr2.in_binders, num_res)\n eqn1 = JaxprEqn(xla_call_p, ins1, dict(jaxpr=jaxpr1, num_consts=0),\n outs1 + residuals)\n eqn2 = JaxprEqn(xla_call_p, residuals + ins2,\n dict(jaxpr=jaxpr2, num_consts=0), outs2)\n return eqn1, eqn2, unks_out, residuals\npartial_eval_jaxpr_rules[xla_call_p] = xla_call_peval_eqn\n# -\n\n# With that, we can compose `linearize` and `jit` however we like:\n\n# +\n@jit\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\ny, f_lin = linearize(f, 3.)\ny_dot = f_lin(1.)\nprint(y, y_dot)\n\n# +\n@jit\ndef f(x):\n y = sin(x) * 2.\n z = g(x, y)\n return z\n\n@jit\ndef g(x, y):\n return cos(x) + y\n\ny, f_lin = linearize(f, 3.)\ny_dot = f_lin(1.)\nprint(y, y_dot)\n# -\n\n# ### `vjp` and `grad`\n#\n# The `vjp` transformation works a lot like linearize. Its type signature is\n# analogous:\n#\n# ```\n# linearize : (a -> b) -> a -> (b, T a -o T b)\n# vjp : (a -> b) -> a -> (b, T b -o T a)\n# ```\n#\n# The only difference is that we transpose the linear part of the computation\n# before returning it, so that it goes from type `T a -o T b` to type `T b -o T\n# a`. That is, we'll implement `vjp` as, essentially,\n#\n# ```\n# def vjp(f, x):\n# y, f_lin = linearize(f, x)\n# f_vjp = lambda y_bar: transpose(f_lin)(y_bar)\n# return y, f_vjp\n# ```\n#\n# Since we have the linear computation as a jaxpr, not just a Python callable,\n# we can implement the transpose transformation as a jaxpr interpreter.\n\n# +\ndef vjp_flat(f, *primals_in):\n pvals_in = ([PartialVal.known(x) for x in primals_in] +\n [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in])\n primal_pvals_in, tangent_pvals_in = split_half(pvals_in)\n def f_jvp(*primals_tangents_in):\n primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in))\n return [*primals_out, *tangents_out]\n jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in) # linearize\n primal_pvals, _ = split_half(pvals_out)\n assert all(pval.is_known for pval in primal_pvals)\n primals_out = [pval.const for pval in primal_pvals]\n transpose_inputs = consts + [UndefPrimal(p.aval) for p in tangent_pvals_in]\n f_vjp = lambda *cts: eval_jaxpr_transposed(jaxpr, transpose_inputs, cts)\n return primals_out, f_vjp\n\ndef vjp(f, *primals_in):\n primals_in_flat, in_tree = tree_flatten(primals_in)\n f, out_tree = flatten_fun(f, in_tree)\n primals_out_flat, f_vjp_flat = vjp_flat(f, *primals_in_flat)\n primals_out = tree_unflatten(out_tree(), primals_out_flat)\n\n def f_vjp(*cotangents_out):\n cotangents_out_flat, _ = tree_flatten(cotangents_out)\n cotangents_in_flat = f_vjp_flat(*cotangents_out_flat)\n return tree_unflatten(in_tree, cotangents_in_flat)\n\n return primals_out, f_vjp\n\nclass UndefPrimal(NamedTuple):\n aval: ShapedArray\n\nregister_pytree_node(UndefPrimal,\n lambda u: (u.aval, ()),\n lambda aval, _: UndefPrimal(aval))\n# -\n\n# We use `UndefPrimal` instances to indicate which arguments with respect to\n# with we want to transpose. These arise because in general, being explicit\n# about closed-over values, we want to transpose functions of type\n# `a -> b -o c` to functions of type `a -> c -o b`. Even more generally, the\n# inputs with respect to which the function is linear could be scattered through\n# the argument list. So we indicate the linear positions using `UndefPrimal`.\n# We register `UndefPrimal` as a pytree node because the pytree mechanism gives\n# a handy way to prune these placeholders out of argument lists.\n#\n# Next, we can write `eval_jaxpr_transposed`, along with transpose rules for\n# all primitives which can be linear in at least one argument:\n\n# +\n# NB: the analogous function in JAX is called 'backward_pass'\ndef eval_jaxpr_transposed(jaxpr: Jaxpr, args: List[Any], cotangents: List[Any]\n ) -> List[Any]:\n primal_env: Dict[Var, Any] = {}\n ct_env: Dict[Var, Any] = {}\n\n def read_primal(x: Atom) -> Any:\n return primal_env.get(x, UndefPrimal(x.aval)) if type(x) is Var else x.val\n\n def write_primal(v: Var, val: Any) -> None:\n if type(val) is not UndefPrimal:\n primal_env[v] = val\n\n def read_cotangent(v: Var) -> Any:\n return ct_env.pop(v, np.zeros(v.aval.shape, v.aval.dtype))\n\n def write_cotangent(x: Atom, val: Any):\n if type(x) is Var and val is not None:\n ct_env[x] = add(ct_env[x], val) if x in ct_env else val\n\n map(write_primal, jaxpr.in_binders, args)\n map(write_cotangent, jaxpr.outs, cotangents)\n for eqn in jaxpr.eqns[::-1]:\n primals_in = map(read_primal, eqn.inputs)\n cts_in = map(read_cotangent, eqn.out_binders)\n rule = transpose_rules[eqn.primitive]\n cts_out = rule(cts_in, *primals_in, **eqn.params)\n map(write_cotangent, eqn.inputs, cts_out)\n\n return [read_cotangent(v) for v, x in zip(jaxpr.in_binders, args)\n if type(x) is UndefPrimal]\n\ntranspose_rules = {}\n\n# +\ndef mul_transpose_rule(cts, x, y):\n z_bar, = cts\n assert (type(x) is UndefPrimal) ^ (type(y) is UndefPrimal)\n return [mul(z_bar, y), None] if type(x) is UndefPrimal else [None, mul(x, z_bar)]\ntranspose_rules[mul_p] = mul_transpose_rule\n\ndef neg_transpose_rule(cts, x):\n ybar, = cts\n assert type(x) is UndefPrimal\n return [neg(ybar)]\ntranspose_rules[neg_p] = neg_transpose_rule\n\ndef add_transpose_rule(cts, x, y):\n z_bar, = cts\n return [z_bar, z_bar]\ntranspose_rules[add_p] = add_transpose_rule\n\ndef xla_call_transpose_rule(cts, *invals, jaxpr, num_consts):\n del num_consts # Unused.\n undef_primals = [type(x) is UndefPrimal for x in invals]\n transposed_jaxpr, new_consts = transpose_jaxpr(jaxpr, tuple(undef_primals))\n residuals, _ = partition_list(undef_primals, invals)\n outs = bind(xla_call_p, *new_consts, *residuals, *cts,\n jaxpr=transposed_jaxpr, num_consts=len(new_consts))\n outs = iter(outs)\n return [next(outs) if undef else None for undef in undef_primals]\ntranspose_rules[xla_call_p] = xla_call_transpose_rule\n\n@lru_cache()\ndef transpose_jaxpr(jaxpr: Jaxpr, undef_primals: Tuple[bool, ...]\n ) -> Tuple[Jaxpr, List[Any]]:\n avals_in, avals_out = typecheck_jaxpr(jaxpr)\n traceable = partial(eval_jaxpr_transposed, jaxpr)\n args = [UndefPrimal(a) if u else a for a, u in zip(avals_in, undef_primals)]\n trans_jaxpr, consts, _ = make_jaxpr(traceable, tuple(args), tuple(avals_out))\n typecheck_jaxpr(trans_jaxpr)\n return trans_jaxpr, consts\n# -\n\n# Now that we can linearize and transpose, we can finally write `grad`:\n\ndef grad(f):\n def gradfun(x, *xs):\n y, f_vjp = vjp(f, x, *xs)\n if np.shape(y) != (): raise TypeError\n x_bar, *_ = f_vjp(np.ones(np.shape(y), np.result_type(y)))\n return x_bar\n return gradfun\n\ny, f_vjp = vjp(sin, 3.)\nprint(f_vjp(1.), cos(3.))\n\n# +\ndef f(x):\n y = sin(x) * 2.\n z = - y + x\n return z\n\nprint(grad(f)(3.))\n\n# +\n@jit\ndef f(x):\n y = x * 2.\n z = g(y)\n return z\n\n@jit\ndef g(x):\n return cos(x) * 2.\n\nprint(grad(f)(3.))\n# -\n\n# Here's something of a compositionality stress test:\n\n# +\n# from core_test.py fun_with_nested_calls_2\ndef foo(x):\n @jit\n def bar(y):\n def baz(w):\n q = jit(lambda x: y)(x)\n q = q + jit(lambda: y)()\n q = q + jit(lambda y: w + y)(y)\n q = jit(lambda w: jit(sin)(x) * y)(1.0) + q\n return q\n p, t = jvp(baz, (x + 1.0,), (y,))\n return t + (x * p)\n return bar(x)\n\ndef assert_allclose(*vals):\n for v1, v2 in zip(vals[:-1], vals[1:]):\n np.testing.assert_allclose(v1, v2)\n\nans1 = f(3.)\nans2 = jit(f)(3.)\nans3, _ = jvp(f, (3.,), (5.,))\nans4, _ = jvp(jit(f), (3.,), (5.,))\nassert_allclose(ans1, ans2, ans3, ans4)\n\nderiv1 = grad(f)(3.)\nderiv2 = grad(jit(f))(3.)\nderiv3 = jit(grad(jit(f)))(3.)\n_, deriv4 = jvp(f, (3.,), (1.,))\n_, deriv5 = jvp(jit(f), (3.,), (1.,))\nassert_allclose(deriv1, deriv2, deriv3, deriv4, deriv5)\n\nhess1 = grad(grad(f))(3.)\nhess2 = grad(grad(jit(f)))(3.)\nhess3 = grad(jit(grad(f)))(3.)\nhess4 = jit(grad(grad(f)))(3.)\n_, hess5 = jvp(grad(f), (3.,), (1.,))\n_, hess6 = jvp(jit(grad(f)), (3.,), (1.,))\n_, hess7 = jvp(jit(grad(f)), (3.,), (1.,))\nassert_allclose(hess1, hess2, hess3, hess4, hess5, hess6, hess7)\n# -\n\n# ## Part 5: the control flow primitives `cond`\n#\n# Next we'll add higher-order primitives for staged-out control flow. These\n# resemble `jit` from Part 3, another higher-order primitive, but differ in that\n# they are parameterized by multiple callables rather than just one.\n\n# ### Adding `cond`\n#\n# We introduce a `cond` primitive to represent conditional application of one\n# function or another inside a jaxpr. We write the type of `cond` as\n# `Bool -> (a -> b) -> (a -> b) -> a -> b`. In words, `cond` takes a boolean\n# representing the predicate and two functions of equal types. Depending on the\n# value of the predicate, it applies one function or the other to its final\n# argument.\n#\n# In Python, we represent it as a function which itself takes two functions as\n# arguments. As with `jit`, the first step is to call `make_jaxpr` on its\n# callable arguments to turn them into jaxprs:\n\n# +\ndef cond(pred, true_fn, false_fn, *operands):\n avals_in = [raise_to_shaped(get_aval(x)) for x in operands]\n true_jaxpr, true_consts, out_tree = make_jaxpr(true_fn, *avals_in)\n false_jaxpr, false_consts, out_tree_ = make_jaxpr(false_fn, *avals_in)\n if out_tree != out_tree_: raise TypeError\n true_jaxpr, false_jaxpr = _join_jaxpr_consts(\n true_jaxpr, false_jaxpr, len(true_consts), len(false_consts))\n if typecheck_jaxpr(true_jaxpr) != typecheck_jaxpr(false_jaxpr):\n raise TypeError\n outs = bind_cond(pred, *true_consts, *false_consts, *operands,\n true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr)\n return tree_unflatten(out_tree, outs)\ncond_p = Primitive('cond')\n\ndef _join_jaxpr_consts(jaxpr1: Jaxpr, jaxpr2: Jaxpr, n1: int, n2: int\n ) -> Tuple[Jaxpr, Jaxpr]:\n jaxpr1_type, jaxpr2_type = typecheck_jaxpr(jaxpr1), typecheck_jaxpr(jaxpr2)\n assert jaxpr1_type.in_types[n1:] == jaxpr2_type.in_types[n2:]\n consts1, rest1 = split_list(jaxpr1.in_binders, n1)\n consts2, rest2 = split_list(jaxpr2.in_binders, n2)\n new_jaxpr1 = Jaxpr(consts1 + consts2 + rest1, jaxpr1.eqns, jaxpr1.outs)\n new_jaxpr2 = Jaxpr(consts1 + consts2 + rest2, jaxpr2.eqns, jaxpr2.outs)\n return new_jaxpr1, new_jaxpr2\n\ndef bind_cond(pred, *args, true_jaxpr, false_jaxpr):\n assert len(args) == len(true_jaxpr.in_binders) == len(false_jaxpr.in_binders)\n return bind(cond_p, pred, *args, true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr)\n# -\n\n# We require `true_jaxpr` and `false_jaxpr` to have the same type, but because\n# they might close over different constants (and because jaxprs can only\n# represent closed terms, i.e. can't have free variables and are instead\n# closure-converted) we need to use the helper `_join_jaxpr_consts` to make\n# consistent the input binder lists of the two jaxprs. (To be more economical we\n# could try to identify pairs of constants with the same shapes, but instead we\n# just concatenate the lists of constants.)\n#\n# Next we can turn to adding interpreter rules for `cond`. Its evaluation rule\n# is simple:\n\n\ndef cond_impl(pred, *operands, true_jaxpr, false_jaxpr):\n if pred:\n return eval_jaxpr(true_jaxpr, operands)\n else:\n return eval_jaxpr(false_jaxpr, operands)\nimpl_rules[cond_p] = cond_impl\n\nout = cond(True, lambda: 3, lambda: 4)\nprint(out)\n\n# For its JVP and vmap rules, we only need to call the same `jvp_jaxpr` and\n# `vmap_jaxpr` utilities we created for `jit`, followed by another pass of\n# `_join_jaxpr_consts`:\n\ndef cond_jvp_rule(primals, tangents, *, true_jaxpr, false_jaxpr):\n pred, *primals = primals\n _ , *tangents = tangents\n true_jaxpr , true_consts = jvp_jaxpr(true_jaxpr)\n false_jaxpr, false_consts = jvp_jaxpr(false_jaxpr)\n true_jaxpr, false_jaxpr = _join_jaxpr_consts(\n true_jaxpr, false_jaxpr, len(true_consts), len(false_consts))\n assert typecheck_jaxpr(true_jaxpr) == typecheck_jaxpr(false_jaxpr)\n outs = bind_cond(pred, *true_consts, *false_consts, *primals, *tangents,\n true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr)\n primals_out, tangents_out = split_half(outs)\n return primals_out, tangents_out\njvp_rules[cond_p] = cond_jvp_rule\n\nout, out_tan = jvp(lambda x: cond(True, lambda: x * x, lambda: 0.), (1.,), (1.,))\nprint(out_tan)\n\ndef cond_vmap_rule(axis_size, vals_in, dims_in, *, true_jaxpr, false_jaxpr):\n pred , *vals_in = vals_in\n pred_dim, *dims_in = dims_in\n if pred_dim is not not_mapped: raise NotImplementedError # TODO\n true_jaxpr, true_consts = vmap_jaxpr(true_jaxpr, axis_size, tuple(dims_in))\n false_jaxpr, false_consts = vmap_jaxpr(false_jaxpr, axis_size, tuple(dims_in))\n true_jaxpr, false_jaxpr = _join_jaxpr_consts(\n true_jaxpr, false_jaxpr, len(true_consts), len(false_consts))\n assert typecheck_jaxpr(true_jaxpr) == typecheck_jaxpr(false_jaxpr)\n outs = bind_cond(pred, *true_consts, *false_consts, *vals_in,\n true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr)\n return outs, [0] * len(outs)\nvmap_rules[cond_p] = cond_vmap_rule\n\nxs = np.array([1., 2., 3])\nout = vmap(lambda x: cond(True, lambda: x + 1., lambda: 0.), (0,))(xs)\nprint(out)\n\n# Notice that we're not currently supporting the case where the predicate value\n# itself is batched. In mainline JAX, we handle this case by transforming the\n# conditional to a [select primitive](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.select.html).\n# That transformation is semantically correct so long as `true_fun` and\n# `false_fun` do not involve any side-effecting primitives.\n#\n# Another thing not represented here, but present in the mainline JAX, is that\n# applying transformations to two jaxprs of equal type might result in jaxprs of\n# different types. For example, applying the mainline JAX version of\n# `vmap_jaxpr` to the identity-function jaxpr\n#\n# ```\n# { lambda a:float32[] .\n# let\n# in ( a ) }\n# ```\n#\n# would result in a jaxpr with a batched output, of type\n# `[float32[10]] -> [float32[10]]` if the batch size were 10, while applying it\n# to the zero-function jaxpr\n#\n# ```\n# { lambda a:float32[] .\n# let\n# in ( 0. ) }\n# ```\n#\n# would result in a jaxpr with an unbatched output, of type\n# `[float32[10]] -> [float32[]]`. This is an optimization, aimed at not batching\n# values unnecessarily. But it means that in `cond` we'd need an extra step of\n# joining the two transformed jaxprs to have consistent output types. We don't\n# need this step here because we chose `vmap_jaxpr` always to batch all outputs\n# over the leading axis.\n\n\n# Next we can turn to abstract evaluation and XLA lowering rules:\n\n# +\ndef cond_abstract_eval(pred_type, *in_types, true_jaxpr, false_jaxpr):\n if pred_type != ShapedArray((), np.dtype('bool')): raise TypeError\n jaxpr_type = typecheck_jaxpr(true_jaxpr)\n if jaxpr_type != typecheck_jaxpr(false_jaxpr):\n raise TypeError\n if not all(t1 == t2 for t1, t2 in zip(jaxpr_type.in_types, in_types)):\n raise TypeError\n return jaxpr_type.out_types\nabstract_eval_rules[cond_p] = cond_abstract_eval\n\ndef cond_translation(c, in_avals, in_vals, *, true_jaxpr, false_jaxpr):\n del in_avals # Unused.\n pred, *in_vals = in_vals\n flat_vals, in_tree = tree_flatten(in_vals)\n operand = xops.Tuple(c, flat_vals)\n operand_shape = c.get_shape(operand)\n\n def make_comp(name: str, jaxpr: Jaxpr) -> xe.XlaComputation:\n c = xb.make_computation_builder(name)\n operand = xb.parameter(c, 0, operand_shape)\n operands = tree_unflatten(in_tree, destructure_tuple(c, operand))\n outs = jaxpr_subcomp(c, jaxpr, operands)\n return c.build(xops.Tuple(c, outs))\n\n true_comp = make_comp('true_fn', true_jaxpr)\n false_comp = make_comp('false_fn', false_jaxpr)\n\n int_etype = xc.dtype_to_etype(np.dtype('int32'))\n out = xops.Conditional(xops.ConvertElementType(pred, int_etype),\n [false_comp, true_comp], [operand] * 2)\n return destructure_tuple(c, out)\nxla_translations[cond_p] = cond_translation\n# -\n\nout = jit(lambda: cond(False, lambda: 1, lambda: 2))()\nprint(out)\n\n# Finally, to support reverse-mode automatic differentiation, we need partial\n# evaluation and transposition rules. For partial evaluation, we need to\n# introduce another jaxpr-munging utility, `_join_jaxpr_res`, to handle the fact\n# that applying partial evaluation to `true_fun` and `false_fun` will in general\n# result in distinct residuals. We use `_join_jaxpr_res` to make the output\n# types of the transformed jaxprs consistent (while `_join_jaxpr_consts` dealt\n# with input types).\n\n# +\ndef cond_partial_eval(trace, tracers, *, true_jaxpr, false_jaxpr):\n pred_tracer, *tracers = tracers\n assert pred_tracer.pval.is_known\n pred = pred_tracer.pval.const\n in_uks = [not t.pval.is_known for t in tracers]\n\n *jaxprs, out_uks, num_res = _cond_partial_eval(true_jaxpr, false_jaxpr, in_uks)\n t_jaxpr1, f_jaxpr1, t_jaxpr2, f_jaxpr2 = jaxprs\n\n known_tracers, unknown_tracers = partition_list(in_uks, tracers)\n known_vals = [t.pval.const for t in known_tracers]\n outs1_res = bind_cond(pred, *known_vals,\n true_jaxpr=t_jaxpr1, false_jaxpr=f_jaxpr1)\n outs1, res = split_list(outs1_res, len(outs1_res) - num_res)\n pred_tracer_ = trace.instantiate_const(full_raise(trace, pred_tracer))\n res_tracers = [trace.instantiate_const(full_raise(trace, x)) for x in res]\n outs2 = [PartialEvalTracer(trace, PartialVal.unknown(v.aval), None)\n for v in t_jaxpr2.outs]\n eqn = JaxprEqnRecipe(cond_p, [pred_tracer_, *res_tracers, *unknown_tracers],\n dict(true_jaxpr=t_jaxpr2, false_jaxpr=f_jaxpr2),\n [v.aval for v in t_jaxpr2.outs], map(ref, outs2))\n for t in outs2: t.recipe = eqn\n return merge_lists(out_uks, outs1, outs2)\npartial_eval_rules[cond_p] = cond_partial_eval\n\ndef _cond_partial_eval(true_jaxpr: Jaxpr, false_jaxpr: Jaxpr, in_uks: List[bool]\n ) -> Tuple[Jaxpr, Jaxpr, Jaxpr, Jaxpr, List[bool], int]:\n _, _, t_out_uks, _ = partial_eval_jaxpr(true_jaxpr , in_uks)\n _, _, f_out_uks, _ = partial_eval_jaxpr(false_jaxpr, in_uks)\n out_uks = map(op.or_, t_out_uks, f_out_uks)\n\n t_jaxpr1, t_jaxpr2, _, t_nres = partial_eval_jaxpr(true_jaxpr , in_uks, out_uks)\n f_jaxpr1, f_jaxpr2, _, f_nres = partial_eval_jaxpr(false_jaxpr, in_uks, out_uks)\n\n t_jaxpr1, f_jaxpr1 = _join_jaxpr_res(t_jaxpr1, f_jaxpr1, t_nres, f_nres)\n t_jaxpr2, f_jaxpr2 = _join_jaxpr_consts(t_jaxpr2, f_jaxpr2, t_nres, f_nres)\n assert typecheck_jaxpr(t_jaxpr1) == typecheck_jaxpr(f_jaxpr1)\n assert typecheck_jaxpr(t_jaxpr2) == typecheck_jaxpr(f_jaxpr2)\n num_res = t_nres + f_nres\n\n return t_jaxpr1, f_jaxpr1, t_jaxpr2, f_jaxpr2, out_uks, num_res\n\ndef _join_jaxpr_res(jaxpr1: Jaxpr, jaxpr2: Jaxpr, n1: int, n2: int\n ) -> Tuple[Jaxpr, Jaxpr]:\n jaxpr1_type, jaxpr2_type = typecheck_jaxpr(jaxpr1), typecheck_jaxpr(jaxpr2)\n out_types1, _ = split_list(jaxpr1_type.out_types, len(jaxpr1.outs) - n1)\n out_types2, _ = split_list(jaxpr2_type.out_types, len(jaxpr2.outs) - n2)\n assert out_types1 == out_types2\n outs1, res1 = split_list(jaxpr1.outs, len(jaxpr1.outs) - n1)\n outs2, res2 = split_list(jaxpr2.outs, len(jaxpr2.outs) - n2)\n zeros_like1 = [Lit(np.zeros(v.aval.shape, v.aval.dtype)) for v in res1]\n zeros_like2 = [Lit(np.zeros(v.aval.shape, v.aval.dtype)) for v in res2]\n new_jaxpr1 = Jaxpr(jaxpr1.in_binders, jaxpr1.eqns, outs1 + res1 + zeros_like2)\n new_jaxpr2 = Jaxpr(jaxpr2.in_binders, jaxpr2.eqns, outs2 + zeros_like1 + res2)\n return new_jaxpr1, new_jaxpr2\n\n\n# -\n\n_, f_lin = linearize(lambda x: cond(True, lambda: x, lambda: 0.), 1.)\nout = f_lin(3.14)\nprint(out)\n\ndef cond_peval_eqn(unks_in: List[bool], eqn: JaxprEqn,\n ) -> Tuple[JaxprEqn, JaxprEqn, List[bool], List[Atom]]:\n pred_unk, *unks_in = unks_in\n assert not pred_unk\n true_jaxpr, false_jaxpr = eqn.params['true_jaxpr'], eqn.params['false_jaxpr']\n *jaxprs, unks_out, num_res = _cond_partial_eval(true_jaxpr, false_jaxpr, unks_in)\n t_jaxpr1, f_jaxpr1, t_jaxpr2, f_jaxpr2 = jaxprs\n ins1, ins2 = partition_list(unks_in, eqn.inputs[1:])\n outs1, outs2 = partition_list(unks_out, eqn.out_binders)\n residuals, _ = split_list(t_jaxpr2.in_binders, num_res)\n eqn1 = JaxprEqn(cond_p, [eqn.inputs[0], *ins1],\n dict(true_jaxpr=t_jaxpr1, false_jaxpr=f_jaxpr1),\n outs1 + residuals)\n eqn2 = JaxprEqn(cond_p, [eqn.inputs[0], *residuals, *ins2],\n dict(true_jaxpr=t_jaxpr2, false_jaxpr=f_jaxpr2),\n outs2)\n return eqn1, eqn2, unks_out, [eqn.inputs[0], *residuals]\npartial_eval_jaxpr_rules[cond_p] = cond_peval_eqn\n\n_, f_lin = linearize(jit(lambda x: cond(True, lambda: x, lambda: 0.)), 1.)\nout = f_lin(3.14)\nprint(out)\n\n# Transposition is a fairly straightforward application of `transpose_jaxpr`:\n\ndef cond_transpose_rule(cts, pred, *invals, true_jaxpr, false_jaxpr):\n undef_primals = tuple([type(x) is UndefPrimal for x in invals])\n true_jaxpr, true_consts = transpose_jaxpr(true_jaxpr, undef_primals)\n false_jaxpr, false_consts = transpose_jaxpr(false_jaxpr, undef_primals)\n true_jaxpr, false_jaxpr = _join_jaxpr_consts(\n true_jaxpr, false_jaxpr, len(true_consts), len(false_consts))\n res = [x for x in invals if type(x) is not UndefPrimal]\n outs = bind_cond(pred, *true_consts, *false_consts, *res, *cts,\n true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr)\n outs = iter(outs)\n return [None] + [next(outs) if type(x) is UndefPrimal else None for x in invals]\ntranspose_rules[cond_p] = cond_transpose_rule\n\nout = grad(lambda x: cond(True, lambda: x * x, lambda: 0.))(1.)\nprint(out)\n"
]
| [
[
"numpy.testing.assert_allclose",
"numpy.negative",
"numpy.multiply",
"numpy.cos",
"numpy.size",
"numpy.broadcast_to",
"numpy.dtype",
"numpy.sin",
"numpy.less",
"numpy.arange",
"numpy.transpose",
"numpy.ndim",
"numpy.greater",
"numpy.expand_dims",
"numpy.array",
"numpy.zeros",
"numpy.shape",
"numpy.result_type",
"numpy.add",
"numpy.asarray",
"numpy.sum"
]
]
|
sakshigarg1098/JointBert-CRF | [
"d69fc3ff40fa1fb61c9177ab0145fc24d0c2d0e8"
]
| [
"model/modeling_jointbert.py"
]
| [
"import torch\nimport torch.nn as nn\nfrom transformers.modeling_bert import BertPreTrainedModel, BertModel, BertConfig\nfrom torchcrf import CRF\nfrom .module import IntentClassifier, SlotClassifier\n\n\nclass JointBERT(BertPreTrainedModel):\n def __init__(self, config, args, intent_label_lst, slot_label_lst):\n super(JointBERT, self).__init__(config)\n self.args = args\n self.num_intent_labels = len(intent_label_lst)\n self.num_slot_labels = len(slot_label_lst)\n self.bert = BertModel(config=config) # Load pretrained bert\n\n self.intent_classifier = IntentClassifier(config.hidden_size, self.num_intent_labels, args.dropout_rate)\n self.slot_classifier = SlotClassifier(\n config.hidden_size,\n self.num_intent_labels,\n self.num_slot_labels,\n self.args.use_intent_context_concat,\n self.args.use_intent_context_attention,\n self.args.max_seq_len,\n self.args.attention_embedding_size,\n args.dropout_rate,\n )\n\n if args.use_crf:\n self.crf = CRF(num_tags=self.num_slot_labels, batch_first=True)\n\n def forward(self, input_ids, attention_mask, token_type_ids, intent_label_ids, slot_labels_ids):\n outputs = self.bert(\n input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids\n ) # sequence_output, pooled_output, (hidden_states), (attentions)\n sequence_output = outputs[0]\n pooled_output = outputs[1] # [CLS]\n\n intent_logits = self.intent_classifier(pooled_output)\n if not self.args.use_attention_mask:\n tmp_attention_mask = None\n else:\n tmp_attention_mask = attention_mask\n\n if self.args.embedding_type == \"hard\":\n hard_intent_logits = torch.zeros(intent_logits.shape)\n for i, sample in enumerate(intent_logits):\n max_idx = torch.argmax(sample)\n hard_intent_logits[i][max_idx] = 1\n slot_logits = self.slot_classifier(sequence_output, hard_intent_logits, tmp_attention_mask)\n else:\n slot_logits = self.slot_classifier(sequence_output, intent_logits, tmp_attention_mask)\n\n total_loss = 0\n # 1. Intent Softmax\n if intent_label_ids is not None:\n if self.num_intent_labels == 1:\n intent_loss_fct = nn.MSELoss()\n intent_loss = intent_loss_fct(intent_logits.view(-1), intent_label_ids.view(-1))\n else:\n intent_loss_fct = nn.CrossEntropyLoss()\n intent_loss = intent_loss_fct(\n intent_logits.view(-1, self.num_intent_labels), intent_label_ids.view(-1)\n )\n total_loss += self.args.intent_loss_coef * intent_loss\n\n # 2. Slot Softmax\n if slot_labels_ids is not None:\n if self.args.use_crf:\n slot_loss = self.crf(slot_logits, slot_labels_ids, mask=attention_mask.byte(), reduction=\"mean\")\n slot_loss = -1 * slot_loss # negative log-likelihood\n else:\n slot_loss_fct = nn.CrossEntropyLoss(ignore_index=self.args.ignore_index)\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = slot_logits.view(-1, self.num_slot_labels)[active_loss]\n active_labels = slot_labels_ids.view(-1)[active_loss]\n slot_loss = slot_loss_fct(active_logits, active_labels)\n else:\n slot_loss = slot_loss_fct(slot_logits.view(-1, self.num_slot_labels), slot_labels_ids.view(-1))\n total_loss += (1 - self.args.intent_loss_coef) * slot_loss\n\n outputs = ((intent_logits, slot_logits),) + outputs[2:] # add hidden states and attention if they are here\n\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions) # Logits is a tuple of intent and slot logits\n"
]
| [
[
"torch.zeros",
"torch.nn.MSELoss",
"torch.nn.CrossEntropyLoss",
"torch.argmax"
]
]
|
jiangwei221/COTR-1 | [
"96abd8f95e23c7bf4d04811db6dd131887a2f37a"
]
| [
"COTR/inference/refinement_task.py"
]
| [
"import time\n\nimport numpy as np\nimport torch\nfrom torchvision.transforms import functional as tvtf\nimport imageio\nimport PIL\n\nfrom COTR.inference.inference_helper import BASE_ZOOM, THRESHOLD_PIXELS_RELATIVE, get_patch_centered_at, two_images_side_by_side, find_prediction_loop\nfrom COTR.utils import debug_utils, utils\nfrom COTR.utils.constants import MAX_SIZE\nfrom COTR.utils.utils import ImagePatch\n\n\nclass RefinementTask():\n def __init__(self, image_from, image_to, loc_from, loc_to, area_from, area_to, converge_iters, zoom_ins, identifier=None):\n self.identifier = identifier\n self.image_from = image_from\n self.image_to = image_to\n self.loc_from = loc_from\n self.best_loc_to = loc_to\n self.cur_loc_to = loc_to\n self.area_from = area_from\n self.area_to = area_to\n if self.area_from < self.area_to:\n self.s_from = BASE_ZOOM\n self.s_to = BASE_ZOOM * np.sqrt(self.area_to / self.area_from)\n else:\n self.s_to = BASE_ZOOM\n self.s_from = BASE_ZOOM * np.sqrt(self.area_from / self.area_to)\n\n self.cur_job = {}\n self.status = 'unfinished'\n self.result = 'unknown'\n\n self.converge_iters = converge_iters\n self.zoom_ins = zoom_ins\n self.cur_zoom_idx = 0\n self.cur_iter = 0\n self.total_iter = 0\n\n self.loc_to_at_zoom = []\n self.loc_history = [loc_to]\n self.all_loc_to_dict = {}\n self.job_history = []\n self.submitted = False\n\n @property\n def cur_zoom(self):\n return self.zoom_ins[self.cur_zoom_idx]\n\n @property\n def confidence_scaling_factor(self):\n if self.cur_zoom_idx > 0:\n conf_scaling = float(self.cur_zoom) / float(self.zoom_ins[0])\n else:\n conf_scaling = 1.0\n return conf_scaling\n\n def peek(self):\n assert self.status == 'unfinished'\n patch_from = get_patch_centered_at(None, self.loc_from, scale=self.s_from * self.cur_zoom, return_content=False, img_shape=self.image_from.shape)\n patch_to = get_patch_centered_at(None, self.cur_loc_to, scale=self.s_to * self.cur_zoom, return_content=False, img_shape=self.image_to.shape)\n top_job = {'patch_from': patch_from,\n 'patch_to': patch_to,\n 'loc_from': self.loc_from,\n 'loc_to': self.cur_loc_to,\n }\n return top_job\n\n def get_task_pilot(self, pilot):\n assert self.status == 'unfinished'\n patch_from = ImagePatch(None, pilot.cur_job['patch_from'].x, pilot.cur_job['patch_from'].y, pilot.cur_job['patch_from'].w, pilot.cur_job['patch_from'].h, pilot.cur_job['patch_from'].ow, pilot.cur_job['patch_from'].oh)\n patch_to = ImagePatch(None, pilot.cur_job['patch_to'].x, pilot.cur_job['patch_to'].y, pilot.cur_job['patch_to'].w, pilot.cur_job['patch_to'].h, pilot.cur_job['patch_to'].ow, pilot.cur_job['patch_to'].oh)\n query = torch.from_numpy((np.array(self.loc_from) - np.array([patch_from.x, patch_from.y])) / np.array([patch_from.w * 2, patch_from.h]))[None].float()\n self.cur_job = {'patch_from': patch_from,\n 'patch_to': patch_to,\n 'loc_from': self.loc_from,\n 'loc_to': self.cur_loc_to,\n 'img': None,\n }\n self.job_history.append((patch_from.h, patch_from.w, patch_to.h, patch_to.w))\n assert self.submitted == False\n self.submitted = True\n return None, query\n\n def get_task_fast(self):\n assert self.status == 'unfinished'\n patch_from = get_patch_centered_at(self.image_from, self.loc_from, scale=self.s_from * self.cur_zoom, return_content=False)\n patch_to = get_patch_centered_at(self.image_to, self.cur_loc_to, scale=self.s_to * self.cur_zoom, return_content=False)\n query = torch.from_numpy((np.array(self.loc_from) - np.array([patch_from.x, patch_from.y])) / np.array([patch_from.w * 2, patch_from.h]))[None].float()\n self.cur_job = {'patch_from': patch_from,\n 'patch_to': patch_to,\n 'loc_from': self.loc_from,\n 'loc_to': self.cur_loc_to,\n 'img': None,\n }\n\n self.job_history.append((patch_from.h, patch_from.w, patch_to.h, patch_to.w))\n assert self.submitted == False\n self.submitted = True\n\n return None, query\n\n def get_task(self):\n assert self.status == 'unfinished'\n patch_from = get_patch_centered_at(self.image_from, self.loc_from, scale=self.s_from * self.cur_zoom)\n patch_to = get_patch_centered_at(self.image_to, self.cur_loc_to, scale=self.s_to * self.cur_zoom)\n\n query = torch.from_numpy((np.array(self.loc_from) - np.array([patch_from.x, patch_from.y])) / np.array([patch_from.w * 2, patch_from.h]))[None].float()\n\n img_from = patch_from.patch\n img_to = patch_to.patch\n assert img_from.shape[0] == img_from.shape[1]\n assert img_to.shape[0] == img_to.shape[1]\n\n img_from = np.array(PIL.Image.fromarray(img_from).resize((MAX_SIZE, MAX_SIZE), resample=PIL.Image.BILINEAR))\n img_to = np.array(PIL.Image.fromarray(img_to).resize((MAX_SIZE, MAX_SIZE), resample=PIL.Image.BILINEAR))\n img = two_images_side_by_side(img_from, img_to)\n img = tvtf.normalize(tvtf.to_tensor(img), (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)).float()\n\n self.cur_job = {'patch_from': ImagePatch(None, patch_from.x, patch_from.y, patch_from.w, patch_from.h, patch_from.ow, patch_from.oh),\n 'patch_to': ImagePatch(None, patch_to.x, patch_to.y, patch_to.w, patch_to.h, patch_to.ow, patch_to.oh),\n 'loc_from': self.loc_from,\n 'loc_to': self.cur_loc_to,\n }\n\n self.job_history.append((patch_from.h, patch_from.w, patch_to.h, patch_to.w))\n assert self.submitted == False\n self.submitted = True\n\n return img, query\n\n def next_zoom(self):\n if self.cur_zoom_idx >= len(self.zoom_ins) - 1:\n self.status = 'finished'\n if self.conclude() is None:\n self.result = 'bad'\n else:\n self.result = 'good'\n self.cur_zoom_idx += 1\n self.cur_iter = 0\n self.loc_to_at_zoom = []\n\n def scale_to_loc(self, raw_to_loc):\n raw_to_loc = raw_to_loc.copy()\n patch_b = self.cur_job['patch_to']\n raw_to_loc[0] = (raw_to_loc[0] - 0.5) * 2\n loc_to = raw_to_loc * np.array([patch_b.w, patch_b.h])\n loc_to = loc_to + np.array([patch_b.x, patch_b.y])\n return loc_to\n\n def step(self, raw_to_loc):\n assert self.submitted == True\n self.submitted = False\n loc_to = self.scale_to_loc(raw_to_loc)\n self.total_iter += 1\n self.loc_to_at_zoom.append(loc_to)\n self.cur_loc_to = loc_to\n zoom_finished = False\n if self.cur_zoom_idx == len(self.zoom_ins) - 1:\n # converge at the last level\n if len(self.loc_to_at_zoom) >= 2:\n zoom_finished = np.prod(self.loc_to_at_zoom[:-1] == loc_to, axis=1, keepdims=True).any()\n if self.cur_iter >= self.converge_iters - 1:\n zoom_finished = True\n self.cur_iter += 1\n else:\n # finish immediately for other levels\n zoom_finished = True\n if zoom_finished:\n self.all_loc_to_dict[self.cur_zoom] = np.array(self.loc_to_at_zoom).copy()\n last_level_loc_to = self.all_loc_to_dict[self.cur_zoom]\n if len(last_level_loc_to) >= 2:\n has_loop = np.prod(last_level_loc_to[:-1] == last_level_loc_to[-1], axis=1, keepdims=True).any()\n if has_loop:\n loop = find_prediction_loop(last_level_loc_to)\n loc_to = loop.mean(axis=0)\n self.loc_history.append(loc_to)\n self.best_loc_to = loc_to\n self.cur_loc_to = self.best_loc_to\n self.next_zoom()\n\n def conclude(self, force=False):\n loc_history = np.array(self.loc_history)\n if (force == False) and (max(loc_history.std(axis=0)) >= THRESHOLD_PIXELS_RELATIVE * max(*self.image_to.shape)):\n return None\n return np.concatenate([self.loc_from, self.best_loc_to])\n\n def conclude_intermedia(self):\n return np.concatenate([np.array(self.loc_history), np.array(self.job_history)], axis=1)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.prod",
"numpy.sqrt"
]
]
|
R-abodyak/PalPose | [
"032565a2f951c8825af562b3593bde3fdbfba082"
]
| [
"depthai_helpers/utils.py"
]
| [
"import importlib\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport depthai as dai\n\n\ndef cos_dist(a, b):\n return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n\ndef frame_norm(frame, bbox):\n norm_vals = np.full(len(bbox), frame.shape[0])\n norm_vals[::2] = frame.shape[1]\n return (np.clip(np.array(bbox), 0, 1) * norm_vals).astype(int)\n\n\ndef to_planar(arr: np.ndarray, shape: tuple = None) -> np.ndarray:\n if shape is None:\n return arr.transpose(2, 0, 1)\n return cv2.resize(arr, shape).transpose(2, 0, 1)\n\n\ndef to_tensor_result(packet):\n data = {}\n for tensor in packet.getRaw().tensors:\n if tensor.dataType == dai.TensorInfo.DataType.INT:\n data[tensor.name] = np.array(packet.getLayerInt32(tensor.name)).reshape(tensor.dims[::-1])\n elif tensor.dataType == dai.TensorInfo.DataType.FP16:\n data[tensor.name] = np.array(packet.getLayerFp16(tensor.name)).reshape(tensor.dims[::-1])\n elif tensor.dataType == dai.TensorInfo.DataType.I8:\n data[tensor.name] = np.array(packet.getLayerUInt8(tensor.name)).reshape(tensor.dims[::-1])\n else:\n print(\"Unsupported tensor layer type: {}\".format(tensor.dataType))\n return data\n\n\n# https://stackoverflow.com/questions/20656135/python-deep-merge-dictionary-data#20666342\ndef merge(source, destination):\n \"\"\"\n run me with nosetests --with-doctest file.py\n\n >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }\n >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }\n >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }\n True\n \"\"\"\n for key, value in source.items():\n if isinstance(value, dict):\n # get node or create one\n node = destination.setdefault(key, {})\n merge(value, node)\n else:\n destination[key] = value\n\n return destination\n\n\ndef load_module(path: Path):\n spec = importlib.util.spec_from_file_location(path.stem, str(path.absolute()))\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
]
]
|
jlbbj111/2019-Software-Engineering-Curriculum-Design | [
"a55deabaf00220c5ffb531c6e40ed9edb8063062"
]
| [
"EMS/courseScheduling/Schedule.py"
]
| [
"import numpy as np\nimport heapq\n# 输入\nfrom courseScheduling.models import MajorCourses as MajorCourses\nfrom courseScheduling.models import Teaching as original_Teaching\nfrom backstage.models import ClassRoom, Student, AdmClass, MajorPlan\nfrom courseSelection.models import CourseSelected as courseSelected\n# from courseScheduling.Synchronize import Sychronize_with_courseSelected as swc\n# 输出\nfrom courseScheduling.models import Schedule_result, Teacher_Schedule_result, Classroom_other_schedule, Exam_Schedule\n\nyear = 2019\nsemester = 2\nStudents_id = dict()\nTeachers_id = dict()\nClassrooms_id = dict()\nCourses_id = dict()\nhas_already_scheduled = dict()\n\n\nclass Students:\n def __init__(self, id, name, major, year, admclass):\n self.id = id\n self.name = name\n self.major = major\n self.year = year\n self.Admclass = admclass\n # 8行14列\n self.courseSchedule = []\n self.examSchedule = []\n for i in range(8):\n self.courseSchedule.append([])\n for j in range(14):\n self.courseSchedule[i].append('')\n for i in range(7):\n self.examSchedule.append([])\n for j in range(5):\n self.examSchedule[i].append('')\n\n\nclass Classroom:\n def __init__(self, id, type, container):\n self.id = id\n self.container = container\n self.type = type\n # 8行14列\n self.courseSchedule = []\n # 8行14列\n self.examSchedule = []\n self.time_count = 0\n self.exam_time_count = 0\n self.cmp_type = 0\n for i in range(8):\n self.courseSchedule.append([])\n for j in range(14):\n self.courseSchedule[i].append('')\n for i in range(7):\n self.examSchedule.append([])\n for j in range(5):\n self.examSchedule[i].append('')\n\n def __lt__(self, other): # operator <\n if self.cmp_type == 0:\n return self.time_count < other.time_count\n else:\n return self.exam_time_count < other.exam_time_count\n\n def __ge__(self, other): # oprator >=\n if self.cmp_type == 0:\n return self.time_count >= other.time_count\n else:\n return self.exam_time_count >= other.exam_time_count\n\n def __le__(self, other): # oprator <=\n if self.cmp_type == 0:\n return self.time_count <= other.time_count\n else:\n return self.exam_time_count <= other.exam_time_count\n\n def update_empty_count(self):\n cnt = 0\n for i in range(1, 8):\n for j in range(0, 13):\n time_block = self.courseSchedule[i][j]\n if time_block != '':\n time_block = time_block.split(',')\n for block in time_block:\n l = int(block.split('-')[0])\n r = int(block.split('-')[1])\n cnt += (r - l + 1)\n self.empty_count = cnt\n\n\nclass Teacher(object):\n def __init__(self, id, name):\n self.id = id\n self.name = name\n # 8行14列\n self.courseSchedule = []\n # 8行14列\n self.examSchedule = []\n self.time_count = 0\n self.exam_time_count = 0\n self.cmp_type = 0\n for i in range(8):\n self.courseSchedule.append([])\n self.examSchedule.append([])\n for j in range(14):\n self.courseSchedule[i].append('')\n self.examSchedule[i].append('')\n\n def __lt__(self, other): # operator <\n if self.cmp_type == 0:\n return self.time_count < other.time_count\n else:\n return self.exam_time_count < other.exam_time_count\n\n def __ge__(self, other): # oprator >=\n if self.cmp_type == 0:\n return self.time_count >= other.time_count\n else:\n return self.exam_time_count >= other.exam_time_count\n\n def __le__(self, other): # oprator <=\n if self.cmp_type == 0:\n return self.time_count <= other.time_count\n else:\n return self.exam_time_count <= other.exam_time_count\n\n def update_empty_count(self):\n cnt = 0\n for i in range(1, 8):\n for j in range(0, 13):\n time_block = self.courseSchedule[i][j]\n if time_block != '':\n time_block = time_block.split(',')\n for block in time_block:\n l = int(block.split('-')[0])\n r = int(block.split('-')[1])\n cnt += (r - l + 1)\n self.time_count = cnt\n\n\nclass Buffer(object):\n def __init__(self):\n self.students = []\n self.teachers = []\n self.classrooms = []\n self.course = ''\n self.is_Sc_result = 0\n # 8行14列\n self.courseSchedule = []\n self.examSchedule = []\n for i in range(8):\n self.courseSchedule.append([])\n for j in range(14):\n self.courseSchedule[i].append('')\n for i in range(7):\n self.examSchedule.append([])\n for j in range(5):\n self.examSchedule[i].append('')\n\n\ndef merge_str(str1: str, str2: str):\n str1_split = str1.split(',')\n str2_split = str2.split(',')\n if str1_split[0].__len__() == 0:\n return str2\n if str2_split[0].__len__() == 0:\n return str1\n week_block = np.zeros(21)\n for e in str1_split + str2_split:\n l = int(e.split('-')[0])\n r = int(e.split('-')[1])\n for i in range(l, r + 1):\n week_block[i] = 1\n res = ''\n flag = 0\n l = 0\n r = 0\n for index, e in enumerate(week_block):\n if flag == 0 and e == 1:\n l = index\n r = index\n flag = 1\n if flag == 1 and e == 1:\n r += 1\n if (flag == 1 and e == 0) or (index == len(week_block) - 1 and flag == 1):\n if r > l:\n r -= 1\n flag = 0\n block = str(l) + '-' + str(r)\n if len(res) == 0:\n res += block\n else:\n res += (',' + block)\n return res\n\n\ndef mergeTable(table1, table2):\n global Classrooms_id, Teachers_id, Students_id, Courses_id\n res = []\n for i in range(len(table1)):\n res.append([])\n for j in range(len(table1[i])):\n res[i].append('')\n for i in range(len(table1)):\n for j in range(len(table1[i])):\n res[i][j] = merge_str(table1[i][j], table2[i][j])\n return res\n\n\ncourse_2_96 = [(1, 2), (3, 4), (6, 7), (7, 8)]\ncourse_2 = [(1, 2), (3, 4), (6, 7), (9, 10), (11, 12)]\ncourse_3 = [(1, 3), (3, 5), (6, 8), (8, 10), (11, 13)]\n\n\ndef String_to_table(string1: str):\n res = []\n for i in range(8):\n res.append([])\n for j in range(14):\n res[i].append('')\n for block in string1.split(','):\n block_split = block.split('-')\n week_time = block_split[2] + '-' + block_split[3]\n weekday = int(int(block_split[0]) / 13)\n weekday_start = int(block_split[0]) % 13\n weekday_end = int(block_split[1]) % 13\n if weekday_end == 0:\n weekday_end = 13\n for day in range(weekday_start, weekday_end + 1):\n res[weekday][day] = week_time\n return res\n\n\ndef init(year=2019, semester=2):\n \"目前只有自动排课\"\n set1 = Teacher_Schedule_result.objects.filter(tno__mcno__year=year, tno__mcno__semester=semester)\n print(\"set1\", len(set1), year, semester)\n for elements in set1:\n Table = String_to_table(elements.time)\n if Classrooms_id.get(elements.where.crno) == None:\n room = Classroom(elements.where.crno, elements.where.crtype, elements.where.contain_num)\n room.courseSchedule = Table\n time_occupy_in_other = Classroom_other_schedule.objects.filter(crno=elements.where)\n if len(time_occupy_in_other) > 0:\n for time_block in time_occupy_in_other:\n room.courseSchedule = mergeTable(room.courseSchedule, String_to_table(time_block.time))\n room.update_empty_count()\n Classrooms_id[elements.where.crno] = room\n else:\n room = Classrooms_id.get(elements.where.crno)\n # 这一步可优化\n room.courseSchedule = mergeTable(room.courseSchedule, Table)\n room.update_empty_count()\n if Teachers_id.get(elements.tno.tno.username) == None:\n tcher = Teacher(elements.tno.tno.username, elements.tno.tno.name)\n tcher.courseSchedule = Table\n tcher.update_empty_count()\n Teachers_id[elements.tno.tno.username] = tcher\n else:\n tcher = Teachers_id.get(elements.tno.tno.username)\n tcher.courseSchedule = mergeTable(tcher.courseSchedule, Table)\n tcher.update_empty_count()\n if Courses_id.get(elements.tno.mcno.cno.cno + elements.tno.mcno.mno.major.mname\n + elements.tno.tno.username) == None:\n Courses_id[elements.tno.mcno.cno.cno + elements.tno.mcno.mno.major.mname\n + elements.tno.tno.username] = True\n elements_in_courseSelection = courseSelected.objects.filter(cno=elements)\n for element in elements_in_courseSelection:\n stu_table = String_to_table(element.cno.time)\n if Students_id.get(element.sno.username) == None:\n stu = Students(element.sno.username, element.sno.name,\n element.sno.in_cls.major.major.mname, element.sno.in_year, element.sno.in_cls.name)\n Students_id[element.sno.username] = stu\n stu.courseSchedule = stu_table\n else:\n Students_id[element.sno.username].courseSchedule = mergeTable(\n Students_id[element.sno.username].courseSchedule, stu_table)\n if has_already_scheduled.get(elements.tno.mcno.cno.cno + elements.tno.mcno.mno.major.mname) == None:\n has_already_scheduled[elements.tno.mcno.cno.cno + elements.tno.mcno.mno.major.mname] = True\n print(\"init\", elements.tno.mcno.cno.cno, elements.tno.mcno.cno.cname, elements.tno.mcno.mno.major.mname,\n has_already_scheduled.get(elements.tno.mcno.cno.cno + elements.tno.mcno.mno.major.mname))\n\n set2 = Schedule_result.objects.filter(tno__mcno__year=year, tno__mcno__semester=semester)\n for elements in set2:\n Table = String_to_table(elements.time)\n if Students_id.get(elements.sno.username) == None:\n stu = Students(elements.sno.username, elements.sno.name,\n elements.sno.in_cls.major.major.mname, elements.sno.in_year, elements.sno.in_cls.name)\n Students_id[elements.sno.username] = stu\n stu.courseSchedule = Table\n else:\n Students_id[elements.sno.username].courseSchedule = mergeTable(\n Students_id[elements.sno.username].courseSchedule, Table)\n\n\ndef check_hazard(weekday, daytime, schedule, week_start, week_end):\n st = daytime[0]\n ed = daytime[1] + 1\n for time in range(st, ed):\n string = str(schedule[weekday][time])\n if len(string) == 0:\n continue\n for subtime in string.split(','):\n if (int(subtime.split('-')[0]) <= week_start and week_start <= int(subtime.split('-')[1])) or \\\n (int(subtime.split('-')[0]) <= week_end and week_end <= int(subtime.split('-')[1])):\n return False\n return True\n\n\ndef coures_time_generate(schedule, time):\n res = ''\n if time > 70:\n weektime_base = int(time / 6)\n rest = time % 6\n way1 = 1\n for cnt in range(3):\n weektime_cur = weektime_base\n if cnt == 0:\n if rest > 0:\n rest -= 2\n weektime_cur += 1\n for i, e in enumerate(course_2_96):\n if check_hazard(cnt * 2, e, schedule, 1, weektime_cur):\n if len(res) == 0:\n res += str(e[0] + cnt * 2 * 13) + '-' + str(e[1] + cnt * 2 * 13) + '-' + '1' + '-' + str(\n weektime_cur)\n else:\n res += ',' + str(e[0] + cnt * 2 * 13) + '-' + str(e[1] + cnt * 2 * 13) + '-' + '1' + '-' + str(\n weektime_cur)\n break\n elif i == len(course_2_96) - 1:\n way1 = 0\n break\n if way1 == 1:\n return res\n else:\n res = ''\n for cnt in range(1, 3):\n weektime_cur = weektime_base\n if cnt == 0:\n if rest > 0:\n rest -= 2\n weektime_cur += 1\n for i, e in enumerate(course_3):\n if check_hazard(cnt * 2, e, schedule, 1, weektime_cur):\n if len(res) == 0:\n res += str(e[0] + cnt * 2 * 13) + '-' + str(e[1] + cnt * 2 * 13) + '-' + '1' + '-' + str(\n weektime_cur)\n else:\n res += ',' + str(e[0] + cnt * 2 * 13) + '-' + str(\n e[1] + cnt * 2 * 13) + '-' + '1' + '-' + str(weektime_cur)\n break\n elif i == len(course_3) - 1:\n return None\n return res\n if 56 <= time and time <= 64:\n way1 = 1\n weektime_base = int(time / 4)\n rest = time % 4\n cnt = 0\n for weekday in range(5):\n weektime_cur = weektime_base\n if rest > 0:\n rest -= 2\n weektime_cur += 1\n for i, e in enumerate(course_2_96):\n if check_hazard(weekday, e, schedule, 1, weektime_cur):\n if len(res) == 0:\n res += str(e[0] + weekday * 13) + '-' + str(e[1] + weekday * 13) + '-' + '1' + '-' + str(\n weektime_cur)\n else:\n weekday += 1\n res += ',' + str(e[0] + weekday * 13) + '-' + str(e[1] + weekday * 13) + '-' + '1' + '-' + str(\n weektime_cur)\n cnt += 1\n break\n if cnt == 2:\n return res\n if weekday == 4 and cnt < 2:\n way1 = 0\n break\n if way1 == 0:\n weektime_base = int(time / 6)\n for bias in range(7):\n cnt = 0\n rest = time % 6\n for weekday in range(5):\n weektime_cur = weektime_base\n if rest > 0:\n rest -= 2\n weektime_cur += 1\n if weektime_cur + bias > 17 and cnt < 2:\n return None\n for i, e in enumerate(course_3):\n if check_hazard(weekday, e, schedule, 1 + bias, weektime_cur + bias):\n if len(res) == 0:\n res += str(e[0] + weekday * 13) + '-' + str(e[1] + weekday * 13) + '-' + str(\n 1 + bias) + '-' + str(\n weektime_cur + bias)\n else:\n weekday += 1\n res += ',' + str(e[0] + weekday * 13) + '-' + str(\n e[1] + weekday * 13) + '-' + str(1 + bias) + '-' + str(weektime_cur + bias)\n cnt += 1\n break\n if cnt == 2:\n return res\n if time < 56:\n weektime_base = int(time / 3)\n for bias in range(8):\n rest = time % 3\n cnt = 0\n for weekday in range(5):\n weektime_cur = weektime_base\n if rest > 0:\n rest -= 3\n weektime_cur += 1\n if weektime_cur + bias > 17:\n return None\n for i, e in enumerate(course_3):\n if check_hazard(weekday, e, schedule, 1 + bias, weektime_cur + bias):\n print(schedule)\n print(1 + bias, weektime_cur + bias, '||||||', weekday, e)\n\n if len(res) == 0:\n res += str(e[0] + weekday * 13) + '-' + str(e[1] + weekday * 13) + '-' + str(\n 1 + bias) + '-' + str(\n weektime_cur + bias)\n else:\n weekday += 1\n res += ',' + str(e[0] + weekday * 13) + '-' + str(e[1] + weekday * 13) + '-' + str(\n 1 + bias) + '-' + str(\n weektime_cur + bias)\n print(String_to_table(res))\n cnt += 1\n break\n if cnt == 1:\n return res\n\n\ndef write_to_database(res: str, bf: Buffer):\n # 字符串 合并到表可进一步优化\n tno_mno = original_Teaching.objects.get(mcno=bf.course, tno__username=bf.teachers[0])\n cur_num = 0\n ctype = tno_mno.mcno.cno.course_type\n if '必修' in ctype or bf.is_Sc_result == 1:\n cur_num = len(bf.students)\n print(res)\n TSr = Teacher_Schedule_result.objects.create(\n tno=tno_mno,\n where=ClassRoom.objects.get(crno=bf.classrooms[0]),\n time=res,\n current_number=cur_num,\n MAX_number=len(bf.students),\n state=ctype,\n )\n table = String_to_table(res)\n Teachers_id.get(bf.teachers[0]).courseSchedule = mergeTable(Teachers_id.get(bf.teachers[0]).courseSchedule, table)\n Classrooms_id.get(bf.classrooms[0]).courseSchedule = mergeTable(Classrooms_id.get(bf.classrooms[0]).courseSchedule,\n table)\n Teachers_id.get(bf.teachers[0]).time_count += tno_mno.mcno.hour_total\n Classrooms_id.get(bf.classrooms[0]).time_count += tno_mno.mcno.hour_total\n TSr.save()\n if \"选修\" in ctype:\n for sno in bf.students:\n Students_id.get(sno).courseSchedule = mergeTable(Students_id.get(sno).courseSchedule, table)\n print('--------------------------------------')\n print(table)\n if '必修' in ctype or bf.is_Sc_result == 1:\n for sno in bf.students:\n Sr = Schedule_result.objects.create(\n sno=Student.objects.get(username=sno),\n tno=tno_mno,\n where=ClassRoom.objects.get(crno=bf.classrooms[0]),\n time=res,\n )\n Sr.save()\n Students_id.get(sno).courseSchedule = mergeTable(Students_id.get(sno).courseSchedule, table)\n\n\ndef distribute_single(bf: Buffer, room: Classroom, tch: Teacher, course):\n bf.courseSchedule = mergeTable(tch.courseSchedule, bf.courseSchedule)\n bf.courseSchedule = mergeTable(room.courseSchedule, bf.courseSchedule)\n bf.teachers.append(tch.id)\n bf.classrooms.append(room.id)\n res = coures_time_generate(bf.courseSchedule, course.hour_total)\n print(course.hour_total)\n write_to_database(res, bf)\n\n\ndef autoSchedule(yy=2019, smt=2):\n year = yy\n semester = smt\n init(yy, smt)\n # 1找课 2找老师 3找学生 4找教室 5生成并检查 6写入数据库\n heap_bigroom = []\n heap_midroom = []\n heap_smallroom = []\n room_set = ClassRoom.objects.all()\n for elements in room_set:\n if Classrooms_id.get(elements.crno) == None:\n Classrooms_id[elements.crno] = Classroom(elements.crno, elements.crtype, elements.contain_num)\n if Classrooms_id[elements.crno].type == '大':\n heapq.heappush(heap_bigroom, Classrooms_id[elements.crno])\n if Classrooms_id[elements.crno].type == '中':\n heapq.heappush(heap_midroom, Classrooms_id[elements.crno])\n if Classrooms_id[elements.crno].type == '小':\n heapq.heappush(heap_smallroom, Classrooms_id[elements.crno])\n coures_set = MajorCourses.objects.filter(year=year, semester=semester)\n for course in coures_set:\n print(course.cno.cno, course.cno.cname, course.mno.major.mname,\n has_already_scheduled.get(course.cno.cno + course.mno.major.mname))\n if has_already_scheduled.get(course.cno.cno + course.mno.major.mname) == True:\n continue\n teacher_set = original_Teaching.objects.filter(mcno__cno__cno=course.cno.cno)\n heap_teacher = []\n # 教师建堆\n for elements in teacher_set:\n if Teachers_id.get(elements.tno.username) == None:\n tcher = Teacher(elements.tno.username, elements.tno.name)\n tcher.update_empty_count()\n Teachers_id[elements.tno.username] = tcher\n heapq.heappush(heap_teacher, tcher)\n else:\n heapq.heappush(heap_teacher, Teachers_id.get(elements.tno.username))\n students_set = Student.objects.filter(in_cls__major=course.mno)\n bf = Buffer()\n bf.course = course\n if len(students_set) > 200:\n class_dic = dict()\n stu_cnt = 0\n for elements in students_set:\n stu = None\n if Students_id.get(elements.username) == None:\n stu = Students(elements.username, elements.name,\n elements.in_cls.major.major.mname, elements.sno.in_year, elements.sno.in_cls.name)\n Students_id[elements.sno.username] = stu\n else:\n stu = Students_id.get(elements.username)\n # 人数达上限分配教师、地点、重置Buffer\n # class_dic班级字典\n if (class_dic.get(stu.in_cls) == None and len(class_dic) == 6) or stu_cnt >= 195:\n teacher = heap_teacher[0]\n bf.courseSchedule = mergeTable(teacher.courseSchedule, bf.courseSchedule)\n bf.teachers.append(teacher.id)\n classroom = heap_bigroom[0]\n bf.courseSchedule = mergeTable(classroom.courseSchedule, bf.courseSchedule)\n bf.classrooms.append(classroom.id)\n res = coures_time_generate(bf.courseSchedule, course.hour_total)\n write_to_database(res, bf)\n # 重置 计数\n bf = Buffer()\n bf.courseSchedule = mergeTable(stu.courseSchedule, bf.courseSchedule)\n class_dic = dict()\n class_dic[stu.in_cls] = 1\n stu_cnt = 1\n # 更新堆\n heapq.heapify(heap_teacher)\n heapq.heapify(classroom)\n else: # 累计\n bf.courseSchedule = mergeTable(stu.courseSchedule, bf.courseSchedule)\n bf.students.append(stu.id)\n class_dic[stu.in_cls] = 1\n stu_cnt += 1\n if len(bf.students) <= 50:\n distribute_single(bf, heap_smallroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_smallroom)\n elif len(bf.students) >= 50 and len(bf.students) <= 120:\n distribute_single(bf, heap_midroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_midroom)\n else:\n distribute_single(bf, heap_bigroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_bigroom)\n # 重置 bf\n elif len(students_set) <= 200 and len(students_set) > 120:\n for elements in students_set:\n if Students_id.get(elements.username) == None:\n stu = Students(elements.username, elements.username,\n elements.in_cls.major.major.mname, elements.in_year, elements.in_cls.name)\n Students_id[elements.username] = stu\n else:\n stu = Students_id.get(elements.username)\n bf.courseSchedule = mergeTable(stu.courseSchedule, bf.courseSchedule)\n bf.students.append(stu.id)\n # print(heap_bigroom, '----', heap_teacher)\n distribute_single(bf, heap_bigroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_bigroom)\n elif len(students_set) <= 120 and len(students_set) > 50:\n for elements in students_set:\n if Students_id.get(elements.username) == None:\n stu = Students(elements.username, elements.username,\n elements.in_cls.major.major.mname, elements.in_year, elements.in_cls.name)\n Students_id[elements.sno.username] = stu\n else:\n stu = Students_id.get(elements.username)\n bf.courseSchedule = mergeTable(stu.courseSchedule, bf.courseSchedule)\n bf.students.append(stu.id)\n distribute_single(bf, heap_midroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_midroom)\n elif len(bf.students) <= 50:\n for elements in students_set:\n if Students_id.get(elements.username) == None:\n stu = Students(elements.username, elements.username,\n elements.in_cls.major.major.mname, elements.in_year, elements.in_cls.name)\n Students_id[elements.sno.username] = stu\n else:\n stu = Students_id.get(elements.username)\n bf.courseSchedule = mergeTable(stu.courseSchedule, bf.courseSchedule)\n bf.students.append(stu.id)\n distribute_single(bf, heap_smallroom[0], heap_teacher[0], course)\n heapq.heapify(heap_teacher)\n heapq.heapify(heap_smallroom)\n has_already_scheduled[course.cno.cno + course.mno.major.mname] = True\n\n\n# ---------------------\n# 自动排考试时间\n\"\"\"\n1.手动排课(排一些没有排好的课,属于教学活动)\n2.查询教室:学生、老师---查询。管理员查+改(添加临时活动1-2,一个上午)。\n3.生成课表---》初步的课表---》选课加入课表\n\"\"\"\n\n\n# ----------------------------\n# 按地点查空闲:\ndef Search_spare_room(name: str):\n cls = ClassRoom.objects.get(crno=name)\n classroom = Classroom(cls.crno, cls.crtype, cls.contain_num)\n time_occupy_in_Teaching = Teacher_Schedule_result.objects.filter(where__crno=name)\n for element in time_occupy_in_Teaching:\n classroom.courseSchedule = mergeTable(classroom.courseSchedule, String_to_table(element.time))\n time_occupy_in_other = Classroom_other_schedule.objects.filter(crno__crno=name)\n for element in time_occupy_in_other:\n classroom.courseSchedule = mergeTable(classroom.courseSchedule, String_to_table(element.time))\n Classrooms_id[name] = classroom\n return classroom\n\n\n# 搜索目标房间名的时间空闲:\ndef Search_spare_room(name: str) -> Classroom:\n cls = ClassRoom.objects.get(crno=name)\n classroom = Classroom(cls.crno, cls.crtype, cls.contain_num)\n time_occupy_in_Teaching = Teacher_Schedule_result.objects.filter(where__crno=name)\n for element in time_occupy_in_Teaching:\n classroom.courseSchedule = mergeTable(classroom.courseSchedule, String_to_table(element.time))\n time_occupy_in_other = Classroom_other_schedule.objects.filter(crno__crno=name)\n for element in time_occupy_in_other:\n classroom.courseSchedule = mergeTable(classroom.courseSchedule, String_to_table(element.time))\n Classrooms_id[name] = classroom\n return classroom\n\n\n# 搜索时间空闲的房间:\ndef init_room():\n \"初始化房间\"\n set1 = Teacher_Schedule_result.objects.filter(tno__mcno__year=year, tno__mcno__semester=semester)\n for elements in set1:\n Table = String_to_table(elements.time)\n if Classrooms_id.get(elements.where.crno) == None:\n room = Classroom(elements.where.crno, elements.where.crtype, elements.where.contain_num)\n room.courseSchedule = Table\n time_occupy_in_other = Classroom_other_schedule.objects.filter(crno=elements.where)\n if len(time_occupy_in_other) > 0:\n for time_block in time_occupy_in_other:\n room.courseSchedule = mergeTable(room.courseSchedule, String_to_table(time_block.time))\n room.update_empty_count()\n Classrooms_id[elements.where.crno] = room\n else:\n room = Classrooms_id.get(elements.where.crno)\n # 这一步可优化\n room.courseSchedule = mergeTable(room.courseSchedule, Table)\n room.update_empty_count()\n set1 = ClassRoom.objects.all()\n for elements in set1:\n if Classrooms_id.get(elements.crno) == None:\n room = Classroom(elements.crno, elements.crtype, elements.contain_num)\n Classrooms_id[room.id] = room\n\n\ndef week_has_hazzard(week1: str, week2: str):\n if len(week1) == 0 or len(week2) == 0:\n return False\n l1 = int(week1.split('-')[0])\n r1 = int(week1.split('-')[1])\n l2 = int(week2.split('-')[0])\n r2 = int(week2.split('-')[1])\n # print(l1,r1,l2,r2)\n if (l2 <= l1 and l1 <= r2) or (l1 <= l2 and l2 <= r1):\n return True\n else:\n return False\n\n\ndef has_table_hazzard(table1, table2):\n for i in range(8):\n for j in range(14):\n if j == 0: continue\n if week_has_hazzard(table1[i][j], table2[i][j]):\n return True\n return False\n\n\ndef Search_time_room(time: str):\n init_room()\n res = []\n table = String_to_table(time)\n for element in Classrooms_id:\n # print(Classrooms_id[element].id)\n room = Classrooms_id[element]\n if has_table_hazzard(room.courseSchedule, table):\n continue\n else:\n res.append({\n 'type': room.type,\n 'id': room.id,\n 'container': room.container,\n })\n return res\n\n\n# 添加临时活动\ndef add_active(time: str, room: str, state: str):\n init_room()\n new_table = String_to_table(time)\n if Classrooms_id.get(room) == None:\n return False\n else:\n tag_room = Classrooms_id[room]\n if has_table_hazzard(new_table, tag_room.courseSchedule):\n return False\n else:\n new_row = Classroom_other_schedule.objects.create(\n crno=ClassRoom.objects.get(crno=room),\n time=time,\n statement=state,\n )\n new_row.save()\n return True\n\n\ndef get_students_teacher_courseSchedule(stuset: [], class_set=None, teacher_username=None) -> Buffer:\n if teacher_username == None:\n return None\n init()\n bf = Buffer()\n if class_set == None:\n for element in stuset:\n stud = None\n if Students_id.get(element) == None:\n stu = Student.objects.get(username=element)\n stud = Students(stu.username, stu.name, stu.in_cls.major, stu.in_year, stu.in_cls.name)\n Students_id[stu.username] = stud\n else:\n stud = Students_id[element]\n bf.courseSchedule = mergeTable(bf.courseSchedule, stud.courseSchedule)\n if Teachers_id[teacher_username] != None:\n bf.courseSchedule = mergeTable(bf.courseSchedule, Teachers_id[teacher_username].courseSchedule)\n return bf\n else:\n bf = Buffer()\n for in_class in class_set:\n stu_set = Student.objects.filter(in_cls__name=in_class)\n for element in stu_set:\n stud = None\n if Students_id.get(element) == None:\n stu = Student.objects.get(username=element)\n stud = Students(stu.username, stu.name, stu.in_cls.major, stu.in_year, stu.in_cls.name)\n Students_id[stu.username] = stud\n else:\n stud = Students_id[element]\n bf.courseSchedule = mergeTable(bf.courseSchedule, stud.courseSchedule)\n if Teachers_id[teacher_username] != None:\n bf.courseSchedule = mergeTable(bf.courseSchedule, Teachers_id[teacher_username].courseSchedule)\n return bf\n\n\n# 处理手工排课\ndef manual_schedule(time_string, place_name, stuset: [], class_set=[], teacher_username=None, course=''):\n if class_set == None or len(class_set) == 0:\n init()\n bf = Buffer()\n bf.is_Sc_result = 1\n tmp = original_Teaching.objects.filter(mcno__cno__cno=course, tno__username=teacher_username)[0]\n bf.course = tmp.mcno\n if Classrooms_id.get(place_name) == None:\n room = ClassRoom.objects.get(crno=place_name)\n Classrooms_id[place_name] = Classroom(place_name, room.crtype, room.contain_num)\n bf.courseSchedule = mergeTable(Classrooms_id[place_name].courseSchedule, bf.courseSchedule)\n bf.classrooms.append(place_name)\n for stu_sno in stuset:\n bf.students.append(stu_sno)\n if Students_id.get(stu_sno) == None:\n stu = Student.objects.get(username=stu_sno)\n stu_ob = Students(stu.username, stu.name, stu.in_cls.major.major.mname,\n stu.in_year, stu.in_cls.name)\n Students_id[stu_sno] = stu_ob\n else:\n bf.courseSchedule = mergeTable(Students_id[stu_sno].courseSchedule, bf.courseSchedule)\n bf.teachers.append(teacher_username)\n if teacher_username != None:\n bf.courseSchedule = mergeTable(bf.courseSchedule, Teachers_id[teacher_username].courseSchedule)\n table = String_to_table(time_string)\n print(table)\n print(bf.courseSchedule)\n if has_table_hazzard(table, bf.courseSchedule) == False:\n write_to_database(time_string, bf)\n return True\n else:\n return False\n else:\n pass\n\n\n# 排考试时间\ndef String_to_examTable(string: str):\n res = []\n for i in range(7):\n res.append([])\n for j in range(5):\n res[i].append('')\n res[int(string.split('-')[0])][int(string.split('-')[1])] = '20-20'\n return res\n\n\ndef init_exam(year=2019, semester=2):\n rows_in_exam = Exam_Schedule.objects.filter(tno_mno_course__tno__mcno__year=year,\n tno_mno_course__tno__mcno__semester=semester)\n for element in rows_in_exam:\n if Students_id.get(element.sno.username) == None:\n stu = Students(element.sno.username, element.sno.name,\n element.sno.in_cls.major.major.mno, element.sno.in_year, element.sno.in_cls.name)\n stu.examSchedule = String_to_examTable(element.time)\n Students_id[element.sno.username] = stu\n else:\n Students_id[element.sno.username].examSchedule = mergeTable(Students_id[element.sno.username].examSchedule,\n String_to_examTable(element.time))\n if Classrooms_id.get(element.where) == None:\n room = Classroom(element.where.crno, element.where.crtype, element.where.contain_num)\n room.examSchedule = String_to_examTable(element.time)\n Classrooms_id[element.where.crno] = room\n else:\n Classrooms_id[element.where].examSchedule = mergeTable(Classrooms_id[element.where].examSchedule,\n String_to_examTable(element.time))\n\n\ndef exam_time_generate(bf: Buffer):\n cnt = 0\n for i in range(7):\n for j in range(5):\n if cnt > 0:\n cnt -= 1\n continue\n if bf.examSchedule[i][j] != '':\n if j + 2 <= 4:\n cnt = 2\n elif j + 2 >= 5:\n break\n else:\n return str(i) + '-' + str(j)\n\n\ndef exam_schedule(year=2019, semester=2):\n init(year, semester)\n init_exam(year, semester)\n for e in Classrooms_id:\n Classrooms_id[e].cmp_type = 1\n heap_bigroom = []\n heap_midroom = []\n heap_smallroom = []\n room_set = ClassRoom.objects.all()\n for elements in room_set:\n if Classrooms_id.get(elements.crno) == None:\n Classrooms_id[elements.crno] = Classroom(elements.crno, elements.crtype, elements.contain_num)\n if Classrooms_id[elements.crno].type == '大':\n heapq.heappush(heap_bigroom, Classrooms_id[elements.crno])\n if Classrooms_id[elements.crno].type == '中':\n heapq.heappush(heap_midroom, Classrooms_id[elements.crno])\n if Classrooms_id[elements.crno].type == '小':\n heapq.heappush(heap_smallroom, Classrooms_id[elements.crno])\n exam_set = Teacher_Schedule_result.objects.filter(tno__mcno__year=year, tno__mcno__semester=semester)\n for course in exam_set:\n if '必修' in course.tno.mcno.cno.course_type:\n if course.current_number >= 165: # 三个大教室\n target_cnt = int(course.current_number / 3)\n cnt_room = 0\n students_set = Schedule_result.objects.filter(tno=course.tno, time=course.time, where=course.where)\n bf = Buffer()\n for element in students_set:\n if target_cnt - 1 < 0:\n # 分配时间、地点判断生成的时间冲突\n room = heap_bigroom[0]\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.examSchedule = mergeTable(room.examSchedule, bf.examSchedule)\n bf.classrooms.append(room)\n res = exam_time_generate(bf)\n exam_write_to_database(bf, course, res)\n room.exam_time_count += 1\n heapq.heapify(heap_bigroom)\n bf = Buffer()\n if cnt_room + 1 == 3:\n cnt_room += 1\n target_cnt = course.current_number - int(course.current_number / 3) * 2\n else:\n target_cnt = int(course.current_number / 3)\n else:\n target_cnt -= 1\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.students.append(element.sno.username)\n\n elif course.current_number < 165 and course.current_number >= 100: # 两个大教室\n target_cnt = int(course.current_number / 2)\n cnt_room = 0\n students_set = Schedule_result.objects.filter(tno=course.tno, time=course.time, where=course.where)\n bf = Buffer()\n for element in students_set:\n if target_cnt - 1 < 0:\n # 分配时间、地点判断生成的时间冲突\n room = heap_bigroom[0]\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.examSchedule = mergeTable(room.examSchedule, bf.examSchedule)\n bf.classrooms.append(room)\n res = exam_time_generate(bf)\n exam_write_to_database(bf, course, res)\n room.exam_time_count += 1\n heapq.heapify(heap_bigroom)\n bf = Buffer()\n if cnt_room + 1 == 2:\n cnt_room += 1\n target_cnt = course.current_number - int(course.current_number / 2)\n else:\n target_cnt = int(course.current_number / 2)\n else:\n target_cnt -= 1\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.students.append(element.sno.username)\n elif course.current_number < 100 and course.current_number >= 80: # 两个中教室\n target_cnt = int(course.current_number / 2)\n cnt_room = 0\n students_set = Schedule_result.objects.filter(tno=course.tno, time=course.time, where=course.where)\n bf = Buffer()\n for element in students_set:\n if target_cnt - 1 < 0:\n # 分配时间、地点判断生成的时间冲突\n room = heap_midroom[0]\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.examSchedule = mergeTable(room.examSchedule, bf.examSchedule)\n bf.classrooms.append(room)\n res = exam_time_generate(bf)\n exam_write_to_database(bf, course, res)\n room.exam_time_count += 1\n heapq.heapify(heap_midroom)\n bf = Buffer()\n if cnt_room + 1 == 2:\n cnt_room += 1\n target_cnt = course.current_number - int(course.current_number / 2)\n else:\n target_cnt = int(course.current_number / 2)\n else:\n target_cnt -= 1\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.students.append(element.sno.username)\n elif course.current_number < 80 and course.current_number >= 25: # 一个中教室\n target_cnt = course.current_number\n students_set = Schedule_result.objects.filter(tno=course.tno, time=course.time, where=course.where)\n bf = Buffer()\n for element in students_set:\n if target_cnt - 1 < 0:\n # 分配时间、地点判断生成的时间冲突\n room = heap_midroom[0]\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.examSchedule = mergeTable(room.examSchedule, bf.examSchedule)\n bf.classrooms.append(room)\n res = exam_time_generate(bf)\n exam_write_to_database(bf, course, res)\n room.exam_time_count += 1\n heapq.heapify(heap_midroom)\n else:\n target_cnt -= 1\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.students.append(element.sno.username)\n elif course.current_number <= 25: # 一个小教室\n target_cnt = course.current_number\n students_set = Schedule_result.objects.filter(tno=course.tno, time=course.time, where=course.where)\n bf = Buffer()\n for element in students_set:\n if target_cnt - 1 < 0:\n # 分配时间、地点判断生成的时间冲突\n room = heap_smallroom[0]\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.examSchedule = mergeTable(room.examSchedule, bf.examSchedule)\n bf.classrooms.append(room)\n res = exam_time_generate(bf)\n exam_write_to_database(bf, course, res)\n room.exam_time_count += 1\n heapq.heapify(heap_smallroom)\n else:\n target_cnt -= 1\n bf.examSchedule = mergeTable(bf.examSchedule, Students_id[element.sno.username].examSchedule)\n bf.students.append(element.sno.username)\n\n\ndef exam_write_to_database(bf: Buffer, course, res: str):\n for element in bf.students:\n row = Exam_Schedule.objects.create(\n sno=Student.objects.get(username=element),\n tno_mno_course=course,\n time=res,\n where=ClassRoom.objects.get(crno=bf.classrooms[0].id)\n )\n row.save()\n Students_id.get(element).examSchedule[int(res.split('-')[0])][int(res.split('-')[1])] = '20-20'\n\n\n# 查询考试时间view里\ndef search_exam_time(stu_username: str):\n pass\n\n\nif __name__ == '__main__':\n # autoSchedule()\n exam_schedule()\n # Sycho()\n # 手工排\n # 以上在管理员的排课界面\n\n # 查询空闲教室页面 学生教师只能看\n # 管理员看+占用空闲教室 ssss('时间段,16-18-14-15','地点','陈述') 返回是否加入成功\n\n # 仅学生可以看自己的考试时间表\n\n # bf = get_students_teacher_courseSchedule(['2016000474', '2016000475', '2016000476', '2016000477'], teacher_username='198500038', )\n # Search_time_room()\n # print('-----------------')\n # print(bf.courseSchedule)\n # fff = Search_time_room(\"14-16-1-1,27-29-8-8\")\n # False print(manual_schedule('16-18-14-15', 'A-202', ['2016000474', '2016000475', '2016000476', '2016000477'], [], '199000064', 'CSE14302C'))\n # print(manual_schedule('14-15-17-18', 'A-202', ['2016000474', '2016000475', '2016000476', '2016000477'], [], '199000064', 'CSE14302C'))\n # print(add_active(\"3-3-11-12\", \"阶A-202\", \"exam\"))\n a = 1\n"
]
| [
[
"numpy.zeros"
]
]
|
AmurG/SPFlow | [
"ab28dd4af9ed722ace69c6b290cf0a279bbda39e"
]
| [
"src/spn/structure/prometheus/data.py"
]
| [
"# Some helper functions to make the entire thing run\nimport spn.structure.prometheus.nodes\nimport math\nimport numpy as np\nimport scipy\nimport scipy.cluster.hierarchy as hcluster\nfrom scipy.cluster.vq import vq, kmeans, whiten\n\n# Converts array indices from function-level indices to global-level objective indices. For example, consider the set [0,1,2,3] and suppose you have passed the [1,3]'s into a call. They will be treated as [0,1] and you will convert them back.\n# The usage of the set functionality slows up the implementation a bit and\n# is not strictly necessary. However, it's a good idea to keep them this\n# way since this simplifies the code.\n\n\ndef eff(tempdat, scope):\n effdat = np.copy(tempdat[:, sorted(list(scope))])\n return effdat\n\n\ndef returnarr(arr, scope):\n q = []\n te = sorted(list(scope))\n for i in arr:\n q.append(te[i])\n return set(q)\n\n\ndef split(arr, k, scope):\n pholder, clusters = scipy.cluster.vq.kmeans2(\n arr[:, sorted(list(scope))], k, minit='points')\n big = []\n for i in range(0, len(set(clusters))):\n mask = np.where(clusters == i)\n print(np.shape(mask))\n mask = np.asarray(mask, dtype=np.int32)\n mask = mask.flatten()\n small = (arr[mask, :])\n print(np.shape(small))\n big.append(small)\n print(big)\n return big\n\n\ndef submat(mat, subset):\n ret = np.copy(mat[:, sorted(list(subset))])\n return ret[sorted(list(subset)), :]\n\n\ndef submean(mean, subset):\n m = np.copy(mean[sorted(list(subset))])\n return m\n"
]
| [
[
"numpy.where",
"numpy.asarray",
"numpy.shape"
]
]
|
rdacomp/pysc2 | [
"d1e7700762723e1ad55bcea4dbb5cc95bcf86e65"
]
| [
"pysc2/lib/renderer_human.py"
]
| [
"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"A viewer for starcraft observations/replays.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport itertools\nimport logging\nimport math\nimport threading\nimport time\n\nimport enum\nfrom future.builtins import range # pylint: disable=redefined-builtin\nimport numpy as np\nimport pygame\nfrom six.moves import queue\nfrom pysc2.lib import colors\nfrom pysc2.lib import features\nfrom pysc2.lib import point\nfrom pysc2.lib import remote_controller\nfrom pysc2.lib import stopwatch\nfrom pysc2.lib import transform\n\nfrom s2clientprotocol import data_pb2 as sc_data\nfrom s2clientprotocol import sc2api_pb2 as sc_pb\nfrom s2clientprotocol import spatial_pb2 as sc_spatial\n\nsw = stopwatch.sw\n\nrender_lock = threading.Lock() # Serialize all window/render operations.\nobs_lock = threading.Lock() # Protect the observations.\n\n\ndef with_lock(lock):\n \"\"\"Make sure the lock is held while in this function.\"\"\"\n def decorator(func):\n @functools.wraps(func)\n def _with_lock(*args, **kwargs):\n with lock:\n return func(*args, **kwargs)\n return _with_lock\n return decorator\n\n\ndef clamp(n, smallest, largest):\n return max(smallest, min(n, largest))\n\n\nclass MouseButtons(object):\n LEFT = 1\n MIDDLE = 2\n RIGHT = 3\n WHEEL_UP = 4\n WHEEL_DOWN = 5\n\n\nclass SurfType(enum.Enum):\n \"\"\"Used to tell what a mouse click refers to.\"\"\"\n CHROME = 1 # ie help, feature layer titles, etc\n SCREEN = 2\n MINIMAP = 3\n\n\nclass ActionCmd(enum.Enum):\n STEP = 1\n RESTART = 2\n QUIT = 3\n\n\nclass _Surface(object):\n \"\"\"A surface to display on screen.\"\"\"\n\n def __init__(self, surf, surf_type, surf_rect, world_to_surf, draw):\n \"\"\"A surface to display on screen.\n\n Args:\n surf: The actual pygame.Surface (or subsurface).\n surf_type: A SurfType, used to tell how to treat clicks in that area.\n surf_rect: Rect of the surface relative to the window.\n world_to_surf: Convert a point relative to the surface to a world point.\n draw: A function that draws onto the surface.\n \"\"\"\n self.surf = surf\n self.surf_type = surf_type\n self.surf_rect = surf_rect\n self.world_to_surf = world_to_surf\n self.draw = draw\n\n def draw_circle(self, color, world_loc, world_radius, thickness=0):\n \"\"\"Draw a circle using world coordinates and radius.\"\"\"\n pygame.draw.circle(self.surf, color,\n self.world_to_surf.fwd_pt(world_loc).floor(),\n int(self.world_to_surf.fwd_dist(world_radius)),\n thickness)\n\n def draw_rect(self, color, world_rect, thickness=0):\n \"\"\"Draw a rectangle using world coordinates.\"\"\"\n tl = self.world_to_surf.fwd_pt(world_rect.tl).floor()\n br = self.world_to_surf.fwd_pt(world_rect.br).floor()\n rect = pygame.Rect(tl, br - tl)\n pygame.draw.rect(self.surf, color, rect, thickness)\n\n def blit_np_array(self, array):\n \"\"\"Fill this surface using the contents of a numpy array.\"\"\"\n with sw(\"make_surface\"):\n raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2]))\n with sw(\"draw\"):\n pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)\n\n\nclass MousePos(collections.namedtuple(\"MousePos\", [\"pos\", \"type\"])):\n \"\"\"Holds the mouse position in world coordinates and a SurfType.\"\"\"\n __slots__ = ()\n\n\nmax_window_size = None\ndef _get_max_window_size(): # pylint: disable=g-wrong-blank-lines\n global max_window_size\n if max_window_size is None:\n display_info = pygame.display.Info()\n desktop_size = point.Point(display_info.current_w, display_info.current_h)\n max_window_size = desktop_size * 0.75\n return max_window_size\n\n\ndef circle_mask(shape, pt, radius):\n # ogrid is confusing but seems to be the best way to generate a circle mask.\n # http://docs.scipy.org/doc/numpy/reference/generated/numpy.ogrid.html\n # http://stackoverflow.com/questions/8647024/how-to-apply-a-disc-shaped-mask-to-a-numpy-array\n y, x = np.ogrid[-pt.y:shape.y - pt.y, -pt.x:shape.x - pt.x]\n # <= is important as radius will often come in as 0 due to rounding.\n return x**2 + y**2 <= radius**2\n\n\nclass RendererHuman(object):\n \"\"\"Render starcraft obs with pygame such that it's playable by humans.\"\"\"\n camera_actions = { # camera moves by 3 world units.\n pygame.K_LEFT: point.Point(-3, 0),\n pygame.K_RIGHT: point.Point(3, 0),\n pygame.K_UP: point.Point(0, 3),\n pygame.K_DOWN: point.Point(0, -3),\n }\n\n shortcuts = [\n (\"F4\", \"Quit the game\"),\n (\"F5\", \"Restart the map\"),\n (\"F8\", \"Toggle synchronous rendering\"),\n (\"F9\", \"Save a replay\"),\n (\"Ctrl++\", \"Zoom in\"),\n (\"Ctrl+-\", \"Zoom out\"),\n (\"PgUp/PgDn\", \"Increase/decrease the max game speed\"),\n (\"Ctrl+PgUp/PgDn\", \"Increase/decrease the step multiplier\"),\n (\"Pause\", \"Pause the game\"),\n (\"?\", \"This help screen\"),\n ]\n\n def __init__(self, fps=22.4, step_mul=1, render_sync=False):\n \"\"\"Create a renderer for use by humans.\n\n Make sure to call `init` with the game info, or just use `run`.\n\n Args:\n fps: How fast should the game be run.\n step_mul: How many game steps to take per observation.\n render_sync: Whether to wait for the obs to render before continuing.\n \"\"\"\n self._fps = fps\n self._step_mul = step_mul\n self._render_sync = render_sync\n self._obs_queue = queue.Queue()\n self._render_thread = threading.Thread(target=self.render_thread,\n name=\"Renderer\")\n self._render_thread.start()\n self._game_times = collections.deque(maxlen=100) # Avg FPS over 100 frames.\n self._render_times = collections.deque(maxlen=100)\n self._last_time = time.time()\n self._last_game_loop = 0\n self._name_lengths = {}\n\n def close(self):\n if self._obs_queue:\n self._obs_queue.put(None)\n self._render_thread.join()\n self._obs_queue = None\n self._render_thread = None\n\n def init(self, game_info, static_data):\n \"\"\"Take the game info and the static data needed to set up the game.\n\n This must be called before render or get_actions for each game or restart.\n\n Args:\n game_info: A `sc_pb.ResponseGameInfo` object for this game.\n static_data: A `StaticData` object for this game.\n \"\"\"\n self._game_info = game_info\n self._static_data = static_data\n self._map_size = point.Point.build(game_info.start_raw.map_size)\n fl_opts = game_info.options.feature_layer\n self._feature_layer_screen_size = point.Point.build(fl_opts.resolution)\n self._feature_layer_minimap_size = point.Point.build(\n fl_opts.minimap_resolution)\n self._camera_width_world_units = fl_opts.width\n try:\n self.init_window()\n self._initialized = True\n except pygame.error as e:\n self._initialized = False\n logging.error(\"-\" * 60)\n logging.error(\"Failed to initialize pygame: %s\", e)\n logging.error(\"Continuing without pygame.\")\n logging.error(\"If you're using ssh and have an X server, try ssh -X.\")\n logging.error(\"-\" * 60)\n\n self._obs = sc_pb.ResponseObservation()\n self.queued_action = None\n self.queued_hotkey = \"\"\n self.select_start = None\n self.help = False\n\n @with_lock(render_lock)\n @sw.decorate\n def init_window(self):\n \"\"\"Initialize the pygame window and lay out the surfaces.\"\"\"\n pygame.init()\n\n # Want a roughly square grid of feature layers, each being roughly square.\n num_feature_layers = (len(features.SCREEN_FEATURES) +\n len(features.MINIMAP_FEATURES))\n cols = math.ceil(math.sqrt(num_feature_layers))\n rows = math.ceil(num_feature_layers / cols)\n features_layout = point.Point(cols, rows * 1.05) # make room for titles\n\n # Scale such that features_layout and screen_aspect ratio have the same\n # height so that we can figure out the max window size and ratio of widths.\n screen_aspect_ratio = (self._feature_layer_screen_size *\n (rows / self._feature_layer_screen_size.y))\n total = features_layout + point.Point(screen_aspect_ratio.x, 0)\n window_size_px = total.scale_max_size(_get_max_window_size()).ceil()\n\n # Create the actual window surface. This should only be blitted to from one\n # of the sub-surfaces defined below.\n self._window = pygame.display.set_mode(window_size_px)\n pygame.display.set_caption(\"Starcraft Viewer\")\n\n # The sub-surfaces that the various draw functions will draw to.\n self.surfaces = []\n def add_surface(surf_type, surf_loc, world_to_surf, draw_fn):\n \"\"\"Add a surface. Drawn in order and intersect in reverse order.\"\"\"\n sub_surf = self._window.subsurface(\n pygame.Rect(surf_loc.tl, surf_loc.size))\n self.surfaces.append(_Surface(\n sub_surf, surf_type, surf_loc, world_to_surf, draw_fn))\n\n self.scale = window_size_px.y // 30\n self.font_small = pygame.font.Font(None, int(self.scale * 0.5))\n self.font_large = pygame.font.Font(None, self.scale)\n\n # Just flip so the base minimap is TL origin\n self._world_to_minimap = transform.Linear(point.Point(1, -1),\n point.Point(0, self._map_size.y))\n self._minimap_to_fl_minimap = transform.Linear(\n self._feature_layer_minimap_size / self._map_size)\n self._world_to_fl_minimap = transform.Chain(\n self._world_to_minimap,\n self._minimap_to_fl_minimap,\n transform.Floor())\n\n # Flip and zoom to the camera area. Update the offset as the camera moves.\n self._world_to_screen = transform.Linear(point.Point(1, -1),\n point.Point(0, self._map_size.y))\n self._screen_to_fl_screen = transform.Linear(\n self._feature_layer_screen_size / self._camera_width_world_units)\n self._world_to_fl_screen = transform.Chain(\n self._world_to_screen,\n self._screen_to_fl_screen,\n transform.Floor())\n\n # Renderable space for the screen.\n self.screen_size_px = self._feature_layer_screen_size.scale_max_size(\n window_size_px)\n screen_to_visual_screen = transform.Linear(\n self.screen_size_px.x / self._camera_width_world_units)\n add_surface(SurfType.SCREEN,\n point.Rect(point.origin, self.screen_size_px),\n transform.Chain(\n self._world_to_screen,\n screen_to_visual_screen),\n self.draw_screen)\n\n # Renderable space for the minimap.\n self.minimap_size_px = self._map_size.scale_max_size(\n self.screen_size_px / 4)\n minimap_to_visual_minimap = transform.Linear(\n self.minimap_size_px.x / self._map_size.x)\n minimap_offset = point.Point(0, (self.screen_size_px.y -\n self.minimap_size_px.y))\n add_surface(SurfType.MINIMAP,\n point.Rect(minimap_offset,\n minimap_offset + self.minimap_size_px),\n transform.Chain(\n self._world_to_minimap,\n minimap_to_visual_minimap),\n self.draw_mini_map)\n\n # Add the feature layers\n features_loc = point.Point(self.screen_size_px.x, 0)\n feature_pane = self._window.subsurface(\n pygame.Rect(features_loc, window_size_px - features_loc))\n feature_pane.fill(colors.white / 2)\n feature_pane_size = point.Point(*feature_pane.get_size())\n feature_grid_size = feature_pane_size / point.Point(cols, rows)\n feature_layer_area = self._feature_layer_screen_size.scale_max_size(\n feature_grid_size)\n feature_layer_size = feature_layer_area * 0.9\n feature_layer_padding = (feature_layer_area - feature_layer_size) / 2\n\n feature_font_size = int(feature_grid_size.y * 0.09)\n feature_font = pygame.font.Font(None, feature_font_size)\n\n feature_counter = itertools.count()\n def add_feature_layer(feature, surf_type, world_to_surf):\n \"\"\"Add a feature layer surface.\"\"\"\n i = next(feature_counter)\n grid_offset = point.Point(i % cols, i // cols) * feature_grid_size\n text = feature_font.render(feature.full_name, True, colors.white)\n rect = text.get_rect()\n rect.center = grid_offset + point.Point(feature_grid_size.x / 2,\n feature_font_size)\n feature_pane.blit(text, rect)\n surf_loc = (features_loc + grid_offset + feature_layer_padding +\n point.Point(0, feature_font_size))\n add_surface(surf_type,\n point.Rect(surf_loc, surf_loc + feature_layer_size),\n world_to_surf,\n lambda surf: self.draw_feature_layer(surf, feature))\n\n # Add the minimap feature layers\n fl_minimap_to_fl_surf = transform.Linear(\n feature_layer_size / self._feature_layer_minimap_size)\n world_to_fl_minimap_surf = transform.Chain(\n self._world_to_minimap,\n self._minimap_to_fl_minimap,\n transform.Center(),\n fl_minimap_to_fl_surf)\n for feature in features.MINIMAP_FEATURES:\n add_feature_layer(feature, SurfType.MINIMAP, world_to_fl_minimap_surf)\n\n # Add the screen feature layers\n fl_screen_to_fl_surf = transform.Linear(\n feature_layer_size / self._feature_layer_screen_size)\n world_to_fl_screen_surf = transform.Chain(\n self._world_to_screen,\n self._screen_to_fl_screen,\n transform.Center(),\n fl_screen_to_fl_surf)\n for feature in features.SCREEN_FEATURES:\n add_feature_layer(feature, SurfType.SCREEN, world_to_fl_screen_surf)\n\n # Add the help screen\n add_surface(SurfType.CHROME,\n point.Rect(window_size_px / 4, window_size_px * 3 / 4),\n None,\n self.draw_help)\n\n # Arbitrarily set the initial camera to the center of the map.\n self._update_camera(self._map_size / 2)\n\n def _update_camera(self, camera_center):\n \"\"\"Update the camera transform based on the new camera center.\"\"\"\n camera_radius = (self._feature_layer_screen_size /\n self._feature_layer_screen_size.x *\n self._camera_width_world_units / 2)\n center = camera_center.bound(camera_radius, self._map_size - camera_radius)\n self._camera = point.Rect(\n (center - camera_radius).bound(self._map_size),\n (center + camera_radius).bound(self._map_size))\n self._world_to_screen.offset = (-self._camera.bl *\n self._world_to_screen.scale)\n\n def zoom(self, factor):\n \"\"\"Zoom the window in/out.\"\"\"\n global max_window_size\n max_window_size *= factor\n self.init_window()\n\n def get_mouse_pos(self, window_pos=None):\n \"\"\"Return a MousePos filled with the world and screen/minimap positions.\"\"\"\n window_pos = window_pos or pygame.mouse.get_pos()\n # +0.5 to center the point on the middle of the pixel.\n window_pt = point.Point(*window_pos) + 0.5\n for surf in reversed(self.surfaces):\n if (surf.surf_type != SurfType.CHROME and\n surf.surf_rect.contains_point(window_pt)):\n surf_rel_pt = window_pt - surf.surf_rect.tl\n world_pt = surf.world_to_surf.back_pt(surf_rel_pt)\n return MousePos(world_pt, surf.surf_type)\n\n def clear_queued_action(self):\n self.queued_hotkey = \"\"\n self.queued_action = None\n\n def save_replay(self, run_config, controller):\n replay_path = run_config.save_replay(\n controller.save_replay(), \"local\", self._game_info.local_map_path)\n print(\"Wrote replay to:\", replay_path)\n\n @with_lock(obs_lock)\n @sw.decorate\n def get_actions(self, run_config, controller):\n \"\"\"Get actions from the UI, apply to controller, and return an ActionCmd.\"\"\"\n if not self._initialized:\n return ActionCmd.STEP\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return ActionCmd.QUIT\n elif event.type == pygame.KEYDOWN:\n if self.help:\n self.help = False\n elif event.key in (pygame.K_QUESTION, pygame.K_SLASH):\n self.help = True\n elif event.key == pygame.K_PAUSE:\n pause = True\n while pause:\n time.sleep(0.1)\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key in (pygame.K_PAUSE, pygame.K_ESCAPE):\n pause = False\n elif event.key == pygame.K_F4:\n return ActionCmd.QUIT\n elif event.key == pygame.K_F5:\n return ActionCmd.RESTART\n elif event.key == pygame.K_F4:\n return ActionCmd.QUIT\n elif event.key == pygame.K_F5:\n return ActionCmd.RESTART\n elif event.key == pygame.K_F8: # Toggle synchronous rendering.\n self._render_sync = not self._render_sync\n print(\"Rendering\", self._render_sync and \"Sync\" or \"Async\")\n elif event.key == pygame.K_F9: # Save a replay.\n self.save_replay(run_config, controller)\n elif (event.key in (pygame.K_PLUS, pygame.K_EQUALS) and\n pygame.key.get_mods() & pygame.KMOD_CTRL): # zoom in\n self.zoom(1.1)\n elif (event.key in (pygame.K_MINUS, pygame.K_UNDERSCORE) and\n pygame.key.get_mods() & pygame.KMOD_CTRL): # zoom out\n self.zoom(1 / 1.1)\n elif event.key in (pygame.K_PAGEUP, pygame.K_PAGEDOWN):\n if pygame.key.get_mods() & pygame.KMOD_CTRL:\n if event.key == pygame.K_PAGEUP:\n self._step_mul += 1\n elif self._step_mul > 1:\n self._step_mul -= 1\n print(\"New step mul:\", self._step_mul)\n else:\n self._fps *= 1.25 if event.key == pygame.K_PAGEUP else 1 / 1.25\n print(\"New max game speed: %.1f\" % self._fps)\n elif event.key in self.camera_actions:\n controller.act(self.camera_action_raw(\n self._camera.center + self.camera_actions[event.key]))\n elif event.key == pygame.K_ESCAPE:\n cmds = self._abilities(lambda cmd: cmd.hotkey == \"escape\")\n if cmds:\n assert len(cmds) == 1\n cmd = cmds[0]\n assert cmd.target == sc_data.AbilityData.Target.Value(\"None\")\n controller.act(self.unit_action(cmd))\n else:\n self.clear_queued_action()\n else:\n if not self.queued_action:\n key = pygame.key.name(event.key).lower()\n new_cmd = self.queued_hotkey + key\n cmds = self._abilities(lambda cmd, n=new_cmd: ( # pylint: disable=g-long-lambda\n cmd.hotkey != \"escape\" and cmd.hotkey.startswith(n)))\n if cmds:\n self.queued_hotkey = new_cmd\n if len(cmds) == 1:\n cmd = cmds[0]\n if cmd.hotkey == self.queued_hotkey:\n if cmd.target != sc_data.AbilityData.Target.Value(\"None\"):\n self.clear_queued_action()\n self.queued_action = cmd\n else:\n controller.act(self.unit_action(cmd))\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = self.get_mouse_pos(event.pos)\n if event.button == MouseButtons.LEFT and mouse_pos:\n if self.queued_action:\n controller.act(self.unit_action(self.queued_action, mouse_pos))\n elif mouse_pos.type == SurfType.MINIMAP:\n controller.act(self.camera_action(mouse_pos.pos))\n else:\n self.select_start = mouse_pos.pos\n elif event.button == MouseButtons.RIGHT:\n if self.queued_action:\n self.clear_queued_action()\n else:\n cmds = self._abilities(lambda cmd: cmd.button_name == \"Smart\")\n if cmds:\n controller.act(self.unit_action(cmds[0], mouse_pos))\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_pos = self.get_mouse_pos(event.pos)\n if event.button == MouseButtons.LEFT and self.select_start:\n if mouse_pos and mouse_pos.type == SurfType.SCREEN:\n controller.act(self.select_action(point.Rect(self.select_start,\n mouse_pos.pos)))\n self.select_start = None\n return ActionCmd.STEP\n\n def camera_action(self, world_pos):\n \"\"\"Return a `sc_pb.Action` with the camera movement filled.\"\"\"\n action = sc_pb.Action()\n self._world_to_fl_minimap.fwd_pt(world_pos).assign_to(\n action.action_feature_layer.camera_move.center_minimap)\n return action\n\n def camera_action_raw(self, world_pos):\n \"\"\"Return a `sc_pb.Action` with the camera movement filled.\"\"\"\n action = sc_pb.Action()\n world_pos.assign_to(action.action_raw.camera_move.center_world_space)\n return action\n\n def select_action(self, select_rect):\n \"\"\"Return a `sc_pb.Action` with the selection filled.\"\"\"\n action = sc_pb.Action()\n\n if select_rect.tl == select_rect.br: # select a point\n select = action.action_feature_layer.unit_selection_point\n self._world_to_fl_screen.fwd_pt(select_rect.tl).assign_to(\n select.selection_screen_coord)\n select.type = sc_spatial.ActionSpatialUnitSelectionPoint.Select\n else:\n select = action.action_feature_layer.unit_selection_rect\n rect = select.selection_screen_coord.add()\n self._world_to_fl_screen.fwd_pt(select_rect.bl).assign_to(rect.p0)\n self._world_to_fl_screen.fwd_pt(select_rect.tr).assign_to(rect.p1)\n select.selection_add = False\n\n # Clear the queued action if something will be selected. An alternative\n # implementation may check whether the selection changed next frame.\n units = self._units_in_area(select_rect)\n if units:\n self.clear_queued_action()\n\n return action\n\n def unit_action(self, cmd, pos=None):\n \"\"\"Return a `sc_pb.Action` filled with the cmd and appropriate target.\"\"\"\n action = sc_pb.Action()\n unit_command = action.action_feature_layer.unit_command\n unit_command.ability_id = cmd.ability_id\n if pos:\n if pos.type == SurfType.SCREEN:\n self._world_to_fl_screen.fwd_pt(pos.pos).assign_to(\n unit_command.target_screen_coord)\n elif pos.type == SurfType.MINIMAP:\n self._world_to_fl_minimap.fwd_pt(pos.pos).assign_to(\n unit_command.target_minimap_coord)\n self.clear_queued_action()\n return action\n\n def _abilities(self, fn=None):\n \"\"\"Return the list of abilities filtered by `fn`.\"\"\"\n return list(filter(fn, (self._static_data.abilities[cmd.ability_id]\n for cmd in self._obs.observation.abilities)))\n\n def _visible_units(self):\n \"\"\"A generator of visible units and their positions as `Point`s, sorted.\"\"\"\n # Sort the units by elevation, then owned (eg refinery) above world (ie 16)\n # (eg geiser), small above big, and otherwise arbitrary but stable.\n for u in sorted(self._obs.observation.raw_data.units,\n key=lambda u: (u.pos.z, u.owner != 16, -u.radius, u.tag)):\n yield u, point.Point.build(u.pos)\n\n def _units_in_area(self, rect):\n \"\"\"Return the list of units that intersect the rect.\"\"\"\n player_id = self._obs.observation.player_common.player_id\n return [u for u, p in self._visible_units()\n if rect.intersects_circle(p, u.radius) and u.owner == player_id]\n\n def get_unit_name(self, surf, name, radius):\n \"\"\"Get a length limited unit name for drawing units.\"\"\"\n key = (name, radius)\n if key not in self._name_lengths:\n max_len = surf.world_to_surf.fwd_dist(radius * 1.6)\n for i in range(len(name)):\n if self.font_small.size(name[:i + 1])[0] > max_len:\n self._name_lengths[key] = name[:i]\n break\n else:\n self._name_lengths[key] = name\n return self._name_lengths[key]\n\n @sw.decorate\n def draw_units(self, surf):\n \"\"\"Draw the units and buildings.\"\"\"\n for u, p in self._visible_units():\n if self._camera.intersects_circle(p, u.radius):\n fraction_damage = clamp((u.health_max - u.health) / (u.health_max or 1),\n 0, 1)\n surf.draw_circle(colors.PLAYER_ABSOLUTE_PALETTE[u.owner], p, u.radius)\n\n if fraction_damage > 0:\n surf.draw_circle(colors.PLAYER_ABSOLUTE_PALETTE[u.owner] // 2,\n p, u.radius * fraction_damage)\n\n name = self.get_unit_name(\n surf, self._static_data.units.get(u.unit_type, \"<none>\"), u.radius)\n if name:\n text = self.font_small.render(name, True, colors.white)\n rect = text.get_rect()\n rect.center = surf.world_to_surf.fwd_pt(p)\n surf.surf.blit(text, rect)\n\n if u.is_selected:\n surf.draw_circle(colors.green, p, u.radius + 0.05, 1)\n\n @sw.decorate\n def draw_selection(self, surf):\n \"\"\"Draw the selection rectange.\"\"\"\n if self.select_start:\n mouse_pos = self.get_mouse_pos()\n if mouse_pos and mouse_pos.type == SurfType.SCREEN:\n surf.draw_rect(\n colors.green, point.Rect(self.select_start, mouse_pos.pos), 1)\n\n @sw.decorate\n def draw_build_target(self, surf):\n \"\"\"Draw the build target.\"\"\"\n round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v)\n\n if self.queued_action:\n radius = self.queued_action.footprint_radius\n if radius:\n pos = self.get_mouse_pos()\n if pos:\n pos = point.Point(round_half(pos.pos.x, (radius * 2) % 2),\n round_half(pos.pos.y, (radius * 2) % 2))\n surf.draw_circle(\n colors.PLAYER_ABSOLUTE_PALETTE[\n self._obs.observation.player_common.player_id],\n pos, radius)\n\n @sw.decorate\n def draw_overlay(self, surf):\n \"\"\"Draw the overlay describing resources.\"\"\"\n player = self._obs.observation.player_common\n text = self.font_large.render(\n \"Minerals: %s, Vespene: %s, Food: %s / %s; Score: %s, Frame: %s, \"\n \"FPS: G:%.1f, R:%.1f\" % (\n player.minerals, player.vespene,\n player.food_used, player.food_cap,\n self._obs.observation.score.score, self._obs.observation.game_loop,\n len(self._game_times) / (sum(self._game_times) or 1),\n len(self._render_times) / (sum(self._render_times) or 1)),\n True, colors.green)\n surf.surf.blit(text, (3, 3))\n\n @sw.decorate\n def draw_help(self, surf):\n \"\"\"Draw the help dialog.\"\"\"\n if not self.help:\n return\n\n def write(line, loc):\n surf.surf.blit(self.font_large.render(line, True, colors.black), loc)\n\n surf.surf.fill(colors.white * 0.8)\n write(\"Shortcuts:\", point.Point(self.scale, self.scale))\n\n for i, (hotkey, description) in enumerate(self.shortcuts, start=2):\n write(hotkey, point.Point(self.scale * 2, self.scale * i))\n write(description, point.Point(self.scale * 8, self.scale * i))\n\n @sw.decorate\n def draw_commands(self, surf):\n \"\"\"Draw the list of available commands.\"\"\"\n y = self.scale * 2\n\n for cmd in sorted(self._abilities(), key=lambda c: c.hotkey):\n if cmd.button_name != \"Smart\":\n if self.queued_action and cmd == self.queued_action:\n color = colors.green\n elif self.queued_hotkey and cmd.hotkey.startswith(self.queued_hotkey):\n color = colors.green / 2\n else:\n color = colors.yellow\n text = self.font_large.render(\n \"%s - %s\" % (cmd.hotkey, cmd.button_name), True, color)\n surf.surf.blit(text, (3, y))\n y += self.scale\n\n @sw.decorate\n def draw_actions(self):\n \"\"\"Draw the actions so that they can be inspected for accuracy.\"\"\"\n for act in self._obs.actions:\n if (act.HasField(\"action_raw\") and\n act.action_raw.HasField(\"unit_command\") and\n act.action_raw.unit_command.HasField(\"target_world_space_pos\")):\n pos = point.Point.build(\n act.action_raw.unit_command.target_world_space_pos)\n self.all_surfs(_Surface.draw_circle, colors.yellow, pos, 0.1)\n if act.HasField(\"action_feature_layer\"):\n act_fl = act.action_feature_layer\n if act_fl.HasField(\"unit_command\"):\n if act_fl.unit_command.HasField(\"target_screen_coord\"):\n pos = self._world_to_fl_screen.back_pt(\n point.Point.build(act_fl.unit_command.target_screen_coord))\n self.all_surfs(_Surface.draw_circle, colors.cyan, pos, 0.1)\n if act_fl.unit_command.HasField(\"target_minimap_coord\"):\n pos = self._world_to_fl_minimap.back_pt(\n point.Point.build(act_fl.unit_command.target_minimap_coord))\n self.all_surfs(_Surface.draw_circle, colors.cyan, pos, 0.1)\n if (act_fl.HasField(\"unit_selection_point\") and\n act_fl.unit_selection_point.HasField(\"selection_screen_coord\")):\n pos = self._world_to_fl_screen.back_pt(point.Point.build(\n act_fl.unit_selection_point.selection_screen_coord))\n self.all_surfs(_Surface.draw_circle, colors.cyan, pos, 0.1)\n if act_fl.HasField(\"unit_selection_rect\"):\n for r in act_fl.unit_selection_rect.selection_screen_coord:\n rect = point.Rect(\n self._world_to_fl_screen.back_pt(point.Point.build(r.p0)),\n self._world_to_fl_screen.back_pt(point.Point.build(r.p1)))\n self.all_surfs(_Surface.draw_rect, colors.cyan, rect, 1)\n\n @sw.decorate\n def draw_base_map(self, surf):\n \"\"\"Draw the base map.\"\"\"\n hmap_feature = features.SCREEN_FEATURES.height_map\n hmap = hmap_feature.unpack(self._obs.observation)\n if not hmap.any():\n hmap += 100\n hmap_color = hmap_feature.color(hmap)\n\n creep_feature = features.SCREEN_FEATURES.creep\n creep = creep_feature.unpack(self._obs.observation)\n creep_mask = creep > 0\n creep_color = creep_feature.color(creep)\n\n power_feature = features.SCREEN_FEATURES.power\n power = power_feature.unpack(self._obs.observation)\n power_mask = power > 0\n power_color = power_feature.color(power)\n\n visibility = features.SCREEN_FEATURES.visibility_map.unpack(\n self._obs.observation)\n visibility_fade = np.array([[0.5] * 3, [0.75]*3, [1]*3])\n\n out = hmap_color * 0.6\n out[creep_mask, :] = (0.4 * out[creep_mask, :] +\n 0.6 * creep_color[creep_mask, :])\n out[power_mask, :] = (0.7 * out[power_mask, :] +\n 0.3 * power_color[power_mask, :])\n out *= visibility_fade[visibility]\n\n surf.blit_np_array(out)\n\n @sw.decorate\n def draw_mini_map(self, surf):\n \"\"\"Draw the minimap.\"\"\"\n if (self._obs.observation.HasField(\"render_data\") and\n self._obs.observation.render_data.HasField(\"minimap\")):\n # Draw the rendered version.\n surf.blit_np_array(features.Feature.unpack_rgb_image(\n self._obs.observation.render_data.minimap))\n else: # Render it manually from feature layer data.\n hmap_feature = features.MINIMAP_FEATURES.height_map\n hmap = hmap_feature.unpack(self._obs.observation)\n if not hmap.any():\n hmap += 100\n hmap_color = hmap_feature.color(hmap)\n\n creep_feature = features.MINIMAP_FEATURES.creep\n creep = creep_feature.unpack(self._obs.observation)\n creep_mask = creep > 0\n creep_color = creep_feature.color(creep)\n\n player_feature = features.MINIMAP_FEATURES.player_relative\n player_relative = player_feature.unpack(self._obs.observation)\n player_mask = player_relative > 0\n player_color = player_feature.color(player_relative)\n\n visibility = features.MINIMAP_FEATURES.visibility_map.unpack(\n self._obs.observation)\n visibility_fade = np.array([[0.5] * 3, [0.75]*3, [1]*3])\n\n out = hmap_color * 0.6\n out[creep_mask, :] = (0.4 * out[creep_mask, :] +\n 0.6 * creep_color[creep_mask, :])\n out[player_mask, :] = player_color[player_mask, :]\n out *= visibility_fade[visibility]\n\n surf.blit_np_array(out)\n\n surf.draw_rect(colors.white * 0.8, self._camera, 1) # Camera\n pygame.draw.rect(surf.surf, colors.red, surf.surf.get_rect(), 1) # Border\n\n def check_valid_queued_action(self):\n # Make sure the existing command is still valid\n if (self.queued_hotkey and not self._abilities(\n lambda cmd: cmd.hotkey.startswith(self.queued_hotkey))):\n self.queued_hotkey = \"\"\n if (self.queued_action and not self._abilities(\n lambda cmd: self.queued_action == cmd)):\n self.queued_action = None\n\n @sw.decorate\n def draw_rendered_map(self, surf):\n \"\"\"Draw the rendered pixels.\"\"\"\n surf.blit_np_array(features.Feature.unpack_rgb_image(\n self._obs.observation.render_data.map))\n\n def draw_screen(self, surf):\n \"\"\"Draw the screen area.\"\"\"\n # surf.fill(colors.black)\n if (self._obs.observation.HasField(\"render_data\") and\n self._obs.observation.render_data.HasField(\"map\")):\n self.draw_rendered_map(surf)\n else:\n self.draw_base_map(surf)\n self.draw_units(surf)\n self.draw_selection(surf)\n self.draw_build_target(surf)\n self.draw_overlay(surf)\n self.draw_commands(surf)\n\n @sw.decorate\n def draw_feature_layer(self, surf, feature):\n \"\"\"Draw a feature layer.\"\"\"\n surf.blit_np_array(feature.color(feature.unpack(self._obs.observation)))\n\n def all_surfs(self, fn, *args, **kwargs):\n for surf in self.surfaces:\n if surf.world_to_surf:\n fn(surf, *args, **kwargs)\n\n @sw.decorate\n def render(self, obs):\n \"\"\"Push an observation onto the queue to be rendered.\"\"\"\n if not self._initialized:\n return\n now = time.time()\n self._game_times.append((now - self._last_time) /\n max(1, (obs.observation.game_loop -\n self._obs.observation.game_loop)))\n self._last_time = now\n self._last_game_loop = self._obs.observation.game_loop\n self._obs_queue.put(obs)\n if self._render_sync:\n self._obs_queue.join()\n\n def render_thread(self):\n \"\"\"A render loop that pulls observations off the queue to render.\"\"\"\n obs = True\n while obs: # Send something falsy through the queue to shut down.\n obs = self._obs_queue.get()\n if obs and self._obs_queue.empty():\n # Only render the latest observation so we keep up with the game.\n self.render_obs(obs)\n self._obs_queue.task_done()\n\n @with_lock(render_lock)\n @sw.decorate\n def render_obs(self, obs):\n \"\"\"Render a frame given an observation.\"\"\"\n start_time = time.time()\n with obs_lock:\n self._obs = obs\n self.check_valid_queued_action()\n self._update_camera(point.Point.build(\n self._obs.observation.raw_data.player.camera))\n\n for surf in self.surfaces:\n # Render that surface.\n surf.draw(surf)\n\n mouse_pos = self.get_mouse_pos()\n if mouse_pos:\n # Draw a small mouse cursor\n self.all_surfs(_Surface.draw_circle, colors.green, mouse_pos.pos, 0.1)\n\n self.draw_actions()\n\n with sw(\"flip\"):\n pygame.display.flip()\n\n self._render_times.append(time.time() - start_time)\n\n def run(self, run_config, controller, max_game_steps=0,\n game_steps_per_episode=0, save_replay=False):\n \"\"\"Run loop that gets observations, renders them, and sends back actions.\"\"\"\n is_replay = (controller.status == remote_controller.Status.in_replay)\n total_game_steps = 0\n start_time = time.time()\n\n try:\n while True:\n self.init(controller.game_info(), controller.data())\n episode_steps = 0\n\n controller.step()\n\n while True:\n total_game_steps += self._step_mul\n episode_steps += self._step_mul\n frame_start_time = time.time()\n\n obs = controller.observe()\n self.render(obs)\n\n if obs.player_result:\n break\n\n cmd = self.get_actions(run_config, controller)\n if cmd == ActionCmd.STEP:\n pass\n elif cmd == ActionCmd.QUIT:\n if not is_replay and save_replay:\n self.save_replay(run_config, controller)\n return\n elif cmd == ActionCmd.RESTART:\n break\n else:\n raise Exception(\"Unexpected command: %s\" % cmd)\n\n controller.step(self._step_mul)\n\n if max_game_steps and total_game_steps >= max_game_steps:\n return\n\n if game_steps_per_episode and episode_steps >= game_steps_per_episode:\n break\n\n with sw(\"sleep\"):\n elapsed_time = time.time() - frame_start_time\n time.sleep(max(0, 1 / self._fps - elapsed_time))\n\n if is_replay:\n break\n\n if save_replay:\n self.save_replay(run_config, controller)\n\n print(\"Restarting\")\n controller.restart()\n except KeyboardInterrupt:\n pass\n finally:\n self.close()\n elapsed_time = time.time() - start_time\n print(\"took %.3f seconds for %s steps: %.3f fps\" %\n (elapsed_time, total_game_steps, total_game_steps / elapsed_time))\n\n def __del__(self):\n self.close()\n"
]
| [
[
"numpy.array"
]
]
|
robertcdickson/pymatgen | [
"fb65122a7c471b9ffd0d01f2341339fb1dee2af1"
]
| [
"pymatgen/analysis/structure_analyzer.py"
]
| [
"# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module provides classes to perform topological analyses of structures.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Sai Jayaraman\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n\nimport collections\nimport itertools\nfrom math import acos, pi\nfrom warnings import warn\n\nimport numpy as np\nfrom monty.dev import deprecated\nfrom scipy.spatial import Voronoi\n\nfrom pymatgen.analysis.local_env import JmolNN, VoronoiNN\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.core.periodic_table import Element, Species\nfrom pymatgen.core.sites import PeriodicSite\nfrom pymatgen.core.surface import SlabGenerator\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.util.num import abs_cap\n\n\ndef average_coordination_number(structures, freq=10):\n \"\"\"\n Calculates the ensemble averaged Voronoi coordination numbers\n of a list of Structures using VoronoiNN.\n Typically used for analyzing the output of a Molecular Dynamics run.\n\n Args:\n structures (list): list of Structures.\n freq (int): sampling frequency of coordination number [every freq steps].\n\n Returns:\n Dictionary of elements as keys and average coordination numbers as values.\n \"\"\"\n coordination_numbers = {}\n for spec in structures[0].composition.as_dict().keys():\n coordination_numbers[spec] = 0.0\n count = 0\n for i, s in enumerate(structures):\n if i % freq != 0:\n continue\n count += 1\n vnn = VoronoiNN()\n for j, atom in enumerate(s):\n cn = vnn.get_cn(s, j, use_weights=True)\n coordination_numbers[atom.species_string] += cn\n elements = structures[0].composition.as_dict()\n for el in coordination_numbers:\n coordination_numbers[el] = coordination_numbers[el] / elements[el] / count\n return coordination_numbers\n\n\nclass VoronoiAnalyzer:\n \"\"\"\n Performs a statistical analysis of Voronoi polyhedra around each site.\n Each Voronoi polyhedron is described using Schaefli notation.\n That is a set of indices {c_i} where c_i is the number of faces with i\n number of vertices. E.g. for a bcc crystal, there is only one polyhedron\n notation of which is [0,6,0,8,0,0,...].\n In perfect crystals, these also corresponds to the Wigner-Seitz cells.\n For distorted-crystals, liquids or amorphous structures, rather than one-type,\n there is a statistical distribution of polyhedra.\n See ref: Microstructure and its relaxation in Fe-B amorphous system\n simulated by molecular dynamics,\n Stepanyuk et al., J. Non-cryst. Solids (1993), 159, 80-87.\n \"\"\"\n\n def __init__(self, cutoff=5.0, qhull_options=\"Qbb Qc Qz\"):\n \"\"\"\n Args:\n cutoff (float): cutoff distance to search for neighbors of a given atom\n (default = 5.0)\n qhull_options (str): options to pass to qhull (optional)\n \"\"\"\n self.cutoff = cutoff\n self.qhull_options = qhull_options\n\n def analyze(self, structure, n=0):\n \"\"\"\n Performs Voronoi analysis and returns the polyhedra around atom n\n in Schlaefli notation.\n\n Args:\n structure (Structure): structure to analyze\n n (int): index of the center atom in structure\n\n Returns:\n voronoi index of n: <c3,c4,c6,c6,c7,c8,c9,c10>\n where c_i denotes number of facets with i vertices.\n \"\"\"\n center = structure[n]\n neighbors = structure.get_sites_in_sphere(center.coords, self.cutoff)\n neighbors = [i[0] for i in sorted(neighbors, key=lambda s: s[1])]\n qvoronoi_input = np.array([s.coords for s in neighbors])\n voro = Voronoi(qvoronoi_input, qhull_options=self.qhull_options)\n vor_index = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n\n for key in voro.ridge_dict:\n if 0 in key: # This means if the center atom is in key\n if -1 in key: # This means if an infinity point is in key\n raise ValueError(\"Cutoff too short.\")\n try:\n vor_index[len(voro.ridge_dict[key]) - 3] += 1\n except IndexError:\n # If a facet has more than 10 edges, it's skipped here.\n pass\n return vor_index\n\n def analyze_structures(self, structures, step_freq=10, most_frequent_polyhedra=15):\n \"\"\"\n Perform Voronoi analysis on a list of Structures.\n Note that this might take a significant amount of time depending on the\n size and number of structures.\n\n Args:\n structures (list): list of Structures\n cutoff (float: cutoff distance around an atom to search for\n neighbors\n step_freq (int): perform analysis every step_freq steps\n qhull_options (str): options to pass to qhull\n most_frequent_polyhedra (int): this many unique polyhedra with\n highest frequencies is stored.\n\n Returns:\n A list of tuples in the form (voronoi_index,frequency)\n \"\"\"\n voro_dict = {}\n step = 0\n for structure in structures:\n step += 1\n if step % step_freq != 0:\n continue\n\n v = []\n for n in range(len(structure)):\n v.append(str(self.analyze(structure, n=n).view()))\n for voro in v:\n if voro in voro_dict:\n voro_dict[voro] += 1\n else:\n voro_dict[voro] = 1\n return sorted(voro_dict.items(), key=lambda x: (x[1], x[0]), reverse=True)[:most_frequent_polyhedra]\n\n @staticmethod\n def plot_vor_analysis(voronoi_ensemble):\n \"\"\"\n Plot the Voronoi analysis.\n\n :param voronoi_ensemble:\n :return: matplotlib.pyplot\n \"\"\"\n t = list(zip(*voronoi_ensemble))\n labels = t[0]\n val = list(t[1])\n tot = np.sum(val)\n val = [float(j) / tot for j in val]\n pos = np.arange(len(val)) + 0.5 # the bar centers on the y axis\n import matplotlib.pyplot as plt\n\n plt.figure()\n plt.barh(pos, val, align=\"center\", alpha=0.5)\n plt.yticks(pos, labels)\n plt.xlabel(\"Count\")\n plt.title(\"Voronoi Spectra\")\n plt.grid(True)\n return plt\n\n\nclass RelaxationAnalyzer:\n \"\"\"\n This class analyzes the relaxation in a calculation.\n \"\"\"\n\n def __init__(self, initial_structure, final_structure):\n \"\"\"\n Please note that the input and final structures should have the same\n ordering of sites. This is typically the case for most computational\n codes.\n\n Args:\n initial_structure (Structure): Initial input structure to\n calculation.\n final_structure (Structure): Final output structure from\n calculation.\n \"\"\"\n if final_structure.formula != initial_structure.formula:\n raise ValueError(\"Initial and final structures have different \" + \"formulas!\")\n self.initial = initial_structure\n self.final = final_structure\n\n def get_percentage_volume_change(self):\n \"\"\"\n Returns the percentage volume change.\n\n Returns:\n Volume change in percentage, e.g., 0.055 implies a 5.5% increase.\n \"\"\"\n initial_vol = self.initial.lattice.volume\n final_vol = self.final.lattice.volume\n return final_vol / initial_vol - 1\n\n def get_percentage_lattice_parameter_changes(self):\n \"\"\"\n Returns the percentage lattice parameter changes.\n\n Returns:\n A dict of the percentage change in lattice parameter, e.g.,\n {'a': 0.012, 'b': 0.021, 'c': -0.031} implies a change of 1.2%,\n 2.1% and -3.1% in the a, b and c lattice parameters respectively.\n \"\"\"\n initial_latt = self.initial.lattice\n final_latt = self.final.lattice\n d = {l: getattr(final_latt, l) / getattr(initial_latt, l) - 1 for l in [\"a\", \"b\", \"c\"]}\n return d\n\n def get_percentage_bond_dist_changes(self, max_radius=3.0):\n \"\"\"\n Returns the percentage bond distance changes for each site up to a\n maximum radius for nearest neighbors.\n\n Args:\n max_radius (float): Maximum radius to search for nearest\n neighbors. This radius is applied to the initial structure,\n not the final structure.\n\n Returns:\n Bond distance changes as a dict of dicts. E.g.,\n {index1: {index2: 0.011, ...}}. For economy of representation, the\n index1 is always less than index2, i.e., since bonding between\n site1 and siten is the same as bonding between siten and site1,\n there is no reason to duplicate the information or computation.\n \"\"\"\n data = collections.defaultdict(dict)\n for inds in itertools.combinations(list(range(len(self.initial))), 2):\n (i, j) = sorted(inds)\n initial_dist = self.initial[i].distance(self.initial[j])\n if initial_dist < max_radius:\n final_dist = self.final[i].distance(self.final[j])\n data[i][j] = final_dist / initial_dist - 1\n return data\n\n\nclass VoronoiConnectivity:\n \"\"\"\n Computes the solid angles swept out by the shared face of the voronoi\n polyhedron between two sites.\n \"\"\"\n\n def __init__(self, structure, cutoff=10):\n \"\"\"\n Args:\n structure (Structure): Input structure\n cutoff (float) Cutoff distance.\n \"\"\"\n self.cutoff = cutoff\n self.s = structure\n recp_len = np.array(self.s.lattice.reciprocal_lattice.abc)\n i = np.ceil(cutoff * recp_len / (2 * pi))\n offsets = np.mgrid[-i[0] : i[0] + 1, -i[1] : i[1] + 1, -i[2] : i[2] + 1].T\n self.offsets = np.reshape(offsets, (-1, 3))\n # shape = [image, axis]\n self.cart_offsets = self.s.lattice.get_cartesian_coords(self.offsets)\n\n @property\n def connectivity_array(self):\n \"\"\"\n Provides connectivity array.\n\n Returns:\n connectivity: An array of shape [atomi, atomj, imagej]. atomi is\n the index of the atom in the input structure. Since the second\n atom can be outside of the unit cell, it must be described\n by both an atom index and an image index. Array data is the\n solid angle of polygon between atomi and imagej of atomj\n \"\"\"\n # shape = [site, axis]\n cart_coords = np.array(self.s.cart_coords)\n # shape = [site, image, axis]\n all_sites = cart_coords[:, None, :] + self.cart_offsets[None, :, :]\n vt = Voronoi(all_sites.reshape((-1, 3)))\n n_images = all_sites.shape[1]\n cs = (len(self.s), len(self.s), len(self.cart_offsets))\n connectivity = np.zeros(cs)\n vts = np.array(vt.vertices)\n for (ki, kj), v in vt.ridge_dict.items():\n atomi = ki // n_images\n atomj = kj // n_images\n\n imagei = ki % n_images\n imagej = kj % n_images\n\n if imagei != n_images // 2 and imagej != n_images // 2:\n continue\n\n if imagei == n_images // 2:\n # atomi is in original cell\n val = solid_angle(vt.points[ki], vts[v])\n connectivity[atomi, atomj, imagej] = val\n\n if imagej == n_images // 2:\n # atomj is in original cell\n val = solid_angle(vt.points[kj], vts[v])\n connectivity[atomj, atomi, imagei] = val\n\n if -10.101 in vts[v]:\n warn(\"Found connectivity with infinite vertex. Cutoff is too low, and results may be incorrect\")\n return connectivity\n\n @property\n def max_connectivity(self):\n \"\"\"\n returns the 2d array [sitei, sitej] that represents\n the maximum connectivity of site i to any periodic\n image of site j\n \"\"\"\n return np.max(self.connectivity_array, axis=2)\n\n def get_connections(self):\n \"\"\"\n Returns a list of site pairs that are Voronoi Neighbors, along\n with their real-space distances.\n \"\"\"\n con = []\n maxconn = self.max_connectivity\n for ii in range(0, maxconn.shape[0]):\n for jj in range(0, maxconn.shape[1]):\n if maxconn[ii][jj] != 0:\n dist = self.s.get_distance(ii, jj)\n con.append([ii, jj, dist])\n return con\n\n def get_sitej(self, site_index, image_index):\n \"\"\"\n Assuming there is some value in the connectivity array at indices\n (1, 3, 12). sitei can be obtained directly from the input structure\n (structure[1]). sitej can be obtained by passing 3, 12 to this function\n\n Args:\n site_index (int): index of the site (3 in the example)\n image_index (int): index of the image (12 in the example)\n \"\"\"\n atoms_n_occu = self.s[site_index].species\n lattice = self.s.lattice\n coords = self.s[site_index].frac_coords + self.offsets[image_index]\n return PeriodicSite(atoms_n_occu, coords, lattice)\n\n\ndef solid_angle(center, coords):\n \"\"\"\n Helper method to calculate the solid angle of a set of coords from the\n center.\n\n Args:\n center (3x1 array): Center to measure solid angle from.\n coords (Nx3 array): List of coords to determine solid angle.\n\n Returns:\n The solid angle.\n \"\"\"\n o = np.array(center)\n r = [np.array(c) - o for c in coords]\n r.append(r[0])\n n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]\n n.append(np.cross(r[1], r[0]))\n vals = []\n for i in range(len(n) - 1):\n v = -np.dot(n[i], n[i + 1]) / (np.linalg.norm(n[i]) * np.linalg.norm(n[i + 1]))\n vals.append(acos(abs_cap(v)))\n phi = sum(vals)\n return phi + (3 - len(r)) * pi\n\n\ndef get_max_bond_lengths(structure, el_radius_updates=None):\n \"\"\"\n Provides max bond length estimates for a structure based on the JMol\n table and algorithms.\n\n Args:\n structure: (structure)\n el_radius_updates: (dict) symbol->float to update atomic radii\n\n Returns: (dict) - (Element1, Element2) -> float. The two elements are\n ordered by Z.\n \"\"\"\n # jmc = JMolCoordFinder(el_radius_updates)\n jmnn = JmolNN(el_radius_updates=el_radius_updates)\n\n bonds_lens = {}\n els = sorted(structure.composition.elements, key=lambda x: x.Z)\n\n for i1, el1 in enumerate(els):\n for i2 in range(len(els) - i1):\n bonds_lens[el1, els[i1 + i2]] = jmnn.get_max_bond_distance(el1.symbol, els[i1 + i2].symbol)\n\n return bonds_lens\n\n\n@deprecated(\n message=(\n \"find_dimension has been moved to\"\n \"pymatgen.analysis.dimensionality.get_dimensionality_gorai\"\n \" this method will be removed in pymatgen v2019.1.1.\"\n )\n)\ndef get_dimensionality(\n structure,\n max_hkl=2,\n el_radius_updates=None,\n min_slab_size=5,\n min_vacuum_size=5,\n standardize=True,\n bonds=None,\n):\n \"\"\"\n This method returns whether a structure is 3D, 2D (layered), or 1D (linear\n chains or molecules) according to the algorithm published in Gorai, P.,\n Toberer, E. & Stevanovic, V. Computational Identification of Promising\n Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater.\n Chem. A 2, 4136 (2016).\n\n Note that a 1D structure detection might indicate problems in the bonding\n algorithm, particularly for ionic crystals (e.g., NaCl)\n\n Users can change the behavior of bonds detection by passing either\n el_radius_updates to update atomic radii for auto-detection of max bond\n distances, or bonds to explicitly specify max bond distances for atom pairs.\n Note that if you pass both, el_radius_updates are ignored.\n\n Args:\n structure: (Structure) structure to analyze dimensionality for\n max_hkl: (int) max index of planes to look for layers\n el_radius_updates: (dict) symbol->float to update atomic radii\n min_slab_size: (float) internal surface construction parameter\n min_vacuum_size: (float) internal surface construction parameter\n standardize (bool): whether to standardize the structure before\n analysis. Set to False only if you already have the structure in a\n convention where layers / chains will be along low <hkl> indexes.\n bonds ({(specie1, specie2): max_bond_dist}: bonds are\n specified as a dict of tuples: float of specie1, specie2\n and the max bonding distance. For example, PO4 groups may be\n defined as {(\"P\", \"O\"): 3}.\n\n Returns: (int) the dimensionality of the structure - 1 (molecules/chains),\n 2 (layered), or 3 (3D)\n\n \"\"\"\n if standardize:\n structure = SpacegroupAnalyzer(structure).get_conventional_standard_structure()\n\n if not bonds:\n bonds = get_max_bond_lengths(structure, el_radius_updates)\n\n num_surfaces = 0\n for h in range(max_hkl):\n for k in range(max_hkl):\n for l in range(max_hkl):\n if max([h, k, l]) > 0 and num_surfaces < 2:\n sg = SlabGenerator(\n structure,\n (h, k, l),\n min_slab_size=min_slab_size,\n min_vacuum_size=min_vacuum_size,\n )\n slabs = sg.get_slabs(bonds)\n for _ in slabs:\n num_surfaces += 1\n\n return 3 - min(num_surfaces, 2)\n\n\ndef contains_peroxide(structure, relative_cutoff=1.1):\n \"\"\"\n Determines if a structure contains peroxide anions.\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff: The peroxide bond distance is 1.49 Angstrom.\n Relative_cutoff * 1.49 stipulates the maximum distance two O\n atoms must be to each other to be considered a peroxide.\n\n Returns:\n Boolean indicating if structure contains a peroxide anion.\n \"\"\"\n return oxide_type(structure, relative_cutoff) == \"peroxide\"\n\n\nclass OxideType:\n \"\"\"\n Separate class for determining oxide type.\n \"\"\"\n\n def __init__(self, structure, relative_cutoff=1.1):\n \"\"\"\n Args:\n structure: Input structure.\n relative_cutoff: Relative_cutoff * act. cutoff stipulates the max.\n distance two O atoms must be from each other. Default value is\n 1.1. At most 1.1 is recommended, nothing larger, otherwise the\n script cannot distinguish between superoxides and peroxides.\n \"\"\"\n self.structure = structure\n self.relative_cutoff = relative_cutoff\n self.oxide_type, self.nbonds = self.parse_oxide()\n\n def parse_oxide(self):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.\n\n Returns:\n oxide_type (str): Type of oxide\n ozonide/peroxide/superoxide/hydroxide/None.\n nbonds (int): Number of peroxide/superoxide/hydroxide bonds in\n structure.\n \"\"\"\n structure = self.structure\n relative_cutoff = self.relative_cutoff\n o_sites_frac_coords = []\n h_sites_frac_coords = []\n lattice = structure.lattice\n\n if isinstance(structure.composition.elements[0], Element):\n comp = structure.composition\n elif isinstance(structure.composition.elements[0], Species):\n elmap = collections.defaultdict(float)\n for site in structure:\n for species, occu in site.species.items():\n elmap[species.element] += occu\n comp = Composition(elmap)\n if Element(\"O\") not in comp or comp.is_element:\n return \"None\", 0\n\n for site in structure:\n syms = [sp.symbol for sp in site.species.keys()]\n if \"O\" in syms:\n o_sites_frac_coords.append(site.frac_coords)\n if \"H\" in syms:\n h_sites_frac_coords.append(site.frac_coords)\n\n if h_sites_frac_coords:\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords, h_sites_frac_coords)\n if np.any(dist_matrix < relative_cutoff * 0.93):\n return (\n \"hydroxide\",\n len(np.where(dist_matrix < relative_cutoff * 0.93)[0]) / 2.0,\n )\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords, o_sites_frac_coords)\n np.fill_diagonal(dist_matrix, 1000)\n is_superoxide = False\n is_peroxide = False\n is_ozonide = False\n if np.any(dist_matrix < relative_cutoff * 1.35):\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.35)[0]\n is_superoxide = True\n elif np.any(dist_matrix < relative_cutoff * 1.49):\n is_peroxide = True\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.49)[0]\n if is_superoxide:\n if len(bond_atoms) > len(set(bond_atoms)):\n is_superoxide = False\n is_ozonide = True\n try:\n nbonds = len(set(bond_atoms))\n except UnboundLocalError:\n nbonds = 0.0\n if is_ozonide:\n str_oxide = \"ozonide\"\n elif is_superoxide:\n str_oxide = \"superoxide\"\n elif is_peroxide:\n str_oxide = \"peroxide\"\n else:\n str_oxide = \"oxide\"\n if str_oxide == \"oxide\":\n nbonds = comp[\"O\"]\n return str_oxide, nbonds\n\n\ndef oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the\n max distance two O atoms must be from each other.\n return_nbonds (bool): Should number of bonds be requested?\n \"\"\"\n\n ox_obj = OxideType(structure, relative_cutoff)\n if return_nbonds:\n return ox_obj.oxide_type, ox_obj.nbonds\n return ox_obj.oxide_type\n\n\ndef sulfide_type(structure):\n \"\"\"\n Determines if a structure is a sulfide/polysulfide/sulfate\n\n Args:\n structure (Structure): Input structure.\n\n Returns:\n (str) sulfide/polysulfide or None if structure is a sulfate.\n \"\"\"\n structure = structure.copy()\n structure.remove_oxidation_states()\n s = Element(\"S\")\n comp = structure.composition\n if comp.is_element or s not in comp:\n return None\n\n finder = SpacegroupAnalyzer(structure, symprec=0.1)\n symm_structure = finder.get_symmetrized_structure()\n s_sites = [sites[0] for sites in symm_structure.equivalent_sites if sites[0].specie == s]\n\n def process_site(site):\n\n # in an exceptionally rare number of structures, the search\n # radius needs to be increased to find a neighbor atom\n search_radius = 4\n neighbors = []\n while len(neighbors) == 0:\n neighbors = structure.get_neighbors(site, search_radius)\n search_radius *= 2\n if search_radius > max(structure.lattice.abc) * 2:\n break\n\n neighbors = sorted(neighbors, key=lambda n: n.nn_distance)\n dist = neighbors[0].nn_distance\n coord_elements = [nn.specie for nn in neighbors if nn.nn_distance < dist + 0.4][:4]\n avg_electroneg = np.mean([e.X for e in coord_elements])\n if avg_electroneg > s.X:\n return \"sulfate\"\n if avg_electroneg == s.X and s in coord_elements:\n return \"polysulfide\"\n return \"sulfide\"\n\n types = {process_site(site) for site in s_sites}\n if \"sulfate\" in types:\n return None\n if \"polysulfide\" in types:\n return \"polysulfide\"\n return \"sulfide\"\n"
]
| [
[
"numpy.dot",
"numpy.mean",
"numpy.where",
"numpy.max",
"numpy.linalg.norm",
"numpy.cross",
"numpy.array",
"scipy.spatial.Voronoi",
"numpy.reshape",
"numpy.zeros",
"matplotlib.pyplot.title",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"numpy.ceil",
"numpy.fill_diagonal",
"numpy.sum",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"numpy.any",
"matplotlib.pyplot.barh"
]
]
|
zhu-eric/ray | [
"8903bcd0c325f76f2642eb542140bdde5a94f7ac"
]
| [
"python/ray/tests/test_basic.py"
]
| [
"# coding: utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nfrom concurrent.futures import ThreadPoolExecutor\nimport glob\nimport json\nimport logging\nfrom multiprocessing import Process\nimport os\nimport random\nimport re\nimport setproctitle\nimport shutil\nimport six\nimport socket\nimport string\nimport subprocess\nimport sys\nimport tempfile\nimport threading\nimport time\n\nimport numpy as np\nimport pickle\nimport pytest\n\nimport ray\nimport ray.ray_constants as ray_constants\nimport ray.tests.cluster_utils\nimport ray.tests.utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_simple_serialization(ray_start_regular):\n primitive_objects = [\n # Various primitive types.\n 0,\n 0.0,\n 0.9,\n 1 << 62,\n 1 << 999,\n \"a\",\n string.printable,\n \"\\u262F\",\n u\"hello world\",\n u\"\\xff\\xfe\\x9c\\x001\\x000\\x00\",\n None,\n True,\n False,\n [],\n (),\n {},\n type,\n int,\n set(),\n # Collections types.\n collections.Counter([np.random.randint(0, 10) for _ in range(100)]),\n collections.OrderedDict([(\"hello\", 1), (\"world\", 2)]),\n collections.defaultdict(lambda: 0, [(\"hello\", 1), (\"world\", 2)]),\n collections.defaultdict(lambda: [], [(\"hello\", 1), (\"world\", 2)]),\n collections.deque([1, 2, 3, \"a\", \"b\", \"c\", 3.5]),\n # Numpy dtypes.\n np.int8(3),\n np.int32(4),\n np.int64(5),\n np.uint8(3),\n np.uint32(4),\n np.uint64(5),\n np.float32(1.9),\n np.float64(1.9),\n ]\n\n if sys.version_info < (3, 0):\n primitive_objects.append(long(0)) # noqa: E501,F821\n\n composite_objects = (\n [[obj]\n for obj in primitive_objects] + [(obj, )\n for obj in primitive_objects] + [{\n (): obj\n } for obj in primitive_objects])\n\n @ray.remote\n def f(x):\n return x\n\n # Check that we can pass arguments by value to remote functions and\n # that they are uncorrupted.\n for obj in primitive_objects + composite_objects:\n new_obj_1 = ray.get(f.remote(obj))\n new_obj_2 = ray.get(ray.put(obj))\n assert obj == new_obj_1\n assert obj == new_obj_2\n # TODO(rkn): The numpy dtypes currently come back as regular integers\n # or floats.\n if type(obj).__module__ != \"numpy\":\n assert type(obj) == type(new_obj_1)\n assert type(obj) == type(new_obj_2)\n\n\ndef test_complex_serialization(ray_start_regular):\n def assert_equal(obj1, obj2):\n module_numpy = (type(obj1).__module__ == np.__name__\n or type(obj2).__module__ == np.__name__)\n if module_numpy:\n empty_shape = ((hasattr(obj1, \"shape\") and obj1.shape == ())\n or (hasattr(obj2, \"shape\") and obj2.shape == ()))\n if empty_shape:\n # This is a special case because currently\n # np.testing.assert_equal fails because we do not properly\n # handle different numerical types.\n assert obj1 == obj2, (\"Objects {} and {} are \"\n \"different.\".format(obj1, obj2))\n else:\n np.testing.assert_equal(obj1, obj2)\n elif hasattr(obj1, \"__dict__\") and hasattr(obj2, \"__dict__\"):\n special_keys = [\"_pytype_\"]\n assert (set(list(obj1.__dict__.keys()) + special_keys) == set(\n list(obj2.__dict__.keys()) + special_keys)), (\n \"Objects {} and {} are different.\".format(obj1, obj2))\n for key in obj1.__dict__.keys():\n if key not in special_keys:\n assert_equal(obj1.__dict__[key], obj2.__dict__[key])\n elif type(obj1) is dict or type(obj2) is dict:\n assert_equal(obj1.keys(), obj2.keys())\n for key in obj1.keys():\n assert_equal(obj1[key], obj2[key])\n elif type(obj1) is list or type(obj2) is list:\n assert len(obj1) == len(obj2), (\"Objects {} and {} are lists with \"\n \"different lengths.\".format(\n obj1, obj2))\n for i in range(len(obj1)):\n assert_equal(obj1[i], obj2[i])\n elif type(obj1) is tuple or type(obj2) is tuple:\n assert len(obj1) == len(obj2), (\"Objects {} and {} are tuples \"\n \"with different lengths.\".format(\n obj1, obj2))\n for i in range(len(obj1)):\n assert_equal(obj1[i], obj2[i])\n elif (ray.serialization.is_named_tuple(type(obj1))\n or ray.serialization.is_named_tuple(type(obj2))):\n assert len(obj1) == len(obj2), (\n \"Objects {} and {} are named \"\n \"tuples with different lengths.\".format(obj1, obj2))\n for i in range(len(obj1)):\n assert_equal(obj1[i], obj2[i])\n else:\n assert obj1 == obj2, \"Objects {} and {} are different.\".format(\n obj1, obj2)\n\n if sys.version_info >= (3, 0):\n long_extras = [0, np.array([[\"hi\", u\"hi\"], [1.3, 1]])]\n else:\n\n long_extras = [\n long(0), # noqa: E501,F821\n np.array([\n [\"hi\", u\"hi\"],\n [1.3, long(1)] # noqa: E501,F821\n ])\n ]\n\n PRIMITIVE_OBJECTS = [\n 0, 0.0, 0.9, 1 << 62, 1 << 100, 1 << 999, [1 << 100, [1 << 100]], \"a\",\n string.printable, \"\\u262F\", u\"hello world\",\n u\"\\xff\\xfe\\x9c\\x001\\x000\\x00\", None, True, False, [], (), {},\n np.int8(3),\n np.int32(4),\n np.int64(5),\n np.uint8(3),\n np.uint32(4),\n np.uint64(5),\n np.float32(1.9),\n np.float64(1.9),\n np.zeros([100, 100]),\n np.random.normal(size=[100, 100]),\n np.array([\"hi\", 3]),\n np.array([\"hi\", 3], dtype=object)\n ] + long_extras\n\n COMPLEX_OBJECTS = [\n [[[[[[[[[[[[]]]]]]]]]]]],\n {\n \"obj{}\".format(i): np.random.normal(size=[100, 100])\n for i in range(10)\n },\n # {(): {(): {(): {(): {(): {(): {(): {(): {(): {(): {\n # (): {(): {}}}}}}}}}}}}},\n (\n (((((((((), ), ), ), ), ), ), ), ), ),\n {\n \"a\": {\n \"b\": {\n \"c\": {\n \"d\": {}\n }\n }\n }\n },\n ]\n\n class Foo(object):\n def __init__(self, value=0):\n self.value = value\n\n def __hash__(self):\n return hash(self.value)\n\n def __eq__(self, other):\n return other.value == self.value\n\n class Bar(object):\n def __init__(self):\n for i, val in enumerate(PRIMITIVE_OBJECTS + COMPLEX_OBJECTS):\n setattr(self, \"field{}\".format(i), val)\n\n class Baz(object):\n def __init__(self):\n self.foo = Foo()\n self.bar = Bar()\n\n def method(self, arg):\n pass\n\n class Qux(object):\n def __init__(self):\n self.objs = [Foo(), Bar(), Baz()]\n\n class SubQux(Qux):\n def __init__(self):\n Qux.__init__(self)\n\n class CustomError(Exception):\n pass\n\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n NamedTupleExample = collections.namedtuple(\n \"Example\", \"field1, field2, field3, field4, field5\")\n\n CUSTOM_OBJECTS = [\n Exception(\"Test object.\"),\n CustomError(),\n Point(11, y=22),\n Foo(),\n Bar(),\n Baz(), # Qux(), SubQux(),\n NamedTupleExample(1, 1.0, \"hi\", np.zeros([3, 5]), [1, 2, 3]),\n ]\n\n # Test dataclasses in Python 3.7.\n if sys.version_info >= (3, 7):\n from dataclasses import make_dataclass\n\n DataClass0 = make_dataclass(\"DataClass0\", [(\"number\", int)])\n\n CUSTOM_OBJECTS.append(DataClass0(number=3))\n\n class CustomClass(object):\n def __init__(self, value):\n self.value = value\n\n DataClass1 = make_dataclass(\"DataClass1\", [(\"custom\", CustomClass)])\n\n class DataClass2(DataClass1):\n @classmethod\n def from_custom(cls, data):\n custom = CustomClass(data)\n return cls(custom)\n\n def __reduce__(self):\n return (self.from_custom, (self.custom.value, ))\n\n CUSTOM_OBJECTS.append(DataClass2(custom=CustomClass(43)))\n\n BASE_OBJECTS = PRIMITIVE_OBJECTS + COMPLEX_OBJECTS + CUSTOM_OBJECTS\n\n LIST_OBJECTS = [[obj] for obj in BASE_OBJECTS]\n TUPLE_OBJECTS = [(obj, ) for obj in BASE_OBJECTS]\n # The check that type(obj).__module__ != \"numpy\" should be unnecessary, but\n # otherwise this seems to fail on Mac OS X on Travis.\n DICT_OBJECTS = ([{\n obj: obj\n } for obj in PRIMITIVE_OBJECTS if (\n obj.__hash__ is not None and type(obj).__module__ != \"numpy\")] + [{\n 0: obj\n } for obj in BASE_OBJECTS] + [{\n Foo(123): Foo(456)\n }])\n\n RAY_TEST_OBJECTS = (\n BASE_OBJECTS + LIST_OBJECTS + TUPLE_OBJECTS + DICT_OBJECTS)\n\n @ray.remote\n def f(x):\n return x\n\n # Check that we can pass arguments by value to remote functions and\n # that they are uncorrupted.\n for obj in RAY_TEST_OBJECTS:\n assert_equal(obj, ray.get(f.remote(obj)))\n assert_equal(obj, ray.get(ray.put(obj)))\n\n\ndef test_nested_functions(ray_start_regular):\n # Make sure that remote functions can use other values that are defined\n # after the remote function but before the first function invocation.\n @ray.remote\n def f():\n return g(), ray.get(h.remote())\n\n def g():\n return 1\n\n @ray.remote\n def h():\n return 2\n\n assert ray.get(f.remote()) == (1, 2)\n\n # Test a remote function that recursively calls itself.\n\n @ray.remote\n def factorial(n):\n if n == 0:\n return 1\n return n * ray.get(factorial.remote(n - 1))\n\n assert ray.get(factorial.remote(0)) == 1\n assert ray.get(factorial.remote(1)) == 1\n assert ray.get(factorial.remote(2)) == 2\n assert ray.get(factorial.remote(3)) == 6\n assert ray.get(factorial.remote(4)) == 24\n assert ray.get(factorial.remote(5)) == 120\n\n # Test remote functions that recursively call each other.\n\n @ray.remote\n def factorial_even(n):\n assert n % 2 == 0\n if n == 0:\n return 1\n return n * ray.get(factorial_odd.remote(n - 1))\n\n @ray.remote\n def factorial_odd(n):\n assert n % 2 == 1\n return n * ray.get(factorial_even.remote(n - 1))\n\n assert ray.get(factorial_even.remote(4)) == 24\n assert ray.get(factorial_odd.remote(5)) == 120\n\n\ndef test_ray_recursive_objects(ray_start_regular):\n class ClassA(object):\n pass\n\n # Make a list that contains itself.\n lst = []\n lst.append(lst)\n # Make an object that contains itself as a field.\n a1 = ClassA()\n a1.field = a1\n # Make two objects that contain each other as fields.\n a2 = ClassA()\n a3 = ClassA()\n a2.field = a3\n a3.field = a2\n # Make a dictionary that contains itself.\n d1 = {}\n d1[\"key\"] = d1\n # Create a list of recursive objects.\n recursive_objects = [lst, a1, a2, a3, d1]\n\n if ray.worker.USE_NEW_SERIALIZER:\n # Serialize the recursive objects.\n for obj in recursive_objects:\n ray.put(obj)\n else:\n # Check that exceptions are thrown when we serialize the recursive\n # objects.\n for obj in recursive_objects:\n with pytest.raises(Exception):\n ray.put(obj)\n\n\ndef test_passing_arguments_by_value_out_of_the_box(ray_start_regular):\n @ray.remote\n def f(x):\n return x\n\n # Test passing lambdas.\n\n def temp():\n return 1\n\n assert ray.get(f.remote(temp))() == 1\n assert ray.get(f.remote(lambda x: x + 1))(3) == 4\n\n # Test sets.\n assert ray.get(f.remote(set())) == set()\n s = {1, (1, 2, \"hi\")}\n assert ray.get(f.remote(s)) == s\n\n # Test types.\n assert ray.get(f.remote(int)) == int\n assert ray.get(f.remote(float)) == float\n assert ray.get(f.remote(str)) == str\n\n class Foo(object):\n def __init__(self):\n pass\n\n # Make sure that we can put and get a custom type. Note that the result\n # won't be \"equal\" to Foo.\n ray.get(ray.put(Foo))\n\n\ndef test_putting_object_that_closes_over_object_id(ray_start_regular):\n # This test is here to prevent a regression of\n # https://github.com/ray-project/ray/issues/1317.\n\n class Foo(object):\n def __init__(self):\n self.val = ray.put(0)\n\n def method(self):\n f\n\n f = Foo()\n ray.put(f)\n\n\ndef test_put_get(shutdown_only):\n ray.init(num_cpus=0)\n\n for i in range(100):\n value_before = i * 10**6\n objectid = ray.put(value_before)\n value_after = ray.get(objectid)\n assert value_before == value_after\n\n for i in range(100):\n value_before = i * 10**6 * 1.0\n objectid = ray.put(value_before)\n value_after = ray.get(objectid)\n assert value_before == value_after\n\n for i in range(100):\n value_before = \"h\" * i\n objectid = ray.put(value_before)\n value_after = ray.get(objectid)\n assert value_before == value_after\n\n for i in range(100):\n value_before = [1] * i\n objectid = ray.put(value_before)\n value_after = ray.get(objectid)\n assert value_before == value_after\n\n\ndef test_custom_serializers(ray_start_regular):\n class Foo(object):\n def __init__(self):\n self.x = 3\n\n def custom_serializer(obj):\n return 3, \"string1\", type(obj).__name__\n\n def custom_deserializer(serialized_obj):\n return serialized_obj, \"string2\"\n\n ray.register_custom_serializer(\n Foo, serializer=custom_serializer, deserializer=custom_deserializer)\n\n assert ray.get(ray.put(Foo())) == ((3, \"string1\", Foo.__name__), \"string2\")\n\n class Bar(object):\n def __init__(self):\n self.x = 3\n\n ray.register_custom_serializer(\n Bar, serializer=custom_serializer, deserializer=custom_deserializer)\n\n @ray.remote\n def f():\n return Bar()\n\n assert ray.get(f.remote()) == ((3, \"string1\", Bar.__name__), \"string2\")\n\n\ndef test_serialization_final_fallback(ray_start_regular):\n pytest.importorskip(\"catboost\")\n # This test will only run when \"catboost\" is installed.\n from catboost import CatBoostClassifier\n\n model = CatBoostClassifier(\n iterations=2,\n depth=2,\n learning_rate=1,\n loss_function=\"Logloss\",\n logging_level=\"Verbose\")\n\n reconstructed_model = ray.get(ray.put(model))\n assert set(model.get_params().items()) == set(\n reconstructed_model.get_params().items())\n\n\ndef test_register_class(ray_start_2_cpus):\n # Check that putting an object of a class that has not been registered\n # throws an exception.\n class TempClass(object):\n pass\n\n ray.get(ray.put(TempClass()))\n\n # Test passing custom classes into remote functions from the driver.\n @ray.remote\n def f(x):\n return x\n\n class Foo(object):\n def __init__(self, value=0):\n self.value = value\n\n def __hash__(self):\n return hash(self.value)\n\n def __eq__(self, other):\n return other.value == self.value\n\n foo = ray.get(f.remote(Foo(7)))\n assert foo == Foo(7)\n\n regex = re.compile(r\"\\d+\\.\\d*\")\n new_regex = ray.get(f.remote(regex))\n # This seems to fail on the system Python 3 that comes with\n # Ubuntu, so it is commented out for now:\n # assert regex == new_regex\n # Instead, we do this:\n assert regex.pattern == new_regex.pattern\n\n class TempClass1(object):\n def __init__(self):\n self.value = 1\n\n # Test returning custom classes created on workers.\n @ray.remote\n def g():\n class TempClass2(object):\n def __init__(self):\n self.value = 2\n\n return TempClass1(), TempClass2()\n\n object_1, object_2 = ray.get(g.remote())\n assert object_1.value == 1\n assert object_2.value == 2\n\n # Test exporting custom class definitions from one worker to another\n # when the worker is blocked in a get.\n class NewTempClass(object):\n def __init__(self, value):\n self.value = value\n\n @ray.remote\n def h1(x):\n return NewTempClass(x)\n\n @ray.remote\n def h2(x):\n return ray.get(h1.remote(x))\n\n assert ray.get(h2.remote(10)).value == 10\n\n # Test registering multiple classes with the same name.\n @ray.remote(num_return_vals=3)\n def j():\n class Class0(object):\n def method0(self):\n pass\n\n c0 = Class0()\n\n class Class0(object):\n def method1(self):\n pass\n\n c1 = Class0()\n\n class Class0(object):\n def method2(self):\n pass\n\n c2 = Class0()\n\n return c0, c1, c2\n\n results = []\n for _ in range(5):\n results += j.remote()\n for i in range(len(results) // 3):\n c0, c1, c2 = ray.get(results[(3 * i):(3 * (i + 1))])\n\n c0.method0()\n c1.method1()\n c2.method2()\n\n assert not hasattr(c0, \"method1\")\n assert not hasattr(c0, \"method2\")\n assert not hasattr(c1, \"method0\")\n assert not hasattr(c1, \"method2\")\n assert not hasattr(c2, \"method0\")\n assert not hasattr(c2, \"method1\")\n\n @ray.remote\n def k():\n class Class0(object):\n def method0(self):\n pass\n\n c0 = Class0()\n\n class Class0(object):\n def method1(self):\n pass\n\n c1 = Class0()\n\n class Class0(object):\n def method2(self):\n pass\n\n c2 = Class0()\n\n return c0, c1, c2\n\n results = ray.get([k.remote() for _ in range(5)])\n for c0, c1, c2 in results:\n c0.method0()\n c1.method1()\n c2.method2()\n\n assert not hasattr(c0, \"method1\")\n assert not hasattr(c0, \"method2\")\n assert not hasattr(c1, \"method0\")\n assert not hasattr(c1, \"method2\")\n assert not hasattr(c2, \"method0\")\n assert not hasattr(c2, \"method1\")\n\n\ndef test_keyword_args(ray_start_regular):\n @ray.remote\n def keyword_fct1(a, b=\"hello\"):\n return \"{} {}\".format(a, b)\n\n @ray.remote\n def keyword_fct2(a=\"hello\", b=\"world\"):\n return \"{} {}\".format(a, b)\n\n @ray.remote\n def keyword_fct3(a, b, c=\"hello\", d=\"world\"):\n return \"{} {} {} {}\".format(a, b, c, d)\n\n x = keyword_fct1.remote(1)\n assert ray.get(x) == \"1 hello\"\n x = keyword_fct1.remote(1, \"hi\")\n assert ray.get(x) == \"1 hi\"\n x = keyword_fct1.remote(1, b=\"world\")\n assert ray.get(x) == \"1 world\"\n x = keyword_fct1.remote(a=1, b=\"world\")\n assert ray.get(x) == \"1 world\"\n\n x = keyword_fct2.remote(a=\"w\", b=\"hi\")\n assert ray.get(x) == \"w hi\"\n x = keyword_fct2.remote(b=\"hi\", a=\"w\")\n assert ray.get(x) == \"w hi\"\n x = keyword_fct2.remote(a=\"w\")\n assert ray.get(x) == \"w world\"\n x = keyword_fct2.remote(b=\"hi\")\n assert ray.get(x) == \"hello hi\"\n x = keyword_fct2.remote(\"w\")\n assert ray.get(x) == \"w world\"\n x = keyword_fct2.remote(\"w\", \"hi\")\n assert ray.get(x) == \"w hi\"\n\n x = keyword_fct3.remote(0, 1, c=\"w\", d=\"hi\")\n assert ray.get(x) == \"0 1 w hi\"\n x = keyword_fct3.remote(0, b=1, c=\"w\", d=\"hi\")\n assert ray.get(x) == \"0 1 w hi\"\n x = keyword_fct3.remote(a=0, b=1, c=\"w\", d=\"hi\")\n assert ray.get(x) == \"0 1 w hi\"\n x = keyword_fct3.remote(0, 1, d=\"hi\", c=\"w\")\n assert ray.get(x) == \"0 1 w hi\"\n x = keyword_fct3.remote(0, 1, c=\"w\")\n assert ray.get(x) == \"0 1 w world\"\n x = keyword_fct3.remote(0, 1, d=\"hi\")\n assert ray.get(x) == \"0 1 hello hi\"\n x = keyword_fct3.remote(0, 1)\n assert ray.get(x) == \"0 1 hello world\"\n x = keyword_fct3.remote(a=0, b=1)\n assert ray.get(x) == \"0 1 hello world\"\n\n # Check that we cannot pass invalid keyword arguments to functions.\n @ray.remote\n def f1():\n return\n\n @ray.remote\n def f2(x, y=0, z=0):\n return\n\n # Make sure we get an exception if too many arguments are passed in.\n with pytest.raises(Exception):\n f1.remote(3)\n\n with pytest.raises(Exception):\n f1.remote(x=3)\n\n with pytest.raises(Exception):\n f2.remote(0, w=0)\n\n with pytest.raises(Exception):\n f2.remote(3, x=3)\n\n # Make sure we get an exception if too many arguments are passed in.\n with pytest.raises(Exception):\n f2.remote(1, 2, 3, 4)\n\n @ray.remote\n def f3(x):\n return x\n\n assert ray.get(f3.remote(4)) == 4\n\n\ndef test_variable_number_of_args(shutdown_only):\n @ray.remote\n def varargs_fct1(*a):\n return \" \".join(map(str, a))\n\n @ray.remote\n def varargs_fct2(a, *b):\n return \" \".join(map(str, b))\n\n try:\n\n @ray.remote\n def kwargs_throw_exception(**c):\n return ()\n\n kwargs_exception_thrown = False\n except Exception:\n kwargs_exception_thrown = True\n\n ray.init(num_cpus=1)\n\n x = varargs_fct1.remote(0, 1, 2)\n assert ray.get(x) == \"0 1 2\"\n x = varargs_fct2.remote(0, 1, 2)\n assert ray.get(x) == \"1 2\"\n\n assert kwargs_exception_thrown\n\n @ray.remote\n def f1(*args):\n return args\n\n @ray.remote\n def f2(x, y, *args):\n return x, y, args\n\n assert ray.get(f1.remote()) == ()\n assert ray.get(f1.remote(1)) == (1, )\n assert ray.get(f1.remote(1, 2, 3)) == (1, 2, 3)\n with pytest.raises(Exception):\n f2.remote()\n with pytest.raises(Exception):\n f2.remote(1)\n assert ray.get(f2.remote(1, 2)) == (1, 2, ())\n assert ray.get(f2.remote(1, 2, 3)) == (1, 2, (3, ))\n assert ray.get(f2.remote(1, 2, 3, 4)) == (1, 2, (3, 4))\n\n def testNoArgs(self):\n @ray.remote\n def no_op():\n pass\n\n self.ray_start()\n\n ray.get(no_op.remote())\n\n\ndef test_defining_remote_functions(shutdown_only):\n ray.init(num_cpus=3)\n\n # Test that we can define a remote function in the shell.\n @ray.remote\n def f(x):\n return x + 1\n\n assert ray.get(f.remote(0)) == 1\n\n # Test that we can redefine the remote function.\n @ray.remote\n def f(x):\n return x + 10\n\n while True:\n val = ray.get(f.remote(0))\n assert val in [1, 10]\n if val == 10:\n break\n else:\n logger.info(\"Still using old definition of f, trying again.\")\n\n # Test that we can close over plain old data.\n data = [\n np.zeros([3, 5]), (1, 2, \"a\"), [0.0, 1.0, 1 << 62], 1 << 60, {\n \"a\": np.zeros(3)\n }\n ]\n\n @ray.remote\n def g():\n return data\n\n ray.get(g.remote())\n\n # Test that we can close over modules.\n @ray.remote\n def h():\n return np.zeros([3, 5])\n\n assert np.alltrue(ray.get(h.remote()) == np.zeros([3, 5]))\n\n @ray.remote\n def j():\n return time.time()\n\n ray.get(j.remote())\n\n # Test that we can define remote functions that call other remote\n # functions.\n @ray.remote\n def k(x):\n return x + 1\n\n @ray.remote\n def k2(x):\n return ray.get(k.remote(x))\n\n @ray.remote\n def m(x):\n return ray.get(k2.remote(x))\n\n assert ray.get(k.remote(1)) == 2\n assert ray.get(k2.remote(1)) == 2\n assert ray.get(m.remote(1)) == 2\n\n\ndef test_submit_api(shutdown_only):\n ray.init(num_cpus=2, num_gpus=1, resources={\"Custom\": 1})\n\n @ray.remote\n def f(n):\n return list(range(n))\n\n @ray.remote\n def g():\n return ray.get_gpu_ids()\n\n assert f._remote([0], num_return_vals=0) is None\n id1 = f._remote(args=[1], num_return_vals=1)\n assert ray.get(id1) == [0]\n id1, id2 = f._remote(args=[2], num_return_vals=2)\n assert ray.get([id1, id2]) == [0, 1]\n id1, id2, id3 = f._remote(args=[3], num_return_vals=3)\n assert ray.get([id1, id2, id3]) == [0, 1, 2]\n assert ray.get(\n g._remote(args=[], num_cpus=1, num_gpus=1,\n resources={\"Custom\": 1})) == [0]\n infeasible_id = g._remote(args=[], resources={\"NonexistentCustom\": 1})\n assert ray.get(g._remote()) == []\n ready_ids, remaining_ids = ray.wait([infeasible_id], timeout=0.05)\n assert len(ready_ids) == 0\n assert len(remaining_ids) == 1\n\n @ray.remote\n class Actor(object):\n def __init__(self, x, y=0):\n self.x = x\n self.y = y\n\n def method(self, a, b=0):\n return self.x, self.y, a, b\n\n def gpu_ids(self):\n return ray.get_gpu_ids()\n\n @ray.remote\n class Actor2(object):\n def __init__(self):\n pass\n\n def method(self):\n pass\n\n a = Actor._remote(\n args=[0], kwargs={\"y\": 1}, num_gpus=1, resources={\"Custom\": 1})\n\n a2 = Actor2._remote()\n ray.get(a2.method._remote())\n\n id1, id2, id3, id4 = a.method._remote(\n args=[\"test\"], kwargs={\"b\": 2}, num_return_vals=4)\n assert ray.get([id1, id2, id3, id4]) == [0, 1, \"test\", 2]\n\n\ndef test_many_fractional_resources(shutdown_only):\n ray.init(num_cpus=2, num_gpus=2, resources={\"Custom\": 2})\n\n @ray.remote\n def g():\n return 1\n\n @ray.remote\n def f(block, accepted_resources):\n true_resources = {\n resource: value[0][1]\n for resource, value in ray.get_resource_ids().items()\n }\n if block:\n ray.get(g.remote())\n return true_resources == accepted_resources\n\n # Check that the resource are assigned correctly.\n result_ids = []\n for rand1, rand2, rand3 in np.random.uniform(size=(100, 3)):\n resource_set = {\"CPU\": int(rand1 * 10000) / 10000}\n result_ids.append(f._remote([False, resource_set], num_cpus=rand1))\n\n resource_set = {\"CPU\": 1, \"GPU\": int(rand1 * 10000) / 10000}\n result_ids.append(f._remote([False, resource_set], num_gpus=rand1))\n\n resource_set = {\"CPU\": 1, \"Custom\": int(rand1 * 10000) / 10000}\n result_ids.append(\n f._remote([False, resource_set], resources={\"Custom\": rand1}))\n\n resource_set = {\n \"CPU\": int(rand1 * 10000) / 10000,\n \"GPU\": int(rand2 * 10000) / 10000,\n \"Custom\": int(rand3 * 10000) / 10000\n }\n result_ids.append(\n f._remote(\n [False, resource_set],\n num_cpus=rand1,\n num_gpus=rand2,\n resources={\"Custom\": rand3}))\n result_ids.append(\n f._remote(\n [True, resource_set],\n num_cpus=rand1,\n num_gpus=rand2,\n resources={\"Custom\": rand3}))\n assert all(ray.get(result_ids))\n\n # Check that the available resources at the end are the same as the\n # beginning.\n stop_time = time.time() + 10\n correct_available_resources = False\n while time.time() < stop_time:\n if (ray.available_resources()[\"CPU\"] == 2.0\n and ray.available_resources()[\"GPU\"] == 2.0\n and ray.available_resources()[\"Custom\"] == 2.0):\n correct_available_resources = True\n break\n if not correct_available_resources:\n assert False, \"Did not get correct available resources.\"\n\n\ndef test_get_multiple(ray_start_regular):\n object_ids = [ray.put(i) for i in range(10)]\n assert ray.get(object_ids) == list(range(10))\n\n # Get a random choice of object IDs with duplicates.\n indices = list(np.random.choice(range(10), 5))\n indices += indices\n results = ray.get([object_ids[i] for i in indices])\n assert results == indices\n\n\ndef test_get_multiple_experimental(ray_start_regular):\n object_ids = [ray.put(i) for i in range(10)]\n\n object_ids_tuple = tuple(object_ids)\n assert ray.experimental.get(object_ids_tuple) == list(range(10))\n\n object_ids_nparray = np.array(object_ids)\n assert ray.experimental.get(object_ids_nparray) == list(range(10))\n\n\ndef test_get_dict(ray_start_regular):\n d = {str(i): ray.put(i) for i in range(5)}\n for i in range(5, 10):\n d[str(i)] = i\n result = ray.experimental.get(d)\n expected = {str(i): i for i in range(10)}\n assert result == expected\n\n\ndef test_wait(ray_start_regular):\n @ray.remote\n def f(delay):\n time.sleep(delay)\n return 1\n\n objectids = [f.remote(1.0), f.remote(0.5), f.remote(0.5), f.remote(0.5)]\n ready_ids, remaining_ids = ray.wait(objectids)\n assert len(ready_ids) == 1\n assert len(remaining_ids) == 3\n ready_ids, remaining_ids = ray.wait(objectids, num_returns=4)\n assert set(ready_ids) == set(objectids)\n assert remaining_ids == []\n\n objectids = [f.remote(0.5), f.remote(0.5), f.remote(0.5), f.remote(0.5)]\n start_time = time.time()\n ready_ids, remaining_ids = ray.wait(objectids, timeout=1.75, num_returns=4)\n assert time.time() - start_time < 2\n assert len(ready_ids) == 3\n assert len(remaining_ids) == 1\n ray.wait(objectids)\n objectids = [f.remote(1.0), f.remote(0.5), f.remote(0.5), f.remote(0.5)]\n start_time = time.time()\n ready_ids, remaining_ids = ray.wait(objectids, timeout=5.0)\n assert time.time() - start_time < 5\n assert len(ready_ids) == 1\n assert len(remaining_ids) == 3\n\n # Verify that calling wait with duplicate object IDs throws an\n # exception.\n x = ray.put(1)\n with pytest.raises(Exception):\n ray.wait([x, x])\n\n # Make sure it is possible to call wait with an empty list.\n ready_ids, remaining_ids = ray.wait([])\n assert ready_ids == []\n assert remaining_ids == []\n\n # Test semantics of num_returns with no timeout.\n oids = [ray.put(i) for i in range(10)]\n (found, rest) = ray.wait(oids, num_returns=2)\n assert len(found) == 2\n assert len(rest) == 8\n\n # Verify that incorrect usage raises a TypeError.\n x = ray.put(1)\n with pytest.raises(TypeError):\n ray.wait(x)\n with pytest.raises(TypeError):\n ray.wait(1)\n with pytest.raises(TypeError):\n ray.wait([1])\n\n\ndef test_wait_iterables(ray_start_regular):\n @ray.remote\n def f(delay):\n time.sleep(delay)\n return 1\n\n objectids = (f.remote(1.0), f.remote(0.5), f.remote(0.5), f.remote(0.5))\n ready_ids, remaining_ids = ray.experimental.wait(objectids)\n assert len(ready_ids) == 1\n assert len(remaining_ids) == 3\n\n objectids = np.array(\n [f.remote(1.0),\n f.remote(0.5),\n f.remote(0.5),\n f.remote(0.5)])\n ready_ids, remaining_ids = ray.experimental.wait(objectids)\n assert len(ready_ids) == 1\n assert len(remaining_ids) == 3\n\n\ndef test_multiple_waits_and_gets(shutdown_only):\n # It is important to use three workers here, so that the three tasks\n # launched in this experiment can run at the same time.\n ray.init(num_cpus=3)\n\n @ray.remote\n def f(delay):\n time.sleep(delay)\n return 1\n\n @ray.remote\n def g(l):\n # The argument l should be a list containing one object ID.\n ray.wait([l[0]])\n\n @ray.remote\n def h(l):\n # The argument l should be a list containing one object ID.\n ray.get(l[0])\n\n # Make sure that multiple wait requests involving the same object ID\n # all return.\n x = f.remote(1)\n ray.get([g.remote([x]), g.remote([x])])\n\n # Make sure that multiple get requests involving the same object ID all\n # return.\n x = f.remote(1)\n ray.get([h.remote([x]), h.remote([x])])\n\n\ndef test_caching_functions_to_run(shutdown_only):\n # Test that we export functions to run on all workers before the driver\n # is connected.\n def f(worker_info):\n sys.path.append(1)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n def f(worker_info):\n sys.path.append(2)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n def g(worker_info):\n sys.path.append(3)\n\n ray.worker.global_worker.run_function_on_all_workers(g)\n\n def f(worker_info):\n sys.path.append(4)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n ray.init(num_cpus=1)\n\n @ray.remote\n def get_state():\n time.sleep(1)\n return sys.path[-4], sys.path[-3], sys.path[-2], sys.path[-1]\n\n res1 = get_state.remote()\n res2 = get_state.remote()\n assert ray.get(res1) == (1, 2, 3, 4)\n assert ray.get(res2) == (1, 2, 3, 4)\n\n # Clean up the path on the workers.\n def f(worker_info):\n sys.path.pop()\n sys.path.pop()\n sys.path.pop()\n sys.path.pop()\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n\ndef test_running_function_on_all_workers(ray_start_regular):\n def f(worker_info):\n sys.path.append(\"fake_directory\")\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n @ray.remote\n def get_path1():\n return sys.path\n\n assert \"fake_directory\" == ray.get(get_path1.remote())[-1]\n\n def f(worker_info):\n sys.path.pop(-1)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n # Create a second remote function to guarantee that when we call\n # get_path2.remote(), the second function to run will have been run on\n # the worker.\n @ray.remote\n def get_path2():\n return sys.path\n\n assert \"fake_directory\" not in ray.get(get_path2.remote())\n\n\ndef test_profiling_api(ray_start_2_cpus):\n @ray.remote\n def f():\n with ray.profile(\n \"custom_event\",\n extra_data={\"name\": \"custom name\"}) as ray_prof:\n ray_prof.set_attribute(\"key\", \"value\")\n\n ray.put(1)\n object_id = f.remote()\n ray.wait([object_id])\n ray.get(object_id)\n\n # Wait until all of the profiling information appears in the profile\n # table.\n timeout_seconds = 20\n start_time = time.time()\n while True:\n if time.time() - start_time > timeout_seconds:\n raise Exception(\"Timed out while waiting for information in \"\n \"profile table.\")\n profile_data = ray.timeline()\n event_types = {event[\"cat\"] for event in profile_data}\n expected_types = [\n \"worker_idle\",\n \"task\",\n \"task:deserialize_arguments\",\n \"task:execute\",\n \"task:store_outputs\",\n \"wait_for_function\",\n \"ray.get\",\n \"ray.put\",\n \"ray.wait\",\n \"submit_task\",\n \"fetch_and_run_function\",\n \"register_remote_function\",\n \"custom_event\", # This is the custom one from ray.profile.\n ]\n\n if all(expected_type in event_types\n for expected_type in expected_types):\n break\n\n\ndef test_wait_cluster(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=1, resources={\"RemoteResource\": 1})\n cluster.add_node(num_cpus=1, resources={\"RemoteResource\": 1})\n ray.init(address=cluster.address)\n\n @ray.remote(resources={\"RemoteResource\": 1})\n def f():\n return\n\n # Make sure we have enough workers on the remote nodes to execute some\n # tasks.\n tasks = [f.remote() for _ in range(10)]\n start = time.time()\n ray.get(tasks)\n end = time.time()\n\n # Submit some more tasks that can only be executed on the remote nodes.\n tasks = [f.remote() for _ in range(10)]\n # Sleep for a bit to let the tasks finish.\n time.sleep((end - start) * 2)\n _, unready = ray.wait(tasks, num_returns=len(tasks), timeout=0)\n # All remote tasks should have finished.\n assert len(unready) == 0\n\n\ndef test_object_transfer_dump(ray_start_cluster):\n cluster = ray_start_cluster\n\n num_nodes = 3\n for i in range(num_nodes):\n cluster.add_node(resources={str(i): 1}, object_store_memory=10**9)\n ray.init(address=cluster.address)\n\n @ray.remote\n def f(x):\n return\n\n # These objects will live on different nodes.\n object_ids = [\n f._remote(args=[1], resources={str(i): 1}) for i in range(num_nodes)\n ]\n\n # Broadcast each object from each machine to each other machine.\n for object_id in object_ids:\n ray.get([\n f._remote(args=[object_id], resources={str(i): 1})\n for i in range(num_nodes)\n ])\n\n # The profiling information only flushes once every second.\n time.sleep(1.1)\n\n transfer_dump = ray.object_transfer_timeline()\n # Make sure the transfer dump can be serialized with JSON.\n json.loads(json.dumps(transfer_dump))\n assert len(transfer_dump) >= num_nodes**2\n assert len({\n event[\"pid\"]\n for event in transfer_dump if event[\"name\"] == \"transfer_receive\"\n }) == num_nodes\n assert len({\n event[\"pid\"]\n for event in transfer_dump if event[\"name\"] == \"transfer_send\"\n }) == num_nodes\n\n\ndef test_identical_function_names(ray_start_regular):\n # Define a bunch of remote functions and make sure that we don't\n # accidentally call an older version.\n\n num_calls = 200\n\n @ray.remote\n def f():\n return 1\n\n results1 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 2\n\n results2 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 3\n\n results3 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 4\n\n results4 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 5\n\n results5 = [f.remote() for _ in range(num_calls)]\n\n assert ray.get(results1) == num_calls * [1]\n assert ray.get(results2) == num_calls * [2]\n assert ray.get(results3) == num_calls * [3]\n assert ray.get(results4) == num_calls * [4]\n assert ray.get(results5) == num_calls * [5]\n\n @ray.remote\n def g():\n return 1\n\n @ray.remote # noqa: F811\n def g():\n return 2\n\n @ray.remote # noqa: F811\n def g():\n return 3\n\n @ray.remote # noqa: F811\n def g():\n return 4\n\n @ray.remote # noqa: F811\n def g():\n return 5\n\n result_values = ray.get([g.remote() for _ in range(num_calls)])\n assert result_values == num_calls * [5]\n\n\ndef test_illegal_api_calls(ray_start_regular):\n\n # Verify that we cannot call put on an ObjectID.\n x = ray.put(1)\n with pytest.raises(Exception):\n ray.put(x)\n # Verify that we cannot call get on a regular value.\n with pytest.raises(Exception):\n ray.get(3)\n\n\n# TODO(hchen): This test currently doesn't work in Python 2. This is likely\n# because plasma client isn't thread-safe. This needs to be fixed from the\n# Arrow side. See #4107 for relevant discussions.\[email protected](six.PY2, reason=\"Doesn't work in Python 2.\")\ndef test_multithreading(ray_start_2_cpus):\n # This test requires at least 2 CPUs to finish since the worker does not\n # release resources when joining the threads.\n\n def run_test_in_multi_threads(test_case, num_threads=10, num_repeats=25):\n \"\"\"A helper function that runs test cases in multiple threads.\"\"\"\n\n def wrapper():\n for _ in range(num_repeats):\n test_case()\n time.sleep(random.randint(0, 10) / 1000.0)\n return \"ok\"\n\n executor = ThreadPoolExecutor(max_workers=num_threads)\n futures = [executor.submit(wrapper) for _ in range(num_threads)]\n for future in futures:\n assert future.result() == \"ok\"\n\n @ray.remote\n def echo(value, delay_ms=0):\n if delay_ms > 0:\n time.sleep(delay_ms / 1000.0)\n return value\n\n @ray.remote\n class Echo(object):\n def echo(self, value):\n return value\n\n def test_api_in_multi_threads():\n \"\"\"Test using Ray api in multiple threads.\"\"\"\n\n # Test calling remote functions in multiple threads.\n def test_remote_call():\n value = random.randint(0, 1000000)\n result = ray.get(echo.remote(value))\n assert value == result\n\n run_test_in_multi_threads(test_remote_call)\n\n # Test multiple threads calling one actor.\n actor = Echo.remote()\n\n def test_call_actor():\n value = random.randint(0, 1000000)\n result = ray.get(actor.echo.remote(value))\n assert value == result\n\n run_test_in_multi_threads(test_call_actor)\n\n # Test put and get.\n def test_put_and_get():\n value = random.randint(0, 1000000)\n result = ray.get(ray.put(value))\n assert value == result\n\n run_test_in_multi_threads(test_put_and_get)\n\n # Test multiple threads waiting for objects.\n num_wait_objects = 10\n objects = [\n echo.remote(i, delay_ms=10) for i in range(num_wait_objects)\n ]\n\n def test_wait():\n ready, _ = ray.wait(\n objects,\n num_returns=len(objects),\n timeout=1000.0,\n )\n assert len(ready) == num_wait_objects\n assert ray.get(ready) == list(range(num_wait_objects))\n\n run_test_in_multi_threads(test_wait, num_repeats=1)\n\n # Run tests in a driver.\n test_api_in_multi_threads()\n\n # Run tests in a worker.\n @ray.remote\n def run_tests_in_worker():\n test_api_in_multi_threads()\n return \"ok\"\n\n assert ray.get(run_tests_in_worker.remote()) == \"ok\"\n\n # Test actor that runs background threads.\n @ray.remote\n class MultithreadedActor(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.thread_results = []\n\n def background_thread(self, wait_objects):\n try:\n # Test wait\n ready, _ = ray.wait(\n wait_objects,\n num_returns=len(wait_objects),\n timeout=1000.0,\n )\n assert len(ready) == len(wait_objects)\n for _ in range(20):\n num = 10\n # Test remote call\n results = [echo.remote(i) for i in range(num)]\n assert ray.get(results) == list(range(num))\n # Test put and get\n objects = [ray.put(i) for i in range(num)]\n assert ray.get(objects) == list(range(num))\n time.sleep(random.randint(0, 10) / 1000.0)\n except Exception as e:\n with self.lock:\n self.thread_results.append(e)\n else:\n with self.lock:\n self.thread_results.append(\"ok\")\n\n def spawn(self):\n wait_objects = [echo.remote(i, delay_ms=10) for i in range(10)]\n self.threads = [\n threading.Thread(\n target=self.background_thread, args=(wait_objects, ))\n for _ in range(20)\n ]\n [thread.start() for thread in self.threads]\n\n def join(self):\n [thread.join() for thread in self.threads]\n assert self.thread_results == [\"ok\"] * len(self.threads)\n return \"ok\"\n\n actor = MultithreadedActor.remote()\n actor.spawn.remote()\n ray.get(actor.join.remote()) == \"ok\"\n\n\ndef test_free_objects_multi_node(ray_start_cluster):\n # This test will do following:\n # 1. Create 3 raylets that each hold an actor.\n # 2. Each actor creates an object which is the deletion target.\n # 3. Wait 0.1 second for the objects to be deleted.\n # 4. Check that the deletion targets have been deleted.\n # Caution: if remote functions are used instead of actor methods,\n # one raylet may create more than one worker to execute the\n # tasks, so the flushing operations may be executed in different\n # workers and the plasma client holding the deletion target\n # may not be flushed.\n cluster = ray_start_cluster\n config = json.dumps({\"object_manager_repeated_push_delay_ms\": 1000})\n for i in range(3):\n cluster.add_node(\n num_cpus=1,\n resources={\"Custom{}\".format(i): 1},\n _internal_config=config)\n ray.init(address=cluster.address)\n\n class RawActor(object):\n def get(self):\n return ray.worker.global_worker.node.unique_id\n\n ActorOnNode0 = ray.remote(resources={\"Custom0\": 1})(RawActor)\n ActorOnNode1 = ray.remote(resources={\"Custom1\": 1})(RawActor)\n ActorOnNode2 = ray.remote(resources={\"Custom2\": 1})(RawActor)\n\n def create(actors):\n a = actors[0].get.remote()\n b = actors[1].get.remote()\n c = actors[2].get.remote()\n (l1, l2) = ray.wait([a, b, c], num_returns=3)\n assert len(l1) == 3\n assert len(l2) == 0\n return (a, b, c)\n\n def run_one_test(actors, local_only, delete_creating_tasks):\n (a, b, c) = create(actors)\n # The three objects should be generated on different object stores.\n assert ray.get(a) != ray.get(b)\n assert ray.get(a) != ray.get(c)\n assert ray.get(c) != ray.get(b)\n ray.internal.free(\n [a, b, c],\n local_only=local_only,\n delete_creating_tasks=delete_creating_tasks)\n # Wait for the objects to be deleted.\n time.sleep(0.1)\n return (a, b, c)\n\n actors = [\n ActorOnNode0.remote(),\n ActorOnNode1.remote(),\n ActorOnNode2.remote()\n ]\n # Case 1: run this local_only=False. All 3 objects will be deleted.\n (a, b, c) = run_one_test(actors, False, False)\n (l1, l2) = ray.wait([a, b, c], timeout=0.01, num_returns=1)\n # All the objects are deleted.\n assert len(l1) == 0\n assert len(l2) == 3\n # Case 2: run this local_only=True. Only 1 object will be deleted.\n (a, b, c) = run_one_test(actors, True, False)\n (l1, l2) = ray.wait([a, b, c], timeout=0.01, num_returns=3)\n # One object is deleted and 2 objects are not.\n assert len(l1) == 2\n assert len(l2) == 1\n # The deleted object will have the same store with the driver.\n local_return = ray.worker.global_worker.node.unique_id\n for object_id in l1:\n assert ray.get(object_id) != local_return\n\n # Case3: These cases test the deleting creating tasks for the object.\n (a, b, c) = run_one_test(actors, False, False)\n task_table = ray.tasks()\n for obj in [a, b, c]:\n assert ray._raylet.compute_task_id(obj).hex() in task_table\n\n (a, b, c) = run_one_test(actors, False, True)\n task_table = ray.tasks()\n for obj in [a, b, c]:\n assert ray._raylet.compute_task_id(obj).hex() not in task_table\n\n\ndef test_local_mode(shutdown_only):\n @ray.remote\n def local_mode_f():\n return np.array([0, 0])\n\n @ray.remote\n def local_mode_g(x):\n x[0] = 1\n return x\n\n ray.init(local_mode=True)\n\n @ray.remote\n def f():\n return np.ones([3, 4, 5])\n\n xref = f.remote()\n # Remote functions should return ObjectIDs.\n assert isinstance(xref, ray.ObjectID)\n assert np.alltrue(ray.get(xref) == np.ones([3, 4, 5]))\n y = np.random.normal(size=[11, 12])\n # Check that ray.get(ray.put) is the identity.\n assert np.alltrue(y == ray.get(ray.put(y)))\n\n # Make sure objects are immutable, this example is why we need to copy\n # arguments before passing them into remote functions in python mode\n aref = local_mode_f.remote()\n assert np.alltrue(ray.get(aref) == np.array([0, 0]))\n bref = local_mode_g.remote(ray.get(aref))\n # Make sure local_mode_g does not mutate aref.\n assert np.alltrue(ray.get(aref) == np.array([0, 0]))\n assert np.alltrue(ray.get(bref) == np.array([1, 0]))\n\n # wait should return the first num_returns values passed in as the\n # first list and the remaining values as the second list\n num_returns = 5\n object_ids = [ray.put(i) for i in range(20)]\n ready, remaining = ray.wait(\n object_ids, num_returns=num_returns, timeout=None)\n assert ready == object_ids[:num_returns]\n assert remaining == object_ids[num_returns:]\n\n # Check that ray.put() and ray.internal.free() work in local mode.\n\n v1 = np.ones(10)\n v2 = np.zeros(10)\n\n k1 = ray.put(v1)\n assert np.alltrue(v1 == ray.get(k1))\n k2 = ray.put(v2)\n assert np.alltrue(v2 == ray.get(k2))\n\n ray.internal.free([k1, k2])\n with pytest.raises(Exception):\n ray.get(k1)\n with pytest.raises(Exception):\n ray.get(k2)\n\n # Should fail silently.\n ray.internal.free([k1, k2])\n\n # Test actors in LOCAL_MODE.\n\n @ray.remote\n class LocalModeTestClass(object):\n def __init__(self, array):\n self.array = array\n\n def set_array(self, array):\n self.array = array\n\n def get_array(self):\n return self.array\n\n def modify_and_set_array(self, array):\n array[0] = -1\n self.array = array\n\n @ray.method(num_return_vals=3)\n def returns_multiple(self):\n return 1, 2, 3\n\n test_actor = LocalModeTestClass.remote(np.arange(10))\n obj = test_actor.get_array.remote()\n assert isinstance(obj, ray.ObjectID)\n assert np.alltrue(ray.get(obj) == np.arange(10))\n\n test_array = np.arange(10)\n # Remote actor functions should not mutate arguments\n test_actor.modify_and_set_array.remote(test_array)\n assert np.alltrue(test_array == np.arange(10))\n # Remote actor functions should keep state\n test_array[0] = -1\n assert np.alltrue(test_array == ray.get(test_actor.get_array.remote()))\n\n # Check that actor handles work in local mode.\n\n @ray.remote\n def use_actor_handle(handle):\n array = np.ones(10)\n handle.set_array.remote(array)\n assert np.alltrue(array == ray.get(handle.get_array.remote()))\n\n ray.get(use_actor_handle.remote(test_actor))\n\n # Check that exceptions are deferred until ray.get().\n\n exception_str = \"test_basic remote task exception\"\n\n @ray.remote\n def throws():\n raise Exception(exception_str)\n\n obj = throws.remote()\n with pytest.raises(Exception, match=exception_str):\n ray.get(obj)\n\n # Check that multiple return values are handled properly.\n\n @ray.remote(num_return_vals=3)\n def returns_multiple():\n return 1, 2, 3\n\n obj1, obj2, obj3 = returns_multiple.remote()\n assert ray.get(obj1) == 1\n assert ray.get(obj2) == 2\n assert ray.get(obj3) == 3\n assert ray.get([obj1, obj2, obj3]) == [1, 2, 3]\n\n obj1, obj2, obj3 = test_actor.returns_multiple.remote()\n assert ray.get(obj1) == 1\n assert ray.get(obj2) == 2\n assert ray.get(obj3) == 3\n assert ray.get([obj1, obj2, obj3]) == [1, 2, 3]\n\n @ray.remote(num_return_vals=2)\n def returns_multiple_throws():\n raise Exception(exception_str)\n\n obj1, obj2 = returns_multiple_throws.remote()\n with pytest.raises(Exception, match=exception_str):\n ray.get(obj)\n ray.get(obj1)\n with pytest.raises(Exception, match=exception_str):\n ray.get(obj2)\n\n\ndef test_resource_constraints(shutdown_only):\n num_workers = 20\n ray.init(num_cpus=10, num_gpus=2)\n\n @ray.remote(num_cpus=0)\n def get_worker_id():\n time.sleep(0.1)\n return os.getpid()\n\n # Attempt to wait for all of the workers to start up.\n while True:\n if len(\n set(\n ray.get([\n get_worker_id.remote() for _ in range(num_workers)\n ]))) == num_workers:\n break\n\n time_buffer = 2\n\n # At most 10 copies of this can run at once.\n @ray.remote(num_cpus=1)\n def f(n):\n time.sleep(n)\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(10)])\n duration = time.time() - start_time\n assert duration < 0.5 + time_buffer\n assert duration > 0.5\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(11)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n @ray.remote(num_cpus=3)\n def f(n):\n time.sleep(n)\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(3)])\n duration = time.time() - start_time\n assert duration < 0.5 + time_buffer\n assert duration > 0.5\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(4)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n @ray.remote(num_gpus=1)\n def f(n):\n time.sleep(n)\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(2)])\n duration = time.time() - start_time\n assert duration < 0.5 + time_buffer\n assert duration > 0.5\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(3)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n start_time = time.time()\n ray.get([f.remote(0.5) for _ in range(4)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n\ndef test_multi_resource_constraints(shutdown_only):\n num_workers = 20\n ray.init(num_cpus=10, num_gpus=10)\n\n @ray.remote(num_cpus=0)\n def get_worker_id():\n time.sleep(0.1)\n return os.getpid()\n\n # Attempt to wait for all of the workers to start up.\n while True:\n if len(\n set(\n ray.get([\n get_worker_id.remote() for _ in range(num_workers)\n ]))) == num_workers:\n break\n\n @ray.remote(num_cpus=1, num_gpus=9)\n def f(n):\n time.sleep(n)\n\n @ray.remote(num_cpus=9, num_gpus=1)\n def g(n):\n time.sleep(n)\n\n time_buffer = 2\n\n start_time = time.time()\n ray.get([f.remote(0.5), g.remote(0.5)])\n duration = time.time() - start_time\n assert duration < 0.5 + time_buffer\n assert duration > 0.5\n\n start_time = time.time()\n ray.get([f.remote(0.5), f.remote(0.5)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n start_time = time.time()\n ray.get([g.remote(0.5), g.remote(0.5)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n start_time = time.time()\n ray.get([f.remote(0.5), f.remote(0.5), g.remote(0.5), g.remote(0.5)])\n duration = time.time() - start_time\n assert duration < 1 + time_buffer\n assert duration > 1\n\n\ndef test_gpu_ids(shutdown_only):\n num_gpus = 10\n ray.init(num_cpus=10, num_gpus=num_gpus)\n\n def get_gpu_ids(num_gpus_per_worker):\n time.sleep(0.1)\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == num_gpus_per_worker\n assert (os.environ[\"CUDA_VISIBLE_DEVICES\"] == \",\".join(\n [str(i) for i in gpu_ids]))\n for gpu_id in gpu_ids:\n assert gpu_id in range(num_gpus)\n return gpu_ids\n\n f0 = ray.remote(num_gpus=0)(lambda: get_gpu_ids(0))\n f1 = ray.remote(num_gpus=1)(lambda: get_gpu_ids(1))\n f2 = ray.remote(num_gpus=2)(lambda: get_gpu_ids(2))\n f4 = ray.remote(num_gpus=4)(lambda: get_gpu_ids(4))\n f5 = ray.remote(num_gpus=5)(lambda: get_gpu_ids(5))\n\n # Wait for all workers to start up.\n @ray.remote\n def f():\n time.sleep(0.1)\n return os.getpid()\n\n start_time = time.time()\n while True:\n if len(set(ray.get([f.remote() for _ in range(10)]))) == 10:\n break\n if time.time() > start_time + 10:\n raise Exception(\"Timed out while waiting for workers to start \"\n \"up.\")\n\n list_of_ids = ray.get([f0.remote() for _ in range(10)])\n assert list_of_ids == 10 * [[]]\n\n list_of_ids = ray.get([f1.remote() for _ in range(10)])\n set_of_ids = {tuple(gpu_ids) for gpu_ids in list_of_ids}\n assert set_of_ids == {(i, ) for i in range(10)}\n\n list_of_ids = ray.get([f2.remote(), f4.remote(), f4.remote()])\n all_ids = [gpu_id for gpu_ids in list_of_ids for gpu_id in gpu_ids]\n assert set(all_ids) == set(range(10))\n\n # There are only 10 GPUs, and each task uses 5 GPUs, so there should only\n # be 2 tasks scheduled at a given time.\n t1 = time.time()\n ray.get([f5.remote() for _ in range(20)])\n assert time.time() - t1 >= 10 * 0.1\n\n # Test that actors have CUDA_VISIBLE_DEVICES set properly.\n\n @ray.remote\n class Actor0(object):\n def __init__(self):\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 0\n assert (os.environ[\"CUDA_VISIBLE_DEVICES\"] == \",\".join(\n [str(i) for i in gpu_ids]))\n # Set self.x to make sure that we got here.\n self.x = 1\n\n def test(self):\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 0\n assert (os.environ[\"CUDA_VISIBLE_DEVICES\"] == \",\".join(\n [str(i) for i in gpu_ids]))\n return self.x\n\n @ray.remote(num_gpus=1)\n class Actor1(object):\n def __init__(self):\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 1\n assert (os.environ[\"CUDA_VISIBLE_DEVICES\"] == \",\".join(\n [str(i) for i in gpu_ids]))\n # Set self.x to make sure that we got here.\n self.x = 1\n\n def test(self):\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 1\n assert (os.environ[\"CUDA_VISIBLE_DEVICES\"] == \",\".join(\n [str(i) for i in gpu_ids]))\n return self.x\n\n a0 = Actor0.remote()\n ray.get(a0.test.remote())\n\n a1 = Actor1.remote()\n ray.get(a1.test.remote())\n\n\ndef test_zero_cpus(shutdown_only):\n ray.init(num_cpus=0)\n\n # We should be able to execute a task that requires 0 CPU resources.\n @ray.remote(num_cpus=0)\n def f():\n return 1\n\n ray.get(f.remote())\n\n # We should be able to create an actor that requires 0 CPU resources.\n @ray.remote(num_cpus=0)\n class Actor(object):\n def method(self):\n pass\n\n a = Actor.remote()\n x = a.method.remote()\n ray.get(x)\n\n\ndef test_zero_cpus_actor(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=0)\n cluster.add_node(num_cpus=2)\n ray.init(address=cluster.address)\n\n node_id = ray.worker.global_worker.node.unique_id\n\n @ray.remote\n class Foo(object):\n def method(self):\n return ray.worker.global_worker.node.unique_id\n\n # Make sure tasks and actors run on the remote raylet.\n a = Foo.remote()\n assert ray.get(a.method.remote()) != node_id\n\n\ndef test_fractional_resources(shutdown_only):\n ray.init(num_cpus=6, num_gpus=3, resources={\"Custom\": 1})\n\n @ray.remote(num_gpus=0.5)\n class Foo1(object):\n def method(self):\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 1\n return gpu_ids[0]\n\n foos = [Foo1.remote() for _ in range(6)]\n gpu_ids = ray.get([f.method.remote() for f in foos])\n for i in range(3):\n assert gpu_ids.count(i) == 2\n del foos\n\n @ray.remote\n class Foo2(object):\n def method(self):\n pass\n\n # Create an actor that requires 0.7 of the custom resource.\n f1 = Foo2._remote([], {}, resources={\"Custom\": 0.7})\n ray.get(f1.method.remote())\n # Make sure that we cannot create an actor that requires 0.7 of the\n # custom resource. TODO(rkn): Re-enable this once ray.wait is\n # implemented.\n f2 = Foo2._remote([], {}, resources={\"Custom\": 0.7})\n ready, _ = ray.wait([f2.method.remote()], timeout=0.5)\n assert len(ready) == 0\n # Make sure we can start an actor that requries only 0.3 of the custom\n # resource.\n f3 = Foo2._remote([], {}, resources={\"Custom\": 0.3})\n ray.get(f3.method.remote())\n\n del f1, f3\n\n # Make sure that we get exceptions if we submit tasks that require a\n # fractional number of resources greater than 1.\n\n @ray.remote(num_cpus=1.5)\n def test():\n pass\n\n with pytest.raises(ValueError):\n test.remote()\n\n with pytest.raises(ValueError):\n Foo2._remote([], {}, resources={\"Custom\": 1.5})\n\n\ndef test_multiple_raylets(ray_start_cluster):\n # This test will define a bunch of tasks that can only be assigned to\n # specific raylets, and we will check that they are assigned\n # to the correct raylets.\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=11, num_gpus=0)\n cluster.add_node(num_cpus=5, num_gpus=5)\n cluster.add_node(num_cpus=10, num_gpus=1)\n ray.init(address=cluster.address)\n cluster.wait_for_nodes()\n\n # Define a bunch of remote functions that all return the socket name of\n # the plasma store. Since there is a one-to-one correspondence between\n # plasma stores and raylets (at least right now), this can be\n # used to identify which raylet the task was assigned to.\n\n # This must be run on the zeroth raylet.\n @ray.remote(num_cpus=11)\n def run_on_0():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n # This must be run on the first raylet.\n @ray.remote(num_gpus=2)\n def run_on_1():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n # This must be run on the second raylet.\n @ray.remote(num_cpus=6, num_gpus=1)\n def run_on_2():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n # This can be run anywhere.\n @ray.remote(num_cpus=0, num_gpus=0)\n def run_on_0_1_2():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n # This must be run on the first or second raylet.\n @ray.remote(num_gpus=1)\n def run_on_1_2():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n # This must be run on the zeroth or second raylet.\n @ray.remote(num_cpus=8)\n def run_on_0_2():\n return ray.worker.global_worker.node.plasma_store_socket_name\n\n def run_lots_of_tasks():\n names = []\n results = []\n for i in range(100):\n index = np.random.randint(6)\n if index == 0:\n names.append(\"run_on_0\")\n results.append(run_on_0.remote())\n elif index == 1:\n names.append(\"run_on_1\")\n results.append(run_on_1.remote())\n elif index == 2:\n names.append(\"run_on_2\")\n results.append(run_on_2.remote())\n elif index == 3:\n names.append(\"run_on_0_1_2\")\n results.append(run_on_0_1_2.remote())\n elif index == 4:\n names.append(\"run_on_1_2\")\n results.append(run_on_1_2.remote())\n elif index == 5:\n names.append(\"run_on_0_2\")\n results.append(run_on_0_2.remote())\n return names, results\n\n client_table = ray.nodes()\n store_names = []\n store_names += [\n client[\"ObjectStoreSocketName\"] for client in client_table\n if client[\"Resources\"].get(\"GPU\", 0) == 0\n ]\n store_names += [\n client[\"ObjectStoreSocketName\"] for client in client_table\n if client[\"Resources\"].get(\"GPU\", 0) == 5\n ]\n store_names += [\n client[\"ObjectStoreSocketName\"] for client in client_table\n if client[\"Resources\"].get(\"GPU\", 0) == 1\n ]\n assert len(store_names) == 3\n\n def validate_names_and_results(names, results):\n for name, result in zip(names, ray.get(results)):\n if name == \"run_on_0\":\n assert result in [store_names[0]]\n elif name == \"run_on_1\":\n assert result in [store_names[1]]\n elif name == \"run_on_2\":\n assert result in [store_names[2]]\n elif name == \"run_on_0_1_2\":\n assert (result in [\n store_names[0], store_names[1], store_names[2]\n ])\n elif name == \"run_on_1_2\":\n assert result in [store_names[1], store_names[2]]\n elif name == \"run_on_0_2\":\n assert result in [store_names[0], store_names[2]]\n else:\n raise Exception(\"This should be unreachable.\")\n assert set(ray.get(results)) == set(store_names)\n\n names, results = run_lots_of_tasks()\n validate_names_and_results(names, results)\n\n # Make sure the same thing works when this is nested inside of a task.\n\n @ray.remote\n def run_nested1():\n names, results = run_lots_of_tasks()\n return names, results\n\n @ray.remote\n def run_nested2():\n names, results = ray.get(run_nested1.remote())\n return names, results\n\n names, results = ray.get(run_nested2.remote())\n validate_names_and_results(names, results)\n\n\ndef test_custom_resources(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=3, resources={\"CustomResource\": 0})\n cluster.add_node(num_cpus=3, resources={\"CustomResource\": 1})\n ray.init(address=cluster.address)\n\n @ray.remote\n def f():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource\": 1})\n def g():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource\": 1})\n def h():\n ray.get([f.remote() for _ in range(5)])\n return ray.worker.global_worker.node.unique_id\n\n # The f tasks should be scheduled on both raylets.\n assert len(set(ray.get([f.remote() for _ in range(50)]))) == 2\n\n node_id = ray.worker.global_worker.node.unique_id\n\n # The g tasks should be scheduled only on the second raylet.\n raylet_ids = set(ray.get([g.remote() for _ in range(50)]))\n assert len(raylet_ids) == 1\n assert list(raylet_ids)[0] != node_id\n\n # Make sure that resource bookkeeping works when a task that uses a\n # custom resources gets blocked.\n ray.get([h.remote() for _ in range(5)])\n\n\ndef test_two_custom_resources(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(\n num_cpus=3, resources={\n \"CustomResource1\": 1,\n \"CustomResource2\": 2\n })\n cluster.add_node(\n num_cpus=3, resources={\n \"CustomResource1\": 3,\n \"CustomResource2\": 4\n })\n ray.init(address=cluster.address)\n\n @ray.remote(resources={\"CustomResource1\": 1})\n def f():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource2\": 1})\n def g():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource1\": 1, \"CustomResource2\": 3})\n def h():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource1\": 4})\n def j():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n @ray.remote(resources={\"CustomResource3\": 1})\n def k():\n time.sleep(0.001)\n return ray.worker.global_worker.node.unique_id\n\n # The f and g tasks should be scheduled on both raylets.\n assert len(set(ray.get([f.remote() for _ in range(50)]))) == 2\n assert len(set(ray.get([g.remote() for _ in range(50)]))) == 2\n\n node_id = ray.worker.global_worker.node.unique_id\n\n # The h tasks should be scheduled only on the second raylet.\n raylet_ids = set(ray.get([h.remote() for _ in range(50)]))\n assert len(raylet_ids) == 1\n assert list(raylet_ids)[0] != node_id\n\n # Make sure that tasks with unsatisfied custom resource requirements do\n # not get scheduled.\n ready_ids, remaining_ids = ray.wait([j.remote(), k.remote()], timeout=0.5)\n assert ready_ids == []\n\n\ndef test_many_custom_resources(shutdown_only):\n num_custom_resources = 10000\n total_resources = {\n str(i): np.random.randint(1, 7)\n for i in range(num_custom_resources)\n }\n ray.init(num_cpus=5, resources=total_resources)\n\n def f():\n return 1\n\n remote_functions = []\n for _ in range(20):\n num_resources = np.random.randint(0, num_custom_resources + 1)\n permuted_resources = np.random.permutation(\n num_custom_resources)[:num_resources]\n random_resources = {\n str(i): total_resources[str(i)]\n for i in permuted_resources\n }\n remote_function = ray.remote(resources=random_resources)(f)\n remote_functions.append(remote_function)\n\n remote_functions.append(ray.remote(f))\n remote_functions.append(ray.remote(resources=total_resources)(f))\n\n results = []\n for remote_function in remote_functions:\n results.append(remote_function.remote())\n results.append(remote_function.remote())\n results.append(remote_function.remote())\n\n ray.get(results)\n\n\n# TODO: 5 retry attempts may be too little for Travis and we may need to\n# increase it if this test begins to be flaky on Travis.\ndef test_zero_capacity_deletion_semantics(shutdown_only):\n ray.init(num_cpus=2, num_gpus=1, resources={\"test_resource\": 1})\n\n def test():\n resources = ray.available_resources()\n MAX_RETRY_ATTEMPTS = 5\n retry_count = 0\n\n del resources[\"memory\"]\n del resources[\"object_store_memory\"]\n\n while resources and retry_count < MAX_RETRY_ATTEMPTS:\n time.sleep(0.1)\n resources = ray.available_resources()\n retry_count += 1\n\n if retry_count >= MAX_RETRY_ATTEMPTS:\n raise RuntimeError(\n \"Resources were available even after five retries.\")\n\n return resources\n\n function = ray.remote(\n num_cpus=2, num_gpus=1, resources={\"test_resource\": 1})(test)\n cluster_resources = ray.get(function.remote())\n\n # All cluster resources should be utilized and\n # cluster_resources must be empty\n assert cluster_resources == {}\n\n\[email protected]\ndef save_gpu_ids_shutdown_only():\n # Record the curent value of this environment variable so that we can\n # reset it after the test.\n original_gpu_ids = os.environ.get(\"CUDA_VISIBLE_DEVICES\", None)\n\n yield None\n\n # The code after the yield will run as teardown code.\n ray.shutdown()\n # Reset the environment variable.\n if original_gpu_ids is not None:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = original_gpu_ids\n else:\n del os.environ[\"CUDA_VISIBLE_DEVICES\"]\n\n\ndef test_specific_gpus(save_gpu_ids_shutdown_only):\n allowed_gpu_ids = [4, 5, 6]\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(\n [str(i) for i in allowed_gpu_ids])\n ray.init(num_gpus=3)\n\n @ray.remote(num_gpus=1)\n def f():\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 1\n assert gpu_ids[0] in allowed_gpu_ids\n\n @ray.remote(num_gpus=2)\n def g():\n gpu_ids = ray.get_gpu_ids()\n assert len(gpu_ids) == 2\n assert gpu_ids[0] in allowed_gpu_ids\n assert gpu_ids[1] in allowed_gpu_ids\n\n ray.get([f.remote() for _ in range(100)])\n ray.get([g.remote() for _ in range(100)])\n\n\ndef test_blocking_tasks(ray_start_regular):\n @ray.remote\n def f(i, j):\n return (i, j)\n\n @ray.remote\n def g(i):\n # Each instance of g submits and blocks on the result of another\n # remote task.\n object_ids = [f.remote(i, j) for j in range(2)]\n return ray.get(object_ids)\n\n @ray.remote\n def h(i):\n # Each instance of g submits and blocks on the result of another\n # remote task using ray.wait.\n object_ids = [f.remote(i, j) for j in range(2)]\n return ray.wait(object_ids, num_returns=len(object_ids))\n\n ray.get([h.remote(i) for i in range(4)])\n\n @ray.remote\n def _sleep(i):\n time.sleep(0.01)\n return (i)\n\n @ray.remote\n def sleep():\n # Each instance of sleep submits and blocks on the result of\n # another remote task, which takes some time to execute.\n ray.get([_sleep.remote(i) for i in range(10)])\n\n ray.get(sleep.remote())\n\n\ndef test_max_call_tasks(ray_start_regular):\n @ray.remote(max_calls=1)\n def f():\n return os.getpid()\n\n pid = ray.get(f.remote())\n ray.tests.utils.wait_for_pid_to_exit(pid)\n\n @ray.remote(max_calls=2)\n def f():\n return os.getpid()\n\n pid1 = ray.get(f.remote())\n pid2 = ray.get(f.remote())\n assert pid1 == pid2\n ray.tests.utils.wait_for_pid_to_exit(pid1)\n\n\ndef attempt_to_load_balance(remote_function,\n args,\n total_tasks,\n num_nodes,\n minimum_count,\n num_attempts=100):\n attempts = 0\n while attempts < num_attempts:\n locations = ray.get(\n [remote_function.remote(*args) for _ in range(total_tasks)])\n names = set(locations)\n counts = [locations.count(name) for name in names]\n logger.info(\"Counts are {}.\".format(counts))\n if (len(names) == num_nodes\n and all(count >= minimum_count for count in counts)):\n break\n attempts += 1\n assert attempts < num_attempts\n\n\ndef test_load_balancing(ray_start_cluster):\n # This test ensures that tasks are being assigned to all raylets\n # in a roughly equal manner.\n cluster = ray_start_cluster\n num_nodes = 3\n num_cpus = 7\n for _ in range(num_nodes):\n cluster.add_node(num_cpus=num_cpus)\n ray.init(address=cluster.address)\n\n @ray.remote\n def f():\n time.sleep(0.01)\n return ray.worker.global_worker.node.unique_id\n\n attempt_to_load_balance(f, [], 100, num_nodes, 10)\n attempt_to_load_balance(f, [], 1000, num_nodes, 100)\n\n\ndef test_load_balancing_with_dependencies(ray_start_cluster):\n # This test ensures that tasks are being assigned to all raylets in a\n # roughly equal manner even when the tasks have dependencies.\n cluster = ray_start_cluster\n num_nodes = 3\n for _ in range(num_nodes):\n cluster.add_node(num_cpus=1)\n ray.init(address=cluster.address)\n\n @ray.remote\n def f(x):\n time.sleep(0.010)\n return ray.worker.global_worker.node.unique_id\n\n # This object will be local to one of the raylets. Make sure\n # this doesn't prevent tasks from being scheduled on other raylets.\n x = ray.put(np.zeros(1000000))\n\n attempt_to_load_balance(f, [x], 100, num_nodes, 25)\n\n\ndef wait_for_num_tasks(num_tasks, timeout=10):\n start_time = time.time()\n while time.time() - start_time < timeout:\n if len(ray.tasks()) >= num_tasks:\n return\n time.sleep(0.1)\n raise Exception(\"Timed out while waiting for global state.\")\n\n\ndef wait_for_num_objects(num_objects, timeout=10):\n start_time = time.time()\n while time.time() - start_time < timeout:\n if len(ray.objects()) >= num_objects:\n return\n time.sleep(0.1)\n raise Exception(\"Timed out while waiting for global state.\")\n\n\[email protected](\n os.environ.get(\"RAY_USE_NEW_GCS\") == \"on\",\n reason=\"New GCS API doesn't have a Python API yet.\")\ndef test_global_state_api(shutdown_only):\n\n error_message = (\"The ray global state API cannot be used \"\n \"before ray.init has been called.\")\n\n with pytest.raises(Exception, match=error_message):\n ray.objects()\n\n with pytest.raises(Exception, match=error_message):\n ray.tasks()\n\n with pytest.raises(Exception, match=error_message):\n ray.nodes()\n\n with pytest.raises(Exception, match=error_message):\n ray.jobs()\n\n ray.init(num_cpus=5, num_gpus=3, resources={\"CustomResource\": 1})\n\n assert ray.cluster_resources()[\"CPU\"] == 5\n assert ray.cluster_resources()[\"GPU\"] == 3\n assert ray.cluster_resources()[\"CustomResource\"] == 1\n\n assert ray.objects() == {}\n\n job_id = ray.utils.compute_job_id_from_driver(\n ray.WorkerID(ray.worker.global_worker.worker_id))\n driver_task_id = ray.worker.global_worker.current_task_id.hex()\n\n # One task is put in the task table which corresponds to this driver.\n wait_for_num_tasks(1)\n task_table = ray.tasks()\n assert len(task_table) == 1\n assert driver_task_id == list(task_table.keys())[0]\n task_spec = task_table[driver_task_id][\"TaskSpec\"]\n nil_unique_id_hex = ray.UniqueID.nil().hex()\n nil_actor_id_hex = ray.ActorID.nil().hex()\n\n assert task_spec[\"TaskID\"] == driver_task_id\n assert task_spec[\"ActorID\"] == nil_actor_id_hex\n assert task_spec[\"Args\"] == []\n assert task_spec[\"JobID\"] == job_id.hex()\n assert task_spec[\"FunctionID\"] == nil_unique_id_hex\n assert task_spec[\"ReturnObjectIDs\"] == []\n\n client_table = ray.nodes()\n node_ip_address = ray.worker.global_worker.node_ip_address\n\n assert len(client_table) == 1\n assert client_table[0][\"NodeManagerAddress\"] == node_ip_address\n\n @ray.remote\n def f(*xs):\n return 1\n\n x_id = ray.put(1)\n result_id = f.remote(1, \"hi\", x_id)\n\n # Wait for one additional task to complete.\n wait_for_num_tasks(1 + 1)\n task_table = ray.tasks()\n assert len(task_table) == 1 + 1\n task_id_set = set(task_table.keys())\n task_id_set.remove(driver_task_id)\n task_id = list(task_id_set)[0]\n\n task_spec = task_table[task_id][\"TaskSpec\"]\n assert task_spec[\"ActorID\"] == nil_actor_id_hex\n assert task_spec[\"Args\"] == [1, \"hi\", x_id]\n assert task_spec[\"JobID\"] == job_id.hex()\n assert task_spec[\"ReturnObjectIDs\"] == [result_id]\n\n assert task_table[task_id] == ray.tasks(task_id)\n\n # Wait for two objects, one for the x_id and one for result_id.\n wait_for_num_objects(2)\n\n def wait_for_object_table():\n timeout = 10\n start_time = time.time()\n while time.time() - start_time < timeout:\n object_table = ray.objects()\n tables_ready = (object_table[x_id][\"ManagerIDs\"] is not None and\n object_table[result_id][\"ManagerIDs\"] is not None)\n if tables_ready:\n return\n time.sleep(0.1)\n raise Exception(\"Timed out while waiting for object table to \"\n \"update.\")\n\n object_table = ray.objects()\n assert len(object_table) == 2\n\n assert object_table[x_id] == ray.objects(x_id)\n object_table_entry = ray.objects(result_id)\n assert object_table[result_id] == object_table_entry\n\n job_table = ray.jobs()\n\n assert len(job_table) == 1\n assert job_table[0][\"JobID\"] == job_id.hex()\n assert job_table[0][\"NodeManagerAddress\"] == node_ip_address\n\n\n# TODO(rkn): Pytest actually has tools for capturing stdout and stderr, so we\n# should use those, but they seem to conflict with Ray's use of faulthandler.\nclass CaptureOutputAndError(object):\n \"\"\"Capture stdout and stderr of some span.\n\n This can be used as follows.\n\n captured = {}\n with CaptureOutputAndError(captured):\n # Do stuff.\n # Access captured[\"out\"] and captured[\"err\"].\n \"\"\"\n\n def __init__(self, captured_output_and_error):\n if sys.version_info >= (3, 0):\n import io\n self.output_buffer = io.StringIO()\n self.error_buffer = io.StringIO()\n else:\n import cStringIO\n self.output_buffer = cStringIO.StringIO()\n self.error_buffer = cStringIO.StringIO()\n self.captured_output_and_error = captured_output_and_error\n\n def __enter__(self):\n sys.stdout.flush()\n sys.stderr.flush()\n self.old_stdout = sys.stdout\n self.old_stderr = sys.stderr\n sys.stdout = self.output_buffer\n sys.stderr = self.error_buffer\n\n def __exit__(self, exc_type, exc_value, traceback):\n sys.stdout.flush()\n sys.stderr.flush()\n sys.stdout = self.old_stdout\n sys.stderr = self.old_stderr\n self.captured_output_and_error[\"out\"] = self.output_buffer.getvalue()\n self.captured_output_and_error[\"err\"] = self.error_buffer.getvalue()\n\n\ndef test_logging_to_driver(shutdown_only):\n ray.init(num_cpus=1, log_to_driver=True)\n\n @ray.remote\n def f():\n # It's important to make sure that these print statements occur even\n # without calling sys.stdout.flush() and sys.stderr.flush().\n for i in range(100):\n print(i)\n print(100 + i, file=sys.stderr)\n\n captured = {}\n with CaptureOutputAndError(captured):\n ray.get(f.remote())\n time.sleep(1)\n\n output_lines = captured[\"out\"]\n for i in range(200):\n assert str(i) in output_lines\n\n # TODO(rkn): Check that no additional logs appear beyond what we expect\n # and that there are no duplicate logs. Once we address the issue\n # described in https://github.com/ray-project/ray/pull/5462, we should\n # also check that nothing is logged to stderr.\n\n\ndef test_not_logging_to_driver(shutdown_only):\n ray.init(num_cpus=1, log_to_driver=False)\n\n @ray.remote\n def f():\n for i in range(100):\n print(i)\n print(100 + i, file=sys.stderr)\n sys.stdout.flush()\n sys.stderr.flush()\n\n captured = {}\n with CaptureOutputAndError(captured):\n ray.get(f.remote())\n time.sleep(1)\n\n output_lines = captured[\"out\"]\n assert len(output_lines) == 0\n\n # TODO(rkn): Check that no additional logs appear beyond what we expect\n # and that there are no duplicate logs. Once we address the issue\n # described in https://github.com/ray-project/ray/pull/5462, we should\n # also check that nothing is logged to stderr.\n\n\[email protected](\n os.environ.get(\"RAY_USE_NEW_GCS\") == \"on\",\n reason=\"New GCS API doesn't have a Python API yet.\")\ndef test_workers(shutdown_only):\n num_workers = 3\n ray.init(num_cpus=num_workers)\n\n @ray.remote\n def f():\n return id(ray.worker.global_worker), os.getpid()\n\n # Wait until all of the workers have started.\n worker_ids = set()\n while len(worker_ids) != num_workers:\n worker_ids = set(ray.get([f.remote() for _ in range(10)]))\n\n\ndef test_specific_job_id():\n dummy_driver_id = ray.JobID.from_int(1)\n ray.init(num_cpus=1, job_id=dummy_driver_id)\n\n # in driver\n assert dummy_driver_id == ray._get_runtime_context().current_driver_id\n\n # in worker\n @ray.remote\n def f():\n return ray._get_runtime_context().current_driver_id\n\n assert dummy_driver_id == ray.get(f.remote())\n\n ray.shutdown()\n\n\ndef test_object_id_properties():\n id_bytes = b\"00112233445566778899\"\n object_id = ray.ObjectID(id_bytes)\n assert object_id.binary() == id_bytes\n object_id = ray.ObjectID.nil()\n assert object_id.is_nil()\n with pytest.raises(ValueError, match=r\".*needs to have length 20.*\"):\n ray.ObjectID(id_bytes + b\"1234\")\n with pytest.raises(ValueError, match=r\".*needs to have length 20.*\"):\n ray.ObjectID(b\"0123456789\")\n object_id = ray.ObjectID.from_random()\n assert not object_id.is_nil()\n assert object_id.binary() != id_bytes\n id_dumps = pickle.dumps(object_id)\n id_from_dumps = pickle.loads(id_dumps)\n assert id_from_dumps == object_id\n file_prefix = \"test_object_id_properties\"\n\n # Make sure the ids are fork safe.\n def write(index):\n str = ray.ObjectID.from_random().hex()\n with open(\"{}{}\".format(file_prefix, index), \"w\") as fo:\n fo.write(str)\n\n def read(index):\n with open(\"{}{}\".format(file_prefix, index), \"r\") as fi:\n for line in fi:\n return line\n\n processes = [Process(target=write, args=(_, )) for _ in range(4)]\n for process in processes:\n process.start()\n for process in processes:\n process.join()\n hexes = {read(i) for i in range(4)}\n [os.remove(\"{}{}\".format(file_prefix, i)) for i in range(4)]\n assert len(hexes) == 4\n\n\[email protected]\ndef shutdown_only_with_initialization_check():\n yield None\n # The code after the yield will run as teardown code.\n ray.shutdown()\n assert not ray.is_initialized()\n\n\ndef test_initialized(shutdown_only_with_initialization_check):\n assert not ray.is_initialized()\n ray.init(num_cpus=0)\n assert ray.is_initialized()\n\n\ndef test_initialized_local_mode(shutdown_only_with_initialization_check):\n assert not ray.is_initialized()\n ray.init(num_cpus=0, local_mode=True)\n assert ray.is_initialized()\n\n\ndef test_wait_reconstruction(shutdown_only):\n ray.init(num_cpus=1, object_store_memory=int(10**8))\n\n @ray.remote\n def f():\n return np.zeros(6 * 10**7, dtype=np.uint8)\n\n x_id = f.remote()\n ray.wait([x_id])\n ray.wait([f.remote()])\n assert not ray.worker.global_worker.core_worker.object_exists(x_id)\n ready_ids, _ = ray.wait([x_id])\n assert len(ready_ids) == 1\n\n\ndef test_ray_setproctitle(ray_start_2_cpus):\n @ray.remote\n class UniqueName(object):\n def __init__(self):\n assert setproctitle.getproctitle() == \"ray_UniqueName:__init__()\"\n\n def f(self):\n assert setproctitle.getproctitle() == \"ray_UniqueName:f()\"\n\n @ray.remote\n def unique_1():\n assert setproctitle.getproctitle(\n ) == \"ray_worker:ray.tests.test_basic.unique_1()\"\n\n actor = UniqueName.remote()\n ray.get(actor.f.remote())\n ray.get(unique_1.remote())\n\n\ndef test_duplicate_error_messages(shutdown_only):\n ray.init(num_cpus=0)\n\n driver_id = ray.WorkerID.nil()\n error_data = ray.gcs_utils.construct_error_message(driver_id, \"test\",\n \"message\", 0)\n\n # Push the same message to the GCS twice (they are the same because we\n # do not include a timestamp).\n\n r = ray.worker.global_worker.redis_client\n\n r.execute_command(\"RAY.TABLE_APPEND\",\n ray.gcs_utils.TablePrefix.Value(\"ERROR_INFO\"),\n ray.gcs_utils.TablePubsub.Value(\"ERROR_INFO_PUBSUB\"),\n driver_id.binary(), error_data)\n\n # Before https://github.com/ray-project/ray/pull/3316 this would\n # give an error\n r.execute_command(\"RAY.TABLE_APPEND\",\n ray.gcs_utils.TablePrefix.Value(\"ERROR_INFO\"),\n ray.gcs_utils.TablePubsub.Value(\"ERROR_INFO_PUBSUB\"),\n driver_id.binary(), error_data)\n\n\[email protected](\n os.getenv(\"TRAVIS\") is None,\n reason=\"This test should only be run on Travis.\")\ndef test_ray_stack(ray_start_2_cpus):\n def unique_name_1():\n time.sleep(1000)\n\n @ray.remote\n def unique_name_2():\n time.sleep(1000)\n\n @ray.remote\n def unique_name_3():\n unique_name_1()\n\n unique_name_2.remote()\n unique_name_3.remote()\n\n success = False\n start_time = time.time()\n while time.time() - start_time < 30:\n # Attempt to parse the \"ray stack\" call.\n output = ray.utils.decode(subprocess.check_output([\"ray\", \"stack\"]))\n if (\"unique_name_1\" in output and \"unique_name_2\" in output\n and \"unique_name_3\" in output):\n success = True\n break\n\n if not success:\n raise Exception(\"Failed to find necessary information with \"\n \"'ray stack'\")\n\n\ndef test_pandas_parquet_serialization():\n # Only test this if pandas is installed\n pytest.importorskip(\"pandas\")\n\n import pandas as pd\n import pyarrow as pa\n import pyarrow.parquet as pq\n\n tempdir = tempfile.mkdtemp()\n filename = os.path.join(tempdir, \"parquet-test\")\n pd.DataFrame({\"col1\": [0, 1], \"col2\": [0, 1]}).to_parquet(filename)\n with open(os.path.join(tempdir, \"parquet-compression\"), \"wb\") as f:\n table = pa.Table.from_arrays([pa.array([1, 2, 3])], [\"hello\"])\n pq.write_table(table, f, compression=\"lz4\")\n # Clean up\n shutil.rmtree(tempdir)\n\n\ndef test_socket_dir_not_existing(shutdown_only):\n random_name = ray.ObjectID.from_random().hex()\n temp_raylet_socket_dir = \"/tmp/ray/tests/{}\".format(random_name)\n temp_raylet_socket_name = os.path.join(temp_raylet_socket_dir,\n \"raylet_socket\")\n ray.init(num_cpus=1, raylet_socket_name=temp_raylet_socket_name)\n\n\ndef test_raylet_is_robust_to_random_messages(ray_start_regular):\n node_manager_address = None\n node_manager_port = None\n for client in ray.nodes():\n if \"NodeManagerAddress\" in client:\n node_manager_address = client[\"NodeManagerAddress\"]\n node_manager_port = client[\"NodeManagerPort\"]\n assert node_manager_address\n assert node_manager_port\n # Try to bring down the node manager:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((node_manager_address, node_manager_port))\n s.send(1000 * b\"asdf\")\n\n @ray.remote\n def f():\n return 1\n\n assert ray.get(f.remote()) == 1\n\n\ndef test_non_ascii_comment(ray_start_regular):\n @ray.remote\n def f():\n # 日本語 Japanese comment\n return 1\n\n assert ray.get(f.remote()) == 1\n\n\[email protected]\ndef echo(x):\n return x\n\n\[email protected]\nclass WithConstructor(object):\n def __init__(self, data):\n self.data = data\n\n def get_data(self):\n return self.data\n\n\[email protected]\nclass WithoutConstructor(object):\n def set_data(self, data):\n self.data = data\n\n def get_data(self):\n return self.data\n\n\nclass BaseClass(object):\n def __init__(self, data):\n self.data = data\n\n def get_data(self):\n return self.data\n\n\[email protected]\nclass DerivedClass(BaseClass):\n def __init__(self, data):\n # Due to different behaviors of super in Python 2 and Python 3,\n # we use BaseClass directly here.\n BaseClass.__init__(self, data)\n\n\ndef test_load_code_from_local(shutdown_only):\n ray.init(load_code_from_local=True, num_cpus=4)\n message = \"foo\"\n # Test normal function.\n assert ray.get(echo.remote(message)) == message\n # Test actor class with constructor.\n actor = WithConstructor.remote(1)\n assert ray.get(actor.get_data.remote()) == 1\n # Test actor class without constructor.\n actor = WithoutConstructor.remote()\n actor.set_data.remote(1)\n assert ray.get(actor.get_data.remote()) == 1\n # Test derived actor class.\n actor = DerivedClass.remote(1)\n assert ray.get(actor.get_data.remote()) == 1\n # Test using ray.remote decorator on raw classes.\n base_actor_class = ray.remote(num_cpus=1)(BaseClass)\n base_actor = base_actor_class.remote(message)\n assert ray.get(base_actor.get_data.remote()) == message\n\n\ndef test_shutdown_disconnect_global_state():\n ray.init(num_cpus=0)\n ray.shutdown()\n\n with pytest.raises(Exception) as e:\n ray.objects()\n assert str(e.value).endswith(\"ray.init has been called.\")\n\n\[email protected](\n \"ray_start_object_store_memory\", [150 * 1024 * 1024], indirect=True)\ndef test_put_pins_object(ray_start_object_store_memory):\n x_id = ray.put(\"HI\")\n x_copy = ray.ObjectID(x_id.binary())\n assert ray.get(x_copy) == \"HI\"\n\n # x cannot be evicted since x_id pins it\n for _ in range(10):\n ray.put(np.zeros(10 * 1024 * 1024))\n assert ray.get(x_id) == \"HI\"\n assert ray.get(x_copy) == \"HI\"\n\n # now it can be evicted since x_id pins it but x_copy does not\n del x_id\n for _ in range(10):\n ray.put(np.zeros(10 * 1024 * 1024))\n with pytest.raises(ray.exceptions.UnreconstructableError):\n ray.get(x_copy)\n\n # weakref put\n y_id = ray.put(\"HI\", weakref=True)\n for _ in range(10):\n ray.put(np.zeros(10 * 1024 * 1024))\n with pytest.raises(ray.exceptions.UnreconstructableError):\n ray.get(y_id)\n\n @ray.remote\n def check_no_buffer_ref(x):\n assert x[0].get_buffer_ref() is None\n\n z_id = ray.put(\"HI\")\n assert z_id.get_buffer_ref() is not None\n ray.get(check_no_buffer_ref.remote([z_id]))\n\n\[email protected](\n \"ray_start_object_store_memory\", [150 * 1024 * 1024], indirect=True)\ndef test_redis_lru_with_set(ray_start_object_store_memory):\n x = np.zeros(8 * 10**7, dtype=np.uint8)\n x_id = ray.put(x, weakref=True)\n\n # Remove the object from the object table to simulate Redis LRU eviction.\n removed = False\n start_time = time.time()\n while time.time() < start_time + 10:\n if ray.state.state.redis_clients[0].delete(b\"OBJECT\" +\n x_id.binary()) == 1:\n removed = True\n break\n assert removed\n\n # Now evict the object from the object store.\n ray.put(x) # This should not crash.\n\n\ndef test_decorated_function(ray_start_regular):\n def function_invocation_decorator(f):\n def new_f(args, kwargs):\n # Reverse the arguments.\n return f(args[::-1], {\"d\": 5}), kwargs\n\n return new_f\n\n def f(a, b, c, d=None):\n return a, b, c, d\n\n f.__ray_invocation_decorator__ = function_invocation_decorator\n f = ray.remote(f)\n\n result_id, kwargs = f.remote(1, 2, 3, d=4)\n assert kwargs == {\"d\": 4}\n assert ray.get(result_id) == (3, 2, 1, 5)\n\n\ndef test_get_postprocess(ray_start_regular):\n def get_postprocessor(object_ids, values):\n return [value for value in values if value > 0]\n\n ray.worker.global_worker._post_get_hooks.append(get_postprocessor)\n\n assert ray.get(\n [ray.put(i) for i in [0, 1, 3, 5, -1, -3, 4]]) == [1, 3, 5, 4]\n\n\ndef test_export_after_shutdown(ray_start_regular):\n # This test checks that we can use actor and remote function definitions\n # across multiple Ray sessions.\n\n @ray.remote\n def f():\n pass\n\n @ray.remote\n class Actor(object):\n def method(self):\n pass\n\n ray.get(f.remote())\n a = Actor.remote()\n ray.get(a.method.remote())\n\n ray.shutdown()\n\n # Start Ray and use the remote function and actor again.\n ray.init(num_cpus=1)\n ray.get(f.remote())\n a = Actor.remote()\n ray.get(a.method.remote())\n\n ray.shutdown()\n\n # Start Ray again and make sure that these definitions can be exported from\n # workers.\n ray.init(num_cpus=2)\n\n @ray.remote\n def export_definitions_from_worker(remote_function, actor_class):\n ray.get(remote_function.remote())\n actor_handle = actor_class.remote()\n ray.get(actor_handle.method.remote())\n\n ray.get(export_definitions_from_worker.remote(f, Actor))\n\n\ndef test_invalid_unicode_in_worker_log(shutdown_only):\n info = ray.init(num_cpus=1)\n\n logs_dir = os.path.join(info[\"session_dir\"], \"logs\")\n\n # Wait till first worker log file is created.\n while True:\n log_file_paths = glob.glob(\"{}/worker*.out\".format(logs_dir))\n if len(log_file_paths) == 0:\n time.sleep(0.2)\n else:\n break\n\n with open(log_file_paths[0], \"wb\") as f:\n f.write(b\"\\xe5abc\\nline2\\nline3\\n\")\n f.write(b\"\\xe5abc\\nline2\\nline3\\n\")\n f.write(b\"\\xe5abc\\nline2\\nline3\\n\")\n f.flush()\n\n # Wait till the log monitor reads the file.\n time.sleep(1.0)\n\n # Make sure that nothing has died.\n assert ray.services.remaining_processes_alive()\n\n\[email protected](reason=\"This test is too expensive to run.\")\ndef test_move_log_files_to_old(shutdown_only):\n info = ray.init(num_cpus=1)\n\n logs_dir = os.path.join(info[\"session_dir\"], \"logs\")\n\n @ray.remote\n class Actor(object):\n def f(self):\n print(\"function f finished\")\n\n # First create a temporary actor.\n actors = [\n Actor.remote() for i in range(ray_constants.LOG_MONITOR_MAX_OPEN_FILES)\n ]\n ray.get([a.f.remote() for a in actors])\n\n # Make sure no log files are in the \"old\" directory before the actors\n # are killed.\n assert len(glob.glob(\"{}/old/worker*.out\".format(logs_dir))) == 0\n\n # Now kill the actors so the files get moved to logs/old/.\n [a.__ray_terminate__.remote() for a in actors]\n\n while True:\n log_file_paths = glob.glob(\"{}/old/worker*.out\".format(logs_dir))\n if len(log_file_paths) > 0:\n with open(log_file_paths[0], \"r\") as f:\n assert \"function f finished\\n\" in f.readlines()\n break\n\n # Make sure that nothing has died.\n assert ray.services.remaining_processes_alive()\n"
]
| [
[
"numpy.random.normal",
"numpy.array",
"numpy.int8",
"numpy.uint8",
"numpy.uint32",
"numpy.zeros",
"numpy.testing.assert_equal",
"pandas.DataFrame",
"numpy.random.permutation",
"numpy.ones",
"numpy.int64",
"numpy.float64",
"numpy.float32",
"numpy.random.uniform",
"numpy.arange",
"numpy.random.randint",
"numpy.uint64",
"numpy.int32"
]
]
|
safeechowdhury/sphere_charts | [
"633e7a7e3cd2f199dbd5bbc824bc3a9c1aa82722"
]
| [
"nba_shot_charts.py"
]
| [
"\"\"\"\nThis script produces NBA Shot Charts\n\"\"\"\n# %% IMPORTS ===========================================================================================================\nfrom nba_api.stats.endpoints import shotchartdetail as scd\nimport logging\nimport os\nimport warnings\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, Rectangle, Arc\nimport pandas as pd\nimport numpy as np\nimport time\n\nLOGGER = logging.getLogger(__name__)\n\nwarnings.simplefilter(action='ignore')\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s:%(name)s:%(levelname)s:%(message)s ')\n\n# %% CONFIG ============================================================================================================\n\n# View a team's (TEAM_NAME) or a player's shot chart (PLAYER_NAME)\ntarget_col = 'PLAYER_NAME'\n# Select team or player\ntarget_name = \"Pascal Siakam\"\n# Select season\ntarget_season = '2019-20'\n# downloads the data and saves it to the DATA folder, if False will use the file in the DATA folder\nextract_data = False\n\n# number of hexagons (row) for shot chart\nhexagons = 35\n\n\n# %% FUNCTION ==========================================================================================================\n\n\n# function to create shot data\ndef season_shot_chart(season_year):\n \"\"\" Returns a dataframe that contains shot information for a given season\n Args:\n season_year (string): A string in the format of YYYY-YY\n\n Returns:\n season_shot_data (list): A dataframe which has shot information for selected season\n \"\"\"\n season_shot_df = scd.ShotChartDetail(team_id=0,\n player_id=0,\n season_nullable=season_year,\n context_measure_simple='FGA').get_data_frames()[0]\n\n LOGGER.info('Obtained data for {} season'.format(season_year))\n # save data to DATA folder\n season_shot_df.to_csv(os.path.join('DATA', 'nba_shots_detail_' + season_year.replace('-', '_') + '.csv'),\n index=False)\n LOGGER.info('Saved {} season data to csv'.format(season_year))\n\n\n# function to draw court\ndef draw_court(ax=None, color='black', lw=2, outer_lines=False):\n \"\"\"\n Args:\n ax: axes object to plot onto, if None then select current one\n color (string): colour for court background, default black\n lw (int): line_width\n outer_lines (bool): select if the drawn court will have outer lines\n\n Returns:\n axes: returns axes object that draws a court\n \"\"\"\n # If an axes object isn't provided to plot onto, just get current one\n if ax is None:\n ax = plt.gca()\n\n # Create the various parts of an NBA basketball court\n\n # Create the basketball hoop\n # Diameter of a hoop is 18\" so it has a radius of 9\", which is a value\n # 7.5 in our coordinate system\n hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)\n\n # Create backboard\n backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color)\n\n # The paint\n # Create the outer box 0f the paint, width=16ft, height=19ft\n outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color,\n fill=False)\n # Create the inner box of the paint, width=12ft, height=19ft\n # inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color,\n # fill=False)\n\n # Create free throw top arc\n top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180,\n linewidth=lw, color=color, fill=False)\n # Create free throw bottom arc\n bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0,\n linewidth=lw, color=color, linestyle='dashed')\n # Restricted Zone, it is an arc with 4ft radius from center of the hoop\n restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw,\n color=color)\n\n # Three point line\n # Create the side 3pt lines, they are 14ft long before they begin to arc\n corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw,\n color=color)\n corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color)\n # 3pt arc - center of arc will be the hoop, arc is 23'9\" away from hoop\n\n three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw,\n color=color)\n\n # List of the court elements to be plotted onto the axes\n court_elements = [hoop, backboard, outer_box,\n top_free_throw, bottom_free_throw,\n restricted, corner_three_a,\n corner_three_b, three_arc]\n\n if outer_lines:\n # Draw the half court line, baseline and side out bound lines\n outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw,\n color=color, fill=False)\n court_elements.append(outer_lines)\n\n # Add the court elements onto the axes\n for element in court_elements:\n ax.add_patch(element)\n\n return ax\n\n\n# function to create shot chart\ndef create_shot_chart(season_df, target_column, target_column_name, season_year, hexagon_width, color_scale='coolwarm'):\n \"\"\"\n Args:\n season_df (list): data_frame of season\n target_column (string): either PLAYER_NAME or TEAM_NAME\n target_column_name (string): name of player or team name\n season_year (string): YYYY-YY format\n hexagon_width (integer): how many hexagons to have (width) in the plot\n color_scale (str): string representing colour selection of plot, default is 'coolwarm'\n\n Returns:\n\n \"\"\"\n # Create league average data frame\n league_avg = (season_df.groupby(['SHOT_ZONE_BASIC', 'SHOT_ZONE_AREA'], as_index=False)\n .agg(FGA=('SHOT_ATTEMPTED_FLAG', 'sum'),\n FGM=('SHOT_MADE_FLAG', 'sum'),\n FG_PCT=('SHOT_MADE_FLAG', 'mean')))\n LOGGER.info('Created league average data frame')\n\n # Create data frame for specific team or player corresponding to target_column_name\n target_df = season_df.loc[season_df[target_column] == target_column_name]\n target_avg = (target_df.groupby(['SHOT_ZONE_BASIC', 'SHOT_ZONE_AREA'], as_index=False)\n .agg(FGA=('SHOT_ATTEMPTED_FLAG', 'sum'),\n FGM=('SHOT_MADE_FLAG', 'sum'),\n FG_PCT=('SHOT_MADE_FLAG', 'mean')))\n LOGGER.info('Created {} average data frame'.format(target_column_name))\n\n # Join dataframes to compute the net difference for each shooting zone between target and league average\n target_avg = pd.merge(target_avg, league_avg, on=['SHOT_ZONE_BASIC', 'SHOT_ZONE_AREA'],\n how='left', suffixes=('', '_league_avg'))\n\n target_avg['DIFF'] = target_avg['FG_PCT'] - target_avg['FG_PCT_league_avg']\n\n # Join net difference to each individual shot\n target_df = pd.merge(target_df,\n target_avg,\n on=['SHOT_ZONE_BASIC', 'SHOT_ZONE_AREA'],\n how='left')\n\n # Group individual shots into hexagonal bins\n target_shots_hex = plt.hexbin(target_df.LOC_X, target_df.LOC_Y,\n C=target_df.SHOT_ATTEMPTED_FLAG,\n reduce_C_function=np.sum,\n extent=(-250, 250, 422.5, -47.5),\n cmap=color_scale,\n gridsize=hexagon_width)\n plt.close()\n\n target_diff_hex = plt.hexbin(target_df.LOC_X, target_df.LOC_Y,\n C=target_df.DIFF,\n reduce_C_function=np.mean,\n extent=(-250, 250, 422.5, -47.5),\n cmap=color_scale,\n gridsize=hexagon_width)\n plt.close()\n\n shots_freq_by_hex = target_shots_hex.get_array()\n shots_diff = target_diff_hex.get_array()\n shots_loc = target_shots_hex.get_offsets()\n\n x = None\n y = None\n\n for i in range(len(shots_diff)):\n x = [i[0] for i in shots_loc]\n y = [i[1] for i in shots_loc]\n\n my_df = pd.DataFrame()\n my_df['loc_x'] = x\n my_df['loc_y'] = y\n my_df['difference'] = shots_diff\n my_df['freq'] = shots_freq_by_hex\n my_df['percentile'] = my_df['freq'].rank(pct=True)\n my_df['sizing'] = my_df['percentile'].apply(\n lambda pct: 2 if pct <= 0.4 else (\n 40 if pct <= 0.75 else (\n 100 if pct <= 0.90 else\n 200)))\n LOGGER.info('Final Data for Plot Created')\n\n plt.figure(figsize=(10, 9.4), facecolor='black')\n plt.scatter(my_df.loc_x,\n my_df.loc_y,\n c=my_df.difference,\n s=my_df.sizing,\n cmap=color_scale,\n marker='h',\n vmin=-0.10,\n vmax=0.10)\n\n draw_court(outer_lines=True, color='blanchedalmond')\n plt.xlim(-250, 250)\n plt.ylim(422.5, -47.5)\n plt.axis('off')\n\n plt.text(240, 390, target_column_name, c='white', fontsize=20, horizontalalignment='right', weight='bold')\n plt.text(240, 410, season_year + \" (reg. season)\", c='dimgrey', fontsize=16, horizontalalignment='right',\n fontstyle='italic')\n plt.text(-245, 415, \"@safee.c\", fontname=\"Gabriola\", fontsize=30, c='purple', weight='bold')\n LOGGER.info('Plot Created')\n plt.show()\n\n\n# %% MAIN ==============================================================================================================\n\n\nif __name__ == \"__main__\":\n\n if extract_data:\n # download data\n LOGGER.info('Data extract required for {}'.format(target_season))\n # run script to save season shot data\n shot_df = season_shot_chart(target_season)\n\n # read csv for season\n league_shot_df = pd.read_csv(os.path.join('DATA', 'nba_shots_detail_' + target_season.replace('-', '_') + '.csv'))\n\n create_shot_chart(league_shot_df, target_col, target_name, target_season, hexagons)\n"
]
| [
[
"matplotlib.pyplot.text",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.hexbin",
"pandas.merge",
"matplotlib.pyplot.gca",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.patches.Circle",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.scatter",
"matplotlib.patches.Rectangle",
"matplotlib.patches.Arc"
]
]
|
Steffy-zxf/models | [
"9952b253645c03709d301788ab91e3c6a2c94670"
]
| [
"PaddleCV/yolov3/eval.py"
]
| [
"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\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 __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport time\nimport json\nimport numpy as np\nimport paddle\nimport paddle.fluid as fluid\nimport reader\nfrom models.yolov3 import YOLOv3\nfrom utility import print_arguments, parse_args\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval, Params\nfrom config import cfg\n\n\ndef eval():\n if '2014' in cfg.dataset:\n test_list = 'annotations/instances_val2014.json'\n elif '2017' in cfg.dataset:\n test_list = 'annotations/instances_val2017.json'\n\n if cfg.debug:\n if not os.path.exists('output'):\n os.mkdir('output')\n\n model = YOLOv3(is_train=False)\n model.build_model()\n outputs = model.get_pred()\n place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()\n exe = fluid.Executor(place)\n # yapf: disable\n if cfg.weights:\n def if_exist(var):\n return os.path.exists(os.path.join(cfg.weights, var.name))\n fluid.io.load_vars(exe, cfg.weights, predicate=if_exist)\n # yapf: enable\n input_size = cfg.input_size\n test_reader = reader.test(input_size, 1)\n label_names, label_ids = reader.get_label_infos()\n if cfg.debug:\n print(\"Load in labels {} with ids {}\".format(label_names, label_ids))\n feeder = fluid.DataFeeder(place=place, feed_list=model.feeds())\n\n def get_pred_result(boxes, scores, labels, im_id):\n result = []\n for box, score, label in zip(boxes, scores, labels):\n x1, y1, x2, y2 = box\n w = x2 - x1 + 1\n h = y2 - y1 + 1\n bbox = [x1, y1, w, h]\n \n res = {\n 'image_id': im_id,\n 'category_id': label_ids[int(label)],\n 'bbox': list(map(float, bbox)),\n 'score': float(score)\n }\n result.append(res)\n return result\n\n dts_res = []\n fetch_list = [outputs]\n total_time = 0\n for batch_id, batch_data in enumerate(test_reader()):\n start_time = time.time()\n batch_outputs = exe.run(\n fetch_list=[v.name for v in fetch_list],\n feed=feeder.feed(batch_data),\n return_numpy=False,\n use_program_cache=True)\n lod = batch_outputs[0].lod()[0]\n nmsed_boxes = np.array(batch_outputs[0])\n if nmsed_boxes.shape[1] != 6:\n continue\n for i in range(len(lod) - 1):\n im_id = batch_data[i][1]\n start = lod[i]\n end = lod[i + 1]\n if start == end:\n continue\n nmsed_box = nmsed_boxes[start:end, :]\n labels = nmsed_box[:, 0]\n scores = nmsed_box[:, 1]\n boxes = nmsed_box[:, 2:6]\n dts_res += get_pred_result(boxes, scores, labels, im_id)\n\n end_time = time.time()\n print(\"batch id: {}, time: {}\".format(batch_id, end_time - start_time))\n total_time += end_time - start_time\n\n with open(\"yolov3_result.json\", 'w') as outfile:\n json.dump(dts_res, outfile)\n print(\"start evaluate detection result with coco api\")\n coco = COCO(os.path.join(cfg.data_dir, test_list))\n cocoDt = coco.loadRes(\"yolov3_result.json\")\n cocoEval = COCOeval(coco, cocoDt, 'bbox')\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n print(\"evaluate done.\")\n\n print(\"Time per batch: {}\".format(total_time / batch_id))\n\n\nif __name__ == '__main__':\n args = parse_args()\n print_arguments(args)\n eval()\n"
]
| [
[
"numpy.array"
]
]
|
tianyu-lu/latent_ode | [
"1a9e9415eda1837ed78e50009752b90eda3ca0db"
]
| [
"lib/latent_ode.py"
]
| [
"###########################\n# Latent ODEs for Irregularly-Sampled Time Series\n# Author: Yulia Rubanova\n###########################\n\nimport numpy as np\nimport sklearn as sk\nimport numpy as np\n#import gc\nimport torch\nimport torch.nn as nn\nfrom torch.nn.functional import relu\n\nimport lib.utils as utils\nfrom lib.utils import get_device\nfrom lib.encoder_decoder import *\nfrom lib.likelihood_eval import *\n\nfrom torch.distributions.multivariate_normal import MultivariateNormal\nfrom torch.distributions.normal import Normal\nfrom torch.distributions import kl_divergence, Independent\nfrom lib.base_models import VAE_Baseline\n\n\n\nclass LatentODE(VAE_Baseline):\n\tdef __init__(self, input_dim, latent_dim, encoder_z0, decoder, diffeq_solver, \n\t\tz0_prior, device, obsrv_std = None, \n\t\tuse_binary_classif = False, use_poisson_proc = False,\n\t\tlinear_classifier = False,\n\t\tclassif_per_tp = False,\n\t\tn_labels = 1,\n\t\ttrain_classif_w_reconstr = False,\n\t\tznet = None):\n\n\t\tsuper(LatentODE, self).__init__(\n\t\t\tinput_dim = input_dim, latent_dim = latent_dim, \n\t\t\tz0_prior = z0_prior, \n\t\t\tdevice = device, obsrv_std = obsrv_std, \n\t\t\tuse_binary_classif = use_binary_classif,\n\t\t\tclassif_per_tp = classif_per_tp, \n\t\t\tlinear_classifier = linear_classifier,\n\t\t\tuse_poisson_proc = use_poisson_proc,\n\t\t\tn_labels = n_labels,\n\t\t\ttrain_classif_w_reconstr = train_classif_w_reconstr)\n\n\t\tself.encoder_z0 = encoder_z0\n\t\tself.diffeq_solver = diffeq_solver\n\t\tself.decoder = decoder\n\t\tself.use_poisson_proc = use_poisson_proc\n\t\tself.znet = znet\n\n\tdef get_reconstruction(self, time_steps_to_predict, truth, truth_time_steps, \n\t\tmask = None, n_traj_samples = 1, run_backwards = True, mode = None):\n\n\t\tif isinstance(self.encoder_z0, Encoder_z0_ODE_RNN) or \\\n\t\t\tisinstance(self.encoder_z0, Encoder_z0_RNN):\n\n\t\t\ttruth_w_mask = truth\n\t\t\tif mask is not None:\n\t\t\t\ttruth_w_mask = torch.cat((truth, mask), -1)\n\t\t\tfirst_point_mu, first_point_std = self.encoder_z0(\n\t\t\t\ttruth_w_mask, truth_time_steps, run_backwards = run_backwards)\n\n\t\t\tmeans_z0 = first_point_mu.repeat(n_traj_samples, 1, 1)\n\t\t\tsigma_z0 = first_point_std.repeat(n_traj_samples, 1, 1)\n\t\t\tfirst_point_enc = utils.sample_standard_gaussian(means_z0, sigma_z0)\n\n\t\telse:\n\t\t\traise Exception(\"Unknown encoder type {}\".format(type(self.encoder_z0).__name__))\n\t\t\n\t\tfirst_point_std = first_point_std.abs()\n\t\tassert(torch.sum(first_point_std < 0) == 0.)\n\n\t\tif self.use_poisson_proc:\n\t\t\tn_traj_samples, n_traj, n_dims = first_point_enc.size()\n\t\t\t# append a vector of zeros to compute the integral of lambda\n\t\t\tzeros = torch.zeros([n_traj_samples, n_traj,self.input_dim]).to(get_device(truth))\n\t\t\tfirst_point_enc_aug = torch.cat((first_point_enc, zeros), -1)\n\t\t\tmeans_z0_aug = torch.cat((means_z0, zeros), -1)\n\t\telse:\n\t\t\tfirst_point_enc_aug = first_point_enc\n\t\t\tmeans_z0_aug = means_z0\n\t\t\t\n\t\tassert(not torch.isnan(time_steps_to_predict).any())\n\t\tassert(not torch.isnan(first_point_enc).any())\n\t\tassert(not torch.isnan(first_point_enc_aug).any())\n\n\t\t# Shape of sol_y [n_traj_samples, n_samples, n_timepoints, n_latents]\n\t\tsol_y = self.diffeq_solver(first_point_enc_aug, time_steps_to_predict)\n\n\t\tif self.use_poisson_proc:\n\t\t\tsol_y, log_lambda_y, int_lambda, _ = self.diffeq_solver.ode_func.extract_poisson_rate(sol_y)\n\n\t\t\tassert(torch.sum(int_lambda[:,:,0,:]) == 0.)\n\t\t\tassert(torch.sum(int_lambda[0,0,-1,:] <= 0) == 0.)\n\n\t\tpred_x = self.decoder(sol_y)\n\n\t\tall_extra_info = {\n\t\t\t\"first_point\": (first_point_mu, first_point_std, first_point_enc),\n\t\t\t\"latent_traj\": sol_y.detach()\n\t\t}\n\n\t\tif self.use_poisson_proc:\n\t\t\t# intergral of lambda from the last step of ODE Solver\n\t\t\tall_extra_info[\"int_lambda\"] = int_lambda[:,:,-1,:]\n\t\t\tall_extra_info[\"log_lambda_y\"] = log_lambda_y\n\n\t\tif self.use_binary_classif:\n\t\t\tif self.classif_per_tp:\n\t\t\t\tall_extra_info[\"label_predictions\"] = self.classifier(sol_y)\n\t\t\telse:\n\t\t\t\tall_extra_info[\"label_predictions\"] = self.classifier(first_point_enc).squeeze(-1)\n\n\t\treturn pred_x, all_extra_info\n\n\n\tdef sample_traj_from_prior(self, time_steps_to_predict, n_traj_samples = 1):\n\t\t# input_dim = starting_point.size()[-1]\n\t\t# starting_point = starting_point.view(1,1,input_dim)\n\n\t\t# Sample z0 from prior\n\t\tstarting_point_enc = self.z0_prior.sample([n_traj_samples, 1, self.latent_dim]).squeeze(-1)\n\n\t\tstarting_point_enc_aug = starting_point_enc\n\t\tif self.use_poisson_proc:\n\t\t\tn_traj_samples, n_traj, n_dims = starting_point_enc.size()\n\t\t\t# append a vector of zeros to compute the integral of lambda\n\t\t\tzeros = torch.zeros(n_traj_samples, n_traj,self.input_dim).to(self.device)\n\t\t\tstarting_point_enc_aug = torch.cat((starting_point_enc, zeros), -1)\n\n\t\tsol_y = self.diffeq_solver.sample_traj_from_prior(starting_point_enc_aug, time_steps_to_predict, \n\t\t\tn_traj_samples = 3)\n\n\t\tif self.use_poisson_proc:\n\t\t\tsol_y, log_lambda_y, int_lambda, _ = self.diffeq_solver.ode_func.extract_poisson_rate(sol_y)\n\t\t\n\t\treturn self.decoder(sol_y)\n\n\n"
]
| [
[
"torch.zeros",
"torch.cat",
"torch.isnan",
"torch.sum"
]
]
|
ALLYOURSR/loud-light | [
"5b6ad910fdcf56a17d675883022785401cf11ece"
]
| [
"docs/plot_generator.py"
]
| [
"import matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\nxvals = np.arange(0, 300, .5)\n\nperception_yvals = np.zeros(xvals.shape)\noutput_yvals = np.zeros(xvals.shape)\n\nfor i in range(len(xvals)):\n x = xvals[i]\n perception_yvals[i] = (math.log(x + 1)/.055452)\n output_yvals[i] = math.exp(.055352 * x) - 1\n\nf, ax = plt.subplots(1, 1)\n\nax.plot(xvals, perception_yvals, label=\"Human Perception\")\nax.plot(xvals, output_yvals, label=\"Corrected Brightness\")\nax.plot(xvals, xvals, label=\"Perceived Brightness\")\n\nplt.title(\"Brightness Perception Correction\")\nplt.xlabel(\"True Output Intensity\")\nplt.ylabel(\"Intensity (Perceived and Corrected)\")\n\nax.set_xlim([0,255])\nax.set_ylim([0,255])\n\nhandles, labels = ax.get_legend_handles_labels()\nplt.legend(handles, labels)\nplt.show()"
]
| [
[
"numpy.zeros",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show"
]
]
|
AstroBarker/thornado_tools | [
"553fb91910e2b93390629fb77253be2a7e8ac9b2"
]
| [
"plot/plot_thor2d.py"
]
| [
"###############################################################################\n#\n# Quick plotting script for plotting 2D thornado data.\n#\n# Syntax is `python plot_thor1d.h5 file.h5 field`, e.g., \n# plot_thor1d.py Output/Jet_FluidFields_000010.h5 uCF_D\n#\n###############################################################################\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport h5py\nimport sys\n\n# Global Plotting Settings\nmpl.rcParams['lines.linewidth'] = 4\nmpl.rcParams['legend.handlelength']=4\nmpl.rcParams['legend.fontsize']=14\nmpl.rcParams['legend.frameon']=False\nmpl.rcParams['axes.labelsize']=18\nmpl.rcParams['xtick.minor.visible']=True\nmpl.rcParams['ytick.minor.visible']=True\nmpl.rcParams['axes.linewidth'] = 2\nmpl.rcParams['xtick.major.width'] = 2\nmpl.rcParams['ytick.major.width'] = 2\nmpl.rcParams['xtick.minor.width'] = 2\nmpl.rcParams['ytick.minor.width'] = 2\nmpl.rcParams['xtick.labelsize'] = 14\nmpl.rcParams['ytick.labelsize'] = 14\n\nmb = 1.660539 * pow(10,-24)\n\nwith h5py.File(sys.argv[1], 'r') as f:\n for key in f.keys():\n print(key)\n\n # These are the only supported fields for quick plotting. Add more if necessary.\n if (sys.argv[2] == 'uCF_D'):\n df = f['/Fluid Fields/Conserved/Conserved Baryon Density'][:]\n elif (sys.argv[2] == 'uAF_P'):\n df =f['/Fluid Fields/Auxiliary/Pressure'][:]\n elif (sys.argv[2] == 'uPF_V1'): \n df = f['/Fluid Fields/Primitive/Three-Velocity (1)' ][:] \n elif (sys.argv[2] == 'uAF_Ye'):\n uCF_Ne = f['/Fluid Fields/Conserved/Conserved Electron Density'][:]\n uCF_D = f['/Fluid Fields/Conserved/Conserved Baryon Density'][:]\n df = mb * uCF_Ne[0][0][:] / uCF_D[0][0][:] \n else:\n Print(\"Please supply a supported field.\") \n \n time = f['Time'][:]\n x = f['/Spatial Grid/X1'][:]\n y = f['/Spatial Grid/X2'][:]\n \n print(time) \n\ndata = np.zeros(len(x1)) \ndata = df[0]\n\nprint(\"Plotting: %s\" % sys.argv[2])\ncmap = plt.get_cmap('Blues')\nfig, cax = plt.subplots(1, sharex=True,sharey=True,figsize=(10,10))\nfor i in range(1) :\n im = cax.pcolormesh(x, y, np.log10(data), cmap=cmap)#, norm=norm)\n cax.set_aspect('auto')\n cax.set(xlabel=r'x [km]', ylabel=r\"y [km]\")\n cax.set_title(\"Log Density\")\n plt.gca().set_aspect('equal', adjustable='box')\nlevel=np.logspace(np.log10(data_d.min()), np.log10(data_d.max()), num=30)\ncf = cax.contour(x1,\n x2, data_d,colors='k', linewidths=1.0,levels=level,\n ) \ncax.set(xlabel=\"x [km]\",ylabel = sys.argv[2])\ncax.legend()\nplt.show()\n\n"
]
| [
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"numpy.log10"
]
]
|
ysfjoe/Improving-learning-from-imbalanced-data-using-CGANs-Credit-card-fraud-detection-case-study | [
"f35ec4bd9638cc8c337ded33cd8d84e0dd1895aa"
]
| [
"utils_fraud.py"
]
| [
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import classification_report,accuracy_score, confusion_matrix,f1_score, roc_auc_score, roc_curve, precision_recall_curve, auc, balanced_accuracy_score, fbeta_score, recall_score, precision_score\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.feature_selection import SelectKBest, chi2 , SelectPercentile , f_classif\nimport random\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.manifold import TSNE\n\n\n\ndef fit_score(model,X_test,y_test):\n y_pred = model.predict(X_test)\n probs=model.predict_proba(X_test)\n probs_ov=probs[:,1]\n\n if(model.best_params_):\n print(\"Best Parameters\", model.best_params_)\n print('AUC-score :', [roc_auc_score(y_test, probs_ov)],)\n precision, recall,_ = precision_recall_curve(y_test, probs_ov)\n print(\"Precision-Recall-auc: \", [auc(recall, precision)])\n print('Balanced accuracy score', [balanced_accuracy_score(y_test,y_pred)]) \n print('Recall :' , [recall_score(y_test, y_pred)])\n print( 'Precision :' , [precision_score(y_test, y_pred)],)\n print('F1_score' , [fbeta_score(y_test,y_pred, beta=1.0)]) \n print(classification_report(y_test, y_pred))\n print(confusion_matrix(y_test, y_pred))\n\n print(\"\\n\\nroc_curve:\")\n ns_probs = [0 for _ in range(len(y_test))]\n ns_auc = roc_auc_score(y_test, ns_probs)\n\n ns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)\n lr_fpr, lr_tpr, _ = roc_curve(y_test, probs_ov)\n\n plt.plot(ns_fpr, ns_tpr, linestyle='--', label='x = y')\n plt.plot(lr_fpr, lr_tpr, marker='.', label='roc_curve')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.legend()\n plt.show()\n\n print(\"\\n\\nprauc_curve:\")\n x_y = len(y_test[y_test==1]) / len(y_test)\n plt.plot([0, 1], [x_y, x_y], linestyle='--')\n plt.plot(recall, precision, marker='.', label='pr_auc_curve')\n\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.legend()\n plt.show()\n\ndef variance(data, threshold):\n var = data.var()\n columns = data.columns\n variable = []\n for i in range(0,len(var)):\n if var[i]>=threshold: \n variable.append(columns[i])\n return variable\n\ndef correlation(data, threshold):\n correlated_features = set()\n for i in range(len(data.corr().columns)):\n for j in range(i):\n if abs(data.corr().iloc[i, j]) > threshold:\n colname = data.corr().columns[i]\n correlated_features.add(colname)\n return correlated_features\n\ndef randomForestSelector(X, y, size):\n model = RandomForestClassifier(random_state=1, max_depth=10)\n model.fit(X, y)\n features = X.columns\n importances = model.feature_importances_\n\n indices = np.argsort(importances)[-size:]\n plt.figure(figsize=(20, 10))\n plt.title('Feature Importances')\n plt.barh(range(len(indices)), importances[indices], color='b', align='center')\n plt.yticks(range(len(indices)), [features[i] for i in indices])\n plt.xlabel('Relative Importance')\n plt.show()\n foreset_variable = [features[i] for i in indices]\n return foreset_variable\n\ndef randomForestSelectorRanges(X, y, min, max):\n model = RandomForestClassifier(random_state=0, max_depth=10).fit(X, y)\n features = X.columns\n importances = model.feature_importances_\n thresholds = []\n praucs = []\n accuracys = []\n recalls = []\n precisions = []\n aucs = []\n for i in range(min, max):\n indices = np.argsort(importances)[-i:]\n foreset_variable = [features[i] for i in indices]\n x_train , x_test,y_train, y_test = train_test_split(X[foreset_variable ], y, test_size=0.3, random_state=42, stratify=y)\n clf = LogisticRegression(random_state=0, C=0.1).fit(x_train, y_train)\n y_pred = clf.predict(x_test)\n probs = clf.predict_proba(x_test)\n probs_rfs = probs[:,1]\n precision, recall, _ = precision_recall_curve(y_test, probs_rfs)\n prauc = auc(recall, precision)\n thresholds.append(i)\n praucs.append(prauc)\n accuracys.append(accuracy_score(y_pred, y_test))\n recalls.append(recall_score(y_pred, y_test))\n precisions.append(precision_score(y_pred, y_test))\n aucs.append(roc_auc_score(y_test, probs_rfs))\n plt.figure(figsize=(10,7))\n plt.plot(thresholds, praucs, marker=\".\", label='praucs')\n plt.plot(thresholds, accuracys, marker=\".\", label='accuracy')\n plt.plot(thresholds, recalls, marker=\".\", label='recall')\n plt.plot(thresholds, precisions, marker=\".\", label='precision')\n plt.plot(thresholds, aucs, marker=\".\", label='auc')\n plt.title('Metrics value for each threshold')\n plt.xlabel('threshold')\n plt.ylabel('Metrics')\n plt.legend()\n plt.show()\n\ndef Anova(X,Y,size):\n anova = f_classif(X,Y)\n p_values_anova = pd.Series(anova[1], index = X.columns)\n p_values_anova.sort_values(ascending = True , inplace= True)\n \n return p_values_anova.index[:size]\n\n\ndef gridSearch(X_train,Y_train, list_models):\n grid_models = list()\n for i in range(len(list_models)):\n grid = GridSearchCV(list_models[i][\"Model\"],list_models[i][\"params\"],cv=5,scoring='recall', verbose=1, n_jobs=-1)\n grid.fit(X_train,Y_train)\n grid_models.append(grid)\n return grid_models\n\ndef tSNE(X, nComponent, perplexity=30, lr=200, randomState=0):\n return TSNE(n_components=nComponent, perplexity=perplexity, learning_rate=lr, random_state=randomState, verbose=1).fit_transform(X)\n\ndef plotTSNE2D(X, y):\n plt.figure(figsize=(16,10))\n plt.scatter(X[:,0], X[:,1], c=y)\n plt.xlabel('component_1')\n plt.ylabel('component_2')\n plt.show()\n\ndef plotHistory(history, loss=False, acc=False):\n if acc == True:\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'val'], loc='upper left')\n plt.show()\n if loss == True:\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'val'], loc='upper left')\n plt.show()\n\ndef pipeline(data):\n rob_scaler = RobustScaler()\n scaled_amount = rob_scaler.fit_transform(data['Amount'].values.reshape(-1,1))\n scaled_time = rob_scaler.fit_transform(data['Time'].values.reshape(-1,1))\n data.insert(0, 'scaled_amount', scaled_amount)\n data.insert(1, 'scaled_time', scaled_time)\n data.drop(['Time','Amount'], axis=1, inplace=True)\n \n randomForestFeatures = randomForestSelector(X_RF, Y_RF, 8)\n \n cgans = cGAN(8)\n X_gans = data.loc[:, randomForestFeatures]\n y_train_gans = data['Class'].values.reshape(-1,1)\n pos_index = np.where(y_train_gans==1)[0]\n neg_index = np.where(y_train_gans==0)[0]\n cgans.train(X_gans.values, y_train_gans, pos_index, neg_index, epochs=2000)\n noise = np.random.normal(0, 1, (3508, 32))\n sampled_labels = np.ones(3508).reshape(-1, 1)\n gen_samples = cgans.generator.predict([noise, sampled_labels])\n data_class_fraud=data.loc[data['Class'] == 1]\n data_fraud_gans= np.concatenate((data_class_fraud.loc[:, randomForestFeatures],gen_samples), axis=0) \n data_fraud_gans = np.concatenate((data_fraud_gans,np.ones((4000,1))),axis=1)\n data_nonfraud_gans= data[data['Class']==0].sample(n=4000).loc[:, randomForestFeatures]\n data_nonfraud_gans['Class']=0\n data_gans= np.concatenate((data_fraud_gans,data_nonfraud_gans), axis=0)\n np.random.shuffle(data_gans)\n Y_gans=data_gans[:, -1]\n X_gans=data_gans[:,:-1]\n clf = RandomForestClassifier(random_state=0, bootstrap=False, max_depth=20, min_samples_split=2, n_estimators=100)\n clf.fit(X_gans,Y_gans)\n return clf\n\n"
]
| [
[
"sklearn.metrics.confusion_matrix",
"sklearn.preprocessing.RobustScaler",
"numpy.where",
"sklearn.feature_selection.f_classif",
"numpy.concatenate",
"numpy.random.normal",
"sklearn.metrics.precision_recall_curve",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.fbeta_score",
"sklearn.ensemble.RandomForestClassifier",
"matplotlib.pyplot.title",
"sklearn.metrics.balanced_accuracy_score",
"sklearn.manifold.TSNE",
"numpy.random.shuffle",
"matplotlib.pyplot.figure",
"numpy.argsort",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.show",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.recall_score",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.ones",
"sklearn.metrics.classification_report",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.auc",
"matplotlib.pyplot.ylabel",
"pandas.Series",
"sklearn.model_selection.GridSearchCV",
"matplotlib.pyplot.scatter",
"sklearn.metrics.precision_score",
"sklearn.metrics.roc_curve"
]
]
|
code-kage/albumentations | [
"f2462be3a4d01c872474d0e7fc0f32f387b06340"
]
| [
"tests/test_pytorch.py"
]
| [
"import pytest\n\nimport numpy as np\nimport torch\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensor, ToTensorV2\n\n\ndef test_torch_to_tensor_v2_augmentations(image, mask):\n aug = ToTensorV2()\n data = aug(image=image, mask=mask, force_apply=True)\n height, width, num_channels = image.shape\n assert isinstance(data[\"image\"], torch.Tensor) and data[\"image\"].shape == (num_channels, height, width)\n assert isinstance(data[\"mask\"], torch.Tensor) and data[\"mask\"].shape == mask.shape\n assert data[\"image\"].dtype == torch.uint8\n assert data[\"mask\"].dtype == torch.uint8\n\n\ndef test_torch_to_tensor_v2_augmentations_with_transpose_2d_mask(image, mask):\n aug = ToTensorV2(transpose_mask=True)\n data = aug(image=image, mask=mask, force_apply=True)\n image_height, image_width, image_num_channels = image.shape\n mask_height, mask_width = mask.shape\n assert isinstance(data[\"image\"], torch.Tensor) and data[\"image\"].shape == (\n image_num_channels,\n image_height,\n image_width,\n )\n assert isinstance(data[\"mask\"], torch.Tensor) and data[\"mask\"].shape == (mask_height, mask_width)\n assert data[\"image\"].dtype == torch.uint8\n assert data[\"mask\"].dtype == torch.uint8\n\n\ndef test_torch_to_tensor_v2_augmentations_with_transpose_3d_mask(image):\n aug = ToTensorV2(transpose_mask=True)\n mask = np.random.randint(low=0, high=256, size=(100, 100, 4), dtype=np.uint8)\n data = aug(image=image, mask=mask, force_apply=True)\n image_height, image_width, image_num_channels = image.shape\n mask_height, mask_width, mask_num_channels = mask.shape\n assert isinstance(data[\"image\"], torch.Tensor) and data[\"image\"].shape == (\n image_num_channels,\n image_height,\n image_width,\n )\n assert isinstance(data[\"mask\"], torch.Tensor) and data[\"mask\"].shape == (\n mask_num_channels,\n mask_height,\n mask_width,\n )\n assert data[\"image\"].dtype == torch.uint8\n assert data[\"mask\"].dtype == torch.uint8\n\n\ndef test_additional_targets_for_totensorv2():\n aug = A.Compose([ToTensorV2()], additional_targets={\"image2\": \"image\", \"mask2\": \"mask\"})\n for _i in range(10):\n image1 = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)\n image2 = image1.copy()\n mask1 = np.random.randint(low=0, high=256, size=(100, 100, 4), dtype=np.uint8)\n mask2 = mask1.copy()\n res = aug(image=image1, image2=image2, mask=mask1, mask2=mask2)\n\n image1_height, image1_width, image1_num_channels = image1.shape\n image2_height, image2_width, image2_num_channels = image2.shape\n assert isinstance(res[\"image\"], torch.Tensor) and res[\"image\"].shape == (\n image1_num_channels,\n image1_height,\n image1_width,\n )\n assert isinstance(res[\"image2\"], torch.Tensor) and res[\"image2\"].shape == (\n image2_num_channels,\n image2_height,\n image2_width,\n )\n assert isinstance(res[\"mask\"], torch.Tensor) and res[\"mask\"].shape == mask1.shape\n assert isinstance(res[\"mask2\"], torch.Tensor) and res[\"mask2\"].shape == mask2.shape\n assert np.array_equal(res[\"image\"], res[\"image2\"])\n assert np.array_equal(res[\"mask\"], res[\"mask2\"])\n\n\ndef test_torch_to_tensor_v2_on_gray_scale_images():\n aug = ToTensorV2()\n grayscale_image = np.random.randint(low=0, high=256, size=(100, 100), dtype=np.uint8)\n data = aug(image=grayscale_image)\n assert isinstance(data[\"image\"], torch.Tensor)\n assert len(data[\"image\"].shape) == 3\n assert data[\"image\"].shape[1:] == grayscale_image.shape\n assert data[\"image\"].dtype == torch.uint8\n\n\ndef test_torch_to_tensor_augmentations(image, mask):\n with pytest.warns(DeprecationWarning):\n aug = ToTensor()\n data = aug(image=image, mask=mask, force_apply=True)\n assert data[\"image\"].dtype == torch.float32\n assert data[\"mask\"].dtype == torch.float32\n\n\ndef test_additional_targets_for_totensor():\n with pytest.warns(DeprecationWarning):\n aug = A.Compose([ToTensor(num_classes=4)], additional_targets={\"image2\": \"image\", \"mask2\": \"mask\"})\n for _i in range(10):\n image1 = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)\n image2 = image1.copy()\n mask1 = np.random.randint(low=0, high=256, size=(100, 100, 4), dtype=np.uint8)\n mask2 = mask1.copy()\n res = aug(image=image1, image2=image2, mask=mask1, mask2=mask2)\n assert np.array_equal(res[\"image\"], res[\"image2\"])\n assert np.array_equal(res[\"mask\"], res[\"mask2\"])\n\n\ndef test_with_replaycompose():\n aug = A.ReplayCompose([ToTensorV2()])\n kwargs = {\n \"image\": np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8),\n \"mask\": np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8),\n }\n res = aug(**kwargs)\n res2 = A.ReplayCompose.replay(res[\"replay\"], **kwargs)\n assert np.array_equal(res[\"image\"], res2[\"image\"])\n assert np.array_equal(res[\"mask\"], res2[\"mask\"])\n assert res[\"image\"].dtype == torch.uint8\n assert res[\"mask\"].dtype == torch.uint8\n assert res2[\"image\"].dtype == torch.uint8\n assert res2[\"mask\"].dtype == torch.uint8\n"
]
| [
[
"numpy.random.randint",
"numpy.array_equal"
]
]
|
neerakara/Adaptive_batch_norm_for_segmentation | [
"6e7591c995b63352c58f2b4e68082e9db4e85b7d"
]
| [
"data_hcp.py"
]
| [
"import os\nimport glob\nimport numpy as np\nimport logging\n# import modules required for reading through layered zip directories\nimport zipfile, re\n# import image and other utility functions\nimport utils\nimport config.system as sys_config\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n# ===============================================================\n# This function unzips and pre-processes the data if this has not already been done.\n# If this already been done, it reads the processed data and returns it. \n# =============================================================== \ndef load_data(input_folder,\n preproc_folder,\n protocol,\n idx_start,\n idx_end,\n force_overwrite = False):\n\n '''\n This function is used to load and if necessary preprocess the HCP data\n \n :param input_folder: Folder where the raw HCP challenge data is located \n :param preproc_folder: Folder where the proprocessed data should be written to\n :param protocol: Can either be 'T1w_', 'T2w_' or 'both'. Indicates the protocol of the training data\n :param data_partition: can be training, validation or testing.\n :param force_overwrite: Set this to True if you want to overwrite already preprocessed data [default: False]\n \n :return: return the read data\n ''' \n # create the pre-processing folder, if it does not exist\n utils.makefolder(preproc_folder) \n \n logging.info('============================================================')\n logging.info('Loading data for %s images...' % (protocol) )\n \n # make appropriate filenames according to the requested indices of training, validation and test images\n config_details = '%sfrom%dto%d_' % (protocol, idx_start, idx_end)\n filepath_images = preproc_folder + config_details + 'images.npy'\n filepath_masks = preproc_folder + config_details + 'annotations15.npy'\n filepath_affine = preproc_folder + config_details + 'affines.npy'\n filepath_patnames = preproc_folder + config_details + 'patnames.npy'\n \n # if the images have not already been extracted, do so\n if not os.path.exists(filepath_images) or force_overwrite:\n logging.info('This configuration of protocol and data indices has not yet been preprocessed')\n logging.info('Preprocessing now...')\n images, masks, affines, patnames = prepare_data(input_folder,\n preproc_folder,\n protocol,\n idx_start,\n idx_end)\n else:\n logging.info('Already preprocessed this configuration. Loading now...')\n # read from already created npy files\n images = np.load(filepath_images)\n masks = np.load(filepath_masks)\n affines = np.load(filepath_affine)\n patnames = np.load(filepath_patnames)\n \n return images, masks, affines, patnames\n\n# ===============================================================\n# Main function that prepares a dataset from the raw challenge data to an hdf5 dataset.\n# Extract the required files from their zipped directories\n# ===============================================================\ndef prepare_data(input_folder,\n preproc_folder,\n protocol,\n idx_start,\n idx_end):\n \n images = []\n affines = []\n patnames = []\n masks = []\n \n # read the filenames\n filenames = sorted(glob.glob(input_folder + '*.zip'))\n logging.info('Number of images in the dataset: %s' % str(len(filenames)))\n \n # iterate through the requested indices\n for idx in range(idx_start, idx_end):\n \n logging.info('============================================================')\n # get the file name for this subject\n filename = filenames[idx]\n # read the contents inside the top-level subject directory\n with zipfile.ZipFile(filename, 'r') as zfile:\n # search for the relevant files\n for name in zfile.namelist():\n # search for files inside the T1w directory\n if re.search(r'\\/T1w/', name) != None:\n # search for .gz files inside the T1w directory\n if re.search(r'\\.gz$', name) != None: \n\n # get the protocol image\n if re.search(protocol + 'acpc_dc_restore_brain', name) != None:\n logging.info('reading image: %s' % name)\n # extract the image filepath\n _filepath = zfile.extract(name, sys_config.preproc_folder_hcp)\n # extract the patient name\n _patname = name[:name.find('/')]\n # read the image\n _img_data, _img_affine, _img_header = utils.load_nii(_filepath)\n # discarding 2 pixels from both sides in the x and z directions so that the size becomes a power of 2.\n _img_data = _img_data[2:-2,:,2:-2]\n # normalise the image\n _img_data = utils.normalise_image(_img_data, norm_type='div_by_max')\n # save the pre-processed image\n savepath = sys_config.preproc_folder_hcp + _patname + '/preprocessed_image' + protocol + '.nii'\n utils.save_nii(savepath, _img_data, _img_affine, _img_header)\n # append to the list of all images, affines and patient names\n images.append(_img_data)\n affines.append(_img_affine)\n patnames.append(_patname)\n\n # get the segmentation mask\n if re.search('aparc.aseg', name) != None: # segmentation mask with ~100 classes \n # if re.search('ribbon.nii.gz',name) != None: # segmentation mask with ~6 classes\n if re.search('T1wDividedByT2w_',name) == None:\n logging.info('reading mask: %s' % name)\n # extract the segmentation mask\n _segpath = zfile.extract(name, sys_config.preproc_folder_hcp)\n # extract the patient name\n _patname = name[:name.find('/')]\n # read the segmentation mask\n _seg_data, _seg_affine, _seg_header = utils.load_nii(_segpath)\n # discarding 2 pixels from both sides in the x and z directions so that the size becomes a power of 2.\n _seg_data = _seg_data[2:-2,:,2:-2]\n # group the segmentation classes as required - passing the \n _seg_data = utils.group_segmentation_classes(_seg_data)\n # save the pre-processed segmentation ground truth\n savepath = sys_config.preproc_folder_hcp + _patname + '/preprocessed_gt15.nii'\n #utils.save_nii(savepath, _seg_data, _seg_affine, _seg_header)\n # append to the list of all masks\n masks.append(_seg_data)\n\n # convert the lists to arrays\n images = np.array(images)\n affines = np.array(affines)\n patnames = np.array(patnames)\n masks = np.array(masks, dtype = 'uint8')\n \n # merge along the y-zis to get a stack of x-z slices, for the images as well as the masks\n images = images.swapaxes(1,2)\n images = images.reshape(-1,images.shape[2], images.shape[3])\n masks = masks.swapaxes(1,2)\n masks = masks.reshape(-1,masks.shape[2], masks.shape[3])\n \n # save the processed images and masks so that they can be directly read the next time\n # make appropriate filenames according to the requested indices of training, validation and test images\n logging.info('Saving pre-processed files...')\n config_details = '%sfrom%dto%d_' % (protocol, idx_start, idx_end)\n filepath_images = preproc_folder + config_details + 'images.npy'\n filepath_masks = preproc_folder + config_details + 'annotations15.npy'\n filepath_affine = preproc_folder + config_details + 'affines.npy'\n filepath_patnames = preproc_folder + config_details + 'patnames.npy'\n np.save(filepath_images, images)\n np.save(filepath_masks, masks)\n np.save(filepath_affine, affines)\n np.save(filepath_patnames, patnames)\n \n return images, masks, affines, patnames\n\n# ===============================================================\n# Main function that runs if this file is run directly\n# ===============================================================\nif __name__ == '__main__':\n\n input_folder = sys_config.orig_data_root_hcp\n preproc_folder = sys_config.preproc_folder_hcp\n\n i, g, _, _ = load_data(sys_config.orig_data_root_hcp, sys_config.preproc_folder_hcp, 'T1w_', 51, 53) \n# i, g, _, _ = load_data(sys_config.orig_data_root_hcp, sys_config.preproc_folder_hcp, 'T1w_', 51, 71) \n# i, g, _, _ = load_data(sys_config.orig_data_root_hcp, sys_config.preproc_folder_hcp, 'T2w_', 151, 171)\n \n import matplotlib.pyplot as plt\n plt.figure(figsize=(5,5))\n n = 140\n plt.subplot(121); plt.imshow(i[n,:,:], cmap='gray')\n plt.subplot(122); plt.imshow(g[n,:,:], cmap='gray')\n plt.show()\n \n# ===============================================================\n# End of file\n# ===============================================================\n"
]
| [
[
"numpy.array",
"numpy.load",
"numpy.save",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot"
]
]
|
PiRSquared17/r-orange | [
"6bc383f1db3c10c59e16b39daffc44df904ce031"
]
| [
"rpy3-setup/rpy/rinterface/tests/test_SexpVectorNumeric.py"
]
| [
"import unittest\nimport itertools\nimport rpy3.rinterface as rinterface\n\n\ntry:\n import numpy\n has_Numpy = True\nexcept ImportError:\n hasNumpy = False\n\n\nrinterface.initr()\n\ndef floatEqual(x, y, epsilon = 0.00000001):\n return abs(x - y) < epsilon\n\ndef testArrayStructInt(self, numericModule):\n px = [1, -2, 3]\n x = rinterface.SexpVector(px, rinterface.INTSXP)\n nx = numericModule.asarray(x)\n self.assertEquals(nx.dtype.kind, 'i')\n for orig, new in itertools.izip(px, nx):\n self.assertEquals(orig, new)\n\n # change value in the Python array... makes it change in the R vector\n nx[1] = 12\n self.assertEquals(x[1], 12)\n\ndef testArrayStructDouble(self, numericModule):\n px = [1.0, -2.0, 3.0]\n x = rinterface.SexpVector(px, rinterface.REALSXP)\n nx = numericModule.asarray(x)\n self.assertEquals(nx.dtype.kind, 'f')\n for orig, new in itertools.izip(px, nx):\n self.assertEquals(orig, new)\n \n # change value in the Python array... makes it change in the R vector\n nx[1] = 333.2\n self.assertEquals(x[1], 333.2)\n\ndef testArrayStructComplex(self, numericModule):\n px = [1+2j, 2+5j, -1+0j]\n x = rinterface.SexpVector(px, rinterface.CPLXSXP)\n nx = numericModule.asarray(x)\n self.assertEquals(nx.dtype.kind, 'c')\n for orig, new in itertools.izip(px, nx):\n self.assertEquals(orig, new)\n \ndef testArrayStructBoolean(self, numericModule):\n px = [True, False, True]\n x = rinterface.SexpVector(px, rinterface.LGLSXP)\n nx = numericModule.asarray(x)\n self.assertEquals('i', nx.dtype.kind) # not 'b', see comments in array.c\n for orig, new in itertools.izip(px, nx):\n self.assertEquals(orig, new)\n\n\nclass SexpVectorNumericTestCase(unittest.TestCase):\n\n\n def testArrayStructNumpyInt(self):\n testArrayStructInt(self, numpy)\n\n def testArrayStructNumpyDouble(self):\n testArrayStructDouble(self, numpy)\n\n def testArrayStructNumpyComplex(self):\n testArrayStructComplex(self, numpy)\n\n def testArrayStructNumpyBoolean(self):\n testArrayStructBoolean(self, numpy)\n\n def testArrayShapeLen3(self):\n extract = rinterface.baseenv['[']\n rarray = rinterface.baseenv['array'](rinterface.IntSexpVector(range(30)),\n dim = rinterface.IntSexpVector([5,2,3]))\n npyarray = numpy.array(rarray)\n for i in range(5):\n for j in range(2):\n for k in range(3):\n self.assertEquals(extract(rarray, i+1, j+1, k+1)[0], \n npyarray[i, j, k])\n\n\ndef suite():\n suite = unittest.TestLoader().loadTestsFromTestCase(SexpVectorNumericTestCase)\n return suite\n\nif __name__ == '__main__':\n tr = unittest.TextTestRunner(verbosity = 2)\n tr.run(suite())\n\n"
]
| [
[
"numpy.array"
]
]
|
iceli1007/DAT-GAN | [
"9d015d5afa4769757edb59a3ef0c53e29b40779a"
]
| [
"torch_mimicry/training/logger.py"
]
| [
"\"\"\"\nImplementation of the Logger object for performing training logging and visualisation.\n\"\"\"\nimport os\n\nimport numpy as np\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision import utils as vutils\nfrom torch_mimicry.metrics import compute_fid, compute_is, compute_kid\n\nclass Logger:\n \"\"\"\n Writes summaries and visualises training progress.\n \n Attributes:\n log_dir (str): The path to store logging information.\n num_steps (int): Total number of training iterations.\n dataset_size (int): The number of examples in the dataset.\n device (Device): Torch device object to send data to.\n flush_secs (int): Number of seconds before flushing summaries to disk.\n writers (dict): A dictionary of tensorboard writers with keys as metric names.\n num_epochs (int): The number of epochs, for extra information.\n \"\"\"\n def __init__(self,\n log_dir,\n num_steps,\n dataset_size,\n device,\n flush_secs=120,\n **kwargs):\n self.log_dir = log_dir\n self.num_steps = num_steps\n self.dataset_size = dataset_size\n self.flush_secs = flush_secs\n self.num_epochs = self._get_epoch(num_steps)\n self.device = device\n self.writers = {}\n\n # Create log directory if haven't already\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n\n def _get_epoch(self, steps):\n \"\"\"\n Helper function for getting epoch.\n \"\"\"\n return max(int(steps / self.dataset_size), 1)\n\n def _build_writer(self, metric):\n writer = SummaryWriter(log_dir=os.path.join(self.log_dir, 'data',\n metric),\n flush_secs=self.flush_secs)\n\n return writer\n\n def write_summaries(self, log_data, global_step):\n \"\"\"\n Tasks appropriate writers to write the summaries in tensorboard. Creates additional\n writers for summary writing if there are new scalars to log in log_data.\n\n Args:\n log_data (MetricLog): Dict-like object to collect log data for TB writing.\n global_step (int): Global step variable for syncing logs.\n\n Returns:\n None\n \"\"\"\n for metric, data in log_data.items():\n if metric not in self.writers:\n self.writers[metric] = self._build_writer(metric)\n\n # Write with a group name if it exists\n name = log_data.get_group_name(metric) or metric\n self.writers[metric].add_scalar(name,\n log_data[metric],\n global_step=global_step)\n\n\n\n def close_writers(self):\n \"\"\"\n Closes all writers.\n \"\"\"\n for metric in self.writers:\n self.writers[metric].close()\n\n def print_log(self, global_step, log_data, time_taken):\n \"\"\"\n Formats the string to print to stdout based on training information.\n\n Args:\n log_data (MetricLog): Dict-like object to collect log data for TB writing.\n global_step (int): Global step variable for syncing logs.\n time_taken (float): Time taken for one training iteration.\n\n Returns:\n str: String to be printed to stdout.\n \"\"\"\n # Basic information\n log_to_show = [\n \"INFO: [Epoch {:d}/{:d}][Global Step: {:d}/{:d}]\".format(\n self._get_epoch(global_step), self.num_epochs, global_step,\n self.num_steps)\n ]\n\n # Display GAN information as fed from user.\n GAN_info = [\"\"]\n metrics = sorted(log_data.keys())\n\n for metric in metrics:\n GAN_info.append('{}: {}'.format(metric, log_data[metric]))\n\n # Add train step time information\n GAN_info.append(\"({:.4f} sec/idx)\".format(time_taken))\n\n # Accumulate to log\n log_to_show.append(\"\\n| \".join(GAN_info))\n\n # Finally print the output\n ret = \" \".join(log_to_show)\n print(ret)\n\n return ret\n\n def _get_fixed_noise(self, nz, num_images, output_dir=None):\n \"\"\"\n Produce the fixed gaussian noise vectors used across all models\n for consistency.\n \"\"\"\n if output_dir is None:\n output_dir = os.path.join(self.log_dir, 'viz')\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n output_file = os.path.join(output_dir,\n 'fixed_noise_nz_{}.pth'.format(nz))\n\n if os.path.exists(output_file):\n noise = torch.load(output_file)\n\n else:\n noise = torch.randn((num_images, nz))\n torch.save(noise, output_file)\n\n return noise.to(self.device)\n\n def _get_fixed_labels(self, num_images, num_classes):\n \"\"\"\n Produces fixed class labels for generating fixed images.\n \"\"\"\n labels = np.array([i % num_classes for i in range(num_images)])\n labels = torch.from_numpy(labels).to(self.device)\n\n return labels\n\n def vis_images(self, netG, global_step, num_images=64):\n \"\"\"\n Produce visualisations of the G(z), one fixed and one random.\n\n Args:\n netG (Module): Generator model object for producing images.\n global_step (int): Global step variable for syncing logs.\n num_images (int): The number of images to visualise.\n\n Returns:\n None\n \"\"\"\n img_dir = os.path.join(self.log_dir, 'images')\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n\n with torch.no_grad():\n # Generate random images\n noise = torch.randn((num_images, netG.nz), device=self.device)\n fake_images = netG(noise).detach().cpu()\n\n # Generate fixed random images\n fixed_noise = self._get_fixed_noise(nz=netG.nz,\n num_images=num_images)\n\n if hasattr(netG, 'num_classes') and netG.num_classes > 0:\n fixed_labels = self._get_fixed_labels(num_images,\n netG.num_classes)\n fixed_fake_images = netG(fixed_noise,\n fixed_labels).detach().cpu()\n else:\n fixed_fake_images = netG(fixed_noise).detach().cpu()\n\n # Map name to results\n images_dict = {\n 'fixed_fake': fixed_fake_images,\n 'fake': fake_images\n }\n\n # Visualise all results\n for name, images in images_dict.items():\n images_viz = vutils.make_grid(images,\n padding=2,\n normalize=True)\n\n vutils.save_image(images_viz,\n '{}/{}_samples_step_{}.png'.format(\n img_dir, name, global_step),\n normalize=True)\n\n if 'img' not in self.writers:\n self.writers['img'] = self._build_writer('img')\n\n self.writers['img'].add_image('{}_vis'.format(name),\n images_viz,\n global_step=global_step)\n \n def summary_fid(self,netG,global_step,dataset,**kwargs):\n \"\"\"\n calculate the fid between generated images and real images\n\n Args:\n netG (Module): Generator model object for producing images.\n global_step (int): Global step variable for syncing logs.\n\n Returns:\n None\n \"\"\"\n img_dir = os.path.join(self.log_dir,'fid')\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n fid_score_train = compute_fid.fid_score(num_real_samples=50000,\n num_fake_samples=50000,\n netG=netG,\n batch_size=100,\n #data='cifar10',\n split='train',\n device=self.device,\n log_dir=img_dir,\n dataset=dataset,\n \n )\n fid_score_test = compute_fid.fid_score(num_real_samples=10000,\n num_fake_samples=10000,\n netG=netG,\n batch_size=100,\n #data='cifar10',\n split='val',\n dataset=dataset,\n device=self.device,\n log_dir=img_dir,\n \n )\n if 'train_Fid' not in self.writers:\n self.writers['train_Fid'] = self._build_writer('train_Fid')\n self.writers[\"train_Fid\"].add_scalar(\"train_Fid\",\n fid_score_train,\n global_step=global_step)\n if 'test_Fid' not in self.writers:\n self.writers['test_Fid'] = self._build_writer('test_Fid')\n self.writers[\"test_Fid\"].add_scalar(\"test_Fid\",\n fid_score_test,\n global_step=global_step)\n \n \n def summary_IS(self,netG,global_step,**kwargs):\n \"\"\"\n calculate the fid between generated images and real images\n\n Args:\n netG (Module): Generator model object for producing images.\n global_step (int): Global step variable for syncing logs.\n\n Returns:\n None\n \"\"\"\n img_dir = os.path.join(self.log_dir,'IS')\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n IS_score,_ = compute_is.inception_score(num_samples=50000,\n netG=netG,\n batch_size=100,\n #data='cifar10',\n device=self.device,\n log_dir=img_dir,\n **kwargs\n )\n if 'IS' not in self.writers:\n self.writers['IS'] = self._build_writer('IS')\n self.writers[\"IS\"].add_scalar(\"IS\",\n IS_score,\n global_step=global_step)\n \n def summary_KID(self,netG,global_step,dataset,**kwargs):\n \"\"\"\n calculate the fid between generated images and real images\n\n Args:\n netG (Module): Generator model object for producing images.\n global_step (int): Global step variable for syncing logs.\n\n Returns:\n None\n \"\"\"\n img_dir = os.path.join(self.log_dir,'fid')\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n kid_score_train,_ = compute_kid.kid_score(num_samples=50000,\n netG=netG,\n batch_size=100,\n split='train',\n #data='cifar10',\n dataset=dataset,\n device=self.device,\n log_dir=img_dir,\n **kwargs\n )\n kid_score_test,_ = compute_kid.kid_score(num_samples=10000,\n netG=netG,\n batch_size=100,\n split='val',\n #data='cifar10',\n device=self.device,\n dataset=dataset,\n log_dir=img_dir,\n **kwargs\n )\n if 'train_KID' not in self.writers:\n self.writers['train_KID'] = self._build_writer('train_KID')\n self.writers[\"train_KID\"].add_scalar(\"train_KID\",\n kid_score_train,\n global_step=global_step)\n if 'test_KID' not in self.writers:\n self.writers['test_KID'] = self._build_writer('test_KID')\n self.writers[\"test_KID\"].add_scalar(\"test_KID\",\n kid_score_test,\n global_step=global_step)\n \n \n \n "
]
| [
[
"torch.save",
"torch.no_grad",
"torch.from_numpy",
"torch.load",
"torch.randn"
]
]
|
HDembinski/boost-histogram | [
"6071588d8b58504938f72818d22ff3ce2a5b45dc"
]
| [
"src/boost_histogram/tag.py"
]
| [
"from __future__ import absolute_import, division, print_function\n\ndel absolute_import, division, print_function\n\n__all__ = (\"Slicer\", \"Locator\", \"at\", \"loc\", \"overflow\", \"underflow\", \"rebin\", \"sum\")\n\nimport numpy as _np\n\n\nclass Slicer(object):\n \"\"\"\n This is a simple class to make slicing inside dictionaries simpler.\n This is how it should be used:\n\n s = bh.tag.Slicer()\n\n h[{0: s[::bh.rebin(2)]}] # rebin axis 0 by two\n\n \"\"\"\n\n def __getitem__(self, item):\n return item\n\n\nclass Locator(object):\n __slots__ = (\"offset\",)\n\n def __init__(self, offset=0):\n if not isinstance(offset, int):\n raise ValueError(\"The offset must be an integer\")\n\n self.offset = offset\n\n def __add__(self, offset):\n from copy import copy\n\n other = copy(self)\n other.offset += offset\n return other\n\n def __sub__(self, offset):\n from copy import copy\n\n other = copy(self)\n other.offset -= offset\n return other\n\n def _print_self_(self):\n return \"\"\n\n def __repr__(self):\n s = self.__class__.__name__\n s += self._print_self_()\n if self.offset != 0:\n s += \" + \" if self.offset > 0 else \" - \"\n s += str(abs(self.offset))\n return s\n\n\nclass loc(Locator):\n __slots__ = (\"value\",)\n\n def __init__(self, value, offset=0):\n super(loc, self).__init__(offset)\n self.value = value\n\n def _print_self_(self):\n return \"({0})\".format(self.value)\n\n def __call__(self, axis):\n return axis.index(self.value) + self.offset\n\n\nclass underflow(Locator):\n __slots__ = ()\n\n def __call__(self, axis):\n return -1 + self.offset\n\n\nunderflow = underflow()\n\n\nclass overflow(Locator):\n __slots__ = ()\n\n def __call__(self, axis):\n return len(axis) + self.offset\n\n\noverflow = overflow()\n\n\nclass at(object):\n __slots__ = (\"value\",)\n\n def __init__(self, value):\n self.value = value\n\n def __call__(self, axis):\n if self.value < -2:\n raise IndexError(\"Index cannot be less than -1\")\n\n return self.value\n\n\nclass rebin(object):\n __slots__ = (\"factor\",)\n projection = False\n\n def __init__(self, value):\n self.factor = value\n\n def __repr__(self):\n return \"{self.__class__.__name__}({self.factor})\".format(self=self)\n\n # TODO: Add __call__ to support UHI\n\n\nclass sum(object):\n __slots__ = ()\n projection = True\n\n # Supports UHI on general histograms, and acts nicely\n # if imported from boost_histogram directly\n def __new__(cls, *args, **kwargs):\n return _np.sum(*args, **kwargs)\n\n\n# Compat only, will be removed after 0.6 release\nclass project(sum):\n pass\n"
]
| [
[
"numpy.sum"
]
]
|
zhampel/FakeFinder | [
"2891a8649acc1dabdef07554d6acb346dd23dbae"
]
| [
"detectors/ntech/ensemble.py"
]
| [
"import numpy as np\nimport cv2\n\nfrom face_utils import get_tracks, extract_sequence, extract_face\nfrom models import *\n\nVIDEO_FACE_MODEL_TRACK_STEP = 2\nVIDEO_SEQUENCE_MODEL_SEQUENCE_LENGTH = 7\nVIDEO_SEQUENCE_MODEL_TRACK_STEP = 14\n\n\nclass video_reader:\n def __init__(self, face_detector, video_target_fps=15, detector_step=3):\n self.video_target_fps = video_target_fps\n self.face_detector = face_detector\n self.detector_step = detector_step\n\n def process_video(self, video_path):\n sample = {\n 'frames': [],\n 'tracks': []\n }\n capture = cv2.VideoCapture(video_path)\n frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))\n if frame_count == 0:\n return sample\n\n fps = int(capture.get(cv2.CAP_PROP_FPS))\n video_step = round(fps / self.video_target_fps)\n if video_step == 0:\n return sample\n\n for i in range(frame_count):\n capture.grab()\n if i % video_step != 0:\n continue\n ret, frame = capture.retrieve()\n if not ret:\n continue\n\n sample['frames'].append(frame)\n\n detector_frames = sample['frames'][::self.detector_step]\n DETECTOR_BATCH_SIZE = 16\n detections = []\n for start in range(0, len(detector_frames), DETECTOR_BATCH_SIZE):\n end = min(len(detector_frames), start + DETECTOR_BATCH_SIZE)\n detections_batch = self.face_detector.detect(\n detector_frames[start:end])\n for detections_per_frame in detections_batch:\n detections.append({key: value.cpu().numpy()\n for key, value in detections_per_frame.items()})\n sample['tracks'] = get_tracks(detections)\n return sample\n\n\nclass Ensemble:\n def __init__(self, detector_weights, video_sequence_weights, first_video_face_weights, second_video_face_weights):\n detector = Detector(detector_weights)\n self.track_sequences_classifier = TrackSequencesClassifier(\n video_sequence_weights)\n self.track_faces_classifier = TrackFacesClassifier(\n first_video_face_weights, second_video_face_weights)\n self.reader = video_reader(detector)\n\n def inference(self, video_path):\n sample = self.reader.process_video(video_path)\n frames, tracks = sample['frames'], sample['tracks']\n if len(frames) == 0 or len(tracks) == 0:\n return 0.5\n sequence_track_scores = []\n for track in tracks:\n track_sequences = []\n for i, (start_idx, _) in enumerate(\n track[:-VIDEO_SEQUENCE_MODEL_SEQUENCE_LENGTH + 1:VIDEO_SEQUENCE_MODEL_TRACK_STEP]):\n assert start_idx >= 0 and start_idx + \\\n VIDEO_SEQUENCE_MODEL_SEQUENCE_LENGTH <= len(frames)\n _, bbox = track[i * VIDEO_SEQUENCE_MODEL_TRACK_STEP +\n VIDEO_SEQUENCE_MODEL_SEQUENCE_LENGTH // 2]\n track_sequences.append(extract_sequence(\n frames, start_idx, bbox, i % 2 == 0))\n sequence_track_scores.append(\n self.track_sequences_classifier.classify(track_sequences))\n face_track_scores = []\n for track in tracks:\n track_faces = []\n for i, (frame_idx, bbox) in enumerate(track[::VIDEO_FACE_MODEL_TRACK_STEP]):\n face = extract_face(frames[frame_idx], bbox, i % 2 == 0)\n track_faces.append(face)\n face_track_scores.append(\n self.track_faces_classifier.classify(track_faces))\n\n sequence_track_scores = np.concatenate(sequence_track_scores)\n face_track_scores = np.concatenate(face_track_scores)\n track_probs = np.concatenate(\n (sequence_track_scores, face_track_scores))\n\n delta = track_probs - 0.5\n sign = np.sign(delta)\n pos_delta = delta > 0\n neg_delta = delta < 0\n track_probs[pos_delta] = np.clip(\n 0.5 + sign[pos_delta] * np.power(abs(delta[pos_delta]), 0.65), 0.01, 0.99)\n track_probs[neg_delta] = np.clip(\n 0.5 + sign[neg_delta] * np.power(abs(delta[neg_delta]), 0.65), 0.01, 0.99)\n weights = np.power(abs(delta), 1.0) + 1e-4\n video_score = float((track_probs * weights).sum() / weights.sum())\n\n return video_score\n"
]
| [
[
"numpy.concatenate",
"numpy.sign"
]
]
|
0aqz0/egm-control | [
"f139980d11f43ae05c306d84dba5b581bf440a51"
]
| [
"yumi-control/client/yumi_control/yumi_cfg.py"
]
| [
"from yumi_utils import *\nimport numpy as np\n\nyumi_leftarm_lower_limits = np.array([-2.94,-2.50,-2.94,-2.15,-5.06,-1.53,-3.99])\nyumi_leftarm_upper_limits = np.array([ 2.94, 0.75, 2.94, 1.39, 5.06, 2.40, 3.99])\nyumi_rightarm_lower_limits = np.array([-2.94,-2.50,-2.94,-2.15,-5.06,-1.53,-3.99])\nyumi_rightarm_upper_limits = np.array([ 2.94, 0.75, 2.94, 1.39, 5.06, 2.40, 3.99])\n\nyumi_leftarm_lower_limits_indegrees = rad2degree( yumi_leftarm_lower_limits)\nyumi_leftarm_upper_limits_indegrees = rad2degree( yumi_leftarm_upper_limits)\nyumi_rightarm_lower_limits_indegrees = rad2degree(yumi_rightarm_lower_limits)\nyumi_rightarm_upper_limits_indegrees = rad2degree(yumi_rightarm_upper_limits)"
]
| [
[
"numpy.array"
]
]
|
plazas/nonlinearity_and_BF_HXRG_detectors | [
"c4d0acbd714e6fa25f79b57fdfa5d91a26b4581b"
]
| [
"pixel_rejector.py"
]
| [
"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nfrom scipy.stats import norm\nfrom scipy import ndimage\n\n\ndef estimateSigma(data=None, mu=0., maxOrder=None, minOrder=None, n_iter=1000):\n factor = 0.\n for i in range(n_iter):\n sample = np.random.randn(data.size) + mu\n factor = factor + np.std(sample[minOrder:maxOrder])\n factor = factor*1./n_iter\n return factor * np.std(data[minOrder:maxOrder])\n\n\ndef getBounds(data=None, center=None, thresh=60, median=False):\n from scipy.special import erf, erfc\n from scipy.optimize import minimize\n # First, get mode.\n if center == None:\n lo, hi = np.percentile(data, [10, 90])\n bins = np.linspace(lo, hi, 151)\n h, _ = np.histogram(data, bins)\n ff = np.zeros(21)\n ff[5:16] = 1./11.\n yh = np.convolve(ff, h, mode='same')\n maxind = np.argmax(yh)\n mode = np.mean([bins[maxind], bins[maxind+1]])\n elif median == False:\n mode = center\n else:\n print(\"using the median to center the distribution\")\n mode = np.median(data)\n print(\"assuming mode is:\", mode)\n # Now assume that the data are gaussian around this point.\n dist = data - mode\n outer_bound_upper = np.percentile(np.abs(dist[dist > 0]), thresh)\n outer_bound_lower = np.percentile(np.abs(dist[dist < 0]), thresh)\n print(\"upper, lower bounds:\", outer_bound_upper, outer_bound_lower)\n\n window_bound = np.min([outer_bound_upper, outer_bound_lower])\n these = ((data - mode) > -window_bound) & ((data-mode) < window_bound)\n initial_sigma = (outer_bound_upper + outer_bound_lower)/2.\n\n def gaussian_logL(sigma):\n det = np.sqrt(2*np.pi*sigma**2)\n norm = 2./erf(window_bound/np.abs(sigma)/np.sqrt(2))\n #logL_each = np.log(np.exp(-(data[these] - mode)**2/sigma**2/2.)/det * norm)\n logL_each = -(data[these]-mode)**2/sigma**2 / \\\n 2. - np.log(det) + np.log(norm)\n return -np.mean(logL_each)\n res = minimize(gaussian_logL, initial_sigma)\n sigma_est = np.abs(res.x[0])\n ncore = 1./erf(window_bound/np.abs(sigma_est)/np.sqrt(2)) * np.sum(these)\n\n return sigma_est, ncore, mode, mode + outer_bound_upper, mode - outer_bound_lower\n\n\ndef evaluate_logL(data, sigma=None, mu=None):\n det = np.sqrt(2*np.pi*sigma**2)\n logL_each = -(data - mu)**2/sigma**2/2. - np.log(det)\n return logL_each\n\n\ndef evaluate_pdf(data, sigma=None, mu=None):\n det = np.sqrt(2*np.pi*sigma**2)\n logL_each = -(data - mu)**2/sigma**2/2. - np.log(det)\n L = np.exp(logL_each)\n return L\n\n\ndef get_test_data(mu=None, sigma=None):\n data1 = sigma * np.random.randn(197000) + mu\n data2 = .3*np.random.randn(3000) - 3.\n data = np.concatenate((data1, data2))\n return data\n\n\ndef get_real_data(dfile='./2017-01-13/master-dark.fits'):\n data = fits.getdata(dfile).astype('float')\n #data = data[data != 0]\n return data\n\n\ndef determine_quality_threshold(objval, bins, qhist, nkeep, forgive=None):\n # return array of indices into original object array of those that pass quality cuts.\n bin_inds = np.digitize(objval, bins)-1\n\n objQual = np.zeros_like(objval)\n for ind in np.unique(bin_inds[(bin_inds > -1) & (bin_inds < qhist.size)]):\n objQual[bin_inds == ind] = qhist[ind]\n if (np.min(bin_inds) == -1) | (np.max(bin_inds) >= qhist.size):\n objQual[(bin_inds == -1) | (bin_inds >= qhist.size)] = np.max(qhist)\n keep_frac = nkeep*100./objval.size\n thresh = np.percentile(objQual, keep_frac)\n if forgive is not None:\n thresh = thresh*(1+forgive)\n bad_inds = objQual > thresh\n return thresh, bad_inds\n\n\ndef find_anomalies(data, center=None, forgive=.25):\n sigma_est, ncore, mode, upper_bd, lower_bd = getBounds(\n data=data, thresh=80, median=False, center=center)\n print(\"best sigma guess for sigma is:\", sigma_est)\n print(\"number of core elements is:\", ncore)\n dist = norm(loc=mode, scale=sigma_est)\n low_bd, hi_bd = dist.interval(1 - 1./data.size)\n bins = np.linspace(low_bd, hi_bd, 150)\n h, _ = np.histogram(data, bins=bins, density=True)\n bin_centers = (bins[0:-1] + bins[1:])/2.\n L = evaluate_pdf(bins, sigma=sigma_est, mu=mode)\n Lmean = (L[0:-1] + L[1:])/2. * data.size\n excess = np.abs(h*data.size - Lmean)\n excess_err = np.sqrt(Lmean)\n exthresh, mask = determine_quality_threshold(\n data, bins, excess/excess_err, ncore, forgive=forgive)\n mask_open = ndimage.binary_opening(mask)\n mask_adj = ndimage.binary_closing(mask_open)\n\n return mask, mask_adj\n\n\ndef main(argv):\n sigma_true = 1.0\n mu_true = 0.\n forgive = 0.25\n data = get_test_data(mu=mu_true, sigma=sigma_true)\n #data = get_real_data()\n sigma_est, ncore, mode, upper_bd, lower_bd = getBounds(\n data=data, thresh=80, median=False)\n logL = evaluate_logL(data, sigma=sigma_est, mu=mode)\n # print \"bound is:\",bd\n print(\"best sigma guess, sigma actual is:\", sigma_est, sigma_true)\n print(\"number of core elements is:\", ncore)\n\n # Now that we have the model fit\n # and the log-likelihoods, figure\n # out which points don't belong.\n # Which points have a low likelihood,\n # given all of the others?\n\n from scipy.stats import norm\n dist = norm(loc=mode, scale=sigma_est)\n # thresh = 1./npts\n low_bd, hi_bd = dist.interval(1 - 1./data.size)\n print(low_bd, hi_bd)\n bins = np.linspace(low_bd, hi_bd, 150)\n h, _ = np.histogram(data, bins=bins, density=True)\n bin_centers = (bins[0:-1] + bins[1:])/2.\n L = evaluate_pdf(bins, sigma=sigma_est, mu=mode)\n Lmean = (L[0:-1] + L[1:])/2. * data.size\n plt.plot(bin_centers, h*data.size)\n plt.plot(bin_centers, Lmean)\n plt.axvline(upper_bd, color='red', linestyle='--')\n plt.axvline(lower_bd, color='red', linestyle='--')\n plt.yscale('log')\n plt.show()\n\n # To establish the thresh, let's figure out how many objects we'll\n # actually want to throw out.\n ngood = ncore*1./data.size\n # Let's assume that the Poisson error is 1./sqrt(n),\n # for n in the histogram bins.\n excess = np.abs(h*data.size - Lmean)\n excess_err = np.sqrt(Lmean)\n exthresh, bad_inds = determine_quality_threshold(\n data, bins, excess/excess_err, ncore)\n exthresh = exthresh*(1+forgive)\n\n mask = np.zeros_like(data).astype('int')\n mask[bad_inds] = 1\n # Let's try simplifying the mask.\n from scipy import ndimage\n mask_open = ndimage.binary_opening(bad_inds)\n mask_close = ndimage.binary_closing(mask_open)\n mask2 = np.zeros_like(data).astype('int')\n mask2[mask_close] = 1\n #mask[bad_inds & (data < mode)] = 2\n # fits.writeto('dark_mask.fits',mask,clobber=True)\n # fits.writeto('dark_mask2.fits',mask2,clobber=True)\n plt.plot(bin_centers, excess / excess_err)\n plt.axhline(exthresh, color='red', linestyle='--')\n plt.show()\n\n\nif __name__ == \"__main__\":\n import pdb\n import traceback\n import sys\n try:\n main(sys.argv)\n except:\n thingtype, value, tb = sys.exc_info()\n traceback.print_exc()\n pdb.post_mortem(tb)\n"
]
| [
[
"numpy.median",
"numpy.exp",
"numpy.min",
"numpy.mean",
"numpy.concatenate",
"numpy.histogram",
"numpy.zeros_like",
"numpy.max",
"numpy.log",
"numpy.argmax",
"numpy.sqrt",
"matplotlib.pyplot.yscale",
"scipy.optimize.minimize",
"numpy.convolve",
"numpy.zeros",
"matplotlib.pyplot.axhline",
"numpy.percentile",
"numpy.random.randn",
"numpy.std",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axvline",
"scipy.ndimage.binary_closing",
"scipy.stats.norm",
"numpy.sum",
"matplotlib.pyplot.plot",
"scipy.ndimage.binary_opening",
"numpy.digitize",
"numpy.abs",
"numpy.linspace",
"numpy.unique"
]
]
|
GNroy/NeMo | [
"3d0c29a317b89b20c93757010db80271eeea6816"
]
| [
"nemo/collections/tts/models/hifigan.py"
]
| [
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport itertools\n\nimport torch\nimport torch.nn.functional as F\nfrom hydra.utils import instantiate\nfrom omegaconf import DictConfig, OmegaConf, open_dict\nfrom pytorch_lightning.loggers.wandb import WandbLogger\n\nfrom nemo.collections.tts.data.datalayers import MelAudioDataset\nfrom nemo.collections.tts.helpers.helpers import get_batch_size, get_num_workers, plot_spectrogram_to_numpy\nfrom nemo.collections.tts.losses.hifigan_losses import DiscriminatorLoss, FeatureMatchingLoss, GeneratorLoss\nfrom nemo.collections.tts.models.base import Vocoder\nfrom nemo.collections.tts.modules.hifigan_modules import MultiPeriodDiscriminator, MultiScaleDiscriminator\nfrom nemo.core.classes import Exportable\nfrom nemo.core.classes.common import PretrainedModelInfo, typecheck\nfrom nemo.core.neural_types.elements import AudioSignal, MelSpectrogramType\nfrom nemo.core.neural_types.neural_type import NeuralType\nfrom nemo.core.optim.lr_scheduler import CosineAnnealing, compute_max_steps\nfrom nemo.utils import logging\n\nHAVE_WANDB = True\ntry:\n import wandb\nexcept ModuleNotFoundError:\n HAVE_WANDB = False\n\n\nclass HifiGanModel(Vocoder, Exportable):\n def __init__(self, cfg: DictConfig, trainer: 'Trainer' = None):\n if isinstance(cfg, dict):\n cfg = OmegaConf.create(cfg)\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.audio_to_melspec_precessor = instantiate(cfg.preprocessor)\n # use a different melspec extractor because:\n # 1. we need to pass grads\n # 2. we need remove fmax limitation\n self.trg_melspec_fn = instantiate(cfg.preprocessor, highfreq=None, use_grads=True)\n self.generator = instantiate(cfg.generator)\n self.mpd = MultiPeriodDiscriminator(debug=cfg.debug if \"debug\" in cfg else False)\n self.msd = MultiScaleDiscriminator(debug=cfg.debug if \"debug\" in cfg else False)\n self.feature_loss = FeatureMatchingLoss()\n self.discriminator_loss = DiscriminatorLoss()\n self.generator_loss = GeneratorLoss()\n\n self.l1_factor = cfg.get(\"l1_loss_factor\", 45)\n\n self.sample_rate = self._cfg.preprocessor.sample_rate\n self.stft_bias = None\n\n if self._train_dl and isinstance(self._train_dl.dataset, MelAudioDataset):\n self.input_as_mel = True\n else:\n self.input_as_mel = False\n\n self.automatic_optimization = False\n\n def _get_max_steps(self):\n return compute_max_steps(\n max_epochs=self._cfg.max_epochs,\n accumulate_grad_batches=self.trainer.accumulate_grad_batches,\n limit_train_batches=self.trainer.limit_train_batches,\n num_workers=get_num_workers(self.trainer),\n num_samples=len(self._train_dl.dataset),\n batch_size=get_batch_size(self._train_dl),\n drop_last=self._train_dl.drop_last,\n )\n\n def _get_warmup_steps(self, max_steps):\n warmup_steps = self._cfg.sched.get(\"warmup_steps\", None)\n warmup_ratio = self._cfg.sched.get(\"warmup_ratio\", None)\n\n if warmup_steps is not None and warmup_ratio is not None:\n raise ValueError(f'Either use warmup_steps or warmup_ratio for scheduler')\n\n if warmup_steps is not None:\n return warmup_steps\n\n if warmup_ratio is not None:\n return warmup_ratio * max_steps\n\n raise ValueError(f'Specify warmup_steps or warmup_ratio for scheduler')\n\n def configure_optimizers(self):\n self.optim_g = instantiate(self._cfg.optim, params=self.generator.parameters(),)\n self.optim_d = instantiate(\n self._cfg.optim, params=itertools.chain(self.msd.parameters(), self.mpd.parameters()),\n )\n\n if hasattr(self._cfg, 'sched'):\n max_steps = self._cfg.get(\"max_steps\", None)\n if max_steps is None or max_steps < 0:\n max_steps = self._get_max_steps()\n\n warmup_steps = self._get_warmup_steps(max_steps)\n\n self.scheduler_g = CosineAnnealing(\n optimizer=self.optim_g, max_steps=max_steps, min_lr=self._cfg.sched.min_lr, warmup_steps=warmup_steps,\n ) # Use warmup to delay start\n sch1_dict = {\n 'scheduler': self.scheduler_g,\n 'interval': 'step',\n }\n\n self.scheduler_d = CosineAnnealing(\n optimizer=self.optim_d, max_steps=max_steps, min_lr=self._cfg.sched.min_lr,\n )\n sch2_dict = {\n 'scheduler': self.scheduler_d,\n 'interval': 'step',\n }\n\n return [self.optim_g, self.optim_d], [sch1_dict, sch2_dict]\n else:\n return [self.optim_g, self.optim_d]\n\n @property\n def input_types(self):\n return {\n \"spec\": NeuralType(('B', 'D', 'T'), MelSpectrogramType()),\n }\n\n @property\n def output_types(self):\n return {\n \"audio\": NeuralType(('B', 'S', 'T'), AudioSignal(self.sample_rate)),\n }\n\n @typecheck()\n def forward(self, *, spec):\n \"\"\"\n Runs the generator, for inputs and outputs see input_types, and output_types\n \"\"\"\n return self.generator(x=spec)\n\n @typecheck(\n input_types={\"spec\": NeuralType(('B', 'C', 'T'), MelSpectrogramType())},\n output_types={\"audio\": NeuralType(('B', 'T'), AudioSignal())},\n )\n def convert_spectrogram_to_audio(self, spec: 'torch.tensor') -> 'torch.tensor':\n return self(spec=spec).squeeze(1)\n\n def training_step(self, batch, batch_idx):\n # if in finetune mode the mels are pre-computed using a\n # spectrogram generator\n if self.input_as_mel:\n audio, audio_len, audio_mel = batch\n # else, we compute the mel using the ground truth audio\n else:\n audio, audio_len = batch\n # mel as input for generator\n audio_mel, _ = self.audio_to_melspec_precessor(audio, audio_len)\n\n # mel as input for L1 mel loss\n audio_trg_mel, _ = self.trg_melspec_fn(audio, audio_len)\n audio = audio.unsqueeze(1)\n\n audio_pred = self.generator(x=audio_mel)\n audio_pred_mel, _ = self.trg_melspec_fn(audio_pred.squeeze(1), audio_len)\n\n # train discriminator\n self.optim_d.zero_grad()\n mpd_score_real, mpd_score_gen, _, _ = self.mpd(y=audio, y_hat=audio_pred.detach())\n loss_disc_mpd, _, _ = self.discriminator_loss(\n disc_real_outputs=mpd_score_real, disc_generated_outputs=mpd_score_gen\n )\n msd_score_real, msd_score_gen, _, _ = self.msd(y=audio, y_hat=audio_pred.detach())\n loss_disc_msd, _, _ = self.discriminator_loss(\n disc_real_outputs=msd_score_real, disc_generated_outputs=msd_score_gen\n )\n loss_d = loss_disc_msd + loss_disc_mpd\n self.manual_backward(loss_d)\n self.optim_d.step()\n\n # train generator\n self.optim_g.zero_grad()\n loss_mel = F.l1_loss(audio_pred_mel, audio_trg_mel)\n _, mpd_score_gen, fmap_mpd_real, fmap_mpd_gen = self.mpd(y=audio, y_hat=audio_pred)\n _, msd_score_gen, fmap_msd_real, fmap_msd_gen = self.msd(y=audio, y_hat=audio_pred)\n loss_fm_mpd = self.feature_loss(fmap_r=fmap_mpd_real, fmap_g=fmap_mpd_gen)\n loss_fm_msd = self.feature_loss(fmap_r=fmap_msd_real, fmap_g=fmap_msd_gen)\n loss_gen_mpd, _ = self.generator_loss(disc_outputs=mpd_score_gen)\n loss_gen_msd, _ = self.generator_loss(disc_outputs=msd_score_gen)\n loss_g = loss_gen_msd + loss_gen_mpd + loss_fm_msd + loss_fm_mpd + loss_mel * self.l1_factor\n self.manual_backward(loss_g)\n self.optim_g.step()\n\n # run schedulers\n schedulers = self.lr_schedulers()\n if schedulers is not None:\n sch1, sch2 = schedulers\n sch1.step()\n sch2.step()\n\n metrics = {\n \"g_loss_fm_mpd\": loss_fm_mpd,\n \"g_loss_fm_msd\": loss_fm_msd,\n \"g_loss_gen_mpd\": loss_gen_mpd,\n \"g_loss_gen_msd\": loss_gen_msd,\n \"g_loss\": loss_g,\n \"d_loss_mpd\": loss_disc_mpd,\n \"d_loss_msd\": loss_disc_msd,\n \"d_loss\": loss_d,\n \"global_step\": self.global_step,\n \"lr\": self.optim_g.param_groups[0]['lr'],\n }\n self.log_dict(metrics, on_step=True, sync_dist=True)\n self.log(\"g_l1_loss\", loss_mel, prog_bar=True, logger=False, sync_dist=True)\n\n def validation_step(self, batch, batch_idx):\n if self.input_as_mel:\n audio, audio_len, audio_mel = batch\n audio_mel_len = [audio_mel.shape[1]] * audio_mel.shape[0]\n else:\n audio, audio_len = batch\n audio_mel, audio_mel_len = self.audio_to_melspec_precessor(audio, audio_len)\n audio_pred = self(spec=audio_mel)\n\n # perform bias denoising\n pred_denoised = self._bias_denoise(audio_pred, audio_mel).squeeze(1)\n pred_denoised_mel, _ = self.audio_to_melspec_precessor(pred_denoised, audio_len)\n\n if self.input_as_mel:\n gt_mel, gt_mel_len = self.audio_to_melspec_precessor(audio, audio_len)\n audio_pred_mel, _ = self.audio_to_melspec_precessor(audio_pred.squeeze(1), audio_len)\n loss_mel = F.l1_loss(audio_mel, audio_pred_mel)\n\n self.log_dict({\"val_loss\": loss_mel}, on_epoch=True, sync_dist=True)\n\n # plot audio once per epoch\n if batch_idx == 0 and isinstance(self.logger, WandbLogger) and HAVE_WANDB:\n clips = []\n specs = []\n for i in range(min(5, audio.shape[0])):\n clips += [\n wandb.Audio(\n audio[i, : audio_len[i]].data.cpu().numpy(),\n caption=f\"real audio {i}\",\n sample_rate=self.sample_rate,\n ),\n wandb.Audio(\n audio_pred[i, 0, : audio_len[i]].data.cpu().numpy().astype('float32'),\n caption=f\"generated audio {i}\",\n sample_rate=self.sample_rate,\n ),\n wandb.Audio(\n pred_denoised[i, : audio_len[i]].data.cpu().numpy(),\n caption=f\"denoised audio {i}\",\n sample_rate=self.sample_rate,\n ),\n ]\n specs += [\n wandb.Image(\n plot_spectrogram_to_numpy(audio_mel[i, :, : audio_mel_len[i]].data.cpu().numpy()),\n caption=f\"input mel {i}\",\n ),\n wandb.Image(\n plot_spectrogram_to_numpy(audio_pred_mel[i, :, : audio_mel_len[i]].data.cpu().numpy()),\n caption=f\"output mel {i}\",\n ),\n wandb.Image(\n plot_spectrogram_to_numpy(pred_denoised_mel[i, :, : audio_mel_len[i]].data.cpu().numpy()),\n caption=f\"denoised mel {i}\",\n ),\n ]\n if self.input_as_mel:\n specs += [\n wandb.Image(\n plot_spectrogram_to_numpy(gt_mel[i, :, : audio_mel_len[i]].data.cpu().numpy()),\n caption=f\"gt mel {i}\",\n ),\n ]\n\n self.logger.experiment.log({\"audio\": clips, \"specs\": specs})\n\n def _bias_denoise(self, audio, mel):\n def stft(x):\n comp = torch.stft(x.squeeze(1), n_fft=1024, hop_length=256, win_length=1024)\n real, imag = comp[..., 0], comp[..., 1]\n mags = torch.sqrt(real ** 2 + imag ** 2)\n phase = torch.atan2(imag, real)\n return mags, phase\n\n def istft(mags, phase):\n comp = torch.stack([mags * torch.cos(phase), mags * torch.sin(phase)], dim=-1)\n x = torch.istft(comp, n_fft=1024, hop_length=256, win_length=1024)\n return x\n\n # create bias tensor\n if self.stft_bias is None or self.stft_bias.shape[0] != audio.shape[0]:\n audio_bias = self(spec=torch.zeros_like(mel, device=mel.device))\n self.stft_bias, _ = stft(audio_bias)\n self.stft_bias = self.stft_bias[:, :, 0][:, :, None]\n\n audio_mags, audio_phase = stft(audio)\n audio_mags = audio_mags - self.cfg.get(\"denoise_strength\", 0.0025) * self.stft_bias\n audio_mags = torch.clamp(audio_mags, 0.0)\n audio_denoised = istft(audio_mags, audio_phase).unsqueeze(1)\n\n return audio_denoised\n\n def __setup_dataloader_from_config(self, cfg, shuffle_should_be: bool = True, name: str = \"train\"):\n if \"dataset\" not in cfg or not isinstance(cfg.dataset, DictConfig):\n raise ValueError(f\"No dataset for {name}\")\n if \"dataloader_params\" not in cfg or not isinstance(cfg.dataloader_params, DictConfig):\n raise ValueError(f\"No dataloder_params for {name}\")\n if shuffle_should_be:\n if 'shuffle' not in cfg.dataloader_params:\n logging.warning(\n f\"Shuffle should be set to True for {self}'s {name} dataloader but was not found in its \"\n \"config. Manually setting to True\"\n )\n with open_dict(cfg[\"dataloader_params\"]):\n cfg.dataloader_params.shuffle = True\n elif not cfg.dataloader_params.shuffle:\n logging.error(f\"The {name} dataloader for {self} has shuffle set to False!!!\")\n elif not shuffle_should_be and cfg.dataloader_params.shuffle:\n logging.error(f\"The {name} dataloader for {self} has shuffle set to True!!!\")\n\n dataset = instantiate(cfg.dataset)\n return torch.utils.data.DataLoader(dataset, collate_fn=dataset.collate_fn, **cfg.dataloader_params)\n\n def setup_training_data(self, cfg):\n self._train_dl = self.__setup_dataloader_from_config(cfg)\n\n def setup_validation_data(self, cfg):\n self._validation_dl = self.__setup_dataloader_from_config(cfg, shuffle_should_be=False, name=\"validation\")\n\n @classmethod\n def list_available_models(cls) -> 'Optional[Dict[str, str]]':\n list_of_models = []\n model = PretrainedModelInfo(\n pretrained_model_name=\"tts_hifigan\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/tts_hifigan/versions/1.0.0rc1/files/tts_hifigan.nemo\",\n description=\"This model is trained on LJSpeech audio sampled at 22050Hz and mel spectrograms generated from Tacotron2, TalkNet, and FastPitch. This model has been tested on generating female English voices with an American accent.\",\n class_=cls,\n )\n list_of_models.append(model)\n\n model = PretrainedModelInfo(\n pretrained_model_name=\"tts_en_lj_hifigan_ft_mixertts\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/tts_en_lj_hifigan/versions/1.6.0/files/tts_en_lj_hifigan_ft_mixertts.nemo\",\n description=\"This model is trained on LJSpeech audio sampled at 22050Hz and mel spectrograms generated from Mixer-TTS. This model has been tested on generating female English voices with an American accent.\",\n class_=cls,\n )\n list_of_models.append(model)\n\n model = PretrainedModelInfo(\n pretrained_model_name=\"tts_en_lj_hifigan_ft_mixerttsx\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/tts_en_lj_hifigan/versions/1.6.0/files/tts_en_lj_hifigan_ft_mixerttsx.nemo\",\n description=\"This model is trained on LJSpeech audio sampled at 22050Hz and mel spectrograms generated from Mixer-TTS-X. This model has been tested on generating female English voices with an American accent.\",\n class_=cls,\n )\n list_of_models.append(model)\n\n return list_of_models\n\n def load_state_dict(self, state_dict, strict=True):\n # override load_state_dict to give us some flexibility to be backward-compatible\n # with old checkpoints\n new_state_dict = {}\n num_resblocks = len(self.cfg['generator']['resblock_kernel_sizes'])\n for k, v in state_dict.items():\n new_k = k\n if 'resblocks' in k:\n parts = k.split(\".\")\n # only do this is the checkpoint type is older\n if len(parts) == 6:\n layer = int(parts[2])\n new_layer = f\"{layer // num_resblocks}.{layer % num_resblocks}\"\n new_k = f\"generator.resblocks.{new_layer}.{'.'.join(parts[3:])}\"\n new_state_dict[new_k] = v\n super().load_state_dict(new_state_dict, strict=strict)\n\n def _prepare_for_export(self, **kwargs):\n \"\"\"\n Override this method to prepare module for export. This is in-place operation.\n Base version does common necessary module replacements (Apex etc)\n \"\"\"\n if self.generator is not None:\n try:\n self.generator.remove_weight_norm()\n except ValueError:\n return\n\n def input_example(self):\n \"\"\"\n Generates input examples for tracing etc.\n Returns:\n A tuple of input examples.\n \"\"\"\n par = next(self.parameters())\n mel = torch.randn((1, self.cfg['preprocessor']['nfilt'], 96), device=par.device, dtype=par.dtype)\n return ({'spec': mel},)\n\n def forward_for_export(self, spec):\n \"\"\"\n Runs the generator, for inputs and outputs see input_types, and output_types\n \"\"\"\n return self.generator(x=spec)\n"
]
| [
[
"torch.cos",
"torch.sqrt",
"torch.sin",
"torch.nn.functional.l1_loss",
"torch.clamp",
"torch.istft",
"torch.utils.data.DataLoader",
"torch.zeros_like",
"torch.atan2",
"torch.randn"
]
]
|
haoweini/spotify_stream | [
"83fd13d4da9fb54a595611d4c0cd594eb5b8a9fd"
]
| [
"src/data/get_saved_library.py"
]
| [
"import configparser\nimport json\nimport spotipy\nimport spotipy.util as util\nimport pandas as pd\nimport spotipy.oauth2 as oauth2\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport bamboolib\nimport streamlit as st\nimport requests\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nwith open('../data/raw/spotify_creds.json') as f:\n spotify_creds = json.load(f)\n\n#with open('../data/raw/spotify_token.json') as f:\n # spotify_token = json.load(f)\n\nclient_id = spotify_creds['client_id']\nclient_secret = spotify_creds['client_secret']\nusername = spotify_creds['username']\nscope = 'user-library-read user-read-recently-played user-top-read'\nredirect_uri = spotify_creds['saved_library_redirect_url']\n#token = spotify_token['all_access_token']\n\n\ndef connect_to_spotify_api(client_id, client_secret, username, scope, redirect_uri):\n \n client_credentials_manager = SpotifyClientCredentials(client_id, client_secret) \n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\n token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)\n if token:\n sp = spotipy.Spotify(auth=token)\n else:\n print(\"Can't get token for\", username)\n \n return sp\n\nsp = connect_to_spotify_api(client_id, client_secret, username, scope, redirect_uri)\n\ndef display_user_name():\n sp = connect_to_spotify_api(client_id, client_secret, username, scope, redirect_uri)\n user = sp.current_user()\n user_name = user['display_name']\n return user_name\n\ndef display_user_pic():\n sp = connect_to_spotify_api(client_id, client_secret, username, scope, redirect_uri)\n user = sp.current_user()\n pic_url = user['images'][0]['url']\n with open('../data/raw/user_pic.jpg', 'wb') as f:\n f.write(requests.get(pic_url).content)\n return pic_url\n\[email protected](suppress_st_warning=True, allow_output_mutation=True)\ndef get_saved_library():\n \n df_saved_tracks = pd.DataFrame()\n track_list = ''\n added_ts_list = []\n artist_list = []\n artist_url_list = []\n title_list = []\n popularity_list = []\n album_cover_list = []\n track_url_list = []\n more_songs = True\n offset_index = 0\n\n while more_songs:\n songs = sp.current_user_saved_tracks(offset=offset_index)\n for song in songs['items']:\n #join track ids to a string for audio_features function\n track_list += song['track']['id'] +','\n #get the time when the song was added\n added_ts_list.append(song['added_at'])\n #get the title of the song\n title_list.append(song['track']['name'])\n #get popularity\n popularity_list.append(song['track']['popularity'])\n album_cover_list.append(song['track']['album']['images'][0]['url'])\n # get track list\n track_url = song['track']['external_urls']['spotify']\n track_url = track_url.split('/')[-1]\n track_url_list.append(track_url)\n #get all the artists in the song\n artists = song['track']['artists']\n artists_name = ''\n for artist in artists:\n artists_name += artist['name'] + ','\n artist_list.append(artists_name[:-1])\n # aritst_url\n artists = song['track']['artists']\n artists_urls = ''\n for artist in artists:\n artist_url = artist['external_urls']['spotify']\n artist_url = artist_url.split('/')[-1]\n artists_urls += artist_url + ','\n artist_url_list.append(artists_urls[:-1])\n \n track_features = sp.audio_features(track_list[:-1])\n df_temp = pd.DataFrame(track_features)\n df_temp = df_temp[['acousticness', 'danceability', 'energy', 'speechiness', 'valence', 'tempo']]\n df_temp = df_temp.rename(columns={'tempo': 'BPM'})\n df_saved_tracks = df_saved_tracks.append(df_temp)\n track_list = ''\n if songs['next'] == None:\n # no more songs in playlist\n more_songs = False\n else:\n # get the next n songs\n offset_index += songs['limit']\n #include timestamp added, title and artists of a song\n df_saved_tracks['song_title'] = title_list\n df_saved_tracks['artists'] = artist_list\n df_saved_tracks['artists_url'] = artist_url_list\n df_saved_tracks['date_added'] = added_ts_list\n df_saved_tracks['album_cover'] = album_cover_list\n df_saved_tracks['popularity'] = popularity_list\n df_saved_tracks['date_added'] = df_saved_tracks['date_added'].apply(lambda x: x.split('T')[0])\n df_saved_tracks['url'] = track_url_list\n df_saved_tracks['date_added'] = pd.to_datetime(df_saved_tracks['date_added'], infer_datetime_format=True)\n df_saved_tracks['date_added_year'] = df_saved_tracks['date_added'].dt.year\n \n return df_saved_tracks\n\ndef get_all_genre(df):\n sp = connect_to_spotify_api(client_id, client_secret, username, scope, redirect_uri)\n artist_list = []\n\n for i in range(len(df)):\n artists = df.iloc[i]['artists_url']\n for artist in artists.split(','):\n artist_list.append(artist)\n\n artist_list = set(artist_list)\n \n df_artist_genre = pd.DataFrame()\n aritst_name_list = []\n aritst_genre_list = []\n\n for i in artist_list:\n aritst_name = sp.artist(i)['name']\n #print(aritst_name)\n aritst_genre = sp.artist(i)['genres']\n aritst_name_list.append(aritst_name)\n aritst_genre_list.append(aritst_genre)\n\n df_artist_genre['name'] = aritst_name_list\n df_artist_genre['genre'] = aritst_genre_list\n \n df_artist_detailed_genre = pd.DataFrame()\n aritst_name_list = []\n aritst_genre_list = []\n\n for i in range(len(df_artist_genre)):\n artist = df_artist_genre.iloc[i]['name']\n genre_list = df_artist_genre.iloc[i]['genre']\n for genre in genre_list:\n aritst_name_list.append(artist)\n aritst_genre_list.append(genre)\n\n df_artist_detailed_genre['name'] = aritst_name_list\n df_artist_detailed_genre['genre'] = aritst_genre_list\n \n return df_artist_detailed_genre"
]
| [
[
"pandas.to_datetime",
"pandas.DataFrame"
]
]
|
jac241/ct-slice-detection | [
"20ceee8f6bb139fbb57455c558d53e303c4ade97"
]
| [
"ct_slice_detection/inout/preprocessing.py"
]
| [
"import numpy as np\nimport cv2\n\n\n\ndef normalise(img):\n img = img.astype(np.float16)\n return (img - img.min())/(img.max()-img.min()+1e-7)*255\n\ndef to256(img):\n img = img.astype(np.float16)\n return 255*(img - img.min())/(img.max()-img.min()+1e-7)\n\ndef mat2gray(img):\n img = img.astype(np.float32)\n return (img - np.min(img))/(np.max(img)-np.min(img)+1e-7)\n\n\ndef blend2d(image, labelmap, alpha):\n\n # for label in np.unique(labelmap):\n label = 1\n image = np.stack((image,)*3,axis=-1)\n labelmap = np.stack((labelmap,)*3, axis=-1)\n labelmap[:,:,1:2] = 0\n return alpha*labelmap + \\\n np.multiply((1-alpha)*mat2gray(image),mat2gray(labelmap==label))\\\n + np.multiply(mat2gray(image),1-mat2gray(labelmap==label))\n\n\ndef normalise_image_zero_one(image, eps=1e-7):\n\n image = image.astype(np.float32)\n v = (image - np.min(image))\n v /= (np.max(image) - np.min(image) + eps)\n\n return v\n\n\ndef normalise_image_one_one(image):\n\n v = 2 * normalise_image_zero_one(image) - 1\n\n return v\n\ndef preprocess_to_8bit(img, minv=100, maxv=1500):\n img = np.clip(img, minv, maxv)\n img = 255 * normalise_image_zero_one(img)\n\n return img\n\n\ndef gray2rgb(img):\n if len(img.shape)==2 or img.shape[2] == 1:\n return np.dstack([img]*3)\n else:\n return img\n\n# def to256(img):\n# return 255 * normalise_image_zero_one(img).astype(np.uint8)\n\n\ndef overlay_heatmap_on_image(img, heatmap):\n pred_map_color = cv2.applyColorMap((255 * (1 - heatmap)).astype(np.uint8), cv2.COLORMAP_JET)\n return (img * (1 - heatmap) + heatmap * pred_map_color).astype(np.uint8)\n\n\n\ndef extract_random_example_array(image_list, example_size=[64, 64], n_examples=1,\n loc=[50, 50], anywhere=False, border_shift=10):\n \"\"\"\n Randomly extract training examples from image (and corresponding label).\n Returns an image example array and the corresponding label array.\n\n Note: adapted from https://github.com/DLTK/DLTK\n Parameters\n ----------\n image_list: np.ndarray or list or tuple\n image(s) to extract random patches from\n example_size: list or tuple\n shape of the patches to extract\n n_examples: int\n number of patches to extract in total\n\n Returns\n -------\n examples\n random patches extracted from bigger images with same type as image_list with of shape\n [batch, example_size..., image_channels]\n \"\"\"\n\n def get_range(img_idx):\n if anywhere:\n valid_loc_range = [image_list[img_idx].shape[i] - example_size[i] for i in range(rank)]\n\n rnd_loc = [np.random.randint(valid_loc_range[dim], size=n_examples)\n if valid_loc_range[dim] > 0 else np.zeros(n_examples, dtype=int) for dim in range(rank)]\n else:\n low_valid_loc_range = [max(loc[i] - example_size[i ] +border_shift ,0) for i in range(rank)]\n # high_valid_loc_range = [min(loc[i] + example_size[i]//2,image_list[img_idx].shape[i])\n # for i in range(rank)]\n high_valid_loc_range = \\\n [min(loc[i] - border_shift, image_list[img_idx].shape[i] - example_size[i] - border_shift)\n for i in range(rank)]\n rnd_loc = [np.random.randint(low_valid_loc_range[dim], high_valid_loc_range[dim], size=n_examples)\n if high_valid_loc_range[dim] > low_valid_loc_range[dim] else np.zeros(n_examples, dtype=int)\n for dim in range(rank)]\n for i in range(0, len(rnd_loc[1])):\n rnd_loc[1][i] = (image_list[img_idx].shape[1] - example_size[1]) // 2\n\n return rnd_loc\n\n assert n_examples > 0\n\n was_singular = False\n if isinstance(image_list, np.ndarray):\n image_list = [image_list]\n was_singular = True\n\n assert all([i_s >= e_s for i_s, e_s in zip(image_list[0].shape, example_size)]), \\\n 'Image must be bigger than example shape'\n assert (image_list[0].ndim - 1 == len(example_size) or image_list[0].ndim == len(example_size)), \\\n 'Example size doesnt fit image size'\n\n for i in image_list:\n if len(image_list) > 1:\n assert (\n i.ndim - 1 == image_list[0].ndim or i.ndim == image_list[0].ndim or i.ndim + 1 == image_list[0].ndim), \\\n 'Example size doesn''t fit image size'\n # assert all([i0_s == i_s for i0_s, i_s in zip(image_list[0].shape, i.shape)]), \\\n # 'Image shapes must match'\n\n rank = len(example_size)\n\n # extract random examples from image and label\n\n\n examples = [[]] * len(image_list)\n y = [0] * n_examples\n\n for i in range(n_examples):\n rnd_loc = get_range(0)\n slicer = [slice(rnd_loc[dim][i], rnd_loc[dim][i] + example_size[dim]) for dim in range(rank)]\n y[i] = loc[0] - rnd_loc[0][i]\n # if y[i] >=100 or y[i] <=28:\n # y[i] = 0\n # else:\n # y[i]= 1\n for j in range(len(image_list)):\n ex_img = image_list[j][slicer][np.newaxis]\n # concatenate and return the examples\n examples[j] = np.concatenate((examples[j], ex_img), axis=0) if (len(examples[j]) != 0) else ex_img\n\n if was_singular:\n return examples[0], y\n return examples, y\n\n\n\n\ndef pad_image_to_size(image, img_size=[64,64,64],loc=[2,2,2], **kwargs):\n \"\"\"Image resizing\n\n Resizes image by cropping or padding dimension to fit specified size.\n\n Note: adapted from https://github.com/DLTK/DLTK\n Parameters\n ----------\n image : np.ndarray\n image to be resized\n img_size : list or tuple\n new image size\n kwargs\n additional arguments to be passed to np.pad\n\n Returns\n -------\n np.ndarray\n resized image\n\n \"\"\"\n\n assert isinstance(image, (np.ndarray, np.generic))\n assert (image.ndim - 1 == len(img_size) or image.ndim == len(img_size)), \\\n 'Example size doesnt fit image size'\n\n # find image dimensionality\n rank = len(img_size)\n\n # create placeholders for new shape\n from_indices = [[0, image.shape[dim]] for dim in range(rank)]\n to_padding = [[0, 0] for dim in range(rank)]\n\n slicer = [slice(None)] * rank\n\n for i in range(rank):\n # for each dimensions find whether it is supposed to be cropped or padded\n if image.shape[i] < img_size[i]:\n if loc[i] == 0:\n to_padding[i][0] = (img_size[i] - image.shape[i])\n to_padding[i][1] = 0\n elif loc[i] == 1:\n to_padding[i][0] = 0\n to_padding[i][1] = (img_size[i] - image.shape[i])\n else:\n to_padding[i][0] = (img_size[i] - image.shape[i]) // 2\n to_padding[i][1] = img_size[i] - image.shape[i] - to_padding[i][0]\n else:\n to_padding[i][0] = 0\n to_padding[i][1] = 0\n\n\n\n # pad the cropped image to extend the missing dimension\n return np.pad(image, to_padding, **kwargs)\n"
]
| [
[
"numpy.max",
"numpy.concatenate",
"numpy.pad",
"numpy.zeros",
"numpy.min",
"numpy.stack",
"numpy.random.randint",
"numpy.clip",
"numpy.dstack"
]
]
|
lucasondel/amdtk | [
"c5382787255b91e6c66ddab2c9ec2362316f0930"
]
| [
"amdtk/densities/normal_gamma.py"
]
| [
"\n\"\"\"\nImplementation of a Normal-Gamma density prior.\n\nCopyright (C) 2017, Lucas Ondel\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use, copy,\nmodify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n\"\"\"\n\n# NOTE\n# ----\n# phi(mean, precision) = [\n# - precision / 2\n# precision * mean\n# -precision * (mean ** 2) / 2\n# (1/2) * ln precision\n# ]\n#\n# natural_params(kappa, mean, rate, scale) = [\n# kappa * (mean ** 2) + 2 * scale\n# kappa * mean\n# kappa\n# 2 * (rate - 1/2)\n# ]\n#\n# log_partition(kappa, mean, rate, scale) =\n# gammaln(rate) - rate * log(scale) - .5 * log(kappa)\n#\n# log_partition(np1, np2, np3, np4) =\n# gammaln(.5 * (np4 + 1)) - .5 * (np4 + 1) log(.5 *\n# (np1 - (np2 ** 2) / np3)) - .5 * log(np3)\n#\n\n\nimport theano\nimport theano.tensor as T\nimport numpy as np\nfrom .efd import EFDPrior\n\n\ndef _log_partition_symfunc():\n natural_params = T.vector()\n size = natural_params.shape[0] // 4\n np1, np2, np3, np4 = T.split(natural_params, 4 * [size], 4)\n\n log_Z = T.sum(T.gammaln(.5 * (np4 + 1)))\n log_Z += T.sum(- .5 * (np4 + 1) * T.log(.5 * (np1 - (np2 ** 2) / np3)))\n log_Z += T.sum(-.5 * T.log(np3))\n\n func = theano.function([natural_params], log_Z)\n grad_func = theano.function([natural_params],\n T.grad(T.sum(log_Z), natural_params))\n return func, grad_func\n\n_lp_func, _grad_lp_func = _log_partition_symfunc()\n\n\nclass NormalGamma(EFDPrior):\n \"\"\"Normal-Gamma density prior.\"\"\"\n\n @staticmethod\n def _log_partition_func(natural_params):\n return _lp_func(natural_params)\n\n @staticmethod\n def _grad_log_partition_func(natural_params):\n return _grad_lp_func(natural_params)\n\n def __init__(self, mean, kappa, rate, scale):\n \"\"\"Initialize a Normal-Gamma Distribution.\n\n Parameters\n ----------\n mean : numpy.ndarray\n Mean of the Normal density.\n kappa : float\n Scale of the precision Normal density.\n rate : float\n Rate parameter of the Gamma density.\n scale : float\n scale parameter of the Gamma density.\n\n \"\"\"\n EFDPrior.__init__(self)\n self.natural_params = np.hstack([\n np.asarray(kappa * (mean ** 2) + 2 * scale, dtype=float),\n np.asarray(kappa * mean, dtype=float),\n np.asarray(kappa, dtype=float),\n np.asarray(2 * (rate - 1./2), dtype=float)\n ])\n\n"
]
| [
[
"numpy.asarray"
]
]
|
bo1929/pamogk | [
"fdd1a5b3dcd43b91ce9aa9989c7815b71f13e710"
]
| [
"visualizations/new_kernel.py"
]
| [
"from pamogk.kernels.new_kernel import *\nimport matplotlib.pyplot as plt\n\nconf_def = 0.1\npatient_map = read_data()\n\n# Patient ve mutated genleri yaziyor\npatients = preprocess_patient_data(patient_map)\n\n# Pathwayler geldi graphlar ile\nall_pw_map = read_pathways()\n\n# list of neigbor of genes for all pathways\nneighbor_mappings, id_mapper = get_neighbors_for_all_pathways(all_pw_map, conf_def)\n\n#\nkernels = calc_kernel_from_pathways(neighbor_mappings, patients, id_mapper)\nfor i in range(1):\n print(isPSD(kernels[i]))\n plt.imshow(kernels[i], cmap='hot')\n plt.savefig(f'{i}.png')\n"
]
| [
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.imshow"
]
]
|
jg1141/DRLND-Project2 | [
"e72a054338df992883610819100e6077a1d313d1"
]
| [
"ddpg_agent.py"
]
| [
"import numpy as np\nimport random\nimport copy\nfrom collections import namedtuple, deque\n\nfrom model import Actor, Critic\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBATCH_SIZE = 128 # minibatch size\nBUFFER_SIZE = int(1e5) # replay buffer size\nGAMMA = 0.99 # discount factor\nLR_ACTOR = 1e-4 # learning rate of the actor \nLR_CRITIC = 1e-3 # learning rate of the critic\nTAU = 1e-3 # for soft update of target parameters\nWEIGHT_DECAY = 0 # L2 weight decay\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Agents():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n \n def __init__(self, state_size, action_size, num_agents, random_seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n num_agents (int): number of agents\n random_seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.num_agents = num_agents\n self.seed = random.seed(random_seed)\n\n # Actor Network (w/ Target Network)\n self.actor_local = Actor(state_size, action_size, random_seed).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n # Critic Network (w/ Target Network)\n self.critic_local = Critic(state_size, action_size, random_seed).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY)\n\n # Noise process\n self.noise = OUNoise((num_agents, action_size), random_seed)\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed)\n \n def step(self, state, action, reward, next_state, done):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n # Save experience / reward\n for i in range(self.num_agents):\n self.memory.add(state[i,:], action[i,:], reward[i], next_state[i,:], done[i])\n\n # Learn, if enough samples are available in memory\n if len(self.memory) > BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, states, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n states = torch.from_numpy(states).float().to(device)\n actions = np.zeros((self.num_agents, self.action_size))\n self.actor_local.eval()\n with torch.no_grad():\n for agent_num, state in enumerate(states):\n action = self.actor_local(state).cpu().data.numpy()\n actions[agent_num, :] = action\n self.actor_local.train()\n if add_noise:\n actions += self.noise.sample()\n return np.clip(actions, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n # Compute critic loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n self.soft_update(self.critic_local, self.critic_target, TAU)\n self.soft_update(self.actor_local, self.actor_target, TAU) \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n \nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0.0, theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.size = size\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.random.standard_normal(self.size)\n self.state = x + dx\n return self.state\n \n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n Params\n ======\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) # internal memory (deque)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)\n"
]
| [
[
"numpy.random.standard_normal",
"numpy.zeros",
"torch.no_grad",
"numpy.ones",
"torch.from_numpy",
"torch.nn.functional.mse_loss",
"torch.cuda.is_available",
"numpy.clip",
"numpy.vstack"
]
]
|
zswdian/BinarizedSNPS | [
"d1a1a1f7eea74ee8f9c2233ae94f7fa079dc11d5"
]
| [
"ImageNet/Models/resnet_snp.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(\n in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = self.conv1(self.relu(self.bn1(x)))\n out = self.conv2(self.relu(self.bn2(out)))\n out += self.shortcut(x)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,\n stride=stride, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion *\n planes, kernel_size=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = self.conv1(self.relu(self.bn1(x)))\n out = self.conv2(self.relu(self.bn2(out)))\n out = self.conv3(self.relu(self.bn3(out)))\n out += self.shortcut(x)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(ResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.bn1 = nn.BatchNorm2d(512)\n self.relu = nn.ReLU(inplace=True)\n self.linear = nn.Linear(512*block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = self.bn1(out)\n out = self.relu(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef ResNet18():\n return ResNet(BasicBlock, [2, 2, 2, 2])\n\n\ndef ResNet34():\n return ResNet(BasicBlock, [3, 4, 6, 3])\n\n\ndef ResNet50():\n return ResNet(Bottleneck, [3, 4, 6, 3])\n\n\ndef ResNet101():\n return ResNet(Bottleneck, [3, 4, 23, 3])\n\n\ndef ResNet152():\n return ResNet(Bottleneck, [3, 8, 36, 3])\n\n\ndef test():\n net = ResNet18()\n y = net(torch.randn(1, 3, 32, 32))\n print(y.size())\n\n# test()"
]
| [
[
"torch.nn.Linear",
"torch.nn.functional.avg_pool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.randn"
]
]
|
adelavega/pybids | [
"d481dda98c7e3b38b4a812124daaf0d450d64e19"
]
| [
"bids/variables/variables.py"
]
| [
"import numpy as np\nimport pandas as pd\nimport math\nfrom copy import deepcopy\nfrom abc import abstractmethod, ABCMeta\nfrom scipy.interpolate import interp1d\nfrom bids.utils import listify\nfrom itertools import chain\nfrom six import add_metaclass\nfrom bids.utils import matches_entities\n\n\n@add_metaclass(ABCMeta)\nclass BIDSVariable(object):\n ''' Base representation of a column in a BIDS project. '''\n\n # Columns that define special properties (e.g., onset, duration). These\n # will be stored separately from the main data object, and are accessible\n # as properties on the BIDSVariable instance.\n _property_columns = set()\n\n def __init__(self, name, values, source):\n self.name = name\n self.values = values\n self.source = source\n self._index_entities()\n\n def clone(self, data=None, **kwargs):\n ''' Clone (deep copy) the current column, optionally replacing its\n data and/or any other attributes.\n\n Args:\n data (DataFrame, ndarray): Optional new data to substitute into\n the cloned column. Must have same dimensionality as the\n original.\n kwargs (dict): Optional keyword arguments containing new attribute\n values to set in the copy. E.g., passing `name='my_name'`\n would set the `.name` attribute on the cloned instance to the\n passed value.\n '''\n result = deepcopy(self)\n if data is not None:\n if data.shape != self.values.shape:\n raise ValueError(\"Replacement data has shape %s; must have \"\n \"same shape as existing data %s.\" %\n (data.shape, self.values.shape))\n result.values = pd.DataFrame(data)\n\n if kwargs:\n for k, v in kwargs.items():\n setattr(result, k, v)\n\n # Need to update name on Series as well\n # result.values.name = kwargs.get('name', self.name)\n return result\n\n def filter(self, filters=None, query=None, strict=False, inplace=False):\n ''' Returns a copy of the current Variable with only rows that match\n the filters retained.\n\n Args:\n filters (dict): Dictionary of filters to apply. Keys can be either\n 'amplitude' or any named entity. Values must be single values\n or lists.\n query (str): Optional query string to pass to df.query(). Will not\n be validated in any way, so must have valid column names. Takes\n precedence over filters in the event that both are passed.\n strict (bool): By default, keys in 'filters' that cannot be found\n in the Variable will be silently ignored. If strict=True, None\n will be returned in such cases.\n inplace (bool): If True, filtering is performed in place. If False,\n a filtered copy of the Variable is returned.\n\n Returns:\n A BIDSVariable, or None if no rows are left after filtering.\n '''\n\n if filters is None and query is None:\n raise ValueError(\"Either the 'filters' or the 'query' argument \"\n \"must be provided!\")\n\n if filters is not None and query is None:\n query = []\n for name, val in filters.items():\n if name != 'amplitude' and name not in self.index.columns:\n if strict:\n return None\n continue\n oper = 'in' if isinstance(val, (list, tuple)) else '=='\n q = '{name} {oper} {val}'.format(name=name, oper=oper,\n val=repr(val))\n query.append(q)\n query = ' and '.join(query)\n\n var = self if inplace else self.clone()\n\n if query:\n inds = self.to_df().query(query).index\n\n var.values = var.values.loc[inds]\n var.index = var.index.loc[inds]\n if hasattr(self, '_build_entity_index'):\n var._build_entity_index()\n\n if not inplace:\n return var\n\n @classmethod\n def merge(cls, variables, name=None, **kwargs):\n ''' Merge/concatenate a list of variables along the row axis.\n\n Args:\n variables (list): A list of Variables to merge.\n name (str): Optional name to assign to the output Variable. By\n default, uses the same name as the input variables.\n kwargs: Optional keyword arguments to pass onto the class-specific\n merge() call. See merge_variables docstring for details.\n\n Returns:\n A single BIDSVariable of the same class as the input variables.\n\n Notes: see merge_variables docstring for additional details.\n '''\n\n variables = listify(variables)\n if len(variables) == 1:\n return variables[0]\n\n var_names = set([v.name for v in variables])\n if len(var_names) > 1:\n raise ValueError(\"Columns with different names cannot be merged. \"\n \"Column names provided: %s\" % var_names)\n\n if name is None:\n name = variables[0].name\n\n return cls._merge(variables, name, **kwargs)\n\n @classmethod\n @abstractmethod\n def _merge(cls, variables, name, **kwargs):\n pass\n\n def get_grouper(self, groupby='run'):\n ''' Return a pandas Grouper object suitable for use in groupby calls.\n Args:\n groupby (str, list): Name(s) of column(s) defining the grouper\n object. Anything that would be valid inside a .groupby() call\n on a pandas structure.\n Returns:\n A pandas Grouper object constructed from the specified columns\n of the current index.\n '''\n return pd.core.groupby._get_grouper(self.index, groupby)[0]\n\n def apply(self, func, groupby='run', *args, **kwargs):\n ''' Applies the passed function to the groups defined by the groupby\n argument. Works identically to the standard pandas df.groupby() call.\n Args:\n func (callable): The function to apply to each group.\n groupby (str, list): Name(s) of column(s) defining the grouping.\n args, kwargs: Optional positional and keyword arguments to pass\n onto the function call.\n '''\n grouper = self.get_grouper(groupby)\n return self.values.groupby(grouper).apply(func, *args, **kwargs)\n\n def to_df(self, condition=True, entities=True, **kwargs):\n ''' Convert to a DataFrame, with columns for name and entities.\n Args:\n condition (bool): If True, adds a column for condition name, and\n names the amplitude column 'amplitude'. If False, returns just\n onset, duration, and amplitude, and gives the amplitude column\n the current column name.\n entities (bool): If True, adds extra columns for all entities.\n '''\n amp = 'amplitude' if condition else self.name\n data = pd.DataFrame({amp: self.values.values.ravel()})\n\n for sc in self._property_columns:\n data[sc] = getattr(self, sc)\n\n if condition:\n data['condition'] = self.name\n\n if entities:\n ent_data = self.index.reset_index(drop=True)\n data = pd.concat([data, ent_data], axis=1)\n\n return data.reset_index(drop=True)\n\n def matches_entities(self, entities, strict=False):\n ''' Checks whether current Variable's entities match the input. '''\n return matches_entities(self, entities, strict)\n\n def _index_entities(self):\n ''' Returns a dict of entities for the current Variable.\n\n Note: Only entity key/value pairs common to all rows in the Variable\n are returned. E.g., if a Variable contains events extracted from\n runs 1, 2 and 3 from subject '01', the returned dict will be\n {'subject': '01'}; the runs will be excluded as they vary across\n the Variable contents.\n '''\n constant = self.index.apply(lambda x: x.nunique() == 1)\n if constant.empty:\n self.entities = {}\n else:\n keep = self.index.columns[constant]\n self.entities = {k: self.index[k].iloc[0] for k in keep}\n\n\nclass SimpleVariable(BIDSVariable):\n ''' Represents a simple design matrix column that has no timing\n information.\n\n Args:\n name (str): Name of the column.\n data (DataFrame): A pandas DataFrame minimally containing a column\n named 'amplitude' as well as any identifying entities.\n source (str): The type of BIDS variable file the data were extracted\n from. Must be one of: 'events', 'physio', 'stim', 'confounds',\n 'scans', 'sessions', 'participants', or 'beh'.\n kwargs: Optional keyword arguments passed onto superclass.\n '''\n\n _entity_columns = {'condition', 'amplitude'}\n\n def __init__(self, name, data, source, **kwargs):\n\n ent_cols = list(set(data.columns) - self._entity_columns)\n self.index = data.loc[:, ent_cols]\n\n values = data['amplitude'].reset_index(drop=True)\n values.name = name\n\n super(SimpleVariable, self).__init__(name, values, source)\n\n def split(self, grouper):\n ''' Split the current SparseRunVariable into multiple columns.\n\n Args:\n grouper (iterable): list to groupby, where each unique value will\n be taken as the name of the resulting column.\n\n Returns:\n A list of SparseRunVariables, one per unique value in the\n grouper.\n '''\n data = self.to_df(condition=True, entities=True)\n data = data.drop('condition', axis=1)\n\n subsets = []\n for i, (name, g) in enumerate(data.groupby(grouper)):\n name = '%s.%s' % (self.name, name)\n args = [name, g, self.source]\n if hasattr(self, 'run_info'):\n args.append(self.run_info)\n col = self.__class__(*args)\n subsets.append(col)\n return subsets\n\n @classmethod\n def _merge(cls, variables, name, **kwargs):\n dfs = [v.to_df() for v in variables]\n data = pd.concat(dfs, axis=0).reset_index(drop=True)\n data = data.rename(columns={name: 'amplitude'})\n return cls(name, data, source=variables[0].source, **kwargs)\n\n\nclass SparseRunVariable(SimpleVariable):\n ''' A sparse representation of a single column of events.\n\n Args:\n name (str): Name of the column.\n data (DataFrame): A pandas DataFrame minimally containing the columns\n 'onset', 'duration', and 'amplitude'.\n run_info (list): A list of RunInfo objects carrying information about\n all runs represented in the Variable.\n source (str): The type of BIDS variable file the data were extracted\n from. Must be one of: 'events', 'physio', 'stim', 'confounds',\n 'scans', 'sessions', 'participants', or 'beh'.\n kwargs: Optional keyword arguments passed onto superclass.\n '''\n\n _property_columns = {'onset', 'duration'}\n\n def __init__(self, name, data, run_info, source, **kwargs):\n if hasattr(run_info, 'duration'):\n run_info = [run_info]\n self.run_info = run_info\n for sc in self._property_columns:\n setattr(self, sc, data.pop(sc).values)\n super(SparseRunVariable, self).__init__(name, data, source, **kwargs)\n\n def get_duration(self):\n ''' Return the total duration of the Variable's run(s). '''\n return sum([r.duration for r in self.run_info])\n\n def to_dense(self, sampling_rate):\n ''' Convert the current sparse column to a dense representation.\n Returns: A DenseRunVariable.\n\n Args:\n sampling_rate (int, str): Sampling rate (in Hz) to use when\n constructing the DenseRunVariable.\n\n Returns:\n A DenseRunVariable.\n\n '''\n duration = int(math.ceil(sampling_rate * self.get_duration()))\n ts = np.zeros(duration, dtype=self.values.dtype)\n\n onsets = np.round(self.onset * sampling_rate).astype(int)\n durations = np.round(self.duration * sampling_rate).astype(int)\n\n run_i, start, last_ind = 0, 0, 0\n for i, val in enumerate(self.values.values):\n if onsets[i] < last_ind:\n start += self.run_info[run_i].duration * sampling_rate\n run_i += 1\n _onset = start + onsets[i]\n _offset = _onset + durations[i]\n ts[_onset:_offset] = val\n last_ind = onsets[i]\n\n run_info = list(self.run_info)\n return DenseRunVariable(self.name, ts, run_info, self.source,\n sampling_rate)\n\n @classmethod\n def _merge(cls, variables, name, **kwargs):\n run_info = list(chain(*[v.run_info for v in variables]))\n return super(SparseRunVariable, cls)._merge(variables, name,\n run_info=run_info,\n **kwargs)\n\n\nclass DenseRunVariable(BIDSVariable):\n ''' A dense representation of a single column.\n\n Parameters\n ----------\n name : :obj:`str`\n The name of the column.\n values : :obj:`numpy.ndarray`\n The values/amplitudes to store.\n run_info : :obj:`list`\n A list of RunInfo objects carrying information about all runs\n represented in the Variable.\n source : {'events', 'physio', 'stim', 'confounds', 'scans', 'sessions', 'participants', 'beh'}\n The type of BIDS variable file the data were extracted from.\n sampling_rate : :obj:`float`\n Optional sampling rate (in Hz) to use. Must match the sampling rate used\n to generate the values. If None, the collection's sampling rate will be used.\n '''\n\n def __init__(self, name, values, run_info, source, sampling_rate):\n\n values = pd.DataFrame(values)\n\n if hasattr(run_info, 'duration'):\n run_info = [run_info]\n self.run_info = run_info\n self.sampling_rate = sampling_rate\n self.index = self._build_entity_index(run_info, sampling_rate)\n\n super(DenseRunVariable, self).__init__(name, values, source)\n\n def split(self, grouper):\n '''Split the current DenseRunVariable into multiple columns.\n\n Parameters\n ----------\n grouper : :obj:`pandas.DataFrame`\n Binary DF specifying the design matrix to use for splitting. Number\n of rows must match current ``DenseRunVariable``; a new ``DenseRunVariable``\n will be generated for each column in the grouper.\n\n Returns\n -------\n A list of DenseRunVariables, one per unique value in the grouper.\n '''\n values = grouper.values * self.values.values\n df = pd.DataFrame(values, columns=grouper.columns)\n return [DenseRunVariable('%s.%s' % (self.name, name), df[name].values,\n self.run_info, self.source,\n self.sampling_rate)\n for i, name in enumerate(df.columns)]\n\n def _build_entity_index(self, run_info, sampling_rate):\n ''' Build the entity index from run information. '''\n\n index = []\n sr = int(round(1000. / sampling_rate))\n _timestamps = []\n for run in run_info:\n reps = int(math.ceil(run.duration * sampling_rate))\n ent_vals = list(run.entities.values())\n data = np.broadcast_to(ent_vals, (reps, len(ent_vals)))\n df = pd.DataFrame(data, columns=list(run.entities.keys()))\n ts = pd.date_range(0, periods=len(df), freq='%sms' % sr)\n _timestamps.append(ts.to_series())\n index.append(df)\n self.timestamps = pd.concat(_timestamps, axis=0)\n return pd.concat(index, axis=0).reset_index(drop=True)\n\n def resample(self, sampling_rate, inplace=False, kind='linear'):\n '''Resample the Variable to the specified sampling rate.\n\n Parameters\n ----------\n sampling_rate : :obj:`int`, :obj:`float`\n Target sampling rate (in Hz).\n inplace : :obj:`bool`, optional\n If True, performs resampling in-place. If False, returns a resampled\n copy of the current Variable. Default is False.\n kind : {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'}\n Argument to pass to :obj:`scipy.interpolate.interp1d`; indicates\n the kind of interpolation approach to use. See interp1d docs for\n valid values. Default is 'linear'.\n '''\n if not inplace:\n var = self.clone()\n var.resample(sampling_rate, True, kind)\n return var\n\n if sampling_rate == self.sampling_rate:\n return\n\n old_sr = self.sampling_rate\n n = len(self.index)\n\n self.index = self._build_entity_index(self.run_info, sampling_rate)\n\n x = np.arange(n)\n num = int(np.ceil(n * sampling_rate / old_sr))\n\n f = interp1d(x, self.values.values.ravel(), kind=kind)\n x_new = np.linspace(0, n - 1, num=num)\n self.values = pd.DataFrame(f(x_new))\n\n self.sampling_rate = sampling_rate\n\n def to_df(self, condition=True, entities=True, timing=True):\n '''Convert to a DataFrame, with columns for name and entities.\n\n Parameters\n ----------\n condition : :obj:`bool`\n If True, adds a column for condition name, and names the amplitude\n column 'amplitude'. If False, returns just onset, duration, and\n amplitude, and gives the amplitude column the current column name.\n entities : :obj:`bool`\n If True, adds extra columns for all entities.\n timing : :obj:`bool`\n If True, includes onset and duration columns (even though events are\n sampled uniformly). If False, omits them.\n '''\n df = super(DenseRunVariable, self).to_df(condition, entities)\n\n if timing:\n df['onset'] = self.timestamps.values.astype(float) / 1e+9\n df['duration'] = 1. / self.sampling_rate\n\n return df\n\n @classmethod\n def _merge(cls, variables, name, sampling_rate=None, **kwargs):\n\n if not isinstance(sampling_rate, int):\n rates = set([v.sampling_rate for v in variables])\n if len(rates) == 1:\n sampling_rate = list(rates)[0]\n else:\n if sampling_rate is 'auto':\n sampling_rate = max(rates)\n else:\n msg = (\"Cannot merge DenseRunVariables (%s) with different\"\n \" sampling rates (%s). Either specify an integer \"\n \"sampling rate to use for all variables, or set \"\n \"sampling_rate='auto' to use the highest sampling \"\n \"rate found.\" % (name, rates))\n raise ValueError(msg)\n\n variables = [v.resample(sampling_rate) for v in variables]\n values = pd.concat([v.values for v in variables], axis=0)\n run_info = list(chain(*[v.run_info for v in variables]))\n source = variables[0].source\n return DenseRunVariable(name, values, run_info, source, sampling_rate)\n\n\ndef merge_variables(variables, name=None, **kwargs):\n '''Merge/concatenate a list of variables along the row axis.\n\n Parameters\n ----------\n variables : :obj:`list`\n A list of Variables to merge.\n name : :obj:`str`\n Optional name to assign to the output Variable. By default, uses the\n same name as the input variables.\n kwargs\n Optional keyword arguments to pass onto the class-specific merge() call.\n Possible args:\n - sampling_rate (int, str): The sampling rate to use if resampling\n of DenseRunVariables is necessary for harmonization. If 'auto',\n the highest sampling rate found will be used. This argument is\n only used when passing DenseRunVariables in the variables list.\n\n Returns\n -------\n A single BIDSVariable of the same class as the input variables.\n\n Notes\n -----\n - Currently, this function only support homogenously-typed lists. In\n future, it may be extended to support implicit conversion.\n - Variables in the list must all share the same name (i.e., it is not\n possible to merge two different variables into a single variable.)\n '''\n\n classes = set([v.__class__ for v in variables])\n if len(classes) > 1:\n raise ValueError(\"Variables of different classes cannot be merged. \"\n \"Variables passed are of classes: %s\" % classes)\n\n sources = set([v.source for v in variables])\n if len(sources) > 1:\n raise ValueError(\"Variables extracted from different types of files \"\n \"cannot be merged. Sources found: %s\" % sources)\n\n return list(classes)[0].merge(variables, **kwargs)\n"
]
| [
[
"numpy.ceil",
"numpy.zeros",
"numpy.round",
"pandas.DataFrame",
"numpy.arange",
"pandas.core.groupby._get_grouper",
"pandas.concat",
"numpy.linspace"
]
]
|
tmiv/lucid | [
"0dd070b4da10a9199369c0c565f62848283b4bdb"
]
| [
"lucid/misc/io/showing.py"
]
| [
"# Copyright 2018 The Lucid Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Methods for displaying images from Numpy arrays.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom io import BytesIO\nimport base64\nimport logging\nimport numpy as np\nimport IPython.display\nfrom string import Template\nimport tensorflow as tf\n\nfrom lucid.misc.io.serialize_array import serialize_array, array_to_jsbuffer\nfrom lucid.misc.io.collapse_channels import collapse_channels\n\n\n# create logger with module name, e.g. lucid.misc.io.showing\nlog = logging.getLogger(__name__)\n\n\ndef _display_html(html_str):\n IPython.display.display(IPython.display.HTML(html_str))\n\n\ndef _image_url(array, fmt='png', mode=\"data\", quality=90, domain=None):\n \"\"\"Create a data URL representing an image from a PIL.Image.\n\n Args:\n image: a numpy array\n mode: presently only supports \"data\" for data URL\n\n Returns:\n URL representing image\n \"\"\"\n supported_modes = (\"data\")\n if mode not in supported_modes:\n message = \"Unsupported mode '%s', should be one of '%s'.\"\n raise ValueError(message, mode, supported_modes)\n\n image_data = serialize_array(array, fmt=fmt, quality=quality, domain=domain)\n base64_byte_string = base64.b64encode(image_data).decode('ascii')\n return \"data:image/\" + fmt.upper() + \";base64,\" + base64_byte_string\n\n\n# public functions\n\ndef _image_html(array, w=None, domain=None, fmt='png'):\n url = _image_url(array, domain=domain, fmt=fmt)\n style = \"image-rendering: pixelated;\"\n if w is not None:\n style += \"width: {w}px;\".format(w=w)\n return \"\"\"<img src=\"{url}\" style=\"{style}\">\"\"\".format(**locals())\n\ndef image(array, domain=None, w=None, format='png', **kwargs):\n \"\"\"Display an image.\n\n Args:\n array: NumPy array representing the image\n fmt: Image format e.g. png, jpeg\n domain: Domain of pixel values, inferred from min & max values if None\n w: width of output image, scaled using nearest neighbor interpolation.\n size unchanged if None\n \"\"\"\n\n _display_html(\n _image_html(array, w=w, domain=domain, fmt=format)\n )\n\n\ndef images(arrays, labels=None, domain=None, w=None):\n \"\"\"Display a list of images with optional labels.\n\n Args:\n arrays: A list of NumPy arrays representing images\n labels: A list of strings to label each image.\n Defaults to show index if None\n domain: Domain of pixel values, inferred from min & max values if None\n w: width of output image, scaled using nearest neighbor interpolation.\n size unchanged if None\n \"\"\"\n\n s = '<div style=\"display: flex; flex-direction: row;\">'\n for i, array in enumerate(arrays):\n label = labels[i] if labels is not None else i\n img_html = _image_html(array, w=w, domain=domain)\n s += \"\"\"<div style=\"margin-right:10px; margin-top: 4px;\">\n {label} <br/>\n {img_html}\n </div>\"\"\".format(**locals())\n s += \"</div>\"\n _display_html(s)\n\n\ndef show(thing, domain=(0, 1), **kwargs):\n \"\"\"Display a numpy array without having to specify what it represents.\n\n This module will attempt to infer how to display your tensor based on its\n rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank\n 2 and 3 tensors as images.\n\n For tensors of rank 3 or 4, the innermost dimension is interpreted as channel.\n Depending on the size of that dimension, different types of images will be\n generated:\n\n shp[-1]\n = 1 -- Black and white image.\n = 2 -- See >4\n = 3 -- RGB image.\n = 4 -- RGBA image.\n > 4 -- Collapse into an RGB image.\n If all positive: each dimension gets an evenly spaced hue.\n If pos and neg: each dimension gets two hues\n (180 degrees apart) for positive and negative.\n\n Common optional arguments:\n\n domain: range values can be between, for displaying normal images\n None = infer domain with heuristics\n (a,b) = clip values to be between a (min) and b (max).\n\n w: width of displayed images\n None = display 1 pixel per value\n int = display n pixels per value (often used for small images)\n\n labels: if displaying multiple objects, label for each object.\n None = label with index\n [] = no labels\n [...] = label with corresponding list item\n\n \"\"\"\n def collapse_if_needed(arr):\n K = arr.shape[-1]\n if K not in [1,3,4]:\n log.debug(\"Collapsing %s channels into 3 RGB channels.\" % K)\n return collapse_channels(arr)\n else:\n return arr\n\n\n if isinstance(thing, np.ndarray):\n rank = len(thing.shape)\n\n if rank in [3,4]:\n thing = collapse_if_needed(thing)\n\n if rank == 4:\n log.debug(\"Show is assuming rank 4 tensor to be a list of images.\")\n images(thing, domain=domain, **kwargs)\n elif rank in (2, 3):\n log.debug(\"Show is assuming rank 2 or 3 tensor to be an image.\")\n image(thing, domain=domain, **kwargs)\n else:\n log.warning(\"Show only supports numpy arrays of rank 2-4. Using repr().\")\n print(repr(thing))\n elif isinstance(thing, (list, tuple)):\n log.debug(\"Show is assuming list or tuple to be a collection of images.\")\n\n if isinstance(thing[0], np.ndarray) and len(thing[0].shape) == 3:\n thing = [collapse_if_needed(t) for t in thing]\n\n images(thing, domain=domain, **kwargs)\n else:\n log.warning(\"Show only supports numpy arrays so far. Using repr().\")\n print(repr(thing))\n\n\ndef textured_mesh(mesh, texture, background='0xffffff'):\n texture_data_url = _image_url(texture, fmt='jpeg', quality=90)\n\n code = Template('''\n <input id=\"unfoldBox\" type=\"checkbox\" class=\"control\">Unfold</input>\n <input id=\"shadeBox\" type=\"checkbox\" class=\"control\" checked>Shade</input>\n\n <script src=\"https://cdn.rawgit.com/mrdoob/three.js/r89/build/three.min.js\"></script>\n <script src=\"https://cdn.rawgit.com/mrdoob/three.js/r89/examples/js/controls/OrbitControls.js\"></script>\n\n <script type=\"x-shader/x-vertex\" id=\"vertexShader\">\n uniform float viewAspect;\n uniform float unfolding_perc;\n uniform float shadeFlag;\n varying vec2 text_coord;\n varying float shading;\n void main () {\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n vec4 plane_position = vec4((uv.x*2.0-1.0)/viewAspect, (uv.y*2.0-1.0), 0, 1);\n gl_Position = mix(gl_Position, plane_position, unfolding_perc);\n\n //not normalized on purpose to simulate the rotation\n shading = 1.0;\n if (shadeFlag > 0.5) {\n vec3 light_vector = mix(normalize(cameraPosition-position), normal, unfolding_perc);\n shading = dot(normal, light_vector);\n }\n\n text_coord = uv;\n }\n </script>\n\n <script type=\"x-shader/x-fragment\" id=\"fragmentShader\">\n uniform float unfolding_perc;\n varying vec2 text_coord;\n varying float shading;\n uniform sampler2D texture;\n\n void main() {\n gl_FragColor = texture2D(texture, text_coord);\n gl_FragColor.rgb *= shading;\n }\n </script>\n\n <script>\n \"use strict\";\n\n const el = id => document.getElementById(id);\n\n const unfoldDuration = 1000.0;\n var camera, scene, renderer, controls, material;\n var unfolded = false;\n var unfoldStart = -unfoldDuration*10.0;\n\n init();\n animate(0.0);\n\n function init() {\n var width = 800, height = 600;\n\n scene = new THREE.Scene();\n\n camera = new THREE.PerspectiveCamera(42, width / height, 0.1, 100);\n camera.position.z = 3.3;\n scene.add(camera);\n\n controls = new THREE.OrbitControls( camera );\n\n var geometry = new THREE.BufferGeometry();\n geometry.addAttribute( 'position', new THREE.BufferAttribute($verts, 3 ) );\n geometry.addAttribute( 'uv', new THREE.BufferAttribute($uvs, 2) );\n geometry.setIndex(new THREE.BufferAttribute($faces, 1 ));\n geometry.computeVertexNormals();\n\n var texture = new THREE.TextureLoader().load('$tex_data_url', update);\n material = new THREE.ShaderMaterial( {\n uniforms: {\n viewAspect: {value: width/height},\n unfolding_perc: { value: 0.0 },\n shadeFlag: { value: 0.0 },\n texture: { type: 't', value: texture },\n },\n side: THREE.DoubleSide,\n vertexShader: el( 'vertexShader' ).textContent,\n fragmentShader: el( 'fragmentShader' ).textContent\n });\n\n var mesh = new THREE.Mesh(geometry, material);\n scene.add(mesh);\n scene.background = new THREE.Color( $background );\n\n renderer = new THREE.WebGLRenderer({antialias: true});\n renderer.setSize(width, height);\n document.body.appendChild(renderer.domElement);\n\n // render on change only\n controls.addEventListener('change', function() {\n // fold mesh back if user wants to interact\n el('unfoldBox').checked = false;\n update();\n });\n document.querySelectorAll('.control').forEach(e=>{\n e.addEventListener('change', update);\n });\n }\n\n function update() {\n requestAnimationFrame(animate);\n }\n\n function ease(x) {\n x = Math.min(Math.max(x, 0.0), 1.0);\n return x*x*(3.0 - 2.0*x);\n }\n\n function animate(time) {\n var unfoldFlag = el('unfoldBox').checked;\n if (unfolded != unfoldFlag) {\n unfolded = unfoldFlag;\n unfoldStart = time - Math.max(unfoldStart+unfoldDuration-time, 0.0);\n }\n var unfoldTime = (time-unfoldStart) / unfoldDuration;\n if (unfoldTime < 1.0) {\n update();\n }\n var unfoldVal = ease(unfoldTime);\n unfoldVal = unfolded ? unfoldVal : 1.0 - unfoldVal;\n material.uniforms.unfolding_perc.value = unfoldVal;\n\n material.uniforms.shadeFlag.value = el('shadeBox').checked ? 1.0 : 0.0;\n controls.update();\n renderer.render(scene, camera);\n }\n </script>\n ''').substitute(\n verts = array_to_jsbuffer(mesh['position'].ravel()),\n uvs = array_to_jsbuffer(mesh['uv'].ravel()),\n faces = array_to_jsbuffer(np.uint32(mesh['face'].ravel())),\n tex_data_url = texture_data_url,\n background = background,\n )\n _display_html(code)\n\n\ndef _strip_consts(graph_def, max_const_size=32):\n \"\"\"Strip large constant values from graph_def.\n\n This is mostly a utility function for graph(), and also originates here:\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb\n \"\"\"\n strip_def = tf.GraphDef()\n for n0 in graph_def.node:\n n = strip_def.node.add()\n n.MergeFrom(n0)\n if n.op == 'Const':\n tensor = n.attr['value'].tensor\n size = len(tensor.tensor_content)\n if size > max_const_size:\n tensor.tensor_content = tf.compat.as_bytes(\"<stripped %d bytes>\"%size)\n return strip_def\n\n\ndef graph(graph_def, max_const_size=32):\n \"\"\"Visualize a TensorFlow graph.\n\n This function was originally found in this notebook (also Apache licensed):\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb\n \"\"\"\n if hasattr(graph_def, 'as_graph_def'):\n graph_def = graph_def.as_graph_def()\n strip_def = _strip_consts(graph_def, max_const_size=max_const_size)\n code = \"\"\"\n <script>\n function load() {{\n document.getElementById(\"{id}\").pbtxt = {data};\n }}\n </script>\n <link rel=\"import\" href=\"https://tensorboard.appspot.com/tf-graph-basic.build.html\" onload=load()>\n <div style=\"height:600px\">\n <tf-graph-basic id=\"{id}\"></tf-graph-basic>\n </div>\n \"\"\".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))\n\n iframe = \"\"\"\n <iframe seamless style=\"width:100%; height:620px; border: none;\" srcdoc=\"{}\"></iframe>\n \"\"\".format(code.replace('\"', '"'))\n _display_html(iframe)\n"
]
| [
[
"tensorflow.compat.as_bytes",
"tensorflow.GraphDef",
"numpy.random.rand"
]
]
|
kwanUm/pytorch-lightning | [
"12edc3099cd0d529b4ff0553f5c7cbe9f47dfdfb"
]
| [
"pytorch_lightning/trainer/evaluation_loop.py"
]
| [
"\"\"\"\n# Validation loop\n\nThe lightning validation loop handles everything except the actual computations of your model.\nTo decide what will happen in your validation loop, define the `validation_step` function.\nBelow are all the things lightning automates for you in the validation loop.\n\n.. note:: Lightning will run 5 steps of validation in the beginning of training as a sanity\n check so you don't have to wait until a full epoch to catch possible validation issues.\n\nCheck validation every n epochs\n-------------------------------\n\nIf you have a small dataset you might want to check validation every n epochs\n\n.. code-block:: python\n\n # DEFAULT\n trainer = Trainer(check_val_every_n_epoch=1)\n\nSet how much of the validation set to check\n-------------------------------------------\n\nIf you don't want to check 100% of the validation set (for debugging or if it's huge), set this flag\n\nval_percent_check will be overwritten by overfit_pct if `overfit_pct > 0`\n\n.. code-block:: python\n\n # DEFAULT\n trainer = Trainer(val_percent_check=1.0)\n\n # check 10% only\n trainer = Trainer(val_percent_check=0.1)\n\nSet how much of the test set to check\n-------------------------------------\n\nIf you don't want to check 100% of the test set (for debugging or if it's huge), set this flag\n\ntest_percent_check will be overwritten by overfit_pct if `overfit_pct > 0`\n\n.. code-block:: python\n\n # DEFAULT\n trainer = Trainer(test_percent_check=1.0)\n\n # check 10% only\n trainer = Trainer(test_percent_check=0.1)\n\nSet validation check frequency within 1 training epoch\n------------------------------------------------------\n\nFor large datasets it's often desirable to check validation multiple times within a training loop.\n Pass in a float to check that often within 1 training epoch.\n Pass in an int k to check every k training batches. Must use an int if using an IterableDataset.\n\n.. code-block:: python\n\n # DEFAULT\n trainer = Trainer(val_check_interval=0.95)\n\n # check every .25 of an epoch\n trainer = Trainer(val_check_interval=0.25)\n\n # check every 100 train batches (ie: for IterableDatasets or fixed frequency)\n trainer = Trainer(val_check_interval=100)\n\n\nSet the number of validation sanity steps\n-----------------------------------------\n\nLightning runs a few steps of validation in the beginning of training.\n This avoids crashing in the validation loop sometime deep into a lengthy training loop.\n\n.. code-block:: python\n\n # DEFAULT\n trainer = Trainer(num_sanity_val_steps=5)\n\n\nYou can use `Trainer(num_sanity_val_steps=0)` to skip the sanity check.\n\n# Testing loop\n\nTo ensure you don't accidentally use test data to guide training decisions Lightning\n makes running the test set deliberate.\n\n**test**\n\nYou have two options to run the test set.\nFirst case is where you test right after a full training routine.\n\n.. code-block:: python\n\n # run full training\n trainer.fit(model)\n\n # run test set\n trainer.test()\n\n\nSecond case is where you load a model and run the test set\n\n.. code-block:: python\n\n model = MyLightningModule.load_from_metrics(\n weights_path='/path/to/pytorch_checkpoint.ckpt',\n tags_csv='/path/to/test_tube/experiment/version/meta_tags.csv',\n on_gpu=True,\n map_location=None\n )\n\n # init trainer with whatever options\n trainer = Trainer(...)\n\n # test (pass in the model)\n trainer.test(model)\n\nIn this second case, the options you pass to trainer will be used when running\n the test set (ie: 16-bit, dp, ddp, etc...)\n\n\"\"\"\n\nfrom abc import ABC, abstractmethod\n\nimport torch\nimport sys\nimport tqdm\n\nfrom pytorch_lightning.utilities.debugging import MisconfigurationException\n\n\nclass TrainerEvaluationLoopMixin(ABC):\n\n def __init__(self):\n # this is just a summary on variables used in this abstract class,\n # the proper values/initialisation should be done in child class\n self.test_progress_bar = None\n self.val_progress_bar = None\n self.main_progress_bar = None\n self.use_ddp = None\n self.use_dp = None\n self.use_ddp2 = None\n self.single_gpu = None\n self.data_parallel_device_ids = None\n self.model = None\n self.num_test_batches = None\n self.num_val_batches = None\n self.fast_dev_run = None\n self.process_position = None\n self.show_progress_bar = None\n self.process_output = None\n self.training_tqdm_dict = None\n self.proc_rank = None\n self.checkpoint_callback = None\n self.current_epoch = None\n self.callback_metrics = None\n self.get_test_dataloaders = None\n self.get_val_dataloaders = None\n\n @abstractmethod\n def copy_trainer_model_properties(self, model):\n # this is just empty shell for code from other class\n pass\n\n @abstractmethod\n def get_model(self):\n # this is just empty shell for code from other class\n pass\n\n @abstractmethod\n def is_overriden(self, m):\n # this is just empty shell for code from other class\n pass\n\n @abstractmethod\n def transfer_batch_to_gpu(self, batch, gpu):\n # this is just empty shell for code from other class\n pass\n\n @abstractmethod\n def add_tqdm_metrics(self, metrics):\n # this is just empty shell for code from other class\n pass\n\n @abstractmethod\n def log_metrics(self, metrics, grad_norm_dic):\n # this is just empty shell for code from other class\n pass\n\n def evaluate(self, model, dataloaders, max_batches, test=False):\n \"\"\"Run evaluation code.\n\n :param model: PT model\n :param dataloaders: list of PT dataloaders\n :param max_batches: Scalar\n :param test: boolean\n :return:\n \"\"\"\n # enable eval mode\n model.zero_grad()\n model.eval()\n\n # copy properties for forward overrides\n self.copy_trainer_model_properties(model)\n\n # disable gradients to save memory\n torch.set_grad_enabled(False)\n\n # bookkeeping\n outputs = []\n\n # run training\n for dataloader_idx, dataloader in enumerate(dataloaders):\n dl_outputs = []\n for batch_idx, batch in enumerate(dataloader):\n\n if batch is None: # pragma: no cover\n continue\n\n # stop short when on fast_dev_run (sets max_batch=1)\n if batch_idx >= max_batches:\n break\n\n # -----------------\n # RUN EVALUATION STEP\n # -----------------\n output = self.evaluation_forward(model,\n batch,\n batch_idx,\n dataloader_idx,\n test)\n\n # track outputs for collation\n dl_outputs.append(output)\n\n # batch done\n if test:\n self.test_progress_bar.update(1)\n else:\n self.val_progress_bar.update(1)\n self.main_progress_bar.update(1)\n outputs.append(dl_outputs)\n\n eval_results = {}\n\n # with a single dataloader don't pass an array\n if len(dataloaders) == 1:\n outputs = outputs[0]\n\n # give model a chance to do something with the outputs (and method defined)\n model = self.get_model()\n if test and self.is_overriden('test_end'):\n eval_results = model.test_end(outputs)\n elif self.is_overriden('validation_end'):\n eval_results = model.validation_end(outputs)\n\n # enable train mode again\n model.train()\n\n # enable gradients to save memory\n torch.set_grad_enabled(True)\n\n return eval_results\n\n def run_evaluation(self, test=False):\n # when testing make sure user defined a test step\n can_run_test_step = False\n if test:\n can_run_test_step = self.is_overriden('test_step') and self.is_overriden('test_end')\n if not can_run_test_step:\n m = '''You called .test() without defining a test step or test_end.\n Please define and try again'''\n raise MisconfigurationException(m)\n\n # validate only if model has validation_step defined\n # test only if test_step or validation_step are defined\n run_val_step = self.is_overriden('validation_step')\n\n if run_val_step or can_run_test_step:\n\n # hook\n model = self.get_model()\n model.on_pre_performance_check()\n\n # select dataloaders\n if test:\n dataloaders = self.get_test_dataloaders()\n max_batches = self.num_test_batches\n else:\n # val\n dataloaders = self.get_val_dataloaders()\n max_batches = self.num_val_batches\n\n # cap max batches to 1 when using fast_dev_run\n if self.fast_dev_run:\n max_batches = 1\n\n # init validation or test progress bar\n # main progress bar will already be closed when testing so initial position is free\n position = 2 * self.process_position + (not test)\n desc = 'Testing' if test else 'Validating'\n pbar = tqdm.tqdm(desc=desc, total=max_batches, leave=test, position=position,\n disable=not self.show_progress_bar, dynamic_ncols=True,\n unit='batch', file=sys.stdout)\n setattr(self, f'{\"test\" if test else \"val\"}_progress_bar', pbar)\n\n # run evaluation\n eval_results = self.evaluate(self.model,\n dataloaders,\n max_batches,\n test)\n _, prog_bar_metrics, log_metrics, callback_metrics, _ = self.process_output(\n eval_results)\n\n # add metrics to prog bar\n self.add_tqdm_metrics(prog_bar_metrics)\n\n # log metrics\n self.log_metrics(log_metrics, {})\n\n # track metrics for callbacks\n self.callback_metrics.update(callback_metrics)\n\n # hook\n model.on_post_performance_check()\n\n # add model specific metrics\n tqdm_metrics = self.training_tqdm_dict\n if not test:\n self.main_progress_bar.set_postfix(**tqdm_metrics)\n\n # close progress bar\n if test:\n self.test_progress_bar.close()\n else:\n self.val_progress_bar.close()\n\n # model checkpointing\n if self.proc_rank == 0 and self.checkpoint_callback is not None and not test:\n self.checkpoint_callback.on_epoch_end(epoch=self.current_epoch,\n logs=self.callback_metrics)\n\n def evaluation_forward(self, model, batch, batch_idx, dataloader_idx, test=False):\n # make dataloader_idx arg in validation_step optional\n args = [batch, batch_idx]\n\n if test and len(self.get_test_dataloaders()) > 1:\n args.append(dataloader_idx)\n\n elif not test and len(self.get_val_dataloaders()) > 1:\n args.append(dataloader_idx)\n\n # handle DP, DDP forward\n if self.use_ddp or self.use_dp or self.use_ddp2:\n output = model(*args)\n return output\n\n # single GPU\n if self.single_gpu:\n # for single GPU put inputs on gpu manually\n root_gpu = 0\n if isinstance(self.data_parallel_device_ids, list):\n root_gpu = self.data_parallel_device_ids[0]\n batch = self.transfer_batch_to_gpu(batch, root_gpu)\n args[0] = batch\n\n # CPU\n if test:\n output = model.test_step(*args)\n else:\n output = model.validation_step(*args)\n\n return output\n"
]
| [
[
"torch.set_grad_enabled"
]
]
|
UMass-ReRanker/AlbertReRanker | [
"f5eaddba2f3d82989ce602b62d98ebb8918e3a45"
]
| [
"src/select_queries.py"
]
| [
"import pandas as pd\nimport numpy\nimport os\nimport sys\ndata_dir = sys.argv[1]\ntop100 = pd.read_csv(os.path.join(data_dir, f'msmarco-doctrain-top100'),\n sep=' ', header=None, names=['qid', 'Q0', 'did', 'rank', 'score', 'run'])\nqueries_id = top100.qid.unique()\nqueries_id = numpy.array(queries_id)\nselected_queries = numpy.random.choice(queries_id, 50000, replace=False) \nwith open(os.path.join(data_dir, \"msmarco-doctrain-selected-queries.txt\"), \"w+\") as file:\n for i in range(len(selected_queries)):\n file.write(str(selected_queries[i]) + \"\\n\")\n"
]
| [
[
"numpy.array",
"numpy.random.choice"
]
]
|
durman53/tensorflow-keras-music-generation | [
"02086a2f5afdde32c2a271b60a55ffef2f393061"
]
| [
"train.py"
]
| [
"#module mido for working with midi files\r\nfrom mido import MidiFile, Message\r\nimport os\r\nimport numpy as np\r\n\r\nfrom tensorflow.keras.models import Sequential, Model\r\nfrom tensorflow.keras.layers import *\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint\r\n\r\ndata = []\r\ntarget = []\r\ntarget1 = []\r\ntarget2 = []\r\ntarget3 = []\r\n\r\n#listing music dir and open all tracks\r\nfor file in os.listdir('musics'):\r\n #reading midi files\r\n pattern = MidiFile('musics/'+file)\r\n a = []\r\n b = []\r\n c = []\r\n d = []\r\n e = []\r\n #get all messages of track\r\n for msg in pattern.tracks[2]:\r\n #if message is not meta message\r\n if msg.type == 'note_on' or msg.type == 'note_off':\r\n #reading message data and preprocessing\r\n m = msg.bytes()\r\n if m[0] == 144:m[0]=1\r\n else:m[0]=0\r\n m[1] = m[1]/127\r\n m[2] = m[2]/127\r\n m.append(msg.time/96/6)\r\n a.append(m)\r\n b.append(m[0])\r\n c.append(round(m[1]*127))\r\n d.append(round(m[2]*127))\r\n e.append(round(m[3]*6))\r\n #if len of data is 101 append it to data variable and delete 1st element\r\n if len(a) == 101:\r\n data.append(a[:-1])\r\n target.append(b[100])\r\n target1.append(c[100])\r\n target2.append(d[100])\r\n target3.append(e[100])\r\n a = a[1:]\r\n b = b[1:]\r\n c = c[1:]\r\n d = d[1:]\r\n e = e[1:]\r\n\r\n#convert lists to numpy arrays\r\ndata = np.array(data)\r\ntarget = np.array(target, dtype='float32')\r\ntarget1 = np.array(target1)\r\ntarget2 = np.array(target2)\r\ntarget3 = np.array(target3)\r\n#neural network initializing with input shape (100, 4)\r\ninp = Input((100, 4))\r\n#hidden layers\r\nhidden = LSTM(128, return_sequences=True)(inp)\r\nhidden = LSTM(128)(hidden)\r\nhidden = Dense(128)(hidden)\r\nhidden = Dropout(0.3)(hidden)\r\n#4 outputs\r\nout1 = Dense(2, activation='softmax', name='type')(hidden)\r\nout2 = Dense(128, activation='softmax', name='note')(hidden)\r\nout3 = Dense(128, activation='softmax', name='vel')(hidden)\r\nout4 = Dense(6, activation='softmax', name='time')(hidden)\r\n\r\nmodel = Model(inputs=[inp], outputs=[out1, out2, out3, out4])\r\n#compile net\r\nmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy')\r\n#make net checkpoints\r\nfilepath = \"checkpoints/weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5\"\r\ncheckpoint = ModelCheckpoint(\r\n filepath, monitor='loss', \r\n verbose=0, \r\n save_best_only=True, \r\n mode='min')\r\n#removing all old checkpoits\r\nfor i in os.listdir('checkpoints'):\r\n os.remove('checkpoints/'+i)\r\n#train net with 200 epochs\r\nmodel.fit(data, [target, target1, target2, target3],\r\n epochs=200, batch_size=64, validation_split=0,\r\n verbose=2, callbacks=[checkpoint])\r\n#save model, but we can use checkpoints\r\nmodel.save('model.h5')\r\n"
]
| [
[
"numpy.array",
"tensorflow.keras.models.Model",
"tensorflow.keras.callbacks.ModelCheckpoint"
]
]
|
iamleeg/pints | [
"bd1c11472ff3ec0990f3d55f0b2f20d92397926d"
]
| [
"pints/_diagnostics.py"
]
| [
"#\n# Functions to calculate various MCMC diagnostics\n#\n# This file is part of PINTS.\n# Copyright (c) 2017-2018, University of Oxford.\n# For licensing information, see the LICENSE file distributed with the PINTS\n# software package.\nimport numpy as np\n\n\ndef autocorrelation(x):\n \"\"\"\n Calculate autocorrelation for a vector x using a spectrum density\n calculation.\n \"\"\"\n x = (x - np.mean(x)) / (np.std(x) * np.sqrt(len(x)))\n result = np.correlate(x, x, mode='full')\n return result[int(result.size / 2):]\n\n\ndef autocorrelate_negative(autocorrelation):\n \"\"\"\n Finds last positive autocorrelation, T.\n \"\"\"\n T = 1\n for a in autocorrelation:\n if a < 0:\n return T - 1\n T += 1\n return T\n\n\ndef ess_single_param(x):\n \"\"\"\n Calculates ESS for a single parameter.\n \"\"\"\n rho = autocorrelation(x)\n T = autocorrelate_negative(rho)\n n = len(x)\n ess = n / (1 + 2 * np.sum(rho[0:T]))\n return ess\n\n\ndef effective_sample_size(samples):\n \"\"\"\n Calculates ESS for a matrix of samples.\n \"\"\"\n try:\n n_samples, n_params = samples.shape\n except (ValueError, IndexError):\n raise ValueError('Samples must be given as a 2d array.')\n if n_samples < 2:\n raise ValueError('At least two samples must be given.')\n\n return [ess_single_param(samples[:, i]) for i in range(0, n_params)]\n\n\ndef within(samples):\n \"\"\"\n Calculates within-chain variance.\n \"\"\"\n mu = list(map(lambda x: np.var(x, ddof=1), samples))\n W = np.mean(mu)\n return W\n\n\ndef between(samples):\n \"\"\"\n Calculates between-chain variance.\n \"\"\"\n mu = list(map(lambda x: np.mean(x), samples))\n mu_overall = np.mean(mu)\n m = len(samples)\n t = len(samples[0])\n return (t / (m - 1.0)) * np.sum((mu - mu_overall) ** 2)\n\n\ndef reorder(param_number, chains):\n \"\"\"\n Reorders chains for a given parameter into a more useful format for\n calculating rhat.\n \"\"\"\n num_chains = len(chains)\n samples = [chains[i][:, param_number] for i in range(0, num_chains)]\n return samples\n\n\ndef reorder_all_params(chains):\n \"\"\"\n Reorders chains for all parameters into a more useful format for\n calculating rhat.\n \"\"\"\n num_params = chains[0].shape[1]\n samples_all = [reorder(i, chains) for i in range(0, num_params)]\n return samples_all\n\n\ndef rhat(samples):\n \"\"\"\n Calculates r-hat = sqrt(((n - 1)/n * W + (1/n) * B)/W) as per \"Bayesian\n data analysis\", 3rd edition, Gelman et al., 2014.\n \"\"\"\n W = within(samples)\n B = between(samples)\n t = len(samples[0])\n return np.sqrt((W + (1.0 / t) * (B - W)) / W)\n\n\ndef rhat_all_params(chains):\n \"\"\"\n Calculates r-hat for all parameters in chains as per \"Bayesian data\n analysis\", 3rd edition, Gelman et al., 2014.\n \"\"\"\n samples_all = reorder_all_params(chains)\n rhat_all = list(map(lambda x: rhat(x), samples_all))\n return rhat_all\n\n"
]
| [
[
"numpy.correlate",
"numpy.sum",
"numpy.mean",
"numpy.std",
"numpy.sqrt",
"numpy.var"
]
]
|
gregaw/mapel | [
"00e813ebf11882938f6dc1364ca6d790f52fd7fe"
]
| [
"mapel/elections/models/single_peaked.py"
]
| [
"import numpy as np\nfrom random import *\n\nfrom scipy.special import binom\n\n\ndef generate_sp_party(model=None, num_voters=None, num_candidates=None, params=None) -> np.ndarray:\n candidates = [[] for _ in range(num_candidates)]\n _ids = [i for i in range(num_candidates)]\n\n for j in range(params['num_parties']):\n for w in range(params['num_winners']):\n _id = j * params['num_winners'] + w\n candidates[_id] = [np.random.normal(params['party'][j][0], params['var'])]\n\n mapping = [x for _, x in sorted(zip(candidates, _ids))]\n\n if model == 'conitzer_party':\n votes = generate_ordinal_sp_conitzer_votes(num_voters=num_voters, num_candidates=num_candidates)\n elif model == 'walsh_party':\n votes = generate_ordinal_sp_walsh_votes(num_voters=num_voters, num_candidates=num_candidates)\n for i in range(num_voters):\n for j in range(num_candidates):\n votes[i][j] = mapping[votes[i][j]]\n\n return votes\n\n\ndef generate_ordinal_sp_conitzer_votes(num_voters=None, num_candidates=None) -> np.ndarray:\n \"\"\" helper function: generate conitzer single-peaked elections \"\"\"\n\n votes = np.zeros([num_voters, num_candidates])\n for j in range(num_voters):\n votes[j][0] = np.random.choice(range(num_candidates))\n left = votes[j][0] - 1\n right = votes[j][0] + 1\n for k in range(1, num_candidates):\n side = np.random.choice([0, 1])\n if side == 0:\n if left >= 0:\n votes[j][k] = left\n left -= 1\n else:\n votes[j][k] = right\n right += 1\n else:\n if right < num_candidates:\n votes[j][k] = right\n right += 1\n else:\n votes[j][k] = left\n left -= 1\n\n return votes\n\n\ndef generate_ordinal_spoc_conitzer_votes(num_voters=None, num_candidates=None) -> np.ndarray:\n \"\"\" helper function: generate spoc_conitzer single-peaked elections\"\"\"\n\n votes = np.zeros([num_voters, num_candidates])\n\n for j in range(num_voters):\n votes[j][0] = np.random.choice(range(num_candidates))\n left = votes[j][0] - 1\n left %= num_candidates\n right = votes[j][0] + 1\n right %= num_candidates\n for k in range(1, num_candidates):\n side = np.random.choice([0, 1])\n if side == 0:\n votes[j][k] = left\n left -= 1\n left %= num_candidates\n else:\n votes[j][k] = right\n right += 1\n right %= num_candidates\n\n return votes\n\n\ndef generate_ordinal_sp_walsh_votes(num_voters=None, num_candidates=None) -> np.ndarray:\n \"\"\" helper function: generate walsh single-peaked elections\"\"\"\n\n votes = np.zeros([num_voters, num_candidates])\n\n for j in range(num_voters):\n votes[j] = walsh_sp(0, num_candidates - 1)\n\n return votes.astype(int)\n\n\n# AUXILIARY\ndef walsh_sp(a, b):\n if a == b:\n return [a]\n elif np.random.choice([0, 1]) == 0:\n return walsh_sp(a + 1, b) + [a]\n else:\n return walsh_sp(a, b - 1) + [b]\n\n\n### MATRICES ###\n\n# WALSH\n\ndef f(i, j):\n if i < 0: return 0\n return (1.0 / (2 ** (i + j))) * binom(i + j, i)\n\n\ndef probW(m, i, t):\n # probability that c_i is ranked t among m candidates\n return 0.5 * f(i - 1, m - t - (i - 1)) + 0.5 * f(i - t, m - i)\n\n\n# RANDOM CONITZER\n\ndef random_conitzer(C):\n # generate a random vote from the Conitzer model_id for axis\n # C[0], ..., C[m-1]\n m = len(C)\n center = np.random.randint(0, m)\n left = center\n right = center\n vote = [C[center]]\n for i in range(m - 1):\n L = False\n R = False\n\n if left > 0 and right < m - 1:\n if random() < 0.5:\n L = True\n else:\n R = True\n elif left > 0:\n L = True\n else:\n R = True\n\n if L:\n left -= 1\n vote.append(C[left])\n else:\n right += 1\n vote.append(C[right])\n\n return vote\n\n\n# CONITZER\n\ndef g(m, i, j):\n if i > j: return 0\n if i == j: return 1.0 / m\n if i == 1 and j < m: return g(m, 1, j - 1) + 0.5 * g(m, 2, j)\n if j == m and i > 1: return g(m, i + 1, m) + 0.5 * g(m, i, m - 1)\n if i == 1 and j == m: return 1.0\n return 1.0 / m\n\n\n# return 0.5*g(m,i+1,j) + 0.5*g(m,i,j-1)\n\n\ndef probC(m, i, t):\n # probability that c_i is ranked t among m candidates\n p = 0.0\n if t == 1: return 1.0 / m\n\n if i - (t - 1) > 1:\n p += 0.5 * g(m, i - (t - 1), i - 1)\n elif i - (t - 1) == 1:\n p += g(m, i - (t - 1), i - 1)\n\n if i + (t - 1) < m:\n p += 0.5 * g(m, i + 1, i + (t - 1))\n elif i + (t - 1) == m:\n p += g(m, i + 1, i + (t - 1))\n\n return p\n\n\nPRECISION = 1000\nDIGITS = 4\n\n\ndef get_conitzer_matrix(m):\n return get_conitzer_vectors(m).transpose()\n\n\ndef get_walsh_matrix(m):\n return get_walsh_vectors(m).transpose()\n\n\ndef get_conitzer_vectors(m):\n P = np.zeros([m, m])\n for i in range(m):\n for j in range(m):\n P[i][j] = probC(m, i + 1, j + 1)\n return P\n\n\ndef simconitzer(m):\n P = [[0] * m for _ in range(m)]\n T = 100000\n\n C = list(range(m))\n for t in range(T):\n if t % 10000 == 0: print(t)\n v = random_conitzer(C)\n for i in range(m):\n P[v[i]][i] += 1\n\n for j in range(m):\n for i in range(m):\n P[i][j] = str(int(PRECISION * (P[i][j] / T))).rjust(DIGITS)\n return P\n\n\ndef get_walsh_vectors(m):\n P = np.zeros([m, m])\n for i in range(m):\n for t in range(m):\n P[i][t] = probW(m, i + 1, t + 1)\n return P\n"
]
| [
[
"numpy.random.normal",
"numpy.random.choice",
"numpy.zeros",
"numpy.random.randint",
"scipy.special.binom"
]
]
|
HanBnrd/mne-python | [
"9917316f4e376d3c6f3d7cff4dafd237dba64bbf"
]
| [
"mne/io/fiff/tests/test_raw_fiff.py"
]
| [
"# -*- coding: utf-8 -*-\n# Author: Alexandre Gramfort <[email protected]>\n# Denis Engemann <[email protected]>\n#\n# License: BSD-3-Clause\n\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom functools import partial\nfrom io import BytesIO\nimport os\nimport os.path as op\nimport pathlib\nimport pickle\nimport shutil\nimport sys\n\nimport numpy as np\nfrom numpy.testing import (assert_array_almost_equal, assert_array_equal,\n assert_allclose)\nimport pytest\n\nfrom mne.datasets import testing\nfrom mne.filter import filter_data\nfrom mne.io.constants import FIFF\nfrom mne.io import RawArray, concatenate_raws, read_raw_fif, base\nfrom mne.io.open import read_tag, read_tag_info\nfrom mne.io.tag import _read_tag_header\nfrom mne.io.tests.test_raw import _test_concat, _test_raw_reader\nfrom mne import (concatenate_events, find_events, equalize_channels,\n compute_proj_raw, pick_types, pick_channels, create_info,\n pick_info)\nfrom mne.utils import (requires_pandas, assert_object_equal, _dt_to_stamp,\n requires_mne, run_subprocess,\n assert_and_remove_boundary_annot)\nfrom mne.annotations import Annotations\n\ntesting_path = testing.data_path(download=False)\ndata_dir = op.join(testing_path, 'MEG', 'sample')\nfif_fname = op.join(data_dir, 'sample_audvis_trunc_raw.fif')\nms_fname = op.join(testing_path, 'SSS', 'test_move_anon_raw.fif')\nskip_fname = op.join(testing_path, 'misc', 'intervalrecording_raw.fif')\n\nbase_dir = op.join(op.dirname(__file__), '..', '..', 'tests', 'data')\ntest_fif_fname = op.join(base_dir, 'test_raw.fif')\ntest_fif_gz_fname = op.join(base_dir, 'test_raw.fif.gz')\nctf_fname = op.join(base_dir, 'test_ctf_raw.fif')\nctf_comp_fname = op.join(base_dir, 'test_ctf_comp_raw.fif')\nfif_bad_marked_fname = op.join(base_dir, 'test_withbads_raw.fif')\nbad_file_works = op.join(base_dir, 'test_bads.txt')\nbad_file_wrong = op.join(base_dir, 'test_wrong_bads.txt')\nhp_fname = op.join(base_dir, 'test_chpi_raw_hp.txt')\nhp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')\n\n\[email protected]_testing_data\ndef test_acq_skip(tmp_path):\n \"\"\"Test treatment of acquisition skips.\"\"\"\n raw = read_raw_fif(skip_fname, preload=True)\n picks = [1, 2, 10]\n assert len(raw.times) == 17000\n annotations = raw.annotations\n assert len(annotations) == 3 # there are 3 skips\n assert_allclose(annotations.onset, [14, 19, 23])\n assert_allclose(annotations.duration, [2., 2., 3.]) # inclusive!\n data, times = raw.get_data(\n picks, reject_by_annotation='omit', return_times=True)\n expected_data, expected_times = zip(raw[picks, :2000],\n raw[picks, 4000:7000],\n raw[picks, 9000:11000],\n raw[picks, 14000:17000])\n expected_times = np.concatenate(list(expected_times), axis=-1)\n assert_allclose(times, expected_times)\n expected_data = list(expected_data)\n assert_allclose(data, np.concatenate(expected_data, axis=-1), atol=1e-22)\n\n # Check that acquisition skips are handled properly in filtering\n kwargs = dict(l_freq=None, h_freq=50., fir_design='firwin')\n raw_filt = raw.copy().filter(picks=picks, **kwargs)\n for data in expected_data:\n filter_data(data, raw.info['sfreq'], copy=False, **kwargs)\n data = raw_filt.get_data(picks, reject_by_annotation='omit')\n assert_allclose(data, np.concatenate(expected_data, axis=-1), atol=1e-22)\n\n # Check that acquisition skips are handled properly during I/O\n fname = tmp_path / 'test_raw.fif'\n raw.save(fname, fmt=raw.orig_format)\n # first: file size should not increase much (orig data is missing\n # 7 of 17 buffers, so if we write them out it should increase the file\n # size quite a bit.\n orig_size = op.getsize(skip_fname)\n new_size = op.getsize(fname)\n max_size = int(1.05 * orig_size) # almost the same + annotations\n assert new_size < max_size, (new_size, max_size)\n raw_read = read_raw_fif(fname)\n assert raw_read.annotations is not None\n assert_allclose(raw.times, raw_read.times)\n assert_allclose(raw_read[:][0], raw[:][0], atol=1e-17)\n # Saving with a bad buffer length emits warning\n raw.pick_channels(raw.ch_names[:2])\n with pytest.warns(None) as w:\n raw.save(fname, buffer_size_sec=0.5, overwrite=True)\n assert len(w) == 0\n with pytest.warns(RuntimeWarning, match='did not fit evenly'):\n raw.save(fname, buffer_size_sec=2., overwrite=True)\n\n\ndef test_fix_types():\n \"\"\"Test fixing of channel types.\"\"\"\n for fname, change in ((hp_fif_fname, True), (test_fif_fname, False),\n (ctf_fname, False)):\n raw = read_raw_fif(fname)\n mag_picks = pick_types(raw.info, meg='mag')\n other_picks = np.setdiff1d(np.arange(len(raw.ch_names)), mag_picks)\n # we don't actually have any files suffering from this problem, so\n # fake it\n if change:\n for ii in mag_picks:\n raw.info['chs'][ii]['coil_type'] = FIFF.FIFFV_COIL_VV_MAG_T2\n orig_types = np.array([ch['coil_type'] for ch in raw.info['chs']])\n raw.fix_mag_coil_types()\n new_types = np.array([ch['coil_type'] for ch in raw.info['chs']])\n if not change:\n assert_array_equal(orig_types, new_types)\n else:\n assert_array_equal(orig_types[other_picks], new_types[other_picks])\n assert ((orig_types[mag_picks] != new_types[mag_picks]).all())\n assert ((new_types[mag_picks] ==\n FIFF.FIFFV_COIL_VV_MAG_T3).all())\n\n\ndef test_concat(tmp_path):\n \"\"\"Test RawFIF concatenation.\"\"\"\n # we trim the file to save lots of memory and some time\n raw = read_raw_fif(test_fif_fname)\n raw.crop(0, 2.)\n test_name = tmp_path / 'test_raw.fif'\n raw.save(test_name)\n # now run the standard test\n _test_concat(partial(read_raw_fif), test_name)\n\n\[email protected]_testing_data\ndef test_hash_raw():\n \"\"\"Test hashing raw objects.\"\"\"\n raw = read_raw_fif(fif_fname)\n pytest.raises(RuntimeError, raw.__hash__)\n raw = read_raw_fif(fif_fname).crop(0, 0.5)\n raw_size = raw._size\n raw.load_data()\n raw_load_size = raw._size\n assert (raw_size < raw_load_size)\n raw_2 = read_raw_fif(fif_fname).crop(0, 0.5)\n raw_2.load_data()\n assert hash(raw) == hash(raw_2)\n # do NOT use assert_equal here, failing output is terrible\n assert pickle.dumps(raw) == pickle.dumps(raw_2)\n\n raw_2._data[0, 0] -= 1\n assert hash(raw) != hash(raw_2)\n\n\[email protected]_testing_data\ndef test_maxshield():\n \"\"\"Test maxshield warning.\"\"\"\n with pytest.warns(RuntimeWarning, match='Internal Active Shielding') as w:\n read_raw_fif(ms_fname, allow_maxshield=True)\n assert ('test_raw_fiff.py' in w[0].filename)\n\n\[email protected]_testing_data\ndef test_subject_info(tmp_path):\n \"\"\"Test reading subject information.\"\"\"\n raw = read_raw_fif(fif_fname).crop(0, 1)\n assert (raw.info['subject_info'] is None)\n # fake some subject data\n keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex',\n 'hand']\n vals = [1, 'foobar', 'bar', 'foo', (1901, 2, 3), 0, 1]\n subject_info = dict()\n for key, val in zip(keys, vals):\n subject_info[key] = val\n raw.info['subject_info'] = subject_info\n out_fname = tmp_path / 'test_subj_info_raw.fif'\n raw.save(out_fname, overwrite=True)\n raw_read = read_raw_fif(out_fname)\n for key in keys:\n assert subject_info[key] == raw_read.info['subject_info'][key]\n assert raw.info['meas_date'] == raw_read.info['meas_date']\n\n for key in ['secs', 'usecs', 'version']:\n assert raw.info['meas_id'][key] == raw_read.info['meas_id'][key]\n assert_array_equal(raw.info['meas_id']['machid'],\n raw_read.info['meas_id']['machid'])\n\n\[email protected]_testing_data\ndef test_copy_append():\n \"\"\"Test raw copying and appending combinations.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True).copy()\n raw_full = read_raw_fif(fif_fname)\n raw_full.append(raw)\n data = raw_full[:, :][0]\n assert data.shape[1] == 2 * raw._data.shape[1]\n\n\[email protected]_testing_data\ndef test_output_formats(tmp_path):\n \"\"\"Test saving and loading raw data using multiple formats.\"\"\"\n formats = ['short', 'int', 'single', 'double']\n tols = [1e-4, 1e-7, 1e-7, 1e-15]\n\n # let's fake a raw file with different formats\n raw = read_raw_fif(test_fif_fname).crop(0, 1)\n\n temp_file = tmp_path / 'raw.fif'\n for ii, (fmt, tol) in enumerate(zip(formats, tols)):\n # Let's test the overwriting error throwing while we're at it\n if ii > 0:\n pytest.raises(IOError, raw.save, temp_file, fmt=fmt)\n raw.save(temp_file, fmt=fmt, overwrite=True)\n raw2 = read_raw_fif(temp_file)\n raw2_data = raw2[:, :][0]\n assert_allclose(raw2_data, raw[:, :][0], rtol=tol, atol=1e-25)\n assert raw2.orig_format == fmt\n\n\ndef _compare_combo(raw, new, times, n_times):\n \"\"\"Compare data.\"\"\"\n for ti in times: # let's do a subset of points for speed\n orig = raw[:, ti % n_times][0]\n # these are almost_equals because of possible dtype differences\n assert_allclose(orig, new[:, ti][0])\n\n\[email protected]\[email protected]_testing_data\ndef test_multiple_files(tmp_path):\n \"\"\"Test loading multiple files simultaneously.\"\"\"\n # split file\n raw = read_raw_fif(fif_fname).crop(0, 10)\n raw.load_data()\n raw.load_data() # test no operation\n split_size = 3. # in seconds\n sfreq = raw.info['sfreq']\n nsamp = (raw.last_samp - raw.first_samp)\n tmins = np.round(np.arange(0., nsamp, split_size * sfreq))\n tmaxs = np.concatenate((tmins[1:] - 1, [nsamp]))\n tmaxs /= sfreq\n tmins /= sfreq\n assert raw.n_times == len(raw.times)\n\n # going in reverse order so the last fname is the first file (need later)\n raws = [None] * len(tmins)\n for ri in range(len(tmins) - 1, -1, -1):\n fname = tmp_path / ('test_raw_split-%d_raw.fif' % ri)\n raw.save(fname, tmin=tmins[ri], tmax=tmaxs[ri])\n raws[ri] = read_raw_fif(fname)\n assert (len(raws[ri].times) ==\n int(round((tmaxs[ri] - tmins[ri]) *\n raw.info['sfreq'])) + 1) # + 1 b/c inclusive\n events = [find_events(r, stim_channel='STI 014') for r in raws]\n last_samps = [r.last_samp for r in raws]\n first_samps = [r.first_samp for r in raws]\n\n # test concatenation of split file\n pytest.raises(ValueError, concatenate_raws, raws, True, events[1:])\n all_raw_1, events1 = concatenate_raws(raws, preload=False,\n events_list=events)\n assert_allclose(all_raw_1.times, raw.times)\n assert raw.first_samp == all_raw_1.first_samp\n assert raw.last_samp == all_raw_1.last_samp\n assert_allclose(raw[:, :][0], all_raw_1[:, :][0])\n raws[0] = read_raw_fif(fname)\n all_raw_2 = concatenate_raws(raws, preload=True)\n assert_allclose(raw[:, :][0], all_raw_2[:, :][0])\n\n # test proper event treatment for split files\n events2 = concatenate_events(events, first_samps, last_samps)\n events3 = find_events(all_raw_2, stim_channel='STI 014')\n assert_array_equal(events1, events2)\n assert_array_equal(events1, events3)\n\n # test various methods of combining files\n raw = read_raw_fif(fif_fname, preload=True)\n n_times = raw.n_times\n # make sure that all our data match\n times = list(range(0, 2 * n_times, 999))\n # add potentially problematic points\n times.extend([n_times - 1, n_times, 2 * n_times - 1])\n\n raw_combo0 = concatenate_raws([read_raw_fif(f)\n for f in [fif_fname, fif_fname]],\n preload=True)\n _compare_combo(raw, raw_combo0, times, n_times)\n raw_combo = concatenate_raws([read_raw_fif(f)\n for f in [fif_fname, fif_fname]],\n preload=False)\n _compare_combo(raw, raw_combo, times, n_times)\n raw_combo = concatenate_raws([read_raw_fif(f)\n for f in [fif_fname, fif_fname]],\n preload='memmap8.dat')\n _compare_combo(raw, raw_combo, times, n_times)\n assert raw[:, :][0].shape[1] * 2 == raw_combo0[:, :][0].shape[1]\n assert raw_combo0[:, :][0].shape[1] == raw_combo0.n_times\n\n # with all data preloaded, result should be preloaded\n raw_combo = read_raw_fif(fif_fname, preload=True)\n raw_combo.append(read_raw_fif(fif_fname, preload=True))\n assert (raw_combo.preload is True)\n assert raw_combo.n_times == raw_combo._data.shape[1]\n _compare_combo(raw, raw_combo, times, n_times)\n\n # with any data not preloaded, don't set result as preloaded\n raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=True),\n read_raw_fif(fif_fname, preload=False)])\n assert (raw_combo.preload is False)\n assert_array_equal(find_events(raw_combo, stim_channel='STI 014'),\n find_events(raw_combo0, stim_channel='STI 014'))\n _compare_combo(raw, raw_combo, times, n_times)\n\n # user should be able to force data to be preloaded upon concat\n raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=False),\n read_raw_fif(fif_fname, preload=True)],\n preload=True)\n assert (raw_combo.preload is True)\n _compare_combo(raw, raw_combo, times, n_times)\n\n raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=False),\n read_raw_fif(fif_fname, preload=True)],\n preload='memmap3.dat')\n _compare_combo(raw, raw_combo, times, n_times)\n\n raw_combo = concatenate_raws([\n read_raw_fif(fif_fname, preload=True),\n read_raw_fif(fif_fname, preload=True)], preload='memmap4.dat')\n _compare_combo(raw, raw_combo, times, n_times)\n\n raw_combo = concatenate_raws([\n read_raw_fif(fif_fname, preload=False),\n read_raw_fif(fif_fname, preload=False)], preload='memmap5.dat')\n _compare_combo(raw, raw_combo, times, n_times)\n\n # verify that combining raws with different projectors throws an exception\n raw.add_proj([], remove_existing=True)\n pytest.raises(ValueError, raw.append,\n read_raw_fif(fif_fname, preload=True))\n\n # now test event treatment for concatenated raw files\n events = [find_events(raw, stim_channel='STI 014'),\n find_events(raw, stim_channel='STI 014')]\n last_samps = [raw.last_samp, raw.last_samp]\n first_samps = [raw.first_samp, raw.first_samp]\n events = concatenate_events(events, first_samps, last_samps)\n events2 = find_events(raw_combo0, stim_channel='STI 014')\n assert_array_equal(events, events2)\n\n # check out the len method\n assert len(raw) == raw.n_times\n assert len(raw) == raw.last_samp - raw.first_samp + 1\n\n\[email protected]_testing_data\[email protected]('on_mismatch', ('ignore', 'warn', 'raise'))\ndef test_concatenate_raws(on_mismatch):\n \"\"\"Test error handling during raw concatenation.\"\"\"\n raw = read_raw_fif(fif_fname).crop(0, 10)\n raws = [raw, raw.copy()]\n raws[1].info['dev_head_t']['trans'] += 0.1\n kws = dict(raws=raws, on_mismatch=on_mismatch)\n\n if on_mismatch == 'ignore':\n concatenate_raws(**kws)\n elif on_mismatch == 'warn':\n with pytest.warns(RuntimeWarning, match='different head positions'):\n concatenate_raws(**kws)\n elif on_mismatch == 'raise':\n with pytest.raises(ValueError, match='different head positions'):\n concatenate_raws(**kws)\n\n\[email protected]_testing_data\[email protected]('mod', (\n 'meg',\n pytest.param('raw', marks=[\n pytest.mark.filterwarnings(\n 'ignore:.*naming conventions.*:RuntimeWarning'),\n pytest.mark.slowtest]),\n))\ndef test_split_files(tmp_path, mod, monkeypatch):\n \"\"\"Test writing and reading of split raw files.\"\"\"\n raw_1 = read_raw_fif(fif_fname, preload=True)\n # Test a very close corner case\n\n assert_allclose(raw_1.buffer_size_sec, 10., atol=1e-2) # samp rate\n split_fname = tmp_path / f'split_raw_{mod}.fif'\n # intended filenames\n split_fname_elekta_part2 = tmp_path / f'split_raw_{mod}-1.fif'\n split_fname_bids_part1 = tmp_path / f'split_raw_split-01_{mod}.fif'\n split_fname_bids_part2 = tmp_path / f'split_raw_split-02_{mod}.fif'\n raw_1.set_annotations(Annotations([2.], [5.5], 'test'))\n\n # Check that if BIDS is used and no split is needed it defaults to\n # simple writing without _split- entity.\n raw_1.save(split_fname, split_naming='bids', verbose=True)\n assert op.isfile(split_fname)\n assert not op.isfile(split_fname_bids_part1)\n for split_naming in ('neuromag', 'bids'):\n with pytest.raises(FileExistsError, match='Destination file'):\n raw_1.save(split_fname, split_naming=split_naming, verbose=True)\n os.remove(split_fname)\n with open(split_fname_bids_part1, 'w'):\n pass\n with pytest.raises(FileExistsError, match='Destination file'):\n raw_1.save(split_fname, split_naming='bids', verbose=True)\n assert not op.isfile(split_fname)\n raw_1.save(split_fname, split_naming='neuromag', verbose=True) # okay\n os.remove(split_fname)\n os.remove(split_fname_bids_part1)\n\n raw_1.save(split_fname, buffer_size_sec=1.0, split_size='10MB',\n verbose=True)\n\n # check that the filenames match the intended pattern\n assert op.isfile(split_fname)\n assert op.isfile(split_fname_elekta_part2)\n # check that filenames are being formatted correctly for BIDS\n raw_1.save(split_fname, buffer_size_sec=1.0, split_size='10MB',\n split_naming='bids', overwrite=True, verbose=True)\n assert op.isfile(split_fname_bids_part1)\n assert op.isfile(split_fname_bids_part2)\n\n annot = Annotations(np.arange(20), np.ones((20,)), 'test')\n raw_1.set_annotations(annot)\n split_fname = op.join(tmp_path, 'split_raw.fif')\n raw_1.save(split_fname, buffer_size_sec=1.0, split_size='10MB')\n raw_2 = read_raw_fif(split_fname)\n assert_allclose(raw_2.buffer_size_sec, 1., atol=1e-2) # samp rate\n assert_allclose(raw_1.annotations.onset, raw_2.annotations.onset)\n assert_allclose(raw_1.annotations.duration, raw_2.annotations.duration,\n rtol=0.001 / raw_2.info['sfreq'])\n assert_array_equal(raw_1.annotations.description,\n raw_2.annotations.description)\n\n data_1, times_1 = raw_1[:, :]\n data_2, times_2 = raw_2[:, :]\n assert_array_equal(data_1, data_2)\n assert_array_equal(times_1, times_2)\n\n raw_bids = read_raw_fif(split_fname_bids_part1)\n data_bids, times_bids = raw_bids[:, :]\n assert_array_equal(data_1, data_bids)\n assert_array_equal(times_1, times_bids)\n del raw_bids\n # split missing behaviors\n os.remove(split_fname_bids_part2)\n with pytest.raises(ValueError, match='manually renamed'):\n read_raw_fif(split_fname_bids_part1, on_split_missing='raise')\n with pytest.warns(RuntimeWarning, match='Split raw file detected'):\n read_raw_fif(split_fname_bids_part1, on_split_missing='warn')\n read_raw_fif(split_fname_bids_part1, on_split_missing='ignore')\n\n # test the case where we only end up with one buffer to write\n # (GH#3210). These tests rely on writing meas info and annotations\n # taking up a certain number of bytes, so if we change those functions\n # somehow, the numbers below for e.g. split_size might need to be\n # adjusted.\n raw_crop = raw_1.copy().crop(0, 5)\n raw_crop.set_annotations(Annotations([2.], [5.5], 'test'),\n emit_warning=False)\n with pytest.raises(ValueError,\n match='after writing measurement information'):\n raw_crop.save(split_fname, split_size='1MB', # too small a size\n buffer_size_sec=1., overwrite=True)\n with pytest.raises(ValueError,\n match='too large for the given split size'):\n raw_crop.save(split_fname,\n split_size=3003000, # still too small, now after Info\n buffer_size_sec=1., overwrite=True)\n # just barely big enough here; the right size to write exactly one buffer\n # at a time so we hit GH#3210 if we aren't careful\n raw_crop.save(split_fname, split_size='4.5MB',\n buffer_size_sec=1., overwrite=True)\n raw_read = read_raw_fif(split_fname)\n assert_allclose(raw_crop[:][0], raw_read[:][0], atol=1e-20)\n\n # Check our buffer arithmetic\n\n # 1 buffer required\n raw_crop = raw_1.copy().crop(0, 1)\n raw_crop.save(split_fname, buffer_size_sec=1., overwrite=True)\n raw_read = read_raw_fif(split_fname)\n assert_array_equal(np.diff(raw_read._raw_extras[0]['bounds']), (301,))\n assert_allclose(raw_crop[:][0], raw_read[:][0])\n # 2 buffers required\n raw_crop.save(split_fname, buffer_size_sec=0.5, overwrite=True)\n raw_read = read_raw_fif(split_fname)\n assert_array_equal(np.diff(raw_read._raw_extras[0]['bounds']), (151, 150))\n assert_allclose(raw_crop[:][0], raw_read[:][0])\n # 2 buffers required\n raw_crop.save(split_fname,\n buffer_size_sec=1. - 1.01 / raw_crop.info['sfreq'],\n overwrite=True)\n raw_read = read_raw_fif(split_fname)\n assert_array_equal(np.diff(raw_read._raw_extras[0]['bounds']), (300, 1))\n assert_allclose(raw_crop[:][0], raw_read[:][0])\n raw_crop.save(split_fname,\n buffer_size_sec=1. - 2.01 / raw_crop.info['sfreq'],\n overwrite=True)\n raw_read = read_raw_fif(split_fname)\n assert_array_equal(np.diff(raw_read._raw_extras[0]['bounds']), (299, 2))\n assert_allclose(raw_crop[:][0], raw_read[:][0])\n\n # proper ending\n assert op.isdir(tmp_path)\n with pytest.raises(ValueError, match='must end with an underscore'):\n raw_crop.save(\n tmp_path / 'test.fif', split_naming='bids', verbose='error')\n\n # reserved file is deleted\n fname = tmp_path / 'test_raw.fif'\n monkeypatch.setattr(base, '_write_raw_fid', _err)\n with pytest.raises(RuntimeError, match='Killed mid-write'):\n raw_1.save(fname, split_size='10MB', split_naming='bids')\n assert op.isfile(fname)\n assert not op.isfile(tmp_path / 'test_split-01_raw.fif')\n\n\ndef _err(*args, **kwargs):\n raise RuntimeError('Killed mid-write')\n\n\ndef _no_write_file_name(fid, kind, data):\n assert kind == FIFF.FIFF_REF_FILE_NAME # the only string we actually write\n return\n\n\ndef test_split_numbers(tmp_path, monkeypatch):\n \"\"\"Test handling of split files using numbers instead of names.\"\"\"\n monkeypatch.setattr(base, 'write_string', _no_write_file_name)\n raw = read_raw_fif(test_fif_fname).pick('eeg')\n # gh-8339\n dashes_fname = tmp_path / 'sub-1_ses-2_task-3_raw.fif'\n raw.save(dashes_fname, split_size='5MB',\n buffer_size_sec=1.)\n assert op.isfile(dashes_fname)\n next_fname = str(dashes_fname)[:-4] + '-1.fif'\n assert op.isfile(next_fname)\n raw_read = read_raw_fif(dashes_fname)\n assert_allclose(raw.times, raw_read.times)\n assert_allclose(raw.get_data(), raw_read.get_data(), atol=1e-16)\n\n\ndef test_load_bad_channels(tmp_path):\n \"\"\"Test reading/writing of bad channels.\"\"\"\n # Load correctly marked file (manually done in mne_process_raw)\n raw_marked = read_raw_fif(fif_bad_marked_fname)\n correct_bads = raw_marked.info['bads']\n raw = read_raw_fif(test_fif_fname)\n # Make sure it starts clean\n assert_array_equal(raw.info['bads'], [])\n\n # Test normal case\n raw.load_bad_channels(bad_file_works)\n # Write it out, read it in, and check\n raw.save(tmp_path / 'foo_raw.fif')\n raw_new = read_raw_fif(tmp_path / 'foo_raw.fif')\n assert correct_bads == raw_new.info['bads']\n # Reset it\n raw.info['bads'] = []\n\n # Test bad case\n pytest.raises(ValueError, raw.load_bad_channels, bad_file_wrong)\n\n # Test forcing the bad case\n with pytest.warns(RuntimeWarning, match='1 bad channel'):\n raw.load_bad_channels(bad_file_wrong, force=True)\n\n # write it out, read it in, and check\n raw.save(tmp_path / 'foo_raw.fif', overwrite=True)\n raw_new = read_raw_fif(tmp_path / 'foo_raw.fif')\n assert correct_bads == raw_new.info['bads']\n\n # Check that bad channels are cleared\n raw.load_bad_channels(None)\n raw.save(tmp_path / 'foo_raw.fif', overwrite=True)\n raw_new = read_raw_fif(tmp_path / 'foo_raw.fif')\n assert raw_new.info['bads'] == []\n\n\[email protected]\[email protected]_testing_data\ndef test_io_raw(tmp_path):\n \"\"\"Test IO for raw data (Neuromag).\"\"\"\n rng = np.random.RandomState(0)\n # test unicode io\n for chars in [u'äöé', 'a']:\n with read_raw_fif(fif_fname) as r:\n assert ('Raw' in repr(r))\n assert (op.basename(fif_fname) in repr(r))\n r.info['description'] = chars\n temp_file = tmp_path / 'raw.fif'\n r.save(temp_file, overwrite=True)\n with read_raw_fif(temp_file) as r2:\n desc2 = r2.info['description']\n assert desc2 == chars\n\n # Let's construct a simple test for IO first\n raw = read_raw_fif(fif_fname).crop(0, 3.5)\n raw.load_data()\n # put in some data that we know the values of\n data = rng.randn(raw._data.shape[0], raw._data.shape[1])\n raw._data[:, :] = data\n # save it somewhere\n fname = tmp_path / 'test_copy_raw.fif'\n raw.save(fname, buffer_size_sec=1.0)\n # read it in, make sure the whole thing matches\n raw = read_raw_fif(fname)\n assert_allclose(data, raw[:, :][0], rtol=1e-6, atol=1e-20)\n # let's read portions across the 1-sec tag boundary, too\n inds = raw.time_as_index([1.75, 2.25])\n sl = slice(inds[0], inds[1])\n assert_allclose(data[:, sl], raw[:, sl][0], rtol=1e-6, atol=1e-20)\n\n\[email protected]('fname_in, fname_out', [\n (test_fif_fname, 'raw.fif'),\n pytest.param(test_fif_gz_fname, 'raw.fif.gz', marks=pytest.mark.slowtest),\n (ctf_fname, 'raw.fif')])\ndef test_io_raw_additional(fname_in, fname_out, tmp_path):\n \"\"\"Test IO for raw data (Neuromag + CTF + gz).\"\"\"\n fname_out = tmp_path / fname_out\n raw = read_raw_fif(fname_in).crop(0, 2)\n\n nchan = raw.info['nchan']\n ch_names = raw.info['ch_names']\n meg_channels_idx = [k for k in range(nchan)\n if ch_names[k][0] == 'M']\n n_channels = 100\n meg_channels_idx = meg_channels_idx[:n_channels]\n start, stop = raw.time_as_index([0, 5], use_rounding=True)\n data, times = raw[meg_channels_idx, start:(stop + 1)]\n meg_ch_names = [ch_names[k] for k in meg_channels_idx]\n\n # Set up pick list: MEG + STI 014 - bad channels\n include = ['STI 014']\n include += meg_ch_names\n picks = pick_types(raw.info, meg=True, eeg=False, stim=True,\n misc=True, ref_meg=True, include=include,\n exclude='bads')\n\n # Writing with drop_small_buffer True\n raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3,\n drop_small_buffer=True, overwrite=True)\n raw2 = read_raw_fif(fname_out)\n\n sel = pick_channels(raw2.ch_names, meg_ch_names)\n data2, times2 = raw2[sel, :]\n assert (times2.max() <= 3)\n\n # Writing\n raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True)\n\n if fname_in in (fif_fname, fif_fname + '.gz'):\n assert len(raw.info['dig']) == 146\n\n raw2 = read_raw_fif(fname_out)\n\n sel = pick_channels(raw2.ch_names, meg_ch_names)\n data2, times2 = raw2[sel, :]\n\n assert_allclose(data, data2, rtol=1e-6, atol=1e-20)\n assert_allclose(times, times2)\n assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5)\n\n # check transformations\n for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']:\n if raw.info[trans] is None:\n assert (raw2.info[trans] is None)\n else:\n assert_array_equal(raw.info[trans]['trans'],\n raw2.info[trans]['trans'])\n\n # check transformation 'from' and 'to'\n if trans.startswith('dev'):\n from_id = FIFF.FIFFV_COORD_DEVICE\n else:\n from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD\n if trans[4:8] == 'head':\n to_id = FIFF.FIFFV_COORD_HEAD\n else:\n to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD\n for raw_ in [raw, raw2]:\n assert raw_.info[trans]['from'] == from_id\n assert raw_.info[trans]['to'] == to_id\n\n if fname_in == fif_fname or fname_in == fif_fname + '.gz':\n assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r'])\n\n # test warnings on bad filenames\n raw_badname = tmp_path / 'test-bad-name.fif.gz'\n with pytest.warns(RuntimeWarning, match='raw.fif'):\n raw.save(raw_badname)\n with pytest.warns(RuntimeWarning, match='raw.fif'):\n read_raw_fif(raw_badname)\n\n\[email protected]_testing_data\[email protected]('dtype', ('complex128', 'complex64'))\ndef test_io_complex(tmp_path, dtype):\n \"\"\"Test IO with complex data types.\"\"\"\n rng = np.random.RandomState(0)\n n_ch = 5\n raw = read_raw_fif(fif_fname).crop(0, 1).pick(np.arange(n_ch)).load_data()\n data_orig = raw.get_data()\n imag_rand = np.array(1j * rng.randn(n_ch, len(raw.times)), dtype=dtype)\n raw_cp = raw.copy()\n raw_cp._data = np.array(raw_cp._data, dtype)\n raw_cp._data += imag_rand\n with pytest.warns(RuntimeWarning, match='Saving .* complex data.'):\n raw_cp.save(tmp_path / 'raw.fif', overwrite=True)\n\n raw2 = read_raw_fif(tmp_path / 'raw.fif')\n raw2_data, _ = raw2[:]\n assert_allclose(raw2_data, raw_cp._data)\n # with preloading\n raw2 = read_raw_fif(tmp_path / 'raw.fif', preload=True)\n raw2_data, _ = raw2[:]\n assert_allclose(raw2_data, raw_cp._data)\n assert_allclose(data_orig, raw_cp._data.real)\n\n\[email protected]_testing_data\ndef test_getitem():\n \"\"\"Test getitem/indexing of Raw.\"\"\"\n for preload in [False, True, 'memmap.dat']:\n raw = read_raw_fif(fif_fname, preload=preload)\n data, times = raw[0, :]\n data1, times1 = raw[0]\n assert_array_equal(data, data1)\n assert_array_equal(times, times1)\n data, times = raw[0:2, :]\n data1, times1 = raw[0:2]\n assert_array_equal(data, data1)\n assert_array_equal(times, times1)\n data1, times1 = raw[[0, 1]]\n assert_array_equal(data, data1)\n assert_array_equal(times, times1)\n assert_array_equal(raw[raw.ch_names[0]][0][0], raw[0][0][0])\n assert_array_equal(\n raw[-10:-1, :][0],\n raw[len(raw.ch_names) - 10:len(raw.ch_names) - 1, :][0])\n with pytest.raises(ValueError, match='No appropriate channels'):\n raw[slice(-len(raw.ch_names) - 1), slice(None)]\n with pytest.raises(ValueError, match='must be'):\n raw[-1000]\n\n\[email protected]_testing_data\ndef test_proj(tmp_path):\n \"\"\"Test SSP proj operations.\"\"\"\n for proj in [True, False]:\n raw = read_raw_fif(fif_fname, preload=False)\n if proj:\n raw.apply_proj()\n assert (all(p['active'] == proj for p in raw.info['projs']))\n\n data, times = raw[0:2, :]\n data1, times1 = raw[0:2]\n assert_array_equal(data, data1)\n assert_array_equal(times, times1)\n\n # test adding / deleting proj\n if proj:\n pytest.raises(ValueError, raw.add_proj, [],\n {'remove_existing': True})\n pytest.raises(ValueError, raw.del_proj, 0)\n else:\n projs = deepcopy(raw.info['projs'])\n n_proj = len(raw.info['projs'])\n raw.del_proj(0)\n assert len(raw.info['projs']) == n_proj - 1\n raw.add_proj(projs, remove_existing=False)\n # Test that already existing projections are not added.\n assert len(raw.info['projs']) == n_proj\n raw.add_proj(projs[:-1], remove_existing=True)\n assert len(raw.info['projs']) == n_proj - 1\n\n # test apply_proj() with and without preload\n for preload in [True, False]:\n raw = read_raw_fif(fif_fname, preload=preload)\n data, times = raw[:, 0:2]\n raw.apply_proj()\n data_proj_1 = np.dot(raw._projector, data)\n\n # load the file again without proj\n raw = read_raw_fif(fif_fname, preload=preload)\n\n # write the file with proj. activated, make sure proj has been applied\n raw.save(tmp_path / 'raw.fif', proj=True, overwrite=True)\n raw2 = read_raw_fif(tmp_path / 'raw.fif')\n data_proj_2, _ = raw2[:, 0:2]\n assert_allclose(data_proj_1, data_proj_2)\n assert (all(p['active'] for p in raw2.info['projs']))\n\n # read orig file with proj. active\n raw2 = read_raw_fif(fif_fname, preload=preload)\n raw2.apply_proj()\n data_proj_2, _ = raw2[:, 0:2]\n assert_allclose(data_proj_1, data_proj_2)\n assert (all(p['active'] for p in raw2.info['projs']))\n\n # test that apply_proj works\n raw.apply_proj()\n data_proj_2, _ = raw[:, 0:2]\n assert_allclose(data_proj_1, data_proj_2)\n assert_allclose(data_proj_2, np.dot(raw._projector, data_proj_2))\n\n # Test that picking removes projectors ...\n raw = read_raw_fif(fif_fname)\n n_projs = len(raw.info['projs'])\n raw.pick_types(meg=False, eeg=True)\n assert len(raw.info['projs']) == n_projs - 3\n\n # ... but only if it doesn't apply to any channels in the dataset anymore.\n raw = read_raw_fif(fif_fname)\n n_projs = len(raw.info['projs'])\n raw.pick_types(meg='mag', eeg=True)\n assert len(raw.info['projs']) == n_projs\n\n # I/O roundtrip of an MEG projector with a Raw that only contains EEG\n # data.\n out_fname = tmp_path / 'test_raw.fif'\n raw = read_raw_fif(test_fif_fname, preload=True).crop(0, 0.002)\n proj = raw.info['projs'][-1]\n raw.pick_types(meg=False, eeg=True)\n raw.add_proj(proj) # Restore, because picking removed it!\n raw._data.fill(0)\n raw._data[-1] = 1.\n raw.save(out_fname)\n raw = read_raw_fif(out_fname, preload=False)\n raw.apply_proj()\n assert_allclose(raw[:, :][0][:1], raw[0, :][0])\n\n\[email protected]_testing_data\[email protected]('preload', [False, True, 'memmap.dat'])\ndef test_preload_modify(preload, tmp_path):\n \"\"\"Test preloading and modifying data.\"\"\"\n rng = np.random.RandomState(0)\n raw = read_raw_fif(fif_fname, preload=preload)\n\n nsamp = raw.last_samp - raw.first_samp + 1\n picks = pick_types(raw.info, meg='grad', exclude='bads')\n\n data = rng.randn(len(picks), nsamp // 2)\n\n try:\n raw[picks, :nsamp // 2] = data\n except RuntimeError:\n if not preload:\n return\n else:\n raise\n\n tmp_fname = tmp_path / 'raw.fif'\n raw.save(tmp_fname, overwrite=True)\n\n raw_new = read_raw_fif(tmp_fname)\n data_new, _ = raw_new[picks, :nsamp // 2]\n\n assert_allclose(data, data_new)\n\n\[email protected]\[email protected]_testing_data\ndef test_filter():\n \"\"\"Test filtering (FIR and IIR) and Raw.apply_function interface.\"\"\"\n raw = read_raw_fif(fif_fname).crop(0, 7)\n raw.load_data()\n sig_dec_notch = 12\n sig_dec_notch_fit = 12\n picks_meg = pick_types(raw.info, meg=True, exclude='bads')\n picks = picks_meg[:4]\n\n trans = 2.0\n filter_params = dict(picks=picks, filter_length='auto',\n h_trans_bandwidth=trans, l_trans_bandwidth=trans,\n fir_design='firwin')\n raw_lp = raw.copy().filter(None, 8.0, **filter_params)\n raw_hp = raw.copy().filter(16.0, None, **filter_params)\n raw_bp = raw.copy().filter(8.0 + trans, 16.0 - trans, **filter_params)\n raw_bs = raw.copy().filter(16.0, 8.0, **filter_params)\n\n data, _ = raw[picks, :]\n\n lp_data, _ = raw_lp[picks, :]\n hp_data, _ = raw_hp[picks, :]\n bp_data, _ = raw_bp[picks, :]\n bs_data, _ = raw_bs[picks, :]\n\n tols = dict(atol=1e-20, rtol=1e-5)\n assert_allclose(bs_data, lp_data + hp_data, **tols)\n assert_allclose(data, lp_data + bp_data + hp_data, **tols)\n assert_allclose(data, bp_data + bs_data, **tols)\n\n filter_params_iir = dict(picks=picks, n_jobs=2, method='iir',\n iir_params=dict(output='ba'))\n raw_lp_iir = raw.copy().filter(None, 4.0, **filter_params_iir)\n raw_hp_iir = raw.copy().filter(8.0, None, **filter_params_iir)\n raw_bp_iir = raw.copy().filter(4.0, 8.0, **filter_params_iir)\n del filter_params_iir\n lp_data_iir, _ = raw_lp_iir[picks, :]\n hp_data_iir, _ = raw_hp_iir[picks, :]\n bp_data_iir, _ = raw_bp_iir[picks, :]\n summation = lp_data_iir + hp_data_iir + bp_data_iir\n assert_array_almost_equal(data[:, 100:-100], summation[:, 100:-100], 11)\n\n # make sure we didn't touch other channels\n data, _ = raw[picks_meg[4:], :]\n bp_data, _ = raw_bp[picks_meg[4:], :]\n assert_array_equal(data, bp_data)\n bp_data_iir, _ = raw_bp_iir[picks_meg[4:], :]\n assert_array_equal(data, bp_data_iir)\n\n # ... and that inplace changes are inplace\n raw_copy = raw.copy()\n assert np.may_share_memory(raw._data, raw._data)\n assert not np.may_share_memory(raw_copy._data, raw._data)\n # this could be assert_array_equal but we do this to mirror the call below\n assert (raw._data[0] == raw_copy._data[0]).all()\n raw_copy.filter(None, 20., n_jobs=2, **filter_params)\n assert not (raw._data[0] == raw_copy._data[0]).all()\n assert_array_equal(raw.copy().filter(None, 20., **filter_params)._data,\n raw_copy._data)\n\n # do a very simple check on line filtering\n raw_bs = raw.copy().filter(60.0 + trans, 60.0 - trans, **filter_params)\n data_bs, _ = raw_bs[picks, :]\n raw_notch = raw.copy().notch_filter(\n 60.0, picks=picks, n_jobs=2, method='fir',\n trans_bandwidth=2 * trans)\n data_notch, _ = raw_notch[picks, :]\n assert_array_almost_equal(data_bs, data_notch, sig_dec_notch)\n\n # now use the sinusoidal fitting\n assert raw.times[-1] < 10 # catch error with filter_length > n_times\n raw_notch = raw.copy().notch_filter(\n None, picks=picks, n_jobs=2, method='spectrum_fit',\n filter_length='10s')\n data_notch, _ = raw_notch[picks, :]\n data, _ = raw[picks, :]\n assert_array_almost_equal(data, data_notch, sig_dec_notch_fit)\n\n # filter should set the \"lowpass\" and \"highpass\" parameters\n raw = RawArray(np.random.randn(3, 1000),\n create_info(3, 1000., ['eeg'] * 2 + ['stim']))\n with raw.info._unlock():\n raw.info['lowpass'] = raw.info['highpass'] = None\n for kind in ('none', 'lowpass', 'highpass', 'bandpass', 'bandstop'):\n print(kind)\n h_freq = l_freq = None\n if kind in ('lowpass', 'bandpass'):\n h_freq = 70\n if kind in ('highpass', 'bandpass'):\n l_freq = 30\n if kind == 'bandstop':\n l_freq, h_freq = 70, 30\n assert (raw.info['lowpass'] is None)\n assert (raw.info['highpass'] is None)\n kwargs = dict(l_trans_bandwidth=20, h_trans_bandwidth=20,\n filter_length='auto', phase='zero', fir_design='firwin')\n raw_filt = raw.copy().filter(l_freq, h_freq, picks=np.arange(1),\n **kwargs)\n assert (raw.info['lowpass'] is None)\n assert (raw.info['highpass'] is None)\n raw_filt = raw.copy().filter(l_freq, h_freq, **kwargs)\n wanted_h = h_freq if kind != 'bandstop' else None\n wanted_l = l_freq if kind != 'bandstop' else None\n assert raw_filt.info['lowpass'] == wanted_h\n assert raw_filt.info['highpass'] == wanted_l\n # Using all data channels should still set the params (GH#3259)\n raw_filt = raw.copy().filter(l_freq, h_freq, picks=np.arange(2),\n **kwargs)\n assert raw_filt.info['lowpass'] == wanted_h\n assert raw_filt.info['highpass'] == wanted_l\n\n\ndef test_filter_picks():\n \"\"\"Test filtering default channel picks.\"\"\"\n ch_types = ['mag', 'grad', 'eeg', 'seeg', 'dbs', 'misc', 'stim', 'ecog',\n 'hbo', 'hbr']\n info = create_info(ch_names=ch_types, ch_types=ch_types, sfreq=256)\n raw = RawArray(data=np.zeros((len(ch_types), 1000)), info=info)\n\n # -- Deal with meg mag grad and fnirs exceptions\n ch_types = ('misc', 'stim', 'meg', 'eeg', 'seeg', 'dbs', 'ecog')\n\n # -- Filter data channels\n for ch_type in ('mag', 'grad', 'eeg', 'seeg', 'dbs', 'ecog', 'hbo', 'hbr'):\n picks = {ch: ch == ch_type for ch in ch_types}\n picks['meg'] = ch_type if ch_type in ('mag', 'grad') else False\n picks['fnirs'] = ch_type if ch_type in ('hbo', 'hbr') else False\n raw_ = raw.copy().pick_types(**picks)\n raw_.filter(10, 30, fir_design='firwin')\n\n # -- Error if no data channel\n for ch_type in ('misc', 'stim'):\n picks = {ch: ch == ch_type for ch in ch_types}\n raw_ = raw.copy().pick_types(**picks)\n pytest.raises(ValueError, raw_.filter, 10, 30)\n\n\[email protected]_testing_data\ndef test_crop():\n \"\"\"Test cropping raw files.\"\"\"\n # split a concatenated file to test a difficult case\n raw = concatenate_raws([read_raw_fif(f)\n for f in [fif_fname, fif_fname]])\n split_size = 10. # in seconds\n sfreq = raw.info['sfreq']\n nsamp = (raw.last_samp - raw.first_samp + 1)\n\n # do an annoying case (off-by-one splitting)\n tmins = np.r_[1., np.round(np.arange(0., nsamp - 1, split_size * sfreq))]\n tmins = np.sort(tmins)\n tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1]))\n tmaxs /= sfreq\n tmins /= sfreq\n raws = [None] * len(tmins)\n for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)):\n raws[ri] = raw.copy().crop(tmin, tmax)\n if ri < len(tmins) - 1:\n assert_allclose(\n raws[ri].times,\n raw.copy().crop(tmin, tmins[ri + 1], include_tmax=False).times)\n assert raws[ri]\n all_raw_2 = concatenate_raws(raws, preload=False)\n assert raw.first_samp == all_raw_2.first_samp\n assert raw.last_samp == all_raw_2.last_samp\n assert_array_equal(raw[:, :][0], all_raw_2[:, :][0])\n\n tmins = np.round(np.arange(0., nsamp - 1, split_size * sfreq))\n tmaxs = np.concatenate((tmins[1:] - 1, [nsamp - 1]))\n tmaxs /= sfreq\n tmins /= sfreq\n\n # going in revere order so the last fname is the first file (need it later)\n raws = [None] * len(tmins)\n for ri, (tmin, tmax) in enumerate(zip(tmins, tmaxs)):\n raws[ri] = raw.copy().crop(tmin, tmax)\n # test concatenation of split file\n all_raw_1 = concatenate_raws(raws, preload=False)\n\n all_raw_2 = raw.copy().crop(0, None)\n for ar in [all_raw_1, all_raw_2]:\n assert raw.first_samp == ar.first_samp\n assert raw.last_samp == ar.last_samp\n assert_array_equal(raw[:, :][0], ar[:, :][0])\n\n # test shape consistency of cropped raw\n data = np.zeros((1, 1002001))\n info = create_info(1, 1000)\n raw = RawArray(data, info)\n for tmin in range(0, 1001, 100):\n raw1 = raw.copy().crop(tmin=tmin, tmax=tmin + 2)\n assert raw1[:][0].shape == (1, 2001)\n\n # degenerate\n with pytest.raises(ValueError, match='No samples.*when include_tmax=Fals'):\n raw.crop(0, 0, include_tmax=False)\n\n\[email protected]_testing_data\ndef test_resample_equiv():\n \"\"\"Test resample (with I/O and multiple files).\"\"\"\n raw = read_raw_fif(fif_fname).crop(0, 1)\n raw_preload = raw.copy().load_data()\n for r in (raw, raw_preload):\n r.resample(r.info['sfreq'] / 4.)\n assert_allclose(raw._data, raw_preload._data)\n\n\[email protected]\[email protected]_testing_data\[email protected]('preload, n, npad', [\n (True, 512, 'auto'),\n (False, 512, 0),\n])\ndef test_resample(tmp_path, preload, n, npad):\n \"\"\"Test resample (with I/O and multiple files).\"\"\"\n raw = read_raw_fif(fif_fname)\n raw.crop(0, raw.times[n - 1])\n assert len(raw.times) == n\n if preload:\n raw.load_data()\n raw_resamp = raw.copy()\n sfreq = raw.info['sfreq']\n # test parallel on upsample\n raw_resamp.resample(sfreq * 2, n_jobs=2, npad=npad)\n assert raw_resamp.n_times == len(raw_resamp.times)\n raw_resamp.save(tmp_path / 'raw_resamp-raw.fif')\n raw_resamp = read_raw_fif(tmp_path / 'raw_resamp-raw.fif', preload=True)\n assert sfreq == raw_resamp.info['sfreq'] / 2\n assert raw.n_times == raw_resamp.n_times // 2\n assert raw_resamp.get_data().shape[1] == raw_resamp.n_times\n assert raw.get_data().shape[0] == raw_resamp._data.shape[0]\n # test non-parallel on downsample\n raw_resamp.resample(sfreq, n_jobs=1, npad=npad)\n assert raw_resamp.info['sfreq'] == sfreq\n assert raw.get_data().shape == raw_resamp._data.shape\n assert raw.first_samp == raw_resamp.first_samp\n assert raw.last_samp == raw.last_samp\n # upsampling then downsampling doubles resampling error, but this still\n # works (hooray). Note that the stim channels had to be sub-sampled\n # without filtering to be accurately preserved\n # note we have to treat MEG and EEG+STIM channels differently (tols)\n assert_allclose(raw.get_data()[:306, 200:-200],\n raw_resamp._data[:306, 200:-200],\n rtol=1e-2, atol=1e-12)\n assert_allclose(raw.get_data()[306:, 200:-200],\n raw_resamp._data[306:, 200:-200],\n rtol=1e-2, atol=1e-7)\n\n # now check multiple file support w/resampling, as order of operations\n # (concat, resample) should not affect our data\n raw1 = raw.copy()\n raw2 = raw.copy()\n raw3 = raw.copy()\n raw4 = raw.copy()\n raw1 = concatenate_raws([raw1, raw2])\n raw1.resample(10., npad=npad)\n raw3.resample(10., npad=npad)\n raw4.resample(10., npad=npad)\n raw3 = concatenate_raws([raw3, raw4])\n assert_array_equal(raw1._data, raw3._data)\n assert_array_equal(raw1._first_samps, raw3._first_samps)\n assert_array_equal(raw1._last_samps, raw3._last_samps)\n assert_array_equal(raw1._raw_lengths, raw3._raw_lengths)\n assert raw1.first_samp == raw3.first_samp\n assert raw1.last_samp == raw3.last_samp\n assert raw1.info['sfreq'] == raw3.info['sfreq']\n\n # smoke test crop after resample\n raw4.crop(tmin=raw4.times[1], tmax=raw4.times[-1])\n\n # test resampling of stim channel\n\n # basic decimation\n stim = [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]\n raw = RawArray([stim], create_info(1, len(stim), ['stim']))\n assert_allclose(raw.resample(8., npad=npad)._data,\n [[1, 1, 0, 0, 1, 1, 0, 0]])\n\n # decimation of multiple stim channels\n raw = RawArray(2 * [stim], create_info(2, len(stim), 2 * ['stim']))\n assert_allclose(raw.resample(8., npad=npad, verbose='error')._data,\n [[1, 1, 0, 0, 1, 1, 0, 0],\n [1, 1, 0, 0, 1, 1, 0, 0]])\n\n # decimation that could potentially drop events if the decimation is\n # done naively\n stim = [0, 0, 0, 1, 1, 0, 0, 0]\n raw = RawArray([stim], create_info(1, len(stim), ['stim']))\n assert_allclose(raw.resample(4., npad=npad)._data,\n [[0, 1, 1, 0]])\n\n # two events are merged in this case (warning)\n stim = [0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0]\n raw = RawArray([stim], create_info(1, len(stim), ['stim']))\n with pytest.warns(RuntimeWarning, match='become unreliable'):\n raw.resample(8., npad=npad)\n\n # events are dropped in this case (warning)\n stim = [0, 1, 1, 0, 0, 1, 1, 0]\n raw = RawArray([stim], create_info(1, len(stim), ['stim']))\n with pytest.warns(RuntimeWarning, match='become unreliable'):\n raw.resample(4., npad=npad)\n\n # test resampling events: this should no longer give a warning\n # we often have first_samp != 0, include it here too\n stim = [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1] # an event at end\n # test is on half the sfreq, but should work with trickier ones too\n o_sfreq, sfreq_ratio = len(stim), 0.5\n n_sfreq = o_sfreq * sfreq_ratio\n first_samp = len(stim) // 2\n raw = RawArray([stim], create_info(1, o_sfreq, ['stim']),\n first_samp=first_samp)\n events = find_events(raw)\n raw, events = raw.resample(n_sfreq, events=events, npad=npad)\n # Try index into raw.times with resampled events:\n raw.times[events[:, 0] - raw.first_samp]\n n_fsamp = int(first_samp * sfreq_ratio) # how it's calc'd in base.py\n # NB np.round used for rounding event times, which has 0.5 as corner case:\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html\n assert_array_equal(\n events,\n np.array([[np.round(1 * sfreq_ratio) + n_fsamp, 0, 1],\n [np.round(10 * sfreq_ratio) + n_fsamp, 0, 1],\n [np.minimum(np.round(15 * sfreq_ratio),\n raw._data.shape[1] - 1) + n_fsamp, 0, 1]]))\n\n # test copy flag\n stim = [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]\n raw = RawArray([stim], create_info(1, len(stim), ['stim']))\n raw_resampled = raw.copy().resample(4., npad=npad)\n assert (raw_resampled is not raw)\n raw_resampled = raw.resample(4., npad=npad)\n assert (raw_resampled is raw)\n\n # resample should still work even when no stim channel is present\n raw = RawArray(np.random.randn(1, 100), create_info(1, 100, ['eeg']))\n with raw.info._unlock():\n raw.info['lowpass'] = 50.\n raw.resample(10, npad=npad)\n assert raw.info['lowpass'] == 5.\n assert len(raw) == 10\n\n\ndef test_resample_stim():\n \"\"\"Test stim_picks argument.\"\"\"\n data = np.ones((2, 1000))\n info = create_info(2, 1000., ('eeg', 'misc'))\n raw = RawArray(data, info)\n raw.resample(500., stim_picks='misc')\n\n\[email protected]_testing_data\ndef test_hilbert():\n \"\"\"Test computation of analytic signal using hilbert.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n picks_meg = pick_types(raw.info, meg=True, exclude='bads')\n picks = picks_meg[:4]\n\n raw_filt = raw.copy()\n raw_filt.filter(10, 20, picks=picks, l_trans_bandwidth='auto',\n h_trans_bandwidth='auto', filter_length='auto',\n phase='zero', fir_window='blackman', fir_design='firwin')\n raw_filt_2 = raw_filt.copy()\n\n raw2 = raw.copy()\n raw3 = raw.copy()\n raw.apply_hilbert(picks, n_fft='auto')\n raw2.apply_hilbert(picks, n_fft='auto', envelope=True)\n\n # Test custom n_fft\n raw_filt.apply_hilbert(picks, n_fft='auto')\n n_fft = 2 ** int(np.ceil(np.log2(raw_filt_2.n_times + 1000)))\n raw_filt_2.apply_hilbert(picks, n_fft=n_fft)\n assert raw_filt._data.shape == raw_filt_2._data.shape\n assert_allclose(raw_filt._data[:, 50:-50], raw_filt_2._data[:, 50:-50],\n atol=1e-13, rtol=1e-2)\n with pytest.raises(ValueError, match='n_fft.*must be at least the number'):\n raw3.apply_hilbert(picks, n_fft=raw3.n_times - 100)\n\n env = np.abs(raw._data[picks, :])\n assert_allclose(env, raw2._data[picks, :], rtol=1e-2, atol=1e-13)\n\n\[email protected]_testing_data\ndef test_raw_copy():\n \"\"\"Test Raw copy.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n data, _ = raw[:, :]\n copied = raw.copy()\n copied_data, _ = copied[:, :]\n assert_array_equal(data, copied_data)\n assert sorted(raw.__dict__.keys()) == sorted(copied.__dict__.keys())\n\n raw = read_raw_fif(fif_fname, preload=False)\n data, _ = raw[:, :]\n copied = raw.copy()\n copied_data, _ = copied[:, :]\n assert_array_equal(data, copied_data)\n assert sorted(raw.__dict__.keys()) == sorted(copied.__dict__.keys())\n\n\n@requires_pandas\ndef test_to_data_frame():\n \"\"\"Test raw Pandas exporter.\"\"\"\n from pandas import Timedelta\n raw = read_raw_fif(test_fif_fname).crop(0, 1).load_data()\n _, times = raw[0, :10]\n df = raw.to_data_frame(index='time')\n assert ((df.columns == raw.ch_names).all())\n assert_array_equal(np.round(times * 1e3), df.index.values[:10])\n df = raw.to_data_frame(index=None)\n assert ('time' in df.columns)\n assert_array_equal(df.values[:, 1], raw._data[0] * 1e13)\n assert_array_equal(df.values[:, 3], raw._data[2] * 1e15)\n # test long format\n df_long = raw.to_data_frame(long_format=True)\n assert(len(df_long) == raw.get_data().size)\n expected = ('time', 'channel', 'ch_type', 'value')\n assert set(expected) == set(df_long.columns)\n # test bad time format\n with pytest.raises(ValueError, match='not a valid time format. Valid'):\n raw.to_data_frame(time_format='foo')\n # test time format error handling\n raw.set_meas_date(None)\n with pytest.warns(RuntimeWarning, match='Cannot convert to Datetime when'):\n df = raw.to_data_frame(time_format='datetime')\n assert isinstance(df['time'].iloc[0], Timedelta)\n\n\n@requires_pandas\[email protected]('time_format', (None, 'ms', 'timedelta', 'datetime'))\ndef test_to_data_frame_time_format(time_format):\n \"\"\"Test time conversion in epochs Pandas exporter.\"\"\"\n from pandas import Timedelta, Timestamp\n raw = read_raw_fif(test_fif_fname, preload=True)\n # test time_format\n df = raw.to_data_frame(time_format=time_format)\n dtypes = {None: np.float64, 'ms': np.int64, 'timedelta': Timedelta,\n 'datetime': Timestamp}\n assert isinstance(df['time'].iloc[0], dtypes[time_format])\n\n\ndef test_add_channels():\n \"\"\"Test raw splitting / re-appending channel types.\"\"\"\n rng = np.random.RandomState(0)\n raw = read_raw_fif(test_fif_fname).crop(0, 1).load_data()\n raw_nopre = read_raw_fif(test_fif_fname, preload=False)\n raw_eeg_meg = raw.copy().pick_types(meg=True, eeg=True)\n raw_eeg = raw.copy().pick_types(meg=False, eeg=True)\n raw_meg = raw.copy().pick_types(meg=True, eeg=False)\n raw_stim = raw.copy().pick_types(meg=False, eeg=False, stim=True)\n raw_new = raw_meg.copy().add_channels([raw_eeg, raw_stim])\n assert (\n all(ch in raw_new.ch_names\n for ch in list(raw_stim.ch_names) + list(raw_meg.ch_names))\n )\n raw_new = raw_meg.copy().add_channels([raw_eeg])\n\n assert (ch in raw_new.ch_names for ch in raw.ch_names)\n assert_array_equal(raw_new[:, :][0], raw_eeg_meg[:, :][0])\n assert_array_equal(raw_new[:, :][1], raw[:, :][1])\n assert (all(ch not in raw_new.ch_names for ch in raw_stim.ch_names))\n\n # Testing force updates\n raw_arr_info = create_info(['1', '2'], raw_meg.info['sfreq'], 'eeg')\n orig_head_t = raw_arr_info['dev_head_t']\n raw_arr = rng.randn(2, raw_eeg.n_times)\n raw_arr = RawArray(raw_arr, raw_arr_info)\n # This should error because of conflicts in Info\n raw_arr.info['dev_head_t'] = orig_head_t\n with pytest.raises(ValueError, match='mutually inconsistent dev_head_t'):\n raw_meg.copy().add_channels([raw_arr])\n raw_meg.copy().add_channels([raw_arr], force_update_info=True)\n # Make sure that values didn't get overwritten\n assert_object_equal(raw_arr.info['dev_head_t'], orig_head_t)\n # Make sure all variants work\n for simult in (False, True): # simultaneous adding or not\n raw_new = raw_meg.copy()\n if simult:\n raw_new.add_channels([raw_eeg, raw_stim])\n else:\n raw_new.add_channels([raw_eeg])\n raw_new.add_channels([raw_stim])\n for other in (raw_meg, raw_stim, raw_eeg):\n assert_allclose(\n raw_new.copy().pick_channels(other.ch_names).get_data(),\n other.get_data())\n\n # Now test errors\n raw_badsf = raw_eeg.copy()\n with raw_badsf.info._unlock():\n raw_badsf.info['sfreq'] = 3.1415927\n raw_eeg.crop(.5)\n\n pytest.raises(RuntimeError, raw_meg.add_channels, [raw_nopre])\n pytest.raises(RuntimeError, raw_meg.add_channels, [raw_badsf])\n pytest.raises(AssertionError, raw_meg.add_channels, [raw_eeg])\n pytest.raises(ValueError, raw_meg.add_channels, [raw_meg])\n pytest.raises(TypeError, raw_meg.add_channels, raw_badsf)\n\n\[email protected]_testing_data\ndef test_save(tmp_path):\n \"\"\"Test saving raw.\"\"\"\n temp_fname = tmp_path / 'test_raw.fif'\n shutil.copyfile(fif_fname, temp_fname)\n raw = read_raw_fif(temp_fname, preload=False)\n # can't write over file being read\n with pytest.raises(ValueError, match='to the same file'):\n raw.save(temp_fname)\n raw.load_data()\n # can't overwrite file without overwrite=True\n with pytest.raises(IOError, match='file exists'):\n raw.save(fif_fname)\n\n # test abspath support and annotations\n orig_time = _dt_to_stamp(raw.info['meas_date'])[0] + raw._first_time\n annot = Annotations([10], [5], ['test'], orig_time=orig_time)\n raw.set_annotations(annot)\n annot = raw.annotations\n new_fname = tmp_path / 'break_raw.fif'\n raw.save(new_fname, overwrite=True)\n new_raw = read_raw_fif(new_fname, preload=False)\n pytest.raises(ValueError, new_raw.save, new_fname)\n assert_array_almost_equal(annot.onset, new_raw.annotations.onset)\n assert_array_equal(annot.duration, new_raw.annotations.duration)\n assert_array_equal(annot.description, new_raw.annotations.description)\n assert annot.orig_time == new_raw.annotations.orig_time\n\n # test set_meas_date(None)\n raw.set_meas_date(None)\n raw.save(new_fname, overwrite=True)\n new_raw = read_raw_fif(new_fname, preload=False)\n assert new_raw.info['meas_date'] is None\n\n\[email protected]_testing_data\ndef test_annotation_crop(tmp_path):\n \"\"\"Test annotation sync after cropping and concatenating.\"\"\"\n annot = Annotations([5., 11., 15.], [2., 1., 3.], ['test', 'test', 'test'])\n raw = read_raw_fif(fif_fname, preload=False)\n raw.set_annotations(annot)\n r1 = raw.copy().crop(2.5, 7.5)\n r2 = raw.copy().crop(12.5, 17.5)\n r3 = raw.copy().crop(10., 12.)\n raw = concatenate_raws([r1, r2, r3]) # segments reordered\n assert_and_remove_boundary_annot(raw, 2)\n onsets = raw.annotations.onset\n durations = raw.annotations.duration\n # 2*5s clips combined with annotations at 2.5s + 2s clip, annotation at 1s\n assert_array_almost_equal(onsets[:3], [47.95, 52.95, 56.46], decimal=2)\n assert_array_almost_equal([2., 2.5, 1.], durations[:3], decimal=2)\n\n # test annotation clipping\n orig_time = _dt_to_stamp(raw.info['meas_date'])\n orig_time = orig_time[0] + orig_time[1] * 1e-6 + raw._first_time - 1.\n annot = Annotations([0., raw.times[-1]], [2., 2.], 'test', orig_time)\n with pytest.warns(RuntimeWarning, match='Limited .* expanding outside'):\n raw.set_annotations(annot)\n assert_allclose(raw.annotations.duration,\n [1., 1. + 1. / raw.info['sfreq']], atol=1e-3)\n\n # make sure we can overwrite the file we loaded when preload=True\n new_fname = tmp_path / 'break_raw.fif'\n raw.save(new_fname)\n new_raw = read_raw_fif(new_fname, preload=True)\n new_raw.save(new_fname, overwrite=True)\n\n\[email protected]_testing_data\ndef test_with_statement():\n \"\"\"Test with statement.\"\"\"\n for preload in [True, False]:\n with read_raw_fif(fif_fname, preload=preload) as raw_:\n print(raw_)\n\n\ndef test_compensation_raw(tmp_path):\n \"\"\"Test Raw compensation.\"\"\"\n raw_3 = read_raw_fif(ctf_comp_fname)\n assert raw_3.compensation_grade == 3\n data_3, times = raw_3[:, :]\n\n # data come with grade 3\n for ii in range(2):\n raw_3_new = raw_3.copy()\n if ii == 0:\n raw_3_new.load_data()\n raw_3_new.apply_gradient_compensation(3)\n assert raw_3_new.compensation_grade == 3\n data_new, times_new = raw_3_new[:, :]\n assert_array_equal(times, times_new)\n assert_array_equal(data_3, data_new)\n\n # change to grade 0\n raw_0 = raw_3.copy().apply_gradient_compensation(0)\n assert raw_0.compensation_grade == 0\n data_0, times_new = raw_0[:, :]\n assert_array_equal(times, times_new)\n assert (np.mean(np.abs(data_0 - data_3)) > 1e-12)\n # change to grade 1\n raw_1 = raw_0.copy().apply_gradient_compensation(1)\n assert raw_1.compensation_grade == 1\n data_1, times_new = raw_1[:, :]\n assert_array_equal(times, times_new)\n assert (np.mean(np.abs(data_1 - data_3)) > 1e-12)\n pytest.raises(ValueError, raw_1.apply_gradient_compensation, 33)\n raw_bad = raw_0.copy()\n raw_bad.add_proj(compute_proj_raw(raw_0, duration=0.5, verbose='error'))\n raw_bad.apply_proj()\n pytest.raises(RuntimeError, raw_bad.apply_gradient_compensation, 1)\n # with preload\n tols = dict(rtol=1e-12, atol=1e-25)\n raw_1_new = raw_3.copy().load_data().apply_gradient_compensation(1)\n assert raw_1_new.compensation_grade == 1\n data_1_new, times_new = raw_1_new[:, :]\n assert_array_equal(times, times_new)\n assert (np.mean(np.abs(data_1_new - data_3)) > 1e-12)\n assert_allclose(data_1, data_1_new, **tols)\n # change back\n raw_3_new = raw_1.copy().apply_gradient_compensation(3)\n data_3_new, times_new = raw_3_new[:, :]\n assert_allclose(data_3, data_3_new, **tols)\n raw_3_new = raw_1.copy().load_data().apply_gradient_compensation(3)\n data_3_new, times_new = raw_3_new[:, :]\n assert_allclose(data_3, data_3_new, **tols)\n\n for load in (False, True):\n for raw in (raw_0, raw_1):\n raw_3_new = raw.copy()\n if load:\n raw_3_new.load_data()\n raw_3_new.apply_gradient_compensation(3)\n assert raw_3_new.compensation_grade == 3\n data_3_new, times_new = raw_3_new[:, :]\n assert_array_equal(times, times_new)\n assert (np.mean(np.abs(data_3_new - data_1)) > 1e-12)\n assert_allclose(data_3, data_3_new, **tols)\n\n # Try IO with compensation\n temp_file = tmp_path / 'raw.fif'\n raw_3.save(temp_file, overwrite=True)\n for preload in (True, False):\n raw_read = read_raw_fif(temp_file, preload=preload)\n assert raw_read.compensation_grade == 3\n data_read, times_new = raw_read[:, :]\n assert_array_equal(times, times_new)\n assert_allclose(data_3, data_read, **tols)\n raw_read.apply_gradient_compensation(1)\n data_read, times_new = raw_read[:, :]\n assert_array_equal(times, times_new)\n assert_allclose(data_1, data_read, **tols)\n\n # Now save the file that has modified compensation\n # and make sure the compensation is the same as it was,\n # but that we can undo it\n\n # These channels have norm 1e-11/1e-12, so atol=1e-18 isn't awesome,\n # but it's due to the single precision of the info['comps'] leading\n # to inexact inversions with saving/loading (casting back to single)\n # in between (e.g., 1->3->1 will degrade like this)\n looser_tols = dict(rtol=1e-6, atol=1e-18)\n raw_1.save(temp_file, overwrite=True)\n for preload in (True, False):\n raw_read = read_raw_fif(temp_file, preload=preload, verbose=True)\n assert raw_read.compensation_grade == 1\n data_read, times_new = raw_read[:, :]\n assert_array_equal(times, times_new)\n assert_allclose(data_1, data_read, **looser_tols)\n raw_read.apply_gradient_compensation(3, verbose=True)\n data_read, times_new = raw_read[:, :]\n assert_array_equal(times, times_new)\n assert_allclose(data_3, data_read, **looser_tols)\n\n\n@requires_mne\ndef test_compensation_raw_mne(tmp_path):\n \"\"\"Test Raw compensation by comparing with MNE-C.\"\"\"\n def compensate_mne(fname, grad):\n tmp_fname = tmp_path / 'mne_ctf_test_raw.fif'\n cmd = ['mne_process_raw', '--raw', fname, '--save', tmp_fname,\n '--grad', str(grad), '--projoff', '--filteroff']\n run_subprocess(cmd)\n return read_raw_fif(tmp_fname, preload=True)\n\n for grad in [0, 2, 3]:\n raw_py = read_raw_fif(ctf_comp_fname, preload=True)\n raw_py.apply_gradient_compensation(grad)\n raw_c = compensate_mne(ctf_comp_fname, grad)\n assert_allclose(raw_py._data, raw_c._data, rtol=1e-6, atol=1e-17)\n assert raw_py.info['nchan'] == raw_c.info['nchan']\n for ch_py, ch_c in zip(raw_py.info['chs'], raw_c.info['chs']):\n for key in ('ch_name', 'coil_type', 'scanno', 'logno', 'unit',\n 'coord_frame', 'kind'):\n assert ch_py[key] == ch_c[key]\n for key in ('loc', 'unit_mul', 'range', 'cal'):\n assert_allclose(ch_py[key], ch_c[key])\n\n\[email protected]_testing_data\ndef test_drop_channels_mixin():\n \"\"\"Test channels-dropping functionality.\"\"\"\n raw = read_raw_fif(fif_fname, preload=True)\n drop_ch = raw.ch_names[:3]\n ch_names = raw.ch_names[3:]\n\n ch_names_orig = raw.ch_names\n dummy = raw.copy().drop_channels(drop_ch)\n assert ch_names == dummy.ch_names\n assert ch_names_orig == raw.ch_names\n assert len(ch_names_orig) == raw._data.shape[0]\n\n raw.drop_channels(drop_ch)\n assert ch_names == raw.ch_names\n assert len(ch_names) == len(raw._cals)\n assert len(ch_names) == raw._data.shape[0]\n\n # Test that dropping all channels a projector applies to will lead to the\n # removal of said projector.\n raw = read_raw_fif(fif_fname)\n n_projs = len(raw.info['projs'])\n eeg_names = raw.info['projs'][-1]['data']['col_names']\n with pytest.raises(RuntimeError, match='loaded'):\n raw.copy().apply_proj().drop_channels(eeg_names)\n raw.load_data().drop_channels(eeg_names) # EEG proj\n assert len(raw.info['projs']) == n_projs - 1\n\n\[email protected]_testing_data\[email protected]('preload', (True, False))\ndef test_pick_channels_mixin(preload):\n \"\"\"Test channel-picking functionality.\"\"\"\n raw = read_raw_fif(fif_fname, preload=preload)\n raw_orig = raw.copy()\n ch_names = raw.ch_names[:3]\n\n ch_names_orig = raw.ch_names\n dummy = raw.copy().pick_channels(ch_names)\n assert ch_names == dummy.ch_names\n assert ch_names_orig == raw.ch_names\n assert len(ch_names_orig) == raw.get_data().shape[0]\n\n raw.pick_channels(ch_names) # copy is False\n assert ch_names == raw.ch_names\n assert len(ch_names) == len(raw._cals)\n assert len(ch_names) == raw.get_data().shape[0]\n with pytest.raises(ValueError, match='must be'):\n raw.pick_channels(ch_names[0])\n\n assert_allclose(raw[:][0], raw_orig[:3][0])\n\n\[email protected]_testing_data\ndef test_equalize_channels():\n \"\"\"Test equalization of channels.\"\"\"\n raw1 = read_raw_fif(fif_fname, preload=True)\n\n raw2 = raw1.copy()\n ch_names = raw1.ch_names[2:]\n raw1.drop_channels(raw1.ch_names[:1])\n raw2.drop_channels(raw2.ch_names[1:2])\n my_comparison = [raw1, raw2]\n my_comparison = equalize_channels(my_comparison)\n for e in my_comparison:\n assert ch_names == e.ch_names\n\n\ndef test_memmap(tmp_path):\n \"\"\"Test some interesting memmapping cases.\"\"\"\n # concatenate_raw\n memmaps = [str(tmp_path / str(ii)) for ii in range(3)]\n raw_0 = read_raw_fif(test_fif_fname, preload=memmaps[0])\n assert raw_0._data.filename == memmaps[0]\n raw_1 = read_raw_fif(test_fif_fname, preload=memmaps[1])\n assert raw_1._data.filename == memmaps[1]\n raw_0.append(raw_1, preload=memmaps[2])\n assert raw_0._data.filename == memmaps[2]\n # add_channels\n orig_data = raw_0[:][0]\n new_ch_info = pick_info(raw_0.info, [0])\n new_ch_info['chs'][0]['ch_name'] = 'foo'\n new_ch_info._update_redundant()\n new_data = np.linspace(0, 1, len(raw_0.times))[np.newaxis]\n ch = RawArray(new_data, new_ch_info)\n raw_0.add_channels([ch])\n if sys.platform == 'darwin':\n assert not hasattr(raw_0._data, 'filename')\n else:\n assert raw_0._data.filename == memmaps[2]\n assert_allclose(orig_data, raw_0[:-1][0], atol=1e-7)\n assert_allclose(new_data, raw_0[-1][0], atol=1e-7)\n\n # now let's see if .copy() actually works; it does, but eventually\n # we should make it optionally memmap to a new filename rather than\n # create an in-memory version (filename=None)\n raw_0 = read_raw_fif(test_fif_fname, preload=memmaps[0])\n assert raw_0._data.filename == memmaps[0]\n assert raw_0._data[:1, 3:5].all()\n raw_1 = raw_0.copy()\n assert isinstance(raw_1._data, np.memmap)\n assert raw_1._data.filename is None\n raw_0._data[:] = 0.\n assert not raw_0._data.any()\n assert raw_1._data[:1, 3:5].all()\n # other things like drop_channels and crop work but do not use memmapping,\n # eventually we might want to add support for some of these as users\n # require them.\n\n\n# These are slow on Azure Windows so let's do a subset\[email protected]('kind', [\n 'file',\n pytest.param('bytes', marks=pytest.mark.slowtest),\n])\[email protected]('preload', [\n True,\n pytest.param(str, marks=pytest.mark.slowtest),\n])\[email protected]('split', [\n False,\n pytest.param(True, marks=pytest.mark.slowtest),\n])\ndef test_file_like(kind, preload, split, tmp_path):\n \"\"\"Test handling with file-like objects.\"\"\"\n if split:\n fname = tmp_path / 'test_raw.fif'\n read_raw_fif(test_fif_fname).save(fname, split_size='5MB')\n assert op.isfile(fname)\n assert op.isfile(str(fname)[:-4] + '-1.fif')\n else:\n fname = test_fif_fname\n if preload is str:\n preload = str(tmp_path / 'memmap')\n with open(str(fname), 'rb') as file_fid:\n fid = BytesIO(file_fid.read()) if kind == 'bytes' else file_fid\n assert not fid.closed\n assert not file_fid.closed\n with pytest.raises(ValueError, match='preload must be used with file'):\n read_raw_fif(fid)\n assert not fid.closed\n assert not file_fid.closed\n # Use test_preloading=False but explicitly pass the preload type\n # so that we don't bother testing preload=False\n kwargs = dict(fname=fid, preload=preload, on_split_missing='ignore',\n test_preloading=False, test_kwargs=False)\n _test_raw_reader(read_raw_fif, **kwargs)\n assert not fid.closed\n assert not file_fid.closed\n assert file_fid.closed\n\n\ndef test_str_like():\n \"\"\"Test handling with str-like objects.\"\"\"\n fname = pathlib.Path(test_fif_fname)\n raw_path = read_raw_fif(fname, preload=True)\n raw_str = read_raw_fif(test_fif_fname, preload=True)\n assert_allclose(raw_path._data, raw_str._data)\n\n\[email protected]('fname', [\n test_fif_fname,\n testing._pytest_param(fif_fname),\n testing._pytest_param(ms_fname),\n])\ndef test_bad_acq(fname):\n \"\"\"Test handling of acquisition errors.\"\"\"\n # see gh-7844\n raw = read_raw_fif(fname, allow_maxshield='yes').load_data()\n with open(fname, 'rb') as fid:\n for ent in raw._raw_extras[0]['ent']:\n fid.seek(ent.pos, 0)\n tag = _read_tag_header(fid)\n # hack these, others (kind, type) should be correct\n tag.pos, tag.next = ent.pos, ent.next\n assert tag == ent\n\n\[email protected]_testing_data\[email protected](sys.platform not in ('darwin', 'linux'),\n reason='Needs proper symlinking')\ndef test_split_symlink(tmp_path):\n \"\"\"Test split files with symlinks.\"\"\"\n # regression test for gh-9221\n (tmp_path / 'first').mkdir()\n first = tmp_path / 'first' / 'test_raw.fif'\n raw = read_raw_fif(fif_fname).pick('meg').load_data()\n raw.save(first, buffer_size_sec=1, split_size='10MB', verbose=True)\n second = str(first)[:-4] + '-1.fif'\n assert op.isfile(second)\n assert not op.isfile(str(first)[:-4] + '-2.fif')\n (tmp_path / 'a').mkdir()\n (tmp_path / 'b').mkdir()\n new_first = tmp_path / 'a' / 'test_raw.fif'\n new_second = tmp_path / 'b' / 'test_raw-1.fif'\n shutil.move(first, new_first)\n shutil.move(second, new_second)\n os.symlink(new_first, first)\n os.symlink(new_second, second)\n raw_new = read_raw_fif(first)\n assert_allclose(raw_new.get_data(), raw.get_data())\n\n\[email protected]_testing_data\ndef test_corrupted(tmp_path):\n \"\"\"Test that a corrupted file can still be read.\"\"\"\n # Must be a file written by Neuromag, not us, since we don't write the dir\n # at the end, so use the skip one (straight from acq).\n raw = read_raw_fif(skip_fname)\n with open(skip_fname, 'rb') as fid:\n tag = read_tag_info(fid)\n tag = read_tag(fid)\n dirpos = int(tag.data)\n assert dirpos == 12641532\n fid.seek(0)\n data = fid.read(dirpos)\n bad_fname = tmp_path / 'test_raw.fif'\n with open(bad_fname, 'wb') as fid:\n fid.write(data)\n with pytest.warns(RuntimeWarning, match='.*tag directory.*corrupt.*'):\n raw_bad = read_raw_fif(bad_fname)\n assert_allclose(raw.get_data(), raw_bad.get_data())\n\n\[email protected]_testing_data\ndef test_expand_user(tmp_path, monkeypatch):\n \"\"\"Test that we're expanding `~` before reading and writing.\"\"\"\n monkeypatch.setenv('HOME', str(tmp_path))\n monkeypatch.setenv('USERPROFILE', str(tmp_path)) # Windows\n\n path_in = Path(fif_fname)\n path_out = tmp_path / path_in.name\n path_home = Path('~') / path_in.name\n\n shutil.copyfile(\n src=path_in,\n dst=path_out\n )\n\n raw = read_raw_fif(fname=path_home, preload=True)\n raw.save(fname=path_home, overwrite=True)\n"
]
| [
[
"numpy.concatenate",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.dot",
"numpy.zeros",
"numpy.random.RandomState",
"numpy.round",
"numpy.testing.assert_array_equal",
"numpy.ones",
"numpy.random.randn",
"numpy.may_share_memory",
"numpy.testing.assert_array_almost_equal",
"numpy.diff",
"numpy.arange",
"numpy.sort",
"numpy.abs",
"numpy.log2"
]
]
|
louity/scattering_transform | [
"1cbf467ff3735f1a91fc512a3fe2b0fb3bccda42"
]
| [
"scattering/scattering1d/filter_bank.py"
]
| [
"import numpy as np\nimport torch\nimport math\nimport warnings\n\n\ndef adaptative_choice_P(sigma, eps=1e-7):\n \"\"\"\n Adaptive choice of the value of the number of periods in the frequency\n domain used to compute the FFT of a Morlet wavelet.\n\n This function considers a Morlet wavelet defined as the sum\n of\n * a Gabor term hat psi(omega) = hat g_{sigma}(omega - xi)\n where 0 < xi < 1 is some frequency and g_{sigma} is\n the Gaussian window defined in Fourier by\n hat g_{sigma}(omega) = e^{-omega^2/(2 sigma^2)}\n * a low pass term \\\\hat \\\\phi which is proportional to \\\\hat g_{\\\\sigma}.\n\n If \\\\sigma is too large, then these formula will lead to discontinuities\n in the frequency interval [0, 1] (which is the interval used by numpy.fft).\n We therefore choose a larger integer P >= 1 such that at the boundaries\n of the FFTs of both filters on the interval [1-P, P], the magnitude of\n the entries is below the required machine precision.\n Mathematically, this means we would need P to satisfy the relations:\n\n |\\\\hat \\\\psi(P)| <= eps and |\\\\hat \\\\phi(1-P)| <= eps\n\n Since 0 <= xi <= 1, the latter implies the former. Hence the formula which\n is easily derived using the explicit formula for g_{\\\\sigma} in Fourier.\n\n Parameters\n ----------\n sigma: float\n Positive number controlling the bandwidth of the filters\n eps : float, optional\n Positive number containing required precision. Defaults to 1e-7\n\n Returns\n -------\n P : int\n integer controlling the number of periods used to ensure the\n periodicity of the final Morlet filter in the frequency interval\n [0, 1[. The value of P will lead to the use of the frequency\n interval [1-P, P[, so that there are 2*P - 1 periods.\n \"\"\"\n val = math.sqrt(-2 * (sigma**2) * math.log(eps))\n P = int(math.ceil(val + 1))\n return P\n\n\ndef periodize_filter_fft(h_fft, nperiods=1):\n \"\"\"\n Computes a periodization of a filter provided in the FFT domain.\n\n Parameters\n ----------\n h_fft : array_like\n complex numpy array of shape (N*n_periods,)\n n_periods: int, optional\n Number of periods which should be used to periodize\n\n Returns\n -------\n v_fft : array_like\n complex numpy array of size (N,), which is a periodization of\n h_fft as described in the formula:\n v_fft[k] = sum_{i=0}^{n_periods - 1} h_fft[i * N + k]\n \"\"\"\n N = h_fft.shape[0] // nperiods\n v_fft = h_fft.reshape(nperiods, N).mean(axis=0)\n return v_fft\n\n\ndef morlet1D(N, xi, sigma, normalize='l1', P_max=5, eps=1e-7):\n \"\"\"\n Computes the FFT of a Morlet filter.\n\n A Morlet filter is the sum of a Gabor filter and a low-pass filter\n to ensure that the sum has exactly zero mean in the temporal domain.\n It is defined by the following formula in time:\n psi(t) = g_{sigma}(t) (e^{i xi t} - beta)\n where g_{sigma} is a Gaussian envelope, xi is a frequency and beta is\n the cancelling parameter.\n\n Parameters\n ----------\n N : int\n size of the temporal support\n xi : float\n central frequency (in [0, 1])\n sigma : float\n bandwidth parameter\n normalize : string, optional\n normalization types for the filters. Defaults to 'l1'.\n Supported normalizations are 'l1' and 'l2' (understood in time domain).\n P_max: int, optional\n integer controlling the maximal number of periods to use to ensure\n the periodicity of the FFT. (At most 2*P_max - 1 periods are used,\n to ensure an equal distribution around 0.5). Defaults to 5\n Should be >= 1\n eps : float\n required machine precision (to choose the adequate P)\n\n Returns\n -------\n morlet_fft : array_like\n numpy array of size (N,) containing the FFT of the Morlet\n filter at the frequencies given by np.fft.fftfreq(N).\n \"\"\"\n if type(P_max) != int:\n raise ValueError('P_max should be an int, got {}'.format(type(P_max)))\n if P_max < 1:\n raise ValueError('P_max should be non-negative, got {}'.format(P_max))\n # Find the adequate value of P\n P = min(adaptative_choice_P(sigma, eps=eps), P_max)\n # Define the frequencies over [1-P, P[\n freqs = np.arange((1 - P) * N, P * N, dtype=float) / float(N)\n if P == 1:\n # in this case, make sure that there is continuity around 0\n # by using the interval [-0.5, 0.5]\n freqs_low = np.fft.fftfreq(N)\n elif P > 1:\n freqs_low = freqs\n else:\n raise ValueError('P should be > 0, got ', P)\n # define the gabor at freq xi and the low-pass, both of width sigma\n gabor_fft = np.exp(-(freqs - xi)**2 / (2 * sigma**2))\n low_pass_fft = np.exp(-(freqs_low**2) / (2 * sigma**2))\n # discretize in signal <=> periodize in Fourier\n gabor_fft = periodize_filter_fft(gabor_fft, nperiods=2 * P - 1)\n low_pass_fft = periodize_filter_fft(low_pass_fft, nperiods=2 * P - 1)\n # find the summation factor to ensure that morlet_fft[0] = 0.\n kappa = gabor_fft[0] / low_pass_fft[0]\n morlet_fft = gabor_fft - kappa * low_pass_fft\n # normalize the Morlet if necessary\n morlet_fft *= get_normalizing_factor(morlet_fft, normalize=normalize)\n return morlet_fft\n\n\ndef get_normalizing_factor(h_fft, normalize='l1'):\n \"\"\"\n Computes the desired normalization factor for a filter defined in Fourier.\n\n Parameters\n ----------\n h_fft : array_like\n numpy vector containing the FFT of a filter\n normalized : string, optional\n desired normalization type, either 'l1' or 'l2'. Defaults to 'l1'.\n\n Returns\n -------\n norm_factor : float\n such that h_fft * norm_factor is the adequately normalized vector.\n \"\"\"\n h_real = np.fft.ifft(h_fft)\n if np.abs(h_real).sum() < 1e-7:\n raise ValueError('Zero division error is very likely to occur, ' +\n 'aborting computations now.')\n if normalize == 'l1':\n norm_factor = 1. / (np.abs(h_real).sum())\n elif normalize == 'l2':\n norm_factor = 1. / np.sqrt((np.abs(h_real)**2).sum())\n else:\n raise ValueError(\"Supported normalizations only include 'l1' and 'l2'\")\n return norm_factor\n\n\ndef gauss1D(N, sigma, normalize='l1', P_max=5, eps=1e-7):\n \"\"\"\n Computes the FFT of a low pass gaussian window.\n\n \\\\hat g_{\\\\sigma}(\\\\omega) = e^{-\\\\omega^2 / 2 \\\\sigma^2}\n\n Parameters\n ----------\n N : int\n size of the temporal support\n sigma : float\n bandwidth parameter\n normalize : string, optional\n normalization types for the filters. Defaults to 'l1'\n Supported normalizations are 'l1' and 'l2' (understood in time domain).\n P_max : int, optional\n integer controlling the maximal number of periods to use to ensure\n the periodicity of the FFT. (At most 2*P_max - 1 periods are used,\n to ensure an equal distribution around 0.5). Defaults to 5\n Should be >= 1\n eps : float, optional\n required machine precision (to choose the adequate P)\n\n Returns\n -------\n g_fft : array_like\n numpy array of size (N,) containing the FFT of the filter (with the\n frequencies in the np.fft.fftfreq convention).\n \"\"\"\n # Find the adequate value of P\n if type(P_max) != int:\n raise ValueError('P_max should be an int, got {}'.format(type(P_max)))\n if P_max < 1:\n raise ValueError('P_max should be non-negative, got {}'.format(P_max))\n P = min(adaptative_choice_P(sigma, eps=eps), P_max)\n # switch cases\n if P == 1:\n freqs_low = np.fft.fftfreq(N)\n elif P > 1:\n freqs_low = np.arange((1 - P) * N, P * N, dtype=float) / float(N)\n else:\n raise ValueError('P should be an integer > 0, got {}'.format(P))\n # define the low pass\n g_fft = np.exp(-freqs_low**2 / (2 * sigma**2))\n # periodize it\n g_fft = periodize_filter_fft(g_fft, nperiods=2 * P - 1)\n # normalize the signal\n g_fft *= get_normalizing_factor(g_fft, normalize=normalize)\n # return the FFT\n return g_fft\n\n\ndef compute_sigma_psi(xi, Q, r=math.sqrt(0.5)):\n \"\"\"\n Computes the frequential width sigma for a Morlet filter of frequency xi\n belonging to a family with Q wavelets.\n\n The frequential width is adapted so that the intersection of the\n frequency responses of the next filter occurs at a r-bandwidth specified\n by r, to ensure a correct coverage of the whole frequency axis.\n\n Parameters\n ----------\n xi : float\n frequency of the filter in [0, 1]\n Q : int\n number of filters per octave, Q is an integer >= 1\n r : float, optional\n Positive parameter defining the bandwidth to use.\n Should be < 1. We recommend keeping the default value.\n The larger r, the larger the filters in frequency domain.\n\n Returns\n -------\n sigma : float\n frequential width of the Morlet wavelet.\n\n Refs\n ----\n Convolutional operators in the time-frequency domain, V. Lostanlen,\n PhD Thesis, 2017\n https://tel.archives-ouvertes.fr/tel-01559667\n \"\"\"\n factor = 1. / math.pow(2, 1. / Q)\n term1 = (1 - factor) / (1 + factor)\n term2 = 1. / math.sqrt(2 * math.log(1. / r))\n return xi * term1 * term2\n\n\ndef compute_temporal_support(h_fft, criterion_amplitude=1e-3):\n \"\"\"\n Computes the (half) temporal support of a family of centered,\n symmetric filters h provided in the Fourier domain\n\n This function computes the support T which is the smallest integer\n such that for all signals x and all filters h,\n\n \\\\| x \\\\conv h - x \\\\conv h_{[-T, T]} \\\\|_{\\\\infty} \\\\leq \\\\epsilon\n \\\\| x \\\\|_{\\\\infty} (1)\n\n where 0<\\\\epsilon<1 is an acceptable error, and h_{[-T, T]} denotes the\n filter h whose support is restricted in the interval [-T, T]\n\n The resulting value T used to pad the signals to avoid boundary effects\n and numerical errors.\n\n If the support is too small, no such T might exist.\n In this case, T is defined as the half of the support of h, and a\n UserWarning is raised.\n\n Parameters\n ----------\n h_fft : array_like\n a numpy array of size batch x time, where each row contains the\n FFT of a filter which is centered and whose absolute value is\n symmetric\n criterion_amplitude : float, optional\n value \\\\epsilon controlling the numerical\n error. The larger criterion_amplitude, the smaller the temporal\n support and the larger the numerical error. Defaults to 1e-3\n\n Returns\n -------\n t_max : int\n temporal support which ensures (1) for all rows of h_fft\n\n \"\"\"\n h = np.fft.ifft(h_fft, axis=1)\n half_support = h.shape[1] // 2\n # compute ||h - h_[-T, T]||_1\n l1_residual = np.fliplr(\n np.cumsum(np.fliplr(np.abs(h)[:, :half_support]), axis=1))\n # find the first point above criterion_amplitude\n if np.any(np.max(l1_residual, axis=0) <= criterion_amplitude):\n # if it is possible\n T = np.min(\n np.where(np.max(l1_residual, axis=0) <= criterion_amplitude)[0])\\\n + 1\n else:\n # if there is none:\n T = half_support\n # Raise a warning to say that there will be border effects\n warnings.warn('Signal support is too small to avoid border effects')\n return T\n\n\ndef get_max_dyadic_subsampling(xi, sigma, alpha=5.):\n \"\"\"\n Computes the maximal dyadic subsampling which is possible for a Gabor\n filter of frequency xi and width sigma\n\n Finds the maximal integer j such that:\n omega_0 < 2^{-(j + 1)}\n where omega_0 is the boundary of the filter, defined as\n omega_0 = xi + alpha * sigma\n\n This ensures that the filter can be subsampled by a factor 2^j without\n aliasing.\n\n We use the same formula for Gabor and Morlet filters.\n\n Parameters\n ----------\n xi : float\n frequency of the filter in [0, 1]\n sigma : float\n frequential width of the filter\n alpha : float, optional\n parameter controlling the error done in the aliasing.\n The larger alpha, the smaller the error. Defaults to 5.\n\n Returns\n -------\n j : int\n integer such that 2^j is the maximal subsampling accepted by the\n Gabor filter without aliasing.\n \"\"\"\n upper_bound = min(xi + alpha * sigma, 0.5)\n j = math.floor(-math.log2(upper_bound)) - 1\n j = int(j)\n return j\n\n\ndef move_one_dyadic_step(cv, Q, alpha=5.):\n \"\"\"\n Computes the parameters of the next wavelet on the low frequency side,\n based on the parameters of the current wavelet.\n\n This function is used in the loop defining all the filters, starting\n at the wavelet frequency and then going to the low frequencies by\n dyadic steps. This makes the loop in compute_params_filterbank much\n simpler to read.\n\n The steps are defined as:\n xi_{n+1} = 2^{-1/Q} xi_n\n sigma_{n+1} = 2^{-1/Q} sigma_n\n\n Parameters\n ----------\n cv : dictionary\n stands for current_value. Is a dictionary with keys:\n *'key': a tuple (j, n) where n is a counter and j is the maximal\n dyadic subsampling accepted by this wavelet.\n *'xi': central frequency of the wavelet\n *'sigma': width of the wavelet\n Q : int\n number of wavelets per octave. Controls the relationship between\n the frequency and width of the current wavelet and the next wavelet.\n alpha : float, optional\n tolerance parameter for the aliasing. The larger alpha,\n the more conservative the algorithm is. Defaults to 5.\n\n Returns\n -------\n new_cv : dictionary\n a dictionary with the same keys as the ones listed for cv,\n whose values are updated\n \"\"\"\n factor = 1. / math.pow(2., 1. / Q)\n n = cv['key'][1]\n new_cv = {'xi': cv['xi'] * factor, 'sigma': cv['sigma'] * factor}\n # compute the new j\n j = get_max_dyadic_subsampling(new_cv['xi'], new_cv['sigma'], alpha=alpha)\n new_cv['key'] = (j, n + 1)\n return new_cv\n\n\ndef compute_xi_max(Q):\n \"\"\"\n Computes the maximal xi to use for the Morlet family, depending on Q.\n\n Parameters\n ----------\n Q : int\n number of wavelets per octave (integer >= 1)\n\n Returns\n -------\n xi_max : float\n largest frequency of the wavelet frame.\n \"\"\"\n xi_max = max(1. / (1. + math.pow(2., 3. / Q)), 0.35)\n return xi_max\n\n\ndef compute_params_filterbank(sigma_low, Q, r_psi=math.sqrt(0.5), alpha=5.):\n \"\"\"\n Computes the parameters of a Morlet wavelet filterbank.\n\n This family is defined by constant ratios between the frequencies and\n width of adjacent filters, up to a minimum frequency where the frequencies\n are translated.\n This ensures that the low-pass filter has the largest temporal support\n among all filters, while preserving the coverage of the whole frequency\n axis.\n\n The keys of the dictionaries are tuples of integers (j, n) where n is a\n counter (starting at 0 for the highest frequency filter) and j is the\n maximal dyadic subsampling accepted by this filter.\n\n Parameters\n ----------\n sigma_low : float\n frequential width of the low-pass filter. This acts as a\n lower-bound on the frequential widths of the band-pass filters,\n so as to ensure that the low-pass filter has the largest temporal\n support among all filters.\n Q : int\n number of wavelets per octave.\n r_psi : float, optional\n Should be >0 and <1. Controls the redundancy of the filters\n (the larger r_psi, the larger the overlap between adjacent wavelets).\n Defaults to sqrt(0.5).\n alpha : float, optional\n tolerance factor for the aliasing after subsampling.\n The larger alpha, the more conservative the value of maximal\n subsampling is. Defaults to 5.\n\n Returns\n -------\n xi : dictionary\n dictionary containing the central frequencies of the wavelets.\n sigma : dictionary\n dictionary containing the frequential widths of the wavelets.\n\n Refs\n ----\n Convolutional operators in the time-frequency domain, 2.1.3, V. Lostanlen,\n PhD Thesis, 2017\n https://tel.archives-ouvertes.fr/tel-01559667\n \"\"\"\n xi_max = compute_xi_max(Q)\n sigma_max = compute_sigma_psi(xi_max, Q, r=r_psi)\n\n xi = {}\n sigma = {}\n\n if sigma_max <= sigma_low:\n # in this exceptional case, we will not go through the loop, so\n # we directly assign\n last_xi = sigma_max\n n = 0\n else:\n # fill all the dyadic wavelets as long as possible\n current = {'key': (0, 0), 'xi': xi_max, 'sigma': sigma_max}\n while current['sigma'] > sigma_low: # while we can attribute something\n xi[current['key']] = current['xi']\n sigma[current['key']] = current['sigma']\n current = move_one_dyadic_step(current, Q, alpha=alpha)\n # get the last key\n last_key = max(xi.keys())\n n = last_key[1] + 1\n last_xi = xi[last_key]\n # fill num_interm wavelets between last_xi and 0, both excluded\n num_intermediate = Q - 1\n for q in range(1, num_intermediate + 1):\n factor = (num_intermediate + 1. - q) / (num_intermediate + 1.)\n new_xi = factor * last_xi\n new_sigma = sigma_low\n j = get_max_dyadic_subsampling(new_xi, new_sigma, alpha=alpha)\n key = (j, n)\n xi[key] = new_xi\n sigma[key] = new_sigma\n n += 1\n # return results\n return xi, sigma\n\n\ndef calibrate_scattering_filters(J, Q, r_psi=math.sqrt(0.5), sigma0=0.1,\n alpha=5.):\n \"\"\"\n Calibrates the parameters of the filters used at the 1st and 2nd orders\n of the scattering transform.\n\n These filterbanks share the same low-pass filterbank, but use a\n different Q: Q_1 = Q and Q_2 = 1.\n\n The dictionaries for the band-pass filters have keys which are 2-tuples\n of the type (j, n), where n is an integer >=0 counting the filters (for\n identification purposes) and j is an integer >= 0 denoting the maximal\n subsampling 2**j which can be performed on a signal convolved with this\n filter without aliasing.\n\n Parameters\n ----------\n J : int\n maximal scale of the scattering (controls the number of wavelets)\n Q : int\n number of wavelets per octave for the first order\n r_psi : float, optional\n Should be >0 and <1. Controls the redundancy of the filters\n (the larger r_psi, the larger the overlap between adjacent wavelets).\n Defaults to sqrt(0.5)\n sigma0 : float, optional\n frequential width of the low-pass filter at scale J=0\n (the subsequent widths are defined by sigma_J = sigma0 / 2^J).\n Defaults to 1e-1\n alpha : float, optional\n tolerance factor for the aliasing after subsampling.\n The larger alpha, the more conservative the value of maximal\n subsampling is. Defaults to 5.\n\n Returns\n -------\n sigma_low : float\n frequential width of the low-pass filter\n xi1 : dictionary\n dictionary containing the center frequencies of the first order\n filters. See above for a decsription of the keys.\n sigma1 : dictionary\n dictionary containing the frequential width of the first order\n filters. See above for a description of the keys.\n xi2 : dictionary\n dictionary containing the center frequencies of the second order\n filters. See above for a decsription of the keys.\n sigma2 : dictionary\n dictionary containing the frequential width of the second order\n filters. See above for a description of the keys.\n \"\"\"\n if Q < 1:\n raise ValueError('Q should always be >= 1, got {}'.format(Q))\n sigma_low = sigma0 / math.pow(2, J) # width of the low pass\n xi1, sigma1 = compute_params_filterbank(sigma_low, Q, r_psi=r_psi,\n alpha=alpha)\n xi2, sigma2 = compute_params_filterbank(sigma_low, 1, r_psi=r_psi,\n alpha=alpha)\n return sigma_low, xi1, sigma1, xi2, sigma2\n\n\ndef scattering_filter_factory(J_support, J_scattering, Q, r_psi=math.sqrt(0.5),\n criterion_amplitude=1e-3, normalize='l1',\n to_torch=False, max_subsampling=None,\n sigma0=0.1, alpha=5., P_max=5, eps=1e-7,\n **kwargs):\n \"\"\"\n Builds in Fourier the Morlet filters used for the scattering transform.\n\n Each single filter is provided as a dictionary with the following keys:\n * 'xi': central frequency, defaults to 0 for low-pass filters.\n * 'sigma': frequential width\n * k where k is an integer bounded below by 0. The maximal value for k\n depends on the type of filter, it is dynamically chosen depending\n on max_subsampling and the characteristics of the filters.\n Each value for k is an array (or tensor) of size 2**(J_support - k)\n containing the FFT of the filter after subsampling by 2**k\n\n Parameters\n ----------\n J_support : int\n 2**J_support is the desired support size of the filters\n J_scattering : int\n parameter for the scattering transform (2**J_scattering\n corresponds to the averaging support of the low-pass filter)\n Q : int\n number of wavelets per octave at the first order. For audio signals,\n a value Q >= 12 is recommended in order to separate partials.\n r_psi : float, optional\n Should be >0 and <1. Controls the redundancy of the filters\n (the larger r_psi, the larger the overlap between adjacent wavelets).\n Defaults to sqrt(0.5).\n criterion_amplitude : float, optional\n Represents the numerical error which is allowed to be lost after\n convolution and padding. Defaults to 1e-3.\n normalize : string, optional\n Normalization convention for the filters (in the\n temporal domain). Supported values include 'l1' and 'l2'; a ValueError\n is raised otherwise. Defaults to 'l1'.\n to_torch: boolean, optional\n whether the filters should be provided as torch\n tensors (true) or numpy arrays (false). Defaults to False.\n max_subsampling: int or None, optional\n maximal dyadic subsampling to compute, in order\n to save computation time if it is not required. Defaults to None, in\n which case this value is dynamically adjusted depending on the filters.\n sigma0 : float, optional\n parameter controlling the frequential width of the\n low-pass filter at J_scattering=0; at a an absolute J_scattering, it\n is equal to sigma0 / 2**J_scattering. Defaults to 1e-1\n alpha : float, optional\n tolerance factor for the aliasing after subsampling.\n The larger alpha, the more conservative the value of maximal\n subsampling is. Defaults to 5.\n P_max : int, optional\n maximal number of periods to use to make sure that the\n FFT of the filters is periodic. P_max = 5 is more than enough for\n double precision. Defaults to 5. Should be >= 1\n eps : float, optional\n required machine precision for the periodization (single\n floating point is enough for deep learning applications).\n Defaults to 1e-7\n\n Returns\n -------\n phi_fft : dictionary\n a dictionary containing the low-pass filter at all possible\n subsamplings. See above for a description of the dictionary structure.\n The possible subsamplings are controlled by the inputs they can\n receive, which correspond to the subsamplings performed on top of the\n 1st and 2nd order transforms.\n psi1_fft : dictionary\n a dictionary containing the band-pass filters of the 1st order,\n only for the base resolution as no subsampling is used in the\n scattering tree.\n Each value corresponds to a dictionary for a single filter, see above\n for an exact description.\n The keys of this dictionary are of the type (j, n) where n is an\n integer counting the filters and j the maximal dyadic subsampling\n which can be performed on top of the filter without aliasing.\n psi2_fft : dictionary\n a dictionary containing the band-pass filters of the 2nd order\n at all possible subsamplings. The subsamplings are determined by the\n input they can receive, which depends on the scattering tree.\n Each value corresponds to a dictionary for a single filter, see above\n for an exact description.\n The keys of this dictionary are of th etype (j, n) where n is an\n integer counting the filters and j is the maximal dyadic subsampling\n which can be performed on top of this filter without aliasing.\n t_max_phi : int\n temporal size to use to pad the signal on the right and on the\n left by making at most criterion_amplitude error. Assumes that the\n temporal support of the low-pass filter is larger than all filters.\n\n Refs\n ----\n Convolutional operators in the time-frequency domain, V. Lostanlen,\n PhD Thesis, 2017\n https://tel.archives-ouvertes.fr/tel-01559667\n \"\"\"\n # compute the spectral parameters of the filters\n sigma_low, xi1, sigma1, xi2, sigma2 = calibrate_scattering_filters(\n J_scattering, Q, r_psi=r_psi, sigma0=sigma0, alpha=alpha)\n\n # instantiate the dictionaries which will contain the filters\n phi_fft = {}\n psi1_fft = {k: {} for k in xi1.keys()}\n psi2_fft = {k: {} for k in xi2.keys()}\n\n # compute the band-pass filters of the second order,\n # which can take as input a subsampled\n for key in xi2.keys():\n j2 = key[0]\n # compute the current value for the max_subsampling,\n # which depends on the input it can accept.\n if max_subsampling is None:\n possible_subsamplings_after_order1 = [\n j1 for (j1, n1) in xi1.keys() if j2 > j1]\n if len(possible_subsamplings_after_order1) > 0:\n max_sub_psi2 = max(possible_subsamplings_after_order1)\n else:\n max_sub_psi2 = 0\n else:\n max_sub_psi2 = max_subsampling\n # We first compute the filter without subsampling\n T = 2**J_support\n psi2_fft[key][0] = morlet1D(\n T, xi2[key], sigma2[key], normalize=normalize, P_max=P_max,\n eps=eps)\n # compute the filter after subsampling at all other subsamplings\n # which might be received by the network, based on this first filter\n for subsampling in range(1, max_sub_psi2 + 1):\n factor_subsampling = 2**subsampling\n psi2_fft[key][subsampling] = periodize_filter_fft(\n psi2_fft[key][0], nperiods=factor_subsampling)\n\n # for the 1st order filters, the input is not subsampled so we\n # can only compute them with T=2**J_support\n for key in xi1.keys():\n T = 2**J_support\n psi1_fft[key][0] = morlet1D(\n T, xi1[key], sigma1[key], normalize=normalize,\n P_max=P_max, eps=eps)\n\n # compute the low-pass filters phi\n # Determine the maximal subsampling for phi, which depends on the\n # input it can accept (both 1st and 2nd order)\n if max_subsampling is None:\n max_subsampling_after_psi1 = max([key[0] for key in psi1_fft.keys()])\n max_subsampling_after_psi2 = max([key[0] for key in psi2_fft.keys()])\n max_sub_phi = max(max_subsampling_after_psi1,\n max_subsampling_after_psi2)\n else:\n max_sub_phi = max_subsampling\n # compute the filters at all possible subsamplings\n phi_fft[0] = gauss1D(T, sigma_low, P_max=P_max, eps=eps)\n for subsampling in range(1, max_sub_phi + 1):\n factor_subsampling = 2**subsampling\n # compute the low_pass filter\n phi_fft[subsampling] = periodize_filter_fft(\n phi_fft[0], nperiods=factor_subsampling)\n\n # Embed the meta information within the filters\n for k in xi1.keys():\n psi1_fft[k]['xi'] = xi1[k]\n psi1_fft[k]['sigma'] = sigma1[k]\n for k in xi2.keys():\n psi2_fft[k]['xi'] = xi2[k]\n psi2_fft[k]['sigma'] = sigma2[k]\n phi_fft['xi'] = 0.\n phi_fft['sigma'] = sigma_low\n\n # compute the support size allowing to pad without boundary errors\n # at the finest resolution\n t_max_phi = compute_temporal_support(\n phi_fft[0].reshape(1, -1), criterion_amplitude=criterion_amplitude)\n\n # prepare for pytorch if necessary\n if to_torch:\n for k in phi_fft.keys():\n if type(k) != str:\n # view(-1, 1) because real numbers!\n phi_fft[k] = torch.from_numpy(phi_fft[k]).view(-1, 1)\n for k in psi1_fft.keys():\n for sub_k in psi1_fft[k].keys():\n if type(sub_k) != str:\n # view(-1, 1) because real numbers!\n psi1_fft[k][sub_k] = torch.from_numpy(\n psi1_fft[k][sub_k]).view(-1, 1)\n for k in psi2_fft.keys():\n for sub_k in psi2_fft[k].keys():\n if type(sub_k) != str:\n # view(-1, 1) because real numbers!\n psi2_fft[k][sub_k] = torch.from_numpy(\n psi2_fft[k][sub_k]).view(-1, 1)\n\n # return results\n return phi_fft, psi1_fft, psi2_fft, t_max_phi\n"
]
| [
[
"numpy.max",
"numpy.fft.ifft",
"numpy.exp",
"torch.from_numpy",
"numpy.arange",
"numpy.abs",
"numpy.fft.fftfreq"
]
]
|
VideoAnalysis/EDUVSUM | [
"52243053a059a77c63668e9898ab319681b44f2e"
]
| [
"src/generateTextFeatures.py"
]
| [
"\n\nfrom common import videoLoading\nimport glob\nimport numpy as np \nimport pickle\nimport webvtt\n\n#https://pypi.org/project/webvtt-py/\n\n\n\nfrom bert_embedding import BertEmbedding\nfrom transformers import pipeline\n#https://pypi.org/project/bert-embedding/\n\n\n\n\ndef getSecFromTimeStr(tm):\n tmTkn=tm.split(\":\")\n hr=int(tmTkn[0])\n mtn=int(tmTkn[1])\n sec=float(tmTkn[2])\n finSecs=(hr*3600)+(mtn*60)+(sec)\n return finSecs\n\n \n\n\ndef getTextPerSecsArr(sub,durationA):\n caption=webvtt.read(sub)\n allTextPerSec=[]\n for i in range(int(durationA)):\n allTextPerSec.append([\"\"])\n for i in range(len(caption)):\n strt=int(getSecFromTimeStr(caption[i].start))\n ed=int(getSecFromTimeStr(caption[i].end))\n for x in range(strt,ed+1):\n allTextPerSec[x-1].append(caption[i].text)\n return np.array(allTextPerSec)\n\ndef getAllTextInSubs(sub):\n caption=webvtt.read(sub)\n listofTexts=[]\n for i in range(len(caption)):\n listofTexts.append(caption[i].text)\n return listofTexts\n \ndef getTextPerSecsArrByChunks(sub,durationA,chunk):\n caption=webvtt.read(sub)\n allTextPerSecByChunk=[]\n for i in range(durationA//chunk):\n allTextPerSecByChunk.append([\"\"])\n for i in range(len(caption)):\n strt=int(getSecFromTimeStr(caption[i].start))\n ed=int(getSecFromTimeStr(caption[i].end))\n allTextPerSecByChunk[strt//chunk].append(caption[i].text)\n allTextPerSecByChunk[ed//chunk].append(caption[i].text)\n return np.array(allTextPerSecByChunk)\n#for caption in webvtt.read(allVideosSubs[0]):\n# print(caption.start)\n# print(caption.end)\n# print(caption.text)\n\n \ndef getAvgGt(gtDf,vidName):\n subGt=gtDf.loc[vidName]\n allUserArr=[]\n for i in range(len(subGt)):\n allUserArr.append(subGt.iloc[i,-1].split(\",\"))\n allUserArr=np.array(allUserArr)\n allUserArr=allUserArr.astype(int)\n meanGt=allUserArr.mean(axis=0)\n return meanGt\n\ndef getTextDataFromVideoPerSec(baseDir,vid,subs):\n frmAll,fps,durationA=videoLoading.getAudioFramesAndFpsDur(vid)\n allTextPerSec=getTextPerSecsArr(baseDir+subs,durationA)\n return allTextPerSec,fps,durationA\n\ndef getTextDataFromVideoPerChunk(vid,sub,chunk=5):\n frmAll,fps,durationA=videoLoading.getAudioFramesAndFpsDur(vid)\n allTextPerSecByChunk=getTextPerSecsArrByChunks(sub,durationA,chunk)\n return allTextPerSecByChunk,fps,durationA\n\n\n\ndef getTxtDataAll(basedir,baseOut,chunk):\n allVideos=glob.glob(basedir)\n for v in range(len(allVideos)):\n vid=allVideos[v]\n vidName=vid.split(\"/\")[-1].split(\".\")[0]\n frmAll,fps,durationA=videoLoading.getAudioFramesAndFpsDur(vid)\n allTextPerSec=getTextPerSecsArr(vid,durationA)\n allTextPerSecByChunk=getTextPerSecsArrByChunks(vid,durationA,chunk)\n pickle.dump(allTextPerSec,open(baseOut+vidName+\"_persec_allTextPerSec.p\",\"wb\"))\n pickle.dump(allTextPerSecByChunk,open(baseOut+vidName+\"_\"+str(chunk)+\"_persec_allTextPerSecByChunk.p\",\"wb\"))\n print(\"audio and text written for: \",vidName)\n\n\n\ndef generateTextFeaturesForAllSec2(bert_embedding,bert_embedding2nlp,allTextPerSec,fps,durationA,baseOut,vidName):\n berstFeaturePerSec=[]\n berstFeaturePerSec2=[]\n berstTokensPerSec2=[]\n berstTokensPerSec=[]\n for i in range(len(allTextPerSec)):\n resultBert = bert_embedding(getAllTokenize(allTextPerSec[i]))\n resultBert2 = bert_embedding2nlp(\" \".join(allTextPerSec[i]))\n tokenArr,featureArr=getFeatureArrayFromTokens(resultBert)\n print(\"at video :\",vidName, \" on sec: \",i)\n berstFeaturePerSec.append(featureArr)\n berstTokensPerSec.append(tokenArr)\n berstFeaturePerSec2.append(np.array(resultBert2))\n berstTokensPerSec2.append(\" \".join(allTextPerSec[i]))\n return np.array(berstTokensPerSec),np.array(berstFeaturePerSec),np.array(berstTokensPerSec2),berstFeaturePerSec2\n\ndef generateTextFeaturesForAllSec3(bert_embedding,bert_embedding2nlp,allTextPerSec,fps,durationA,baseOut,vidName):\n berstFeaturePerSec=[]\n berstTokensPerSec=[]\n for i in range(len(allTextPerSec)):\n alltokens=getAllTokenize(allTextPerSec[i])\n \n resultBert = bert_embedding(alltokens)\n resultBert2 = bert_embedding2nlp(\" \".join(allTextPerSec[i]))\n tokenArr,featureArr=getFeatureArrayFromTokens(resultBert)\n print(\"at video :\",vidName, \" on sec: \",i)\n berstFeaturePerSec.append(featureArr)\n berstTokensPerSec.append(tokenArr)\n return np.array(berstTokensPerSec),np.array(berstFeaturePerSec),np.array(resultBert2)\n\n\ndef combineStrList(strLs):\n finalStr=\"\"\n for st in strls:\n if(st!=\"\" and st!=\" \"):\n finalStr+=st\n\ndef getAllTokenize(lst):\n tokenize=[]\n for v in lst:\n if(v!=\"\" and v!=\" \" and v!='' and v!=' '):\n tokenize2=v.replace(\"\\n\",\" \").split(\" \")\n for tk in tokenize2:\n tkRefine=''.join(e for e in tk if e.isalnum())\n tokenize.append(tkRefine)\n return tokenize\n\ndef getFeatureArrayFromTokens(resultBert):\n tokenls=[]\n featureLs=[]\n for i in range(len(resultBert)):\n tokenls.append(resultBert[i][0])\n featureLs.append(resultBert[i][1])\n return np.array(tokenls),np.array(featureLs)\n \n\n\ndef getparts(oneLinerText,size=1600,ol=160):\n parts=[]\n poss=int(len(oneLinerText)/size)+1\n lag=0\n for i in range(poss):\n if(i>0):\n lag=ol\n parts.append(oneLinerText[i*size-lag:((i+1)*size)])\n return parts\n\nimport pandas as pd\n# thsi is all names train + test files as in data directory\nannotatedVideos=pd.read_csv('./annotatedData/annotatedVideos.csv',header=None,delimiter=\"XYZ\").values \n\nbase=\"./AnnotatedVideosAndSubtitles_version_1/\"\nbasedirVids=base+\"*.mp4\"\nbasedirSubs=\"en_*.vtt\"\nbaseOut=\"./data/textFeatures/\"\nbaseDir=base\nallVideos=glob.glob(basedirVids)\n\nbert_embedding = BertEmbedding()\nbert_embedding2nlp = pipeline('feature-extraction')\n\nfor v in range(len(allVideos)):\n vid=allVideos[v]\n vidName=vid.split(\"/\")[-1][:-4]\n nameShowLimit=25\n if(not vidName in annotatedVideos): #check for already done videos\n print(\"video num: \",v,\" name: \",vidName[:nameShowLimit],\" not found labeled\")\n continue\n subs=\"en_\"+vidName+\".vtt\"\n print(\"subs bert features for video: \",vidName, \"idx: \",v)\n\n listAllText=getAllTextInSubs(baseDir+subs)\n oneLinerText=\" \".join(listAllText)\n resultBertAll = bert_embedding(oneLinerText.replace(\"\\n\",\" \").split(\" \"))\n tokenArrAll,featureArrAll=getFeatureArrayFromTokens(resultBertAll)\n partAll=getparts(oneLinerText)\n embedAllOuts2=[]\n textAllOut2=[]\n for i in range(len(partAll)):\n embedAllOuts2.append(np.array(bert_embedding2nlp(partAll[i])))\n textAllOut2.append(partAll[i])\n pickle.dump(tokenArrAll,open(baseOut+vidName+\"_tokenArrAll.p\",\"wb\")) # token all\n pickle.dump(featureArrAll,open(baseOut+vidName+\"_featureArrAll.p\",\"wb\")) # bert all\n pickle.dump(embedAllOuts2,open(baseOut+vidName+\"_embedAllOuts2.p\",\"wb\"))# hugging face all\n pickle.dump(textAllOut2,open(baseOut+vidName+\"_textAllOut2.p\",\"wb\"))# hugging face all\n print(\"features extracted now save as array: \",vidName, \"idx: \",v)\n\n\n"
]
| [
[
"numpy.array",
"pandas.read_csv"
]
]
|
frutoper/Hockey-Scraper | [
"bd521a4670396f0a565573fdc9cb95c28064ce0a"
]
| [
"hockey_scraper/scrape_functions.py"
]
| [
"\"\"\"\nFunctions to scrape by season, games, and date range\n\"\"\"\n\nimport hockey_scraper.json_schedule as json_schedule\nimport hockey_scraper.game_scraper as game_scraper\nimport hockey_scraper.shared as shared\nimport pandas as pd\nimport time\nimport random\n\n\n# This hold the scraping errors in a string format.\n# This may seem pointless but I have a personal reason for it (I think...)\nerrors = ''\n\n\ndef print_errors():\n \"\"\"\n Print errors with scraping.\n \n Also puts errors in the \"error\" string (would just print the string but it would look like shit on one line. I\n could store it as I \"should\" print it but that isn't how I want it). \n\n :return: None\n \"\"\"\n global errors\n\n if game_scraper.broken_pbp_games:\n print('\\nBroken pbp:')\n errors += 'Broken pbp:'\n for x in game_scraper.broken_pbp_games:\n print(x[0], x[1])\n errors = ' '.join([errors, str(x[0]), \",\"])\n\n if game_scraper.broken_shifts_games:\n print('\\nBroken shifts:')\n errors += 'Broken shifts:'\n for x in game_scraper.broken_shifts_games:\n print(x[0], x[1])\n errors = ' '.join([errors, str(x[0]), \",\"])\n\n if game_scraper.players_missing_ids:\n print(\"\\nPlayers missing ID's:\")\n errors += \"Players missing ID's:\"\n for x in game_scraper.players_missing_ids:\n print(x[0], x[1])\n errors = ' '.join([errors, str(x[0]), \",\"])\n\n if game_scraper.missing_coords:\n print('\\nGames missing coordinates:')\n errors += 'Games missing coordinates:'\n for x in game_scraper.missing_coords:\n print(x[0], x[1])\n errors = ' '.join([errors, str(x[0]), \",\"])\n\n print('\\n')\n\n # Clear them all out for the next call\n game_scraper.broken_shifts_games = []\n game_scraper.broken_pbp_games = []\n game_scraper.players_missing_ids = []\n game_scraper.missing_coords = []\n\n\ndef check_data_format(data_format):\n \"\"\"\n Checks if data_format specified (if it is at all) is either None, 'Csv', or 'pandas'.\n It exits program with error message if input isn't good.\n \n :param data_format: data_format provided \n \n :return: Boolean - True if good\n \"\"\"\n if not data_format or data_format.lower() not in ['csv', 'pandas']:\n raise shared.HaltException('{} is an unspecified data format. The two options are Csv and Pandas '\n '(Csv is default)\\n'.format(data_format))\n\n\ndef check_valid_dates(from_date, to_date):\n \"\"\"\n Check if it's a valid date range\n \n :param from_date: date should scrape from\n :param to_date: date should scrape to\n \n :return: None\n \"\"\"\n try:\n if time.strptime(to_date, \"%Y-%m-%d\") < time.strptime(from_date, \"%Y-%m-%d\"):\n raise shared.HaltException(\"Error: The second date input is earlier than the first one\")\n except ValueError:\n raise shared.HaltException(\"Error: Incorrect format given for dates. They must be given like 'yyyy-mm-dd' \"\n \"(ex: '2016-10-01').\")\n\n\ndef to_csv(file_name, pbp_df, shifts_df):\n \"\"\"\n Write DataFrame(s) to csv file(s)\n \n :param file_name: name of file\n :param pbp_df: pbp DataFrame\n :param shifts_df: shifts DataFrame\n \n :return: None\n \"\"\"\n if pbp_df is not None:\n print(\"\\nPbp data deposited in file - \" + 'nhl_pbp{}.csv'.format(file_name))\n pbp_df.to_csv('nhl_pbp{}.csv'.format(file_name), sep=',', encoding='utf-8',index=False)\n if shifts_df is not None:\n print(\"Shift data deposited in file - \" + 'nhl_shifts{}.csv'.format(file_name))\n shifts_df.to_csv('nhl_shifts{}.csv'.format(file_name), sep=',', encoding='utf-8',index=False)\n\n\ndef scrape_list_of_games(games, if_scrape_shifts):\n \"\"\"\n Given a list of game_id's (and a date for each game) it scrapes them\n \n :param games: list of [game_id, date]\n :param if_scrape_shifts: Boolean indicating whether to also scrape shifts \n \n :return: DataFrame of pbp info, also shifts if specified\n \"\"\"\n pbp_dfs = []\n shifts_dfs = []\n\n for game in games:\n pbp_df, shifts_df = game_scraper.scrape_game(str(game[\"game_id\"]), game[\"date\"], if_scrape_shifts)\n if pbp_df is not None:\n pbp_dfs.extend([pbp_df])\n if shifts_df is not None:\n shifts_dfs.extend([shifts_df])\n\n # Check if any games...if not let's get out of here\n if len(pbp_dfs) == 0:\n return None, None\n else:\n pbp_df = pd.concat(pbp_dfs)\n pbp_df = pbp_df.reset_index(drop=True)\n pbp_df.apply(lambda row: game_scraper.check_goalie(row), axis=1)\n\n if if_scrape_shifts:\n shifts_df = pd.concat(shifts_dfs)\n shifts_df = shifts_df.reset_index(drop=True)\n else:\n shifts_df = None\n\n # Print all errors associated with scrape call\n print_errors()\n\n return pbp_df, shifts_df\n\n\ndef scrape_date_range(from_date, to_date, if_scrape_shifts, data_format='csv', preseason=False, rescrape=False, docs_dir=None):\n \"\"\"\n Scrape games in given date range\n \n :param from_date: date you want to scrape from\n :param to_date: date you want to scrape to\n :param if_scrape_shifts: Boolean indicating whether to also scrape shifts \n :param data_format: format you want data in - csv or pandas (csv is default)\n :param preseason: Boolean indicating whether to include preseason games (default if False)\n This is may or may not work!!! I don't give a shit.\n :param rescrape: If you want to rescrape pages already scraped. Only applies if you supply a docs dir. (def. = None)\n :param docs_dir: Directory that either contains previously scraped docs or one that you want them to be deposited \n in after scraping. (default is None)\n \n :return: Dictionary with DataFrames and errors or None\n \"\"\"\n # First check if the inputs are good\n check_data_format(data_format)\n check_valid_dates(from_date, to_date)\n\n # Check on the docs_dir and re_scrape\n shared.add_dir(docs_dir)\n shared.if_rescrape(rescrape)\n\n games = json_schedule.scrape_schedule(from_date, to_date, preseason)\n pbp_df, shifts_df = scrape_list_of_games(games, if_scrape_shifts)\n\n if data_format.lower() == 'csv':\n to_csv(from_date+'--'+to_date, pbp_df, shifts_df)\n else:\n return {\"pbp\": pbp_df, \"shifts\": shifts_df, \"errors\": errors} if if_scrape_shifts else {\"pbp\": pbp_df,\n \"errors\": errors}\n\n\ndef scrape_seasons(seasons, if_scrape_shifts, data_format='csv', preseason=False, rescrape=False, docs_dir=None):\n \"\"\"\n Given list of seasons it scrapes all the seasons \n \n :param seasons: list of seasons\n :param if_scrape_shifts: Boolean indicating whether to also scrape shifts \n :param data_format: format you want data in - csv or pandas (csv is default)\n :param preseason: Boolean indicating whether to include preseason games (default if False)\n This is may or may not work!!! I don't give a shit.\n :param rescrape: If you want to rescrape pages already scraped. Only applies if you supply a docs dir.\n :param docs_dir: Directory that either contains previously scraped docs or one that you want them to be deposited \n in after scraping\n \n :return: Dictionary with DataFrames and errors or None\n \"\"\"\n # First check if the inputs are good\n check_data_format(data_format)\n\n # Check on the docs_dir and re_scrape\n shared.add_dir(docs_dir)\n shared.if_rescrape(rescrape)\n\n # Holds all seasons scraped (if not csv)\n master_pbps, master_shifts = [], []\n\n for season in seasons:\n from_date = '-'.join([str(season), '9', '1'])\n to_date = '-'.join([str(season + 1), '7', '1'])\n\n games = json_schedule.scrape_schedule(from_date, to_date, preseason)\n pbp_df, shifts_df = scrape_list_of_games(games, if_scrape_shifts)\n\n if data_format.lower() == 'csv':\n to_csv(str(season)+str(season+1), pbp_df, shifts_df)\n else:\n master_pbps.append(pbp_df)\n master_shifts.append(shifts_df)\n\n if data_format.lower() == 'pandas':\n if if_scrape_shifts:\n return {\"pbp\": pd.concat(master_pbps), \"shifts\": pd.concat(master_shifts), \"errors\": errors}\n else:\n return {\"pbp\": pd.concat(master_pbps), \"errors\": errors}\n\n\ndef scrape_games(games, if_scrape_shifts, data_format='csv', rescrape=False, docs_dir=None):\n \"\"\"\n Scrape a list of games\n \n :param games: list of game_ids\n :param if_scrape_shifts: Boolean indicating whether to also scrape shifts \n :param data_format: format you want data in - csv or pandas (csv is default)\n :param rescrape: If you want to rescrape pages already scraped. Only applies if you supply a docs dir.\n :param docs_dir: Directory that either contains previously scraped docs or one that you want them to be deposited \n in after scraping\n \n :return: Dictionary with DataFrames and errors or None\n \"\"\"\n # First check if the inputs are good\n check_data_format(data_format)\n\n # Check on the docs_dir and re_scrape\n shared.add_dir(docs_dir)\n shared.if_rescrape(rescrape)\n\n # Create List of game_id's and dates\n games_list = json_schedule.get_dates(games)\n\n # Scrape pbp and shifts\n pbp_df, shifts_df = scrape_list_of_games(games_list, if_scrape_shifts)\n\n if data_format.lower() == 'csv':\n to_csv(str(random.randint(1, 101)), pbp_df, shifts_df)\n else:\n return {\"pbp\": pbp_df, \"shifts\": shifts_df, \"errors\": errors} if if_scrape_shifts else {\"pbp\": pbp_df,\n \"errors\": errors}\n"
]
| [
[
"pandas.concat"
]
]
|
NickeZ/pyepics | [
"114463cefc15a260b20b1965864bd80ac8415ac6"
]
| [
"epics/devices/mca.py"
]
| [
"#!/usr/bin/python\nimport sys\nimport time\nimport numpy as np\nfrom .. import Device, get_pv, poll, caput, caget\n\ntry:\n from collections import OrderedDict\nexcept:\n from ordereddict import OrderedDict\n\nif sys.version[0] == '2':\n from ConfigParser import ConfigParser\nelif sys.version[0] == '3':\n from configparser import ConfigParser\n\nMAX_ROIS = 32\nclass DXP(Device):\n _attrs = ('PreampGain','MaxEnergy','ADCPercentRule','BaselineCutPercent',\n 'BaselineThreshold','BaselineFilterLength','BaselineCutEnable',\n 'InputCountRate', 'OutputCountRate',\n 'GapTime','PeakingTime','EnergyThreshold','MaxWidth',\n 'PresetMode', 'TriggerPeakingTime',\n 'TriggerGapTime','TriggerThreshold')\n\n def __init__(self,prefix,mca=1):\n self._prefix = \"%sdxp%i\" % (prefix, mca)\n Device.__init__(self, self._prefix, delim=':')\n poll()\n\n\nclass ROI(Device):\n \"\"\"epics ROI device for MCA record\n\n >>> from epics.devices.mca import ROI, MCA\n >>> r = ROI('PRE:mca1', roi=1)\n >>> print r.name, r.left, r.right\n\n arguments\n ---------\n prefix MCA record prefix\n roi integer for ROI (0 through 31)\n bgr_width width in bins for calculating NET counts\n data_pv optional PV name to read counts from (not needed\n for most MCA records, but useful for some)\n\n attribute (read/write)\n ----------------------\n LO, left low bin for ROI\n HI, right high bin for ROI\n NM, name name\n\n properties (read only)\n -----------------------\n center roi center bin\n width roi width (in bins)\n address == prefix\n total sum counts in ROI\n net background-subtracted sum counts in ROI\n\n methods\n -------\n clear remove ROI\n \"\"\"\n\n _nonpvs = ('_prefix', '_pvs', '_delim', 'attrs', 'width', 'center',\n 'bgr_width', 'address', 'net', 'total', '_dat_', '_net_')\n _aliases = {'left': 'LO', 'right': 'HI', 'name': 'NM'}\n def __init__(self, prefix, roi=0, bgr_width=3, data_pv=None):\n self.address = self._prefix = '%s.R%i' % (prefix, roi)\n self.bgr_width = bgr_width\n _attrs = ('NM', 'LO', 'HI')\n Device.__init__(self,self._prefix, delim='', \n attrs=_attrs, aliases=self._aliases, \n with_poll=False)\n if data_pv is None:\n data_pv = self.address\n if isinstance(data_pv, basestring):\n data_pv = get_pv(data_pv)\n self._pvs['_dat_'] = data_pv\n self._pvs['_net_'] = get_pv(self.address + 'N')\n\n def __eq__(self, other):\n \"\"\"used for comparisons\"\"\"\n return (self.LO == getattr(other, 'LO', None) and\n self.HI == getattr(other, 'HI', None) and\n self.bgr_width == getattr(other, 'bgr_width', None) )\n\n def __ne__(self, other): return not self.__eq__(other)\n def __lt__(self, other): return self.LO < getattr(other, 'LO', None)\n def __le__(self, other): return self.LO <= getattr(other, 'LO', None)\n def __gt__(self, other): return self.LO > getattr(other, 'LO', None)\n def __ge__(self, other): return self.LO >= getattr(other, 'LO', None)\n\n def __repr__(self):\n \"string representation\"\n pref = self._prefix\n if pref.endswith('.'):\n pref = pref[:-1]\n return \"<ROI '%s', name='%s', range=[%s:%s]>\" % (pref, self.NM,\n self.LO, self.HI)\n\n #return \"<ROI '%s', name='%s', range=[%i:%i]>\" % (pref, self.NM,\n # self.LO, self.HI)\n\n @property\n def total(self):\n return self.get_counts(net=False)\n\n @property\n def net(self):\n return self.get_counts(net=True)\n\n @property\n def center(self):\n return int(round(self.HI + self.LO)/2.0)\n\n @property\n def width(self):\n return int(round(self.HI - self.LO))\n\n def clear(self):\n self.NM = ''\n self.LO = -1\n self.HI = -1\n\n def get_counts(self, data=None, net=False):\n \"\"\"\n calculate total and net counts for a spectra\n\n Parameters:\n -----------\n * data: numpy array of spectra or None to read from PV\n * net: bool to set net counts (default=False: total counts returned)\n \"\"\"\n # implicitly read data from a PV\n if data is None and self._pvs['_dat_'] is not None:\n data = self._pvs['_dat_'].get()\n if net and not isinstance(data, np.ndarray):\n data = self._pvs['_net_'].get()\n if not isinstance(data, np.ndarray):\n return data\n\n total = data[self.LO:self.HI+1].sum()\n if not net:\n return total\n # calculate net counts\n bgr_width = int(self.bgr_width)\n ilmin = max((self.LO - bgr_width), 0)\n irmax = min((self.HI + bgr_width), len(data)-1) + 1\n bgr_counts = np.concatenate((data[ilmin:self.LO],\n data[self.HI+1:irmax])).mean()\n\n return (total - bgr_counts*(self.HI-self.LO))\n\nclass MCA(Device):\n _attrs =('CALO', 'CALS', 'CALQ', 'TTH', 'EGU', \n 'PRTM', 'PLTM', 'ACQG', 'NUSE', 'DWEL', \n 'ERTM', 'ELTM', 'IDTIM')\n _nonpvs = ('_prefix', '_pvs', '_delim',\n '_npts', 'rois', '_nrois', 'rois')\n\n def __init__(self, prefix, mca=None, nrois=None, data_pv=None):\n self._prefix = prefix\n self._npts = None\n self._nrois = nrois\n if self._nrois is None:\n self._nrois = MAX_ROIS\n self.rois = []\n if isinstance(mca, int):\n self._prefix = \"%smca%i\" % (prefix, mca)\n\n Device.__init__(self,self._prefix, delim='.',\n attrs=self._attrs, with_poll=False)\n self._pvs['VAL'] = get_pv(\"%sVAL\" % self._prefix, auto_monitor=False)\n\n self._pvs['_dat_'] = None\n if data_pv is not None:\n self._pvs['_dat_'] = get_pv(data_pv)\n poll()\n\n\n def get_rois(self, nrois=None):\n self.rois = []\n data_pv = self._pvs['_dat_']\n prefix = self._prefix\n if prefix.endswith('.'):\n prefix = prefix[:-1]\n if nrois is None:\n nrois = self._nrois\n for i in range(nrois):\n roi = ROI(prefix=prefix, roi=i, data_pv=data_pv)\n if len(roi.NM.strip()) <= 0 or roi.HI <= 0:\n break\n self.rois.append(roi)\n poll()\n \n return self.rois\n\n def del_roi(self, roiname):\n self.get_rois()\n for roi in self.rois:\n if roi.NM.strip().lower() == roiname.strip().lower():\n roi.clear()\n poll(0.010, 1.0)\n self.set_rois(self.rois)\n\n def add_roi(self, roiname, lo=-1, hi=-1, calib=None):\n \"\"\"add an roi, given name, lo, and hi channels, and\n an optional calibration other than that of this mca.\n\n That is, specifying an ROI with all of lo, hi AND calib\n will set the ROI **by energy** so that it matches the\n provided calibration. To add an ROI to several MCAs\n with differing calibration, use\n\n cal_1 = mca1.get_calib()\n for mca im (mca1, mca2, mca3, mca4):\n mca.add_roi('Fe Ka', lo=600, hi=700, calib=cal_1)\n \"\"\"\n if lo < 0 or hi <0:\n return\n rois = self.get_rois()\n try:\n iroi = len(rois)\n except:\n iroi = 0\n if iroi >= MAX_ROIS:\n raise ValueError('too many ROIs - cannot add more %i/%i' % (iroi, MAX_ROIS))\n data_pv = self._pvs['_dat_']\n prefix = self._prefix\n if prefix.endswith('.'): prefix = prefix[:-1]\n roi = ROI(prefix=prefix, roi=iroi, data_pv=self._pvs['_dat_'])\n roi.NM = roiname.strip()\n\n offset, scale = 0.0, 1.0\n if calib is not None:\n off, slope, quad = self.get_calib()\n offset = calib[0] - off\n scale = calib[1] / slope\n\n roi.LO = round(offset + scale*lo)\n roi.HI = round(offset + scale*hi)\n rois.append(roi)\n self.set_rois(rois)\n\n def set_rois(self, rois, calib=None):\n \"\"\"set all rois, with optional calibration that those\n ROIs correspond to (if they have a different energy\n calibration), and ensures they are ordered and contiguous.\n\n A whole set of ROIs can be copied by energy from one mca\n to another with:\n\n rois = mca1.get_rois()\n calib = mca1.get_calib()\n mca2.set_rois(rois, calib=calib)\n \"\"\"\n data_pv = self._pvs['_dat_']\n prefix = self._prefix\n if prefix.endswith('.'): prefix = prefix[:-1]\n\n offset, scale = 0.0, 1.0\n if calib is not None:\n off, slope, quad = self.get_calib()\n offset = calib[0] - off\n scale = calib[1] / slope\n\n # do an explicit get here to make sure all data is\n # available before trying to sort it!\n poll(0.0050, 1.0)\n \n [(r.get('NM'), r.get('LO')) for r in rois]\n roidat = [(r.NM, r.LO, r.HI) for r in sorted(rois)]\n\n iroi = 0\n self.rois = []\n for name, lo, hi in roidat:\n if len(name)<1 or lo<0 or hi<0:\n continue\n roi = ROI(prefix=prefix, roi=iroi, data_pv=data_pv)\n roi.NM = name.strip()\n roi.LO = round(offset + scale*lo)\n roi.HI = round(offset + scale*hi)\n self.rois.append(roi)\n iroi += 1\n\n # erase any remaning ROIs\n for i in range(iroi, MAX_ROIS):\n lo = caget(\"%s.R%iLO\" % (prefix, i))\n if lo < 0:\n break\n caput(\"%s.R%iLO\" % (prefix, i), -1)\n caput(\"%s.R%iHI\" % (prefix, i), -1)\n caput(\"%s.R%iNM\" % (prefix, i), '')\n \n def clear_rois(self, nrois=None):\n for roi in self.get_rois(nrois=nrois):\n roi.clear()\n self.rois = []\n\n def get_calib(self):\n return [self.get(i) for i in ('CALO','CALS','CALQ')]\n\n def get_energy(self):\n if self._npts is None:\n self._npts = len(self.get('VAL'))\n\n en = np.arange(self._npts, dtype='f8')\n cal = self.get_calib()\n return cal[0] + en*(cal[1] + en*cal[2])\n\n\nclass MultiXMAP(Device):\n \"\"\"\n multi-Channel XMAP DXP device\n \"\"\"\n\n attrs = ['PresetReal','Dwell','Acquiring', 'EraseStart','StopAll',\n 'PresetMode', 'PixelsPerBuffer_RBV', 'NextPixel',\n 'PixelsPerRun', 'Apply', 'AutoApply', 'CollectMode',\n 'SyncCount', 'BufferSize_RBV']\n\n pathattrs = ('FilePath', 'FileTemplate', 'FileWriteMode',\n 'FileName', 'FileNumber', 'FullFileName_RBV',\n 'Capture', 'NumCapture', 'WriteFile_RBV',\n 'AutoSave', 'EnableCallbacks', 'ArraySize0_RBV',\n 'FileTemplate_RBV', 'FileName_RBV', 'AutoIncrement')\n\n _nonpvs = ('_prefix', '_pvs', '_delim', 'filesaver',\n 'pathattrs', '_nonpvs', 'nmca', 'dxps', 'mcas')\n\n def __init__(self, prefix, filesaver='netCDF1:',nmca=4):\n self.filesaver = filesaver\n self._prefix = prefix\n self.nmca = nmca\n\n self.dxps = [DXP(prefix, mca=i+1) for i in range(nmca)]\n self.mcas = [MCA(prefix, mca=i+1) for i in range(nmca)]\n\n Device.__init__(self, prefix, attrs=self.attrs,\n delim='', mutable=True)\n for p in self.pathattrs:\n pvname = '%s%s%s' % (prefix, filesaver, p)\n self.add_pv(pvname, attr=p)\n\n def get_calib(self):\n return [m.get_calib() for m in self.mcas]\n\n def get_rois(self):\n return [m.get_rois() for m in self.mcas]\n\n def roi_calib_info(self):\n buff = ['[rois]']\n add = buff.append\n rois = self.get_rois()\n for iroi in range(len(rois[0])):\n name = rois[0][iroi].NM\n s = [[rois[m][iroi].LO, rois[m][iroi].HI] for m in range(self.nmca)]\n dat = repr(s).replace('],', '').replace('[', '').replace(']','').replace(',','')\n add(\"ROI%2.2i = %s | %s\" % (iroi, name, dat))\n\n caldat = np.array(self.get_calib())\n add('[calibration]')\n add(\"OFFSET = %s \" % (' '.join([\"%.7g\" % i for i in caldat[:, 0]])))\n add(\"SLOPE = %s \" % (' '.join([\"%.7g\" % i for i in caldat[:, 1]])))\n add(\"QUAD = %s \" % (' '.join([\"%.7g\" % i for i in caldat[:, 2]])))\n\n add('[dxp]')\n for a in self.dxps[0]._attrs:\n vals = [str(dxp.get(a, as_string=True)).replace(' ','_') for dxp in self.dxps]\n add(\"%s = %s\" % (a, ' '.join(vals)))\n return buff\n\n def restore_rois(self, roifile):\n \"\"\"restore ROI setting from ROI.dat file\"\"\"\n cp = ConfigParser()\n cp.read(roifile)\n rois = []\n self.mcas[0].clear_rois()\n prefix = self.mcas[0]._prefix\n if prefix.endswith('.'):\n prefix = prefix[:-1]\n iroi = 0\n for a in cp.options('rois'):\n if a.lower().startswith('roi'):\n name, dat = cp.get('rois', a).split('|')\n lims = [int(i) for i in dat.split()]\n lo, hi = lims[0], lims[1]\n roi = ROI(prefix=prefix, roi=iroi)\n roi.LO = lo\n roi.HI = hi\n roi.NM = name.strip()\n rois.append(roi)\n iroi += 1\n\n poll(0.050, 1.0)\n self.mcas[0].set_rois(rois)\n cal0 = self.mcas[0].get_calib()\n for mca in self.mcas[1:]:\n mca.set_rois(rois, calib=cal0)\n\n def Write_CurrentConfig(self, filename=None):\n buff = []\n add = buff.append\n add('#Multi-Element xMAP Settings saved: %s' % time.ctime())\n add('[general]')\n add('prefix= %s' % self._prefix)\n add('nmcas = %i' % self.nmca)\n add('filesaver= %s' % self.filesaver)\n d.add('starting roi....')\n buff.extend( self.roi_calib_info() )\n\n d.add('wrote roi / calib / dxp')\n\n buff = '\\n'.join(buff)\n if filename is not None:\n fh = open(filename,'w')\n fh.write(buff)\n fh.close()\n d.add('wrote file')\n # d.show()\n return buff\n\n def start(self):\n \"Start Struck\"\n self.EraseStart = 1\n\n if self.Acquiring == 0:\n poll()\n self.EraseStart = 1\n return self.EraseStart\n\n def stop(self):\n \"Stop Struck Collection\"\n self.StopAll = 1\n return self.StopAll\n\n def next_pixel(self):\n \"Advance to Next Pixel:\"\n self.NextPixel = 1\n return self.NextPixel\n\n def finish_pixels(self, timeout=2):\n \"Advance to Next Pixel until CurrentPixel == PixelsPerRun\"\n pprun = self.PixelsPerRun\n cur = self.dxps[0].get('CurrentPixel')\n t0 = time.time()\n while cur < pprun and time.time()-t0 < timeout:\n time.sleep(0.1)\n pprun = self.PixelsPerRun\n cur = self.dxps[0].get('CurrentPixel')\n ok = cur >= pprun\n if not ok:\n print('XMAP needs to finish pixels ', cur, ' / ' , pprun)\n for i in range(pprun-cur):\n self.next_pixel()\n time.sleep(0.10)\n self.FileCaptureOff()\n return ok, pprun-cur\n\n\n def readmca(self,n=1):\n \"Read a Struck MCA\"\n return self.get('mca%i' % n)\n\n def SCAMode(self):\n \"put XMAP in SCA mapping mode\"\n self.CollectMode = 2\n\n def SpectraMode(self):\n \"put XMAP in MCA spectra mode\"\n self.stop()\n self.CollectMode = 0\n self.PresetMode = 0\n # wait until BufferSize is ready\n buffsize = -1\n t0 = time.time()\n while time.time() - t0 < 5:\n self.CollectMode = 0\n time.sleep(0.05)\n if self.BufferSize_RBV < 16384:\n break\n\n def MCAMode(self, filename=None, filenumber=None, npulses=11):\n \"put XMAP in MCA mapping mode\"\n self.AutoApply = 1\n self.stop()\n self.PresetMode = 0\n self.setFileWriteMode(2)\n if npulses < 2:\n npulses = 2\n self.CollectMode = 1\n self.PixelsPerRun = npulses\n\n # First, make sure ArraySize0_RBV for the netcdf plugin\n # is the correct value\n self.FileCaptureOff()\n self.start()\n f_size = -1\n t0 = time.time()\n while (f_size < 16384) and time.time()-t0 < 10:\n for i in range(5):\n time.sleep(0.1)\n self.NextPixel = 1\n f_size = self.fileGet('ArraySize0_RBV')\n if f_size > 16384:\n break\n #\n self.PixelsPerRun = npulses\n self.SyncCount = 1\n\n self.setFileNumber(filenumber)\n if filename is not None:\n self.setFileName(filename)\n\n # wait until BufferSize is ready\n self.Apply = 1\n self.CollectMode = 1\n self.PixelsPerRun = npulses\n time.sleep(0.50)\n t0 = time.time()\n while time.time() - t0 < 10:\n time.sleep(0.25)\n if self.BufferSize_RBV > 16384:\n break\n\n # set expected number of buffers to put in a single file\n ppbuff = self.PixelsPerBuffer_RBV\n time.sleep(0.25)\n if ppbuff is None:\n ppbuff = 124\n self.setFileNumCapture(1 + (npulses-1)/ppbuff)\n f_buffsize = -1\n t0 = time.time()\n while time.time()- t0 < 5:\n time.sleep(0.1)\n f_buffsize = self.fileGet('ArraySize0_RBV')\n if self.BufferSize_RBV == f_buffsize:\n break\n\n time.sleep(0.5)\n return\n\n def filePut(self,attr, value, **kw):\n return self.put(\"%s%s\" % (self.filesaver, attr), value, **kw)\n\n def fileGet(self, attr, **kw):\n return self.get(\"%s%s\" % (self.filesaver, attr), **kw)\n\n def setFilePath(self, pathname):\n return self.filePut('FilePath', pathname)\n\n def setFileTemplate(self, fmt):\n return self.filePut('FileTemplate', fmt)\n\n def setFileWriteMode(self, mode):\n return self.filePut('FileWriteMode', mode)\n\n def setFileName(self, fname):\n return self.filePut('FileName', fname)\n\n def nextFileNumber(self):\n self.setFileNumber(1+self.fileGet('FileNumber'))\n\n def setFileNumber(self, fnum=None):\n if fnum is None:\n self.filePut('AutoIncrement', 1)\n else:\n self.filePut('AutoIncrement', 0)\n return self.filePut('FileNumber',fnum)\n\n def getLastFileName(self):\n return self.fileGet('FullFileName_RBV',as_string=True)\n\n def FileCaptureOn(self):\n return self.filePut('Capture', 1)\n\n def FileCaptureOff(self):\n return self.filePut('Capture', 0)\n\n def setFileNumCapture(self,n):\n return self.filePut('NumCapture', n)\n\n def FileWriteComplete(self):\n return (0==self.fileGet('WriteFile_RBV') )\n\n def getFileTemplate(self):\n return self.fileGet('FileTemplate_RBV',as_string=True)\n\n def getFileName(self):\n return self.fileGet('FileName_RBV',as_string=True)\n\n def getFileNumber(self):\n return self.fileGet('FileNumber_RBV')\n\n def getFilePath(self):\n return self.fileGet('FilePath_RBV',as_string=True)\n\n def getFileNameByIndex(self,index):\n return self.getFileTemplate() % (self.getFilePath(), self.getFileName(), index)\n\n"
]
| [
[
"numpy.concatenate",
"numpy.arange"
]
]
|
bukeplato/pyBKT | [
"733a4ccf0de78bef7d47b5a6af7131c7778560db"
]
| [
"source-py/pyBKT/models/Model.py"
]
| [
"#########################################\n# Model.py #\n# Model #\n# #\n# @author Anirudhan Badrinath #\n# Last edited: 07 April 2021 #\n#########################################\n\nimport numpy as np\nimport numbers\nimport os\nimport pandas as pd\nimport random\nimport pickle\nimport urllib.request as urllib2\nfrom pyBKT.generate import synthetic_data, random_model_uni\nfrom pyBKT.fit import EM_fit, predict_onestep\nfrom pyBKT.util import crossvalidate, data_helper, check_data, metrics\n\npd.options.display.float_format = '{:,.5f}'.format\n\nclass Model:\n MODELS_BKT = ['multilearn', 'multiprior', 'multipair', 'multigs']\n MODEL_ARGS = ['parallel', 'num_fits', 'seed', 'defaults'] + MODELS_BKT\n FIT_ARGS = ['skills', 'num_fits', 'defaults', 'fixed',\n 'parallel', 'forgets', 'preload'] + MODELS_BKT\n CV_ARGS = FIT_ARGS + ['folds', 'seed']\n DEFAULTS = {'num_fits': 5,\n 'defaults': None,\n 'parallel': True,\n 'skills': '.*',\n 'seed': random.randint(0, 1e8),\n 'folds': 5,\n 'forgets': False,\n 'fixed': None,\n 'model_type': [False] * len(MODELS_BKT)}\n DEFAULTS_BKT = {'order_id': 'order_id',\n 'skill_name': 'skill_name',\n 'correct': 'correct',\n 'user_id': 'user_id',\n 'multilearn': 'template_id',\n 'multiprior': 'correct',\n 'multipair': 'problem_id',\n 'multigs': 'template_id',\n 'folds': 'template_id'}\n INITIALIZABLE_PARAMS = ['prior', 'learns', 'guesses', 'slips', 'forgets']\n\n def __init__(self, **kwargs):\n \"\"\"\n Constructs a BKT Model. Takes arguments parallel, num_fits, seed, defaults,\n and any model variant(s) that may be used. Note that all of these can be modified\n during fit/crossvalidation time.\n\n >>> model = Model(seed = 42)\n >>> model\n Model(parallel=True, num_fits=5, seed=42, defaults=None)\n\n \"\"\"\n self.fit_model = None\n self.manual_param_init = False\n self._check_args(Model.MODEL_ARGS, kwargs)\n self.keep = {}\n self._update_param(['parallel', 'num_fits', 'seed', 'defaults'], kwargs, keep = True)\n self._update_param('model_type', self._update_defaults(kwargs), keep = True)\n\n def fit(self, data_path = None, data = None, **kwargs):\n \"\"\"\n Fits a BKT model given model and data information. Takes arguments skills,\n number of initialization fits, default column names (i.e. correct, skill_name),\n parallelization, and model types. Resets model state if uninitialized.\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.evaluate(data_path = 'as.csv', metric = 'auc')\n 0.6128265543747811\n\n \"\"\"\n if not self.manual_param_init:\n self.fit_model = {}\n self.partial_fit(data_path = data_path, data = data, **kwargs)\n\n def partial_fit(self, data_path = None, data = None, **kwargs):\n \"\"\"\n Partially fits a BKT model given model and data information. Takes arguments skills,\n number of initialization fits, default column names (i.e. correct, skill_name),\n parallelization, and model types. Behaviour is to ignore if the model is changed\n between partial fits since parameters are copied but data is reprocessed. Note\n that model type need not be specified when using partial fit after the first partial\n fit.\n\n >>> model = Model(seed = 42)\n >>> model.partial_fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.partial_fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.partial_fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.evaluate(data_path = 'as.csv', metric = 'auc')\n 0.6579800168987382\n\n \"\"\"\n self._check_data(data_path, data)\n self._check_args(Model.FIT_ARGS, kwargs)\n self._update_param(['skills', 'num_fits', 'defaults', 'fixed',\n 'parallel', 'forgets'], kwargs)\n if self.fit_model is None or self.fit_model == {}:\n self.fit_model = {}\n if self.fit_model == {} or (self.manual_param_init and self.fit_model):\n self._update_param('model_type', self._update_defaults(kwargs))\n self.manual_param_init = True\n all_data = self._data_helper(data_path, data, self.defaults, self.skills, self.model_type)\n self._update_param(['skills'], {'skills': list(all_data.keys())})\n for skill in all_data:\n self.fit_model[skill] = self._fit(all_data[skill], skill, self.forgets, \n preload = kwargs['preload'] if 'preload' in kwargs else False)\n self.manual_param_init = False\n\n def predict(self, data_path = None, data = None):\n \"\"\"\n Predicts using the trained BKT model and test data information. Takes test data\n location or DataFrame as arguments. Returns a dictionary mapping skills to predicted\n values for those skills. Note that the predicted values are a tuple of\n (correct_predictions, state_predictions).\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> preds_df = model.predict(data_path = 'as.csv')\n >>> preds_df[preds_df['skill_name'] == 'Box and Whisker'][['user_id', 'correct', 'correct_predictions', 'state_predictions']]\n user_id correct correct_predictions state_predictions\n 0 64525 1 0.69205 0.28276\n 1 64525 1 0.80226 0.10060\n 2 70363 0 0.69205 0.28276\n 3 70363 1 0.54989 0.51775\n 4 70363 0 0.74196 0.20028\n ... ... ... ... ...\n 3952 96297 1 0.84413 0.03139\n 3953 96297 1 0.84429 0.03113\n 3954 96297 1 0.84432 0.03108\n 3955 96298 1 0.69205 0.28276\n 3956 96298 1 0.80226 0.10060\n\n [3957 rows x 4 columns]\n\n \"\"\"\n self._check_data(data_path, data)\n if self.fit_model is None:\n raise ValueError(\"model has not been fitted yet\")\n all_data, df = self._data_helper(data_path = data_path, data = data,\n defaults = self.defaults, skills = self.skills,\n model_type = self.model_type, gs_ref = self.fit_model,\n resource_ref = self.fit_model,\n return_df = True)\n # default best effort prediction of 0.5\n df['correct_predictions'] = 0.5\n df['state_predictions'] = 0.5\n for skill in all_data:\n correct_predictions, state_predictions = self._predict(self.fit_model[skill], all_data[skill])\n state_predictions = state_predictions[1]\n if all_data[skill]['multiprior_index'] is not None:\n correct_predictions = np.delete(correct_predictions, all_data[skill]['multiprior_index'])\n state_predictions = np.delete(state_predictions, all_data[skill]['multiprior_index'])\n df.loc[all_data[skill]['index'], 'correct_predictions'] = correct_predictions\n df.loc[all_data[skill]['index'], 'state_predictions'] = state_predictions\n return df\n\n def evaluate(self, data = None, data_path = None, metric = metrics.rmse):\n \"\"\"\n Evaluates a BKT model given model and data information. Takes a metric and\n data location or DataFrame as arguments. Returns the value of the metric\n for the given trained model tested on the given data.\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.evaluate(data_path = 'as.csv', metric = 'auc')\n 0.6128265543747811\n\n \"\"\"\n self._check_data(data_path, data)\n if not isinstance(metric, (tuple, list)):\n metric = [metric]\n if self.fit_model is None:\n raise ValueError(\"model has not been fitted yet\")\n else:\n for i in range(len(metric)):\n m = metric[i]\n if isinstance(m, str):\n if not m in metrics.SUPPORTED_METRICS:\n raise ValueError(\"metric must be one of: \" + \", \".join(metrics.SUPPORTED_METRICS))\n metric[i] = metrics.SUPPORTED_METRICS[m] \n elif not callable(m):\n raise ValueError(\"metric must either be a string, function or list/tuple of strings and functions\")\n\n all_data = self._data_helper(data_path, data, self.defaults, self.skills, self.model_type,\n gs_ref = self.fit_model, resource_ref = self.fit_model)\n results = self._evaluate(all_data, metric)\n return results[0] if len(results) == 1 else results\n\n def crossvalidate(self, data = None, data_path = None, metric = metrics.rmse, **kwargs):\n \"\"\"\n Crossvalidates (trains and evaluates) the BKT model. Takes the data, metric, and any\n arguments that would be passed to the fit function (skills, number of initialization fits, \n default column names, parallelization, and model types) as arguments.\n\n >>> model = Model(seed = 42)\n >>> model.crossvalidate(data_path = 'as.csv')\n mean_error\n skill\n Circle Graph 0.45840\n Percent Of 0.38005\n Finding Percents 0.42757\n Equivalent Fractions 0.45754\n Proportion 0.45437\n ... ...\n Solving Systems of Linear Equations 0.38976\n Simplifying Expressions positive exponents 0.46494\n Parts of a Polyomial, Terms, Coefficient, Monom... 0.33278\n Finding Slope From Equation 0.30684\n Recognize Quadratic Pattern 0.00000\n\n [110 rows x 1 columns]\n\n \"\"\"\n metric_names = []\n if not isinstance(metric, (tuple, list)):\n metric = [metric]\n if not isinstance(data, pd.DataFrame) and not isinstance(data_path, str):\n raise ValueError(\"no data specified\")\n else:\n for i in range(len(metric)):\n m = metric[i]\n if isinstance(m, str):\n if not m in metrics.SUPPORTED_METRICS:\n raise ValueError(\"metric must be one of: \" + \", \".join(metrics.SUPPORTED_METRICS))\n metric[i] = metrics.SUPPORTED_METRICS[m]\n metric_names.append(m)\n elif callable(m):\n metric_names.append(m.__name__)\n else:\n raise ValueError(\"metric must either be a string, function or list/tuple of strings and functions\")\n\n self._check_args(Model.CV_ARGS, kwargs)\n self._update_param(['skills', 'num_fits', 'defaults', \n 'parallel', 'forgets', 'seed', 'folds'], kwargs)\n self._update_param('model_type', self._update_defaults(kwargs))\n metric_vals = {}\n if not self.manual_param_init:\n self.fit_model = {}\n if isinstance(self.folds, str):\n self._update_defaults({'folds': self.folds})\n all_data = self._data_helper(data_path, data, self.defaults, self.skills, self.model_type, folds = isinstance(self.folds, str))\n self._update_param(['skills'], {'skills': list(all_data.keys())})\n for skill in all_data:\n metric_vals[skill] = self._crossvalidate(all_data[skill], skill, metric)\n self.manual_param_init = False\n self.fit_model = {}\n df = pd.DataFrame(metric_vals.items())\n df.columns = ['skill', 'dummy']\n df[metric_names] = pd.DataFrame(df['dummy'].tolist(), index = df.index)\n return df.set_index('skill').drop(columns = 'dummy')\n\n @property\n def coef_(self):\n \"\"\"\n Returns the learned or preset parameters in the BKT model. Errors if model\n has not been fit or initialized. Note that the parameters are unique for\n each trained skill.\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.coef_\n {'Box and Whisker': {'learns': array([0.17969027]), 'forgets': array([0.01269486]), 'guesses': array([0.26595481]), 'slips': array([0.14831746]), 'prior': 0.8268892896231745}}\n\n \"\"\"\n if not self.fit_model:\n raise ValueError(\"model has not been trained or initialized\")\n return {skill: {param: self.fit_model[skill][param] for param in Model.INITIALIZABLE_PARAMS\n if param in self.fit_model[skill]}\n for skill in self.fit_model}\n\n @coef_.setter\n def coef_(self, values, fixed = None):\n \"\"\"\n Sets or initializes parameters in the BKT model. Values must be organized\n by skill and the BKT parameters as follows: {skill_name: {'learns': ..., 'guesses': ...}.\n Note that all parameters except the prior must be NumPy arrays.\n\n >>> model = Model(seed = 42)\n >>> model.coef_ = {'Box and Whisker': {'prior': 0.5}}\n >>> model.coef_\n {'Box and Whisker': {'prior': 0.5}}\n >>> model.fit(data_path = 'as.csv', forgets = True, skills = 'Box and Whisker')\n >>> model.coef_\n {'Box and Whisker': {'prior': 0.8221172842316857, 'learns': array([0.17918678]), 'guesses': array([0.27305474]), 'slips': array([0.14679578]), 'forgets': array([0.01293728])}}\n\n \"\"\"\n self.fit_model = {}\n for skill in values:\n if skill not in self.fit_model:\n self.fit_model[skill] = {}\n if not self._check_params(values[skill]):\n raise ValueError(\"error in length, type or non-existent parameter\")\n for param in values[skill]:\n self.fit_model[skill][param] = values[skill][param]\n self.manual_param_init = True\n\n def params(self):\n \"\"\" \n Returns a DataFrame containing fitted parameters for easy\n printing.\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', multilearn = True, forgets = True, skills = 'Box and Whisker')\n >>> model.params()\n value\n skill param class \n Box and Whisker prior default 0.67443\n learns 30799 0.16737\n 30059 0.33788\n 30060 0.28723\n 63448 0.10231\n 63447 0.07025\n 63446 0.13453\n guesses default 0.31793\n slips default 0.12543\n forgets 30799 0.00000\n 30059 0.04908\n 30060 0.01721\n 63448 0.03895\n 63447 0.00000\n 63446 0.01058\n\n \"\"\"\n coefs = self.coef_\n formatted_coefs = []\n for skill in coefs:\n for param in coefs[skill]:\n classes = self._format_param(skill, param, coefs[skill][param])\n for class_ in classes:\n formatted_coefs.append((skill, param, str(class_), classes[class_]))\n df = pd.DataFrame(formatted_coefs)\n df.columns = ['skill', 'param', 'class', 'value']\n return df.set_index(['skill', 'param', 'class'])\n\n def save(self, loc):\n \"\"\"\n Saves a model to disk. Uses Python pickles.\n\n >>> model = Model(seed = 42)\n >>> model.fit(data_path = 'as.csv', multilearn = True, forgets = True, skills = 'Box and Whisker')\n >>> model.save('model.pkl')\n \"\"\"\n with open(loc, 'wb') as handle:\n pickle.dump(self, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n def load(self, loc):\n \"\"\"\n Loads model given by loc into the current model.\n\n >>> model = Model(seed = 42)\n >>> model.load('model.pkl')\n \"\"\"\n with open(loc, 'rb') as handle:\n orig_model = pickle.load(handle)\n for attr in vars(orig_model):\n setattr(self, attr, getattr(orig_model, attr))\n\n\n def fetch_dataset(self, link, loc):\n \"\"\"\n Fetches dataset from an online link. Must be accessible without password\n or other authentication. Saves to the given location.\n\n >>> model = Model()\n >>> model.fetch_dataset('https://raw.githubusercontent.com/CAHLR/pyBKT-examples/master/data/as.csv', '.')\n \"\"\"\n file_data = urllib2.urlopen(link)\n name = link.split('/')[-1]\n with open(os.path.normpath(loc + '/' + name), 'wb') as f:\n f.write(file_data.read())\n\n def _data_helper(self, data_path, data, defaults, skills, model_type, gs_ref = None, resource_ref = None, return_df = False, folds = False):\n \"\"\" Processes data given defaults, skills, and the model type. \"\"\"\n if isinstance(data_path, str):\n data_p = data_helper.convert_data(data_path, skills, defaults = defaults, model_type = model_type, \n gs_refs = gs_ref, resource_refs = resource_ref, return_df = return_df, folds = folds)\n elif isinstance(data, pd.DataFrame):\n data_p = data_helper.convert_data(data, skills, defaults = defaults, model_type = model_type,\n gs_refs = gs_ref, resource_refs = resource_ref, return_df = return_df, folds = folds)\n if not return_df:\n for d in data_p.values():\n check_data.check_data(d)\n else:\n for d in data_p[0].values():\n check_data.check_data(d)\n return data_p\n\n def _fit(self, data, skill, forgets, preload = False):\n \"\"\" Helper function for fitting data. \"\"\"\n num_learns = len(data[\"resource_names\"])\n num_gs = len(data[\"gs_names\"])\n self._check_manual_param_init(num_learns, num_gs, skill)\n if hasattr(self, \"fixed\"):\n self._check_fixed(self)\n num_fit_initializations = self.num_fits\n best_likelihood = float(\"-inf\")\n best_model = None\n\n for i in range(num_fit_initializations):\n fitmodel = random_model_uni.random_model_uni(num_learns, num_gs)\n optional_args = {'fixed': {}}\n if forgets:\n fitmodel[\"forgets\"] = np.random.uniform(size = fitmodel[\"forgets\"].shape)\n if self.model_type[Model.MODELS_BKT.index('multiprior')]:\n fitmodel[\"prior\"] = 0\n if self.manual_param_init and skill in self.fit_model:\n for var in self.fit_model[skill]:\n if self.fixed is not None and skill in self.fixed and var in self.fixed[skill] and \\\n isinstance(self.fixed[skill][var], bool) and self.fixed[skill][var]:\n optional_args['fixed'][var] = self.fit_model[skill][var] \n elif var in fitmodel:\n fitmodel[var] = self.fit_model[skill][var]\n if hasattr(self, \"fixed\") and self.fixed is not None and skill in self.fixed:\n for var in self.fixed[skill]:\n if not isinstance(self.fixed[skill][var], bool):\n optional_args['fixed'][var] = self.fixed[skill][var]\n if not preload:\n fitmodel, log_likelihoods = EM_fit.EM_fit(fitmodel, data, parallel = self.parallel, **optional_args)\n if log_likelihoods[-1] > best_likelihood:\n best_likelihood = log_likelihoods[-1]\n best_model = fitmodel\n else:\n best_model = fitmodel\n fit_model = best_model\n fit_model[\"learns\"] = fit_model[\"As\"][:, 1, 0]\n fit_model[\"forgets\"] = fit_model[\"As\"][:, 0, 1]\n fit_model[\"prior\"] = fit_model[\"pi_0\"][1][0]\n fit_model[\"resource_names\"] = data[\"resource_names\"]\n fit_model[\"gs_names\"] = data[\"gs_names\"]\n return fit_model\n \n def _predict(self, model, data):\n \"\"\" Helper function for predicting. \"\"\"\n return predict_onestep.run(model, data)\n\n def _evaluate(self, all_data, metric):\n \"\"\" Helper function for evaluating. \"\"\"\n per_skill = []\n true, pred = [], []\n for skill in all_data:\n correct_predictions, state_predictions = self._predict(self.fit_model[skill], all_data[skill])\n real_data = all_data[skill]['data']\n true = np.append(true, real_data.sum(axis = 0))\n pred = np.append(pred, correct_predictions)\n true = true - 1\n try:\n res = [m(true, pred) for m in metric]\n except ValueError:\n res = [m(true, pred.round(0)) for m in metric]\n return res\n\n def _crossvalidate(self, data, skill, metric):\n \"\"\" Helper function for crossvalidating. \"\"\"\n if isinstance(self.folds, str):\n return crossvalidate.crossvalidate(self, data, skill, self.folds, metric, self.seed, True)\n else:\n return crossvalidate.crossvalidate(self, data, skill, self.folds, metric, self.seed)\n\n def _format_param(self, skill, param, value):\n \"\"\" Formats parameter for nice printing. \"\"\"\n if isinstance(value, np.ndarray):\n ptype = 'resource_names' if (param == 'learns' or param == 'forgets') \\\n else 'gs_names'\n names = [str(i) for i in self.fit_model[skill][ptype]]\n return dict(sorted(zip(names, value)))\n else:\n return {'default': value}\n\n def _check_fixed(self, fixed):\n \"\"\" Checks fixed parameter. \"\"\"\n if self.fixed is None:\n return\n elif isinstance(self.fixed, bool) and self.fixed:\n self.fixed = self.fit_model\n elif isinstance(self.fixed, dict):\n return\n else:\n raise ValueError(\"fixed parameter incorrectly specified\")\n\n\n def _update_param(self, params, args, keep = False):\n \"\"\" Updates parameters given kwargs. \"\"\"\n if isinstance(args, dict):\n for param in params:\n if param not in args and (param not in self.keep or not self.keep[param]):\n setattr(self, param, Model.DEFAULTS[param])\n elif param in args:\n setattr(self, param, args[param])\n self.keep[param] = keep\n else:\n setattr(self, params, args)\n self.keep[params] = keep\n\n def _update_defaults(self, defaults):\n \"\"\" Update the default column names. \"\"\"\n model_types = [False] * 4\n for d in defaults:\n if d in Model.MODELS_BKT:\n if isinstance(defaults[d], bool):\n model_types[Model.MODELS_BKT.index(d)] = defaults[d]\n elif isinstance(defaults[d], str):\n if self.defaults is None:\n self.defaults = {}\n self.defaults[d] = defaults[d]\n model_types[Model.MODELS_BKT.index(d)] = True\n else:\n raise ValueError(\"model type must either be boolean for automatic column inference\" + \\\n \" or string specifying column\")\n elif d in Model.DEFAULTS_BKT:\n if self.defaults is None:\n self.defaults = {}\n self.defaults[d] = defaults[d]\n return model_types\n\n def _check_params(self, params):\n \"\"\" Checks if BKT parameters are valid. \"\"\"\n valid = True\n for param in params:\n if param == 'prior':\n valid = valid and isinstance(params[param], numbers.Number)\n else:\n valid = valid and isinstance(params[param], np.ndarray) \\\n and param in Model.INITIALIZABLE_PARAMS\n if 'learns' in params and 'forgets' in params:\n valid = valid and (len(params['learns']) == len(params['forgets']))\n if 'guesses' in params and 'slips' in params:\n valid = valid and (len(params['slips']) == len(params['guesses']))\n return valid\n\n def _check_manual_param_init(self, num_learns, num_gs, skill):\n if self.fit_model and skill in self.fit_model and 'learns' in self.fit_model[skill] \\\n and len(self.fit_model[skill]['learns']) != num_learns:\n raise ValueError(\"invalid number of learns in initialization\")\n if self.fit_model and skill in self.fit_model and 'guesses' in self.fit_model[skill] \\\n and len(self.fit_model[skill]['guesses']) != num_gs:\n raise ValueError(\"invalid number of guess classes in initialization\")\n if self.fit_model and skill in self.fit_model and 'slips' in self.fit_model[skill] \\\n and len(self.fit_model[skill]['slips']) != num_gs:\n raise ValueError(\"invalid number of slip classes in initialization\")\n\n def _check_args(self, expected_args, args):\n for arg in args:\n if arg not in expected_args:\n raise ValueError(\"provided arguments are not recognized. they must be one or more of: \" + \\\n \", \".join(expected_args))\n\n def _check_data(self, data_path, data):\n if not isinstance(data_path, str) and not isinstance(data, pd.DataFrame):\n raise ValueError(\"no data specified\")\n elif isinstance(data_path, str) and isinstance(data, pd.DataFrame):\n raise ValueError(\"cannot specify both data location and data\")\n elif isinstance(data_path, str) and not os.path.exists(data_path):\n raise ValueError(\"data path is invalid or file not found\")\n\n def __repr__(self):\n ret = 'Model('\n args = ['%s=%s' % (arg, str(getattr(self, arg))) for arg in Model.MODEL_ARGS if hasattr(self, arg)]\n ret += ', '.join(args) + ')'\n return ret\n"
]
| [
[
"pandas.DataFrame",
"numpy.delete",
"numpy.random.uniform",
"numpy.append"
]
]
|
mananmadan/Ontology-Based-Concept-Similarity | [
"7f9ca63b3b4ef40bd2e8ece8c0872f14a4fade9b"
]
| [
"kntool/test_version.py"
]
| [
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 18 20:12:38 2020\n\n@author: manan\n\"\"\"\nimport nltk\nimport re\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom nltk.tokenize import PunktSentenceTokenizer\n\n\n\n#reading the data:\npst = PunktSentenceTokenizer()\nopenfile = open(\"data.txt\")\ndata = openfile.read()\ndata=data.decode('utf-8')\n\n#tokenizing:\ntokenized_sentence = pst.tokenize(data)\n\n#making a list for storing pos vs original word\nwordlist = []\n\n\n#chunk formation and converting to a string:\nstringlist = []\nfor i in tokenized_sentence:\n #try:\n words = nltk.word_tokenize(i)\n tagged = nltk.pos_tag(words)\n count=0\n for i in words:#loop to map pos form to original word\n #print(tagged[count][0]+\"/\"+tagged[count][1])\n if len(tagged[count])==2:\n wordlist.append([tagged[count][0]+\"/\"+tagged[count][1]])\n count = count+1\n\n chunkGram = r\"\"\"Chunk: {<JJ.?>{0,2}<VBG>{0,1}<NN.?>{1,2}<VBG>{0,1}<NN..?>{0,2}<VBG>{0,1}}\"\"\"\n chunkParser = nltk.RegexpParser(chunkGram)\n chunked = chunkParser.parse(tagged)\n print(chunked)\n stringlist.append(chunked.pformat().encode('ascii','ignore'))\n #except Exception as e:\n # print(str(e))\n\n\n\n\n#string extraction:\nindex = 0\nlistoflist = []\nfor f in stringlist:\n String = f\n chunklist = []\n iter = re.finditer(r\"\\Chunk\\b\", String)\n indices = [m.start(0) for m in iter]\n for x in indices:\n j=1\n temp =\"\"\n while(stringlist[index][x+5+j]!=')'):\n temp = temp + stringlist[index][x+5+j]\n j = j+1\n chunklist.append(temp)\n index = index + 1\n listoflist.append(chunklist)\n#print(listoflist)\n\n\n\n\n\n\n#graph connection :\nsource = []\ntarget = []\n\nfor i in listoflist:\n temp_source = []\n temp_target = []\n for j in i:\n temp_source.append(j)\n temp_target.append(j)\n if len(temp_source)!=0 and len(temp_target)!=0:\n temp_source.pop(len(temp_source)-1)\n temp_target.pop(0)\n for x in temp_source:\n source.append(x)\n for y in temp_target:\n target.append(y)\nfinal_source = []\nfinal_target = []\nfor i in source:\n final_source.append('('+ i +')')\n\nfor i in target:\n final_target.append('('+ i + ')')\n\n\n\n\n#putting data into the data frame and creating graph:\nkg_df = pd.DataFrame({'source':final_source, 'target':final_target})\nprint(\"printing pandas data frame--------\")\nprint(kg_df)\nG=nx.from_pandas_edgelist(kg_df, \"source\", \"target\")\n\n\n\nmax = 0\nfinal_k1=0\nfinal_k2=0\nfinal_k3=0\nmatch_value=0\n#doing data analysis:\nfor k1 in range(0,3):\n for k2 in range(0,3):\n for k3 in range(0,3):\n somelist = [[0,\"\"]]\n done = []\n for i in final_source :\n temp_sum = 0\n conn_nodes = 0\n temp_count = 0\n for j in final_target:\n try:\n temp_sum = temp_sum + nx.shortest_path_length(G,i,j)\n if nx.shortest_path_length(G,i,j) == 1 :\n conn_nodes = conn_nodes + 1#directly connected nodes\n for temp in final_source :\n if temp == i :\n temp_count = temp_count+1\n except:\n temp_sum = temp_sum + 0\n if i not in done :\n somelist.append((k1*(conn_nodes)+k2*(temp_count)+k3*(len(i)),i))\n done.append((i))\n #somelist.sort()\n #print(\"sort()\")\n #for i in somelist:\n #print(i)\n somelist.sort(reverse = True)\n #print(\"reverse_sort()\")\n #for i in somelist:\n #print(i)\n\n\n ##extract info for control loop\n output = []\n temp_somlist_count = 0\n for i in somelist:\n if temp_somlist_count==10:\n break\n else :\n output.insert(temp_somlist_count,i)\n temp_somlist_count = temp_somlist_count+1\n\n print(output)\n\n #find if matching is possible:\n expected_output = [\"committee of decision\",\"ensemble learning\",\"machine learning model\",\"help of source\",\"high confidence\",\"different decision ensemble\",\"training data\",\"updated sample distribution\",\"weighted majority voting\",\"artificial training example\"]\n final_count = 0\n for i in output:\n for j in expected_output:\n #print(j)\n relist = re.split(r'\\s',j)\n #print(relist)\n for temp in relist:\n if re.search(temp,i[1]):\n #print(\"finding in\")\n #print(i[1])\n final_count = final_count+1\n \n print(str(final_count)+str(\":\")+str(k1)+str(\":\")+str(k2)+str(\":\")+str(k3))\n if final_count>max:\n max = final_count\n print(\"improved:\")\n print(str(max)+str(\":\")+str(k1)+str(\":\")+str(k2)+str(\":\")+str(k3))\n match_value = max\n final_k1 = k1\n final_k2 = k2\n final_k3 = k3\nprint(\"final_values\")\nprint(match_value)\nprint(final_k1)\nprint(final_k2)\nprint(final_k3)\n#plotting the graph:\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G)\nnx.draw(G, with_labels=True, node_color='skyblue', edge_cmap=plt.cm.Blues, pos = pos)\n#plt.show()\n"
]
| [
[
"pandas.DataFrame",
"matplotlib.pyplot.figure"
]
]
|
chilung/VisDA1 | [
"d5bafb7c6048f56483d2b03ae7040eee7a60af71"
]
| [
"modeling/backbones/resnet_ibn_a.py"
]
| [
"import torch\nimport torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n__all__ = ['ResNet_IBN', 'resnet50_ibn_a', 'resnet101_ibn_a',\n 'resnet152_ibn_a']\n\n\nmodel_urls = {\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\nclass IBN(nn.Module):\n def __init__(self, planes):\n super(IBN, self).__init__()\n half1 = int(planes/2)\n self.half = half1\n half2 = planes - half1\n self.IN = nn.InstanceNorm2d(half1, affine=True)\n self.BN = nn.BatchNorm2d(half2)\n \n def forward(self, x):\n split = torch.split(x, self.half, 1)\n out1 = self.IN(split[0].contiguous())\n out2 = self.BN(split[1].contiguous())\n out = torch.cat((out1, out2), 1)\n return out\n\n\nclass Bottleneck_IBN(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, ibn=False, stride=1, downsample=None):\n super(Bottleneck_IBN, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n if ibn:\n self.bn1 = IBN(planes)\n else:\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n \n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck_IBN_LeaklyRelu(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, ibn=False, stride=1, downsample=None):\n super(Bottleneck_IBN_LeaklyRelu, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n if ibn:\n self.bn1 = IBN(planes)\n else:\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n self.relu = nn.LeakyReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\nclass ResNet_IBN(nn.Module):\n\n def __init__(self, last_stride, block, layers, num_classes=1000):\n scale = 64\n self.inplanes = scale\n super(ResNet_IBN, self).__init__()\n self.conv1 = nn.Conv2d(3, scale, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(scale)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, scale, layers[0])\n self.layer2 = self._make_layer(block, scale*2, layers[1], stride=2)\n self.layer3 = self._make_layer(block, scale*4, layers[2], stride=2)\n self.layer4 = self._make_layer(block, scale*8, layers[3], stride=last_stride)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.InstanceNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n ibn = True\n if planes == 512:\n ibn = False\n layers.append(block(self.inplanes, planes, ibn, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, ibn))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n \n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n def load_param(self, model_path):\n param_dict = torch.load(model_path, map_location='cpu')\n # param_dict = torch.load(model_path)\n if 'state_dict' in param_dict:\n param_dict = param_dict['state_dict']\n for i in param_dict:\n if 'fc' in i:\n continue\n self.state_dict()[i.replace('module.','')].copy_(param_dict[i])\n\n\ndef resnet50_ibn_a(last_stride, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\ndef resnet101_ibn_a(last_stride, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 23, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\ndef resnet152_ibn_a(last_stride, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model\n"
]
| [
[
"torch.cat",
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.split",
"torch.nn.LeakyReLU",
"torch.utils.model_zoo.load_url",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.load"
]
]
|
CombatCovid/operation-air-ventilator | [
"0f11748f2b57ef8f1b3af6bb73581e778cbb0d88"
]
| [
"src/Software/src/utils/anamolyDetection.py"
]
| [
"from enum import Enum\nfrom queue import Queue\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import collections as mc\nfrom matplotlib import colors as cl\n\nfrom models.mcuSettingsModel import Settings\nfrom utils.logPlayer import replay_log\n\n\nclass Anomaly(Enum):\n NONE = 0\n PEEP_TOO_HIGH = 1\n PEEP_TOO_LOW = 2\n PRESS_TOO_HIGH = 3\n PRESS_TOO_LOW = 4\n\ndef check_for_anomalies(sensor_frame, settings, visualize=False):\n # Determine current pressure and breathing phase\n curr_press = sensor_frame.pressure\n current_phase = determine_phase(sensor_frame, visualize)\n\n # Check for PEEP values\n if curr_press < settings.min_peep: return Anomaly.PEEP_TOO_LOW\n if current_phase == 4 and curr_press > settings.max_peep: return Anomaly.PEEP_TOO_HIGH\n\n # Check for pressure values\n if current_phase == 2 and curr_press < settings.min_pressure: return Anomaly.PRESS_TOO_LOW\n if curr_press > settings.max_pressure: return Anomaly.PRESS_TOO_HIGH\n\n return Anomaly.NONE\n\ndef to_line_collection(x, y, colors):\n global BREATH_IN_C, BREATH_IN_MAX_C, BREATH_OUT_C, BREATH_OUT_MIN_C\n points = np.array([x, y]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n colors = colors[1:] # Truncate colors for segments\n rgba_mat = np.zeros(shape=(len(segments), 4))\n rgba_mat[colors == 1] = cl.to_rgba(BREATH_IN_C)\n rgba_mat[colors == 2] = cl.to_rgba(BREATH_IN_MAX_C)\n rgba_mat[colors == 3] = cl.to_rgba(BREATH_OUT_C)\n rgba_mat[colors == 4] = cl.to_rgba(BREATH_OUT_MIN_C)\n return mc.LineCollection(segments, colors=rgba_mat, linewidths=2)\n\n# Convolution helper functions\ndef conv(input, filter): return np.convolve(np.array(input), np.array(filter), 'valid')\ndef conf(input, filter): return np.convolve(np.array(input), np.array(filter), 'full')\n\nBREATH_IN_C = '#3de068'\nBREATH_IN_MAX_C = '#08a112'\nBREATH_OUT_C = '#3bcbff'\nBREATH_OUT_MIN_C = '#057c87'\n\nsensor_buffer = []\nstate_buffer = np.array([], dtype=int)\ncycle_start_index = 0\nreached_extrema = False\nprev_cycle_state = None\nplt_axes = None\ndef determine_phase(sensor_frame, visualize=False):\n \"\"\"\n Dynamically determines the current breathing phase.\n This is any of the 4 following phases:\n - 1: Starting to breath in \n - 2: Holding breath, highest pressure at this point\n - 3: Starting to breath out\n - 4: Finished breathing out, lowest pressure at this point\n The phase is returned as an integer [1-4].\n \"\"\"\n global prev_cycle_state, reached_extrema, state_buffer, plt_axes, sensor_buffer, cycle_start_index\n\n # Store and retrieve data\n sensor_buffer.append(sensor_frame)\n x = np.arange(len(sensor_buffer))\n y = np.array([sf.pressure for sf in sensor_buffer])\n\n # Calculate signal derivative\n delta_filter = conf([0.5, 0.5], [1, -1])\n valid_delta = len(x) >= len(delta_filter)\n if valid_delta:\n dx = np.arange(len(delta_filter) - 1, len(sensor_buffer))\n dy = conv(y, delta_filter)\n\n # Determine current breath state\n if prev_cycle_state is not None and sensor_frame.cycle_state != prev_cycle_state: reached_extrema = False; cycle_start_index = len(sensor_buffer) - 1\n breath_state = 1 if sensor_frame.cycle_state == 1 else 3\n if not reached_extrema and valid_delta and len(dx) > 5 and len(sensor_buffer) - cycle_start_index > 5:\n if np.mean(dy[-5:-1]) < 0.5 and np.var(dy[-5:-1]) < 1: reached_extrema = True\n elif reached_extrema: breath_state = 2 if sensor_frame.cycle_state == 1 else 4\n state_buffer = np.append(state_buffer, breath_state)\n prev_cycle_state = sensor_frame.cycle_state\n\n # Make plot dynamic\n if not visualize or len(x) < 2: return breath_state\n if not mpl.is_interactive():\n plt.ion()\n _, plt_axes = plt.subplots(2, figsize=(10, 5))\n plt.subplots_adjust(hspace=0.35, left=0.09, right=0.95, bottom=0.07, top=0.91)\n plt.show()\n for ax in plt_axes: ax.clear()\n PLOT_SIZE = 100\n\n # Plot main graph\n plt_axes[0].set_title(\"Pressure over time\")\n plt_axes[0].set_xlim(x[-PLOT_SIZE:-1].min() - 1, x[-PLOT_SIZE:-1].max() + 1)\n plt_axes[0].set_ylim(y[-PLOT_SIZE:-1].min() - 5, y[-PLOT_SIZE:-1].max() + 5)\n plt_axes[0].add_collection(to_line_collection(x[-PLOT_SIZE:-1], y[-PLOT_SIZE:-1], state_buffer[-PLOT_SIZE:-1]))\n\n # Plot derivative\n plt_axes[1].set_title(\"Pressure change over time\")\n if valid_delta: plt_axes[1].plot(dx[-PLOT_SIZE:-1], dy[-PLOT_SIZE:-1])\n\n # Render plot\n plt.draw(); plt.pause(0.00000000001)\n print(\"Drawing plot\")\n return breath_state\n\n# If script is ran standalone, replay log\nif __name__ == \"__main__\":\n callback_queue = replay_log('sensors_0.csv', 250)\n while True:\n callback = callback_queue.get()\n anomalies = check_for_anomalies(callback, visualize=True)\n if anomalies == Anomaly.NONE: str = 'No anomalies.'\n elif anomalies == Anomaly.PEEP_TOO_LOW: str = 'PEEP WAS TOO LOW!'\n elif anomalies == Anomaly.PEEP_TOO_HIGH: str = 'PEEP WAS TOO HIGH!'\n elif anomalies == Anomaly.PRESS_TOO_LOW: str = 'PRESSURE WAS TOO LOW!'\n elif anomalies == Anomaly.PRESS_TOO_HIGH: str = 'PRESSURE WAS TOO HIGH!'\n print(str)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"matplotlib.pyplot.ion",
"matplotlib.colors.to_rgba",
"matplotlib.pyplot.subplots",
"numpy.mean",
"matplotlib.collections.LineCollection",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.pause",
"matplotlib.is_interactive",
"numpy.append",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots_adjust",
"numpy.var"
]
]
|
talbertc-usgs/pyphenocam | [
"a414857c0915c26d804c98852c1d509046ef5d81"
]
| [
"notebooks/animation.py"
]
| [
"\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport sys\nimport datetime as dt\n\nsys.path.append(r\"..\")\nimport pyphenocam\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport rasterio\n\n\n# In[2]:\n\nbase_dname = r\"J:\\Projects\\NCCSC\\phenocam\\DerivedData\\nationalelkrefuge\"\nsite_name = \"nationalelkrefuge\"\n\n\n# In[3]:\n\nphenosite = pyphenocam.dataaccess.get_site(site_name)\n\n\n# In[4]:\n\nget_ipython().magic('matplotlib inline')\nlandsat_fishnet_fname = os.path.join(base_dname, \"ArcScene\", \"landsat_fishnet.bmp\")\nlandsat_index_fname = os.path.join(base_dname, \"ArcScene\", \"landsat_subset_index.bmp\")\n\nphenosite = pyphenocam.dataaccess.get_site(site_name)\n\nclosest_date = dt.datetime(2016, 5, 29, 12, 30)\nprint(closest_date)\nsample_photo_fname = phenosite.get_closest_fname(closest_date)\n\nlocal_fname = phenosite.get_local_image_fname(sample_photo_fname)\nlocal_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\nsample_image = phenosite.get_local_image(sample_photo_fname)\nsample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\nfig, ax = plt.subplots(1, figsize=(12,5))\nax.imshow(sample_image)\npyphenocam.plotting.format_photo_axes(ax)\n\n\n# In[5]:\n\nimport numpy as np\nimport skimage.transform as trans\n\nimport skimage\nindex = skimage.io.imread(landsat_index_fname)\nsky = (np.sum(index, axis=2) == 765)\n#resize sky to match our sample_image\nsky = trans.resize(sky, (sample_image.shape[0], sample_image.shape[1]), preserve_range=True, order=0).astype(np.bool)\n\n\n# In[6]:\n\nfig, ax = plt.subplots(1, figsize=(12,5))\nax.imshow(sample_image)\nax.imshow(sky, alpha=0.5, cmap=mpl.cm.jet_r)\npyphenocam.plotting.format_photo_axes(ax)\n\n\n# In[7]:\n\ndef get_bluesky(sample_image, sky):\n blue = sample_image[:,:,2] / np.sum(sample_image, axis=2).astype(np.float32)\n pcnt_bluesky = 1 - np.mean(sample_image[sky][:, 2])/255.\n return pcnt_bluesky\n\n\n# In[8]:\n\nclosest_date = dt.datetime(2016, 5, 29, 12, 30)\nprint(closest_date)\nsample_photo_fname = phenosite.get_closest_fname(closest_date)\n\nlocal_fname = phenosite.get_local_image_fname(sample_photo_fname)\nlocal_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\nsample_image = phenosite.get_local_image(sample_photo_fname)\nsample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\nfig, ax = plt.subplots(1, figsize=(12,5))\n# ax.imshow(sample_image)\nblue = sample_image[:,:,2] / np.sum(sample_image, axis=2).astype(np.float32)\nax.imshow(blue)\npyphenocam.plotting.format_photo_axes(ax)\nprint(get_bluesky(sample_image, sky))\n\n\n# In[9]:\n\nclosest_date = dt.datetime(2015, 9, 1, 12, 30)\nprint(closest_date)\nsample_photo_fname = phenosite.get_closest_fname(closest_date)\n\nlocal_fname = phenosite.get_local_image_fname(sample_photo_fname)\nlocal_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\nsample_image = phenosite.get_local_image(sample_photo_fname)\nsample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\nfig, ax = plt.subplots(1, figsize=(12,5))\n# ax.imshow(sample_image)\nblue = sample_image[:,:,2] / np.sum(sample_image, axis=2).astype(np.float32)\nax.imshow(blue)\npyphenocam.plotting.format_photo_axes(ax)\n\nprint(get_bluesky(sample_image, sky))\n\n\n# In[14]:\n\nclosest_date = dt.datetime(2015, 10, 1, 12, 30)\nprint(closest_date)\nsample_photo_fname = phenosite.get_closest_fname(closest_date)\n\nlocal_fname = phenosite.get_local_image_fname(sample_photo_fname)\nlocal_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\nsample_image = phenosite.get_local_image(sample_photo_fname)\nsample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\nfig, ax = plt.subplots(1, figsize=(12,5))\nax.imshow(sample_image)\npyphenocam.plotting.format_photo_axes(ax)\n\nprint(get_bluesky(sample_image, sky))\n\n\n# In[15]:\n\ndef gcc(img):\n gcc = img[:,:, 0].astype(np.float32) / np.sum(img, axis=2)\n return np.ma.masked_where(sky, gcc)\n\n\n# In[16]:\n\ndef bottom_align_cb(fig, ax, im, height=0.02, shrink=0.01, yoffset=0.08):\n b = ax.get_position()\n b.x0, b.width\n cax = fig.add_axes([b.x0 + shrink, b.y0 + yoffset, \n b.width - (shrink * 2), height])\n fig.colorbar(im, cax=cax, orientation='horizontal')\n return cax\n\n\n# In[22]:\n\nclosest_date = dt.datetime(2016, 6, 1, 12, 30)\nprint(closest_date)\nsample_photo_fname = phenosite.get_closest_fname(closest_date)\n\nlocal_fname = phenosite.get_local_image_fname(sample_photo_fname)\nlocal_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\nsample_image = phenosite.get_local_image(sample_photo_fname)\nsample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\nexposure = pyphenocam.headerextraction.get_exposure(local_fname)\nexposure_ir = pyphenocam.headerextraction.get_exposure(local_fname_ir)\n\ncorrected_ndvi = pyphenocam.imageprocessing._get_corrected_ndvi(local_fname, \n local_fname_ir, \n float(exposure), \n float(exposure_ir))\ncorrected_ndvi_m = np.ma.masked_where(sky, corrected_ndvi)\n\nfig, (ax_photo, ax_ndvi, ax_gcc) = plt.subplots(1, 3, figsize=(15,5))\npyphenocam.plotting.format_photo_axes(ax_photo)\npyphenocam.plotting.format_photo_axes(ax_ndvi)\npyphenocam.plotting.format_photo_axes(ax_gcc)\n\npyphenocam.plotting.add_inner_title(ax_ndvi, \"NDVI\", \n 2, dict(size=25, alpha=0.5))\npyphenocam.plotting.add_inner_title(ax_gcc, \"GCC\", \n 2, dict(size=25, alpha=0.5))\n\nexp_title = pyphenocam.plotting.add_inner_title(ax_photo, \"Exp: {}\\nIR Exp: {}\".format(exposure, exposure_ir), \n 1, dict(size=15, alpha=0.5))\ndate_title = pyphenocam.plotting.add_inner_title(ax_ndvi, \"{dt.month}/{dt.day}/{dt.year} {dt.hour}:{dt.minute}\".format(dt=closest_date), \n 1, dict(size=20, alpha=0.5))\n\nim_photo = ax_photo.imshow(sample_image)\nim_ndvi = ax_ndvi.imshow(corrected_ndvi_m, vmin=0, vmax=1.0, cmap=mpl.cm.RdYlGn)\nim_gcc = ax_gcc.imshow(gcc(sample_image), vmin=0, vmax=0.7, cmap=mpl.cm.RdYlGn)\n\nplt.tight_layout()\nbottom_align_cb(fig, ax_ndvi, im_ndvi)\nbottom_align_cb(fig, ax_gcc, im_gcc)\n\n\n\n# In[18]:\n\n# This example uses a MovieWriter directly to grab individual frames and\n# write them to a file. This avoids any event loop integration, but has\n# the advantage of working with even the Agg backend. This is not recommended\n# for use in an interactive setting.\n# -*- noplot -*-\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as manimation\n\nFFMpegWriter = manimation.writers['ffmpeg']\nmetadata = dict(title='test', artist='Matplotlib',\n comment='test2')\nwriter = FFMpegWriter(fps=10, bitrate=5000, metadata=metadata)\n\nfig, (ax_photo, ax_ndvi, ax_gcc) = plt.subplots(1, 3, figsize=(15,5))\npyphenocam.plotting.format_photo_axes(ax_photo)\npyphenocam.plotting.format_photo_axes(ax_ndvi)\npyphenocam.plotting.format_photo_axes(ax_gcc)\n\npyphenocam.plotting.add_inner_title(ax_ndvi, \"NDVI\", \n 2, dict(size=25, alpha=0.5))\npyphenocam.plotting.add_inner_title(ax_gcc, \"GCC\", \n 2, dict(size=25, alpha=0.5))\n\nexp_title = pyphenocam.plotting.add_inner_title(ax_photo, \"Exp: {}\\nIR Exp: {}\".format(exposure, exposure_ir), \n 1, dict(size=12, alpha=0.5))\ndate_title = pyphenocam.plotting.add_inner_title(ax_ndvi, \"{dt.month}/{dt.day}/{dt.year} {dt.hour}:{dt.minute}\".format(dt=closest_date), \n 1, dict(size=15, alpha=0.5))\n\nbottom_align_cb(fig, ax_ndvi, im_ndvi)\nbottom_align_cb(fig, ax_gcc, im_gcc)\n\nwith writer.saving(fig, os.path.join(base_dname, 'natelk.mp4'), 100):\n for month in range(2, 6):\n print(month)\n for day in range(1, 32):\n print(\"\")\n print('\\t', day, '\\t', end=' ')\n for hour in range(9, 16):\n print(hour, end=' ')\n for minute in [0, 30]:\n print(\".\", end=' ')\n try:\n closest_date = dt.datetime(2016, month, day, hour, minute)\n sample_photo_fname = phenosite.get_closest_fname(closest_date)\n\n local_fname = phenosite.get_local_image_fname(sample_photo_fname)\n local_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\n sample_image = phenosite.get_local_image(sample_photo_fname)\n sample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\n exposure = pyphenocam.headerextraction.get_exposure(local_fname)\n exposure_ir = pyphenocam.headerextraction.get_exposure(local_fname_ir)\n corrected_ndvi = pyphenocam.imageprocessing._get_corrected_ndvi(local_fname, \n local_fname_ir, \n float(exposure), \n float(exposure_ir))\n corrected_ndvi_m = np.ma.masked_where(sky, corrected_ndvi)\n\n im_photo = ax_photo.imshow(sample_image)\n im_ndvi = ax_ndvi.imshow(corrected_ndvi_m, vmin=0, vmax=1., cmap=mpl.cm.RdYlGn)\n im_gcc = ax_gcc.imshow(gcc(sample_image), vmin=0, vmax=0.5, cmap=mpl.cm.RdYlGn)\n\n date_title.txt.set_text(\"{dt.month}/{dt.day}/{dt.year} {dt.hour:02d}:{dt.minute:02d}\".format(dt=closest_date))\n exp_title.txt.set_text(\"Exp: {}\\nIR Exp: {}\".format(exposure, exposure_ir))\n \n writer.grab_frame()\n im_photo.remove()\n im_ndvi.remove()\n im_gcc.remove()\n \n del im_photo\n del im_ndvi\n del im_gcc\n \n del sample_image\n del corrected_ndvi\n del corrected_ndvi_m\n del sample_image_ir\n except Exception as e:\n print(\"except:\", str(e))\n try:\n del im\n del im2\n del sample_image\n del corrected_ndvi\n del corrected_ndvi_m\n del sample_image_ir\n except:\n pass\n\n\n# In[ ]:\n\n# This example uses a MovieWriter directly to grab individual frames and\n# write them to a file. This avoids any event loop integration, but has\n# the advantage of working with even the Agg backend. This is not recommended\n# for use in an interactive setting.\n# -*- noplot -*-\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as manimation\n\nFFMpegWriter = manimation.writers['ffmpeg']\nmetadata = dict(title='test', artist='Matplotlib',\n comment='test2')\nwriter = FFMpegWriter(fps=2, bitrate=5000, metadata=metadata)\n\nfig, (ax_photo, ax_ndvi, ax_gcc) = plt.subplots(1, 3, figsize=(15,5))\npyphenocam.plotting.format_photo_axes(ax_photo)\npyphenocam.plotting.format_photo_axes(ax_ndvi)\npyphenocam.plotting.format_photo_axes(ax_gcc)\n\npyphenocam.plotting.add_inner_title(ax_ndvi, \"NDVI\", \n 2, dict(size=25, alpha=0.5))\npyphenocam.plotting.add_inner_title(ax_gcc, \"GCC\", \n 2, dict(size=25, alpha=0.5))\n\nexp_title = pyphenocam.plotting.add_inner_title(ax_photo, \"Exp: {}\\nIR Exp: {}\".format(exposure, exposure_ir), \n 1, dict(size=15, alpha=0.5))\ndate_title = pyphenocam.plotting.add_inner_title(ax_ndvi, \"{dt.month}/{dt.day}/{dt.year} {dt.hour}:{dt.minute}\".format(dt=closest_date), \n 1, dict(size=20, alpha=0.5))\n\n\nwith writer.saving(fig, r'C:\\temp_colin\\downloads\\Python_exploration\\natelk.mp4', 100):\n for month in range(5, 6):\n print(month)\n for day in range(1, 4):\n print(\"\")\n print('\\t', day, '\\t', end=' ')\n for hour in range(9, 15):\n print(hour, end=' ')\n for minute in [0, 30]:\n print(\".\", end=' ')\n try:\n closest_date = dt.datetime(2016, month, day, hour, minute)\n sample_photo_fname = phenosite.get_closest_fname(closest_date)\n\n local_fname = phenosite.get_local_image_fname(sample_photo_fname)\n local_fname_ir = phenosite.get_local_image_fname(sample_photo_fname, IR=True)\n sample_image = phenosite.get_local_image(sample_photo_fname)\n sample_image_ir = phenosite.get_local_image(sample_photo_fname, IR=True)\n\n exposure = pyphenocam.headerextraction.get_exposure(local_fname)\n exposure_ir = pyphenocam.headerextraction.get_exposure(local_fname_ir)\n corrected_ndvi = pyphenocam.imageprocessing._get_corrected_ndvi(local_fname, \n local_fname_ir, \n float(exposure), \n float(exposure_ir))\n corrected_ndvi_m = np.ma.masked_where(sky, corrected_ndvi)\n\n im_photo = ax_photo.imshow(sample_image)\n im_ndvi = ax_ndvi.imshow(corrected_ndvi_m, vmin=0, vmax=1., cmap=mpl.cm.RdYlGn)\n im_gcc = ax_gcc.imshow(gcc(sample_image), vmin=0, vmax=0.5, cmap=mpl.cm.RdYlGn)\n plt.tight_layout()\n\n \n \n \n del im\n del im2\n del sample_image\n del corrected_ndvi\n del corrected_ndvi_m\n del sample_image_ir\n except:\n try:\n del im\n del im2\n del sample_image\n del corrected_ndvi\n del corrected_ndvi_m\n del sample_image_ir\n except:\n pass\n\n"
]
| [
[
"matplotlib.use",
"numpy.sum",
"matplotlib.pyplot.subplots",
"numpy.mean",
"matplotlib.pyplot.tight_layout",
"numpy.ma.masked_where"
]
]
|
magnusja/metriculous | [
"53fa17ad04ef5d52017a9d1f76cb7f5c4b144960"
]
| [
"src/metriculous/evaluators/_regression_evaluator_test.py"
]
| [
"from dataclasses import replace\nfrom typing import Optional, Sequence\n\nimport numpy as np\nimport numpy.testing as npt\nimport pytest\n\nfrom .. import Evaluation, Quantity\nfrom . import RegressionEvaluator\nfrom ._bokeh_utils import check_that_all_figures_can_be_rendered\n\n\nclass TestRegressionEvaluator:\n @pytest.mark.parametrize(\"use_sample_weights\", [True, False])\n def test_that_it_does_not_smoke(self, use_sample_weights: bool) -> None:\n n = 100\n evaluation = RegressionEvaluator().evaluate(\n ground_truth=np.random.randn(n),\n model_prediction=np.random.randn(n),\n model_name=\"Mock Regression Model\",\n sample_weights=np.random.random(size=n) if use_sample_weights else None,\n )\n check_any_evaluation(evaluation)\n\n @pytest.mark.parametrize(\"use_sample_weights\", [True, False])\n def test_perfect_prediction(self, use_sample_weights: bool) -> None:\n n_samples = 100\n ground_truth = np.random.randn(n_samples)\n maybe_sample_weights = (\n np.random.random(size=n_samples) if use_sample_weights else None\n )\n\n evaluation = RegressionEvaluator().evaluate(\n ground_truth=ground_truth,\n model_prediction=ground_truth,\n model_name=\"Mock Regression Model\",\n sample_weights=maybe_sample_weights,\n )\n\n check_any_evaluation(evaluation)\n\n for q in evaluation.quantities:\n print(q)\n\n for q in evaluation.quantities:\n if \"error\" in q.name.lower():\n assert q.higher_is_better is False\n assert q.value == 0.0\n\n expected_quantities = [\n Quantity(name=\"R^2\", value=1.0, higher_is_better=True, description=None),\n Quantity(name=\"Explained Variance\", value=1.0, higher_is_better=True),\n Quantity(\n name=\"MSE (Mean Squared Error)\", value=0.0, higher_is_better=False\n ),\n Quantity(\n name=\"RMSE (Root Mean Squared Error)\", value=0.0, higher_is_better=False\n ),\n Quantity(\n name=\"MAE (Mean Absolute Error)\", value=0.0, higher_is_better=False\n ),\n Quantity(name=\"Max Absolute Error\", value=0.0, higher_is_better=False),\n Quantity(name=\"Number of Samples\", value=n_samples, higher_is_better=None),\n Quantity(\n name=\"Sample Weights Used?\",\n value=\"Yes\" if use_sample_weights else \"No\",\n higher_is_better=None,\n ),\n Quantity(\n name=\"Mean Ground Truth\",\n value=np.average(ground_truth, weights=maybe_sample_weights),\n higher_is_better=None,\n ),\n Quantity(\n name=\"Mean Prediction\",\n value=np.average(ground_truth, weights=maybe_sample_weights),\n higher_is_better=None,\n ),\n ]\n\n if not use_sample_weights:\n expected_quantities.extend(\n [\n Quantity(\n name=\"Median Absolute Error\", value=0.0, higher_is_better=False\n ),\n Quantity(\n name=\"Median Ground Truth\",\n value=np.median(ground_truth),\n higher_is_better=None,\n ),\n Quantity(\n name=\"Median Prediction\",\n value=np.median(ground_truth),\n higher_is_better=None,\n ),\n ]\n )\n\n assert evaluation.quantities == expected_quantities\n\n @pytest.mark.parametrize(\"use_sample_weights\", [True, False])\n def test_imperfect_prediction(self, use_sample_weights: bool) -> None:\n n_samples = 100\n ground_truth = np.random.randn(n_samples)\n residual = np.random.randn(n_samples)\n prediction = ground_truth - residual\n maybe_sample_weights = (\n np.random.random(size=n_samples) if use_sample_weights else None\n )\n\n evaluation = RegressionEvaluator().evaluate(\n ground_truth=ground_truth,\n model_prediction=prediction,\n model_name=\"Mock Regression Model\",\n sample_weights=maybe_sample_weights,\n )\n\n check_any_evaluation(evaluation)\n\n for q in evaluation.quantities:\n print(q)\n\n for q in evaluation.quantities:\n if \"error\" in q.name.lower():\n assert q.higher_is_better is False\n assert isinstance(q.value, float)\n assert q.value > 0.0\n\n sample_weights = (\n np.ones_like(ground_truth)\n if maybe_sample_weights is None\n else maybe_sample_weights\n )\n\n r2_numerator = np.sum(residual ** 2 * sample_weights)\n\n r2_denominator = np.sum(\n (ground_truth - np.average(ground_truth, weights=maybe_sample_weights)) ** 2\n * sample_weights\n )\n\n expected_quantities = [\n Quantity(\n name=\"R^2\",\n value=(1.0 - (r2_numerator / r2_denominator)),\n higher_is_better=True,\n ),\n Quantity(\n name=\"Explained Variance\",\n value=(\n 1.0\n - (\n var(residual, weights=maybe_sample_weights)\n / var(ground_truth, weights=maybe_sample_weights)\n )\n ),\n higher_is_better=True,\n ),\n Quantity(\n name=\"MSE (Mean Squared Error)\",\n value=np.average(residual ** 2, weights=maybe_sample_weights),\n higher_is_better=False,\n ),\n Quantity(\n name=\"RMSE (Root Mean Squared Error)\",\n value=float(\n np.sqrt(np.average(residual ** 2, weights=maybe_sample_weights))\n ),\n higher_is_better=False,\n ),\n Quantity(\n name=\"MAE (Mean Absolute Error)\",\n value=np.average(np.absolute(residual), weights=maybe_sample_weights),\n higher_is_better=False,\n ),\n Quantity(\n name=\"Max Absolute Error\",\n value=max(np.absolute(residual)),\n higher_is_better=False,\n ),\n Quantity(name=\"Number of Samples\", value=n_samples, higher_is_better=None),\n Quantity(\n name=\"Sample Weights Used?\",\n value=\"Yes\" if use_sample_weights else \"No\",\n higher_is_better=None,\n ),\n Quantity(\n name=\"Mean Ground Truth\",\n value=np.average(ground_truth, weights=maybe_sample_weights),\n higher_is_better=None,\n ),\n Quantity(\n name=\"Mean Prediction\",\n value=np.average(prediction, weights=maybe_sample_weights),\n higher_is_better=None,\n ),\n ]\n\n if not use_sample_weights:\n expected_quantities.extend(\n [\n Quantity(\n name=\"Median Absolute Error\",\n value=np.median(np.absolute(residual)),\n higher_is_better=False,\n ),\n Quantity(\n name=\"Median Ground Truth\",\n value=np.median(ground_truth),\n higher_is_better=None,\n ),\n Quantity(\n name=\"Median Prediction\",\n value=np.median(prediction),\n higher_is_better=None,\n ),\n ]\n )\n\n assert_all_close(\n evaluation.quantities, expected_quantities, atol=1e-10, rtol=1e-10\n )\n\n\ndef check_any_evaluation(evaluation: Evaluation) -> None:\n \"\"\" Performs basic checks that should pass for any `Evaluation` object. \"\"\"\n for quantity in evaluation.quantities:\n assert isinstance(quantity, Quantity)\n assert isinstance(quantity.value, (float, str, int))\n\n check_that_all_figures_can_be_rendered(evaluation.figures())\n\n\ndef assert_all_close(\n a: Sequence[Quantity], b: Sequence[Quantity], atol: float, rtol: float\n) -> None:\n assert len(a) == len(b)\n for qa, qb in zip(a, b):\n if isinstance(qa.value, float):\n npt.assert_allclose(qa.value, qb.value, atol=atol, rtol=rtol)\n assert replace(qa, value=\"any\") == replace(qb, value=\"any\")\n else:\n assert qa == qb\n\n\ndef var(values: np.ndarray, weights: Optional[np.ndarray]) -> float:\n mean = np.average(values, weights=weights)\n return np.average((values - mean) ** 2, weights=weights)\n"
]
| [
[
"numpy.testing.assert_allclose",
"numpy.ones_like",
"numpy.median",
"numpy.sum",
"numpy.random.randn",
"numpy.absolute",
"numpy.average",
"numpy.random.random"
]
]
|
coderefinery/pre-workshop-survey | [
"98d45b263908a394d3a28580f1376304a0b0e26d"
]
| [
"preprocess/preprocess-typeform.py"
]
| [
"import glob\nimport pandas as pd\n\n# first typeform data\npersonal = \"personal/\"\nyears = [2016, 2017, 2018]\ncols_to_rm = ['First Name', 'Last Name', 'E-mail Address']\n\ndfs = []\nkeys = []\nfor f in glob.glob(personal+'/20*/*.csv'):\n if not \"_processed.csv\" in f:\n df = pd.read_csv(f)\n fnew = f.replace(\".csv\", \"_processed.csv\")\n df.drop(labels=cols_to_rm, axis=1, inplace=True)\n df.to_csv(path_or_buf=fnew)\n\n# then indico data\npersonal = \"personal_indico/\"\nyears = [2018]\ncols_to_rm = ['ID', 'Name', 'Email Address', 'Registration date', 'Registration state', 'Title']\n\ndfs = []\nkeys = []\nfor f in glob.glob(personal+'/20*/*.csv'):\n if not \"_processed.csv\" in f:\n df = pd.read_csv(f)\n fnew = f.replace(\".csv\", \"_processed.csv\")\n df.drop(labels=cols_to_rm, axis=1, inplace=True)\n df.to_csv(path_or_buf=fnew)\n\n"
]
| [
[
"pandas.read_csv"
]
]
|
Jammy2211/AutoLens | [
"bc132a21d1a52248f08f198474e29f985e365d85"
]
| [
"autolens/lens/subhalo.py"
]
| [
"from typing import List, Tuple\r\nimport numpy as np\r\n\r\nimport autoarray as aa\r\nimport autogalaxy.plot as aplt\r\n\r\nfrom autoarray.plot.abstract_plotters import AbstractPlotter\r\n\r\nfrom autolens.imaging.fit_imaging import FitImaging\r\nfrom autolens.imaging.plot.fit_imaging_plotters import FitImagingPlotter\r\n\r\nfrom autolens.aggregator.fit_imaging import _fit_imaging_from\r\n\r\n\r\nclass SubhaloResult:\r\n def __init__(\r\n self, grid_search_result, result_no_subhalo, stochastic_log_likelihoods=None\r\n ):\r\n\r\n self.grid_search_result = grid_search_result\r\n self.result_no_subhalo = result_no_subhalo\r\n self.stochastic_log_likelihoods = stochastic_log_likelihoods\r\n\r\n @property\r\n def fit_imaging_before(self):\r\n return _fit_imaging_from(\r\n fit=self.result_no_subhalo,\r\n galaxies=self.result_no_subhalo.instance.galaxies,\r\n )\r\n\r\n def _subhalo_array_from(self, values_native) -> aa.Array2D:\r\n\r\n values_reshaped = [value for values in values_native for value in values]\r\n\r\n return aa.Array2D.manual_yx_and_values(\r\n y=[centre[0] for centre in self.grid_search_result.physical_centres_lists],\r\n x=[centre[1] for centre in self.grid_search_result.physical_centres_lists],\r\n values=values_reshaped,\r\n pixel_scales=self.grid_search_result.physical_step_sizes,\r\n shape_native=self.grid_search_result.shape,\r\n )\r\n\r\n def subhalo_detection_array_from(\r\n self,\r\n use_log_evidences: bool = True,\r\n use_stochastic_log_likelihoods: bool = False,\r\n relative_to_no_subhalo: bool = True,\r\n ) -> aa.Array2D:\r\n\r\n if (not use_log_evidences) and (not use_stochastic_log_likelihoods):\r\n\r\n values_native = self.grid_search_result.log_likelihoods_native\r\n values_native[values_native == None] = np.nan\r\n\r\n if relative_to_no_subhalo:\r\n values_native -= self.result_no_subhalo[\r\n \"samples\"\r\n ].max_log_likelihood_sample.log_likelihood\r\n\r\n elif use_log_evidences and not use_stochastic_log_likelihoods:\r\n\r\n values_native = self.grid_search_result.log_evidences_native\r\n values_native[values_native == None] = np.nan\r\n\r\n if relative_to_no_subhalo:\r\n values_native -= self.result_no_subhalo[\"samples\"].log_evidence\r\n\r\n else:\r\n\r\n values_native = self.stochastic_log_evidences_native\r\n values_native[values_native == None] = np.nan\r\n\r\n if relative_to_no_subhalo:\r\n values_native -= np.median(\r\n self.result_no_subhalo[\"stochastic_log_likelihoods\"]\r\n )\r\n\r\n return self._subhalo_array_from(values_native=values_native)\r\n\r\n def subhalo_mass_array_from(self):\r\n return self._subhalo_array_from(values_native=self.masses_native)\r\n\r\n @property\r\n def stochastic_log_evidences_native(self) -> List[float]:\r\n\r\n return self.grid_search_result._list_to_native(\r\n lst=self.stochastic_log_likelihoods\r\n )\r\n\r\n def instance_list_via_results_from(self, results):\r\n return [\r\n None\r\n if result.samples.median_pdf_instance is None\r\n else result.samples.median_pdf_instance\r\n for result in results\r\n ]\r\n\r\n @property\r\n def masses_native(self) -> List[float]:\r\n\r\n instance_list = self.instance_list_via_results_from(\r\n results=self.grid_search_result.results\r\n )\r\n\r\n return self.grid_search_result._list_to_native(\r\n [\r\n None if instance is None else instance.galaxies.subhalo.mass.mass_at_200\r\n for instance in instance_list\r\n ]\r\n )\r\n\r\n @property\r\n def centres_native(self) -> List[Tuple[float]]:\r\n\r\n instance_list = self.instance_list_via_results_from(\r\n results=self.grid_search_result.results\r\n )\r\n\r\n centres_native = np.zeros(\r\n (self.grid_search_result.shape[0], self.grid_search_result.shape[1], 2)\r\n )\r\n\r\n centres_native[:, :, 0] = self.grid_search_result._list_to_native(\r\n lst=[\r\n None if instance is None else instance.galaxies.subhalo.mass.centre[0]\r\n for instance in instance_list\r\n ]\r\n )\r\n\r\n centres_native[:, :, 1] = self.grid_search_result._list_to_native(\r\n lst=[\r\n None if instance is None else instance.galaxies.subhalo.mass.centre[1]\r\n for instance in instance_list\r\n ]\r\n )\r\n\r\n return aa.Grid2D.manual_native(\r\n grid=centres_native,\r\n pixel_scales=self.grid_search_result.physical_step_sizes,\r\n )\r\n\r\n\r\nclass SubhaloPlotter(AbstractPlotter):\r\n def __init__(\r\n self,\r\n subhalo_result: SubhaloResult,\r\n fit_imaging_detect,\r\n use_log_evidences: bool = True,\r\n use_stochastic_log_likelihoods: bool = False,\r\n mat_plot_2d: aplt.MatPlot2D = aplt.MatPlot2D(),\r\n visuals_2d: aplt.Visuals2D = aplt.Visuals2D(),\r\n include_2d: aplt.Include2D = aplt.Include2D(),\r\n ):\r\n super().__init__(\r\n mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d\r\n )\r\n\r\n self.subhalo_result = subhalo_result\r\n self.fit_imaging_detect = fit_imaging_detect\r\n self.use_log_evidences = use_log_evidences\r\n self.use_stochastic_log_likelihoods = use_stochastic_log_likelihoods\r\n\r\n @property\r\n def fit_imaging_before(self):\r\n return self.subhalo_result.fit_imaging_before\r\n\r\n @property\r\n def fit_imaging_before_plotter(self):\r\n return FitImagingPlotter(\r\n fit=self.fit_imaging_before,\r\n mat_plot_2d=self.mat_plot_2d,\r\n visuals_2d=self.visuals_2d,\r\n include_2d=self.include_2d,\r\n )\r\n\r\n @property\r\n def fit_imaging_detect_plotter(self):\r\n return self.fit_imaging_detect_plotter_from(visuals_2d=self.visuals_2d)\r\n\r\n def fit_imaging_detect_plotter_from(self, visuals_2d):\r\n return FitImagingPlotter(\r\n fit=self.fit_imaging_detect,\r\n mat_plot_2d=self.mat_plot_2d,\r\n visuals_2d=visuals_2d,\r\n include_2d=self.include_2d,\r\n )\r\n\r\n def detection_array_from(self, remove_zeros: bool = False):\r\n\r\n detection_array = self.subhalo_result.subhalo_detection_array_from(\r\n use_log_evidences=self.use_log_evidences,\r\n use_stochastic_log_likelihoods=self.use_stochastic_log_likelihoods,\r\n relative_to_no_subhalo=True,\r\n )\r\n\r\n if remove_zeros:\r\n\r\n detection_array[detection_array < 0.0] = 0.0\r\n\r\n return detection_array\r\n\r\n def figure_with_detection_overlay(\r\n self,\r\n image: bool = False,\r\n remove_zeros: bool = False,\r\n show_median: bool = True,\r\n overwrite_title=False,\r\n transpose_array=False,\r\n ):\r\n\r\n array_overlay = self.detection_array_from(remove_zeros=remove_zeros)\r\n\r\n median_detection = np.round(np.nanmedian(array_overlay), 2)\r\n\r\n # Due to bug with flipped subhalo inv, can remove one day\r\n\r\n if transpose_array:\r\n array_overlay = np.fliplr(np.fliplr(array_overlay.native).T)\r\n\r\n visuals_2d = self.visuals_2d + self.visuals_2d.__class__(\r\n array_overlay=array_overlay,\r\n mass_profile_centres=self.subhalo_result.centres_native,\r\n )\r\n\r\n fit_imaging_plotter = self.fit_imaging_detect_plotter_from(\r\n visuals_2d=visuals_2d\r\n )\r\n\r\n if show_median:\r\n if overwrite_title:\r\n fit_imaging_plotter.set_title(label=f\"Image {median_detection}\")\r\n\r\n # fit_imaging_plotter.figures_2d(image=image)\r\n fit_imaging_plotter.figures_2d_of_planes(plane_index=-1, subtracted_image=True)\r\n\r\n def figure_with_mass_overlay(self, image: bool = False, transpose_array=False):\r\n\r\n array_overlay = self.subhalo_result.subhalo_mass_array_from()\r\n\r\n # Due to bug with flipped subhalo inv, can remove one day\r\n\r\n if transpose_array:\r\n array_overlay = np.fliplr(np.fliplr(array_overlay.native).T)\r\n\r\n visuals_2d = self.visuals_2d + self.visuals_2d.__class__(\r\n array_overlay=array_overlay,\r\n mass_profile_centres=self.subhalo_result.centres_native,\r\n )\r\n\r\n fit_imaging_plotter = self.fit_imaging_detect_plotter_from(\r\n visuals_2d=visuals_2d\r\n )\r\n\r\n fit_imaging_plotter.figures_2d_of_planes(plane_index=-1, subtracted_image=True)\r\n\r\n def subplot_detection_imaging(self, remove_zeros: bool = False):\r\n\r\n self.open_subplot_figure(number_subplots=4)\r\n\r\n self.set_title(\"Image\")\r\n self.fit_imaging_detect_plotter.figures_2d(image=True)\r\n\r\n self.set_title(\"Signal-To-Noise Map\")\r\n self.fit_imaging_detect_plotter.figures_2d(signal_to_noise_map=True)\r\n self.set_title(None)\r\n\r\n self.mat_plot_2d.plot_array(\r\n array=self.detection_array_from(remove_zeros=remove_zeros),\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=aplt.AutoLabels(title=\"Increase in Log Evidence\"),\r\n )\r\n\r\n mass_array = self.subhalo_result.subhalo_mass_array_from()\r\n\r\n self.mat_plot_2d.plot_array(\r\n array=mass_array,\r\n visuals_2d=self.visuals_2d,\r\n auto_labels=aplt.AutoLabels(title=\"Subhalo Mass\"),\r\n )\r\n\r\n self.mat_plot_2d.output.subplot_to_figure(\r\n auto_filename=\"subplot_detection_imaging\"\r\n )\r\n self.close_subplot_figure()\r\n\r\n def subplot_detection_fits(self):\r\n \"\"\"\r\n A subplot comparing the normalized residuals, chi-squared map and source reconstructions of the model-fits\r\n before the subhalo added to the model (top row) and the subhalo fit which gives the largest increase in\r\n Bayesian evidence on the subhalo detection grid search.\r\n\r\n Parameters\r\n ----------\r\n fit_imaging_before : FitImaging\r\n The fit of a `Tracer` not including a subhalo in the model to a `MaskedImaging` dataset (e.g. the\r\n model-image, residual_map, chi_squared_map).\r\n fit_imaging_detect : FitImaging\r\n The fit of a `Tracer` with the subhalo detection grid's highest evidence model including a subhalo to a\r\n `MaskedImaging` dataset (e.g. the model-image, residual_map, chi_squared_map).\r\n include : Include\r\n Customizes what appears on the plots (e.g. critical curves, profile centres, origin, etc.).\r\n mat_plot_2d : Plotter\r\n Object for plotting PyAutoLens data-stuctures as subplots via Matplotlib.\r\n \"\"\"\r\n\r\n self.open_subplot_figure(number_subplots=6)\r\n\r\n self.set_title(\"Normalized Residuals (No Subhalo)\")\r\n self.fit_imaging_before_plotter.figures_2d(normalized_residual_map=True)\r\n\r\n self.set_title(\"Chi-Squared Map (No Subhalo)\")\r\n self.fit_imaging_before_plotter.figures_2d(chi_squared_map=True)\r\n\r\n self.set_title(\"Source Reconstruction (No Subhalo)\")\r\n self.fit_imaging_before_plotter.figures_2d_of_planes(\r\n plane_image=True, plane_index=1\r\n )\r\n\r\n self.set_title(\"Normailzed Residuals (With Subhalo)\")\r\n self.fit_imaging_detect_plotter.figures_2d(normalized_residual_map=True)\r\n\r\n self.set_title(\"Chi-Squared Map (With Subhalo)\")\r\n self.fit_imaging_detect_plotter.figures_2d(chi_squared_map=True)\r\n\r\n self.set_title(\"Source Reconstruction (With Subhalo)\")\r\n self.fit_imaging_detect_plotter.figures_2d_of_planes(\r\n plane_image=True, plane_index=1\r\n )\r\n\r\n self.mat_plot_2d.output.subplot_to_figure(\r\n auto_filename=\"subplot_detection_fits\"\r\n )\r\n self.close_subplot_figure()\r\n"
]
| [
[
"numpy.median",
"numpy.nanmedian",
"numpy.zeros",
"numpy.fliplr"
]
]
|
sdhnshu/Pytorch-Model-Zoo | [
"96fb38db5200f455bf332871f8fbf134f490d4d8"
]
| [
"dcgan/train.py"
]
| [
"import torch\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import ImageFolder\nfrom torch.autograd import Variable\nfrom model import Generator, Discriminator\n\n# Hyperparameters\nlr = 0.0002\nbatch_size = 32\nimage_size = 64\nz_dim = 100\nepochs = 80\n\n# Image Preprocessing\ntransform = transforms.Compose([transforms.Scale(image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))])\n\n# LFW DeepFunneled Dataset\ndataset = ImageFolder(root='../datasets/lfw-deepfunneled/',\n transform=transform)\n\n# Data Loader (Input Pipeline)\ndata_loader = torch.utils.data.DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=2,\n drop_last=True)\n\n# Model\ng = Generator(z_dim=z_dim,\n image_size=image_size,\n conv_dim=64)\nd = Discriminator(image_size=image_size,\n conv_dim=64)\nd = d.cuda()\ng = g.cuda()\n\n# Optimizers and loss\ng_optimizer = torch.optim.Adam(g.parameters(),\n lr, betas=(0.5, 0.999))\nd_optimizer = torch.optim.Adam(d.parameters(),\n lr, betas=(0.5, 0.999))\ncriterion = torch.nn.BCELoss()\n\n# Training\nfor epoch in range(epochs):\n for i, (images, _) in enumerate(data_loader):\n\n zeros = Variable(torch.zeros(batch_size).cuda())\n ones = Variable(torch.ones(batch_size).cuda())\n\n # Passing through generator\n noise = Variable(torch.randn(batch_size, z_dim).cuda())\n fake_images = g(noise)\n outputs = d(fake_images)\n g_loss = criterion(outputs, ones)\n\n d.zero_grad()\n g.zero_grad()\n\n g_loss.backward()\n g_optimizer.step()\n\n # Passing through discriminator\n images = Variable(images.cuda())\n outputs = d(images)\n real_loss = criterion(outputs, ones)\n\n noise = Variable(torch.randn(batch_size, z_dim).cuda())\n fake_images = g(noise)\n outputs = d(fake_images)\n fake_loss = criterion(outputs, zeros)\n\n d_loss = real_loss + fake_loss\n\n d.zero_grad()\n g.zero_grad()\n\n d_loss.backward()\n d_optimizer.step()\n\n if (i + 1) % batch_size == 0:\n print('Epoch [%d/%d], Iter [%d/%d], d_real_loss: %.4f, d_fake_loss: %.4f, g_loss: %.4f' %\n (epoch + 1, epochs, i + 1, len(data_loader),\n real_loss.data[0], fake_loss.data[0],\n g_loss.data[0]))\n\n# Save the Model\ntorch.save(g, '../trained/generator.pkl')\ntorch.save(d, '../trained/discriminator.pkl')\n"
]
| [
[
"torch.zeros",
"torch.save",
"torch.ones",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss",
"torch.randn"
]
]
|
matthewfeickert/monolens | [
"fb0daae0a7c6a86ee5999bbf65d64d08604e819a"
]
| [
"monolens/util.py"
]
| [
"import os\nimport sys\nfrom PySide6 import QtGui\nimport numpy as np\nimport numba as nb\n\nDEBUG = int(os.environ.get(\"DEBUG\", \"0\"))\n\nif sys.byteorder == \"little\":\n argb = (3, 2, 1, 0)\nelse:\n argb = (0, 1, 2, 3)\n\n# matrix values from colorblind package\ncb_lms = np.array(\n [\n # Protanopia (red weakness)\n [[0, 0.90822864, 0.008192], [0, 1, 0], [0, 0, 1]],\n # Deuteranopia (green weakness)\n [[1, 0, 0], [1.10104433, 0, -0.00901975], [0, 0, 1]],\n # Tritanopia (blue weakness)\n [[1, 0, 0], [0, 1, 0], [-0.15773032, 1.19465634, 0]],\n ],\n)\nrgb2lms = np.array(\n [\n [0.3904725, 0.54990437, 0.00890159],\n [0.07092586, 0.96310739, 0.00135809],\n [0.02314268, 0.12801221, 0.93605194],\n ],\n)\nlms2rgb = np.linalg.inv(rgb2lms)\ncb_full = [np.linalg.multi_dot((lms2rgb, cbi, rgb2lms)) for cbi in cb_lms]\n\n\[email protected](cache=True)\ndef clip(x, xmin, xmax):\n if x < xmin:\n return xmin\n return min(x, xmax)\n\n\nclass QImageArrayInterface:\n __slots__ = (\"__array_interface__\",)\n\n def __init__(self, image):\n format = image.format()\n assert format == QtGui.QImage.Format_RGB32\n\n self.__array_interface__ = {\n \"shape\": (image.width() * image.height(), 4),\n \"typestr\": \"|u1\",\n \"data\": image.bits(),\n \"version\": 3,\n }\n\n\ndef qimage_array_view(image):\n return np.asarray(QImageArrayInterface(image))\n\n\[email protected](parallel=True, cache=True)\ndef _grayscale(d, s, argb):\n a, r, g, b = argb\n for i in nb.prange(len(s)):\n sr = s[i, r]\n sg = s[i, g]\n sb = s[i, b]\n c = clip(0.299 * sr + 0.587 * sg + 0.114 * sb, 0, 255)\n d[i, a] = 255\n d[i, r] = c\n d[i, g] = c\n d[i, b] = c\n\n\ndef grayscale(dest, source):\n s = qimage_array_view(source)\n d = qimage_array_view(dest)\n _grayscale(d, s, argb)\n\n\[email protected](parallel=True, cache=True)\ndef _colorblindness(d, s, cb, argb):\n a, r, g, b = argb\n for i in nb.prange(len(s)):\n sr = s[i, r]\n sg = s[i, g]\n sb = s[i, b]\n dr = cb[0, 0] * sr + cb[0, 1] * sg + cb[0, 2] * sb\n dg = cb[1, 0] * sr + cb[1, 1] * sg + cb[1, 2] * sb\n db = cb[2, 0] * sr + cb[2, 1] * sg + cb[2, 2] * sb\n d[i, a] = 255\n d[i, r] = clip(dr, 0, 255)\n d[i, g] = clip(dg, 0, 255)\n d[i, b] = clip(db, 0, 255)\n\n\ndef colorblindness(dest, source, type):\n s = qimage_array_view(source)\n d = qimage_array_view(dest)\n cb = cb_full[type]\n _colorblindness(d, s, cb, argb)\n"
]
| [
[
"numpy.array",
"numpy.linalg.inv",
"numpy.linalg.multi_dot"
]
]
|
FlackoJodye1/thvisa | [
"1472cba988a261ba0084e9997f3a5d483250c8fd"
]
| [
"spd3303c_thvisa.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 6 21:37:06 2019\n\n@author: thirschbuechler\n\"\"\"\nimport time\nimport pandas as pd\nimport numpy as np\nimport thvisa as thv\n\n# ToDo: check system:status? to find out whether in cc mode, i.e. limited \n# ToDo: series / parallel mode\n\n# ----------------------------------------------------------------------- #\n# ToDo: find out whether lock-mode exists (spam commands, ref. manual doesn't say)\n\n# ToDo: check for human goblins (i.e. measure voltage each time after it\n# got set to verify it hasn't been changed while 1s in unlocked mode)\n# maybe as locklevel (0=none, 1=lock, 2=lock + while(not confirmed when locked))\n# aka level=[engineer, user, toddler]\n# right now this is setp\n\nclass spd3303c(thv.thInstr):\n\n # overwrite class inherited defaults\n myprintdef = print\n instrnamedef = \"SPD\"\n qdelaydef = 1\n \n \n \n # ----- Instrument Setup ----- #\n def __init__(self, instrname = instrnamedef, qdelay = qdelaydef, myprint = myprintdef, settletime=1):\n self.qdelay=qdelay\n self.myprint=myprint\n self.instrname=instrname\n self.settletime=settletime\n \n # call parent init #\n # the righthand stuff has to be \"self.\" properties and unusually, has no \".self\" prefix\n super(spd3303c, self).__init__(myprint=myprint, instrname=instrname, qdelay=qdelay, wdelay = 0.1)\n self.alwayscheck=False # screw error checking every time, now we need wdelay=100ms instead of 10ms but are overall faster\n\n # define output state, should be off, but nonetheless:\n # can't do here, no handle open! make one with \"with\" or omit\n # self.disable(1)\n # self.disable(2)\n \n # ----- EXIT - With Context ----- #\n def __exit__(self, exc_type, exc_value, tb):# \"with\" context exit\n self.do_command( \"*unlock\") # return full control, was partially locked anyhow\n super(spd3303c, self).__exit__( exc_type, exc_value, tb) # call inherited fct\n\n # -------------------------------------------------------- #\n # -------------------------------------------------------- #\n\n # ----- Importing the Testcases from a xlsx-File ----- #\n\n def load_testcases(self, fileName = 'cubesat_testcases_V0.1.xlsx'):\n \n self.testCases = pd.read_excel(fileName)\n\n # Renaming the Columns #\n\n colNameDic = list(self.testCases.iloc[0].values)\n self.testCases.columns = colNameDic\n\n self.testCases = self.testCases.drop([0],axis = 0)\n\n print(self.testCases.columns)\n print(self.testCases.iloc[1])\n\n # ----- Checking System-Status ----- #\n\n def check_systemstatus(self):\n \n # Could work, but could also be the case, that i need to convert the\n # hex-value which was returned, manually ( bin() )\n num = self.do_query_ieee_block('*SYSTem: STATus?')\n\n # Channel Power Switches (On or Off)\n switch_ch1, switch_ch2 = 'off'\n if(self.access_binarydigit(num,4)):\n switch_ch1 = 'on'\n if(self.access_binarydigit(num,5)):\n switch_ch1 = 'on'\n \n # Channel 1 - Mode (CV or CC)\n if(self.access_binarydigit(num,0)):\n self.myprint(f\"Channel 1 is {switch_ch1} and in CC mode\")\n else:\n self.myprint(f\"Channel 1 is {switch_ch1} and in CV mode\")\n\n # Channel 2 - Mode (CV or CC)\n if(self.access_binarydigit(num,1)):\n self.myprint(f\"Channel 2 is {switch_ch2} and in CC mode\")\n else:\n self.myprint(f\"Channel 2 is {switch_ch2} and in CV mode\")\n\n # PSU - Mode (independent, series or parallel)\n mode = self.access_binarydigit(num,2,True)\n mode_name = \"independent\"\n if(mode == bin(2)):\n mode_name = \"parallel\"\n elif (mode == bin(4)):\n mode_name = \"serial\"\n self.myprint(f\"PSU is in {mode_name} mode\")\n\n\n \n \n # --- Accessing digits of binary values ---\n # number: binary value you want to access digits of\n # index: index of the digits \n # double (optional): False returns the bit with the index, \n # True adds up bit with the index + the bit at position (index +1)\n def access_binarydigit(self,number = 1, index = 0, double = False):\n value = (number & (1 << index)) >> index\n if(double):\n return ((number & (1 << (index+1))) >> (index+1)) << value \n else:\n return value\n\n\n # -------------------------------------------------------- #\n # -------------------------------------------------------- #\n\n # ----- Auxiliary Setup ----- #\n def set_settletime(self,newsettletime): \n self.settletime = newsettletime # waittime for transients to settle\n\n def test_undoc_cmd(self): # no {preset, reset, factory, *rst, *cls, *tst, syst:pres, *OPC?} comands\n self.do_command(\"*unlock\") # output can only be changed in unlocked state\n self.do_command( \"*OPC?\")\n #self.beep()\n \n def beep(self): # upset instrument by sending garbage\n self.do_command( \"beep\") # intentionally invalid command \n\n\n # ----- Control Functions ----- #\n # outsourced from \"set\" to make user think whether to turn it on immediately after setting # \n def output(self, ch, state=float(\"nan\")):\n \n self.myprint('PSU channel {}:'.format(str(ch))) # ch = channel \n #self.do_command(\"*unlock\") # output can only be changed in unlocked state\n self.do_command('OUTP CH{}, {}'.format(str(ch), thv.statedict[state]))\n #self.do_command(\"*lock\")\n \n # todo: $use eggtimer / mysleep to avoid UI freeze\n #time.sleep(self.settletime) # wait for off-transient\n\n \n # synonyms #\n def enable(self, ch):\n self.output(ch=ch, state=True)\n \n def disable(self, ch):\n self.output(ch=ch, state=False)\n\n\n # ----- Parameter Settings ----- #\n # per channel, since independent #\n def set(self, ch=float('nan'), v_set = float('nan'), c_max = float('nan')):\n \n self.myprint(\"Setting channel {} parameters:\".format(str(ch)))\n \n self.do_command(\"*unlock\") # output can only be changed in unlocked state\n self.do_command('CH%i:VOLTage, %2.2f' % (ch,v_set))\n self.do_command('CH%i:CURRent, %2.2f' % (ch,c_max))\n self.do_command(\"*lock\") \n \n\n\n # doesn't work due to dmm_results\n def setp(self, ch=float('nan'), v_set = float('nan'), c_max = float('nan')): # paranoid variant, assume someone may hit V/I wheel \n while (not (self.DMM_results(ch)==[v_set,c_max])):\n self.set(ch , v_set, c_max)\n\n\n ## ---- DMM functions ---- ##\n # don't work reliably, for some reason, waiting doesn't seem to help,\n # also appends \\n \\x00 \\x00 or something\n # approximate, take with grain of salt #\n def DMM_results(self, ch=float(\"nan\")):\n \n #$todo if-else or switch-case\n v=self.do_query_number(\"Measure:Voltage? CH{}\".format(str(ch)))\n time.sleep(1)\n c=self.do_query_number(\"Measure:Current? CH{}\".format(str(ch)))\n time.sleep(1)\n \n self.myprint(v)\n self.myprint(c)\n return [float(v),float(c)]\n\n\n\n### module test ###\nif __name__ == '__main__': # test if called as executable, not as library, regular prints allowed\n print(\"Step 0 - done\")\n #psu = spd3303c(\"SPD\",qdelay=1,myprint=print) # no, use with-context!\n with spd3303c() as psu:\n print(\"Entered successfully !\")\n psu.set_settletime(1)\n print(print(\"Step 1 - done\"))\n #psu.disable(1)\n print(\"Step 2 - done\")\n #psu.disable(2)\n print(\"Step 3 - done\")\n #psu.test_undoc_cmd()\n #print(psu.do_query_string(\"MEASure:VOLTage? CH{}\".format(str(1))))\n #time.sleep(1)\n #print(psu.do_query_string(\"Measure:Voltage? CH{}\".format(str(1))))\n print(\"major range change to make it kachunck\")\n psu.set(ch=1, v_set=5, c_max=0.1)\n #print(psu.do_query_string(\"MEASure:VOLTage? CH{}\".format(str(1))))\n psu.set(ch=2, v_set=5, c_max=0.1)\n #print(psu.do_query_string(\"Measure:Voltage? CH{}\".format(str(2))))\n #print(psu.do_query_string(\"Measure:Voltage? CH{}\".format(str(1))))\n #psu.enable(ch=1)\n \n #psu.set(ch=1, v_set=10, c_max=0.1)\n #print(psu.do_query_string(\"Measure:Voltage? CH{}\".format(str(1))))\n #print(psu.do_query_string(\"Measure:Voltage? CH{}\".format(str(1))))\n\n #psu.disable(ch=1)\n # del psu # the \"with\" context automatically calls the de-constructur and ends the session\n # please use it to avoid dead sessions, which result in the necessity to reboot the instrument and also the PC at times!!\n\n"
]
| [
[
"pandas.read_excel"
]
]
|
micom-dev/paper | [
"a347dd40f498665462acfa1ee65db316c82650ef"
]
| [
"workflows/taxa_stats.py"
]
| [
"\"\"\"Calculate stats for taxa assignments and availability in AGORA.\"\"\"\n\nimport pandas as pd\nimport micom\n\n\ntax = pd.read_csv(\"data/abundances.csv\").query(\"kingdom == 'Bacteria'\")\ntax.relative = tax.groupby(\"id\").relative.apply(lambda a: a / a.sum())\ntax.taxa_id = tax.taxa_id.str.replace(\"*\", \"\").astype(\"int\")\nagora = micom.data.agora\nagora.species = agora.genus + \" \" + agora.species\ntaxa = [\"kingdom\", \"phylum\", \"class\", \"order\", \"family\", \"genus\", \"species\"]\n\n\ndef taxa_stats(taxonomy, rank, agora):\n res = pd.Series(\n index=[\n \"n_unique\",\n \"mean_percent_assigned\",\n \"sd_percent_assigned\",\n \"n_model\",\n \"mean_percent_model\",\n \"sd_percent_model\",\n ]\n )\n assigned = taxonomy.dropna(subset=[rank]).groupby(\"id\").relative.sum()\n if rank == \"superkingdom\":\n arank = \"kingdom\"\n elif rank == \"class\":\n arank = \"mclass\"\n else:\n arank = rank\n good = taxonomy[rank].isin(agora[arank].dropna())\n has_model = taxonomy[good].groupby(\"id\").relative.sum()\n res.iloc[:] = [\n taxonomy[rank].nunique(),\n assigned.mean(),\n assigned.std(),\n taxonomy[good][rank].nunique(),\n has_model.mean(),\n has_model.std(),\n ]\n res.name = rank\n return res\n\n\nstats = pd.concat([taxa_stats(tax, ta, agora) for ta in taxa], axis=1)\nprint(stats)\n"
]
| [
[
"pandas.read_csv",
"pandas.Series"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.