repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
DiZhang-XDU/SleepStage
[ "97cb21d13b782f85a4d9fa4c292ee8cb96bb6f62" ]
[ "data/prepare_physionet_SHHS_Resample.py" ]
[ "import argparse\nimport glob\nimport math\nimport ntpath\nimport os\nimport shutil\nimport urllib\n# import urllib2\n\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom mne import Epochs, pick_types, find_events\nfrom mne.io import concatenate_raws, read_raw_edf\n\nimport dhedfreader\n\nstage_dict = {\n \"W\": 0,\n \"N1\": 1,\n \"N2\": 2,\n \"N3\": 3,\n \"REM\": 4,\n}\nEPOCH_SEC_SIZE = 30\n\ndef Resample(input_signal,src_fs,tar_fs):\n '''\n :param input_signal:输入信号\n :param src_fs:输入信号采样率\n :param tar_fs:输出信号采样率\n :return:输出信号\n '''\n dtype = input_signal.dtype\n audio_len = len(input_signal)\n # audio_time_max = 1.0*(audio_len-1) / src_fs\n audio_time_max = 1.0*audio_len / src_fs\n src_time = 1.0 * np.linspace(0,audio_len,audio_len) / src_fs\n tar_time = 1.0 * np.linspace(0,np.int(audio_time_max*tar_fs),np.int(audio_time_max*tar_fs)) / tar_fs\n output_signal = np.interp(tar_time,src_time,input_signal).astype(dtype)\n\n return output_signal\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data_dir\", type=str, default=\"D:/SLEEP/shhs/polysomnography/edfs/shhs1/\",\n help=\"File path to the CSV or NPY file that contains walking data.\")\n parser.add_argument(\"--anno_dir\", type=str, default=\"D:/SLEEP/shhs/polysomnography/annotations-events-profusion/shhs1/\",\n help=\"x\")\n parser.add_argument(\"--output_dir\", type=str, default=\"../prepared_data/SHHS-NPZ/\",\n help=\"Directory where to save outputs.\")\n args = parser.parse_args()\n\n # Output dir\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n else:\n shutil.rmtree(args.output_dir)\n os.makedirs(args.output_dir)\n\n\n # Read raw and annotation EDF files\n psg_fnames = glob.glob(os.path.join(args.data_dir, \"*.edf\"))\n ann_fnames = glob.glob(os.path.join(args.anno_dir, \"*.xml\"))\n psg_fnames.sort()\n ann_fnames.sort()\n psg_fnames = np.asarray(psg_fnames)\n ann_fnames = np.asarray(ann_fnames)\n\n\n f_all = open(os.path.join(args.output_dir, 'all.txt'),'a')\n for i in len(psg_fnames): \n\n folder_npz = os.path.join(args.output_dir, '{:04d}'.format(i))\n if os.path.exists(folder_npz) is False:\n os.mkdir(folder_npz)\n\n raw = read_raw_edf(psg_fnames[i], preload=True, stim_channel=None)\n \n # get raw Sample Freq and Channel Name\n sampling_rate = raw.info['sfreq']\n resample = False if sampling_rate == 125 else True\n print('【sampling rate】:',sampling_rate)\n\n # # for MASS\n # c3 = [c for c in raw.ch_names if 'EEG C3' in c][0]\n # c4 = [c for c in raw.ch_names if 'EEG C4' in c][0]\n # eogl = [c for c in raw.ch_names if 'EOG Left' in c][0]\n # eogr = [c for c in raw.ch_names if 'EOG Right' in c][0]\n # emg = [c for c in raw.ch_names if 'EMG Chin' in c][0]\n # channel_name = (c3, c4, eogl, eogr, emg)\n\n names_SHHS_C3 = ['EEG(sec)', 'EEG2', 'EEG 2', 'EEG(SEC)', 'EEG sec']\n c3 = [n for n in names_SHHS_C3 if n in raw.ch_names][0]\n c4 = 'EEG'\n eogl, eogr = 'EOG(L)','EOG(R)'\n emg = 'EMG'\n channel_name = (c3, c4, eogl, eogr, emg)\n\n raw_ch_tmp = []\n for cn in channel_name:\n raw_ch_df = raw.to_data_frame(scaling_time=100.0)[cn]\n raw_ch_df = raw_ch_df.to_frame()\n raw_ch_df.set_index(np.arange(len(raw_ch_df)))\n if resample:\n raw_ch_tmp.append(Resample(raw_ch_df.values[:].flatten(), sampling_rate, 125).reshape([-1,1]))\n else:\n raw_ch_tmp.append(raw_ch_df.values[:])\n raw_ch = np.concatenate(raw_ch_tmp, axis = 1) \n\n # Get anno\n from anno_tool import xml\n ann = xml(ann_fnames[i])\n assert len(raw_ch) % (EPOCH_SEC_SIZE * 125) == 0\n\n n_epochs = len(raw_ch) // (EPOCH_SEC_SIZE * 125)\n raw_ch_slim = raw_ch[:int(n_epochs * EPOCH_SEC_SIZE * 125)]\n\n x = np.asarray(np.split(raw_ch_slim, n_epochs)).astype(np.float32)\n y = np.asarray(ann).astype(np.int32)\n\n assert len(x) == len(ann)\n\n y_onehot = np.zeros((y.shape[0], 5))\n for j in range(y.shape[0]):\n y_onehot[j][y[j]] = 1.\n\n print(\"Data shape: {}, {}\".format(x.shape, y.shape))\n\n # Save\n for j in range(y.shape[0]):\n path_npz = os.path.join(folder_npz, '{:04d}.npz'.format(j))\n save_dict = {\n \"X\":x[j],\n \"y\":y[j],\n \"y_onehot\":y_onehot[j]\n }\n np.savez(path_npz, **save_dict)\n f_all.write(path_npz[1:] + ',' + str(y[j]) + '\\n')\n with open(os.path.join(args.output_dir, 'refer.txt'), 'a') as f:\n f.write('{:04d},{}\\n'.format(i, psg_fnames[i]))\n print (\"\\n================i={:3d} done==================\\n\".format(i))\n f_all.close()\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.split", "numpy.savez", "numpy.linspace", "numpy.asarray", "numpy.concatenate", "numpy.int", "numpy.interp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jeremyDT/P2P-lending-with-AI
[ "0240c77d9987a28e571d34d64e8b4804ea1a553a" ]
[ "code/code_1_acceptance.py" ]
[ "'''import the required packages and read the file.'''\n\nimport pandas as pd\nimport numpy as np\n\n\nprint('reading file')\n\ndata = pd.read_csv('../data/input_file_1.csv.zip', sep = ',', index_col=0, compression='zip')\n\nprint('file shape', data.shape)\n\n'''parse column to date format'''\n\nprint('date encoding')\n\ndata['issue_d'] = pd.to_datetime(data['issue_d'])\n\n'''check for and remove datapoints with null values.'''\n\nprint(data['issue_d'].isnull().any(), data['purpose'].isnull().any())\n\nprint('remove null datapoints to see if it helps...')\n\ndata = data.loc[data['purpose'].isnull() == False]\n\n'''eliminate purpose categories with low count.'''\n\nprint('eliminating small count categories')\n\nthreshold = 19000\n\ncounts = data['purpose'].value_counts()\n\nkeep_list = counts[counts > threshold].index\n\ndata = data[data['purpose'].isin(keep_list)]\n\n'''replace the existing labels so that they can be called easily from pandas and TensorFlow'''\n\nprint('replacing labels')\n\nto_replace = {\n 'Debt consolidation': 'debt_consolidation',\n 'Home improvement': 'home_improvement',\n 'Credit card refinancing': 'credit_card',\n 'Other': 'other',\n 'Vacation': 'vacation',\n 'Medical expenses': 'medical',\n 'Car financing': 'car',\n 'Major purchase': 'major_purchase',\n 'Moving and relocation': 'moving',\n 'Home buying': 'house'\n}\n\ndata['purpose'] = data['purpose'].replace(to_replace)\n\nprint(data['purpose'].value_counts())\n\n'''Create one-hot encoded dummy columns for categorical variables.'''\n\nprint('hot encoding')\n\ndata = pd.get_dummies(data, columns=['purpose'], drop_first=False)\n\nprint('data columns AFTER hot encoding ', data.columns)\n\n'''split training and test data by date quantile.'''\n\ndata_train = data.loc[data['issue_d'] < data['issue_d'].quantile(0.9)]\ndata_test = data.loc[data['issue_d'] >= data['issue_d'].quantile(0.9)]\n\nprint('Number of loans in the partition: ', data_train.shape[0] + data_test.shape[0])\nprint('Number of loans in the full dataset:', data.shape[0])\n\n'''Drop the date column as not needed for the model.'''\n\ndata_train.drop('issue_d', axis=1, inplace=True)\ndata_test.drop('issue_d', axis=1, inplace=True)\n\n'''Split features and labels'''\n\ny_train = data_train['rejected']\ny_test = data_test['rejected']\n\nX_train = data_train.drop('rejected', axis=1)\nX_test = data_test.drop('rejected', axis=1)\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler, PolynomialFeatures\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.linear_model import SGDClassifier\n\n'''Build a pipeline for preprocessing and training'''\n\npipeline_sgdlogreg = Pipeline([\n ('imputer', Imputer(copy=False)), # Mean imputation by default\n ('scaler', StandardScaler(copy=False)),\n ('model', SGDClassifier(\n class_weight='balanced',\n loss='log',\n max_iter=1000,\n tol = 1e-3,\n random_state=1,\n n_jobs=10,\n warm_start=True\n )\n )\n])\n\n\n\nparam_grid_sgdlogreg = {\n 'model__alpha': [10**-3, 10**-2, 10**1],\n 'model__penalty': ['l1', 'l2']\n}\n\n'''Set up a grid search.'''\n\ngrid_sgdlogreg = GridSearchCV(\n estimator=pipeline_sgdlogreg,\n param_grid=param_grid_sgdlogreg,\n scoring='roc_auc',\n pre_dispatch=3,\n n_jobs=5,\n cv=5,\n verbose=5,\n return_train_score=False\n)\n\n'''Fit the model.'''\n\nprint('fitting')\n\ngrid_sgdlogreg.fit(X_train, y_train)\n\n'''Print model parameters, best parameters and best score.'''\n\nprint('parameters ', grid_sgdlogreg._get_param_iterator())\n\nprint(grid_sgdlogreg.best_params_, grid_sgdlogreg.best_score_)\n\nfrom sklearn.metrics import roc_auc_score, recall_score\n\n'''Make predictions on test dataset.'''\n\ny_score = grid_sgdlogreg.predict_proba(X_test)[:,1]\n\ny_score_flag = [int(round(i)) for i in y_score]\n\n'''Two ways of evaluating results, check that they match.'''\n\nprint('LOOK FOR DISCREPANCIES HERE...')\n\nprint(roc_auc_score(y_test, y_score), recall_score(y_test, y_score_flag, pos_label=1), recall_score(y_test, y_score_flag, pos_label=0))\n\ny_score_flag = grid_sgdlogreg.predict(X_test)\n\nprint(roc_auc_score(y_test, y_score), recall_score(y_test, y_score_flag, pos_label=1), recall_score(y_test, y_score_flag, pos_label=0))\n\n" ]
[ [ "sklearn.metrics.roc_auc_score", "sklearn.model_selection.GridSearchCV", "pandas.read_csv", "pandas.to_datetime", "sklearn.preprocessing.Imputer", "sklearn.preprocessing.StandardScaler", "sklearn.metrics.recall_score", "sklearn.linear_model.SGDClassifier", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
joebhakim/mimic_understander
[ "62c146e966cbd5d5e815db4580388977792c7ce7" ]
[ "src/extract_from_mimic.py" ]
[ "# MIMIC IIIv14 on postgres 9.4\nimport argparse\nimport os\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport psycopg2\n\npickle.HIGHEST_PROTOCOL = 3\n\n# Output filenames\nstatic_filename = 'static_data.csv'\nstatic_columns_filename = 'static_colnames.txt'\n\ndynamic_filename = 'vitals_hourly_data.csv'\ncolumns_filename = 'vitals_colnames.txt'\nsubjects_filename = 'subjects.npy'\ntimes_filename = 'fenceposts.npy'\ndynamic_hd5_filename = 'vitals_hourly_data.h5'\ndynamic_hd5_filt_filename = 'all_hourly_data.h5'\n\ncodes_filename = 'C.npy'\ncodes_hd5_filename = 'C.h5'\nidx_hd5_filename = 'C_idx.h5'\n\noutcome_filename = 'outcomes_hourly_data.csv'\noutcome_hd5_filename = 'outcomes_hourly_data.h5'\noutcome_columns_filename = 'outcomes_colnames.txt'\n\n# SQL command params\ndbname = 'mimic'\nschema_name = 'mimiciii'\n\nID_COLS = ['subject_id', 'hadm_id', 'icustay_id']\nITEM_COLS = ['itemid', 'label', 'LEVEL1', 'LEVEL2']\n\n\ndef get_values_by_name_from_df_column_or_index(data_df, colname):\n \"\"\" Easily get values for named field, whether a column or an index\n\n Returns\n -------\n values : 1D array\n \"\"\"\n try:\n values = data_df[colname]\n except KeyError as e:\n if colname in data_df.index.names:\n values = data_df.index.get_level_values(colname)\n else:\n raise e\n return values\n\n\ndef add_outcome_indicators(out_gb):\n subject_id = out_gb['subject_id'].unique()[0]\n hadm_id = out_gb['hadm_id'].unique()[0]\n icustay_id = out_gb['icustay_id'].unique()[0]\n max_hrs = out_gb['max_hours'].unique()[0]\n on_hrs = set()\n\n for index, row in out_gb.iterrows():\n on_hrs.update(range(row['starttime'], row['endtime'] + 1))\n\n off_hrs = set(range(max_hrs + 1)) - on_hrs\n on_vals = [0]*len(off_hrs) + [1]*len(on_hrs)\n hours = list(off_hrs) + list(on_hrs)\n return pd.DataFrame({'subject_id': subject_id, 'hadm_id':hadm_id,\n 'hours_in':hours, 'on':on_vals}) #icustay_id': icustay_id})\n\n\ndef add_blank_indicators(out_gb):\n subject_id = out_gb['subject_id'].unique()[0]\n hadm_id = out_gb['hadm_id'].unique()[0]\n #icustay_id = out_gb['icustay_id'].unique()[0]\n max_hrs = out_gb['max_hours'].unique()[0]\n\n hrs = range(max_hrs + 1)\n vals = list([0]*len(hrs))\n return pd.DataFrame({'subject_id': subject_id, 'hadm_id':hadm_id,\n 'hours_in':hrs, 'on':vals})#'icustay_id': icustay_id,\n\n\ndef get_variable_mapping(mimic_mapping_filename):\n # Read in the second level mapping of the itemids\n var_map = pd.read_csv(mimic_mapping_filename, index_col=None).fillna('')#.astype(str)\n var_map = var_map.loc[(var_map['LEVEL2'] != '') & (var_map.count(axis='columns')>0)]\n var_map = var_map.loc[(var_map.STATUS == 'ready')]\n var_map.ITEMID = var_map.ITEMID.astype(int)\n return var_map\n\n\ndef get_variable_ranges(range_filename):\n # Read in the second level mapping of the itemid, and take those values out\n columns = [ 'LEVEL2', 'OUTLIER LOW', 'VALID LOW', 'IMPUTE', 'VALID HIGH', 'OUTLIER HIGH' ]\n to_rename = dict(zip(columns, [ c.replace(' ', '_') for c in columns ]))\n to_rename['LEVEL2'] = 'VARIABLE'\n var_ranges = pd.read_csv(range_filename, index_col=None)\n var_ranges = var_ranges[columns]\n var_ranges.rename(to_rename, axis=1, inplace=True)\n var_ranges = var_ranges.drop_duplicates(subset='VARIABLE', keep='first')\n var_ranges['VARIABLE'] = var_ranges['VARIABLE'].map(str.lower)\n var_ranges.set_index('VARIABLE', inplace=True)\n var_ranges = var_ranges.loc[var_ranges.notnull().all(axis=1)]\n\n return var_ranges\n\n\nUNIT_CONVERSIONS = [\n ('weight', 'oz', None, lambda x: x/16.*0.45359237),\n ('weight', 'lbs', None, lambda x: x*0.45359237),\n ('fraction inspired oxygen', None, lambda x: x > 1, lambda x: x/100.),\n ('oxygen saturation', None, lambda x: x <= 1, lambda x: x*100.),\n ('temperature', 'f', lambda x: x > 79, lambda x: (x - 32) * 5./9),\n ('height', 'in', None, lambda x: x*2.54),\n]\n\n\ndef standardize_units(X, name_col='itemid', unit_col='valueuom', value_col='value', inplace=False):\n if not inplace: X = X.copy()\n name_col_vals = get_values_by_name_from_df_column_or_index(X, name_col)\n unit_col_vals = get_values_by_name_from_df_column_or_index(X, unit_col)\n\n try:\n name_col_vals = name_col_vals.str\n unit_col_vals = unit_col_vals.str\n except:\n print(\"Can't call *.str\")\n print(name_col_vals)\n print(unit_col_vals)\n raise\n\n #name_filter, unit_filter = [\n # (lambda n: col.contains(n, case=False, na=False)) for col in (name_col_vals, unit_col_vals)\n #]\n # TODO(mmd): Why does the above not work, but the below does?\n name_filter = lambda n: name_col_vals.contains(n, case=False, na=False)\n unit_filter = lambda n: unit_col_vals.contains(n, case=False, na=False)\n\n for name, unit, rng_check_fn, convert_fn in UNIT_CONVERSIONS:\n name_filter_idx = name_filter(name)\n needs_conversion_filter_idx = name_filter_idx & False\n\n if unit is not None: needs_conversion_filter_idx |= name_filter(unit) | unit_filter(unit)\n if rng_check_fn is not None: needs_conversion_filter_idx |= rng_check_fn(X[value_col])\n\n idx = name_filter_idx & needs_conversion_filter_idx\n\n X.loc[idx, value_col] = convert_fn(X[value_col][idx])\n\n return X\n\n\ndef interpolate_variables(df):\n df_copy = df.copy()\n df_copy.loc[:, 'hours_in'] = (df_copy['charttime'] - df_copy['intime']).dt.floor('min')\n\n df_pruned = df_copy[ID_COLS + ['label', 'value', 'hours_in']]\n #df_pruned.loc[:, 'value'] = df_pruned['value'].astype(np.float32)\n df_pruned_indexed = df_pruned.set_index(ID_COLS)\n df_pivot = df_pruned_indexed.pivot_table(values='value',columns='label',index=ID_COLS + ['hours_in'], aggfunc='last')\n\n df_filled = df_pivot.reset_index().set_index(ID_COLS + ['hours_in'])\n #TODO DOESNT DO ANYTHING TODO\n #df_filled_grouped = df_filled.groupby([pd.Grouper(key=idx) for idx in ID_COLS]).resample('H').mean() #upsample to hourly\n\n\n return df_filled\n\n\ndef preprocess_dynamic_covariates(dynamic_covariates_df):\n # columns to start: ubject_id hadm_id icustay_id intime outtime charttime itemid value valueuom\n # var_map = var_map[['LEVEL2', 'ITEMID', 'LEVEL1']].set_index('ITEMID')\n\n # df = pd.merge(dynamic_covariates_df, var_map, how='left', left_on='label', right_on='LEVEL1')\n # df['value'] = pd.to_numeric(df['value'], 'coerce')\n\n # df = standardize_units(df, name_col='LEVEL1', inplace=False)\n\n # df = apply_variable_limits(df, var_ranges, 'LEVEL2')\n\n df = interpolate_variables(dynamic_covariates_df)\n\n return df\n \ndef interpolate_input_events(input_events_df):\n # in this function: there are two types of inputs, continuous and bolus\n ## for the continuous, add the rate over the entire time its given, and upsample to minutely\n ## note that some intervals of continuous drug overlap, so sum over those overlapping\n\n ## for the bolus, treat as separate columns and record the amount at a given time\n ## determine bolus vs continuous via wehtether rate is missing (-> bolus)\n\n #df = inputs_covariates_pruned.copy()\n df = input_events_df.copy()\n\n df_cont = df.loc[~pd.isna(df['rate']), :]\n df_bolus = df.loc[pd.isna(df['rate']), :]\n\n df_cont.loc[:, 'starttime_in'] = (df_cont['starttime'] - df_cont['intime']).dt.floor('min')\n df_cont.loc[:, 'endtime_in'] = (df_cont['endtime'] - df_cont['intime']).dt.floor('min')\n df_cont_pruned = df_cont[ID_COLS + ['rate', 'label', 'starttime_in', 'endtime_in']]\n df_pivot = df_cont_pruned.pivot_table(\n values='rate', columns='label', index=ID_COLS + ['starttime_in', 'endtime_in'],\n aggfunc='last')\n #sometimes, there is one start and several stopping times, so use the latest endtime only\n df_pivot_groupstarts = df_pivot.reset_index().\\\n groupby(by=ID_COLS + ['starttime_in']).last().\\\n set_index(['endtime_in'], append=True)\n\n #reset twice gives us a column to use called \"index\" later on when matching intervals\n indexed_df = df_pivot_groupstarts.reset_index().reset_index() \n\n # this melts on indexes \"index\" (just 0 through num rows), ID_COLS, and each variable name\n melted_df = pd.melt(indexed_df,\n id_vars=list(indexed_df.drop(['starttime_in','endtime_in'], axis=1).columns),\n value_vars=['starttime_in','endtime_in'],\n var_name='startend',value_name='hours_in')\n\n # takes about a minute; fills only within each index; each index identifies a start-end pair\n filled_timegroups = melted_df.set_index('hours_in').groupby('index').resample('min').\\\n ffill().drop('startend', axis=1)\n \n # sum overlapping intervals, only group by hours_in and id_cols\n summed_timegroups = filled_timegroups.drop('index',axis=1).reset_index().\\\n groupby(['hours_in'] + ID_COLS).sum()\n df_summed_timegroups_clean = summed_timegroups.drop('index',axis=1).\\\n reset_index().set_index(ID_COLS + ['hours_in']).sort_index()\n\n # TODO: merge with interpolate_variables fn\n # treat the bolus ins the same way as the chartevents, since they happen at a discrete time\n df_bolus.loc[:, 'hours_in'] = (df_bolus['starttime'] - df_bolus['intime']).dt.floor('min')\n\n df_bolus_pruned = df_bolus[ID_COLS + ['label', 'amount', 'hours_in']]\n\n df_bolus_pivot = df_bolus_pruned.pivot_table(\n values='amount',columns='label',index=ID_COLS + ['hours_in'], aggfunc='last')\n\n df_bolus_pivot_rename = df_bolus_pivot.copy()\n df_bolus_pivot_rename.columns = [colname + '_bolus' for colname in list(df_bolus_pivot.columns)]\n\n return df_summed_timegroups_clean, df_bolus_pivot_rename\n\ndef preprocess_input_events(input_events_df): #TODO: unify with other preprocessor\n input_events_processed = interpolate_input_events(input_events_df)\n\n return input_events_processed\n\ndef apply_variable_limits(df, var_ranges, var_names_index_col='LEVEL2'):\n idx_vals = df[var_names_index_col]\n non_null_idx = ~df['value'].isnull()\n var_names = set(idx_vals)\n var_range_names = set(var_ranges.index.values)\n\n for var_name in var_names:\n if type(var_name) == float and np.isnan(var_name) or var_name.lower() not in var_range_names:\n print(\"No known ranges for %s\" % var_name)\n continue\n else:\n var_name_lower = var_name.lower()\n\n outlier_low_val, outlier_high_val, valid_low_val, valid_high_val = [\n var_ranges.loc[var_name_lower, x] for x in ('OUTLIER_LOW','OUTLIER_HIGH','VALID_LOW','VALID_HIGH')\n ]\n\n running_idx = non_null_idx & (idx_vals == var_name)\n\n outlier_low_idx = (df.value < outlier_low_val)\n outlier_high_idx = (df.value > outlier_high_val)\n valid_low_idx = ~outlier_low_idx & (df.value < valid_low_val)\n valid_high_idx = ~outlier_high_idx & (df.value > valid_high_val)\n\n var_outlier_idx = running_idx & (outlier_low_idx | outlier_high_idx)\n var_valid_low_idx = running_idx & valid_low_idx\n var_valid_high_idx = running_idx & valid_high_idx\n\n df.loc[var_outlier_idx, 'value'] = np.nan\n df.loc[var_valid_low_idx, 'value'] = valid_low_val\n df.loc[var_valid_high_idx, 'value'] = valid_high_val\n\n n_outlier = sum(var_outlier_idx)\n n_valid_low = sum(var_valid_low_idx)\n n_valid_high = sum(var_valid_high_idx)\n if n_outlier + n_valid_low + n_valid_high > 0:\n print(\n \"%s had %d / %d rows cleaned:\\n\"\n \" %d rows were strict outliers, set to np.nan\\n\"\n \" %d rows were low valid outliers, set to %.2f\\n\"\n \" %d rows were high valid outliers, set to %.2f\\n\"\n \"\" % (\n var_name,\n n_outlier + n_valid_low + n_valid_high, sum(running_idx),\n n_outlier, n_valid_low, valid_low_val, n_valid_high, valid_high_val\n )\n )\n\n return df\n\ndef get_args():\n ap = argparse.ArgumentParser()\n ap.add_argument('--out_path', type=str, default= '../data/curated',\n help='Enter the path you want the output')\n ap.add_argument('--resource_path',\n type=str,\n default=os.path.expandvars(\"$MIMIC_EXTRACT_CODE_DIR/resources/\"))\n ap.add_argument('--extract_pop', type=int, default=1,\n help='Whether or not to extract population data: 0 - no extraction, ' +\n '1 - extract if not present in the data directory, 2 - extract even if there is data')\n\n ap.add_argument('--extract_numerics', type=int, default=1,\n help='Whether or not to extract numerics data: 0 - no extraction, ' +\n '1 - extract if not present in the data directory, 2 - extract even if there is data')\n ap.add_argument('--extract_outcomes', type=int, default=1,\n help='Whether or not to extract outcome data: 0 - no extraction, ' +\n '1 - extract if not present in the data directory, 2 - extract even if there is data')\n ap.add_argument('--extract_codes', type=int, default=1,\n help='Whether or not to extract ICD9 codes: 0 - no extraction, ' +\n '1 - extract if not present in the data directory, 2 - extract even if there is data')\n ap.add_argument('--pop_size', type=int, default=-1,\n help='Size of population to extract')\n ap.add_argument('--exit_after_loading', type=int, default=0)\n ap.add_argument('--var_limits', type=int, default=1,\n help='Whether to create a version of the data with variable limits included. ' +\n '1 - apply variable limits, 0 - do not apply variable limits')\n ap.add_argument('--plot_hist', type=int, default=1,\n help='Whether to plot the histograms of the data')\n ap.add_argument('--psql_host', type=str, default=None,\n help='Postgres host. Try \"/var/run/postgresql/\" for Unix domain socket errors.')\n ap.add_argument('--psql_password', type=str, default=None, help='Postgres password.')\n ap.add_argument('--group_by_level2', action='store_false', dest='group_by_level2', default=True,\n help='Do group by level2.')\n \n ap.add_argument('--min_percent', type=float, default=0.0,\n help='Minimum percentage of row numbers need to be observations for each numeric column.' +\n 'min_percent = 1 means columns with more than 99 percent of nan will be removed')\n ap.add_argument('--min_age', type=int, default=15,\n help='Minimum age of patients to be included')\n ap.add_argument('--min_duration', type=int, default=12,\n help='Minimum hours of stay to be included')\n ap.add_argument('--max_duration', type=int, default=240,\n help='Maximum hours of stay to be included')\n \n #############\n # Parse args\n args = vars(ap.parse_args())\n printargs = False\n if printargs:\n for key in sorted(args.keys()):\n print(key, args[key])\n\n# TODO\n #if not isdir(args['resource_path']):\n # raise ValueError(\"Invalid resource_path: %s\" % args['resource_path'])\n\n\n return args\n\ndef get_eligibility_query_prefix(pop_size_string, min_age_string, min_dur_string, max_dur_string, min_day_string):\n with open('./queries/eligibility.sql','r') as f:\n query_raw = f.read()\n query_parsed = query_raw.format(\n limit=pop_size_string, min_age=min_age_string, min_dur=min_dur_string, \n max_dur=max_dur_string, min_day=min_day_string)\n return query_parsed\n\ndef get_eligibility_query(eligibility_query_prefix):\n query = eligibility_query_prefix + \\\n \"\"\"\n select * from eligible_patients\n ;\n \"\"\"\n return query\n\ndef get_static_covariates_query(eligibility_query_prefix):\n with open('./queries/static_covariates.sql','r') as f:\n query_raw = f.read()\n query_parsed = eligibility_query_prefix + query_raw # no formatting needed\n return query_parsed\n\ndef get_outcomes_query(eligibility_query_prefix): \n with open(',/queries/outcomes.sql','r') as f:\n query_raw = f.read()\n query_parsed = eligibility_query_prefix + query_raw # no formatting needed yet\n return query_parsed\n\n\ndef get_treatment_query(eligibility_query_prefix):\n with open('./queries/treatments.sql','r') as f:\n query_raw = f.read()\n query_parsed = eligibility_query_prefix + query_raw # no formatting needed yet\n return query_parsed\n\n\ndef get_inputs_query(eligibility_query_prefix):\n with open('./queries/inputs_dynamic.sql','r') as f:\n query_raw = f.read()\n query_parsed = eligibility_query_prefix + query_raw # no formatting needed yet\n return query_parsed\n\ndef get_dynamic_covariates_query(eligible_prefix, chartitems_to_keep, labitems_to_keep):\n with open('./queries/dynamic_covariates_choose_all.sql','r') as f:\n query_raw = f.read()\n query_parsed = eligibility_query_prefix + query_raw.format(\\\n chitem=chartitems_to_keep, lbitem=labitems_to_keep)\n return query_parsed\n\ndef get_useful_chart_lab_itemids(common_chartlabs_filename):\n common_ids = pd.read_csv(common_chartlabs_filename)\n\n common_chartevents = common_ids[common_ids['chartorlab'] == 'chart']['itemid']\n common_labevents = common_ids[common_ids['chartorlab'] == 'lab']['itemid']\n\n chartitems_to_keep = str(tuple(common_chartevents.values[:200]))\n labitems_to_keep = str(tuple(common_labevents.values[:100]))\n\n return chartitems_to_keep, labitems_to_keep\nif __name__ == '__main__':\n #TODO main: icd codes, \"colloid_bolus\", \"crystalloid_bolus\", \"nivdurations\" vasopressordurations', 'adenosinedurations', 'dobutaminedurations', 'dopaminedurations', 'epinephrinedurations', 'isupreldurations', 'milrinonedurations', 'norepinephrinedurations', 'phenylephrinedurations', 'vasopressindurations']\n \n #print(args)\n using_args = True\n if using_args:\n args = get_args()\n min_age_string = str(args['min_age'])\n min_dur_string = str(args['min_duration'])\n max_dur_string = str(args['max_duration'])\n min_day_string = str(float(args['min_duration'])/24)\n if args['pop_size'] == -1:\n pop_size_string = ''\n else:\n pop_size_string = str(args['pop_size'])\n #if args['psql_host'] is not None: query_args['host'] = args['psql_host']\n #if args['psql_password'] is not None: query_args['password'] = args['psql_password']\n else:\n min_age_string = '16'\n min_dur_string = '12'\n max_dur_string = '240'\n min_day_string = '0.5'\n pop_size_string = ''\n\n query_args = {'dbname': dbname}\n query_args['user'] = 'postgres'\n\n\n # used for joining rest of downstream queries\n eligibility_query_prefix = get_eligibility_query_prefix(\n pop_size_string, min_age_string, min_dur_string, max_dur_string, min_day_string)\n static_covariates_query = get_static_covariates_query(eligibility_query_prefix)\n\n root_dir = '/home/joe/Predict_PO2/new_mimic_cleaner/'\n common_chartlabs_filename = root_dir + 'mimic_id_tables/get_common_charts_labs_results_metavision.csv'\n chartitems_to_keep, labitems_to_keep = get_useful_chart_lab_itemids(common_chartlabs_filename)\n\n dynamic_query = get_dynamic_covariates_query(eligibility_query_prefix, chartitems_to_keep, labitems_to_keep)\n\n inputs_query = get_inputs_query(eligibility_query_prefix)\n \n con = psycopg2.connect(**query_args)\n cur = con.cursor()\n cur.execute('SET search_path to ' + schema_name)\n\n inputs_covariates = pd.read_sql_query(inputs_query, con)\n\n print('getting dynamic covariates')\n dynamic_covariates = pd.read_sql_query(dynamic_query, con)\n print('got dynamic covariates')\n\n common_vars = dynamic_covariates['label'].value_counts() > 20\n common_vars_names = common_vars[common_vars].index\n dynamic_covariates_pruned = dynamic_covariates[dynamic_covariates['label'].isin(common_vars_names)]\n print('preprocessing dyn cov')\n interpolated_dyn_cov = preprocess_dynamic_covariates(dynamic_covariates_pruned)\n print('done preprocessing dyn cov')\n\n common_inputs = inputs_covariates['label'].value_counts() > 400\n common_inputs_names = common_inputs[common_inputs].index\n inputs_covariates_pruned = inputs_covariates[inputs_covariates['label'].isin(common_inputs_names)]\n\n print('preprocessing inputs')\n interpolated_input_infusion, interpolated_input_bolus = \\\n preprocess_input_events(inputs_covariates_pruned)\n print('done preprocessing inputs')\n \n print('merging everything')\n #all_inputs = interpolated_input_bolus.merge(interpolated_input_infusion, how='outer',on=ID_COLS + ['hours_in'])\n #all_inputs_chartlab = all_inputs.merge(interpolated_dyn_cov, how='outer',on=ID_COLS + ['hours_in'])\n #print('total size:' + str(all_inputs_chartlab.shape))\n \n print('saving')\n interpolated_input_bolus.to_csv('./interpolated_input_bolus.csv')\n interpolated_input_infusion.to_csv('./interpolated_input_infusion.csv')\n interpolated_dyn_cov.to_csv('./interpolated_dyn_cov.csv')\n print('done!')" ]
[ [ "pandas.read_sql_query", "pandas.read_csv", "numpy.isnan", "pandas.DataFrame", "pandas.isna" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mythrocks/spark
[ "47659a0675e4bb0403d1ebe207ec697a78936d04" ]
[ "examples/src/main/python/sql/arrow.py" ]
[ "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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\"\"\"\nA simple example demonstrating Arrow in Spark.\nRun with:\n ./bin/spark-submit examples/src/main/python/sql/arrow.py\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.pandas.utils import require_minimum_pandas_version, require_minimum_pyarrow_version\n\nrequire_minimum_pandas_version()\nrequire_minimum_pyarrow_version()\n\n\ndef dataframe_with_arrow_example(spark):\n # $example on:dataframe_with_arrow$\n import numpy as np\n import pandas as pd\n\n # Enable Arrow-based columnar data transfers\n spark.conf.set(\"spark.sql.execution.arrow.pyspark.enabled\", \"true\")\n\n # Generate a Pandas DataFrame\n pdf = pd.DataFrame(np.random.rand(100, 3))\n\n # Create a Spark DataFrame from a Pandas DataFrame using Arrow\n df = spark.createDataFrame(pdf)\n\n # Convert the Spark DataFrame back to a Pandas DataFrame using Arrow\n result_pdf = df.select(\"*\").toPandas()\n # $example off:dataframe_with_arrow$\n print(\"Pandas DataFrame result statistics:\\n%s\\n\" % str(result_pdf.describe()))\n\n\ndef scalar_pandas_udf_example(spark):\n # $example on:scalar_pandas_udf$\n import pandas as pd\n\n from pyspark.sql.functions import col, pandas_udf\n from pyspark.sql.types import LongType\n\n # Declare the function and create the UDF\n def multiply_func(a, b):\n return a * b\n\n multiply = pandas_udf(multiply_func, returnType=LongType())\n\n # The function for a pandas_udf should be able to execute with local Pandas data\n x = pd.Series([1, 2, 3])\n print(multiply_func(x, x))\n # 0 1\n # 1 4\n # 2 9\n # dtype: int64\n\n # Create a Spark DataFrame, 'spark' is an existing SparkSession\n df = spark.createDataFrame(pd.DataFrame(x, columns=[\"x\"]))\n\n # Execute function as a Spark vectorized UDF\n df.select(multiply(col(\"x\"), col(\"x\"))).show()\n # +-------------------+\n # |multiply_func(x, x)|\n # +-------------------+\n # | 1|\n # | 4|\n # | 9|\n # +-------------------+\n # $example off:scalar_pandas_udf$\n\n\ndef scalar_iter_pandas_udf_example(spark):\n # $example on:scalar_iter_pandas_udf$\n import pandas as pd\n\n from pyspark.sql.functions import col, pandas_udf, struct, PandasUDFType\n\n pdf = pd.DataFrame([1, 2, 3], columns=[\"x\"])\n df = spark.createDataFrame(pdf)\n\n # When the UDF is called with a single column that is not StructType,\n # the input to the underlying function is an iterator of pd.Series.\n @pandas_udf(\"long\", PandasUDFType.SCALAR_ITER)\n def plus_one(batch_iter):\n for x in batch_iter:\n yield x + 1\n\n df.select(plus_one(col(\"x\"))).show()\n # +-----------+\n # |plus_one(x)|\n # +-----------+\n # | 2|\n # | 3|\n # | 4|\n # +-----------+\n\n # When the UDF is called with more than one columns,\n # the input to the underlying function is an iterator of pd.Series tuple.\n @pandas_udf(\"long\", PandasUDFType.SCALAR_ITER)\n def multiply_two_cols(batch_iter):\n for a, b in batch_iter:\n yield a * b\n\n df.select(multiply_two_cols(col(\"x\"), col(\"x\"))).show()\n # +-----------------------+\n # |multiply_two_cols(x, x)|\n # +-----------------------+\n # | 1|\n # | 4|\n # | 9|\n # +-----------------------+\n\n # When the UDF is called with a single column that is StructType,\n # the input to the underlying function is an iterator of pd.DataFrame.\n @pandas_udf(\"long\", PandasUDFType.SCALAR_ITER)\n def multiply_two_nested_cols(pdf_iter):\n for pdf in pdf_iter:\n yield pdf[\"a\"] * pdf[\"b\"]\n\n df.select(\n multiply_two_nested_cols(\n struct(col(\"x\").alias(\"a\"), col(\"x\").alias(\"b\"))\n ).alias(\"y\")\n ).show()\n # +---+\n # | y|\n # +---+\n # | 1|\n # | 4|\n # | 9|\n # +---+\n\n # In the UDF, you can initialize some states before processing batches.\n # Wrap your code with try/finally or use context managers to ensure\n # the release of resources at the end.\n y_bc = spark.sparkContext.broadcast(1)\n\n @pandas_udf(\"long\", PandasUDFType.SCALAR_ITER)\n def plus_y(batch_iter):\n y = y_bc.value # initialize states\n try:\n for x in batch_iter:\n yield x + y\n finally:\n pass # release resources here, if any\n\n df.select(plus_y(col(\"x\"))).show()\n # +---------+\n # |plus_y(x)|\n # +---------+\n # | 2|\n # | 3|\n # | 4|\n # +---------+\n # $example off:scalar_iter_pandas_udf$\n\n\ndef grouped_map_pandas_udf_example(spark):\n # $example on:grouped_map_pandas_udf$\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n df = spark.createDataFrame(\n [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n (\"id\", \"v\"))\n\n @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP)\n def subtract_mean(pdf):\n # pdf is a pandas.DataFrame\n v = pdf.v\n return pdf.assign(v=v - v.mean())\n\n df.groupby(\"id\").apply(subtract_mean).show()\n # +---+----+\n # | id| v|\n # +---+----+\n # | 1|-0.5|\n # | 1| 0.5|\n # | 2|-3.0|\n # | 2|-1.0|\n # | 2| 4.0|\n # +---+----+\n # $example off:grouped_map_pandas_udf$\n\n\ndef grouped_agg_pandas_udf_example(spark):\n # $example on:grouped_agg_pandas_udf$\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n from pyspark.sql import Window\n\n df = spark.createDataFrame(\n [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n (\"id\", \"v\"))\n\n @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG)\n def mean_udf(v):\n return v.mean()\n\n df.groupby(\"id\").agg(mean_udf(df['v'])).show()\n # +---+-----------+\n # | id|mean_udf(v)|\n # +---+-----------+\n # | 1| 1.5|\n # | 2| 6.0|\n # +---+-----------+\n\n w = Window \\\n .partitionBy('id') \\\n .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)\n df.withColumn('mean_v', mean_udf(df['v']).over(w)).show()\n # +---+----+------+\n # | id| v|mean_v|\n # +---+----+------+\n # | 1| 1.0| 1.5|\n # | 1| 2.0| 1.5|\n # | 2| 3.0| 6.0|\n # | 2| 5.0| 6.0|\n # | 2|10.0| 6.0|\n # +---+----+------+\n # $example off:grouped_agg_pandas_udf$\n\n\ndef map_iter_pandas_udf_example(spark):\n # $example on:map_iter_pandas_udf$\n import pandas as pd\n\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n df = spark.createDataFrame([(1, 21), (2, 30)], (\"id\", \"age\"))\n\n @pandas_udf(df.schema, PandasUDFType.MAP_ITER)\n def filter_func(batch_iter):\n for pdf in batch_iter:\n yield pdf[pdf.id == 1]\n\n df.mapInPandas(filter_func).show()\n # +---+---+\n # | id|age|\n # +---+---+\n # | 1| 21|\n # +---+---+\n # $example off:map_iter_pandas_udf$\n\n\ndef cogrouped_map_pandas_udf_example(spark):\n # $example on:cogrouped_map_pandas_udf$\n import pandas as pd\n\n from pyspark.sql.functions import pandas_udf, PandasUDFType\n\n df1 = spark.createDataFrame(\n [(20000101, 1, 1.0), (20000101, 2, 2.0), (20000102, 1, 3.0), (20000102, 2, 4.0)],\n (\"time\", \"id\", \"v1\"))\n\n df2 = spark.createDataFrame(\n [(20000101, 1, \"x\"), (20000101, 2, \"y\")],\n (\"time\", \"id\", \"v2\"))\n\n @pandas_udf(\"time int, id int, v1 double, v2 string\", PandasUDFType.COGROUPED_MAP)\n def asof_join(l, r):\n return pd.merge_asof(l, r, on=\"time\", by=\"id\")\n\n df1.groupby(\"id\").cogroup(df2.groupby(\"id\")).apply(asof_join).show()\n # +--------+---+---+---+\n # | time| id| v1| v2|\n # +--------+---+---+---+\n # |20000101| 1|1.0| x|\n # |20000102| 1|3.0| x|\n # |20000101| 2|2.0| y|\n # |20000102| 2|4.0| y|\n # +--------+---+---+---+\n # $example off:cogrouped_map_pandas_udf$\n\n\nif __name__ == \"__main__\":\n spark = SparkSession \\\n .builder \\\n .appName(\"Python Arrow-in-Spark example\") \\\n .getOrCreate()\n\n print(\"Running Pandas to/from conversion example\")\n dataframe_with_arrow_example(spark)\n print(\"Running pandas_udf scalar example\")\n scalar_pandas_udf_example(spark)\n print(\"Running pandas_udf scalar iterator example\")\n scalar_iter_pandas_udf_example(spark)\n print(\"Running pandas_udf grouped map example\")\n grouped_map_pandas_udf_example(spark)\n print(\"Running pandas_udf grouped agg example\")\n grouped_agg_pandas_udf_example(spark)\n print(\"Running pandas_udf map iterator example\")\n map_iter_pandas_udf_example(spark)\n print(\"Running pandas_udf cogrouped map example\")\n cogrouped_map_pandas_udf_example(spark)\n\n spark.stop()\n" ]
[ [ "numpy.random.rand", "pandas.Series", "pandas.DataFrame", "pandas.merge_asof" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
Amjad50/Fyp
[ "6bd934ef42edf7e355ade6cf5d2a151f098f2352" ]
[ "parser/utils.py" ]
[ "from re import sub as re_sub\nfrom typing import Optional\n\nimport numpy as np\n\nfrom segmenter.utils import box_center, box_size\nfrom symbols_utils.symbol_size import get_baseline_center, percentage_of_default_size\nfrom utils.geometry import angle_between_points, distance_between_points\nfrom utils.types import LabelCrop, Box\n\nRELATIONS = [\"left\", \"power\", \"sub\", \"up\", \"down\", \"none\"]\n\n\ndef can_symbol_have_up_down(symbol: str) -> bool:\n can_have_up_down = [\"\\\\frac\", \"\\\\sum\", \"\\\\int\"]\n return symbol in can_have_up_down\n\n\ndef can_be_power_or_sub(box1: Box, box2: Box) -> bool:\n w1, h1 = box_size(box1)\n w2, h2 = box_size(box2)\n left1, top1, right1, down1 = box1\n left2, top2, right2, down2 = box2\n\n assert left1 < left2, \"box1 must be to the left of box2\"\n\n # must not be too far to the left\n if right1 + min(w1, w2) < left2:\n return False\n\n # power possibility\n if top1 > top2:\n if top1 - h1 > down2:\n return False\n # sub possibility\n else:\n if down1 + h1 < top2:\n return False\n return True\n\n\ndef get_most_probable_relation(label_crop1: LabelCrop, label_crop2: LabelCrop) -> Optional[str]:\n label1, box1 = label_crop1\n label2, box2 = label_crop2\n\n left1, top1, right1, down1 = box1\n left2, top2, right2, down2 = box2\n\n # the left should be first\n if left1 > left2:\n # TODO: is this the best way? using this to reduce connections\n return None\n\n center1 = box_center(box1)\n center2 = box_center(box2)\n\n baseline1 = get_baseline_center(*label_crop1)\n baseline2 = get_baseline_center(*label_crop2)\n\n perc1 = percentage_of_default_size(label1, box1)\n perc2 = percentage_of_default_size(label2, box2)\n\n perc_perc = perc2 / perc1\n\n angle = angle_between_points(baseline1, baseline2)\n\n if left1 <= left2 and right1 >= right2 and can_symbol_have_up_down(label1):\n if angle > 0:\n return 'up'\n else:\n return 'down'\n\n # this is a case where the top/down is a bit outside the boundary of the \\frac element\n # which results in having `power/sub` connection which is not true\n if left2 < right1 < right2 and can_symbol_have_up_down(label2):\n return None\n\n if label1 == '\\\\frac' or label2 == '\\\\frac':\n angle = angle_between_points(center1, center2)\n\n if perc_perc < 0.85:\n if -8 >= angle >= -30 and label1 != '\\\\frac' and can_be_power_or_sub(box1, box2):\n return 'sub'\n elif 15 <= angle <= 60 and label1 != '\\\\frac' and can_be_power_or_sub(box1, box2):\n return 'power'\n\n if abs(perc_perc - 1) > 0.15 and label1 != '\\\\frac' and label2 != '\\\\frac':\n # cannot have power, sub or left of smaller symbol to a larger symbol\n if 15 >= angle >= -30:\n return 'none'\n\n if -12 >= angle >= -30 and label1 != '-' and can_be_power_or_sub(box1, box2):\n return 'sub'\n elif 25 <= angle <= 60 and label1 != '-' and can_be_power_or_sub(box1, box2):\n return 'power'\n elif -10 <= angle <= 10:\n return 'left'\n elif 140 >= angle >= 60 and can_symbol_have_up_down(label1):\n return 'up'\n elif -60 >= angle >= -130 and can_symbol_have_up_down(label1):\n return 'down'\n\n return 'none'\n\n\ndef distance_labeled_crops(label_crop1: LabelCrop, label_crop2: LabelCrop) -> Optional[float]:\n label1, box1 = label_crop1\n label2, box2 = label_crop2\n\n # the left should be first\n if box1[0] > box2[0]:\n return None\n\n p1 = box_center(box1)\n p2 = box_center(box2)\n\n options = [distance_between_points(p1, p2)]\n\n if label1 == '\\\\frac':\n t, l, d, r = box1\n options.append(distance_between_points((t, l), p2))\n\n if label2 == '\\\\frac':\n t, l, d, r = box2\n options.append(distance_between_points(p1, (t, r)))\n\n return np.min(options)\n\n\ndef compute_modified_distance(distance: float, relation: str) -> float:\n additions = {\n 'none': 1e6,\n 'left': 0,\n 'sub': 0,\n 'power': 0,\n 'up': 0,\n 'down': 0,\n }\n\n assert relation in additions\n\n return distance + additions[relation]\n\n\ndef optimize_latex_string(input_string: str) -> str:\n # remove latex brackets if only one character is inside\n return re_sub(r'{(.)}', '\\\\1', input_string.replace(' ', ''))\n" ]
[ [ "numpy.min" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qihongl/dlstm-demo
[ "1f2edc02708d1226224c76396548b40caafef76e" ]
[ "src/task/ContextualChoice.py" ]
[ "import torch\nimport numpy as np\n\n\nclass ContextualChoice():\n\n def __init__(self, obs_dim, trial_length=10, t_noise_off=5):\n self.obs_dim = obs_dim\n self.ctx_dim = obs_dim\n self.trial_length = trial_length\n self.t_noise_off = t_noise_off\n # 2nd level params\n self.x_dim = self.obs_dim + self.ctx_dim\n self.y_dim = 1\n # input validation\n assert t_noise_off < trial_length\n\n def sample(\n self, n_unique_examples,\n to_torch=True,\n ):\n \"\"\"sample a task sequence\n\n Parameters\n ----------\n n_unique_examples : type\n Description of parameter `n_unique_examples`.\n to_torch : type\n Description of parameter `to_torch`.\n\n Returns\n -------\n type\n Description of returned object.\n\n \"\"\"\n observation_p1, target_p1, context_p1 = self._sample_n_trials(\n n_unique_examples)\n # form the 2nd part of the data\n [observation_p2, target_p2, context_p2] = _permute_array_list(\n [observation_p1, target_p1, context_p1])\n # concat observation and context\n observation_context_p1 = np.dstack([observation_p1, context_p1])\n observation_context_p2 = np.dstack([observation_p2, context_p2])\n # combine the two phases\n X = np.vstack([observation_context_p1, observation_context_p2])\n Y = np.vstack([target_p1, target_p2])\n # to pytorch form\n if to_torch:\n X = to_pth(X)\n Y = to_pth(Y, pth_dtype=torch.LongTensor)\n return X, Y\n\n def _sample_n_trials(self, n_examples):\n observation = np.zeros((n_examples, self.trial_length, self.obs_dim))\n context = np.zeros((n_examples, self.trial_length, self.ctx_dim))\n target = np.zeros((n_examples, self.trial_length, self.y_dim))\n for i in range(n_examples):\n observation[i], context[i], target[i] = self._sample_one_trial()\n return observation, target, context\n\n def _sample_one_trial(self):\n \"\"\"\n evidence:\n initially ambiguous,\n after `t_noise_off`, become predictive about the target\n \"\"\"\n evidence = np.random.normal(\n loc=np.sign(np.random.normal()),\n size=(self.trial_length, self.obs_dim)\n )\n # integration results\n target_value = 1 if np.sum(evidence) > 0 else 0\n target = np.tile(target_value, (self.trial_length, 1))\n # corrupt the evidence input\n evidence[:self.t_noise_off] = np.random.normal(\n loc=0, size=(self.t_noise_off, self.obs_dim)\n )\n # generate a cue\n cue_t = np.random.normal(size=(self.ctx_dim, ))\n cue = np.tile(cue_t, (self.trial_length, 1))\n return evidence, cue, target\n\n\ndef _permute_array_list(input_list):\n \"\"\"permute a list of n-d arrays\n\n Parameters\n ----------\n input_list : list\n a list of arrays, 0-th dim must be the same\n\n Returns\n -------\n list\n a list of arrays, permuted in the same way (along the 0-th dim)\n\n \"\"\"\n n_examples_ = len(input_list[0])\n for np_array in input_list:\n assert np.shape(np_array)[0] == n_examples_, \\\n f'{np.shape(np_array)} != n_examples_ == ({n_examples_})'\n perm_op = np.random.permutation(n_examples_)\n # for every list, permute them by\n perm_list = [input_list_j[perm_op] for input_list_j in input_list]\n return perm_list\n\n\ndef to_pth(np_array, pth_dtype=torch.FloatTensor):\n return torch.tensor(np_array).type(pth_dtype)\n\n\n'''how to use'''\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n import seaborn as sns\n sns.set(style='white', context='talk')\n\n # build a sampler\n obs_dim = 20\n trial_length = 10\n t_noise_off = 5\n task = ContextualChoice(\n obs_dim=obs_dim,\n trial_length=trial_length,\n t_noise_off=t_noise_off\n )\n # sample\n n_examples = 5\n X, Y = task.sample(n_examples, to_torch=False)\n print(f'X shape = {np.shape(X)}, n_example x time x x-dim')\n print(f'Y shape = {np.shape(Y)}, n_example x time x y-dim')\n\n # show one trial\n i = 0\n input = X[i]\n target = int(Y[i][0])\n vmin = np.min(X)\n vmax = np.max(X)\n\n f, ax = plt.subplots(1, 1, figsize=(3, 5))\n sns.heatmap(\n input.T,\n vmin=vmin, vmax=vmax,\n cmap='RdBu_r', yticklabels=10, center=0,\n ax=ax\n )\n ax.axvline(t_noise_off, color='grey', linestyle='--')\n ax.axhline(obs_dim, color='black', linestyle='--')\n ax.set_title(f'Stimulus for a trial, y = {target}')\n ax.set_xlabel('Time')\n ax.set_ylabel('x-dim: context | input')\n f.savefig(f'../figs/eg-{target}.png', dpi=100, bbox_inches='tight')\n" ]
[ [ "numpy.min", "matplotlib.pyplot.subplots", "numpy.dstack", "numpy.tile", "torch.tensor", "numpy.max", "numpy.random.normal", "numpy.random.permutation", "numpy.shape", "numpy.zeros", "numpy.sum", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Bonder-MJ/limix_qtl
[ "71f18f4e39cdba0f0e6dc59713b83701599bc86f" ]
[ "Limix_QTL/test_QTL_small_analysis_lm.py" ]
[ "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n#from depricated_run_QTL_analysis_limix_1 import run_QTL_analysis\nfrom run_QTL_analysis import run_QTL_analysis\nfrom qtl_utilities import merge_QTL_results\nimport subprocess\nimport numpy as np\nimport pandas as pd\nimport pytest\n\ndef hdf5_results_checking(filename,fun=lambda df: np.mean(df['beta']) ):\n '''For a given hdf5 results file, returns a value derived from the first dataframe\n in the file.'''\n with pd.HDFStore(filename,'r') as h5file:\n feature_id = sorted(h5file.keys())[0]\n df = h5file.select(feature_id)\n return fun(df)\n\ndef results_checking(results_checking_dict,error_tolerance=1e-6):\n for f in results_checking_dict.keys():\n check_value = hdf5_results_checking(f)\n print(f,check_value)\n assert(abs(results_checking_dict[f]-check_value)<error_tolerance)\n\n\ndef test_QTL_analysis():\n '''Run a set of test cases'''\n data_path = '../geuvadis_CEU_test_data/'\n covariates_filename = data_path+'Expression/Geuvadis_CEU_YRI_covariates.txt'\n geno_prefix = data_path+'Genotypes/Geuvadis'\n pheno_filename = data_path+'Expression/Geuvadis_CEU_YRI_Expr.txt.gz'\n anno_filename = data_path+'Expression/Geuvadis_CEU_Annot_small.txt'\n individual2sample_filename = data_path + 'Geuvadis_CEU_gte.txt'\n min_maf = 0.05\n min_hwe_P=0.001\n min_call_rate =0.95\n blocksize = 50\n output_dir = data_path+'limix_QTL_results_covs/'\n randomSeed = 73\n chromosome = '1'\n \n ws = 2500000\n \n run_QTL_analysis(pheno_filename,anno_filename,geno_prefix,True,output_dir,ws,\n min_maf, min_hwe_P, min_call_rate,\n blocksize,cis_mode=True, seed=randomSeed, n_perm=100, snps_filename=None,feature_filename = None,\n genetic_range=chromosome,\n covariates_filename=covariates_filename,\n write_permutations = True,\n sample_mapping_filename=individual2sample_filename)\n\nif __name__=='__main__':\n test_QTL_analysis()\n" ]
[ [ "numpy.mean", "pandas.HDFStore" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Jamie725/RGBT-detection
[ "e7741bf0a8bdfb940794248a6d3247e4a5025dc4" ]
[ "demo/demo_bayesian_fusion.py" ]
[ "\"\"\"\nTake 3 model as input\n\nCorrect multi-class Bayesian fusion\n\nFuse multi-class probability, also perform logits summation\n\"\"\"\nimport pdb\nimport os\nimport json\nimport numpy as np\nfrom os.path import isfile, join\nimport cv2\nimport torch\nimport pickle\nfrom torch.nn import functional as F\nfrom torchvision.ops import boxes as box_ops\nfrom torchvision.ops import nms # BC-compat\nfrom detectron2.config import get_cfg\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.data.datasets import register_coco_instances\nfrom detectron2.structures import Instances, Boxes\nfrom detectron2.evaluation import FLIREvaluator\n# For COCO evaluation\nfrom fvcore.common.file_io import PathManager\nfrom detectron2.pycocotools.coco import COCO\nfrom detectron2.pycocotools.cocoeval import COCOeval\n\ndef batched_nms(boxes, scores, idxs, iou_threshold):\n \"\"\"\n Same as torchvision.ops.boxes.batched_nms, but safer.\n \"\"\"\n assert boxes.shape[-1] == 4\n # TODO may need better strategy.\n # Investigate after having a fully-cuda NMS op.\n if len(boxes) < 40000:\n return box_ops.batched_nms(boxes, scores, idxs, iou_threshold)\n\n result_mask = scores.new_zeros(scores.size(), dtype=torch.bool)\n for id in torch.unique(idxs).cpu().tolist():\n mask = (idxs == id).nonzero().view(-1)\n keep = nms(boxes[mask], scores[mask], iou_threshold)\n result_mask[mask[keep]] = True\n keep = result_mask.nonzero().view(-1)\n keep = keep[scores[keep].argsort(descending=True)]\n return keep\n\ndef avg_bbox_fusion(match_bbox_vec):\n avg_bboxs = np.sum(match_bbox_vec,axis=0) / len(match_bbox_vec)\n return avg_bboxs\n\ndef bayesian_fusion(match_score_vec):\n log_positive_scores = np.log(match_score_vec)\n log_negative_scores = np.log(1 - match_score_vec)\n fused_positive = np.exp(np.sum(log_positive_scores))\n fused_negative = np.exp(np.sum(log_negative_scores))\n fused_positive_normalized = fused_positive / (fused_positive + fused_negative)\n return fused_positive_normalized\n\ndef bayesian_fusion_multiclass(match_score_vec, pred_class):\n scores = np.zeros((match_score_vec.shape[0], 4))\n scores[:,:3] = match_score_vec\n scores[:,-1] = 1 - np.sum(match_score_vec, axis=1)\n log_scores = np.log(scores)\n sum_logits = np.sum(log_scores, axis=0)\n exp_logits = np.exp(sum_logits)\n out_score = exp_logits[pred_class] / np.sum(exp_logits)\n return out_score\n\ndef bayesian_fusion_multiclass_prior(match_score_vec, pred_class, class_prior):\n scores = np.zeros((match_score_vec.shape[0], 4))\n scores[:,:3] = match_score_vec\n scores[:,-1] = 1 - np.sum(match_score_vec, axis=1)\n log_scores = np.log(scores)\n sum_logits = np.sum(log_scores, axis=0) - np.log(class_prior)\n exp_logits = np.exp(sum_logits)\n out_score = exp_logits[pred_class] / np.sum(exp_logits)\n return out_score\n \ndef nms_1(info_1, info_2, info_3=''):\n # Boxes\n boxes = info_1['bbox'].copy()\n boxes.extend(info_2['bbox'])\n # Scores\n scores = info_1['score'].copy()\n scores.extend(info_2['score'])\n # Classes\n classes = info_1['class'].copy()\n classes.extend(info_2['class'])\n if info_3:\n boxes.extend(info_3['bbox'])\n scores.extend(info_3['score'])\n classes.extend(info_3['class'])\n \n classes = torch.Tensor(classes)\n scores = torch.Tensor(scores)\n boxes = torch.Tensor(boxes)\n # Perform nms\n iou_threshold = 0.5\n keep_id = batched_nms(boxes, scores, classes, iou_threshold)\n\n # Add to output\n out_boxes = boxes[keep_id]\n out_scores = torch.Tensor(scores[keep_id])\n out_class = torch.Tensor(classes[keep_id])\n \n return out_boxes, out_scores, out_class\n\ndef weighted_box_fusion(bbox, score):\n weight = score / np.sum(score)\n out_bbox = np.zeros(4)\n for i in range(len(score)):\n out_bbox += weight[i] * bbox[i]\n return out_bbox\n\ndef prepare_data(info1, info2, info3=''):\n bbox1 = np.array(info1['bbox'])\n bbox2 = np.array(info2['bbox'])\n score1 = np.array(info1['score'])\n score2 = np.array(info2['score'])\n class1 = np.array(info1['class'])\n class2 = np.array(info2['class'])\n out_logits = {}\n out_logits['1'] = np.array(info1['class_logits'])\n out_logits['2'] = np.array(info2['class_logits'])\n out_bbox = np.concatenate((bbox1, bbox2), axis=0)\n out_score = np.concatenate((score1, score2), axis=0)\n out_class = np.concatenate((class1, class2), axis=0)\n \n # If more than two detections are fused\n if info3:\n bbox3 = np.array(info3['bbox'])\n score3 = np.array(info3['score'])\n class3 = np.array(info3['class'])\n out_logits['3'] = np.array(info3['class_logits'])\n out_bbox = np.concatenate((out_bbox, bbox3), axis=0)\n out_score = np.concatenate((out_score, score3), axis=0)\n out_class = np.concatenate((out_class, class3), axis=0)\n \n if 'prob' in info1.keys():\n prob1 = np.array(info1['prob'])\n prob2 = np.array(info2['prob']) \n out_prob = np.concatenate((prob1, prob2), axis=0)\n if info3:\n prob3 = np.array(info3['prob']) \n out_prob = np.concatenate((out_prob, prob3), axis=0)\n return out_bbox, out_score, out_class, out_logits, out_prob\n else: \n return out_bbox, out_score, out_class, out_logits\n\ndef nms_bayesian(dets, scores, classes, probs, thresh, method):\n x1 = dets[:, 0] + classes * 640\n y1 = dets[:, 1] + classes * 512\n x2 = dets[:, 2] + classes * 640\n y2 = dets[:, 3] + classes * 512\n \n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n \n keep = []\n match_scores = []\n match_bboxs = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n \n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n \n inds = np.where(ovr <= thresh)[0]\n match = np.where(ovr > thresh)[0]\n match_ind = order[match+1]\n \n match_prob = list(probs[match_ind])\n match_score = list(scores[match_ind])\n match_bbox = list(dets[match_ind][:,:4])\n original_prob = probs[i]\n original_score = scores[i].tolist()\n original_bbox = dets[i][:4]\n \n # If some boxes are matched\n if len(match_score)>0:\n match_score += [original_score]\n match_prob += [original_prob]\n # Try with different fusion methods\n if method == 'avg_score':\n final_score = np.mean(np.asarray(match_score))\n final_bbox = avg_bbox_fusion(match_bbox)\n elif method == 'bayesian':\n final_score = bayesian_fusion_multiclass(np.asarray(match_prob), classes[i])\n final_bbox = avg_bbox_fusion(match_bbox)\n elif method == 'baysian_avg_bbox':\n final_score = bayesian_fusion_multiclass(np.asarray(match_prob), classes[i]) \n match_bbox += [original_bbox]\n final_bbox = avg_bbox_fusion(match_bbox)\n elif method == 'bayesian_wt_score_box':\n final_score = bayesian_fusion_multiclass(np.asarray(match_prob), classes[i]) \n match_bbox += [original_bbox]\n final_bbox = weighted_box_fusion(match_bbox, match_score) \n elif method == 'bayesian_prior_wt_score_box':\n \"\"\"\n This method is to set different ratios o priors to test how serious priors affect the overall performance (See supplements.)\n \"\"\"\n p4person = 4\n class_prior = [p4person,1,1,1]\n class_prior /= np.sum(class_prior)\n final_score = bayesian_fusion_multiclass_prior(np.asarray(match_prob), classes[i], class_prior) \n match_bbox += [original_bbox]\n final_bbox = weighted_box_fusion(match_bbox, match_score)\n \n match_scores.append(final_score)\n match_bboxs.append(final_bbox)\n else:\n match_scores.append(original_score)\n match_bboxs.append(original_bbox)\n\n order = order[inds + 1]\n \n assert len(keep)==len(match_scores)\n assert len(keep)==len(match_bboxs)\n\n match_bboxs = match_bboxs\n match_scores = torch.Tensor(match_scores)\n match_classes = torch.Tensor(classes[keep])\n\n return keep,match_scores,match_bboxs, match_classes\n\ndef handle_logits(logits, classes):\n logits1 = logits['1']\n logits2 = logits['2']\n out_logits = np.concatenate((logits1, logits2), axis=0)\n if '3' in logits.keys():\n logits3 = logits['3']\n out_logits = np.concatenate((out_logits, logits3), axis=0)\n return out_logits\n\ndef nms_logits(dets, scores, classes, logits, thresh, method):\n x1 = dets[:, 0] + classes * 640\n y1 = dets[:, 1] + classes * 512\n x2 = dets[:, 2] + classes * 640\n y2 = dets[:, 3] + classes * 512\n \n out_logits = handle_logits(logits, classes)\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n \n order = scores.argsort()[::-1]\n keep = []\n match_scores = []\n match_bboxs = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n \n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n \n inds = np.where(ovr <= thresh)[0]\n match = np.where(ovr > thresh)[0]\n match_ind = order[match+1]\n\n match_score = list(out_logits[match_ind])\n match_bbox = list(dets[match_ind][:,:4])\n original_score = out_logits[i].tolist() \n original_bbox = dets[i][:4]\n if len(match_score)>0:\n match_score += [original_score]\n if method == 'avgLogits_softmax': \n final_score = np.mean(np.asarray(match_score), axis=0)\n final_score = F.softmax(torch.Tensor(final_score), dim=0)[classes[i]].tolist()\n final_bbox = avg_bbox_fusion(match_bbox)\n elif method == 'sumLogits_softmax':\n final_score = np.sum(np.asarray(match_score), axis=0)\n final_score = F.softmax(torch.Tensor(final_score), dim=0)[classes[i]].tolist()\n final_bbox = avg_bbox_fusion(match_bbox)\n \n match_scores.append(final_score)\n match_bboxs.append(final_bbox)\n else:\n final_score = F.softmax(torch.Tensor(original_score), dim=0)[classes[i]].tolist()\n match_scores.append(final_score)\n match_bboxs.append(original_bbox)\n \n order = order[inds + 1]\n \n assert len(keep)==len(match_scores)\n assert len(keep)==len(match_bboxs)\n\n match_bboxs = match_bboxs\n match_scores = torch.Tensor(match_scores)\n match_classes = torch.Tensor(classes[keep])\n return keep,match_scores,match_bboxs, match_classes\n\ndef fusion(method, info_1, info_2, info_3=''):\n if method == 'nms': \n out_boxes, out_scores, out_class = nms_1(info_1, info_2, info_3=info_3)\n elif method == 'pooling':\n in_boxes, in_scores, in_class, in_logits, in_prob = prepare_data(info_1, info_2, info3=info_3)\n out_boxes = in_boxes\n out_scores = torch.Tensor(in_scores)\n out_class = torch.Tensor(in_class)\n elif method == 'bayesian' or method == 'baysian_avg_bbox' or method == 'avg_score' or method == 'bayesian_wt_score_box' or method == 'bayesian_prior_wt_score_box':\n threshold = 0.5\n in_boxes, in_scores, in_class, in_logits, in_prob = prepare_data(info_1, info_2, info3=info_3)\n keep, out_scores, out_boxes, out_class = nms_bayesian(in_boxes, in_scores, in_class, in_prob, threshold, method)\n elif method == 'avgLogits_softmax' or method == 'sumLogits_softmax':\n threshold = 0.5\n in_boxes, in_scores, in_class, in_logits, _ = prepare_data(info_1, info_2, info3=info_3)\n keep, out_scores, out_boxes, out_class = nms_logits(in_boxes, in_scores, in_class, in_logits, threshold, method)\n return out_boxes, out_scores, out_class\n\ndef draw_box(img, bbox, pred_class, color):\n class_name = ['person', 'bike', 'car']\n # font\n font = cv2.FONT_HERSHEY_SIMPLEX\n # fontScale\n fontScale = 0.8\n # Line thickness of 2 px\n thickness = 2\n color2 = (0, 130, 255)\n for i in range(len(bbox)):\n img = cv2.rectangle(img, (int(bbox[i][0]+0.5), int(bbox[i][1]+0.5)), (int(bbox[i][2]+0.5), int(bbox[i][3]+0.5)), color, 2)\n thickness = 2\n for i in range(len(bbox)):\n min_x = max(int(bbox[i][0] - 5), 0)\n min_y = max(int(bbox[i][1] - 5), 0) \n img = cv2.putText(img, class_name[int(pred_class[i])], (min_x, min_y), font, fontScale, color2, 2, cv2.LINE_AA)\n return img\n\ndef apply_late_fusion_and_evaluate(cfg, evaluator, det_1, det_2, method, det_3=''):\n evaluator.reset()\n img_folder = '../../../Datasets/FLIR/val/thermal_8_bit/'\n \n num_img = len(det_2['image'])\n count_1=0\n count_2=0\n count_fusion=0\n\n print('Method: ', method)\n\n for i in range(num_img):\n info_1 = {}\n info_1['img_name'] = det_1['image'][i]\n info_1['bbox'] = det_1['boxes'][i]\n info_1['score'] = det_1['scores'][i]\n info_1['class'] = det_1['classes'][i]\n info_1['class_logits'] = det_1['class_logits'][i]\n if 'probs' in det_1.keys():\n info_1['prob'] = det_1['probs'][i]\n\n info_2 = {}\n info_2['img_name'] = det_2['image'][i].split('.')[0] + '.jpeg'\n info_2['bbox'] = det_2['boxes'][i]\n info_2['score'] = det_2['scores'][i]\n info_2['class'] = det_2['classes'][i]\n info_2['class_logits'] = det_2['class_logits'][i]\n if 'probs' in det_2.keys():\n info_2['prob'] = det_2['probs'][i]\n \n if len(info_1['bbox']) > 0:\n num_1 = 1\n else:\n num_1 = 0\n if len(info_2['bbox']) > 0:\n num_2 = 1\n else:\n num_2 = 0\n \n num_detections = num_1 + num_2\n\n if det_3:\n info_3 = {}\n info_3['img_name'] = det_3['image'][i].split('.')[0] + '.jpeg'\n info_3['bbox'] = det_3['boxes'][i]\n info_3['score'] = det_3['scores'][i]\n info_3['class'] = det_3['classes'][i]\n info_3['class_logits'] = det_3['class_logits'][i]\n if 'probs' in det_3.keys():\n info_3['prob'] = det_3['probs'][i]\n if len(info_3['bbox']) > 0:\n num_3 = 1\n else:\n num_3 = 0\n\n num_detections += num_3\n \n # No detections\n if num_detections == 0:\n continue\n # Only 1 model detection\n elif num_detections == 1: \n if len(info_1['bbox']) > 0:\n out_boxes = np.array(info_1['bbox'])\n out_class = torch.Tensor(info_1['class'])\n out_scores = torch.Tensor(info_1['score'])\n elif len(info_2['bbox']) > 0:\n out_boxes = np.array(info_2['bbox'])\n out_class = torch.Tensor(info_2['class'])\n out_scores = torch.Tensor(info_2['score'])\n else:\n if det_3:\n out_boxes = np.array(info_3['bbox'])\n out_class = torch.Tensor(info_3['class'])\n out_scores = torch.Tensor(info_3['score'])\n # Only two models with detections\n elif num_detections == 2:\n if not det_3:\n out_boxes, out_scores, out_class = fusion(method, info_1, info_2)\n else: \n if len(info_1['bbox']) == 0:\n out_boxes, out_scores, out_class = fusion(method, info_2, info_3)\n elif len(info_2['bbox']) == 0:\n out_boxes, out_scores, out_class = fusion(method, info_1, info_3)\n else:\n out_boxes, out_scores, out_class = fusion(method, info_1, info_2)\n # All models detected things\n else:\n out_boxes, out_scores, out_class = fusion(method, info_1, info_2, info_3=info_3)\n \n file_name = img_folder + info_1['img_name'].split('.')[0] + '.jpeg'\n img = cv2.imread(file_name)\n H, W, _ = img.shape\n\n # Handle inputs\n inputs = []\n input_info = {}\n input_info['file_name'] = file_name\n input_info['height'] = H\n input_info['width'] = W\n input_info['image_id'] = det_2['image_id'][i]\n input_info['image'] = torch.Tensor(img)\n inputs.append(input_info)\n \n # Handle outputs\n outputs = []\n out_info = {}\n proposals = Instances([H, W])\n proposals.pred_boxes = Boxes(out_boxes)\n proposals.scores = out_scores\n proposals.pred_classes = out_class\n out_info['instances'] = proposals\n outputs.append(out_info)\n evaluator.process(inputs, outputs)\n \n results = evaluator.evaluate(out_eval_path='FLIR_pooling_.out')\n \n if results is None:\n results = {}\n\n return results\n\n\nif __name__ == '__main__':\n data_set = 'val'\n data_folder = 'out/box_predictions/'\n dataset = 'FLIR'\n IOU = 50 \n time = 'Day'\n model_1 = 'early_fusion'\n model_2 = 'mid_fusion'\n model_3 = 'thermal_only'\n if time == 'Day':\n val_file_name = 'thermal_RGBT_pairs_3_class_Day.json'#'thermal_annotations_4_channel_no_dogs_Day.json'\n det_file_1 = data_folder + 'val_'+model_1+'_predictions_IOU50_with_multiclass_prob_score_Day.json'\n det_file_2 = data_folder + 'val_'+model_2+'_predictions_IOU50_with_multiclass_prob_score_Day.json'\n det_file_3 = data_folder + 'val_'+model_3+'_predictions_IOU50_with_multiclass_prob_score_Day.json'\n elif time == 'Night':\n val_file_name = 'thermal_RGBT_pairs_3_class_Night.json'#'thermal_annotations_4_channel_no_dogs_Night.json'\n det_file_1 = data_folder + 'val_'+model_1+'_predictions_IOU50_with_multiclass_prob_score_Night.json'\n det_file_2 = data_folder + 'val_'+model_2+'_predictions_IOU50_with_multiclass_prob_score_Night.json'\n det_file_3 = data_folder + 'val_'+model_3+'_predictions_IOU50_with_multiclass_prob_score_Night.json'\n else:\n det_file_1 = data_folder + 'val_'+model_1+'_predictions_IOU50_with_multiclass_prob_score.json'\n det_file_2 = data_folder + 'val_'+model_2+'_predictions_IOU50_with_multiclass_prob_score.json'\n det_file_3 = data_folder + 'val_'+model_3+'_predictions_IOU50_with_multiclass_prob_score.json'\n\n val_file_name = 'thermal_RGBT_pairs_3_class.json'\n \n print('detection file 1:', det_file_1)\n print('detection file 2:', det_file_2)\n print('detection file 3:', det_file_3)\n \n path_1 = '../../../Datasets/FLIR/' + data_set + '/resized_RGB/'\n path_2 = '../../../Datasets/FLIR/' + data_set + '/thermal_8_bit/'\n out_folder = 'out/box_comparison/'\n \n val_json_path = '../../../Datasets/'+dataset+'/val/' + val_file_name\n val_folder = '../../../Datasets/FLIR/val/thermal_8_bit'\n \n if not os.path.exists(out_folder):\n os.mkdir(out_folder)\n\n # Register dataset\n dataset = 'FLIR_val'\n register_coco_instances(dataset, {}, val_json_path, val_folder)\n FLIR_metadata = MetadataCatalog.get(dataset)\n dataset_dicts = DatasetCatalog.get(dataset)\n\n # Create config\n cfg = get_cfg()\n cfg.OUTPUT_DIR = out_folder\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = 3\n cfg.DATASETS.TEST = (dataset, )\n cfg.INPUT.FORMAT = 'BGR'\n cfg.INPUT.NUM_IN_CHANNELS = 3\n cfg.MODEL.PIXEL_MEAN = [103.530, 116.280, 123.675]\n cfg.MODEL.PIXEL_STD = [1.0, 1.0, 1.0]\n\n # Read detection results\n det_1 = json.load(open(det_file_1, 'r'))\n det_2 = json.load(open(det_file_2, 'r'))\n det_3 = json.load(open(det_file_3, 'r'))\n evaluator = FLIREvaluator(dataset, cfg, False, output_dir=out_folder, save_eval=True, out_eval_path='out/mAP/FLIR_Baysian_'+data_set+'_avg_box_all.out')\n \"\"\"\n \n Method lists: 'bayesian_prior_wt_score_box': This is \n 'bayesian_wt_score_box'\n 'baysian_avg_bbox'\n 'sumLogits_softmax'\n 'avgLogits_softmax'\n 'baysian_avg_bbox'\n 'avg_score'\n 'pooling'\n 'bayesian'\n 'nms'\n \"\"\"\n method = 'baysian_avg_bbox'\n result = apply_late_fusion_and_evaluate(cfg, evaluator, det_1, det_2, method, det_3=det_3)\n" ]
[ [ "numpy.log", "numpy.maximum", "numpy.minimum", "torch.Tensor", "numpy.asarray", "numpy.concatenate", "torch.unique", "numpy.where", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
clulab/gentlenlp
[ "f30f459acabfb89db32bfbe1dec5293611d313d3" ]
[ "chapter4/preprocess_dataset.py" ]
[ "import argparse\nfrom pathlib import Path\nimport numpy as np\nfrom vocabulary import Vocabulary\nimport imdb\n\nif __name__ == '__main__':\n # parse command-line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('data_dir', type=Path, help='path to the data directory')\n parser.add_argument('out_dir', type=Path, help='path to save output files')\n parser.add_argument('--compress', action='store_true', help='compress data')\n args = parser.parse_args()\n # ensure output directory exists\n if not args.out_dir.exists():\n args.out_dir.mkdir()\n # collect data\n print('collecting training data ...')\n vocab = Vocabulary()\n train_token_ids, train_labels = imdb.read_imdb_data(args.data_dir/'train', vocab, add_tokens=True)\n print('saving vocabulary ...')\n vocab.save(args.out_dir/'vocab.imdb')\n print('converting training data to numpy ...')\n X_train, y_train = imdb.to_numpy(train_token_ids, train_labels, vocab)\n print('saving training data ...')\n if args.compress:\n np.savez_compressed(args.out_dir/'train.npz', X=X_train, y=y_train)\n else:\n np.savez(args.out_dir/'train.npz', X=X_train, y=y_train)\n print('collecting test data ...')\n test_token_ids, test_labels = imdb.read_imdb_data(args.data_dir/'test', vocab, add_tokens=False)\n print('converting test data to numpy ...')\n X_test, y_test = imdb.to_numpy(test_token_ids, test_labels, vocab)\n print('saving test data ...')\n if args.compress:\n np.savez_compressed(args.out_dir/'test.npz', X=X_test, y=y_test)\n else:\n np.savez(args.out_dir/'test.npz', X=X_test, y=y_test)\n" ]
[ [ "numpy.savez_compressed", "numpy.savez" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hdpc2015/BasicSR
[ "e7001551571194e71a15e908c38c3616c8ff0454" ]
[ "codes/models/SRRaGAN_hfen_model.py" ]
[ "import os\nimport logging\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\n\nimport models.networks as networks\nfrom .base_model import BaseModel\nfrom models.modules.loss import GANLoss, GradientPenaltyLoss, HFENL1Loss, HFENL2Loss, TVLoss, CharbonnierLoss, ElasticLoss\nfrom models.modules.ssim2 import SSIM, MS_SSIM\nlogger = logging.getLogger('base')\n\n\nclass SRRaGANModel(BaseModel):\n def __init__(self, opt):\n super(SRRaGANModel, self).__init__(opt)\n train_opt = opt['train']\n\n # define networks and load pretrained models\n self.netG = networks.define_G(opt).to(self.device) # G\n if self.is_train:\n self.netD = networks.define_D(opt).to(self.device) # D\n self.netG.train()\n self.netD.train()\n self.load() # load G and D if needed\n\n # define losses, optimizer and scheduler\n if self.is_train:\n # G pixel loss\n if train_opt['pixel_weight'] > 0:\n l_pix_type = train_opt['pixel_criterion']\n if l_pix_type == 'l1':\n self.cri_pix = nn.L1Loss().to(self.device)\n elif l_pix_type == 'l2':\n self.cri_pix = nn.MSELoss().to(self.device)\n elif l_pix_type == 'cb':\n self.cri_pix = CharbonnierLoss().to(self.device)\n elif l_pix_type == 'elastic':\n self.cri_pix = ElasticLoss().to(self.device)\n else:\n raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_pix_type))\n self.l_pix_w = train_opt['pixel_weight']\n else:\n logger.info('Remove pixel loss.')\n self.cri_pix = None\n\n # G feature loss\n if train_opt['feature_weight'] > 0:\n l_fea_type = train_opt['feature_criterion']\n if l_fea_type == 'l1':\n self.cri_fea = nn.L1Loss().to(self.device)\n elif l_fea_type == 'l2':\n self.cri_fea = nn.MSELoss().to(self.device)\n elif l_fea_type == 'cb':\n self.cri_fea = CharbonnierLoss().to(self.device)\n elif l_fea_type == 'elastic':\n self.cri_fea = ElasticLoss().to(self.device)\n else:\n raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_fea_type))\n self.l_fea_w = train_opt['feature_weight']\n else:\n logger.info('Remove feature loss.')\n self.cri_fea = None\n if self.cri_fea: # load VGG perceptual loss\n self.netF = networks.define_F(opt, use_bn=False).to(self.device)\n \n #HFEN loss\n if train_opt['hfen_weight'] > 0:\n l_hfen_type = train_opt['hfen_criterion']\n if l_hfen_type == 'l1':\n self.cri_hfen = HFENL1Loss().to(self.device) #RelativeHFENL1Loss().to(self.device)\n elif l_hfen_type == 'l2':\n self.cri_hfen = HFENL2Loss().to(self.device)\n elif l_hfen_type == 'rel_l1':\n self.cri_hfen = RelativeHFENL1Loss().to(self.device)\n elif l_hfen_type == 'rel_l2':\n self.cri_hfen = RelativeHFENL2Loss().to(self.device)\n else:\n raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_hfen_type))\n self.l_hfen_w = train_opt['hfen_weight']\n else:\n logger.info('Remove HFEN loss.')\n self.cri_hfen = None\n \n #TV loss\n if train_opt['tv_weight'] > 0:\n self.l_tv_w = train_opt['tv_weight']\n l_tv_type = train_opt['tv_type']\n if l_tv_type == 'normal':\n self.cri_tv = TVLoss(self.l_tv_w).to(self.device) \n elif l_tv_type == '4D':\n self.cri_tv = TVLoss4D(self.l_tv_w).to(self.device) #Total Variation regularization in 4 directions\n else:\n raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_tv_type))\n else:\n logger.info('Remove TV loss.')\n self.cri_tv = None\n \n #SSIM loss\n if train_opt['ssim_weight'] > 0:\n self.l_ssim_w = train_opt['ssim_weight']\n l_ssim_type = train_opt['ssim_type']\n if l_ssim_type == 'ssim':\n self.cri_ssim = SSIM(win_size=11, win_sigma=1.5, size_average=True, data_range=1., channel=3).to(self.device)\n elif l_ssim_type == 'ms-ssim':\n self.cri_ssim = MS_SSIM(win_size=11, win_sigma=1.5, size_average=True, data_range=1., channel=3).to(self.device)\n else:\n logger.info('Remove SSIM loss.')\n self.cri_ssim = None\n\n # GD gan loss\n self.cri_gan = GANLoss(train_opt['gan_type'], 1.0, 0.0).to(self.device)\n self.l_gan_w = train_opt['gan_weight']\n # D_update_ratio and D_init_iters are for WGAN\n self.D_update_ratio = train_opt['D_update_ratio'] if train_opt['D_update_ratio'] else 1\n self.D_init_iters = train_opt['D_init_iters'] if train_opt['D_init_iters'] else 0\n\n if train_opt['gan_type'] == 'wgan-gp':\n self.random_pt = torch.Tensor(1, 1, 1, 1).to(self.device)\n # gradient penalty loss\n self.cri_gp = GradientPenaltyLoss(device=self.device).to(self.device)\n self.l_gp_w = train_opt['gp_weigth']\n\n # optimizers\n # G\n wd_G = train_opt['weight_decay_G'] if train_opt['weight_decay_G'] else 0\n optim_params = []\n for k, v in self.netG.named_parameters(): # can optimize for a part of the model\n if v.requires_grad:\n optim_params.append(v)\n else:\n logger.warning('Params [{:s}] will not optimize.'.format(k))\n self.optimizer_G = torch.optim.Adam(optim_params, lr=train_opt['lr_G'], \\\n weight_decay=wd_G, betas=(train_opt['beta1_G'], 0.999))\n self.optimizers.append(self.optimizer_G)\n # D\n wd_D = train_opt['weight_decay_D'] if train_opt['weight_decay_D'] else 0\n self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=train_opt['lr_D'], \\\n weight_decay=wd_D, betas=(train_opt['beta1_D'], 0.999))\n self.optimizers.append(self.optimizer_D)\n\n # schedulers\n if train_opt['lr_scheme'] == 'MultiStepLR':\n for optimizer in self.optimizers:\n self.schedulers.append(lr_scheduler.MultiStepLR(optimizer, \\\n train_opt['lr_steps'], train_opt['lr_gamma']))\n else:\n raise NotImplementedError('MultiStepLR learning rate scheme is enough.')\n\n self.log_dict = OrderedDict()\n self.print_network()\n\n def feed_data(self, data, need_HR=True):\n # LR\n self.var_L = data['LR'].to(self.device)\n\n if need_HR: # train or val\n self.var_H = data['HR'].to(self.device)\n\n input_ref = data['ref'] if 'ref' in data else data['HR']\n self.var_ref = input_ref.to(self.device)\n\n def optimize_parameters(self, step):\n # G\n for p in self.netD.parameters():\n p.requires_grad = False\n\n self.optimizer_G.zero_grad()\n\n self.fake_H = self.netG(self.var_L)\n\n l_g_total = 0\n if step % self.D_update_ratio == 0 and step > self.D_init_iters:\n if self.cri_pix: # pixel loss\n l_g_pix = self.l_pix_w * self.cri_pix(self.fake_H, self.var_H)\n l_g_total += l_g_pix\n if self.cri_ssim: # structural loss\n l_g_ssim = 1.-(self.l_ssim_w *self.cri_ssim(self.fake_H, self.var_H)) #using ssim2.py\n if torch.isnan(l_g_ssim).any():\n l_g_total = l_g_total\n else:\n l_g_total += l_g_ssim\n if self.cri_fea: # feature loss\n real_fea = self.netF(self.var_H).detach()\n fake_fea = self.netF(self.fake_H)\n l_g_fea = self.l_fea_w * self.cri_fea(fake_fea, real_fea)\n l_g_total += l_g_fea\n if self.cri_hfen: # HFEN loss \n l_g_HFEN = self.l_hfen_w * self.cri_hfen(self.fake_H, self.var_H)\n l_g_total += l_g_HFEN\n if self.cri_tv: #TV loss\n l_g_tv = self.cri_tv(self.fake_H) #note: the weight is already multiplied inside the function, doesn't need to be here\n l_g_total += l_g_tv\n # G gan + cls loss\n pred_g_fake = self.netD(self.fake_H)\n pred_d_real = self.netD(self.var_ref).detach()\n\n l_g_gan = self.l_gan_w * (self.cri_gan(pred_d_real - torch.mean(pred_g_fake), False) +\n self.cri_gan(pred_g_fake - torch.mean(pred_d_real), True)) / 2\n l_g_total += l_g_gan\n\n l_g_total.backward()\n self.optimizer_G.step()\n\n # D\n for p in self.netD.parameters():\n p.requires_grad = True\n\n self.optimizer_D.zero_grad()\n l_d_total = 0\n pred_d_real = self.netD(self.var_ref)\n pred_d_fake = self.netD(self.fake_H.detach()) # detach to avoid BP to G\n l_d_real = self.cri_gan(pred_d_real - torch.mean(pred_d_fake), True)\n l_d_fake = self.cri_gan(pred_d_fake - torch.mean(pred_d_real), False)\n\n l_d_total = (l_d_real + l_d_fake) / 2\n\n if self.opt['train']['gan_type'] == 'wgan-gp':\n batch_size = self.var_ref.size(0)\n if self.random_pt.size(0) != batch_size:\n self.random_pt.resize_(batch_size, 1, 1, 1)\n self.random_pt.uniform_() # Draw random interpolation points\n interp = self.random_pt * self.fake_H.detach() + (1 - self.random_pt) * self.var_ref\n interp.requires_grad = True\n interp_crit = self.netD(interp)\n l_d_gp = self.l_gp_w * self.cri_gp(interp, interp_crit)\n l_d_total += l_d_gp\n\n l_d_total.backward()\n self.optimizer_D.step()\n\n # set log\n if step % self.D_update_ratio == 0 and step > self.D_init_iters:\n # G\n if self.cri_pix:\n self.log_dict['l_g_pix'] = l_g_pix.item()\n if self.cri_fea:\n self.log_dict['l_g_fea'] = l_g_fea.item()\n if self.cri_hfen:\n self.log_dict['l_g_HFEN'] = l_g_HFEN.item()\n if self.cri_tv:\n self.log_dict['l_g_tv'] = l_g_tv.item()\n if self.cri_ssim:\n self.log_dict['l_g_ssim'] = l_g_ssim.item()\n self.log_dict['l_g_gan'] = l_g_gan.item()\n # D\n self.log_dict['l_d_real'] = l_d_real.item()\n self.log_dict['l_d_fake'] = l_d_fake.item()\n\n if self.opt['train']['gan_type'] == 'wgan-gp':\n self.log_dict['l_d_gp'] = l_d_gp.item()\n # D outputs\n self.log_dict['D_real'] = torch.mean(pred_d_real.detach())\n self.log_dict['D_fake'] = torch.mean(pred_d_fake.detach())\n\n def test(self):\n self.netG.eval()\n with torch.no_grad():\n self.fake_H = self.netG(self.var_L)\n self.netG.train()\n\n def get_current_log(self):\n return self.log_dict\n\n def get_current_visuals(self, need_HR=True):\n out_dict = OrderedDict()\n out_dict['LR'] = self.var_L.detach()[0].float().cpu()\n out_dict['SR'] = self.fake_H.detach()[0].float().cpu()\n if need_HR:\n out_dict['HR'] = self.var_H.detach()[0].float().cpu()\n return out_dict\n\n def print_network(self):\n # Generator\n s, n = self.get_network_description(self.netG)\n if isinstance(self.netG, nn.DataParallel):\n net_struc_str = '{} - {}'.format(self.netG.__class__.__name__,\n self.netG.module.__class__.__name__)\n else:\n net_struc_str = '{}'.format(self.netG.__class__.__name__)\n\n logger.info('Network G structure: {}, with parameters: {:,d}'.format(net_struc_str, n))\n logger.info(s)\n if self.is_train:\n # Discriminator\n s, n = self.get_network_description(self.netD)\n if isinstance(self.netD, nn.DataParallel):\n net_struc_str = '{} - {}'.format(self.netD.__class__.__name__,\n self.netD.module.__class__.__name__)\n else:\n net_struc_str = '{}'.format(self.netD.__class__.__name__)\n\n logger.info('Network D structure: {}, with parameters: {:,d}'.format(net_struc_str, n))\n logger.info(s)\n\n if self.cri_fea: # F, Perceptual Network\n s, n = self.get_network_description(self.netF)\n if isinstance(self.netF, nn.DataParallel):\n net_struc_str = '{} - {}'.format(self.netF.__class__.__name__,\n self.netF.module.__class__.__name__)\n else:\n net_struc_str = '{}'.format(self.netF.__class__.__name__)\n\n logger.info('Network F structure: {}, with parameters: {:,d}'.format(net_struc_str, n))\n logger.info(s)\n\n def load(self):\n load_path_G = self.opt['path']['pretrain_model_G']\n if load_path_G is not None:\n logger.info('Loading pretrained model for G [{:s}] ...'.format(load_path_G))\n self.load_network(load_path_G, self.netG)\n load_path_D = self.opt['path']['pretrain_model_D']\n if self.opt['is_train'] and load_path_D is not None:\n logger.info('Loading pretrained model for D [{:s}] ...'.format(load_path_D))\n self.load_network(load_path_D, self.netD)\n\n def save(self, iter_step):\n self.save_network(self.netG, 'G', iter_step)\n self.save_network(self.netD, 'D', iter_step)\n" ]
[ [ "torch.optim.Adam", "torch.mean", "torch.optim.lr_scheduler.MultiStepLR", "torch.nn.MSELoss", "torch.Tensor", "torch.isnan", "torch.no_grad", "torch.nn.L1Loss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jackzipu/heterogeneity-aware-lowering-and-optimization
[ "5e4387b9d415499cf007c67ab4ffc5d2e3e95ac3" ]
[ "utils/halo_pgq.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"\nCopyright (C) 2019-2020 Alibaba Group Holding Limited.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n=============================================================================\n\"\"\"\n\nimport subprocess\nfrom PIL import Image\nimport os\nimport glob\nimport sys\nimport ctypes\nimport numpy as np\nimport shutil\nimport argparse\nimport json\n\nuse_pillow = False\ntry:\n import cv2\nexcept ImportError:\n print(\"OpenCV not found. Run pip3 install scikit-build opencv-python-headless\")\n printf(\"Use Pillow\")\n use_pillow = True\n pass\n\n\ndef verify(proc):\n if verbose:\n print(proc.args)\n if proc.returncode != 0:\n print(proc.args)\n print(proc.stderr)\n exit(proc.returncode)\n\n\ndef compile(model_files, halo_flags, is_prof):\n model_file = model_files[0]\n file_stem = os.path.basename(os.path.splitext(model_file)[0])\n output_dir = '/tmp' if is_prof else os.path.dirname(model_file)\n output_stem = file_stem + ('_prof' if is_prof else '')\n cc_file = os.path.join(output_dir, output_stem + '.c')\n bin_file = os.path.join(output_dir, output_stem + '.bin')\n obj_file = os.path.join(output_dir, output_stem + '.o')\n debug = '-g' if True else '-O2'\n verify(subprocess.run([halo_exe, *model_files, *halo_flags, '-o',\n cc_file]))\n if not is_prof:\n return (cc_file, bin_file)\n verify(subprocess.run(\n ['gcc', cc_file, debug, '-c', '-fPIC', '-o', obj_file, '-I/halo/include']))\n return (obj_file, bin_file)\n\n\ndef link(obj, bin, as_shared):\n exe = obj.split('.o')[0] + '.so'\n flags = '-shared' if as_shared else ''\n verify(subprocess.run(['g++', flags, obj, bin,\n '-lodla_profiler', '-L', halo_lib, '-Wl,-rpath=' + halo_lib, '-o', exe]))\n return exe\n\n\ndef compile_with_halo(model_files, func_name, is_prof, skip_weights_quan, prof_result_file=''):\n halo_flags = []\n needs_relayout = False\n if len(model_files) == 1 and os.path.splitext(model_files[0])[1] == '.pb':\n needs_relayout = True\n halo_flags.append('-target')\n halo_flags.append('cc')\n halo_flags.append('-disable-broadcasting')\n halo_flags.append('-entry-func-name=' + func_name)\n halo_flags.append('-fuse-conv-bias')\n halo_flags.append('-fuse-matmul-bias')\n if needs_relayout:\n halo_flags.append('-remove-input-transpose')\n halo_flags.append('-reorder-data-layout=channel-first')\n if is_prof:\n halo_flags.append('-exec-mode=interpret')\n else:\n if not skip_weights_quan:\n halo_flags.append('-quantize-weights=quint8')\n halo_flags.append('-emit-data-as-c')\n halo_flags.append('-pgq-file=' + prof_result_file)\n\n obj, bin = compile(model_files, halo_flags, is_prof)\n return link(obj, bin, True) if is_prof else (obj, bin)\n\n\ndef run(exe):\n proc = subprocess.run([exe], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n print(proc)\n return proc.stdout\n\n\ndef get_image_ndarray(path, width, height):\n if use_pillow:\n image = Image.open(path)\n image = image.resize((width, height))\n mode = image.mode\n image = np.array(image) # type uint8\n if mode == 'L':\n image = np.expand_dims(image, axis=2)\n image = image.repeat(3, axis=2)\n elif mode == 'RGB':\n pass\n else:\n print('image mode has to be either L or RGB, but got {}'.format(mode))\n else:\n image = cv2.imread(path)\n image = cv2.resize(image, (width, height))\n return image\n\ndef merge_ranges(data, output_id, input_ids):\n data_keys = ['min_value', 'max_value']\n for in_id in input_ids:\n data[output_id]['min_value'] = min(data[output_id]['min_value'],\n data[in_id]['min_value'])\n data[output_id]['max_value'] = max(data[output_id]['max_value'],\n data[in_id]['max_value'])\n for in_id in input_ids:\n data[in_id]['min_value'] = data[output_id]['min_value']\n data[in_id]['max_value'] = data[output_id]['max_value']\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-m', '--model', nargs='+', dest='model', required=True,\n type=open, help='model files')\n parser.add_argument('-i', '--image-dir', required=True,\n type=str, help='image directory')\n parser.add_argument('-s', '--skip-weights-prof',\n dest='skip_weights_prof', action='store_true', default=False,\n help='No profiling for weights')\n parser.add_argument('-width', dest='img_w', type=int, default=112)\n parser.add_argument('-height', dest='img_h', type=int, default=112)\n parser.add_argument('-c', '--chs-prof', dest='chs_prof',\n action='store_true', default=False,\n help='Enable channel-wise profiling')\n parser.add_argument('-a', '--chs-axis', dest='chs_axis', type=int,\n help='axis of channel (e.g.: 1 for NCHW, 3 for NHWC)', default=1)\n parser.add_argument('-q', '--quantize-scheme', dest='q_scheme', required=True,\n choices=['sym', 'asym', 'asym_max_zp_255',\n 'sym_unsigned', 'sym_power2_scale'],\n type=str.lower, help='quantization scheme')\n parser.add_argument('-min-dim-chs-prof', '--min-dim-chs-prof',\n dest='min_dim_chs_prof', type=int, default=0,\n help='minimum dimension of tensors for channel-wise profiling')\n parser.add_argument('-max-dim-chs-prof', '--max-dim-chs-prof',\n dest='max_dim_chs_prof', type=int, default=sys.maxsize,\n help='maximum dimension of tensors for channel-wise profiling')\n parser.add_argument('-norm-ops', '--normalize-range-for-ops', dest='norm_ops', default='',\n help=\"normalize ranges for certain ops. \"\n \"Note that channel-wise info won't be merged. \"\n \"E.g. -norm-ops=concat,maxpool\")\n parser.add_argument('-v', '--verbose', dest='verbose',\n action='store_true', default=False)\n args = parser.parse_args()\n\n model_files = [x.name for x in args.model]\n image_path = args.image_dir\n\n global halo_exe\n global halo_home\n global halo_lib\n global verbose\n\n verbose = args.verbose\n\n # Check halo\n halo_exe = shutil.which('halo')\n if not halo_exe:\n print('halo not found. Please add it to PATH')\n exit(1)\n\n print(\"Quantization Scheme: \" + args.q_scheme)\n print(\"Halo: \" + halo_exe)\n halo_home = os.path.dirname(halo_exe) + '/..'\n halo_lib = halo_home + '/lib'\n\n print(\"\\n##### Compile model (for profiling) #####\")\n model_lib = compile_with_halo(\n model_files, 'model', True, args.skip_weights_prof)\n print(\"Generated \", model_lib)\n\n print(\"\\n##### Start to profile #####\")\n\n files = glob.glob(image_path + '/*.jpg')\n\n if not files:\n print(\"No images found in \" + image_path)\n exit(1)\n else:\n print(str(len(files)) + \" images found\")\n print(files)\n\n c_lib = ctypes.CDLL(model_lib)\n prof_file = os.path.splitext(model_lib)[0] + '.prof'\n prof_file_buf = prof_file.encode('utf-8')\n prof_file_p = ctypes.c_char_p(prof_file_buf)\n c_lib.StartProfiling(prof_file_p)\n if args.chs_prof:\n c_lib.EnableChannelWiseProf()\n c_lib.SetChannelAxis(args.chs_axis) # NCHW\n if args.skip_weights_prof:\n c_lib.SkipWeightsProfiling(1)\n\n ### preprocessing ###\n for i, path in enumerate(files):\n image = get_image_ndarray(path, args.img_w, args.img_h)\n image = image.transpose([2, 0, 1]).flatten() # TO CHW\n image = image.astype(ctypes.c_float)\n # np.savetxt('image_' + str(i) + '.inc', image.flatten(),\n # delimiter=',', newline=',\\n')\n ret0 = (ctypes.c_float * 28224 * 10)()\n ret1 = (ctypes.c_float * 28224 * 2)()\n ret2 = (ctypes.c_float * 28224 * 4)()\n\n print('Profiling {} of {}: {}'.format(i, len(files), path))\n tag = path.encode('utf-8')\n c_lib.StartOneRun(ctypes.c_char_p(tag))\n c_lib.model(ctypes.c_void_p(image.ctypes.data), ret0, ret1, ret2)\n c_lib.StopOneRun()\n # ret = np.array(ret)\n # ind = ret.argsort()[-3:][::-1]\n # print(ind, ret[ind])\n c_lib.StopProfiling()\n\n # Consolidate profiling results\n with open(prof_file, 'r') as f:\n prof_data = json.load(f)\n network_info = prof_data['NetworkInfo']\n prof_data = prof_data['ProfilingResults']\n consolidated = {}\n for run, run_data in prof_data.items():\n for layer_name, prof_vals in run_data.items():\n # Validate\n chs = prof_vals['channels']\n if chs != len(prof_vals['channels_max']) or chs != len(prof_vals['channels_min']):\n print(\"Skip invalid record\")\n continue\n\n if not layer_name in consolidated:\n consolidated[layer_name] = prof_vals\n else:\n v = consolidated[layer_name]['min_value']\n consolidated[layer_name]['min_value'] = min(\n v, prof_vals['min_value'])\n v = consolidated[layer_name]['max_value']\n consolidated[layer_name]['max_value'] = max(\n v, prof_vals['max_value'])\n op_type = prof_vals['op_type']\n if consolidated[layer_name]['channels'] != chs or \\\n consolidated[layer_name]['op_type'] != op_type:\n print(\"Skip invalid record\")\n continue\n v = consolidated[layer_name]['channels_min']\n consolidated[layer_name]['channels_min'] = min(\n v, prof_vals['channels_min'])\n v = consolidated[layer_name]['channels_max']\n consolidated[layer_name]['channels_max'] = max(\n v, prof_vals['channels_max'])\n norm_ops = args.norm_ops.upper().split(',')\n norm_ops = { x if x.startswith('ODLA_') else 'ODLA_' + x for x in norm_ops}\n for name, data in consolidated.items():\n if data[\"op_type\"].upper() in norm_ops:\n merge_ranges(consolidated, name, network_info[name]['inputs'])\n\n\n # Compute scale and zp based on 8-bit quant rule\n for data in consolidated.values():\n valid_range = 255\n scale = (data['max_value'] - data['min_value']) / valid_range\n zp = 0\n if args.q_scheme == 'asym_max_zp_255':\n if scale == 0:\n scale = abs(data['max_value'])\n if scale == 0:\n scale = 1\n zp = min(255, max(0, round(0 - data['min_value'] / scale)))\n elif args.q_scheme == 'asym':\n zp = round(-((data['min_value'] / scale)) if scale != 0 else 0)\n else:\n print(\"Unsupported quantization scheme\")\n exit(1)\n data['scale'] = scale\n data['zp'] = round(zp)\n\n output_file = os.path.splitext(model_lib)[0] + '.json'\n\n # Output json\n with open(output_file, 'w') as fp:\n json.dump(consolidated, fp)\n print('Consolidated JSON file:{}'.format(output_file))\n\n # Output C code, assumes quant\n output_file = os.path.splitext(model_lib)[0] + '.c'\n nr_recs = 0\n with open(output_file, 'w') as cf:\n cf.write('#include <ODLA/ops/odla_ops_quantization.h>\\n')\n cf.write('const odla_value_quant_info quant_infos[] = {\\n')\n fmt = ' {{.value_id = (const odla_value_id) \"{}\", .ch_idx = {}, .scale = {}, .offset = {}, .min = {}, .max = {}}},\\n'\n for name, data in consolidated.items():\n chs = data['channels']\n shape = data['shape']\n dims = len(shape)\n if dims < args.min_dim_chs_prof or dims > args.max_dim_chs_prof:\n chs = 1\n cf.write(fmt.format(name, -chs,\n data['scale'], data['zp'], data['min_value'], data['max_value']))\n nr_recs += 1\n if chs == 1:\n continue\n for ch in range(0, chs):\n cf.write(fmt.format(\n name, ch, 0, 0, data['channels_min'][ch], data['channels_max'][ch]))\n nr_recs += 1\n cf.write('};\\n')\n cf.write('const int quant_infos_size = {};\\n'.format(\n nr_recs))\n\n print('ODLA Quantization info file:{}'.format(output_file))\n\n # Output csv\n output_file = os.path.splitext(model_lib)[0] + '.csv'\n with open(output_file, 'w') as fp:\n for name, data in consolidated.items():\n fp.write('{},{},{},{},{}\\n'.format(\n name, data['min_value'], data['max_value'], data['scale'], data['zp']))\n print('Quantization csv file:{}'.format(output_file))\n\n # Final compile\n print(\"\\n##### Compile model (with profiled info) #####\")\n final_cc, final_bin = compile_with_halo(\n model_files, 'model', False, args.skip_weights_prof, output_file)\n print('Final outputs: {}, {}'.format(final_cc, final_bin))\n" ]
[ [ "numpy.array", "numpy.expand_dims" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RadeenXALNW/Pytorch-DeepLabV3-Underwater-Image
[ "024535d7a847ac43922a88dde4cf6b5b6437fe66" ]
[ "utils/dataloader.py" ]
[ "\n\"\"\"\nRGB color code and object categories:\n------------------------------------\n000 BW: Background waterbody\n001 HD: Human divers\n010 PF: Plants/sea-grass\n011 WR: Wrecks/ruins\n100 RO: Robots/instruments\n101 RI: Reefs and invertebrates\n110 FV: Fish and vertebrates\n111 SR: Sand/sea-floor (& rocks)\n\"\"\"\n\nfrom __future__ import print_function,division\nimport os\nfrom os.path import join, exists\nfrom torch.utils.data import DataLoader,Dataset\nimport torch\nimport torchvision\nfrom torchvision import datasets,models,transforms\nimport itertools \n\ndef robotfishhumanreefwrecks(mask):\n human=torch.zeros((imw,imh))\n fish=torch.zeros((imw,imh))\n robot=torch.zeros((imw,imh))\n reef=torch.zeros((imw,imh))\n wrecks=torch.zeros((imw,imh))\n for i in range(imw):\n for j in range(imh):\n if (mask[i,j,0]==0 and mask[i,j,1]==0 and mask[i,j,2]==1):\n Human[i, j] = 1 \n elif (mask[i,j,0]==1 and mask[i,j,1]==1 and mask[i,j,2]==0):\n fish[i, j] = 1 \n elif (mask[i,j,0]==1 and mask[i,j,1]==0 and mask[i,j,2]==0):\n robot[i, j] = 1 \n elif (mask[i,j,0]==1 and mask[i,j,1]==0 and mask[i,j,2]==1):\n reef[i, j] = 1 \n elif (mask[i,j,0]==0 and mask[i,j,1]==1 and mask[i,j,2]==1):\n wreck[i, j] = 1 \n else:\n pass\n\n return torch.stack((robot,fish,human,reef,wreck),-1)\n\ndef getSaliency(mask):\n imgw,imgh=mask.shape[0],mask.shape[1]\n sal=torch.zeros((imgw,imgh))\n for i in range(imgw):\n for j in range(imgh):\n if (mask[i,j,0]==0 and mask[i,j,1]==0 and mask[i,j,2]==1):\n sal[i,j]=1\n elif (mask[i,j,0]==1 and mask[i,j,1]==0 and mask[i,j,2]==0):\n sal[i, j] = 1 \n elif (mask[i,j,0]==1 and mask[i,j,1]==1 and mask[i,j,2]==0):\n sal[i, j] = 1 \n elif (mask[i,j,0]==0 and mask[i,j,1]==1 and mask[i,j,2]==1):\n sal[i, j] = 0.8 \n else: pass \n \n \n return sal.unsqueeze(1)\n \n \n\ndef processData(image,mask,sal=False):\n # scaling image data and masks\n image = image / 255\n mask = mask /255\n mask[mask > 0.5] = 1\n mask[mask <= 0.5] = 0\n m = []\n for i in range(mask.shape[0]):\n if sal:\n m.append(getSaliency(mask[i]))\n else:\n m.append(robotfishhumanreefwrecks(mask[i]))\n \n m=torch.tensor(m)\n return (img,m)\n\n# def load_training(batch_size,train_path,image_folder,mask_folder,aug_dict, target_size=(256,256), sal=False):\n \n# transform = transforms.Compose(\n# [transforms.RandomHorizontalFlip(),\n# transforms.ToTensor()])\n# data=datasets.ImageFolder(**aug_dict,transform=transform)\n \n# image_generator=torch.utils.data.DataLoader(data,train_path,prefix='image',batch_size=batch_size,target_size=target_size)\n# mask_generator=torch.utils.data.DataLoader(data,train_path,prefix='mask',batch_size=batch_size,target_size=target_size)\n \n# for (img, mask) in it.izip(image_generator, mask_generator):\n# img, mask_indiv = processSUIMDataRFHW(img, mask, sal)\n# yield (img, mask_indiv)\n\nclass SUIMData(Dataset):\n def __init__(self,images_filenames,images_directory,marks_directory,transform=None):\n self.images_filenames=images_filenames\n self.images_directory=images_directory\n self.masks_directory=masks_directory\n self.transform=transform\n def __len__(self):\n return len(self.images_filenames)\n \n def __getitem(self,idx):\n image_filename=self.images_filenames[idx]\n image=cv2.imread(os.path.join(self.images_directory,image_filename))\n image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\n mask=cv2.imread(os.path.join(self.masks_directory,image_filename))\n \n image=processData(image)\n mask=processData(mask)\n if self.transform is not None:\n transformed = self.transform(image=image, mask=mask)\n image = transformed[\"image\"]\n mask = transformed[\"mask\"]\n return image, mask\n\ndef load_training(batch_size,image_folder,mask_folder, sal=False):\n scale=Rescale(256)\n transform = transforms.Compose(\n# [transforms.RandomHorizontalFlip(),\n [Rescale(256),\n transforms.ToTensor()])\n image_data=torchvision.datasets.ImageFolder(root=image_folder,transform=transform)\n mask_data=torchvision.datasets.ImageFolder(root=mask_folder,transform=transform)\n\n image_generator=DataLoader(image_data,batch_size=batch_size,shuffle=True,num_workers=4)\n mask_generator=DataLoader(mask_data,batch_size=batch_size,shuffle=True,num_workers=4)\n for (img,mask) in zip(image_generator,mask_generator):\n img,mask_indiv=processData(img,mask,sal)\n print(img.shape,mask_indiv.shape)\n \ndef getPaths(data_dir):\n # read image files from directory\n exts = ['*.png','*.PNG','*.jpg','*.JPG', '*.JPEG', '*.bmp']\n image_paths = []\n for pattern in exts:\n for d, s, fList in os.walk(data_dir):\n for filename in fList:\n if (fnmatch.fnmatch(filename, pattern)):\n fname_ = os.path.join(d,filename)\n image_paths.append(fname_)\n return image_paths\n" ]
[ [ "torch.stack", "torch.tensor", "torch.utils.data.DataLoader", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AdvaitGadhikar/federated-1
[ "be2aa1d296b61e93be2cb5b7365866fd652b5a9c" ]
[ "differential_privacy/stackoverflow/run_federated.py" ]
[ "# Copyright 2019, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Trains and evaluates Stackoverflow NWP model using TFF.\"\"\"\n\nimport functools\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom optimization.shared import keras_metrics\nfrom optimization.shared import optimizer_utils\nfrom utils import training_loop\nfrom utils import training_utils\nfrom utils import utils_impl\nfrom utils.datasets import stackoverflow_word_prediction\nfrom utils.models import stackoverflow_models\n\nwith utils_impl.record_new_flags():\n # Training hyperparameters\n flags.DEFINE_integer('clients_per_round', 10,\n 'How many clients to sample per round.')\n flags.DEFINE_integer('client_epochs_per_round', 1,\n 'Number of epochs in the client to take per round.')\n flags.DEFINE_integer('client_batch_size', 8, 'Batch size used on the client.')\n flags.DEFINE_integer('sequence_length', 20, 'Max sequence length to use.')\n flags.DEFINE_integer('max_elements_per_user', 1000, 'Max number of training '\n 'sentences to use per user.')\n flags.DEFINE_integer('num_validation_examples', 10000, 'Number of examples '\n 'to use from test set for per-round validation.')\n flags.DEFINE_boolean('uniform_weighting', False,\n 'Whether to weigh clients uniformly. If false, clients '\n 'are weighted by the number of tokens.')\n\n # Optimizer configuration (this defines one or more flags per optimizer).\n utils_impl.define_optimizer_flags('server')\n utils_impl.define_optimizer_flags('client')\n\n # Modeling flags\n flags.DEFINE_integer('vocab_size', 10000, 'Size of vocab to use.')\n flags.DEFINE_integer('embedding_size', 96,\n 'Dimension of word embedding to use.')\n flags.DEFINE_integer('latent_size', 670,\n 'Dimension of latent size to use in recurrent cell')\n flags.DEFINE_integer('num_layers', 1,\n 'Number of stacked recurrent layers to use.')\n flags.DEFINE_boolean(\n 'shared_embedding', False,\n 'Boolean indicating whether to tie input and output embeddings.')\n\n # Differential privacy flags\n flags.DEFINE_float('clip', 0.05, 'Initial clip.')\n flags.DEFINE_float('noise_multiplier', None,\n 'Noise multiplier. If None, no DP is used.')\n flags.DEFINE_float('adaptive_clip_learning_rate', 0,\n 'Adaptive clip learning rate.')\n flags.DEFINE_float('target_unclipped_quantile', 0.5,\n 'Target unclipped quantile.')\n flags.DEFINE_float(\n 'clipped_count_budget_allocation', 0.1,\n 'Fraction of privacy budget to allocate for clipped counts.')\n\nwith utils_impl.record_new_flags() as training_loop_flags:\n flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.')\n flags.DEFINE_string(\n 'experiment_name', None, 'The name of this experiment. Will be append to '\n '--root_output_dir to separate experiment results.')\n flags.DEFINE_string('root_output_dir', '/tmp/differential_privacy/',\n 'Root directory for writing experiment output.')\n flags.DEFINE_integer(\n 'rounds_per_eval', 1,\n 'How often to evaluate the global model on the validation dataset.')\n flags.DEFINE_integer('rounds_per_checkpoint', 50,\n 'How often to checkpoint the global model.')\n flags.DEFINE_integer(\n 'rounds_per_profile', 0,\n '(Experimental) How often to run the experimental TF profiler, if >0.')\n\nFLAGS = flags.FLAGS\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Expected no command-line arguments, '\n 'got: {}'.format(argv))\n tff.backends.native.set_local_execution_context(max_fanout=10)\n\n model_builder = functools.partial(\n stackoverflow_models.create_recurrent_model,\n vocab_size=FLAGS.vocab_size,\n embedding_size=FLAGS.embedding_size,\n latent_size=FLAGS.latent_size,\n num_layers=FLAGS.num_layers,\n shared_embedding=FLAGS.shared_embedding)\n\n loss_builder = functools.partial(\n tf.keras.losses.SparseCategoricalCrossentropy, from_logits=True)\n\n special_tokens = stackoverflow_word_prediction.get_special_tokens(\n FLAGS.vocab_size)\n pad_token = special_tokens.pad\n oov_tokens = special_tokens.oov\n eos_token = special_tokens.eos\n\n def metrics_builder():\n return [\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_with_oov', masked_tokens=[pad_token]),\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_no_oov', masked_tokens=[pad_token] + oov_tokens),\n # Notice BOS never appears in ground truth.\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_no_oov_or_eos',\n masked_tokens=[pad_token, eos_token] + oov_tokens),\n keras_metrics.NumBatchesCounter(),\n keras_metrics.NumTokensCounter(masked_tokens=[pad_token]),\n ]\n\n train_dataset, _ = stackoverflow_word_prediction.get_federated_datasets(\n vocab_size=FLAGS.vocab_size,\n train_client_batch_size=FLAGS.client_batch_size,\n train_client_epochs_per_round=FLAGS.client_epochs_per_round,\n max_sequence_length=FLAGS.sequence_length,\n max_elements_per_train_client=FLAGS.max_elements_per_user)\n _, validation_dataset, test_dataset = stackoverflow_word_prediction.get_centralized_datasets(\n vocab_size=FLAGS.vocab_size,\n max_sequence_length=FLAGS.sequence_length,\n num_validation_examples=FLAGS.num_validation_examples)\n\n if FLAGS.uniform_weighting:\n def client_weight_fn(local_outputs):\n del local_outputs\n return 1.0\n else:\n def client_weight_fn(local_outputs):\n return tf.cast(tf.squeeze(local_outputs['num_tokens']), tf.float32)\n\n def model_fn():\n return tff.learning.from_keras_model(\n model_builder(),\n loss_builder(),\n input_spec=validation_dataset.element_spec,\n metrics=metrics_builder())\n\n if FLAGS.noise_multiplier is not None:\n if not FLAGS.uniform_weighting:\n raise ValueError(\n 'Differential privacy is only implemented for uniform weighting.')\n\n dp_query = tff.utils.build_dp_query(\n clip=FLAGS.clip,\n noise_multiplier=FLAGS.noise_multiplier,\n expected_total_weight=FLAGS.clients_per_round,\n adaptive_clip_learning_rate=FLAGS.adaptive_clip_learning_rate,\n target_unclipped_quantile=FLAGS.target_unclipped_quantile,\n clipped_count_budget_allocation=FLAGS.clipped_count_budget_allocation,\n expected_clients_per_round=FLAGS.clients_per_round)\n\n weights_type = tff.learning.framework.weights_type_from_model(model_fn)\n aggregation_process = tff.utils.build_dp_aggregate_process(\n weights_type.trainable, dp_query)\n else:\n aggregation_process = None\n\n server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server')\n client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client')\n\n iterative_process = tff.learning.build_federated_averaging_process(\n model_fn=model_fn,\n server_optimizer_fn=server_optimizer_fn,\n client_weight_fn=client_weight_fn,\n client_optimizer_fn=client_optimizer_fn,\n aggregation_process=aggregation_process)\n\n client_datasets_fn = training_utils.build_client_datasets_fn(\n train_dataset, FLAGS.clients_per_round)\n\n evaluate_fn = training_utils.build_centralized_evaluate_fn(\n model_builder=model_builder,\n eval_dataset=validation_dataset,\n loss_builder=loss_builder,\n metrics_builder=metrics_builder)\n\n test_fn = training_utils.build_centralized_evaluate_fn(\n model_builder=model_builder,\n # Use both val and test for symmetry with other experiments, which\n # evaluate on the entire test set.\n eval_dataset=validation_dataset.concatenate(test_dataset),\n loss_builder=loss_builder,\n metrics_builder=metrics_builder)\n\n logging.info('Training model:')\n logging.info(model_builder().summary())\n\n hparam_dict = utils_impl.lookup_flag_values(utils_impl.get_hparam_flags())\n training_loop_dict = utils_impl.lookup_flag_values(training_loop_flags)\n\n training_loop.run(\n iterative_process=iterative_process,\n client_datasets_fn=client_datasets_fn,\n validation_fn=evaluate_fn,\n test_fn=test_fn,\n hparam_dict=hparam_dict,\n **training_loop_dict)\n\n\nif __name__ == '__main__':\n app.run(main)\n" ]
[ [ "tensorflow.squeeze" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
tamnguyenvan/AnchorUDF
[ "e08705e5b7350367df3868432ddb9a3a32628f5a" ]
[ "apps/train_hd.py" ]
[ "import sys\nimport os\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nimport time\nimport json\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom lib.options import BaseOptions\nfrom lib.train_util import *\nfrom lib.data import *\nfrom lib.model import *\n\n# get options\nopt = BaseOptions().parse()\n\ndef train(opt):\n # set cuda\n cuda = torch.device('cuda:%d' % opt.gpu_id)\n\n train_dataset = TrainDatasetDF3DHD(opt, phase='train')\n test_dataset = TrainDatasetDF3DHD(opt, phase='test')\n\n projection_mode = train_dataset.projection_mode\n\n # create data loader\n train_data_loader = DataLoader(train_dataset,\n batch_size=opt.batch_size, shuffle=not opt.serial_batches,\n num_workers=opt.num_threads, pin_memory=opt.pin_memory)\n\n print('train data size: ', len(train_data_loader))\n\n # NOTE: batch size should be 1 and use all the points for evaluation\n test_data_loader = DataLoader(test_dataset,\n batch_size=1, shuffle=False,\n num_workers=opt.num_threads, pin_memory=opt.pin_memory)\n print('test data size: ', len(test_data_loader))\n\n # create net\n if opt.anchor:\n if opt.backbone_detach:\n netG = AnchorUdfDetachNet(opt, projection_mode).to(device=cuda)\n else:\n netG = AnchorUdfNet(opt, projection_mode).to(device=cuda)\n else:\n netG = UdfNet(opt, projection_mode).to(device=cuda)\n\n if opt.backbone_detach:\n netMR = AnchorUdfMRDetachNet(opt, netG, projection_mode).to(device=cuda)\n else:\n netMR = AnchorUdfMRNet(opt, netG, projection_mode).to(device=cuda)\n\n if opt.joint_train and not opt.grad_constraint:\n base_param_ids = set(map(id, netMR.netG.parameters()))\n new_params = [p for p in netMR.parameters() if\n id(p) not in base_param_ids]\n params = [\n {'params': netMR.netG.parameters(), 'lr': opt.learning_rate*0.1},\n {'params': new_params}]\n\n optimizerMR = torch.optim.RMSprop(params, lr=opt.learning_rate, momentum=0, weight_decay=0)\n else:\n optimizerMR = torch.optim.RMSprop(netMR.parameters(), lr=opt.learning_rate, momentum=0, weight_decay=0)\n\n lr = opt.learning_rate\n print('Using Network: ', netG.name)\n print('Using Network_HD: ', netMR.name)\n \n def set_train():\n netMR.train()\n netMR.netG.image_filter.eval()\n\n if opt.backbone_detach:\n netMR.image_filter.eval()\n netMR.netG.svr_net.eval()\n\n if not opt.joint_train:\n netMR.netG.eval()\n\n def set_eval():\n netMR.eval()\n\n # load checkpoints\n if opt.load_netG_checkpoint_path is not None:\n print('loading for net G ...', opt.load_netG_checkpoint_path)\n netG.load_state_dict(torch.load(opt.load_netG_checkpoint_path, map_location=cuda))\n\n if opt.continue_train:\n if opt.resume_epoch < 0:\n model_path = '%s/%s/netMR_latest' % (opt.checkpoints_path, opt.name)\n else:\n model_path = '%s/%s/netMR_epoch_%d' % (opt.checkpoints_path, opt.name, opt.resume_epoch)\n print('Resuming from ', model_path)\n netMR.load_state_dict(torch.load(model_path, map_location=cuda))\n\n os.makedirs(opt.checkpoints_path, exist_ok=True)\n os.makedirs(opt.results_path, exist_ok=True)\n os.makedirs('%s/%s' % (opt.checkpoints_path, opt.name), exist_ok=True)\n os.makedirs('%s/%s' % (opt.results_path, opt.name), exist_ok=True)\n\n opt_log = os.path.join(opt.results_path, opt.name, 'opt.txt')\n with open(opt_log, 'w') as outfile:\n outfile.write(json.dumps(vars(opt), indent=2))\n\n loss_log = os.path.join(opt.checkpoints_path, opt.name, 'loss_log.txt')\n\n # training\n start_epoch = 0 if not opt.continue_train else max(opt.resume_epoch,0)\n for epoch in range(start_epoch, opt.num_epoch):\n epoch_start_time = time.time()\n mean_error_rec = 0\n mean_error_anchor_netG = 0\n mean_error_rec_netG = 0\n mean_error_direct = 0\n\n set_train()\n iter_data_time = time.time()\n\n for train_idx, train_data in enumerate(train_data_loader):\n iter_start_time = time.time()\n\n # retrieve the data\n image_tensor = train_data['img'].to(device=cuda)\n image_low_tensor = train_data['img_low'].to(device=cuda)\n calib_tensor = train_data['calib'].to(device=cuda)\n sample_tensor = train_data['samples'].to(device=cuda)\n\n image_low_tensor, _ = reshape_multiview_tensors(image_low_tensor, calib_tensor)\n image_tensor, calib_tensor = reshape_multiview_tensors(image_tensor, calib_tensor)\n\n if opt.num_views > 1:\n sample_tensor = reshape_sample_tensor(sample_tensor, opt.num_views)\n\n label_tensor = train_data['labels'].to(device=cuda)\n\n if opt.joint_train:\n if opt.anchor:\n kp_tensor = train_data['key_points'].to(device=cuda)\n\n if opt.grad_constraint:\n neigh_tensor = train_data['neighbors'].to(device=cuda)\n\n res, error_rec, error_direct = netMR.forward(image_tensor, image_low_tensor, sample_tensor, calib_tensor, labels=label_tensor, key_points=kp_tensor, neighbors=neigh_tensor)\n error = 0.5 * (error_rec + error_direct * 0.02)\n mean_error_rec += (error_rec.data.item() / len(train_data_loader))\n mean_error_direct += (error_direct.data.item() / len(train_data_loader))\n\n else:\n res, error_rec, error_rec_netG, error_anchor_netG = netMR.forward(image_tensor, image_low_tensor, sample_tensor, calib_tensor, labels=label_tensor, key_points=kp_tensor)\n error = error_rec * 0.5 + (error_rec_netG + error_anchor_netG) * 0.5\n mean_error_rec += (error_rec.data.item() / len(train_data_loader))\n mean_error_rec_netG += (error_rec_netG.data.item() / len(train_data_loader))\n mean_error_anchor_netG += (error_anchor_netG.data.item() / len(train_data_loader))\n else:\n res, error, _ = netMR.forward(image_tensor, image_low_tensor, sample_tensor, calib_tensor, labels=label_tensor)\n mean_error_rec += (error.data.item() / len(train_data_loader))\n else:\n res, error = netMR.forward(image_tensor, image_low_tensor, sample_tensor, calib_tensor, labels=label_tensor)\n mean_error_rec += (error.data.item() / len(train_data_loader))\n\n optimizerMR.zero_grad()\n error.backward()\n optimizerMR.step()\n\n iter_net_time = time.time()\n eta = ((iter_net_time - epoch_start_time) / (train_idx + 1)) * len(train_data_loader) - (\n iter_net_time - epoch_start_time)\n\n if train_idx % opt.freq_plot == 0:\n if opt.joint_train and opt.anchor:\n if opt.grad_constraint:\n message = 'Name: {0} | Epoch: {1} | {2}/{3} | ErrREC: {4:.06f} | ErrDIR: {5:.06f} | LR: {6:.06f} | Sigma: {7:.04f} | dataT: {8:.05f} | netT: {9:.05f} | ETA: {10:02d}:{11:02d}'.format(\n opt.name, epoch, train_idx, len(train_data_loader), error_rec.item(), error_direct.item(), lr, opt.sigma[-1],\n iter_start_time - iter_data_time,\n iter_net_time - iter_start_time, int(eta // 60),\n int(eta - 60 * (eta // 60)))\n else:\n message = 'Name: {0} | Epoch: {1} | {2}/{3} | ErrREC: {4:.06f} | ErrRECG: {5:.06f} | ErrPCG: {6:.06f} | LR: {7:.06f} | Sigma: {8:.04f} | dataT: {9:.05f} | netT: {10:.05f} | ETA: {11:02d}:{12:02d}'.format(\n opt.name, epoch, train_idx, len(train_data_loader), error_rec.item(), error_rec_netG.item(), error_anchor_netG.item(), lr, opt.sigma[-1],\n iter_start_time - iter_data_time,\n iter_net_time - iter_start_time, int(eta // 60),\n int(eta - 60 * (eta // 60)))\n else:\n message = 'Name: {0} | Epoch: {1} | {2}/{3} | Err: {4:.06f} | LR: {5:.06f} | Sigma: {6:.04f} | dataT: {7:.05f} | netT: {8:.05f} | ETA: {9:02d}:{10:02d}'.format(\n opt.name, epoch, train_idx, len(train_data_loader), error.item(), lr, opt.sigma[-1],\n iter_start_time - iter_data_time,\n iter_net_time - iter_start_time, int(eta // 60),\n int(eta - 60 * (eta // 60)))\n\n print(message)\n with open(loss_log, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n if train_idx % opt.freq_save == 0 and train_idx != 0:\n torch.save(netMR.state_dict(), '%s/%s/netMR_latest' % (opt.checkpoints_path, opt.name))\n torch.save(netMR.state_dict(), '%s/%s/netMR_epoch_%d' % (opt.checkpoints_path, opt.name, epoch))\n\n iter_data_time = time.time()\n\n torch.save(netMR.state_dict(), '%s/%s/netMR_epoch_%d' % (opt.checkpoints_path, opt.name, epoch))\n\n # update learning rate\n lr = adjust_learning_rate(optimizerMR, epoch, lr, opt.schedule, opt.gamma)\n\n message = 'mean train L1Loss: {0:06f} L1LossG: {1:06f} ChamLossG: {2:06f} DirectLoss: {3:06f}'.format(mean_error_rec, mean_error_rec_netG, mean_error_pc_netG, mean_error_direct)\n print(message)\n with open(loss_log, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n #### test\n set_eval()\n\n if not opt.no_num_eval:\n test_losses = {}\n print('calc error (test) ...')\n if opt.anchor:\n test_errors = calc_error_anchor(opt, netG, cuda, test_dataset, 100)\n if opt.grad_constraint:\n message = 'eval test L1Loss: {0:06f} ChamLoss: {1:06f} DirectLoss: {2:06f} GradLoss: {3:06f}'.format(*test_errors)\n L1Loss, ChamLoss, DirectLoss, GradLoss = test_errors\n test_losses['L1Loss(test)'] = L1Loss\n test_losses['ChamLoss(test)'] = ChamLoss\n test_losses['DirectLoss(test)'] = DirectLoss\n test_losses['GradLoss(test)'] = GradLoss\n else:\n message = 'eval test L1Loss: {0:06f} ChamLoss: {1:06f}'.format(*test_errors)\n L1Loss, ChamLoss = test_errors\n test_losses['L1Loss(test)'] = L1Loss\n test_losses['ChamLoss(test)'] = ChamLoss\n else:\n test_errors = calc_error_udf(opt, netG, cuda, test_dataset, 100)\n message = 'eval test L1Loss: {0:06f}'.format(test_errors)\n L1Loss = test_errors\n test_losses['L1Loss(test)'] = L1Loss\n\n print(message)\n with open(loss_log, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n print('calc error (train) ...')\n if opt.anchor_pc:\n train_dataset.is_train = False\n train_errors = calc_error_anchor(opt, netG, cuda, train_dataset, 100)\n train_dataset.is_train = True\n if opt.grad_constraint:\n message = 'eval train L1Loss: {0:06f} ChamLoss: {1:06f} DirectLoss: {2:06f} GradLoss: {3:06f}'.format(*train_errors)\n L1Loss, ChamLoss, DirectLoss, GradLoss = train_errors\n test_losses['L1Loss(train)'] = L1Loss\n test_losses['ChamLoss(train)'] = ChamLoss\n test_losses['DirectLoss(train)'] = DirectLoss\n test_losses['GradLoss(train)'] = GradLoss\n else:\n message = 'eval train L1Loss: {0:06f} ChamLoss: {1:06f}'.format(*train_errors)\n L1Loss, ChamLoss = train_errors\n test_losses['L1Loss(train)'] = L1Loss\n test_losses['ChamLoss(train)'] = ChamLoss\n else:\n train_dataset.is_train = False\n train_errors = calc_error_udf(opt, netG, cuda, train_dataset, 100)\n train_dataset.is_train = True\n message = 'eval train L1Loss: {0:06f}'.format(train_errors)\n L1Loss = train_errors\n test_losses['L1Loss(train)'] = L1Loss\n\n print(message)\n with open(loss_log, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n\nif __name__ == '__main__':\n train(opt)" ]
[ [ "torch.device", "torch.optim.RMSprop", "torch.utils.data.DataLoader", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fedingo/gym-unblockme
[ "a4dd20a7608122e09862d681259111e2634f3d4b" ]
[ "gym_unblockme/envs/unblockme_render.py" ]
[ "import pygame\nimport time\nimport numpy as np\nimport sys\n\ngray = (150, 150, 150)\nwhite = (255, 255, 255)\nblack = (0, 0, 0, )\nred_block = (255, 0, 0)\nred_border = (76, 0, 19)\nblock_color = (255, 128, 0)\nborder_color = (165,42,42)\n\nscreen = None\nSIDE = 50\nBORDER = 5\nMARGIN = 5\nLINE = 1\n\nh_switch = True\ndef __draw_horizontal_block(x,y):\n\n global screen, h_switch\n pygame.draw.rect(screen, border_color, pygame.Rect(MARGIN + y*SIDE,MARGIN + x*SIDE, SIDE, SIDE))\n pygame.draw.rect(screen, block_color, pygame.Rect(MARGIN + y*SIDE + h_switch*BORDER, MARGIN + x*SIDE + BORDER,\n SIDE - BORDER, SIDE - 2*BORDER))\n h_switch = not h_switch\n\ndef __draw_red_block(x,y):\n\n global screen, h_switch\n pygame.draw.rect(screen, red_border, pygame.Rect(MARGIN + y*SIDE,MARGIN + x*SIDE, SIDE, SIDE))\n pygame.draw.rect(screen, red_block, pygame.Rect(MARGIN + y*SIDE + h_switch*BORDER, MARGIN + x*SIDE + BORDER,\n SIDE - BORDER, SIDE - 2*BORDER))\n h_switch = not h_switch\n\ndef __draw_vertical_block(x,y):\n\n global screen\n pygame.draw.rect(screen, border_color, pygame.Rect(MARGIN + y*SIDE, MARGIN + x*SIDE, SIDE, 2*SIDE))\n pygame.draw.rect(screen, block_color, pygame.Rect(MARGIN + y*SIDE + BORDER, MARGIN + x*SIDE + BORDER,\n SIDE - 2*BORDER, 2*SIDE - 2*BORDER))\n\n## Render function for the unblockme_class\ndef render_unblockme(game_object):\n\n matrix = game_object.internal_state\n k, h, _ = game_object.shape\n\n global screen \n if screen is None:\n pygame.init()\n screen = pygame.display.set_mode((2*MARGIN+k*SIDE, 2*MARGIN+h*SIDE))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.display.quit()\n pygame.quit()\n sys.exit(0)\n\n screen.fill(black)\n\n # first we draw the background\n for x in range(0,k):\n for y in range(0,h):\n cell = matrix[x,y,:]\n selected_block = np.where(cell == 1)[0]\n if len(selected_block) != 0:\n #draw the exit on the outer border\n if selected_block[0] == 0:\n if y == 0:\n pygame.draw.rect(screen, white, pygame.Rect(y*SIDE,x*SIDE+MARGIN, SIDE+MARGIN, SIDE))\n else:\n pygame.draw.rect(screen, white, pygame.Rect(y*SIDE+MARGIN,x*SIDE+MARGIN, SIDE+MARGIN, SIDE))\n # Draw the background with the grid pattern\n pygame.draw.rect(screen, gray , pygame.Rect(MARGIN + y*SIDE,MARGIN + x*SIDE, SIDE, SIDE))\n pygame.draw.rect(screen, white, pygame.Rect(MARGIN + y*SIDE + LINE,MARGIN + x*SIDE + LINE,\n SIDE - 2*LINE, SIDE - 2*LINE))\n \n # then we draw the blocks in the grid\n for x in range(0,k):\n for y in range(0,h):\n cell = matrix[x,y,1:]\n selected_block = np.where(cell == 1)[0] \n if len(selected_block) != 0: \n if selected_block[-1] == 1:\n __draw_horizontal_block(x,y)\n elif selected_block[-1] == 2:\n if (x == 0 or not (matrix[x-1,y,1:] == cell).all() ) and \\\n (x != k-1 and (matrix[x+1,y,1:] == cell).all() ):\n __draw_vertical_block(x,y)\n elif selected_block[-1] == 0:\n __draw_red_block(x,y)\n\n pygame.display.update()\n time.sleep(0.1)\n\nif __name__ == \"__main__\":\n from unblockme_class import *\n matrix, goal = get_example()\n game = unblock_me(matrix, goal)\n render_unblockme(game)" ]
[ [ "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Nancy823/PGL
[ "fc517bbb87c570d0b854507769078c479d613914" ]
[ "ogb_examples/graphproppred/mol/monitor/train_monitor.py" ]
[ "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tqdm\nimport json\nimport numpy as np\nimport os\nfrom datetime import datetime\nimport logging\nfrom collections import defaultdict\n\nimport paddle.fluid as F\nfrom pgl.utils.logger import log\nfrom pgl.utils.log_writer import LogWriter\n\n\ndef multi_device(reader, dev_count):\n if dev_count == 1:\n for batch in reader:\n yield batch\n else:\n batches = []\n for batch in reader:\n batches.append(batch)\n if len(batches) == dev_count:\n yield batches\n batches = []\n\n\ndef evaluate(exe, loader, prog, model, evaluator):\n total_labels = []\n for i in range(len(loader.dataset)):\n g, l = loader.dataset[i]\n total_labels.append(l)\n total_labels = np.vstack(total_labels)\n\n pred_output = []\n for feed_dict in loader:\n ret = exe.run(prog, feed=feed_dict, fetch_list=model.pred)\n pred_output.append(ret[0])\n\n pred_output = np.vstack(pred_output)\n\n result = evaluator.eval({\"y_true\": total_labels, \"y_pred\": pred_output})\n\n return result\n\n\ndef _create_if_not_exist(path):\n basedir = os.path.dirname(path)\n if not os.path.exists(basedir):\n os.makedirs(basedir)\n\n\ndef train_and_evaluate(exe,\n train_exe,\n valid_exe,\n train_ds,\n valid_ds,\n test_ds,\n train_prog,\n valid_prog,\n args,\n model,\n evaluator,\n dev_count=1):\n\n global_step = 0\n\n timestamp = datetime.now().strftime(\"%Hh%Mm%Ss\")\n log_path = os.path.join(args.log_dir, \"log_%s\" % timestamp)\n _create_if_not_exist(log_path)\n\n writer = LogWriter(log_path)\n\n best_valid_score = 0.0\n for e in range(args.epoch):\n for feed_dict in multi_device(train_ds, dev_count):\n if dev_count > 1:\n ret = train_exe.run(feed=feed_dict,\n fetch_list=model.metrics.vars)\n ret = [[np.mean(v)] for v in ret]\n else:\n ret = train_exe.run(train_prog,\n feed=feed_dict,\n fetch_list=model.metrics.vars)\n\n ret = model.metrics.parse(ret)\n if global_step % args.train_log_step == 0:\n writer.add_scalar(\n \"batch_loss\", ret['loss'], global_step)\n log.info(\"epoch: %d | step: %d | loss: %.4f \" %\n (e, global_step, ret['loss']))\n\n global_step += 1\n if global_step % args.eval_step == 0:\n valid_ret = evaluate(exe, valid_ds, valid_prog, model,\n evaluator)\n message = \"valid: \"\n for key, value in valid_ret.items():\n message += \"%s %.4f | \" % (key, value)\n writer.add_scalar(\n \"eval_%s\" % key, value, global_step)\n log.info(message)\n\n # testing\n test_ret = evaluate(exe, test_ds, valid_prog, model, evaluator)\n message = \"test: \"\n for key, value in test_ret.items():\n message += \"%s %.4f | \" % (key, value)\n writer.add_scalar(\n \"test_%s\" % key, value, global_step)\n log.info(message)\n\n # evaluate after one epoch\n valid_ret = evaluate(exe, valid_ds, valid_prog, model, evaluator)\n message = \"epoch %s valid: \" % e\n for key, value in valid_ret.items():\n message += \"%s %.4f | \" % (key, value)\n writer.add_scalar(\"eval_%s\" % key, value, global_step)\n log.info(message)\n\n # testing\n test_ret = evaluate(exe, test_ds, valid_prog, model, evaluator)\n message = \"epoch %s test: \" % e\n for key, value in test_ret.items():\n message += \"%s %.4f | \" % (key, value)\n writer.add_scalar(\"test_%s\" % key, value, global_step)\n log.info(message)\n\n message = \"epoch %s best %s result | \" % (e, args.eval_metrics)\n if valid_ret[args.eval_metrics] > best_valid_score:\n best_valid_score = valid_ret[args.eval_metrics]\n best_test_score = test_ret[args.eval_metrics]\n\n message += \"valid %.4f | test %.4f\" % (best_valid_score,\n best_test_score)\n log.info(message)\n\n # if global_step % args.save_step == 0:\n # F.io.save_persistables(exe, os.path.join(args.save_dir, \"%s\" % global_step), train_prog)\n\n writer.close()\n" ]
[ [ "numpy.mean", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sanket-kamthe/gptf
[ "7db86b8a608f9ca45548c4e2c9fcb5f48daf9187" ]
[ "gptf/core/models.py" ]
[ "# -*- encoding: utf-8 -*-\n\"\"\"Provides base classes for models of all kinds.\"\"\"\nfrom builtins import super, range\nfrom future.utils import with_metaclass\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.opt import ScipyOptimizerInterface\nfrom scipy.optimize import OptimizeResult\n\nfrom . import tfhacks, utils\nfrom .params import Parameterized, ParamAttributes, DataHolder, autoflow\nfrom .wrappedtf import tf_method\n\nclass Model(with_metaclass(ABCMeta, Parameterized)):\n \"\"\"Base class for models. \n \n Inheriting classes must define `.build_log_likelihood(self)`.\n\n `Param` and `Parameterized` objects that are children of the model\n can be used in the tensorflow expression. Children on the model are\n defined like so:\n\n >>> from overrides import overrides\n >>> from gptf import Param, ParamAttributes\n >>> class Example(Model, ParamAttributes):\n ... def __init__(self):\n ... super().__init__()\n ... self.x = Param(1.) # create new Param child\n ...\n ... @tf_method()\n ... @overrides\n ... def build_log_likelihood(self, X, Y):\n ... return 3 - self.x.tensor # use Param in expression\n\n The `.optimize` method can be used to optimize the parameters of the\n model to minimise the likelihood. The loss function (the negative of\n the sum of the likelihood and any priors) is cached in the WrappedTF\n cache, and lazily recompiled when the cache is cleared, e.g. on \n recompile.\n\n \"\"\"\n @abstractmethod\n def build_log_likelihood(self, X, Y):\n \"\"\"Builds the log likelihood of the model w.r.t. the data.\n\n Args:\n X (tf.Tensor): The training inputs.\n Y (tf.Tensor): The training outputs.\n\n Returns:\n (tf.Tensor): A tensor that, when run, calculates the log\n likelihood of the model.\n\n \"\"\"\n NotImplemented\n\n @tf_method()\n def build_log_prior(self):\n NotImplemented\n\n @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]))\n def compute_log_likelihood(self, X, Y):\n \"\"\"Computes the likelihood of the model w.r.t. the data.\n \n Returns:\n (np.ndarray): The log likelihood of the model.\n\n \"\"\"\n return self.build_log_likelihood(X, Y)\n\n @autoflow()\n def compute_log_prior(self):\n NotImplemented\n\n @tf_method(cache=False)\n def optimize(self, X, Y, method='L-BFGS-B', callback=None, \n maxiter=1000, **kw):\n \"\"\"Optimize the model by maximising the log likelihood.\n\n Maximises the sum of the log likelihood given X & Y and any \n priors with respect to any free variables.\n\n Args:\n X (np.ndarray | tf.Tensor): The training inputs.\n Y (np.ndarray | tf.Tensor): The training outputs.\n method (tf.train.Optimizer | str): The means by which to\n optimise. If `method` is a string, it will be passed as\n the `method` argument to the initialiser of\n `tf.contrib.opt.ScipyOptimizerInterface`. Else, it\n will be treated as an instance of `tf.train.Optimizer`\n and its `.minimize()` method will be used as the training\n step.\n callback (Callable[[np.ndarray], ...]): A function that will\n be called at each optimization step with the current value\n of the variable vector (a vector constructed by flattening\n the free state of each free `Param` and then concatenating \n them in the order the `Param`\\ s are returned by `.params`.\n maxiter (int): The maximum number of iterations of the optimizer.\n **kw: Additional keyword arguments are passed through to the\n optimizer.\n\n Returns:\n (scipy.OptimizeResult) The result of the optimisation.\n\n Examples:\n Let's construct a very simple model for demonstration \n purposes. It has two (scalar) parameters, `.a` and `.b`, \n which are constrained to be positive, and its likelihood is\n `10 - a - b`, regardless of X and Y.\n\n >>> import numbers\n >>> import numpy as np\n >>> from overrides import overrides\n >>> from gptf import Param, ParamAttributes, transforms\n >>> class Example(Model, ParamAttributes):\n ... def __init__(self, a, b):\n ... assert isinstance(a, numbers.Number)\n ... assert isinstance(b, numbers.Number)\n ... super().__init__()\n ... self.a = Param(a, transform=transforms.Exp(0.))\n ... self.b = Param(b, transform=transforms.Exp(0.))\n ... @tf_method()\n ... @overrides\n ... def build_log_likelihood(self, X, Y):\n ... return 10. - self.a.tensor - self.b.tensor\n\n We won't care about the values of X and Y.\n\n >>> X = np.array(0.)\n >>> Y = np.array(0.)\n\n .. rubric:: TensorFlow optimizers\n\n We can optimise the parameters of the model using a TensorFlow\n optimizer like so:\n\n >>> m = Example(3., 4.)\n >>> opt = tf.train.GradientDescentOptimizer(learning_rate=1)\n >>> m.optimize(X, Y, opt) # use None for X, Y\n message: 'Finished iterations.'\n success: True\n x: array([..., ...])\n\n After the optimisation, both parameters are optimised\n towards 0, but are still positive. The constraints on the \n parameters have been respected.\n\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.001\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 0.001\n\n If we fix a parameter, it is not optimized:\n \n >>> m.a = 5.\n >>> m.b = 1.\n >>> m.b.fixed = True\n >>> m.optimize(X, Y, opt)\n message: 'Finished iterations.'\n success: True\n x: array([...])\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.001\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 1.000\n\n .. rubric:: SciPy optimizers\n\n We can optimise the parameters of the model using a SciPy\n optimizer by provided a string value for `method`:\n\n >>> m = Example(3., 4.)\n >>> m.optimize(X, Y, 'L-BFGS-B', disp=False, ftol=.0001)\n message: 'SciPy optimizer completed successfully.'\n success: True\n x: array([..., ...])\n\n As for TensorFlow optimizers, after the optimisation both \n parameters are optimised towards 0, but are still positive. \n The constraints on the parameters have been respected.\n\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.000\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 0.000\n\n If we fix a parameter, it is not optimized:\n\n >>> m.a = 5.\n >>> m.b = 1.\n >>> m.b.fixed = True\n >>> m.optimize(X, Y, 'L-BFGS-B', disp=False, ftol=.0001)\n message: 'SciPy optimizer completed successfully.'\n success: True\n x: array([...])\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.000\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 1.000\n\n .. rubric:: Miscellaneous\n\n Optimisation still works, even with weird device contexts and\n session targets.\n\n >>> # set up a distributed execution environment\n >>> clusterdict = \\\\\n ... { 'worker': ['localhost:2226']\n ... , 'master': ['localhost:2227']\n ... }\n >>> spec = tf.train.ClusterSpec(clusterdict)\n >>> worker = tf.train.Server(spec, job_name='worker', task_index=0)\n >>> worker.start()\n >>> master = tf.train.Server(spec, job_name='master', task_index=0)\n >>> # change m's device context\n >>> # we're about to do weird things with op placement, and we\n >>> # don't want it in the default graph where it can mess with\n >>> # other doctests, so change m's tf_graph as well.\n >>> m.tf_graph = tf.Graph()\n >>> m.tf_device = '/job:worker/task:0'\n >>> m.tf_session_target = master.target\n\n TensorFlow:\n\n >>> m.a = 4.5\n >>> m.optimize(X, Y, opt)\n message: 'Finished iterations.'\n success: True\n x: array([...])\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.001\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 1.000\n \n SciPy:\n\n >>> m.a = 4.5\n >>> m.optimize(X, Y, 'L-BFGS-B', disp=False, ftol=.0001)\n message: 'SciPy optimizer completed successfully.'\n success: True\n x: array([...])\n >>> print(\"m.a: {:.3f}\".format(np.asscalar(m.a.value)))\n m.a: 0.001\n >>> print(\"m.b: {:.3f}\".format(np.asscalar(m.b.value)))\n m.b: 1.000\n\n \"\"\"\n X_key = X if isinstance(X, tf.Tensor) else None\n Y_key = Y if isinstance(Y, tf.Tensor) else None\n key = (\"_Model__loss\", X_key, Y_key)\n if key not in self.cache:\n X_tensor = (X if isinstance(X, tf.Tensor) else\n tf.placeholder(tf.as_dtype(X.dtype)))\n Y_tensor = (Y if isinstance(Y, tf.Tensor) else\n tf.placeholder(tf.as_dtype(Y.dtype)))\n self.cache[key] = (self._compile_loss(X_tensor, Y_tensor),\n X_tensor, Y_tensor)\n loss, X_tensor, Y_tensor = self.cache[key]\n\n feed_dict = self.feed_dict\n if not isinstance(X, tf.Tensor): feed_dict[X_tensor] = X\n if not isinstance(Y, tf.Tensor): feed_dict[Y_tensor] = Y\n\n variables = [p.free_state for p in self.params if not p.fixed]\n variables = utils.unique(variables)\n free_state = tf.concat(0, [tf.reshape(v, [-1]) for v in variables])\n\n with self.get_session() as sess:\n try:\n if type(method) is str:\n success_msg = \"SciPy optimizer completed successfully.\"\n options = {'maxiter': maxiter, 'disp': True}\n options.update(kw)\n optimizer = ScipyOptimizerInterface(\n loss, var_list=variables, method=method, \n options=options\n )\n optimizer.minimize(self.get_session(), feed_dict, \n step_callback=callback)\n else:\n # treat method as TensorFlow optimizer.\n success_msg = \"Finished iterations.\"\n opt_step = method.minimize(loss, var_list=variables, **kw)\n for _ in range(maxiter):\n sess.run(opt_step, feed_dict=feed_dict)\n if callback is not None:\n callback(sess.run(free_state))\n except KeyboardInterrupt:\n return OptimizeResult\\\n ( x=sess.run(free_state)\n , success=False\n , message=\"Keyboard interrupt.\"\n )\n\n return OptimizeResult\\\n ( x=sess.run(free_state)\n , success=True\n , message=success_msg\n )\n\n def _compile_loss(self, X, Y):\n return -self.build_log_likelihood(X, Y)\n\nclass GPModel(Model):\n \"\"\"A base class for Guassian Process models.\n\n A Gaussian process model is a model of the form\n\n .. math::\n\n θ ~ p(θ)\n\n f ~ GP(m(x), k(x, x'; θ))\n\n F = f(X)\n\n Y|F ~ p(Y|F)\n\n Adds functionality to compile various predictions. Inheriting \n classes must define `.build_predict()`, which is then used by this \n class's methods to provide various predictions. The mean and \n variance are pushed through the likelihood to obtain the means and \n variances of held out data.\n\n \"\"\"\n @abstractmethod\n def build_prior_mean_var(self, test_points, num_latent, full_cov=False):\n \"\"\"Builds an op for the mean and variance of the prior(s).\n \n In the returned tensors, the last index should always be the \n latent function index.\n\n Args:\n test_points (tf.Tensor): The points from the sample\n space for which to predict means and variances\n of the prior distribution(s). The shape should be\n `[m, point_dims]`.\n num_latent (tf.int32): The number of latent functions of \n the GP.\n full_cov (bool): If `False`, return an array of variances\n at the test points. If `True`, return the full\n covariance matrix of the posterior distribution.\n \n Returns:\n (tf.Tensor, tf.Tensor): A tensor that calculates the mean\n at the test points with shape `[m, num_latent]`, a tensor\n that calculates either the variances at the test points \n (shape `[m, num_latent]`) or the full covariance matrix \n (shape `[m, m, num_latent]`).\n Both tensors have the same dtype.\n\n \"\"\"\n NotImplemented\n\n @abstractmethod\n def build_posterior_mean_var(self, X, Y, test_points, full_cov=False):\n \"\"\"Builds an op for the mean and variance of the posterior(s).\n\n In the returned tensors, the last index should always be the \n latent function index.\n\n Args:\n X (tf.Tensor): The training inputs, shape `[n, point_dims]`\n Y (tf.Tensor): The training outputs, shape `[n, num_latent]`\n test_points (tf.Tensor): The points from the sample\n space for which to predict means and variances\n of the posterior distribution(s), shape \n `[m, point_dims]`.\n full_cov (bool): If `False`, return an array of variances\n at the test points. If `True`, return the full\n covariance matrix of the posterior distribution.\n\n Returns:\n (tf.Tensor, tf.Tensor): A tensor that calculates the mean\n at the test points with shape `[m, num_latent]`, a tensor\n that calculates either the variances at the test points \n (shape `[m, num_latent]`) or the full covariance matrix \n (shape `[m, m, num_latent]`).\n Both tensors have the same dtype.\n\n \"\"\"\n NotImplemented\n\n @autoflow((tf.float64, [None, None]), (tf.int32, []))\n def compute_prior_mean_var(self, test_points, num_latent):\n \"\"\"Computes the means and variances of the prior(s).\n\n This is just an autoflowed version of \n `.build_prior_mean_var(test_points, num_latent)`.\n\n Args:\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the prior distribution(s). The shape should be\n `[m, point_dims]`.\n num_latent (int): The number of latent functions of the GP.\n \n Returns:\n (np.ndarray, np.ndarray): the mean at the test points \n (shape `[m, num_latent]`), the variances at the test \n points (shape `[m, num_latent]`).\n\n \"\"\"\n return self.build_prior_mean_var(test_points, num_latent, False)\n\n @autoflow((tf.float64, [None, None]), (tf.int32, []))\n def compute_prior_mean_cov(self, test_points, num_latent):\n \"\"\"Computes the means and full covariance matrices.\n\n This is just an autoflowed version of \n `.build_prior_mean_var(test_points, num_latent, True)`.\n\n Args:\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the prior distribution(s). The shape should be\n `[m, point_dims]`.\n num_latent (int): The number of latent functions of the GP.\n\n Returns:\n (np.ndarray, np.ndarray): The means at the test points\n (shape `[m, num_latent]`), the full covariance \n matri(x|ces) for the prior distribution(s) (shape\n `[m, m, num_latent]`.\n\n \"\"\"\n return self.build_prior_mean_var(test_points, num_latent, True)\n\n @autoflow((tf.float64, [None, None]), (tf.int32, []), (tf.int32, []))\n def compute_prior_samples(self, test_points, num_latent, num_samples): \n \"\"\"Computes samples from the prior distribution(s).\n\n Args:\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the posterior distribution(s), shape \n `[m, point_dims]`.\n num_latent (int): The number of latent functions of the GP.\n num_samples (int): The number of samples to take.\n\n Returns:\n (np.ndarray): An array of samples from the prior\n distributions, with shape `[num_samples, m, num_latent]`\n\n Examples:\n For testing purposes, we create an example model whose\n likelihood is always `0` and whose `.build_predict()`\n returns mean `0` and variance `1` for every test point,\n or an independent covariance matrix.\n\n >>> from overrides import overrides\n >>> from gptf import ParamAttributes, tfhacks\n >>> class Example(GPModel, ParamAttributes):\n ... def __init__(self, dtype):\n ... super().__init__()\n ... self.dtype = dtype\n ... @property\n ... def dtype(self):\n ... return self._dtype\n ... @dtype.setter\n ... def dtype(self, value):\n ... self.clear_cache()\n ... self._dtype = value\n ... @tf_method()\n ... @overrides\n ... def build_log_likelihood(self):\n ... NotImplemented\n ... @tf_method()\n ... @overrides\n ... def build_prior_mean_var\\\\\n ... (self, test_points, num_latent, full_cov=False):\n ... n = tf.shape(test_points)[0]\n ... mu = tf.zeros([n, 1], self.dtype)\n ... mu = tf.tile(mu, (1, num_latent))\n ... if full_cov:\n ... var = tf.expand_dims(tfhacks.eye(n, self.dtype), 2)\n ... var = tf.tile(var, (1, 1, num_latent))\n ... else:\n ... var = tf.ones([n, 1], self.dtype)\n ... var = tf.tile(var, (1, num_latent))\n ... return mu, var\n ... @tf_method()\n ... @overrides\n ... def build_posterior_mean_var\\\\\n ... (self, X, Y, test_points, full_cov=False):\n ... NotImplemented\n >>> m = Example(tf.float64) # ignore the likelihood\n >>> test_points = np.array([[0.], [1.], [2.], [3.]])\n\n The shape of the returned array is `(a, b, c)`, where `a`\n is the number of samples, `b` is the number of test points\n and `c` is the number of latent functions.\n\n >>> samples = m.compute_prior_samples(test_points, 1, 2)\n >>> samples.shape\n (2, 4, 1)\n\n `.compute_prior_samples()` respects the dtype of the tensors\n returned by `.build_predict()`.\n\n >>> samples.dtype\n dtype('float64')\n >>> m.dtype = tf.float32\n >>> samples = m.compute_prior_samples(test_points, 1, 2)\n >>> samples.dtype\n dtype('float32')\n \n \"\"\"\n mu, var = self.build_prior_mean_var(test_points, num_latent, True)\n jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06\n L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter)\n V_shape = [tf.shape(L)[0], tf.shape(L)[1], num_samples]\n V = tf.random_normal(V_shape, dtype=L.dtype)\n samples = tf.expand_dims(tf.transpose(mu), -1) + tf.batch_matmul(L, V)\n return tf.transpose(samples)\n \n @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]),\n (tf.float64, [None, None]))\n def compute_posterior_mean_var(self, X, Y, test_points):\n \"\"\"Computes the means and variances of the posterior(s).\n\n This is just an autoflowed version of \n `.build_posterior_mean_var(X, Y, test_points)`.\n\n Args:\n X (np.ndarray): The training inputs, shape `[n, point_dims]`\n Y (np.ndarray): The training outputs, shape `[n, num_latent]`\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the posterior distribution(s), shape \n `[m, point_dims]`.\n\n Returns:\n (np.ndarray, np.ndarray): The means at the test points\n (shape `[m, num_latent]`), the variances at the test points\n (shape `[m, num_latent]`).\n\n \"\"\"\n return self.build_posterior_mean_var(X, Y, test_points, full_cov=False)\n\n @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]),\n (tf.float64, [None, None]))\n def compute_posterior_mean_cov(self, X, Y, test_points):\n \"\"\"Computes the means and full covariance matrices.\n\n This is just an autoflowed version of \n `.build_predict(X, Y, test_points, full_cov=True)`.\n\n Args:\n X (np.ndarray): The training inputs, shape `[n, point_dims]`\n Y (np.ndarray): The training outputs, shape `[n, num_latent]`\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the posterior distribution(s), shape \n `[m, point_dims]`.\n\n Returns:\n (np.ndarray, np.ndarray): The means at the test points\n (shape `[m, num_latent]`), the full covriance \n matri(x|ces) for the posterior distribution(s)\n (shape `[m, m, num_latent]`).\n\n \"\"\"\n return self.build_posterior_mean_var(X, Y, test_points, full_cov=True)\n\n @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]), \n (tf.float64, [None, None]), (tf.int32, []))\n def compute_posterior_samples(self, X, Y, test_points, num_samples): \n \"\"\"Computes samples from the posterior distribution(s).\n\n Args:\n X (np.ndarray): The training inputs, shape `[n, point_dims]`\n Y (np.ndarray): The training outputs, shape `[n, num_latent]`\n test_points (np.ndarray): The points from the sample\n space for which to predict means and variances\n of the posterior distribution(s), shape \n `[m, point_dims]`.\n num_samples (int): The number of samples to take.\n\n Returns:\n (np.ndarray): An array of samples from the posterior\n distributions, with shape `[num_samples, m, num_latent]`\n\n Examples:\n For testing purposes, we create an example model whose\n likelihood is always `0` and whose `.build_predict()`\n returns mean `0` and variance `1` for every test point,\n or an independent covariance matrix.\n\n >>> from overrides import overrides\n >>> from gptf import ParamAttributes, tfhacks\n >>> class Example(GPModel, ParamAttributes):\n ... def __init__(self, dtype):\n ... super().__init__()\n ... self.dtype = dtype\n ... @property\n ... def dtype(self):\n ... return self._dtype\n ... @dtype.setter\n ... def dtype(self, value):\n ... self.clear_cache()\n ... self._dtype = value\n ... @tf_method()\n ... @overrides\n ... def build_log_likelihood(self):\n ... NotImplemented\n ... @tf_method()\n ... @overrides\n ... def build_prior_mean_var\\\\\n ... (self, test_points, num_latent, full_cov=False):\n ... NotImplemented\n ... @tf_method()\n ... @overrides\n ... def build_posterior_mean_var\\\\\n ... (self, X, Y, test_points, full_cov=False):\n ... n = tf.shape(test_points)[0]\n ... num_latent = tf.shape(Y)[1]\n ... mu = tf.zeros([n, 1], self.dtype)\n ... mu = tf.tile(mu, (1, num_latent))\n ... if full_cov:\n ... var = tf.expand_dims(tfhacks.eye(n, self.dtype), 2)\n ... var = tf.tile(var, (1, 1, num_latent))\n ... else:\n ... var = tf.ones([n, 1], self.dtype)\n ... var = tf.tile(var, (1, num_latent))\n ... return mu, var\n >>> m = Example(tf.float64)\n >>> X = np.array([[.5]])\n >>> Y = np.array([[.3]])\n >>> test_points = np.array([[0.], [1.], [2.], [3.]])\n\n The shape of the returned array is `(a, b, c)`, where `a`\n is the number of samples, `b` is the number of test points\n and `c` is the number of latent functions.\n\n >>> samples = m.compute_posterior_samples(X, Y, test_points, 2)\n >>> samples.shape\n (2, 4, 1)\n\n `.compute_posterior_samples()` respects the dtype of the tensors\n returned by `.build_predict()`.\n\n >>> samples.dtype\n dtype('float64')\n >>> m.dtype = tf.float32\n >>> samples = m.compute_posterior_samples(X, Y, test_points, 2)\n >>> samples.dtype\n dtype('float32')\n \n \"\"\"\n mu, var = self.build_posterior_mean_var(X, Y, test_points, True)\n jitter = tfhacks.eye(tf.shape(mu)[0], var.dtype) * 1e-06\n L = tf.batch_cholesky(tf.transpose(var, (2, 0, 1)) + jitter)\n V_shape = [tf.shape(L)[0], tf.shape(L)[1], num_samples]\n V = tf.random_normal(V_shape, dtype=L.dtype)\n samples = tf.expand_dims(tf.transpose(mu), -1) + tf.batch_matmul(L, V)\n return tf.transpose(samples)\n #samples = []\n #for i in range(self.num_latent_functions):\n # L = tf.cholesky(var[:, :, i] + jitter)\n # V = tf.random_normal([tf.shape(L)[0], num_samples], dtype=L.dtype)\n # samples.append(mu[:, i:i + 1] + tf.matmul(L, V)) # broadcast\n #return tf.transpose(tf.pack(samples))\n\n @autoflow((tf.float64, [None, None]))\n def predict_y(self, test_points):\n \"\"\"Computes the mean and variance of held-out data.\"\"\"\n NotImplemented\n\n @autoflow((tf.float64, [None, None]), (tf.float64, [None, None]))\n def predict_density(self, test_points, test_values):\n \"\"\"Computes the (log) density of the test values at the test points.\"\"\"\n NotImplemented\n" ]
[ [ "tensorflow.batch_matmul", "tensorflow.transpose", "tensorflow.contrib.opt.ScipyOptimizerInterface", "tensorflow.as_dtype", "tensorflow.shape", "tensorflow.reshape", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
hkuich/kglib
[ "bc221d7abbff801802ca327bfd293d50e619ff5f" ]
[ "kglib/kgcn_tensorflow/learn/learn_IT.py" ]
[ "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\nimport unittest\n\nimport networkx as nx\nimport numpy as np\n\nfrom kglib.kgcn_tensorflow.learn.learn import KGCNLearner\nfrom kglib.kgcn_tensorflow.models.core import KGCN\nfrom kglib.kgcn_tensorflow.models.embedding import ThingEmbedder, RoleEmbedder\n\n\nclass ITKGCNLearner(unittest.TestCase):\n def test_learner_runs(self):\n input_graph = nx.MultiDiGraph()\n input_graph.add_node(0, features=np.array([0, 1, 2], dtype=np.float32))\n input_graph.add_edge(1, 0, features=np.array([0, 1, 2], dtype=np.float32))\n input_graph.add_node(1, features=np.array([0, 1, 2], dtype=np.float32))\n input_graph.add_edge(1, 2, features=np.array([0, 1, 2], dtype=np.float32))\n input_graph.add_node(2, features=np.array([0, 1, 2], dtype=np.float32))\n input_graph.graph['features'] = np.zeros(5, dtype=np.float32)\n\n target_graph = nx.MultiDiGraph()\n target_graph.add_node(0, features=np.array([0, 1, 0], dtype=np.float32))\n target_graph.add_edge(1, 0, features=np.array([0, 0, 1], dtype=np.float32))\n target_graph.add_node(1, features=np.array([0, 0, 1], dtype=np.float32))\n target_graph.add_edge(1, 2, features=np.array([0, 0, 1], dtype=np.float32))\n target_graph.add_node(2, features=np.array([0, 1, 0], dtype=np.float32))\n target_graph.graph['features'] = np.zeros(5, dtype=np.float32)\n\n thing_embedder = ThingEmbedder(node_types=['a', 'b', 'c'], type_embedding_dim=5,\n attr_embedding_dim=6, categorical_attributes={}, continuous_attributes={})\n\n role_embedder = RoleEmbedder(num_edge_types=2, type_embedding_dim=5)\n\n kgcn = KGCN(thing_embedder, role_embedder, edge_output_size=3, node_output_size=3)\n\n learner = KGCNLearner(kgcn, num_processing_steps_tr=2, num_processing_steps_ge=2)\n\n learner([input_graph], [target_graph], [input_graph], [target_graph], num_training_iterations=50)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
B-Eltzner/geomstats
[ "d0e81fd81c86ed380a2444337e9ba9621ee73f04" ]
[ "geomstats/_backend/pytorch/__init__.py" ]
[ "\"\"\"Pytorch based computation backend.\"\"\"\n\nimport math\nfrom functools import wraps\n\nimport numpy as _np\nimport torch\nfrom torch import ( # NOQA\n arange,\n argmin,\n arccos,\n arccosh,\n arcsin,\n arctanh,\n atan2 as arctan2,\n bool as t_bool,\n broadcast_tensors as broadcast_arrays,\n ceil,\n clip,\n cos,\n cosh,\n cross,\n divide,\n empty_like,\n eq,\n erf,\n exp,\n eye,\n flatten,\n float32,\n float64,\n floor,\n fmod as mod,\n outer,\n greater,\n hstack,\n imag,\n int32,\n int64,\n isnan,\n log,\n logical_or,\n less,\n matmul,\n max as amax,\n mean,\n meshgrid,\n min as amin,\n nonzero,\n ones,\n ones_like,\n polygamma,\n pow as power,\n real,\n repeat_interleave as repeat,\n reshape,\n sign,\n sin,\n sinh,\n stack,\n std,\n tan,\n tanh,\n tril,\n uint8,\n vstack,\n zeros,\n zeros_like\n)\n\nfrom . import autograd # NOQA\nfrom . import linalg # NOQA\nfrom . import random # NOQA\nfrom ..constants import pytorch_atol, pytorch_rtol\n\nDTYPES = {\n int32: 0,\n int64: 1,\n float32: 2,\n float64: 3}\n\n\natol = pytorch_atol\nrtol = pytorch_rtol\n\n\ndef _raise_not_implemented_error(*args, **kwargs):\n raise NotImplementedError\n\n\nsearchsorted = _raise_not_implemented_error\n\n\ndef _box_scalar(function):\n @wraps(function)\n def wrapper(x):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n return function(x)\n return wrapper\n\n\nabs = _box_scalar(abs)\nceil = _box_scalar(ceil)\ncos = _box_scalar(cos)\ncosh = _box_scalar(cosh)\nexp = _box_scalar(exp)\nimag = _box_scalar(imag)\nlog = _box_scalar(log)\nreal = _box_scalar(real)\nsin = _box_scalar(sin)\nsinh = _box_scalar(sinh)\ntan = _box_scalar(tan)\n\n\ndef comb(n, k):\n return math.factorial(n) // math.factorial(k) // math.factorial(n - k)\n\n\ndef to_numpy(x):\n return x.numpy()\n\n\ndef one_hot(labels, num_classes):\n if not torch.is_tensor(labels):\n labels = torch.LongTensor(labels)\n return torch.nn.functional.one_hot(\n labels, num_classes).type(torch.uint8)\n\n\ndef argmax(a, **kwargs):\n if a.dtype == torch.bool:\n return torch.as_tensor(_np.argmax(a.data.numpy(), **kwargs))\n return torch.argmax(a, **kwargs)\n\n\ndef convert_to_wider_dtype(tensor_list):\n dtype_list = [DTYPES[x.dtype] for x in tensor_list]\n wider_dtype_index = max(dtype_list)\n\n wider_dtype = list(DTYPES.keys())[wider_dtype_index]\n\n tensor_list = [cast(x, dtype=wider_dtype) for x in tensor_list]\n return tensor_list\n\n\ndef less_equal(x, y, **kwargs):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n if not torch.is_tensor(y):\n y = torch.tensor(y)\n return torch.le(x, y, **kwargs)\n\n\ndef empty(shape, dtype=float64):\n return torch.empty(*shape, dtype=dtype)\n\n\ndef split(x, indices_or_sections, axis=0):\n if isinstance(indices_or_sections, int):\n indices_or_sections = x.shape[axis] // indices_or_sections\n return torch.split(x, indices_or_sections, dim=axis)\n indices_or_sections = _np.array(indices_or_sections)\n intervals_length = indices_or_sections[1:] - indices_or_sections[:-1]\n last_interval_length = x.shape[axis] - indices_or_sections[-1]\n if last_interval_length > 0:\n intervals_length = _np.append(intervals_length, last_interval_length)\n intervals_length = _np.insert(intervals_length, 0, indices_or_sections[0])\n return torch.split(x, tuple(intervals_length), dim=axis)\n\n\ndef logical_and(x, y):\n if torch.is_tensor(x):\n return torch.logical_and(x, y)\n return x and y\n\n\ndef any(x, axis=None):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n if axis is None:\n return torch.any(x)\n if isinstance(axis, int):\n return torch.any(x.bool(), axis)\n if len(axis) == 1:\n return torch.any(x, *axis)\n axis = list(axis)\n for i_axis, one_axis in enumerate(axis):\n if one_axis < 0:\n axis[i_axis] = ndim(x) + one_axis\n new_axis = tuple(k - 1 if k >= 0 else k for k in axis[1:])\n return any(torch.any(x.bool(), axis[0]), new_axis)\n\n\ndef cast(x, dtype):\n if torch.is_tensor(x):\n return x.to(dtype=dtype)\n return array(x).to(dtype=dtype)\n\n\ndef flip(x, axis):\n if isinstance(axis, int):\n axis = [axis]\n if axis is None:\n axis = list(range(x.ndim))\n return torch.flip(x, dims=axis)\n\n\ndef concatenate(seq, axis=0, out=None):\n seq = convert_to_wider_dtype(seq)\n return torch.cat(seq, dim=axis, out=out)\n\n\ndef _get_largest_dtype(seq):\n dtype_dict = {0: t_bool,\n 1: uint8,\n 2: int32,\n 3: int64,\n 4: float32,\n 5: float64}\n reverse_dict = {dtype_dict[key]: key for key in dtype_dict}\n dtype_code_set = {reverse_dict[t.dtype] for t in seq}\n return dtype_dict[max(dtype_code_set)]\n\n\ndef array(val, dtype=None):\n if isinstance(val, (list, tuple)):\n if isinstance(val[0], (list, tuple)):\n aux_list = [array(t, dtype) for t in val]\n if dtype is None:\n local_dtype = _get_largest_dtype(aux_list)\n aux_list = [cast(t, local_dtype) for t in aux_list]\n return stack(aux_list)\n if not any([isinstance(t, torch.Tensor) for t in val]):\n val = _np.copy(_np.array(val))\n elif any([not isinstance(t, torch.Tensor) for t in val]):\n tensor_members = [t for t in val if torch.is_tensor(t)]\n local_dtype = _get_largest_dtype(tensor_members)\n for index, t in enumerate(val):\n if torch.is_tensor(t) and t.dtype != local_dtype:\n cast(t, local_dtype)\n elif torch.is_tensor(t):\n val[index] = cast(t, dtype=local_dtype)\n else:\n val[index] = torch.tensor(t, dtype=local_dtype)\n val = stack(val)\n else:\n val = stack(val)\n\n if isinstance(val, (bool, int, float)):\n val = _np.array(val)\n\n if isinstance(val, _np.ndarray):\n val = torch.from_numpy(val)\n\n if not isinstance(val, torch.Tensor):\n val = torch.Tensor([val])\n\n if dtype is not None:\n if val.dtype != dtype:\n val = cast(val, dtype)\n elif val.dtype == torch.float64:\n val = val.float()\n return val\n\n\ndef all(x, axis=None):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n if axis is None:\n return x.bool().all()\n if isinstance(axis, int):\n return torch.all(x.bool(), axis)\n if len(axis) == 1:\n return torch.all(x, *axis)\n axis = list(axis)\n for i_axis, one_axis in enumerate(axis):\n if one_axis < 0:\n axis[i_axis] = ndim(x) + one_axis\n new_axis = tuple(k - 1 if k >= 0 else k for k in axis[1:])\n return all(torch.all(x.bool(), axis[0]), new_axis)\n\n\ndef get_slice(x, indices):\n \"\"\"Return a slice of an array, following Numpy's style.\n\n Parameters\n ----------\n x : array-like, shape=[dim]\n Initial array.\n indices : iterable(iterable(int))\n Indices which are kept along each axis, starting from 0.\n\n Returns\n -------\n slice : array-like\n Slice of x given by indices.\n\n Notes\n -----\n This follows Numpy's convention: indices are grouped by axis.\n\n Examples\n --------\n >>> a = torch.tensor(range(30)).reshape(3,10)\n >>> get_slice(a, ((0, 2), (8, 9)))\n tensor([8, 29])\n \"\"\"\n return x[indices]\n\n\ndef allclose(a, b, atol=atol, rtol=rtol):\n if not isinstance(a, torch.Tensor):\n a = torch.tensor(a)\n if not isinstance(b, torch.Tensor):\n b = torch.tensor(b)\n a = to_ndarray(a.float(), to_ndim=1)\n b = to_ndarray(b.float(), to_ndim=1)\n n_a = a.shape[0]\n n_b = b.shape[0]\n nb_dim = a.dim()\n if n_a > n_b:\n reps = (int(n_a / n_b),) + (nb_dim - 1) * (1,)\n b = tile(b, reps)\n elif n_a < n_b:\n reps = (int(n_b / n_a),) + (nb_dim - 1) * (1,)\n a = tile(a, reps)\n return torch.allclose(a, b, atol=atol, rtol=rtol)\n\n\ndef shape(val):\n return val.shape\n\n\ndef dot(a, b):\n return einsum('...i,...i->...', a, b)\n\n\ndef maximum(a, b):\n return torch.max(array(a), array(b))\n\n\ndef to_ndarray(x, to_ndim, axis=0):\n x = array(x)\n if x.dim() == to_ndim - 1:\n x = torch.unsqueeze(x, dim=axis)\n return x\n\n\ndef broadcast_to(x, shape):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n return x.expand(shape)\n\n\ndef sqrt(x):\n if not isinstance(x, torch.Tensor):\n x = torch.tensor(x).float()\n return torch.sqrt(x)\n\n\ndef isclose(x, y, rtol=rtol, atol=atol):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n if not torch.is_tensor(y):\n y = torch.tensor(y)\n return torch.isclose(x, y, atol=atol, rtol=rtol)\n\n\ndef sum(x, axis=None, keepdims=None, **kwargs):\n if axis is None:\n if keepdims is None:\n return torch.sum(x, **kwargs)\n return torch.sum(x, keepdim=keepdims, **kwargs)\n if keepdims is None:\n return torch.sum(x, dim=axis, **kwargs)\n return torch.sum(x, dim=axis, keepdim=keepdims, **kwargs)\n\n\ndef einsum(*args, **kwargs):\n einsum_str = args[0]\n input_tensors_list = args[1:]\n\n input_tensors_list = convert_to_wider_dtype(input_tensors_list)\n\n if len(input_tensors_list) == 1:\n return torch.einsum(einsum_str, input_tensors_list)\n\n einsum_list = einsum_str.split('->')\n input_str = einsum_list[0]\n if len(einsum_list) > 1:\n output_str = einsum_list[1]\n\n input_str_list = input_str.split(',')\n\n is_ellipsis = [input_str[:3] == '...' for input_str in input_str_list]\n all_ellipsis = bool(_np.prod(is_ellipsis))\n\n if all_ellipsis:\n ndims = [len(input_str[3:]) for input_str in input_str_list]\n\n if len(input_str_list) > 2:\n raise NotImplementedError(\n 'Ellipsis support not implemented for >2 input tensors')\n\n tensor_a = input_tensors_list[0]\n tensor_b = input_tensors_list[1]\n initial_ndim_a = tensor_a.ndim\n initial_ndim_b = tensor_b.ndim\n tensor_a = to_ndarray(tensor_a, to_ndim=ndims[0] + 1)\n tensor_b = to_ndarray(tensor_b, to_ndim=ndims[1] + 1)\n\n n_tensor_a = tensor_a.shape[0]\n n_tensor_b = tensor_b.shape[0]\n\n cond = (\n n_tensor_a == n_tensor_b == 1\n and initial_ndim_a != tensor_a.ndim\n and initial_ndim_b != tensor_b.ndim)\n\n if cond:\n tensor_a = squeeze(tensor_a, axis=0)\n tensor_b = squeeze(tensor_b, axis=0)\n input_prefix_list = ['', '']\n output_prefix = ''\n elif n_tensor_a != n_tensor_b:\n if n_tensor_a == 1:\n tensor_a = squeeze(tensor_a, axis=0)\n input_prefix_list = ['', 'r']\n output_prefix = 'r'\n elif n_tensor_b == 1:\n tensor_b = squeeze(tensor_b, axis=0)\n input_prefix_list = ['r', '']\n output_prefix = 'r'\n else:\n raise ValueError('Shape mismatch for einsum.')\n else:\n input_prefix_list = ['r', 'r']\n output_prefix = 'r'\n\n input_str_list = [\n input_str.replace('...', prefix) for input_str, prefix in zip(\n input_str_list, input_prefix_list)]\n\n input_str = input_str_list[0] + ',' + input_str_list[1]\n\n einsum_str = input_str\n if len(einsum_list) > 1:\n output_str = output_str.replace('...', output_prefix)\n einsum_str = input_str + '->' + output_str\n\n result = torch.einsum(einsum_str, tensor_a, tensor_b, **kwargs)\n\n return result\n\n return torch.einsum(*args, **kwargs)\n\n\ndef T(x):\n return torch.t(x)\n\n\ndef transpose(x, axes=None):\n if axes:\n return x.permute(axes)\n if x.dim() == 1:\n return x\n if x.dim() > 2 and axes is None:\n return x.permute(tuple(range(x.ndim)[::-1]))\n return x.t()\n\n\ndef squeeze(x, axis=None):\n if axis is None:\n return torch.squeeze(x)\n return torch.squeeze(x, dim=axis)\n\n\ndef trace(x, axis1=0, axis2=1):\n min_axis = min(axis1, axis2)\n max_axis = max(axis1, axis2)\n if min_axis == 1 and max_axis == 2:\n return torch.einsum('...ii', x)\n if min_axis == -2 and max_axis == -1:\n return torch.einsum('...ii', x)\n if min_axis == 0 and max_axis == 1:\n return torch.einsum('ii...', x)\n if min_axis == 0 and max_axis == 2:\n return torch.einsum('i...i', x)\n raise NotImplementedError()\n\n\ndef linspace(start, stop, num):\n return torch.linspace(start=start, end=stop, steps=num)\n\n\ndef equal(a, b, **kwargs):\n if a.dtype == torch.ByteTensor:\n a = cast(a, torch.uint8).float()\n if b.dtype == torch.ByteTensor:\n b = cast(b, torch.uint8).float()\n return torch.eq(a, b, **kwargs)\n\n\ndef diag_indices(*args, **kwargs):\n return tuple(map(torch.from_numpy, _np.diag_indices(*args, **kwargs)))\n\n\ndef tril_indices(n, k=0, m=None):\n if m is None:\n m = n\n return torch.tril_indices(row=n, col=m, offset=k)\n\n\ndef triu_indices(n, k=0, m=None):\n if m is None:\n m = n\n return torch.triu_indices(row=n, col=m, offset=k)\n\n\ndef tile(x, y):\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n return x.repeat(y)\n\n\ndef expand_dims(x, axis=0):\n return torch.unsqueeze(x, dim=axis)\n\n\ndef ndim(x):\n return x.dim()\n\n\ndef hsplit(x, indices_or_section):\n if isinstance(indices_or_section, int):\n indices_or_section = x.shape[1] // indices_or_section\n return torch.split(x, indices_or_section, dim=1)\n\n\ndef diagonal(x, offset=0, axis1=0, axis2=1):\n return torch.diagonal(x, offset=offset, dim1=axis1, dim2=axis2)\n\n\ndef set_diag(x, new_diag):\n \"\"\"Set the diagonal along the last two axis.\n\n Parameters\n ----------\n x : array-like, shape=[dim]\n Initial array.\n new_diag : array-like, shape=[dim[-2]]\n Values to set on the diagonal.\n\n Returns\n -------\n None\n\n Notes\n -----\n This mimics tensorflow.linalg.set_diag(x, new_diag), when new_diag is a\n 1-D array, but modifies x instead of creating a copy.\n \"\"\"\n arr_shape = x.shape\n off_diag = (1 - torch.eye(arr_shape[-1])) * x\n diag = torch.einsum(\n 'ij,...i->...ij', torch.eye(new_diag.shape[-1]), new_diag)\n return diag + off_diag\n\n\ndef prod(x, axis=None):\n if axis is None:\n axis = 0\n return torch.prod(x, axis)\n\n\ndef where(condition, x=None, y=None):\n if x is None and y is None:\n return torch.where(condition)\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n if not torch.is_tensor(y):\n y = torch.tensor(y)\n y = cast(y, x.dtype)\n return torch.where(condition, x, y)\n\n\ndef get_mask_i_float(i, n):\n \"\"\"Create a 1D array of zeros with one element at one, with floating type.\n\n Parameters\n ----------\n i : int\n Index of the non-zero element.\n n: n\n Length of the created array.\n\n Returns\n -------\n mask_i_float : array-like, shape=[n,]\n 1D array of zeros except at index i, where it is one\n \"\"\"\n range_n = arange(cast(array(n), int32))\n i_float = cast(array(i), int32)\n mask_i = equal(range_n, i_float)\n mask_i_float = cast(mask_i, float32)\n return mask_i_float\n\n\ndef _is_boolean(x):\n if isinstance(x, bool):\n return True\n if isinstance(x, (tuple, list)):\n return _is_boolean(x[0])\n if torch.is_tensor(x):\n return x.dtype in [torch.bool, torch.uint8]\n return False\n\n\ndef _is_iterable(x):\n if isinstance(x, (list, tuple)):\n return True\n if torch.is_tensor(x):\n return ndim(x) > 0\n return False\n\n\ndef assignment(x, values, indices, axis=0):\n \"\"\"Assign values at given indices of an array.\n\n Parameters\n ----------\n x: array-like, shape=[dim]\n Initial array.\n values: {float, list(float)}\n Value or list of values to be assigned.\n indices: {int, tuple, list(int), list(tuple)}\n Single int or tuple, or list of ints or tuples of indices where value\n is assigned.\n If the length of the tuples is shorter than ndim(x), values are\n assigned to each copy along axis.\n axis: int, optional\n Axis along which values are assigned, if vectorized.\n\n Returns\n -------\n x_new : array-like, shape=[dim]\n Copy of x with the values assigned at the given indices.\n\n Notes\n -----\n If a single value is provided, it is assigned at all the indices.\n If a list is given, it must have the same length as indices.\n \"\"\"\n x_new = copy(x)\n\n use_vectorization = hasattr(indices, '__len__') and len(indices) < ndim(x)\n if _is_boolean(indices):\n x_new[indices] = values\n return x_new\n zip_indices = _is_iterable(indices) and _is_iterable(indices[0])\n len_indices = len(indices) if _is_iterable(indices) else 1\n if zip_indices:\n indices = tuple(zip(*indices))\n if not use_vectorization:\n if not zip_indices:\n len_indices = len(indices) if _is_iterable(indices) else 1\n len_values = len(values) if _is_iterable(values) else 1\n if len_values > 1 and len_values != len_indices:\n raise ValueError('Either one value or as many values as indices')\n x_new[indices] = values\n else:\n indices = tuple(\n list(indices[:axis]) + [slice(None)] + list(indices[axis:]))\n x_new[indices] = values\n return x_new\n\n\ndef assignment_by_sum(x, values, indices, axis=0):\n \"\"\"Add values at given indices of an array.\n\n Parameters\n ----------\n x: array-like, shape=[dim]\n Initial array.\n values: {float, list(float)}\n Value or list of values to be assigned.\n indices: {int, tuple, list(int), list(tuple)}\n Single int or tuple, or list of ints or tuples of indices where value\n is assigned.\n If the length of the tuples is shorter than ndim(x), values are\n assigned to each copy along axis.\n axis: int, optional\n Axis along which values are assigned, if vectorized.\n\n Returns\n -------\n x_new : array-like, shape=[dim]\n Copy of x with the values assigned at the given indices.\n\n Notes\n -----\n If a single value is provided, it is assigned at all the indices.\n If a list is given, it must have the same length as indices.\n \"\"\"\n x_new = copy(x)\n values = array(values)\n use_vectorization = hasattr(indices, '__len__') and len(indices) < ndim(x)\n if _is_boolean(indices):\n x_new[indices] += values\n return x_new\n zip_indices = _is_iterable(indices) and _is_iterable(indices[0])\n if zip_indices:\n indices = list(zip(*indices))\n if not use_vectorization:\n len_indices = len(indices) if _is_iterable(indices) else 1\n len_values = len(values) if _is_iterable(values) else 1\n if len_values > 1 and len_values != len_indices:\n raise ValueError('Either one value or as many values as indices')\n x_new[indices] += values\n else:\n indices = tuple(\n list(indices[:axis]) + [slice(None)] + list(indices[axis:]))\n x_new[indices] += values\n return x_new\n\n\ndef copy(x):\n return x.clone()\n\n\ndef cumsum(x, axis=None):\n if not torch.is_tensor(x):\n x = array(x)\n if axis is None:\n return x.flatten().cumsum(dim=0)\n return torch.cumsum(x, dim=axis)\n\n\ndef cumprod(x, axis=None):\n if axis is None:\n axis = 0\n return torch.cumprod(x, axis)\n\n\ndef array_from_sparse(indices, data, target_shape):\n \"\"\"Create an array of given shape, with values at specific indices.\n\n The rest of the array will be filled with zeros.\n\n Parameters\n ----------\n indices : iterable(tuple(int))\n Index of each element which will be assigned a specific value.\n data : iterable(scalar)\n Value associated at each index.\n target_shape : tuple(int)\n Shape of the output array.\n\n Returns\n -------\n a : array, shape=target_shape\n Array of zeros with specified values assigned to specified indices.\n \"\"\"\n return torch.sparse.FloatTensor(\n torch.LongTensor(indices).t(),\n torch.FloatTensor(cast(data, float32)),\n torch.Size(target_shape)).to_dense()\n\n\ndef vectorize(x, pyfunc, multiple_args=False, **kwargs):\n if multiple_args:\n return stack(list(map(lambda y: pyfunc(*y), zip(*x))))\n return stack(list(map(pyfunc, x)))\n\n\ndef triu_to_vec(x, k=0):\n n = x.shape[-1]\n rows, cols = triu_indices(n, k=k)\n return x[..., rows, cols]\n\n\ndef mat_from_diag_triu_tril(diag, tri_upp, tri_low):\n \"\"\"Build matrix from given components.\n\n Forms a matrix from diagonal, strictly upper triangular and\n strictly lower traingular parts.\n\n Parameters\n ----------\n diag : array_like, shape=[..., n]\n tri_upp : array_like, shape=[..., (n * (n - 1)) / 2]\n tri_low : array_like, shape=[..., (n * (n - 1)) / 2]\n\n Returns\n -------\n mat : array_like, shape=[..., n, n]\n \"\"\"\n n = diag.shape[-1]\n i, = diag_indices(n, ndim=1)\n j, k = triu_indices(n, k=1)\n mat = torch.zeros((diag.shape + (n, )))\n mat[..., i, i] = diag\n mat[..., j, k] = tri_upp\n mat[..., k, j] = tri_low\n return mat\n" ]
[ [ "torch.all", "torch.cat", "torch.zeros", "numpy.diag_indices", "torch.sum", "torch.le", "torch.where", "torch.split", "torch.cumprod", "torch.allclose", "torch.logical_and", "torch.t", "torch.isclose", "torch.Size", "torch.sqrt", "torch.einsum", "torch.eq", "torch.eye", "torch.from_numpy", "torch.tensor", "numpy.insert", "torch.triu_indices", "torch.prod", "torch.squeeze", "torch.linspace", "torch.LongTensor", "torch.empty", "torch.is_tensor", "torch.unsqueeze", "torch.tril_indices", "numpy.append", "torch.stack", "torch.flip", "numpy.array", "torch.diagonal", "torch.Tensor", "torch.any", "numpy.prod", "torch.nn.functional.one_hot", "torch.cumsum", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pomonam/AttentionCluster
[ "7dd11bcc5e4a5572fcd4b14c6450602e922ac9b7" ]
[ "utils.py" ]
[ "# Copyright 2018 Google Inc., Juhan Bae 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\"\"\"Contains a collection of util functions for training and evaluating. \"\"\"\n\nfrom tensorflow import logging\nimport numpy\nimport tensorflow as tf\n\ntry:\n xrange # Python 2\nexcept NameError:\n xrange = range # Python 3\n\n\ndef Dequantize(feat_vector, max_quantized_value=2, min_quantized_value=-2):\n \"\"\"Dequantize the feature from the byte format to the float format.\n\n Args:\n feat_vector: the input 1-d vector.\n max_quantized_value: the maximum of the quantized value.\n min_quantized_value: the minimum of the quantized value.\n\n Returns:\n A float vector which has the same shape as feat_vector.\n \"\"\"\n assert max_quantized_value > min_quantized_value\n quantized_range = max_quantized_value - min_quantized_value\n scalar = quantized_range / 255.0\n bias = (quantized_range / 512.0) + min_quantized_value\n return feat_vector * scalar + bias\n\n\ndef MakeSummary(name, value):\n \"\"\"Creates a tf.Summary proto with the given name and value.\"\"\"\n summary = tf.Summary()\n val = summary.value.add()\n val.tag = str(name)\n val.simple_value = float(value)\n return summary\n\n\ndef AddGlobalStepSummary(summary_writer,\n global_step_val,\n global_step_info_dict,\n summary_scope=\"Eval\"):\n \"\"\"Add the global_step summary to the Tensorboard.\n\n Args:\n summary_writer: Tensorflow summary_writer.\n global_step_val: a int value of the global step.\n global_step_info_dict: a dictionary of the evaluation metrics calculated for\n a mini-batch.\n summary_scope: Train or Eval.\n\n Returns:\n A string of this global_step summary\n \"\"\"\n this_hit_at_one = global_step_info_dict[\"hit_at_one\"]\n this_perr = global_step_info_dict[\"perr\"]\n this_loss = global_step_info_dict[\"loss\"]\n examples_per_second = global_step_info_dict.get(\"examples_per_second\", -1)\n\n summary_writer.add_summary(\n MakeSummary(\"GlobalStep/\" + summary_scope + \"_Hit@1\", this_hit_at_one),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"GlobalStep/\" + summary_scope + \"_Perr\", this_perr),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"GlobalStep/\" + summary_scope + \"_Loss\", this_loss),\n global_step_val)\n\n if examples_per_second != -1:\n summary_writer.add_summary(\n MakeSummary(\"GlobalStep/\" + summary_scope + \"_Example_Second\",\n examples_per_second), global_step_val)\n\n summary_writer.flush()\n info = (\"global_step {0} | Batch Hit@1: {1:.3f} | Batch PERR: {2:.3f} | Batch Loss: {3:.3f} \"\n \"| Examples_per_sec: {4:.3f}\").format(\n global_step_val, this_hit_at_one, this_perr, this_loss,\n examples_per_second)\n return info\n\n\ndef AddEpochSummary(summary_writer,\n global_step_val,\n epoch_info_dict,\n summary_scope=\"Eval\"):\n \"\"\"Add the epoch summary to the Tensorboard.\n\n Args:\n summary_writer: TensorFlow summary_writer.\n global_step_val: a int value of the global step.\n epoch_info_dict: a dictionary of the evaluation metrics calculated for the\n whole epoch.\n summary_scope: Train or Eval.\n\n Returns:\n A string of this global_step summary\n \"\"\"\n epoch_id = epoch_info_dict[\"epoch_id\"]\n avg_hit_at_one = epoch_info_dict[\"avg_hit_at_one\"]\n avg_perr = epoch_info_dict[\"avg_perr\"]\n avg_loss = epoch_info_dict[\"avg_loss\"]\n aps = epoch_info_dict[\"aps\"]\n gap = epoch_info_dict[\"gap\"]\n mean_ap = numpy.mean(aps)\n\n summary_writer.add_summary(\n MakeSummary(\"Epoch/\" + summary_scope + \"_Avg_Hit@1\", avg_hit_at_one),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"Epoch/\" + summary_scope + \"_Avg_Perr\", avg_perr),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"Epoch/\" + summary_scope + \"_Avg_Loss\", avg_loss),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"Epoch/\" + summary_scope + \"_MAP\", mean_ap),\n global_step_val)\n summary_writer.add_summary(\n MakeSummary(\"Epoch/\" + summary_scope + \"_GAP\", gap),\n global_step_val)\n summary_writer.flush()\n\n info = (\"epoch/eval number {0} | Avg_Hit@1: {1:.3f} | Avg_PERR: {2:.3f} \"\n \"| MAP: {3:.3f} | GAP: {4:.3f} | Avg_Loss: {5:3f}\").format(\n epoch_id, avg_hit_at_one, avg_perr, mean_ap, gap, avg_loss)\n return info\n\n\ndef GetListOfFeatureNamesAndSizes(feature_names, feature_sizes):\n \"\"\"Extract the list of feature names and the dimensionality of each feature\n from string of comma separated values.\n\n Args:\n feature_names: string containing comma separated list of feature names\n feature_sizes: string containing comma separated list of feature sizes\n\n Returns:\n List of the feature names and list of the dimensionality of each feature.\n Elements in the first/second list are strings/integers.\n \"\"\"\n list_of_feature_names = [\n feature_names.strip() for feature_names in feature_names.split(',')]\n list_of_feature_sizes = [\n int(feature_sizes) for feature_sizes in feature_sizes.split(',')]\n if len(list_of_feature_names) != len(list_of_feature_sizes):\n logging.error(\"length of the feature names (=\" +\n str(len(list_of_feature_names)) + \") != length of feature \"\n \"sizes (=\" + str(len(list_of_feature_sizes)) + \")\")\n\n return list_of_feature_names, list_of_feature_sizes\n\n\ndef clip_gradient_norms(gradients_to_variables, max_norm):\n \"\"\"Clips the gradients by the given value.\n\n Args:\n gradients_to_variables: A list of gradient to variable pairs (tuples).\n max_norm: the maximum norm value.\n\n Returns:\n A list of clipped gradient to variable pairs.\n \"\"\"\n clipped_grads_and_vars = []\n for grad, var in gradients_to_variables:\n if grad is not None:\n if isinstance(grad, tf.IndexedSlices):\n tmp = tf.clip_by_norm(grad.values, max_norm)\n grad = tf.IndexedSlices(tmp, grad.indices, grad.dense_shape)\n else:\n grad = tf.clip_by_norm(grad, max_norm)\n clipped_grads_and_vars.append((grad, var))\n return clipped_grads_and_vars\n\n\ndef combine_gradients(tower_grads):\n \"\"\"Calculate the combined gradient for each shared variable across all towers.\n\n Note that this function provides a synchronization point across all towers.\n\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n Returns:\n List of pairs of (gradient, variable) where the gradient has been summed\n across all towers.\n \"\"\"\n filtered_grads = [[x for x in grad_list if x[0] is not None] for grad_list in tower_grads]\n final_grads = []\n for i in xrange(len(filtered_grads[0])):\n grads = [filtered_grads[t][i] for t in xrange(len(filtered_grads))]\n grad = tf.stack([x[0] for x in grads], 0)\n grad = tf.reduce_sum(grad, 0)\n final_grads.append((grad, filtered_grads[0][i][1],))\n\n return final_grads\n" ]
[ [ "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.clip_by_norm", "numpy.mean", "tensorflow.IndexedSlices", "tensorflow.Summary" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xiqicpt/VNPY-Master
[ "d3b8b945bc534d5e0bd8bf9cc9fdf0069e31a9cd" ]
[ "vnpy/app/cta_strategy/backtesting.py" ]
[ "from collections import defaultdict\nfrom datetime import date, datetime, timedelta\nfrom typing import Callable\nfrom itertools import product\nfrom functools import lru_cache\nfrom time import time\nimport multiprocessing\nimport random\nimport traceback\nfrom platform import system\n\nimport numpy as np\nfrom pandas import DataFrame\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom deap import creator, base, tools, algorithms\n\nfrom vnpy.trader.constant import (Direction, Offset, Exchange,\n Interval, Status)\nfrom vnpy.trader.database import database_manager\nfrom vnpy.trader.object import OrderData, TradeData, BarData, TickData\nfrom vnpy.trader.utility import round_to\n\nfrom .base import (\n BacktestingMode,\n EngineType,\n STOPORDER_PREFIX,\n StopOrder,\n StopOrderStatus,\n INTERVAL_DELTA_MAP\n)\nfrom .template import CtaTemplate\n\n\n# Set deap algo\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\n\n\nclass OptimizationSetting:\n \"\"\"\n Setting for runnning optimization.\n \"\"\"\n\n def __init__(self):\n \"\"\"\"\"\"\n self.params = {}\n self.target_name = \"\"\n\n def add_parameter(\n self, name: str, start: float, end: float = None, step: float = None\n ):\n \"\"\"\"\"\"\n if not end and not step:\n self.params[name] = [start]\n return\n\n if start >= end:\n print(\"参数优化起始点必须小于终止点\")\n return\n\n if step <= 0:\n print(\"参数优化步进必须大于0\")\n return\n\n value = start\n value_list = []\n\n while value <= end:\n value_list.append(value)\n value += step\n\n self.params[name] = value_list\n\n def set_target(self, target_name: str):\n \"\"\"\"\"\"\n self.target_name = target_name\n\n def generate_setting(self):\n \"\"\"\"\"\"\n keys = self.params.keys()\n values = self.params.values()\n products = list(product(*values))\n\n settings = []\n for p in products:\n setting = dict(zip(keys, p))\n settings.append(setting)\n\n return settings\n\n def generate_setting_ga(self):\n \"\"\"\"\"\"\n settings_ga = []\n settings = self.generate_setting()\n for d in settings:\n param = [tuple(i) for i in d.items()]\n settings_ga.append(param)\n return settings_ga\n\n\nclass BacktestingEngine:\n \"\"\"\"\"\"\n\n engine_type = EngineType.BACKTESTING\n gateway_name = \"BACKTESTING\"\n\n def __init__(self):\n \"\"\"\"\"\"\n self.vt_symbol = \"\"\n self.symbol = \"\"\n self.exchange = None\n self.start = None\n self.end = None\n self.rate = 0\n self.slippage = 0\n self.size = 1\n self.pricetick = 0\n self.capital = 1_000_000\n self.risk_free: float = 0.02\n self.mode = BacktestingMode.BAR\n self.inverse = False\n\n self.strategy_class = None\n self.strategy = None\n self.tick: TickData\n self.bar: BarData\n self.datetime = None\n\n self.interval = None\n self.days = 0\n self.callback = None\n self.history_data = []\n\n self.stop_order_count = 0\n self.stop_orders = {}\n self.active_stop_orders = {}\n\n self.limit_order_count = 0\n self.limit_orders = {}\n self.active_limit_orders = {}\n\n self.trade_count = 0\n self.trades = {}\n\n self.logs = []\n\n self.daily_results = {}\n self.daily_df = None\n\n def clear_data(self):\n \"\"\"\n Clear all data of last backtesting.\n \"\"\"\n self.strategy = None\n self.tick = None\n self.bar = None\n self.datetime = None\n\n self.stop_order_count = 0\n self.stop_orders.clear()\n self.active_stop_orders.clear()\n\n self.limit_order_count = 0\n self.limit_orders.clear()\n self.active_limit_orders.clear()\n\n self.trade_count = 0\n self.trades.clear()\n\n self.logs.clear()\n self.daily_results.clear()\n\n def set_parameters(\n self,\n vt_symbol: str,\n interval: Interval,\n start: datetime,\n rate: float,\n slippage: float,\n size: float,\n pricetick: float,\n capital: int = 0,\n end: datetime = None,\n mode: BacktestingMode = BacktestingMode.BAR,\n inverse: bool = False,\n risk_free: float = 0,\n collection_name: str = None\n ):\n \"\"\"\"\"\"\n self.mode = mode\n self.vt_symbol = vt_symbol\n self.interval = Interval(interval)\n self.rate = rate\n self.slippage = slippage\n self.size = size\n self.pricetick = pricetick\n self.start = start\n\n self.symbol, exchange_str = self.vt_symbol.split(\".\")\n self.exchange = Exchange(exchange_str)\n\n self.capital = capital\n self.end = end\n self.mode = mode\n self.inverse = inverse\n self.risk_free = risk_free\n self.collection_name = collection_name\n\n def add_strategy(self, strategy_class: type, setting: dict):\n \"\"\"\"\"\"\n self.strategy_class = strategy_class\n self.strategy = strategy_class(\n self, strategy_class.__name__, self.vt_symbol, setting\n )\n\n def load_data(self):\n \"\"\"\"\"\"\n self.output(\"开始加载历史数据\")\n\n if not self.end:\n self.end = datetime.now()\n\n if self.start >= self.end:\n self.output(\"起始日期必须小于结束日期\")\n return\n\n self.history_data.clear() # Clear previously loaded history data\n\n # Load 30 days of data each time and allow for progress update\n total_days = (self.end - self.start).days\n progress_days = max(int(total_days / 10), 1)\n progress_delta = timedelta(days=progress_days)\n interval_delta = INTERVAL_DELTA_MAP[self.interval]\n\n start = self.start\n end = self.start + progress_delta\n progress = 0\n\n while start < self.end:\n progress_bar = \"#\" * int(progress * 10 + 1)\n self.output(f\"加载进度:{progress_bar} [{progress:.0%}]\")\n\n end = min(end, self.end) # Make sure end time stays within set range\n\n if self.mode == BacktestingMode.BAR:\n data = load_bar_data(\n self.symbol,\n self.exchange,\n self.interval,\n start,\n end,\n collection_name = self.collection_name\n )\n else:\n data = load_tick_data(\n self.symbol,\n self.exchange,\n start,\n end,\n collection_name = self.collection_name\n )\n\n self.history_data.extend(data)\n\n progress += progress_days / total_days\n progress = min(progress, 1)\n\n start = end + interval_delta\n end += progress_delta\n\n self.output(f\"历史数据加载完成,数据量:{len(self.history_data)}\")\n\n def run_backtesting(self):\n \"\"\"\"\"\"\n if self.mode == BacktestingMode.BAR:\n func = self.new_bar\n else:\n func = self.new_tick\n\n self.strategy.on_init()\n\n # Use the first [days] of history data for initializing strategy\n day_count = 1\n ix = 0\n\n for ix, data in enumerate(self.history_data):\n if self.datetime and data.datetime.day != self.datetime.day:\n day_count += 1\n if day_count >= self.days:\n break\n\n self.datetime = data.datetime\n\n try:\n self.callback(data)\n except Exception:\n self.output(\"触发异常,回测终止\")\n self.output(traceback.format_exc())\n return\n\n self.strategy.inited = True\n self.output(\"策略初始化完成\")\n\n self.strategy.on_start()\n self.strategy.trading = True\n self.output(\"开始回放历史数据\")\n\n # Use the rest of history data for running backtesting\n backtesting_data = self.history_data[ix + 1:]\n if not backtesting_data:\n self.output(\"历史数据不足,回测终止\")\n return\n\n total_size = len(backtesting_data)\n batch_size = max(int(total_size / 10), 1)\n\n for ix, i in enumerate(range(0, total_size, batch_size)):\n batch_data = backtesting_data[i: i + batch_size]\n for data in batch_data:\n try:\n func(data)\n except Exception:\n self.output(\"触发异常,回测终止\")\n self.output(traceback.format_exc())\n return\n\n progress = min(ix / 10, 1)\n progress_bar = \"=\" * (ix + 1)\n self.output(f\"回放进度:{progress_bar} [{progress:.0%}]\")\n\n self.strategy.on_stop()\n self.output(\"历史数据回放结束\")\n\n def calculate_result(self):\n \"\"\"\"\"\"\n self.output(\"开始计算逐日盯市盈亏\")\n\n if not self.trades:\n self.output(\"成交记录为空,无法计算\")\n return\n\n # Add trade data into daily reuslt.\n for trade in self.trades.values():\n d = trade.datetime.date()\n daily_result = self.daily_results[d]\n daily_result.add_trade(trade)\n\n # Calculate daily result by iteration.\n pre_close = 0\n start_pos = 0\n\n for daily_result in self.daily_results.values():\n daily_result.calculate_pnl(\n pre_close,\n start_pos,\n self.size,\n self.rate,\n self.slippage,\n self.inverse\n )\n\n pre_close = daily_result.close_price\n start_pos = daily_result.end_pos\n\n # Generate dataframe\n results = defaultdict(list)\n\n for daily_result in self.daily_results.values():\n for key, value in daily_result.__dict__.items():\n results[key].append(value)\n\n self.daily_df = DataFrame.from_dict(results).set_index(\"date\")\n\n self.output(\"逐日盯市盈亏计算完成\")\n return self.daily_df\n\n def calculate_statistics(self, df: DataFrame = None, output=True):\n \"\"\"\"\"\"\n self.output(\"开始计算策略统计指标\")\n\n # Check DataFrame input exterior\n if df is None:\n df = self.daily_df\n\n # Check for init DataFrame\n if df is None:\n # Set all statistics to 0 if no trade.\n start_date = \"\"\n end_date = \"\"\n total_days = 0\n profit_days = 0\n loss_days = 0\n end_balance = 0\n max_drawdown = 0\n max_ddpercent = 0\n max_drawdown_duration = 0\n total_net_pnl = 0\n daily_net_pnl = 0\n total_commission = 0\n daily_commission = 0\n total_slippage = 0\n daily_slippage = 0\n total_turnover = 0\n daily_turnover = 0\n total_trade_count = 0\n daily_trade_count = 0\n total_return = 0\n annual_return = 0\n daily_return = 0\n return_std = 0\n sharpe_ratio = 0\n return_drawdown_ratio = 0\n else:\n # Calculate balance related time series data\n df[\"balance\"] = df[\"net_pnl\"].cumsum() + self.capital\n\n # When balance falls below 0, set daily return to 0\n x = df[\"balance\"] / df[\"balance\"].shift(1)\n x[x <= 0] = np.nan\n df[\"return\"] = np.log(x).fillna(0)\n\n df[\"highlevel\"] = (\n df[\"balance\"].rolling(\n min_periods=1, window=len(df), center=False).max()\n )\n df[\"drawdown\"] = df[\"balance\"] - df[\"highlevel\"]\n df[\"ddpercent\"] = df[\"drawdown\"] / df[\"highlevel\"] * 100\n\n # Calculate statistics value\n start_date = df.index[0]\n end_date = df.index[-1]\n\n total_days = len(df)\n profit_days = len(df[df[\"net_pnl\"] > 0])\n loss_days = len(df[df[\"net_pnl\"] < 0])\n\n end_balance = df[\"balance\"].iloc[-1]\n max_drawdown = df[\"drawdown\"].min()\n max_ddpercent = df[\"ddpercent\"].min()\n max_drawdown_end = df[\"drawdown\"].idxmin()\n\n if isinstance(max_drawdown_end, date):\n max_drawdown_start = df[\"balance\"][:max_drawdown_end].idxmax()\n max_drawdown_duration = (max_drawdown_end - max_drawdown_start).days\n else:\n max_drawdown_duration = 0\n\n total_net_pnl = df[\"net_pnl\"].sum()\n daily_net_pnl = total_net_pnl / total_days\n\n total_commission = df[\"commission\"].sum()\n daily_commission = total_commission / total_days\n\n total_slippage = df[\"slippage\"].sum()\n daily_slippage = total_slippage / total_days\n\n total_turnover = df[\"turnover\"].sum()\n daily_turnover = total_turnover / total_days\n\n total_trade_count = df[\"trade_count\"].sum()\n daily_trade_count = total_trade_count / total_days\n\n total_return = (end_balance / self.capital - 1) * 100\n annual_return = total_return / total_days * 240\n daily_return = df[\"return\"].mean() * 100\n return_std = df[\"return\"].std() * 100\n\n if return_std:\n daily_risk_free = self.risk_free / np.sqrt(240)\n sharpe_ratio = (daily_return - daily_risk_free) / return_std * np.sqrt(240)\n else:\n sharpe_ratio = 0\n\n return_drawdown_ratio = -total_return / max_ddpercent\n\n # Output\n if output:\n self.output(\"-\" * 30)\n self.output(f\"首个交易日:\\t{start_date}\")\n self.output(f\"最后交易日:\\t{end_date}\")\n\n self.output(f\"总交易日:\\t{total_days}\")\n self.output(f\"盈利交易日:\\t{profit_days}\")\n self.output(f\"亏损交易日:\\t{loss_days}\")\n\n self.output(f\"起始资金:\\t{self.capital:,.2f}\")\n self.output(f\"结束资金:\\t{end_balance:,.2f}\")\n\n self.output(f\"总收益率:\\t{total_return:,.2f}%\")\n self.output(f\"年化收益:\\t{annual_return:,.2f}%\")\n self.output(f\"最大回撤: \\t{max_drawdown:,.2f}\")\n self.output(f\"百分比最大回撤: {max_ddpercent:,.2f}%\")\n self.output(f\"最长回撤天数: \\t{max_drawdown_duration}\")\n\n self.output(f\"总盈亏:\\t{total_net_pnl:,.2f}\")\n self.output(f\"总手续费:\\t{total_commission:,.2f}\")\n self.output(f\"总滑点:\\t{total_slippage:,.2f}\")\n self.output(f\"总成交金额:\\t{total_turnover:,.2f}\")\n self.output(f\"总成交笔数:\\t{total_trade_count}\")\n\n self.output(f\"日均盈亏:\\t{daily_net_pnl:,.2f}\")\n self.output(f\"日均手续费:\\t{daily_commission:,.2f}\")\n self.output(f\"日均滑点:\\t{daily_slippage:,.2f}\")\n self.output(f\"日均成交金额:\\t{daily_turnover:,.2f}\")\n self.output(f\"日均成交笔数:\\t{daily_trade_count}\")\n\n self.output(f\"日均收益率:\\t{daily_return:,.2f}%\")\n self.output(f\"收益标准差:\\t{return_std:,.2f}%\")\n self.output(f\"Sharpe Ratio:\\t{sharpe_ratio:,.2f}\")\n self.output(f\"收益回撤比:\\t{return_drawdown_ratio:,.2f}\")\n\n statistics = {\n \"start_date\": start_date,\n \"end_date\": end_date,\n \"total_days\": total_days,\n \"profit_days\": profit_days,\n \"loss_days\": loss_days,\n \"capital\": self.capital,\n \"end_balance\": end_balance,\n \"max_drawdown\": max_drawdown,\n \"max_ddpercent\": max_ddpercent,\n \"max_drawdown_duration\": max_drawdown_duration,\n \"total_net_pnl\": total_net_pnl,\n \"daily_net_pnl\": daily_net_pnl,\n \"total_commission\": total_commission,\n \"daily_commission\": daily_commission,\n \"total_slippage\": total_slippage,\n \"daily_slippage\": daily_slippage,\n \"total_turnover\": total_turnover,\n \"daily_turnover\": daily_turnover,\n \"total_trade_count\": total_trade_count,\n \"daily_trade_count\": daily_trade_count,\n \"total_return\": total_return,\n \"annual_return\": annual_return,\n \"daily_return\": daily_return,\n \"return_std\": return_std,\n \"sharpe_ratio\": sharpe_ratio,\n \"return_drawdown_ratio\": return_drawdown_ratio,\n }\n\n # Filter potential error infinite value\n for key, value in statistics.items():\n if value in (np.inf, -np.inf):\n value = 0\n statistics[key] = np.nan_to_num(value)\n\n self.output(\"策略统计指标计算完成\")\n return statistics\n\n def show_chart(self, df: DataFrame = None):\n \"\"\"\"\"\"\n # Check DataFrame input exterior\n if df is None:\n df = self.daily_df\n\n # Check for init DataFrame\n if df is None:\n return\n\n fig = make_subplots(\n rows=4,\n cols=1,\n subplot_titles=[\"Balance\", \"Drawdown\", \"Daily Pnl\", \"Pnl Distribution\"],\n vertical_spacing=0.06\n )\n\n balance_line = go.Scatter(\n x=df.index,\n y=df[\"balance\"],\n mode=\"lines\",\n name=\"Balance\"\n )\n drawdown_scatter = go.Scatter(\n x=df.index,\n y=df[\"drawdown\"],\n fillcolor=\"red\",\n fill='tozeroy',\n mode=\"lines\",\n name=\"Drawdown\"\n )\n pnl_bar = go.Bar(y=df[\"net_pnl\"], name=\"Daily Pnl\")\n pnl_histogram = go.Histogram(x=df[\"net_pnl\"], nbinsx=100, name=\"Days\")\n\n fig.add_trace(balance_line, row=1, col=1)\n fig.add_trace(drawdown_scatter, row=2, col=1)\n fig.add_trace(pnl_bar, row=3, col=1)\n fig.add_trace(pnl_histogram, row=4, col=1)\n\n fig.update_layout(height=1000, width=1000)\n if system() == 'Linux':\n fig.show(renderer=\"iframe\")\n else:\n fig.show()\n\n def run_optimization(self, optimization_setting: OptimizationSetting, output=True):\n \"\"\"\"\"\"\n # Get optimization setting and target\n settings = optimization_setting.generate_setting()\n target_name = optimization_setting.target_name\n\n if not settings:\n self.output(\"优化参数组合为空,请检查\")\n return\n\n if not target_name:\n self.output(\"优化目标未设置,请检查\")\n return\n\n # Use multiprocessing pool for running backtesting with different setting\n # Force to use spawn method to create new process (instead of fork on Linux)\n # ctx = multiprocessing.get_context(\"spawn\")\n # pool = ctx.Pool(multiprocessing.cpu_count())\n from concurrent.futures import ThreadPoolExecutor\n\n results = []\n with ThreadPoolExecutor(10) as executor:\n for setting in settings:\n result = executor.submit(optimize,\n target_name,\n self.strategy_class,\n setting,\n self.vt_symbol,\n self.interval,\n self.start,\n self.rate,\n self.slippage,\n self.size,\n self.pricetick,\n self.capital,\n self.end,\n self.mode,\n self.inverse,\n self.collection_name\n )\n results.append(result)\n\n # pool.close()\n # pool.join()\n\n # Sort results and output\n # result_values = [result.get() for result in results]\n result_values = [exe.result() for exe in results]\n result_values.sort(reverse=True, key=lambda result: result[1])\n\n if output:\n for value in result_values:\n msg = f\"参数:{value[0]}, 目标:{value[1]}\"\n self.output(msg)\n\n return result_values\n\n def run_ga_optimization(self, optimization_setting: OptimizationSetting, population_size=100, ngen_size=30, output=True):\n \"\"\"\"\"\"\n # Clear lru_cache before running ga optimization\n _ga_optimize.cache_clear()\n\n # Get optimization setting and target\n settings = optimization_setting.generate_setting_ga()\n target_name = optimization_setting.target_name\n\n if not settings:\n self.output(\"优化参数组合为空,请检查\")\n return\n\n if not target_name:\n self.output(\"优化目标未设置,请检查\")\n return\n\n # Define parameter generation function\n def generate_parameter():\n \"\"\"\"\"\"\n return random.choice(settings)\n\n def mutate_individual(individual, indpb):\n \"\"\"\"\"\"\n size = len(individual)\n paramlist = generate_parameter()\n for i in range(size):\n if random.random() < indpb:\n individual[i] = paramlist[i]\n return individual,\n\n # Create ga object function\n global ga_target_name\n global ga_strategy_class\n global ga_setting\n global ga_vt_symbol\n global ga_interval\n global ga_start\n global ga_rate\n global ga_slippage\n global ga_size\n global ga_pricetick\n global ga_capital\n global ga_end\n global ga_mode\n global ga_inverse\n\n ga_target_name = target_name\n ga_strategy_class = self.strategy_class\n ga_setting = settings[0]\n ga_vt_symbol = self.vt_symbol\n ga_interval = self.interval\n ga_start = self.start\n ga_rate = self.rate\n ga_slippage = self.slippage\n ga_size = self.size\n ga_pricetick = self.pricetick\n ga_capital = self.capital\n ga_end = self.end\n ga_mode = self.mode\n ga_inverse = self.inverse\n\n # Set up genetic algorithm\n toolbox = base.Toolbox()\n toolbox.register(\"individual\", tools.initIterate, creator.Individual, generate_parameter)\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n toolbox.register(\"mate\", tools.cxTwoPoint)\n toolbox.register(\"mutate\", mutate_individual, indpb=1)\n toolbox.register(\"evaluate\", ga_optimize)\n toolbox.register(\"select\", tools.selNSGA2)\n\n total_size = len(settings)\n pop_size = population_size # number of individuals in each generation\n lambda_ = pop_size # number of children to produce at each generation\n mu = int(pop_size * 0.8) # number of individuals to select for the next generation\n\n cxpb = 0.95 # probability that an offspring is produced by crossover\n mutpb = 1 - cxpb # probability that an offspring is produced by mutation\n ngen = ngen_size # number of generation\n\n pop = toolbox.population(pop_size)\n hof = tools.ParetoFront() # end result of pareto front\n\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n np.set_printoptions(suppress=True)\n stats.register(\"mean\", np.mean, axis=0)\n stats.register(\"std\", np.std, axis=0)\n stats.register(\"min\", np.min, axis=0)\n stats.register(\"max\", np.max, axis=0)\n\n # Multiprocessing is not supported yet.\n # pool = multiprocessing.Pool(multiprocessing.cpu_count())\n # toolbox.register(\"map\", pool.map)\n\n # Run ga optimization\n self.output(f\"参数优化空间:{total_size}\")\n self.output(f\"每代族群总数:{pop_size}\")\n self.output(f\"优良筛选个数:{mu}\")\n self.output(f\"迭代次数:{ngen}\")\n self.output(f\"交叉概率:{cxpb:.0%}\")\n self.output(f\"突变概率:{mutpb:.0%}\")\n\n start = time()\n\n algorithms.eaMuPlusLambda(\n pop,\n toolbox,\n mu,\n lambda_,\n cxpb,\n mutpb,\n ngen,\n stats,\n halloffame=hof\n )\n\n end = time()\n cost = int((end - start))\n\n self.output(f\"遗传算法优化完成,耗时{cost}秒\")\n\n # Return result list\n results = []\n\n for parameter_values in hof:\n setting = dict(parameter_values)\n target_value = ga_optimize(parameter_values, self.collection_name)[0]\n results.append((setting, target_value, {}))\n\n return results\n\n def update_daily_close(self, price: float):\n \"\"\"\"\"\"\n d = self.datetime.date()\n\n daily_result = self.daily_results.get(d, None)\n if daily_result:\n daily_result.close_price = price\n else:\n self.daily_results[d] = DailyResult(d, price)\n\n def new_bar(self, bar: BarData):\n \"\"\"\"\"\"\n self.bar = bar\n self.datetime = bar.datetime\n\n self.cross_limit_order()\n self.cross_stop_order()\n self.strategy.on_bar(bar)\n\n self.update_daily_close(bar.close_price)\n\n def new_tick(self, tick: TickData):\n \"\"\"\"\"\"\n self.tick = tick\n self.datetime = tick.datetime\n\n self.cross_limit_order()\n self.cross_stop_order()\n self.strategy.on_tick(tick)\n\n self.update_daily_close(tick.last_price)\n\n def cross_limit_order(self):\n \"\"\"\n Cross limit order with last bar/tick data.\n \"\"\"\n if self.mode == BacktestingMode.BAR:\n long_cross_price = self.bar.low_price\n short_cross_price = self.bar.high_price\n long_best_price = self.bar.open_price\n short_best_price = self.bar.open_price\n else:\n long_cross_price = self.tick.ask_price_1\n short_cross_price = self.tick.bid_price_1\n long_best_price = long_cross_price\n short_best_price = short_cross_price\n\n for order in list(self.active_limit_orders.values()):\n # Push order update with status \"not traded\" (pending).\n if order.status == Status.SUBMITTING:\n order.status = Status.NOTTRADED\n self.strategy.on_order(order)\n\n # Check whether limit orders can be filled.\n long_cross = (\n order.direction == Direction.LONG\n and order.price >= long_cross_price\n and long_cross_price > 0\n )\n\n short_cross = (\n order.direction == Direction.SHORT\n and order.price <= short_cross_price\n and short_cross_price > 0\n )\n\n if not long_cross and not short_cross:\n continue\n\n # Push order udpate with status \"all traded\" (filled).\n order.traded = order.volume\n order.status = Status.ALLTRADED\n self.strategy.on_order(order)\n\n self.active_limit_orders.pop(order.vt_orderid)\n\n # Push trade update\n self.trade_count += 1\n\n if long_cross:\n trade_price = min(order.price, long_best_price)\n pos_change = order.volume\n else:\n trade_price = max(order.price, short_best_price)\n pos_change = -order.volume\n\n trade = TradeData(\n symbol=order.symbol,\n exchange=order.exchange,\n orderid=order.orderid,\n tradeid=str(self.trade_count),\n direction=order.direction,\n offset=order.offset,\n price=trade_price,\n volume=order.volume,\n datetime=self.datetime,\n gateway_name=self.gateway_name,\n )\n\n self.strategy.pos += pos_change\n self.strategy.on_trade(trade)\n\n self.trades[trade.vt_tradeid] = trade\n\n def cross_stop_order(self):\n \"\"\"\n Cross stop order with last bar/tick data.\n \"\"\"\n if self.mode == BacktestingMode.BAR:\n long_cross_price = self.bar.high_price\n short_cross_price = self.bar.low_price\n long_best_price = self.bar.open_price\n short_best_price = self.bar.open_price\n else:\n long_cross_price = self.tick.last_price\n short_cross_price = self.tick.last_price\n long_best_price = long_cross_price\n short_best_price = short_cross_price\n\n for stop_order in list(self.active_stop_orders.values()):\n # Check whether stop order can be triggered.\n long_cross = (\n stop_order.direction == Direction.LONG\n and stop_order.price <= long_cross_price\n )\n\n short_cross = (\n stop_order.direction == Direction.SHORT\n and stop_order.price >= short_cross_price\n )\n\n if not long_cross and not short_cross:\n continue\n\n # Create order data.\n self.limit_order_count += 1\n\n order = OrderData(\n symbol=self.symbol,\n exchange=self.exchange,\n orderid=str(self.limit_order_count),\n direction=stop_order.direction,\n offset=stop_order.offset,\n price=stop_order.price,\n volume=stop_order.volume,\n traded=stop_order.volume,\n status=Status.ALLTRADED,\n gateway_name=self.gateway_name,\n datetime=self.datetime\n )\n\n self.limit_orders[order.vt_orderid] = order\n\n # Create trade data.\n if long_cross:\n trade_price = max(stop_order.price, long_best_price)\n pos_change = order.volume\n else:\n trade_price = min(stop_order.price, short_best_price)\n pos_change = -order.volume\n\n self.trade_count += 1\n\n trade = TradeData(\n symbol=order.symbol,\n exchange=order.exchange,\n orderid=order.orderid,\n tradeid=str(self.trade_count),\n direction=order.direction,\n offset=order.offset,\n price=trade_price,\n volume=order.volume,\n datetime=self.datetime,\n gateway_name=self.gateway_name,\n )\n\n self.trades[trade.vt_tradeid] = trade\n\n # Update stop order.\n stop_order.vt_orderids.append(order.vt_orderid)\n stop_order.status = StopOrderStatus.TRIGGERED\n\n if stop_order.stop_orderid in self.active_stop_orders:\n self.active_stop_orders.pop(stop_order.stop_orderid)\n\n # Push update to strategy.\n self.strategy.on_stop_order(stop_order)\n self.strategy.on_order(order)\n\n self.strategy.pos += pos_change\n self.strategy.on_trade(trade)\n\n def load_bar(\n self,\n vt_symbol: str,\n days: int,\n interval: Interval,\n callback: Callable,\n use_database: bool\n ):\n \"\"\"\"\"\"\n self.days = days\n self.callback = callback\n\n def load_tick(self, vt_symbol: str, days: int, callback: Callable):\n \"\"\"\"\"\"\n self.days = days\n self.callback = callback\n\n def send_order(\n self,\n strategy: CtaTemplate,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n stop: bool,\n lock: bool\n ):\n \"\"\"\"\"\"\n if callable(self.pricetick):\n price = round_to(price, self.pricetick(price))\n else:\n price = round_to(price, self.pricetick)\n if stop:\n vt_orderid = self.send_stop_order(direction, offset, price, volume)\n else:\n vt_orderid = self.send_limit_order(direction, offset, price, volume)\n return [vt_orderid]\n\n def send_stop_order(\n self,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float\n ):\n \"\"\"\"\"\"\n self.stop_order_count += 1\n\n stop_order = StopOrder(\n vt_symbol=self.vt_symbol,\n direction=direction,\n offset=offset,\n price=price,\n volume=volume,\n stop_orderid=f\"{STOPORDER_PREFIX}.{self.stop_order_count}\",\n strategy_name=self.strategy.strategy_name,\n )\n\n self.active_stop_orders[stop_order.stop_orderid] = stop_order\n self.stop_orders[stop_order.stop_orderid] = stop_order\n\n return stop_order.stop_orderid\n\n def send_limit_order(\n self,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float\n ):\n \"\"\"\"\"\"\n self.limit_order_count += 1\n\n order = OrderData(\n symbol=self.symbol,\n exchange=self.exchange,\n orderid=str(self.limit_order_count),\n direction=direction,\n offset=offset,\n price=price,\n volume=volume,\n status=Status.SUBMITTING,\n gateway_name=self.gateway_name,\n datetime=self.datetime\n )\n\n self.active_limit_orders[order.vt_orderid] = order\n self.limit_orders[order.vt_orderid] = order\n\n return order.vt_orderid\n\n def cancel_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\n Cancel order by vt_orderid.\n \"\"\"\n if vt_orderid.startswith(STOPORDER_PREFIX):\n self.cancel_stop_order(strategy, vt_orderid)\n else:\n self.cancel_limit_order(strategy, vt_orderid)\n\n def cancel_stop_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\"\"\"\n if vt_orderid not in self.active_stop_orders:\n return\n stop_order = self.active_stop_orders.pop(vt_orderid)\n\n stop_order.status = StopOrderStatus.CANCELLED\n self.strategy.on_stop_order(stop_order)\n\n def cancel_limit_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\"\"\"\n if vt_orderid not in self.active_limit_orders:\n return\n order = self.active_limit_orders.pop(vt_orderid)\n\n order.status = Status.CANCELLED\n self.strategy.on_order(order)\n\n def cancel_all(self, strategy: CtaTemplate):\n \"\"\"\n Cancel all orders, both limit and stop.\n \"\"\"\n vt_orderids = list(self.active_limit_orders.keys())\n for vt_orderid in vt_orderids:\n self.cancel_limit_order(strategy, vt_orderid)\n\n stop_orderids = list(self.active_stop_orders.keys())\n for vt_orderid in stop_orderids:\n self.cancel_stop_order(strategy, vt_orderid)\n\n def write_log(self, msg: str, strategy: CtaTemplate = None):\n \"\"\"\n Write log message.\n \"\"\"\n msg = f\"{self.datetime}\\t{msg}\"\n self.logs.append(msg)\n\n def send_email(self, msg: str, strategy: CtaTemplate = None):\n \"\"\"\n Send email to default receiver.\n \"\"\"\n pass\n\n def sync_strategy_data(self, strategy: CtaTemplate):\n \"\"\"\n Sync strategy data into json file.\n \"\"\"\n pass\n\n def get_engine_type(self):\n \"\"\"\n Return engine type.\n \"\"\"\n return self.engine_type\n\n def get_pricetick(self, strategy: CtaTemplate):\n \"\"\"\n Return contract pricetick data.\n \"\"\"\n return self.pricetick\n\n def put_strategy_event(self, strategy: CtaTemplate):\n \"\"\"\n Put an event to update strategy status.\n \"\"\"\n pass\n\n def output(self, msg):\n \"\"\"\n Output message of backtesting engine.\n \"\"\"\n print(f\"{datetime.now()}\\t{msg}\")\n\n def get_all_trades(self):\n \"\"\"\n Return all trade data of current backtesting result.\n \"\"\"\n return list(self.trades.values())\n\n def get_all_orders(self):\n \"\"\"\n Return all limit order data of current backtesting result.\n \"\"\"\n return list(self.limit_orders.values())\n\n def get_all_daily_results(self):\n \"\"\"\n Return all daily result data.\n \"\"\"\n return list(self.daily_results.values())\n\n\nclass DailyResult:\n \"\"\"\"\"\"\n\n def __init__(self, date: date, close_price: float):\n \"\"\"\"\"\"\n self.date = date\n self.close_price = close_price\n self.pre_close = 0\n\n self.trades = []\n self.trade_count = 0\n\n self.start_pos = 0\n self.end_pos = 0\n\n self.turnover = 0\n self.commission = 0\n self.slippage = 0\n\n self.trading_pnl = 0\n self.holding_pnl = 0\n self.total_pnl = 0\n self.net_pnl = 0\n\n def add_trade(self, trade: TradeData):\n \"\"\"\"\"\"\n self.trades.append(trade)\n\n def calculate_pnl(\n self,\n pre_close: float,\n start_pos: float,\n size: int,\n rate: float,\n slippage: float,\n inverse: bool\n ):\n \"\"\"\"\"\"\n # If no pre_close provided on the first day,\n # use value 1 to avoid zero division error\n if pre_close:\n self.pre_close = pre_close\n else:\n self.pre_close = 1\n\n # Holding pnl is the pnl from holding position at day start\n self.start_pos = start_pos\n self.end_pos = start_pos\n\n if not inverse: # For normal contract\n self.holding_pnl = self.start_pos * \\\n (self.close_price - self.pre_close) * size\n else: # For crypto currency inverse contract\n self.holding_pnl = self.start_pos * \\\n (1 / self.pre_close - 1 / self.close_price) * size\n\n # Trading pnl is the pnl from new trade during the day\n self.trade_count = len(self.trades)\n\n for trade in self.trades:\n if trade.direction == Direction.LONG:\n pos_change = trade.volume\n else:\n pos_change = -trade.volume\n\n self.end_pos += pos_change\n \n if callable(slippage): # For Taiwan Stock Market\n slippage = slippage(trade.price)\n\n # For normal contract\n if not inverse:\n turnover = trade.volume * size * trade.price\n self.trading_pnl += pos_change * \\\n (self.close_price - trade.price) * size\n self.slippage += trade.volume * size * slippage\n # For crypto currency inverse contract\n else:\n turnover = trade.volume * size / trade.price\n self.trading_pnl += pos_change * \\\n (1 / trade.price - 1 / self.close_price) * size\n self.slippage += trade.volume * size * slippage / (trade.price ** 2)\n\n self.turnover += turnover\n if callable(rate): # For Taiwan Stock Market\n self.commission += rate(cost=trade.price, multiplier=size, qty=trade.volume, direction=trade.direction)\n else:\n self.commission += turnover * rate\n\n # Net pnl takes account of commission and slippage cost\n self.total_pnl = self.trading_pnl + self.holding_pnl\n self.net_pnl = self.total_pnl - self.commission - self.slippage\n\n\ndef optimize(\n target_name: str,\n strategy_class: CtaTemplate,\n setting: dict,\n vt_symbol: str,\n interval: Interval,\n start: datetime,\n rate: float,\n slippage: float,\n size: float,\n pricetick: float,\n capital: int,\n end: datetime,\n mode: BacktestingMode,\n inverse: bool,\n colleciton_name:str = None\n):\n \"\"\"\n Function for running in multiprocessing.pool\n \"\"\"\n engine = BacktestingEngine()\n\n engine.set_parameters(\n vt_symbol=vt_symbol,\n interval=interval,\n start=start,\n rate=rate,\n slippage=slippage,\n size=size,\n pricetick=pricetick,\n capital=capital,\n end=end,\n mode=mode,\n inverse=inverse,\n collection_name=colleciton_name\n )\n\n engine.add_strategy(strategy_class, setting)\n engine.load_data()\n engine.run_backtesting()\n engine.calculate_result()\n statistics = engine.calculate_statistics(output=False)\n\n target_value = statistics[target_name]\n return (str(setting), target_value, statistics)\n\n\n@lru_cache(maxsize=1000000)\ndef _ga_optimize(parameter_values: tuple, collection_name:str=None):\n \"\"\"\"\"\"\n setting = dict(parameter_values)\n\n result = optimize(\n ga_target_name,\n ga_strategy_class,\n setting,\n ga_vt_symbol,\n ga_interval,\n ga_start,\n ga_rate,\n ga_slippage,\n ga_size,\n ga_pricetick,\n ga_capital,\n ga_end,\n ga_mode,\n ga_inverse,\n collection_name\n )\n return (result[1],)\n\n\ndef ga_optimize(parameter_values: list, collection_name:str=None):\n \"\"\"\"\"\"\n return _ga_optimize(tuple(parameter_values), collection_name)\n\n\n@lru_cache(maxsize=999)\ndef load_bar_data(\n symbol: str,\n exchange: Exchange,\n interval: Interval,\n start: datetime,\n end: datetime,\n collection_name:str = None\n):\n \"\"\"\"\"\"\n return database_manager.load_bar_data(\n symbol, exchange, interval, start, end, collection_name = collection_name\n )\n\n\n@lru_cache(maxsize=999)\ndef load_tick_data(\n symbol: str,\n exchange: Exchange,\n start: datetime,\n end: datetime,\n collection_name:str = None\n):\n \"\"\"\"\"\"\n return database_manager.load_tick_data(\n symbol, exchange, start, end, collection_name = collection_name\n )\n\n\n# GA related global value\nga_end = None\nga_mode = None\nga_target_name = None\nga_strategy_class = None\nga_setting = None\nga_vt_symbol = None\nga_interval = None\nga_start = None\nga_rate = None\nga_slippage = None\nga_size = None\nga_pricetick = None\nga_capital = None\n" ]
[ [ "numpy.log", "numpy.sqrt", "numpy.set_printoptions", "numpy.nan_to_num", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
akimotty877/mmediting
[ "cae872d6f3e867ba144c7c0dbc29a0ee1a29e5a6" ]
[ "mmedit/models/backbones/sr_backbones/basicvsr_net.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import ConvModule\nfrom mmcv.runner import load_checkpoint\n\nfrom mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN,\n flow_warp, make_layer)\nfrom mmedit.models.registry import BACKBONES\nfrom mmedit.utils import get_root_logger\n\n\[email protected]_module()\nclass BasicVSRNet(nn.Module):\n \"\"\"BasicVSR network structure for video super-resolution.\n\n Support only x4 upsampling.\n Paper:\n BasicVSR: The Search for Essential Components in Video Super-Resolution\n and Beyond, CVPR, 2021\n\n Args:\n mid_channels (int): Channel number of the intermediate features.\n Default: 64.\n num_blocks (int): Number of residual blocks in each propagation branch.\n Default: 30.\n spynet_pretrained (str): Pre-trained model path of SPyNet.\n Default: None.\n \"\"\"\n\n def __init__(self, mid_channels=64, num_blocks=30, spynet_pretrained=None):\n\n super().__init__()\n\n self.mid_channels = mid_channels\n\n # optical flow network for feature alignment\n self.spynet = SPyNet(pretrained=spynet_pretrained)\n\n # propagation branches\n self.backward_resblocks = ResidualBlocksWithInputConv(\n mid_channels + 3, mid_channels, num_blocks)\n self.forward_resblocks = ResidualBlocksWithInputConv(\n mid_channels + 3, mid_channels, num_blocks)\n\n # upsample\n self.fusion = nn.Conv2d(\n mid_channels * 2, mid_channels, 1, 1, 0, bias=True)\n self.upsample1 = PixelShufflePack(\n mid_channels, mid_channels, 2, upsample_kernel=3)\n self.upsample2 = PixelShufflePack(\n mid_channels, 64, 2, upsample_kernel=3)\n self.conv_hr = nn.Conv2d(64, 64, 3, 1, 1)\n self.conv_last = nn.Conv2d(64, 3, 3, 1, 1)\n self.img_upsample = nn.Upsample(\n scale_factor=4, mode='bilinear', align_corners=False)\n\n # activation function\n self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n\n def check_if_mirror_extended(self, lrs):\n \"\"\"Check whether the input is a mirror-extended sequence.\n\n If mirror-extended, the i-th (i=0, ..., t-1) frame is equal to the\n (t-1-i)-th frame.\n\n Args:\n lrs (tensor): Input LR images with shape (n, t, c, h, w)\n \"\"\"\n\n self.is_mirror_extended = False\n if lrs.size(1) % 2 == 0:\n lrs_1, lrs_2 = torch.chunk(lrs, 2, dim=1)\n if torch.norm(lrs_1 - lrs_2.flip(1)) == 0:\n self.is_mirror_extended = True\n\n def compute_flow(self, lrs):\n \"\"\"Compute optical flow using SPyNet for feature warping.\n\n Note that if the input is an mirror-extended sequence, 'flows_forward'\n is not needed, since it is equal to 'flows_backward.flip(1)'.\n\n Args:\n lrs (tensor): Input LR images with shape (n, t, c, h, w)\n\n Return:\n tuple(Tensor): Optical flow. 'flows_forward' corresponds to the\n flows used for forward-time propagation (current to previous).\n 'flows_backward' corresponds to the flows used for\n backward-time propagation (current to next).\n \"\"\"\n\n n, t, c, h, w = lrs.size()\n lrs_1 = lrs[:, :-1, :, :, :].reshape(-1, c, h, w)\n lrs_2 = lrs[:, 1:, :, :, :].reshape(-1, c, h, w)\n\n flows_backward = self.spynet(lrs_1, lrs_2).view(n, t - 1, 2, h, w)\n\n if self.is_mirror_extended: # flows_forward = flows_backward.flip(1)\n flows_forward = None\n else:\n flows_forward = self.spynet(lrs_2, lrs_1).view(n, t - 1, 2, h, w)\n\n return flows_forward, flows_backward\n\n def forward(self, lrs):\n \"\"\"Forward function for BasicVSR.\n\n Args:\n lrs (Tensor): Input LR sequence with shape (n, t, c, h, w).\n\n Returns:\n Tensor: Output HR sequence with shape (n, t, c, 4h, 4w).\n \"\"\"\n\n n, t, c, h, w = lrs.size()\n assert h >= 64 and w >= 64, (\n 'The height and width of inputs should be at least 64, '\n f'but got {h} and {w}.')\n\n # check whether the input is an extended sequence\n self.check_if_mirror_extended(lrs)\n\n # compute optical flow\n flows_forward, flows_backward = self.compute_flow(lrs)\n\n # backward-time propagation\n outputs = []\n feat_prop = lrs.new_zeros(n, self.mid_channels, h, w)\n for i in range(t - 1, -1, -1):\n if i < t - 1: # no warping required for the last timestep\n flow = flows_backward[:, i, :, :, :]\n feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))\n\n feat_prop = torch.cat([lrs[:, i, :, :, :], feat_prop], dim=1)\n feat_prop = self.backward_resblocks(feat_prop)\n\n outputs.append(feat_prop)\n outputs = outputs[::-1]\n\n # forward-time propagation and upsampling\n feat_prop = torch.zeros_like(feat_prop)\n for i in range(0, t):\n lr_curr = lrs[:, i, :, :, :]\n if i > 0: # no warping required for the first timestep\n if flows_forward is not None:\n flow = flows_forward[:, i - 1, :, :, :]\n else:\n flow = flows_backward[:, -i, :, :, :]\n feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))\n\n feat_prop = torch.cat([lr_curr, feat_prop], dim=1)\n feat_prop = self.forward_resblocks(feat_prop)\n\n # upsampling given the backward and forward features\n out = torch.cat([outputs[i], feat_prop], dim=1)\n out = self.lrelu(self.fusion(out))\n out = self.lrelu(self.upsample1(out))\n out = self.lrelu(self.upsample2(out))\n out = self.lrelu(self.conv_hr(out))\n out = self.conv_last(out)\n base = self.img_upsample(lr_curr)\n out += base\n outputs[i] = out\n\n return torch.stack(outputs, dim=1)\n\n def init_weights(self, pretrained=None, strict=True):\n \"\"\"Init weights for models.\n\n Args:\n pretrained (str, optional): Path for pretrained weights. If given\n None, pretrained weights will not be loaded. Defaults: None.\n strict (boo, optional): Whether strictly load the pretrained model.\n Defaults to True.\n \"\"\"\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=strict, logger=logger)\n elif pretrained is not None:\n raise TypeError(f'\"pretrained\" must be a str or None. '\n f'But received {type(pretrained)}.')\n\n\nclass ResidualBlocksWithInputConv(nn.Module):\n \"\"\"Residual blocks with a convolution in front.\n\n Args:\n in_channels (int): Number of input channels of the first conv.\n out_channels (int): Number of channels of the residual blocks.\n Default: 64.\n num_blocks (int): Number of residual blocks. Default: 30.\n \"\"\"\n\n def __init__(self, in_channels, out_channels=64, num_blocks=30):\n super().__init__()\n\n main = []\n\n # a convolution used to match the channels of the residual blocks\n main.append(nn.Conv2d(in_channels, out_channels, 3, 1, 1, bias=True))\n main.append(nn.LeakyReLU(negative_slope=0.1, inplace=True))\n\n # residual blocks\n main.append(\n make_layer(\n ResidualBlockNoBN, num_blocks, mid_channels=out_channels))\n\n self.main = nn.Sequential(*main)\n\n def forward(self, feat):\n \"\"\"\n Forward function for ResidualBlocksWithInputConv.\n\n Args:\n feat (Tensor): Input feature with shape (n, in_channels, h, w)\n\n Returns:\n Tensor: Output feature with shape (n, out_channels, h, w)\n \"\"\"\n return self.main(feat)\n\n\nclass SPyNet(nn.Module):\n \"\"\"SPyNet network structure.\n\n The difference to the SPyNet in [tof.py] is that\n 1. more SPyNetBasicModule is used in this version, and\n 2. no batch normalization is used in this version.\n\n Paper:\n Optical Flow Estimation using a Spatial Pyramid Network, CVPR, 2017\n\n Args:\n pretrained (str): path for pre-trained SPyNet. Default: None.\n \"\"\"\n\n def __init__(self, pretrained):\n super().__init__()\n\n self.basic_module = nn.ModuleList(\n [SPyNetBasicModule() for _ in range(6)])\n\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=True, logger=logger)\n elif pretrained is not None:\n raise TypeError('[pretrained] should be str or None, '\n f'but got {type(pretrained)}.')\n\n self.register_buffer(\n 'mean',\n torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))\n self.register_buffer(\n 'std',\n torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))\n\n def compute_flow(self, ref, supp):\n \"\"\"Compute flow from ref to supp.\n\n Note that in this function, the images are already resized to a\n multiple of 32.\n\n Args:\n ref (Tensor): Reference image with shape of (n, 3, h, w).\n supp (Tensor): Supporting image with shape of (n, 3, h, w).\n\n Returns:\n Tensor: Estimated optical flow: (n, 2, h, w).\n \"\"\"\n n, _, h, w = ref.size()\n\n # normalize the input images\n ref = [(ref - self.mean) / self.std]\n supp = [(supp - self.mean) / self.std]\n\n # generate downsampled frames\n for level in range(5):\n ref.append(\n F.avg_pool2d(\n input=ref[-1],\n kernel_size=2,\n stride=2,\n count_include_pad=False))\n supp.append(\n F.avg_pool2d(\n input=supp[-1],\n kernel_size=2,\n stride=2,\n count_include_pad=False))\n ref = ref[::-1]\n supp = supp[::-1]\n\n # flow computation\n flow = ref[0].new_zeros(n, 2, h // 32, w // 32)\n for level in range(len(ref)):\n if level == 0:\n flow_up = flow\n else:\n flow_up = F.interpolate(\n input=flow,\n scale_factor=2,\n mode='bilinear',\n align_corners=True) * 2.0\n\n # add the residue to the upsampled flow\n flow = flow_up + self.basic_module[level](\n torch.cat([\n ref[level],\n flow_warp(\n supp[level],\n flow_up.permute(0, 2, 3, 1),\n padding_mode='border'), flow_up\n ], 1))\n\n return flow\n\n def forward(self, ref, supp):\n \"\"\"Forward function of SPyNet.\n\n This function computes the optical flow from ref to supp.\n\n Args:\n ref (Tensor): Reference image with shape of (n, 3, h, w).\n supp (Tensor): Supporting image with shape of (n, 3, h, w).\n\n Returns:\n Tensor: Estimated optical flow: (n, 2, h, w).\n \"\"\"\n\n # upsize to a multiple of 32\n h, w = ref.shape[2:4]\n w_up = w if (w % 32) == 0 else 32 * (w // 32 + 1)\n h_up = h if (h % 32) == 0 else 32 * (h // 32 + 1)\n ref = F.interpolate(\n input=ref, size=(h_up, w_up), mode='bilinear', align_corners=False)\n supp = F.interpolate(\n input=supp,\n size=(h_up, w_up),\n mode='bilinear',\n align_corners=False)\n\n # compute flow, and resize back to the original resolution\n flow = F.interpolate(\n input=self.compute_flow(ref, supp),\n size=(h, w),\n mode='bilinear',\n align_corners=False)\n\n # adjust the flow values\n flow[:, 0, :, :] *= float(w) / float(w_up)\n flow[:, 1, :, :] *= float(h) / float(h_up)\n\n return flow\n\n\nclass SPyNetBasicModule(nn.Module):\n \"\"\"Basic Module for SPyNet.\n\n Paper:\n Optical Flow Estimation using a Spatial Pyramid Network, CVPR, 2017\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.basic_module = nn.Sequential(\n ConvModule(\n in_channels=8,\n out_channels=32,\n kernel_size=7,\n stride=1,\n padding=3,\n norm_cfg=None,\n act_cfg=dict(type='ReLU')),\n ConvModule(\n in_channels=32,\n out_channels=64,\n kernel_size=7,\n stride=1,\n padding=3,\n norm_cfg=None,\n act_cfg=dict(type='ReLU')),\n ConvModule(\n in_channels=64,\n out_channels=32,\n kernel_size=7,\n stride=1,\n padding=3,\n norm_cfg=None,\n act_cfg=dict(type='ReLU')),\n ConvModule(\n in_channels=32,\n out_channels=16,\n kernel_size=7,\n stride=1,\n padding=3,\n norm_cfg=None,\n act_cfg=dict(type='ReLU')),\n ConvModule(\n in_channels=16,\n out_channels=2,\n kernel_size=7,\n stride=1,\n padding=3,\n norm_cfg=None,\n act_cfg=None))\n\n def forward(self, tensor_input):\n \"\"\"\n Args:\n tensor_input (Tensor): Input tensor with shape (b, 8, h, w).\n 8 channels contain:\n [reference image (3), neighbor image (3), initial flow (2)].\n\n Returns:\n Tensor: Refined flow with shape (b, 2, h, w)\n \"\"\"\n return self.basic_module(tensor_input)\n" ]
[ [ "torch.nn.Sequential", "torch.chunk", "torch.Tensor", "torch.cat", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.zeros_like", "torch.nn.Upsample", "torch.nn.LeakyReLU", "torch.nn.functional.interpolate", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
giorgio-arena/ComputeLibraryBinary
[ "b8bb65f0dc2561907e566908e102aabcb7d41d61" ]
[ "full_model.py" ]
[ "import numpy as np\nimport tensorflow as tf\nfrom keras import regularizers, optimizers, backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Activation, Flatten, Dropout, BatchNormalization\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.datasets import cifar10\nfrom keras.callbacks import LearningRateScheduler\n\nfrom binary_conv2d import BinaryConv2D\nfrom accurate_conv2d import ABCConv2D\n\n\n# Define constants\nBATCH_SIZE = 64\nEPOCHS = 200\n\n\n# Define learning rate\ndef lr_schedule(epoch):\n lrate = 0.001\n\n '''\n # Uncomment for XNOR\n if epoch > 25:\n lrate = 0.00001\n '''\n if epoch > 75:\n lrate = 0.0005\n if epoch > 100:\n lrate = 0.0003\n return lrate\n\n\n# Add convolution layer to model: if binary, bn -> act -> binary_conv; otherwise conv -> bn -> act\ndef add_conv_layer(model, out_channels, is_binary=False, binarize_input=False, dropout=None, in_shape=None):\n if is_binary:\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(BinaryConv2D(out_channels, (3, 3), binarize_input, dropout))\n else:\n if in_shape is None:\n model.add(Conv2D(out_channels, (3, 3), padding='same', kernel_regularizer=regularizers.l2(1e-4)))\n else:\n model.add(Conv2D(out_channels, (3, 3), padding='same', kernel_regularizer=regularizers.l2(1e-4), input_shape=in_shape))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n\n if dropout is not None:\n model.add(MaxPooling2D(pool_size=(2,2)))\n if not binarize_input:\n model.add(Dropout(dropout))\n\n\n# Define model\ndef get_model(is_binary, binarize_input):\n assert(not binarize_input or is_binary)\n\n model = Sequential()\n\n add_conv_layer(model, 32, in_shape=x_train.shape[1:])\n add_conv_layer(model, 32, is_binary, binarize_input, 0.2)\n add_conv_layer(model, 64, is_binary, binarize_input)\n add_conv_layer(model, 64, is_binary, binarize_input, 0.3)\n add_conv_layer(model, 128, is_binary, binarize_input)\n add_conv_layer(model, 128, dropout=0.4)\n \n model.add(Flatten())\n model.add(Dense(10, activation='softmax'))\n\n return model\n\n\nif __name__ == '__main__':\n \n # Load data\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n \n # Normalize data\n mean = np.mean(x_train, axis=(0,1,2,3))\n std = np.std(x_train, axis=(0,1,2,3))\n x_train = (x_train - mean) / (std + 1e-7)\n x_test = (x_test - mean) / (std + 1e-7)\n y_train = to_categorical(y_train, 10)\n y_test = to_categorical(y_test, 10)\n\n # Data augmentation\n datagen = ImageDataGenerator(rotation_range=15, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True,)\n datagen.fit(x_train)\n\n # Get models\n models_pairs = [('Full', get_model(False, False)), ('BinWeights', get_model(True, False)), ('XNOR', get_model(True, True))]\n\n\n # Train models\n for model_name, model in models_pairs:\n # Compile model using RMSprop optimizer\n opt_rms = optimizers.RMSprop(lr=0.001, decay=1e-6)\n model.compile(loss='categorical_crossentropy', optimizer=opt_rms, metrics=['accuracy'])\n\n # Fit augmented data into the model and train\n model.fit_generator(datagen.flow(x_train, y_train, batch_size=BATCH_SIZE), steps_per_epoch=x_train.shape[0] // BATCH_SIZE, epochs=EPOCHS,\n verbose=2, validation_data=(x_test,y_test), callbacks=[LearningRateScheduler(lr_schedule)])\n \n # Save to disk as numpy arrays\n counters = [0, 0]\n for l in model.layers:\n if(type(l) == BatchNormalization):\n layer_name = \"BatchNorm\" + str(counters[0])\n weights_names = [\"Gamma\", \"Beta\", \"Mean\", \"Std\"]\n counters[0] += 1\n elif(type(l) == Conv2D or type(l) == BinaryConv2D):\n layer_name = \"Conv\" + str(counters[1])\n weights_names = [\"Weights\", \"Bias\"]\n counters[1] += 1\n else:\n continue # Only save BatchNorm and Conv\n\n filename = model_name + layer_name\n weights = l.get_weights()\n \n if(type(l) == BinaryConv2D):\n del weights[1] # Discard approx_weights\n\n for w, n in zip(weights, weights_names):\n np.save(filename + n, w)\n\n # Test\n scores = model.evaluate(x_test, y_test, batch_size=BATCH_SIZE, verbose=0)\n print('\\n' + model_name + ' validation, accuracy: %.3f loss: %.3f\\n\\n' % (scores[1] * 100, scores[0]))" ]
[ [ "numpy.std", "numpy.mean", "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jacobver/diag_context
[ "ca8d008b745743bf20c4bedcf6faa412a5ad8080" ]
[ "visualize.py" ]
[ "import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport train\nimport argparse\n\n\ndef process_data(net_data):\n # vocab = net_data['dicts']['vdict']\n dicts = (net_data['dicts']['src'], net_data['dicts']['tgt'])\n\n (src, tgt) = net_data['data'] # ['src']\n\n plt.ion()\n print('\\n == visualize \\'%s\\' net activity ====\\n 1) %s\\n 2) %s\\n q) quit' % (\n new_opt.mem, *new_opt.mem.split('_')))\n i = input(' \\n\\n --> ')\n if i == 'q':\n print()\n return(0)\n else:\n i = int(i) - 1\n net = new_opt.mem.split('_')[i]\n\n inv = False\n viz_txt = sort_data(\n net, net_data['modules'][i], net_data['data'][i], dicts[i])\n if net == 'nse':\n if i == 1:\n inv = True\n show_z_data(*viz_txt, inv)\n elif net == 'n2n':\n show_n2n_data(*viz_txt)\n\n\ndef sort_data(net, data, utts, vocab):\n txt = []\n utt_pix = []\n for i, utt in enumerate(utts):\n utt_pix += [{param: data[param][i].tolist()\n for param in data}]\n txt += [vocab.convertToLabels(utt.squeeze().data.tolist(), 0)]\n\n return utt_pix, txt\n\n\ndef show_z_data(visuals, src_sens, inverted=False):\n\n for z_map, src_sen in zip(visuals, src_sens):\n z = z_map['z']\n print(' z sz: ' + str(np.shape(z)))\n print(' '.join(src_sen))\n # plt.figure()\n plt.matshow(z)\n plt.xticks(range(len(src_sen)), src_sen)\n if inverted:\n plt.yticks(range(len(src_sen)), src_sen[::-1])\n else:\n plt.yticks(range(len(src_sen)), src_sen)\n plt.xlabel(' memory cell ')\n plt.ylabel(' t ')\n i = input('press enter, or \\'q\\' to quit : ')\n if i == 'q':\n break\n plt.close()\n\n\ndef show_n2n_data(visuals, src_sens):\n\n plt.figure(1)\n for pix, src_sen in zip(visuals, src_sens):\n plt.subplot(311)\n plt.imshow(pix['C'], aspect='auto')\n print(' C sz: ' + str(np.shape(pix['C'])))\n\n print(' p sz: ' + str(np.shape(pix['p'])))\n print(' M sz: ' + str(np.shape(pix['M'])))\n #print(' C sz: ' + str(np.shape(pix['M'])))\n print(' '.join(src_sen))\n # plt.figure()\n plt.subplot(312)\n plt.imshow(pix['p'], aspect='auto', origin='lower')\n plt.xticks(range(len(src_sen)), src_sen)\n #plt.yticks(range(len(src_sen)), src_sen)\n plt.xlabel(' memory cell ')\n plt.ylabel(' hops ')\n\n plt.subplot(313)\n plt.imshow(pix['M'], aspect='auto')\n i = input('press enter, or \\'q\\' to quit : ')\n if i == 'q':\n break\n plt.close()\n\n\ndef show_dnc_data(visuals, src_sens):\n\n for z_map, src_sen in zip(visuals, src_sens):\n\n i = input('press enter, or \\'q\\' to quit : ')\n if i == 'q':\n break\n plt.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-model', type=str)\n opt = parser.parse_args()\n new_opt = torch.load(opt.model)['opt']\n new_opt.batch_size = 1\n new_opt.train_from_state_dict = opt.model\n new_opt.gather_net_data = 1\n new_opt.n_samples = 10\n\n train.opt = new_opt\n net_data = train.main()\n\n process_data(net_data)\n" ]
[ [ "matplotlib.pyplot.imshow", "torch.load", "matplotlib.pyplot.figure", "matplotlib.pyplot.subplot", "numpy.shape", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.close", "matplotlib.pyplot.matshow", "matplotlib.pyplot.ion", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WiseDoge/ChatBotCHS
[ "bbdc396b3106573a25eda05b2bb0d342cdda035c" ]
[ "module/decoder.py" ]
[ "import torch.nn as nn\nimport torch\nfrom .attention import DotAttention\n\n\nclass AttnGRUDecoder(nn.Module):\n def __init__(self, embedding, hidden_dim, output_dim, n_layers=1, dropout=0.1, attn_type='dot'):\n super().__init__()\n self.embedding = embedding\n embedding_dim = embedding.weight.data.shape[1]\n self.embedding_dropout = nn.Dropout(dropout)\n self.attn = DotAttention(hidden_dim)\n self.n_layers = n_layers\n self.gru = nn.GRU(embedding_dim, hidden_dim, n_layers,\n dropout=(0 if n_layers == 1 else dropout))\n\n self.concat = nn.Linear(hidden_dim * 2, hidden_dim)\n self.linear = nn.Linear(hidden_dim, output_dim)\n\n def forward(self, step, last_hidden, encoder_outputs):\n \"\"\"\n step: shape=(1, batch_size).\n last_hidden: shape=(n_layers * num_directions, batch_size, hidden_size).\n encoder_outputs: shape=(max_seq_len, batch_size, hidden_size).\n \"\"\"\n # embedded.shape=(1, batch_size, hidden_dim).\n embedded = self.embedding(step)\n embedded = self.embedding_dropout(embedded)\n # output.shape=(1, batch_size, hidden_dim).\n # hidden.shape=(n_layers * num_directions, batch_size, hidden_size)\n output, hidden = self.gru(embedded, last_hidden)\n # scores.shape=(batch_size, 1, max_seq_len)\n scores = self.attn(output.squeeze(0), encoder_outputs)\n # context.shape=(batch_size, 1, hidden_dim)\n context = scores.bmm(encoder_outputs.transpose(0, 1))\n # context.shape=(batch_size, hidden_dim)\n context = context.squeeze(1)\n # output.shape=(batch_size, hidden_dim)\n output = output.squeeze(0)\n # concat.shape=(batch_size, hidden_dim * 2)\n concat = torch.cat((output, context), 1)\n # output.shape=(batch_size, hidden_dim)\n output = torch.tanh(self.concat(concat))\n # output.shape=(batch_size, output_dim)\n output = self.linear(output)\n # output = F.softmax(output, dim=1)\n # Return output and final hidden state\n return output, hidden\n" ]
[ [ "torch.nn.Linear", "torch.nn.Dropout", "torch.nn.GRU", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
geohci/language-switching
[ "14e5e91af7aab80d0fc09077eb8e9168df5b21a4" ]
[ "reader_language_overlap.py" ]
[ "import argparse\nfrom copy import deepcopy\nimport csv\nimport glob\nimport logging\n\nimport pandas as pd\n\nfrom session_utils import tsv_to_sessions\nfrom session_utils import get_lang_switch\nfrom session_utils import usertypes\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--tsvs\", nargs=\"+\",\n help=\".tsv files with anonymized page views ordered by user/datetime\")\n parser.add_argument(\"--stopafter\", type=int, default=-1,\n help=\"Process only this many sessions.\")\n parser.add_argument(\"--debug\", action=\"store_true\",\n help=\"More verbose logging\")\n parser.add_argument(\"--maxpvs\", type=int, default=500,\n help=\"Max pageviews in a session to still be included in analysis.\")\n parser.add_argument(\"--switch_fn\", default=\"switches_by_proj.tsv\")\n parser.add_argument(\"--cooc_fn\", default=\"cooc_by_proj.tsv\")\n args = parser.parse_args()\n\n if len(args.tsvs) == 1:\n args.tsvs = glob.glob(args.tsvs[0])\n logging.info(args)\n\n if args.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n\n logging.info((\"Filtering of statistics:\\n\"\n \"\\t*only Wikipedia projects considered (.wikipedia; mobile/desktop/app aggregated)\\n\"\n \"\\t*only namespace = 0 considered\\n\"\n \"\\t*only first pageview of a given article retained (e.g. enwiki+Chicago)\\n\"\n \"\\t*language switching defined as same wikidata item, different project\\n\"\n \"\\t*devices w/ greater than {0} pageviews dropped as likely bots.\".format(args.maxpvs)))\n\n # count of language pairs involved in switches (directional)\n switch_to_from = {}\n # count of languages co-occurring in same session (whether switch or not)\n lang_cooccurrence = {}\n # number of unique language projects per session\n lang_counts = {}\n # number of views per language project\n proj_pvs = {}\n\n for d in [switch_to_from, lang_cooccurrence, lang_counts, proj_pvs]:\n for ut in usertypes:\n d[ut] = {}\n\n i = 0\n for tsv in args.tsvs:\n logging.info(\"Processing: {0}\".format(tsv))\n # this only includes the first page view for a given QID-project so a user repeatedly viewing a page doesn't skew the statistics\n for session in tsv_to_sessions(tsv, trim=True):\n if i == args.stopafter:\n break\n i += 1\n if i % 500000 == 0:\n logging.info(\"{0} sessions analyzed.\".format(i))\n\n ut = session.usertype\n\n # filter out likely bots\n pvs = session.pageviews\n num_pvs = len(pvs)\n if not num_pvs or num_pvs > args.maxpvs:\n continue\n\n unique_langs = set([p.proj for p in pvs])\n for proj in unique_langs:\n proj_pvs[ut][proj] = proj_pvs[ut].get(proj, 0) + 1\n\n num_langs = len(unique_langs)\n lang_counts[ut][num_langs] = lang_counts[ut].get(num_langs, 0) + 1\n if num_langs > 1:\n lang_switches = get_lang_switch(pvs)\n tfs = set()\n for ls_pair in lang_switches:\n frompv = pvs[ls_pair[0]]\n topv = pvs[ls_pair[1]]\n tf = '{0}-{1}'.format(frompv.proj, topv.proj)\n tfs.add(tf)\n for tf in tfs:\n switch_to_from[ut][tf] = switch_to_from[ut].get(tf, 0) + 1\n sorted_langs = sorted(unique_langs)\n for li in range(0, num_langs - 1):\n for lj in range(li+1, num_langs):\n tf = '{0}-{1}'.format(sorted_langs[li], sorted_langs[lj])\n lang_cooccurrence[ut][tf] = lang_cooccurrence[ut].get(tf, 0) + 1\n else:\n single_lang = pvs[0].proj\n tf = '{0}-{0}'.format(single_lang)\n lang_cooccurrence[ut][tf] = lang_cooccurrence[ut].get(tf, 0) + 1\n switch_to_from[ut][tf] = switch_to_from[ut].get(tf, 0) + 1\n\n\n logging.info(\"\\nLangs per userhash:\")\n for ut in usertypes:\n logging.info(\"==={0}===\".format(ut))\n print_stats(lang_counts[ut], 10, \"langs\")\n\n logging.info(\"\\nLanguage pairs:\")\n for ut in usertypes:\n logging.info(\"==={0}===\".format(ut))\n print_stats(switch_to_from[ut], 30, \"\")\n\n logging.info(\"\\nWeighted language pairs:\")\n for ut in usertypes:\n logging.info(\"==={0}===\".format(ut))\n weighted_to_from = weight_by_proj(switch_to_from[ut], proj_pvs[ut])\n print_stats(weighted_to_from, 20, \"\", context_dict=switch_to_from[ut])\n\n if args.switch_fn:\n for ut in usertypes:\n with open(args.switch_fn.replace('.tsv', '_{0}.tsv'.format(ut)), \"w\") as fout:\n csvwriter = csv.writer(fout, delimiter=\"\\t\")\n csvwriter.writerow(['to', 'from', 'count_switches', 'to_lang_totalsessions', 'from_lang_totalsessions'])\n for tf in switch_to_from[ut]:\n tolang, fromlang = tf.split(\"-\")\n count = switch_to_from[ut].get(tf)\n csvwriter.writerow([tolang, fromlang, count, proj_pvs[ut][tolang], proj_pvs[ut][fromlang]])\n# lang_coocurrence_csv(switch_to_from, proj_pvs)\n\n if args.cooc_fn:\n for ut in usertypes:\n with open(args.cooc_fn.replace('.tsv', '_{0}.tsv'.format(ut)), \"w\") as fout:\n csvwriter = csv.writer(fout, delimiter=\"\\t\")\n csvwriter.writerow(['to', 'from', 'count_cooc', 'to_lang_totalsessions', 'from_lang_totalsessions'])\n for lc in lang_cooccurrence[ut]:\n l1, l2 = lc.split(\"-\")\n count = lang_cooccurrence[ut].get(lc)\n csvwriter.writerow([l1, l2, count, proj_pvs[ut][l1], proj_pvs[ut][l2]])\n if l1 != l2:\n csvwriter.writerow([l2, l1, count, proj_pvs[ut][l2], proj_pvs[ut][l1]])\n# lang_coocurrence_csv(lang_cooccurrence, proj_pvs)\n\n\ndef lang_coocurrence_csv(switches, lang_counts, fn=None):\n lang_sorted_by_popularity = sorted(lang_counts, key=lang_counts.get, reverse=True)\n lang_overlap = pd.DataFrame(index=lang_sorted_by_popularity, columns=lang_sorted_by_popularity, dtype=\"float32\")\n for l_to in lang_sorted_by_popularity:\n for l_from in lang_sorted_by_popularity:\n to_from = switches.get('{0}-{1}'.format(l_to, l_from), 0)\n lang_overlap.loc[l_to, l_from] = to_from\n from_to = switches.get('{0}-{1}'.format(l_from, l_to), 0)\n lang_overlap.loc[l_from, l_to] = from_to\n if fn:\n lang_overlap.to_csv(fn, sep=\"\\t\")\n else:\n print(lang_overlap)\n\ndef weight_by_proj(countdict, pvs_by_proj, minpv_threshold=500):\n \"\"\"Normalize count stats by how many page views occurred on a project\"\"\"\n # have to deep copy otherwise, this will change in-place and affect other statistics\n countdict = deepcopy(countdict)\n for pi_to_pj in list(countdict.keys()):\n count = countdict.pop(pi_to_pj)\n pi = pi_to_pj.split(\"-\")[0]\n norm = pvs_by_proj[pi]\n # only compute proportion for projects w/ enough traffic that the pattern MIGHT be real\n if norm > minpv_threshold:\n countdict[pi_to_pj] = count / norm\n else:\n countdict[pi_to_pj] = 0\n return countdict\n\n\ndef weight_by_pvs(countdict, pvs_by_wd, minpv_threshold=50):\n \"\"\"Normalize count stats by how often a page was viewed\"\"\"\n for wd_title in list(countdict.keys()):\n count = countdict.pop(wd_title)\n norm = pvs_by_wd[wd_title]\n # only compute proportion for pages w/ enough traffic that the pattern MIGHT be real\n if norm > minpv_threshold:\n countdict[wd_title] = count / norm\n else:\n countdict[wd_title] = 0\n\ndef print_stats(countdict, threshold, lbl, ignore=(), context_dict=None):\n \"\"\"Print limited statistics for count dictionaries.\"\"\"\n rest = 0\n ignorevals = []\n for k in ignore:\n ignorevals.append((k, countdict.pop(k)))\n denominator = sum(countdict.values())\n for topk, sc in enumerate([(k, countdict[k]) for k in sorted(countdict, key=countdict.get, reverse=True)]):\n if topk <= threshold:\n if context_dict:\n logging.info(\"{0} {1}:\\t{2}\\t({3}) times.\".format(sc[0], lbl, sc[1], context_dict.get(sc[0], \"N/A\")))\n else:\n logging.info(\"{0} {1}:\\t{2}\\t({3:.3f}) times.\".format(sc[0], lbl, sc[1], sc[1] / denominator))\n else:\n rest += sc[1]\n if rest:\n logging.info(\"Remainder:\\t{0}\\t({1:.3f}) times.\".format(rest, rest / denominator))\n for k,v in ignorevals:\n countdict[k] = v\n\n\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
asenina/mmdetection
[ "951b23a7ecee7fa79caf7f80d71491b7f555a261" ]
[ "mmdet/models/roi_heads/scnet_roi_head.py" ]
[ "import torch\nimport torch.nn.functional as F\n\nfrom mmdet.core import (bbox2result, bbox2roi, bbox_mapping, merge_aug_bboxes,\n merge_aug_masks, multiclass_nms)\nfrom mmdet.core.mask.transforms import mask2result\nfrom mmdet.core.utils.misc import dummy_pad\nfrom mmdet.integration.nncf.utils import is_in_nncf_tracing\nfrom ..builder import HEADS, build_head, build_roi_extractor\nfrom .cascade_roi_head import CascadeRoIHead\n\n\[email protected]_module()\nclass SCNetRoIHead(CascadeRoIHead):\n \"\"\"RoIHead for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n num_stages (int): number of cascade stages.\n stage_loss_weights (list): loss weight of cascade stages.\n semantic_roi_extractor (dict): config to init semantic roi extractor.\n semantic_head (dict): config to init semantic head.\n feat_relay_head (dict): config to init feature_relay_head.\n glbctx_head (dict): config to init global context head.\n \"\"\"\n\n def __init__(self,\n num_stages,\n stage_loss_weights,\n semantic_roi_extractor=None,\n semantic_head=None,\n feat_relay_head=None,\n glbctx_head=None,\n **kwargs):\n super(SCNetRoIHead, self).__init__(num_stages, stage_loss_weights,\n **kwargs)\n assert self.with_bbox and self.with_mask\n assert not self.with_shared_head # shared head is not supported\n\n if semantic_head is not None:\n self.semantic_roi_extractor = build_roi_extractor(\n semantic_roi_extractor)\n self.semantic_head = build_head(semantic_head)\n\n if feat_relay_head is not None:\n self.feat_relay_head = build_head(feat_relay_head)\n\n if glbctx_head is not None:\n self.glbctx_head = build_head(glbctx_head)\n\n def init_mask_head(self, mask_roi_extractor, mask_head):\n \"\"\"Initialize ``mask_head``\"\"\"\n if mask_roi_extractor is not None:\n self.mask_roi_extractor = build_roi_extractor(mask_roi_extractor)\n self.mask_head = build_head(mask_head)\n\n def init_weights(self, pretrained):\n \"\"\"Initialize the weights in head.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n for i in range(self.num_stages):\n if self.with_bbox:\n self.bbox_roi_extractor[i].init_weights()\n self.bbox_head[i].init_weights()\n if self.with_mask:\n self.mask_roi_extractor.init_weights()\n self.mask_head.init_weights()\n if self.with_semantic:\n self.semantic_head.init_weights()\n if self.with_glbctx:\n self.glbctx_head.init_weights()\n if self.with_feat_relay:\n self.feat_relay_head.init_weights()\n\n @property\n def with_semantic(self):\n \"\"\"bool: whether the head has semantic head\"\"\"\n return hasattr(self,\n 'semantic_head') and self.semantic_head is not None\n\n @property\n def with_feat_relay(self):\n \"\"\"bool: whether the head has feature relay head\"\"\"\n return (hasattr(self, 'feat_relay_head')\n and self.feat_relay_head is not None)\n\n @property\n def with_glbctx(self):\n \"\"\"bool: whether the head has global context head\"\"\"\n return hasattr(self, 'glbctx_head') and self.glbctx_head is not None\n\n def _fuse_glbctx(self, roi_feats, glbctx_feat, rois):\n \"\"\"Fuse global context feats with roi feats.\"\"\"\n assert roi_feats.size(0) == rois.size(0)\n img_inds = torch.unique(rois[:, 0].cpu(), sorted=True).long()\n fused_feats = torch.zeros_like(roi_feats)\n for img_id in img_inds:\n inds = (rois[:, 0] == img_id.item())\n fused_feats[inds] = roi_feats[inds] + glbctx_feat[img_id]\n return fused_feats\n\n def _slice_pos_feats(self, feats, sampling_results):\n \"\"\"Get features from pos rois.\"\"\"\n num_rois = [res.bboxes.size(0) for res in sampling_results]\n num_pos_rois = [res.pos_bboxes.size(0) for res in sampling_results]\n inds = torch.zeros(sum(num_rois), dtype=torch.bool)\n start = 0\n for i in range(len(num_rois)):\n start = 0 if i == 0 else start + num_rois[i - 1]\n stop = start + num_pos_rois[i]\n inds[start:stop] = 1\n sliced_feats = feats[inds]\n return sliced_feats\n\n def _bbox_forward(self,\n stage,\n x,\n rois,\n semantic_feat=None,\n glbctx_feat=None):\n \"\"\"Box head forward function used in both training and testing.\"\"\"\n bbox_roi_extractor = self.bbox_roi_extractor[stage]\n bbox_head = self.bbox_head[stage]\n bbox_feats = bbox_roi_extractor(\n x[:len(bbox_roi_extractor.featmap_strides)], rois)\n if self.with_semantic and semantic_feat is not None:\n bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n rois)\n if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:\n bbox_semantic_feat = F.adaptive_avg_pool2d(\n bbox_semantic_feat, bbox_feats.shape[-2:])\n bbox_feats += bbox_semantic_feat\n if self.with_glbctx and glbctx_feat is not None:\n bbox_feats = self._fuse_glbctx(bbox_feats, glbctx_feat, rois)\n cls_score, bbox_pred, relayed_feat = bbox_head(\n bbox_feats, return_shared_feat=True)\n\n bbox_results = dict(\n cls_score=cls_score,\n bbox_pred=bbox_pred,\n relayed_feat=relayed_feat)\n return bbox_results\n\n def _mask_forward(self,\n x,\n rois,\n semantic_feat=None,\n glbctx_feat=None,\n relayed_feat=None):\n \"\"\"Mask head forward function used in both training and testing.\"\"\"\n mask_feats = self.mask_roi_extractor(\n x[:self.mask_roi_extractor.num_inputs], rois)\n if self.with_semantic and semantic_feat is not None:\n mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n rois)\n if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:\n mask_semantic_feat = F.adaptive_avg_pool2d(\n mask_semantic_feat, mask_feats.shape[-2:])\n mask_feats += mask_semantic_feat\n if self.with_glbctx and glbctx_feat is not None:\n mask_feats = self._fuse_glbctx(mask_feats, glbctx_feat, rois)\n if self.with_feat_relay and relayed_feat is not None:\n mask_feats = mask_feats + relayed_feat\n mask_pred = self.mask_head(mask_feats)\n mask_results = dict(mask_pred=mask_pred)\n\n return mask_results\n\n def _bbox_forward_train(self,\n stage,\n x,\n sampling_results,\n gt_bboxes,\n gt_labels,\n rcnn_train_cfg,\n semantic_feat=None,\n glbctx_feat=None):\n \"\"\"Run forward function and calculate loss for box head in training.\"\"\"\n bbox_head = self.bbox_head[stage]\n rois = bbox2roi([res.bboxes for res in sampling_results])\n bbox_results = self._bbox_forward(\n stage,\n x,\n rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat)\n\n bbox_targets = bbox_head.get_targets(sampling_results, gt_bboxes,\n gt_labels, rcnn_train_cfg)\n loss_bbox = bbox_head.loss(bbox_results['cls_score'],\n bbox_results['bbox_pred'], rois,\n *bbox_targets)\n\n bbox_results.update(\n loss_bbox=loss_bbox, rois=rois, bbox_targets=bbox_targets)\n return bbox_results\n\n def _mask_forward_train(self,\n x,\n sampling_results,\n gt_masks,\n rcnn_train_cfg,\n semantic_feat=None,\n glbctx_feat=None,\n relayed_feat=None):\n \"\"\"Run forward function and calculate loss for mask head in\n training.\"\"\"\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n mask_results = self._mask_forward(\n x,\n pos_rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat,\n relayed_feat=relayed_feat)\n\n mask_targets = self.mask_head.get_targets(sampling_results, gt_masks,\n rcnn_train_cfg)\n pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])\n loss_mask = self.mask_head.loss(mask_results['mask_pred'],\n mask_targets, pos_labels)\n\n mask_results = loss_mask\n return mask_results\n\n def forward_train(self,\n x,\n img_metas,\n proposal_list,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_masks=None,\n gt_semantic_seg=None):\n \"\"\"\n Args:\n x (list[Tensor]): list of multi-level img features.\n\n img_metas (list[dict]): list of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmdet/datasets/pipelines/formatting.py:Collect`.\n\n proposal_list (list[Tensors]): list of region proposals.\n\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n\n gt_labels (list[Tensor]): class indices corresponding to each box\n\n gt_bboxes_ignore (None, list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n\n gt_masks (None, Tensor) : true segmentation masks for each box\n used if the architecture supports a segmentation task.\n\n gt_semantic_seg (None, list[Tensor]): semantic segmentation masks\n used if the architecture supports semantic segmentation task.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n losses = dict()\n\n # semantic segmentation branch\n if self.with_semantic:\n semantic_pred, semantic_feat = self.semantic_head(x)\n loss_seg = self.semantic_head.loss(semantic_pred, gt_semantic_seg)\n losses['loss_semantic_seg'] = loss_seg\n else:\n semantic_feat = None\n\n # global context branch\n if self.with_glbctx:\n mc_pred, glbctx_feat = self.glbctx_head(x)\n loss_glbctx = self.glbctx_head.loss(mc_pred, gt_labels)\n losses['loss_glbctx'] = loss_glbctx\n else:\n glbctx_feat = None\n\n for i in range(self.num_stages):\n self.current_stage = i\n rcnn_train_cfg = self.train_cfg[i]\n lw = self.stage_loss_weights[i]\n\n # assign gts and sample proposals\n sampling_results = []\n bbox_assigner = self.bbox_assigner[i]\n bbox_sampler = self.bbox_sampler[i]\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n\n for j in range(num_imgs):\n assign_result = bbox_assigner.assign(proposal_list[j],\n gt_bboxes[j],\n gt_bboxes_ignore[j],\n gt_labels[j])\n sampling_result = bbox_sampler.sample(\n assign_result,\n proposal_list[j],\n gt_bboxes[j],\n gt_labels[j],\n feats=[lvl_feat[j][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n bbox_results = \\\n self._bbox_forward_train(\n i, x, sampling_results, gt_bboxes, gt_labels,\n rcnn_train_cfg, semantic_feat, glbctx_feat)\n roi_labels = bbox_results['bbox_targets'][0]\n\n for name, value in bbox_results['loss_bbox'].items():\n losses[f's{i}.{name}'] = (\n value * lw if 'loss' in name else value)\n\n # refine boxes\n if i < self.num_stages - 1:\n pos_is_gts = [res.pos_is_gt for res in sampling_results]\n with torch.no_grad():\n proposal_list = self.bbox_head[i].refine_bboxes(\n bbox_results['rois'], roi_labels,\n bbox_results['bbox_pred'], pos_is_gts, img_metas)\n\n if self.with_feat_relay:\n relayed_feat = self._slice_pos_feats(bbox_results['relayed_feat'],\n sampling_results)\n relayed_feat = self.feat_relay_head(relayed_feat)\n else:\n relayed_feat = None\n\n mask_results = self._mask_forward_train(x, sampling_results, gt_masks,\n rcnn_train_cfg, semantic_feat,\n glbctx_feat, relayed_feat)\n mask_lw = sum(self.stage_loss_weights)\n losses['loss_mask'] = mask_lw * mask_results['loss_mask']\n\n return losses\n\n def simple_test(self, x, proposal_list, img_metas, rescale=False, postprocess=False):\n \"\"\"Test without augmentation.\"\"\"\n if self.with_semantic:\n _, semantic_feat = self.semantic_head(x)\n else:\n semantic_feat = None\n\n if self.with_glbctx:\n mc_pred, glbctx_feat = self.glbctx_head(x)\n else:\n glbctx_feat = None\n\n num_imgs = len(proposal_list)\n img_shapes = tuple(meta['img_shape'] for meta in img_metas)\n ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)\n scale_factors = tuple(meta['scale_factor'] for meta in img_metas)\n\n # \"ms\" in variable names means multi-stage\n ms_scores = []\n rcnn_test_cfg = self.test_cfg\n\n rois = bbox2roi(proposal_list)\n for i in range(self.num_stages):\n bbox_head = self.bbox_head[i]\n bbox_results = self._bbox_forward(\n i,\n x,\n rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat)\n # split batch bbox prediction back to each image\n cls_score = bbox_results['cls_score']\n bbox_pred = bbox_results['bbox_pred']\n num_proposals_per_img = tuple(len(p) for p in proposal_list)\n if torch.onnx.is_in_onnx_export() or is_in_nncf_tracing():\n rois = [rois]\n cls_score = [cls_score]\n bbox_pred = [bbox_pred]\n else:\n rois = rois.split(num_proposals_per_img, 0)\n cls_score = cls_score.split(num_proposals_per_img, 0)\n bbox_pred = bbox_pred.split(num_proposals_per_img, 0)\n ms_scores.append(cls_score)\n\n if i < self.num_stages - 1:\n bbox_label = [s[:, :-1].argmax(dim=1) for s in cls_score]\n rois = torch.cat([\n bbox_head.regress_by_class(rois[j], bbox_label[j],\n bbox_pred[j], img_metas[j])\n for j in range(num_imgs)\n ])\n\n # average scores of each image by stages\n cls_score = [\n sum([score[i] for score in ms_scores]) / float(len(ms_scores))\n for i in range(num_imgs)\n ]\n\n # apply bbox post-processing to each image individually\n det_bboxes = []\n det_labels = []\n for i in range(num_imgs):\n det_bbox, det_label = self.bbox_head[-1].get_bboxes(\n rois[i],\n cls_score[i],\n bbox_pred[i],\n img_shapes[i],\n scale_factors[i],\n rescale=False,\n cfg=rcnn_test_cfg)\n det_bboxes.append(det_bbox)\n det_labels.append(det_label)\n\n det_bboxes_results = (det_bboxes, det_labels)\n\n if self.with_mask:\n if (torch.onnx.is_in_onnx_export() or is_in_nncf_tracing() )and det_bboxes[0].shape[0] == 0:\n # If there are no detection there is nothing to do for a mask head.\n # But during ONNX export we should run mask head\n # for it to appear in the graph.\n # So add one zero / dummy ROI that will be mapped\n # to an Identity op in the graph.\n det_bboxes = [dummy_pad(det_bboxes[0], (0, 0, 0, 1))]\n det_labels = [dummy_pad(det_labels[0], (0, 1))]\n if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):\n mask_classes = self.mask_head.num_classes\n det_segm_results = [[[] for _ in range(mask_classes)]\n for _ in range(num_imgs)]\n else:\n if rescale and not isinstance(scale_factors[0], float):\n scale_factors = [\n torch.from_numpy(scale_factor).to(det_bboxes[0].device)\n for scale_factor in scale_factors\n ]\n _bboxes = [\n det_bboxes[i][:, :4] *\n scale_factors[i] if rescale else det_bboxes[i]\n for i in range(num_imgs)\n ]\n mask_rois = bbox2roi(det_bboxes)\n\n # get relay feature on mask_rois\n bbox_results = self._bbox_forward(\n -1,\n x,\n mask_rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat)\n relayed_feat = bbox_results['relayed_feat']\n relayed_feat = self.feat_relay_head(relayed_feat)\n\n mask_results = self._mask_forward(\n x,\n mask_rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat,\n relayed_feat=relayed_feat)\n mask_pred = mask_results['mask_pred']\n\n # split batch mask prediction back to each image\n num_bbox_per_img = tuple(len(_bbox) for _bbox in _bboxes)\n if torch.onnx.is_in_onnx_export() or is_in_nncf_tracing():\n mask_preds = [mask_pred]\n else:\n mask_preds = mask_pred.split(num_bbox_per_img, 0)\n\n # apply mask post-processing to each image individually\n det_segm_results = []\n for i in range(num_imgs):\n if det_bboxes[i].shape[0] == 0:\n det_segm_results.append(\n [[] for _ in range(self.mask_head.num_classes)])\n else:\n segm_result = self.mask_head.get_seg_masks(\n mask_preds[i], _bboxes[i], det_labels[i],\n self.test_cfg, ori_shapes[i], scale_factors[i],\n rescale)\n det_segm_results.append(segm_result)\n\n if postprocess:\n det_masks = det_segm_results if self.with_mask else [None for _ in det_bboxes]\n return [self.postprocess(det_bboxes[i], det_labels[i], det_masks[i], img_metas[i], rescale=rescale)\n for i in range(len(det_bboxes))]\n # return results\n if self.with_mask:\n return list(zip(det_bboxes_results, det_segm_results))\n else:\n return det_bboxes_results\n\n def aug_test(self, img_feats, proposal_list, img_metas, rescale=False):\n if self.with_semantic:\n semantic_feats = [\n self.semantic_head(feat)[1] for feat in img_feats\n ]\n else:\n semantic_feats = [None] * len(img_metas)\n\n if self.with_glbctx:\n glbctx_feats = [self.glbctx_head(feat)[1] for feat in img_feats]\n else:\n glbctx_feats = [None] * len(img_metas)\n\n rcnn_test_cfg = self.test_cfg\n aug_bboxes = []\n aug_scores = []\n for x, img_meta, semantic_feat, glbctx_feat in zip(\n img_feats, img_metas, semantic_feats, glbctx_feats):\n # only one image in the batch\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n\n proposals = bbox_mapping(proposal_list[0][:, :4], img_shape,\n scale_factor, flip)\n # \"ms\" in variable names means multi-stage\n ms_scores = []\n\n rois = bbox2roi([proposals])\n for i in range(self.num_stages):\n bbox_head = self.bbox_head[i]\n bbox_results = self._bbox_forward(\n i,\n x,\n rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat)\n ms_scores.append(bbox_results['cls_score'])\n if i < self.num_stages - 1:\n bbox_label = bbox_results['cls_score'].argmax(dim=1)\n rois = bbox_head.regress_by_class(\n rois, bbox_label, bbox_results['bbox_pred'],\n img_meta[0])\n\n cls_score = sum(ms_scores) / float(len(ms_scores))\n bboxes, scores = self.bbox_head[-1].get_bboxes(\n rois,\n cls_score,\n bbox_results['bbox_pred'],\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None)\n aug_bboxes.append(bboxes)\n aug_scores.append(scores)\n\n # after merging, bboxes will be rescaled to the original image size\n merged_bboxes, merged_scores = merge_aug_bboxes(\n aug_bboxes, aug_scores, img_metas, rcnn_test_cfg)\n det_bboxes, det_labels = multiclass_nms(merged_bboxes, merged_scores,\n rcnn_test_cfg.score_thr,\n rcnn_test_cfg.nms,\n rcnn_test_cfg.max_per_img)\n\n det_bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head[-1].num_classes)\n\n if self.with_mask:\n if det_bboxes.shape[0] == 0:\n det_segm_results = [[]\n for _ in range(self.mask_head.num_classes)]\n else:\n aug_masks = []\n for x, img_meta, semantic_feat, glbctx_feat in zip(\n img_feats, img_metas, semantic_feats, glbctx_feats):\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n _bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,\n scale_factor, flip)\n mask_rois = bbox2roi([_bboxes])\n # get relay feature on mask_rois\n bbox_results = self._bbox_forward(\n -1,\n x,\n mask_rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat)\n relayed_feat = bbox_results['relayed_feat']\n relayed_feat = self.feat_relay_head(relayed_feat)\n mask_results = self._mask_forward(\n x,\n mask_rois,\n semantic_feat=semantic_feat,\n glbctx_feat=glbctx_feat,\n relayed_feat=relayed_feat)\n mask_pred = mask_results['mask_pred']\n aug_masks.append(mask_pred)\n merged_masks = merge_aug_masks(aug_masks, img_metas,\n self.test_cfg)\n ori_shape = img_metas[0][0]['ori_shape']\n det_masks = self.mask_head.get_seg_masks(\n merged_masks,\n det_bboxes,\n det_labels,\n rcnn_test_cfg,\n ori_shape,\n scale_factor=1.0,\n rescale=False)\n\n det_segm_results = mask2result(\n det_bboxes,\n det_labels,\n det_masks,\n self.mask_head.num_classes,\n mask_thr_binary=self.test_cfg.mask_thr_binary,\n img_size=ori_shape[:2])\n return [(det_bbox_results, det_segm_results)]\n else:\n return [det_bbox_results]\n" ]
[ [ "torch.cat", "torch.zeros_like", "torch.from_numpy", "torch.nn.functional.adaptive_avg_pool2d", "torch.no_grad", "torch.onnx.is_in_onnx_export" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ysinha1/entropica_qaoa
[ "ac2a16fc8fb3cfedf86fe4154f5c21fc76c0d0c1" ]
[ "entropica_qaoa/vqe/measurelib.py" ]
[ "# Copyright 2019 Entropica Labs\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\"\"\"\nVarious convenience functions for measurements on a quantum computer or\nwavefunction simulator.\n\n\nSome preliminary explanation\n============================\n\nMeasuring the expectation value of a hamiltonian like\n\n.. math::\n\n H = a Z_0 Z_1 + b Z_1 Z_2 + c X_0 X_1 + d X_1 + e X_2\n\nrequires decomposing the hamiltonian into parts that commute with each other\nand then measuring them succesively. On a real QPU we need to do this,\nbecause physics don't allow us to measure non-commuting parts of a\nhamiltonian in one run. On the Wavefunction Simulator we need to do this,\nbecause translating :math:`\\\\left< \\\\psi | H | \\\\psi \\\\right>` naively to\n``wf.conj()@[email protected]()`` results in huge and sparse matrices ``ham`` that\ntake longer to generate, than it takes to calculate the wavefunction ``wf``.\n\nEven though :math:`Z_0 Z_1` and :math:`X_0 X_1` commute (go ahead and check\nit), we will measure them in separate runs, because measuring them\nsimultaenously can't be done by simply measuring the qubits 0 and 1. We only\nattempt to measure Pauli products simultaneously that *commute trivially*.\nTwo Pauli products commute trivially, if on each qubit both act with the same\nPauli Operator, or if either one acts only with the identity. This implies in\nparticular, that they can be measured without the need for ancilla qubits.\n\"\"\"\n\nfrom typing import List, Union, Tuple, Callable, Set\nfrom string import ascii_letters\nimport warnings\n\nimport numpy as np\nimport networkx as nx\nimport itertools\nimport functools\n\nfrom pyquil.quil import MEASURE, Program, QubitPlaceholder\nfrom pyquil.paulis import PauliSum, PauliTerm\nfrom pyquil.gates import H, I, RX\n\n\n# ###########################################################################\n# Tools to decompose PauliSums into smaller PauliSums that can be measured\n# simultaneously\n# ###########################################################################\n\n\ndef _PauliTerms_commute_trivially(term1: PauliTerm, term2: PauliTerm) -> bool:\n \"\"\"Checks if two PauliTerms commute trivially.\n\n Returns true, if on each qubit both terms have the same Pauli operator\n or if one has only an identity gate\n \"\"\"\n for factor in term1:\n if factor[1] != term2[factor[0]] and not term2[factor[0]] == 'I':\n return False\n return True\n\n\ndef commuting_decomposition(ham: PauliSum) -> List[PauliSum]:\n \"\"\"Decompose ham into a list of PauliSums with mutually commuting terms.\"\"\"\n\n # create the commutation graph of the hamiltonian\n # connected edges don't commute\n commutation_graph = nx.Graph()\n for term in ham:\n commutation_graph.add_node(term)\n\n # If the hamiltonian wasn't fully simplified, not all terms get added\n # to the graph. Taking care of this here.\n if len(commutation_graph.nodes) != len(ham):\n warnings.warn(f\"The hamiltonian {ham} is not fully simplified. \"\n \"Simplifying it now for you.\")\n ham.simplify()\n commutation_graph = nx.Graph()\n for term in ham:\n commutation_graph.add_node(term)\n\n\n for (term1, term2) in itertools.combinations(ham, 2):\n if not _PauliTerms_commute_trivially(term1, term2):\n commutation_graph.add_edge(term1, term2)\n\n # color the commutation graph. All terms with one color can be measured\n # simultaneously without the need of ancilla qubits\n color_map = nx.algorithms.coloring.greedy_color(commutation_graph)\n\n pauli_sum_list = [False] * (max(color_map.values()) + 1)\n for term in color_map.keys():\n if pauli_sum_list[color_map[term]] is False:\n pauli_sum_list[color_map[term]] = PauliSum([term])\n else:\n pauli_sum_list[color_map[term]] += term\n\n return pauli_sum_list\n\n\n# ##########################################################################\n# Functions to calculate expectation values of PauliSums from bitstrings\n# created by a QPU or the QVM\n# ##########################################################################\n\n\ndef append_measure_register(program: Program,\n qubits: List = None,\n trials: int = 10,\n ham: PauliSum = None) -> Program:\n \"\"\"Creates readout register, MEASURE instructions for register and wraps\n in ``trials`` numshots.\n\n Parameters\n ----------\n param qubits:\n List of Qubits to measure. If None, program.get_qubits() is used\n param trials:\n The number of trials to run.\n param ham:\n Hamiltonian to whose basis we need to switch. All terms in it must\n trivially commute. No base change gates are applied, if ``None``\n is passed.\n\n Returns\n -------\n Program:\n program with the gate change and measure instructions appended\n \"\"\"\n base_change_gates = {'X': lambda qubit: H(qubit),\n 'Y': lambda qubit: RX(np.pi / 2, qubit),\n 'Z': lambda qubit: I(qubit)}\n\n if qubits is None:\n qubits = program.get_qubits()\n\n def _get_correct_gate(qubit: Union[int, QubitPlaceholder]) -> Program():\n \"\"\"Correct base change gate on the qubit `qubit` given `ham`\"\"\"\n # this is an extra function, because `return` allows us to\n # easily break out of loops\n for term in ham:\n if term[qubit] != 'I':\n return base_change_gates[term[qubit]](qubit)\n\n raise ValueError(f\"PauliSum {ham} doesn't act on qubit {qubit}\")\n\n # append to correct base change gates if ham is specified. Otherwise\n # assume diagonal basis\n if ham is not None:\n for qubit in ham.get_qubits():\n program += Program(_get_correct_gate(qubit))\n\n # create a read out register\n ro = program.declare('ro', memory_type='BIT', memory_size=len(qubits))\n\n # add measure instructions to the specified qubits\n for i, qubit in enumerate(qubits):\n program += MEASURE(qubit, ro[i])\n program.wrap_in_numshots_loop(trials)\n return program\n\n\ndef sampling_expectation_z_base(hamiltonian: PauliSum,\n bitstrings: np.array) -> Tuple[float, float]:\n \"\"\"Calculates the energy expectation value of ``bitstrings`` w.r.t ``ham``.\n\n Warning\n -------\n This function assumes, that all terms in ``hamiltonian`` commute trivially\n _and_ that the ``bitstrings`` were measured in their basis.\n\n Parameters\n ----------\n param hamiltonian:\n The hamiltonian\n param bitstrings: 2D arry or list\n The measurement outcomes. One column per qubit.\n\n Returns\n -------\n tuple (expectation_value, variance/(n-1))\n \"\"\"\n\n # this dictionary maps from qubit indices to indices of the bitstrings\n # This is neccesary, because hamiltonian might not act on all qubits.\n # E.g. if hamiltonian = X0 + 1.0*Z2 bitstrings is a 2 x numshots array\n index_lut = {q: i for (i, q) in enumerate(hamiltonian.get_qubits())}\n if bitstrings.ndim == 2:\n energies = np.zeros(bitstrings.shape[0])\n else:\n energies = np.array([0])\n for term in hamiltonian:\n sign = np.zeros_like(energies)\n for factor in term:\n sign += bitstrings[:, index_lut[factor[0]]]\n energies += term.coefficient.real * (-1)**sign\n\n return (np.mean(energies),\n np.var(energies) / (bitstrings.shape[0] - 1))\n\n\ndef sampling_expectation(hamiltonians: List[PauliSum],\n bitstrings: List[np.array]) -> Tuple:\n \"\"\"Mapped wrapper around ``sampling_expectation_z_base``.\n\n A function that computes expectation values of a list of hamiltonians\n w.r.t a list of bitstrings. Assumes, that each pair in\n ``zip(hamiltonians, bitstrings)`` is as needed by\n ``sampling_expectation_z_base``\n\n Parameters\n ----------\n hamiltonians : List[PauliSum]\n List of PauliSums. Each PauliSum must only consist of mutually\n commuting terms\n bitstrings : List[np.array]\n List of the measured bitstrings. Each bitstring must have dimensions\n corresponding to the coresponding PauliSum\n\n Returns\n -------\n tuple (expectation_value, standard_deviation)\n \"\"\"\n energies = 0\n var = 0\n for ham, bits in zip(hamiltonians, bitstrings):\n e, v = sampling_expectation_z_base(ham, bits)\n energies += e\n var += v\n return (energies, np.sqrt(var))\n\n\n# ##########################################################################\n# Functions to calculate PauliSum expectation values from PauliSums\n# without having to create the full hamiltonian matrix\n# ##########################################################################\n\nH_mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2)\nRX_mat = np.array([[1, -1j], [-1j, 1]]) / np.sqrt(2)\n\n\ndef apply_H(qubit: int, n_qubits: int, wf: np.array) -> np.array:\n \"\"\"Apply a hadamard gate to wavefunction `wf` on the qubit `qubit`\"\"\"\n wf = wf.reshape([2] * n_qubits)\n einstring = \"YZ,\" + ascii_letters[0:n_qubits - 1 - qubit]\n einstring += \"Z\" + ascii_letters[n_qubits - 1 - qubit:n_qubits - 1]\n einstring += \"->\" + ascii_letters[0:n_qubits - 1 - qubit] + \"Y\"\n einstring += ascii_letters[n_qubits - 1 - qubit:n_qubits - 1]\n out = np.einsum(einstring, H_mat, wf)\n return out.reshape(-1)\n\n\ndef apply_RX(qubit: int, n_qubits: int, wf: np.array) -> np.array:\n \"\"\"Apply a RX(pi/2) gate to wavefunction `wf` on the qubit `qubit`\"\"\"\n wf = wf.reshape([2] * n_qubits)\n einstring = \"YZ,\" + ascii_letters[0:n_qubits - 1 - qubit]\n einstring += \"Z\" + ascii_letters[n_qubits - 1 - qubit:n_qubits - 1]\n einstring += \"->\" + ascii_letters[0:n_qubits - 1 - qubit] + \"Y\"\n einstring += ascii_letters[n_qubits - 1 - qubit:n_qubits - 1]\n out = np.einsum(einstring, RX_mat, wf)\n return out.reshape(-1)\n\n\ndef base_change_fun(ham: PauliSum, qubits: List[int]) -> Callable:\n \"\"\"\n Create a function that applies the correct base change for ``ham``\n on a wavefunction on ``n_qubits`` qubits.\n \"\"\"\n n_qubits = len(qubits)\n\n # returns the correct base change function for `qubit`.\n # Make this is a nextra function, because it allows better\n # control flow via `return`\n def _base_change_fun(qubit):\n for term in ham:\n if term[qubit] == 'X':\n return functools.partial(apply_H,\n qubits.index(qubit),\n n_qubits)\n if term[qubit] == 'Y':\n return functools.partial(apply_RX,\n qubits.index(qubit),\n n_qubits)\n return None\n\n funs = []\n for qubit in ham.get_qubits():\n next_fun = _base_change_fun(qubit)\n if next_fun is not None:\n funs.append(next_fun)\n\n def out(wf):\n return functools.reduce(lambda x, g: g(x), funs, wf)\n\n return out\n\n\ndef kron_eigs(ham: PauliSum, qubits: List[int]) -> np.array:\n \"\"\"\n Calculate the eigenvalues of `ham` ordered as a tensorproduct\n on `qubits`. Each qubit should be acted on with the same operator\n by each term or not at all.\n \"\"\"\n diag = np.zeros((2**len(qubits)))\n for term in ham:\n out = term.coefficient.real\n for qubit in qubits:\n if term[qubit] != 'I':\n out = np.kron([1, -1], out)\n else:\n out = np.kron([1, 1], out)\n diag += out\n\n return diag\n\n\ndef wavefunction_expectation(hams_eigs: List[np.array],\n base_changes: List[Callable],\n hams_squared_eigs: List[np.array],\n base_changes_squared: List[Callable],\n wf: np.array) -> Tuple[float, float]:\n \"\"\"Compute the exp. value and standard dev. of ``hams`` w.r.t ``wf``.\n\n Parameters\n ----------\n hams_eigs: List[np.array]\n A list of arrays of eigenvalues of the PauliSums in the\n commuting decomposition of the original hamiltonian.\n base_changes:\n A list of functions that apply the neccesary base change\n gates to the wavefunction\n hams_squared_eigs: List[np.array]\n The same as ``hams``, but for the square of ``ham``.\n base_changes_squared:\n The same as ``base_changes``, but for the square of ``ham``.\n wf:\n The wavefunction whose expectation value we want to know.\n\n Returns\n -------\n Tuple[float, float]:\n A tuple containing the expectation value of ``ham`` and the expectation\n value of ``ham**2``.\n \"\"\"\n\n energy = 0\n for eigs, fun in zip(hams_eigs, base_changes):\n wf_new = fun(wf)\n probs = np.abs(wf_new)**2\n energy += probs@eigs\n\n energy2 = 0\n for eigs, fun in zip(hams_squared_eigs, base_changes_squared):\n wf_new = fun(wf)\n probs = np.abs(wf_new)**2\n energy2 += probs@eigs\n\n return (energy, energy2)\n" ]
[ [ "numpy.sqrt", "numpy.einsum", "numpy.abs", "numpy.kron", "numpy.zeros_like", "numpy.mean", "numpy.var", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mdipronio/models
[ "48791660c4525d2f4c9a3d317cce62a3f8139d7b" ]
[ "official/vision/image_classification/resnet_imagenet_main.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs a ResNet model on the ImageNet dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport tensorflow as tf\n\nimport tensorflow_model_optimization as tfmot\n\nfrom official.benchmark.models import trivial_model\nfrom official.modeling import performance\nfrom official.utils.flags import core as flags_core\nfrom official.utils.logs import logger\nfrom official.utils.misc import distribution_utils\nfrom official.utils.misc import keras_utils\nfrom official.utils.misc import model_helpers\nfrom official.vision.image_classification import common\nfrom official.vision.image_classification import imagenet_preprocessing\nfrom official.vision.image_classification import resnet_model\n\n\ndef run(flags_obj):\n \"\"\"Run ResNet ImageNet training and eval loop using native Keras APIs.\n\n Args:\n flags_obj: An object containing parsed flag values.\n\n Raises:\n ValueError: If fp16 is passed as it is not currently supported.\n NotImplementedError: If some features are not currently supported.\n\n Returns:\n Dictionary of training and eval stats.\n \"\"\"\n keras_utils.set_session_config(\n enable_eager=flags_obj.enable_eager,\n enable_xla=flags_obj.enable_xla)\n\n # Execute flag override logic for better model performance\n if flags_obj.tf_gpu_thread_mode:\n keras_utils.set_gpu_thread_mode_and_count(\n per_gpu_thread_count=flags_obj.per_gpu_thread_count,\n gpu_thread_mode=flags_obj.tf_gpu_thread_mode,\n num_gpus=flags_obj.num_gpus,\n datasets_num_private_threads=flags_obj.datasets_num_private_threads)\n common.set_cudnn_batchnorm_mode()\n\n dtype = flags_core.get_tf_dtype(flags_obj)\n performance.set_mixed_precision_policy(\n flags_core.get_tf_dtype(flags_obj),\n flags_core.get_loss_scale(flags_obj, default_for_fp16=128))\n\n data_format = flags_obj.data_format\n if data_format is None:\n data_format = ('channels_first'\n if tf.test.is_built_with_cuda() else 'channels_last')\n tf.keras.backend.set_image_data_format(data_format)\n\n # Configures cluster spec for distribution strategy.\n _ = distribution_utils.configure_cluster(flags_obj.worker_hosts,\n flags_obj.task_index)\n\n strategy = distribution_utils.get_distribution_strategy(\n distribution_strategy=flags_obj.distribution_strategy,\n num_gpus=flags_obj.num_gpus,\n all_reduce_alg=flags_obj.all_reduce_alg,\n num_packs=flags_obj.num_packs,\n tpu_address=flags_obj.tpu)\n\n if strategy:\n # flags_obj.enable_get_next_as_optional controls whether enabling\n # get_next_as_optional behavior in DistributedIterator. If true, last\n # partial batch can be supported.\n strategy.extended.experimental_enable_get_next_as_optional = (\n flags_obj.enable_get_next_as_optional\n )\n\n strategy_scope = distribution_utils.get_strategy_scope(strategy)\n\n # pylint: disable=protected-access\n if flags_obj.use_synthetic_data:\n distribution_utils.set_up_synthetic_data()\n input_fn = common.get_synth_input_fn(\n height=imagenet_preprocessing.DEFAULT_IMAGE_SIZE,\n width=imagenet_preprocessing.DEFAULT_IMAGE_SIZE,\n num_channels=imagenet_preprocessing.NUM_CHANNELS,\n num_classes=imagenet_preprocessing.NUM_CLASSES,\n dtype=dtype,\n drop_remainder=True)\n else:\n distribution_utils.undo_set_up_synthetic_data()\n input_fn = imagenet_preprocessing.input_fn\n\n # When `enable_xla` is True, we always drop the remainder of the batches\n # in the dataset, as XLA-GPU doesn't support dynamic shapes.\n drop_remainder = flags_obj.enable_xla\n\n # Current resnet_model.resnet50 input format is always channel-last.\n # We use keras_application mobilenet model which input format is depends on\n # the keras beckend image data format.\n # This use_keras_image_data_format flags indicates whether image preprocessor\n # output format should be same as the keras backend image data format or just\n # channel-last format.\n use_keras_image_data_format = (flags_obj.model == 'mobilenet')\n train_input_dataset = input_fn(\n is_training=True,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n parse_record_fn=imagenet_preprocessing.get_parse_record_fn(\n use_keras_image_data_format=use_keras_image_data_format),\n datasets_num_private_threads=flags_obj.datasets_num_private_threads,\n dtype=dtype,\n drop_remainder=drop_remainder,\n tf_data_experimental_slack=flags_obj.tf_data_experimental_slack,\n training_dataset_cache=flags_obj.training_dataset_cache,\n )\n\n eval_input_dataset = None\n if not flags_obj.skip_eval:\n eval_input_dataset = input_fn(\n is_training=False,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n parse_record_fn=imagenet_preprocessing.get_parse_record_fn(\n use_keras_image_data_format=use_keras_image_data_format),\n dtype=dtype,\n drop_remainder=drop_remainder)\n\n lr_schedule = common.PiecewiseConstantDecayWithWarmup(\n batch_size=flags_obj.batch_size,\n epoch_size=imagenet_preprocessing.NUM_IMAGES['train'],\n warmup_epochs=common.LR_SCHEDULE[0][1],\n boundaries=list(p[1] for p in common.LR_SCHEDULE[1:]),\n multipliers=list(p[0] for p in common.LR_SCHEDULE),\n compute_lr_on_cpu=True)\n steps_per_epoch = (\n imagenet_preprocessing.NUM_IMAGES['train'] // flags_obj.batch_size)\n\n with strategy_scope:\n if flags_obj.optimizer == 'resnet50_default':\n optimizer = common.get_optimizer(lr_schedule)\n elif flags_obj.optimizer == 'mobilenet_default':\n initial_learning_rate = \\\n flags_obj.initial_learning_rate_per_sample * flags_obj.batch_size\n optimizer = tf.keras.optimizers.SGD(\n learning_rate=tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate,\n decay_steps=steps_per_epoch * flags_obj.num_epochs_per_decay,\n decay_rate=flags_obj.lr_decay_factor,\n staircase=True),\n momentum=0.9)\n if flags_obj.fp16_implementation == 'graph_rewrite':\n # Note: when flags_obj.fp16_implementation == \"graph_rewrite\", dtype as\n # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32'\n # which will ensure tf.compat.v2.keras.mixed_precision and\n # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double\n # up.\n optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(\n optimizer)\n\n # TODO(hongkuny): Remove trivial model usage and move it to benchmark.\n if flags_obj.use_trivial_model:\n model = trivial_model.trivial_model(\n imagenet_preprocessing.NUM_CLASSES)\n elif flags_obj.model == 'resnet50_v1.5':\n resnet_model.change_keras_layer(flags_obj.use_tf_keras_layers)\n model = resnet_model.resnet50(\n num_classes=imagenet_preprocessing.NUM_CLASSES)\n elif flags_obj.model == 'mobilenet':\n # TODO(kimjaehong): Remove layers attribute when minimum TF version\n # support 2.0 layers by default.\n model = tf.keras.applications.mobilenet.MobileNet(\n weights=None,\n classes=imagenet_preprocessing.NUM_CLASSES,\n layers=tf.keras.layers)\n if flags_obj.pretrained_filepath:\n model.load_weights(flags_obj.pretrained_filepath)\n\n if flags_obj.pruning_method == 'polynomial_decay':\n if dtype != tf.float32:\n raise NotImplementedError(\n 'Pruning is currently only supported on dtype=tf.float32.')\n pruning_params = {\n 'pruning_schedule':\n tfmot.sparsity.keras.PolynomialDecay(\n initial_sparsity=flags_obj.pruning_initial_sparsity,\n final_sparsity=flags_obj.pruning_final_sparsity,\n begin_step=flags_obj.pruning_begin_step,\n end_step=flags_obj.pruning_end_step,\n frequency=flags_obj.pruning_frequency),\n }\n model = tfmot.sparsity.keras.prune_low_magnitude(model, **pruning_params)\n elif flags_obj.pruning_method:\n raise NotImplementedError(\n 'Only polynomial_decay is currently supported.')\n\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=optimizer,\n metrics=(['sparse_categorical_accuracy']\n if flags_obj.report_accuracy_metrics else None),\n run_eagerly=flags_obj.run_eagerly)\n\n train_epochs = flags_obj.train_epochs\n\n callbacks = common.get_callbacks(\n steps_per_epoch=steps_per_epoch,\n pruning_method=flags_obj.pruning_method,\n enable_checkpoint_and_export=flags_obj.enable_checkpoint_and_export,\n model_dir=flags_obj.model_dir)\n\n # if mutliple epochs, ignore the train_steps flag.\n if train_epochs <= 1 and flags_obj.train_steps:\n steps_per_epoch = min(flags_obj.train_steps, steps_per_epoch)\n train_epochs = 1\n\n num_eval_steps = (\n imagenet_preprocessing.NUM_IMAGES['validation'] // flags_obj.batch_size)\n\n validation_data = eval_input_dataset\n if flags_obj.skip_eval:\n # Only build the training graph. This reduces memory usage introduced by\n # control flow ops in layers that have different implementations for\n # training and inference (e.g., batch norm).\n if flags_obj.set_learning_phase_to_train:\n # TODO(haoyuzhang): Understand slowdown of setting learning phase when\n # not using distribution strategy.\n tf.keras.backend.set_learning_phase(1)\n num_eval_steps = None\n validation_data = None\n\n if not strategy and flags_obj.explicit_gpu_placement:\n # TODO(b/135607227): Add device scope automatically in Keras training loop\n # when not using distribition strategy.\n no_dist_strat_device = tf.device('/device:GPU:0')\n no_dist_strat_device.__enter__()\n\n history = model.fit(train_input_dataset,\n epochs=train_epochs,\n steps_per_epoch=steps_per_epoch,\n callbacks=callbacks,\n validation_steps=num_eval_steps,\n validation_data=validation_data,\n validation_freq=flags_obj.epochs_between_evals,\n verbose=2)\n\n eval_output = None\n if not flags_obj.skip_eval:\n eval_output = model.evaluate(eval_input_dataset,\n steps=num_eval_steps,\n verbose=2)\n\n if flags_obj.pruning_method:\n model = tfmot.sparsity.keras.strip_pruning(model)\n if flags_obj.enable_checkpoint_and_export:\n if dtype == tf.bfloat16:\n logging.warning('Keras model.save does not support bfloat16 dtype.')\n else:\n # Keras model.save assumes a float32 input designature.\n export_path = os.path.join(flags_obj.model_dir, 'saved_model')\n model.save(export_path, include_optimizer=False)\n\n if not strategy and flags_obj.explicit_gpu_placement:\n no_dist_strat_device.__exit__()\n\n stats = common.build_stats(history, eval_output, callbacks)\n return stats\n\n\ndef define_imagenet_keras_flags():\n common.define_keras_flags(\n model=True,\n optimizer=True,\n pretrained_filepath=True)\n common.define_pruning_flags()\n flags_core.set_defaults()\n flags.adopt_module_key_flags(common)\n\n\ndef main(_):\n model_helpers.apply_clean(flags.FLAGS)\n with logger.benchmark_context(flags.FLAGS):\n stats = run(flags.FLAGS)\n logging.info('Run stats:\\n%s', stats)\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n define_imagenet_keras_flags()\n app.run(main)\n" ]
[ [ "tensorflow.device", "tensorflow.test.is_built_with_cuda", "tensorflow.keras.optimizers.schedules.ExponentialDecay", "tensorflow.keras.backend.set_image_data_format", "tensorflow.keras.applications.mobilenet.MobileNet", "tensorflow.keras.backend.set_learning_phase", "tensorflow.train.experimental.enable_mixed_precision_graph_rewrite" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JesseLT/qstrader
[ "1e82d70aacff71e4f484e1d88038d4bf0ad67bc9" ]
[ "qstrader/price_handler/yahoo_daily_csv_bar.py" ]
[ "import os\n\nimport pandas as pd\n\nfrom ..price_parser import PriceParser\nfrom .base import AbstractBarPriceHandler\nfrom ..event import BarEvent\n\n\nclass YahooDailyCsvBarPriceHandler(AbstractBarPriceHandler):\n \"\"\"\n YahooDailyBarPriceHandler is designed to read CSV files of\n Yahoo Finance daily Open-High-Low-Close-Volume (OHLCV) data\n for each requested financial instrument and stream those to\n the provided events queue as BarEvents.\n \"\"\"\n def __init__(\n self, csv_dir, events_queue,\n init_tickers=None,\n start_date=None, end_date=None,\n calc_adj_returns=False, sm='close'\n ):\n \"\"\"\n Takes the CSV directory, the events queue and a possible\n list of initial ticker symbols then creates an (optional)\n list of ticker subscriptions and associated prices.\n \"\"\"\n self.csv_dir = csv_dir\n self.events_queue = events_queue\n self.continue_backtest = True\n self.tickers = {}\n self.tickers_data = {}\n self.bar_stream = {}\n\n self.start_date = start_date\n self.end_date = end_date\n # self.bar_stream = self._merge_sort_ticker_data()\n self.calc_adj_returns = calc_adj_returns\n if self.calc_adj_returns:\n self.adj_close_returns = []\n self.subject_matter = sm\n\n if init_tickers is not None:\n for ticker in init_tickers:\n self.subscribe_ticker(ticker)\n self.bar_stream[ticker] = self._merge_sort_ticker_data(ticker)\n\n def _open_ticker_price_csv(self, ticker):\n \"\"\"\n Opens the CSV files containing the equities ticks from\n the specified CSV data directory, converting them into\n them into a pandas DataFrame, stored in a dictionary.\n \"\"\"\n ticker_path = os.path.join(self.csv_dir, \"%s.csv\" % ticker)\n # self.tickers_data[ticker] = pd.io.parsers.read_csv(\n # ticker_path, header=0, parse_dates=True,\n # index_col=0, names=(\n # \"Date\", \"Open\", \"High\", \"Low\",\n # \"Close\", \"Volume\", \"Adj Close\"\n # )\n # )\n self.tickers_data[ticker] = pd.read_csv(ticker_path, index_col=0, parse_dates=True)\n self.tickers_data[ticker][\"Ticker\"] = ticker\n\n def _merge_sort_ticker_data(self, ticker):\n \"\"\"\n Concatenates all of the separate equities DataFrames\n into a single DataFrame that is time ordered, allowing tick\n data events to be added to the queue in a chronological fashion.\n\n Note that this is an idealised situation, utilised solely for\n backtesting. In live trading ticks may arrive \"out of order\".\n \"\"\"\n # df = pd.concat(self.tickers_data.values()).sort_index()\n df = self.tickers_data[ticker].sort_index()\n start = None\n end = None\n if self.start_date is not None:\n start = df.index.searchsorted(self.start_date)\n if self.end_date is not None:\n end = df.index.searchsorted(self.end_date)\n # This is added so that the ticker events are\n # always deterministic, otherwise unit test values\n # will differ\n df['colFromIndex'] = df.index\n df = df.sort_values(by=[\"colFromIndex\", \"Ticker\"])\n if start is None and end is None:\n return df.iterrows()\n elif start is not None and end is None:\n return df.loc[start:].iterrows()\n elif start is None and end is not None:\n return df.iloc[:end].iterrows()\n else:\n return df.iloc[start:end].iterrows()\n\n def subscribe_ticker(self, ticker):\n \"\"\"\n Subscribes the price handler to a new ticker symbol.\n \"\"\"\n if ticker not in self.tickers:\n try:\n self._open_ticker_price_csv(ticker)\n dft = self.tickers_data[ticker]\n row0 = dft.iloc[0].to_dict()\n # print(row0)\n\n # close = PriceParser.parse(row0[\"Close\"])\n # adj_close = PriceParser.parse(row0[\"Adj Close\"])\n\n # ticker_prices = {\n # \"close\": close,\n # \"adj_close\": adj_close,\n # \"timestamp\": dft.index[0]\n # }\n # print(ticker_prices)\n row0['timestamp'] = dft.index[0]\n # self.tickers[ticker] = ticker_prices\n self.tickers[ticker] = row0\n except OSError:\n print(\n \"Could not subscribe ticker %s \"\n \"as no data CSV found for pricing.\" % ticker\n )\n else:\n print(\n \"Could not subscribe ticker %s \"\n \"as is already subscribed.\" % ticker\n )\n\n def _create_event(self, index, period, ticker, row):\n \"\"\"\n Obtain all elements of the bar from a row of dataframe\n and return a BarEvent\n \"\"\"\n # open_price = PriceParser.parse(row[\"Open\"])\n # high_price = PriceParser.parse(row[\"High\"])\n # low_price = PriceParser.parse(row[\"Low\"])\n # close_price = PriceParser.parse(row[\"Close\"])\n # adj_close_price = PriceParser.parse(row[\"Adj Close\"])\n # volume = int(row[\"Volume\"])\n # bev = BarEvent(\n # ticker, index, period, open_price,\n # high_price, low_price, close_price,\n # volume, adj_close_price\n # )\n row = row.to_dict()\n for k, v in row.items():\n if k=='Ticker' or k=='colFromIndex':\n continue\n row[k] = PriceParser.parse(v)\n bev = BarEvent(index, period, ticker, row)\n return bev\n\n def _store_event(self, event):\n \"\"\"\n Store price event for closing price and adjusted closing price\n \"\"\"\n ticker = event.ticker\n # If the calc_adj_returns flag is True, then calculate\n # and store the full list of adjusted closing price\n # percentage returns in a list\n # TODO: Make this faster\n # if self.calc_adj_returns:\n # prev_adj_close = self.tickers[ticker][\n # \"adj_close\"\n # ] / float(PriceParser.PRICE_MULTIPLIER)\n # cur_adj_close = event.adj_close_price / float(\n # PriceParser.PRICE_MULTIPLIER\n # )\n # self.tickers[ticker][\n # \"adj_close_ret\"\n # ] = cur_adj_close / prev_adj_close - 1.0\n # self.adj_close_returns.append(self.tickers[ticker][\"adj_close_ret\"])\n # self.tickers[ticker][\"close\"] = event.close_price\n # self.tickers[ticker][\"adj_close\"] = event.adj_close_price\n # self.tickers[ticker][\"timestamp\"] = event.time\n\n event.rows.update({'timestamp': event.time})\n self.tickers[ticker] = event.rows\n # print(self.tickers[ticker])\n\n def stream_next(self):\n \"\"\"\n Place the next BarEvent onto the event queue.\n \"\"\"\n for t in self.tickers.keys():\n try:\n index, row = next(self.bar_stream[t])\n # index, row = next(self._merge_sort_ticker_data(t))\n except StopIteration:\n self.continue_backtest = False\n return\n # Obtain all elements of the bar from the dataframe\n ticker = row[\"Ticker\"]\n period = 86400 # Seconds in a day\n # Create the tick event for the queue\n bev = self._create_event(index, period, ticker, row)\n # Store event\n self._store_event(bev)\n # Send event to queue\n self.events_queue.put(bev)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
ZephyrII/competitive_colaboration
[ "a557d1e23ef2c0b8e3794f085a79bfffb860f9df", "2167e089be80ca01911ba55c07b83c9f26f147e7" ]
[ "test_disp.py", "models/MaskResNet6.py" ]
[ "import torch\nfrom torch.autograd import Variable\nfrom PIL import Image\nfrom scipy import interpolate\nfrom scipy.misc import imresize\nfrom scipy.ndimage.interpolation import zoom\nimport numpy as np\nfrom path import Path\nimport argparse\nfrom tqdm import tqdm\nfrom utils import tensor2array\nimport models\nfrom loss_functions import spatial_normalize\n\nparser = argparse.ArgumentParser(description='Script for DispNet testing with corresponding groundTruth',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--dispnet\", dest='dispnet', type=str, default='DispResNet6', help='dispnet architecture')\nparser.add_argument(\"--posenet\", dest='posenet', type=str, default='PoseExpNet', help='posenet architecture')\nparser.add_argument(\"--pretrained-dispnet\", required=True, type=str, help=\"pretrained DispNet path\")\nparser.add_argument(\"--pretrained-posenet\", default=None, type=str, help=\"pretrained PoseNet path (for scale factor)\")\nparser.add_argument(\"--img-height\", default=256, type=int, help=\"Image height\")\nparser.add_argument(\"--img-width\", default=832, type=int, help=\"Image width\")\nparser.add_argument(\"--no-resize\", action='store_true', help=\"no resizing is done\")\nparser.add_argument(\"--spatial-normalize\", action='store_true', help=\"spatial normalization\")\nparser.add_argument(\"--min-depth\", default=1e-3)\nparser.add_argument(\"--max-depth\", default=80, type=float)\n\nparser.add_argument(\"--dataset-dir\", default='.', type=str, help=\"Dataset directory\")\nparser.add_argument(\"--dataset-list\", default=None, type=str, help=\"Dataset list file\")\nparser.add_argument(\"--output-dir\", default=None, type=str, help=\"Output directory for saving predictions in a big 3D numpy file\")\n\nparser.add_argument(\"--gt-type\", default='KITTI', type=str, help=\"GroundTruth data type\", choices=['npy', 'png', 'KITTI', 'stillbox'])\nparser.add_argument(\"--img-exts\", default=['png', 'jpg', 'bmp'], nargs='*', type=str, help=\"images extensions to glob\")\n\n\ndef main():\n args = parser.parse_args()\n if args.gt_type == 'KITTI':\n from kitti_eval.depth_evaluation_utils import test_framework_KITTI as test_framework\n elif args.gt_type == 'stillbox':\n from stillbox_eval.depth_evaluation_utils import test_framework_stillbox as test_framework\n\n disp_net = getattr(models, args.dispnet)().cuda()\n weights = torch.load(args.pretrained_dispnet)\n disp_net.load_state_dict(weights['state_dict'])\n disp_net.eval()\n\n if args.pretrained_posenet is None:\n print('no PoseNet specified, scale_factor will be determined by median ratio, which is kiiinda cheating\\\n (but consistent with original paper)')\n seq_length = 0\n else:\n weights = torch.load(args.pretrained_posenet)\n seq_length = int(weights['state_dict']['conv1.0.weight'].size(1)/3)\n pose_net = getattr(models, args.posenet)(nb_ref_imgs=seq_length - 1, output_exp=False).cuda()\n pose_net.load_state_dict(weights['state_dict'], strict=False)\n\n dataset_dir = Path(args.dataset_dir)\n if args.dataset_list is not None:\n with open(args.dataset_list, 'r') as f:\n test_files = list(f.read().splitlines())\n else:\n test_files = [file.relpathto(dataset_dir) for file in sum([dataset_dir.files('*.{}'.format(ext)) for ext in args.img_exts], [])]\n\n framework = test_framework(dataset_dir, test_files, seq_length, args.min_depth, args.max_depth)\n\n print('{} files to test'.format(len(test_files)))\n errors = np.zeros((2, 7, len(test_files)), np.float32)\n if args.output_dir is not None:\n output_dir = Path(args.output_dir)\n viz_dir = output_dir/'viz'\n output_dir.makedirs_p()\n viz_dir.makedirs_p()\n\n for j, sample in enumerate(tqdm(framework)):\n tgt_img = sample['tgt']\n\n ref_imgs = sample['ref']\n\n h,w,_ = tgt_img.shape\n if (not args.no_resize) and (h != args.img_height or w != args.img_width):\n tgt_img = imresize(tgt_img, (args.img_height, args.img_width)).astype(np.float32)\n ref_imgs = [imresize(img, (args.img_height, args.img_width)).astype(np.float32) for img in ref_imgs]\n\n tgt_img = np.transpose(tgt_img, (2, 0, 1))\n ref_imgs = [np.transpose(img, (2,0,1)) for img in ref_imgs]\n\n tgt_img = torch.from_numpy(tgt_img).unsqueeze(0)\n tgt_img = ((tgt_img/255 - 0.5)/0.5).cuda()\n tgt_img_var = Variable(tgt_img, volatile=True)\n\n ref_imgs_var = []\n for i, img in enumerate(ref_imgs):\n img = torch.from_numpy(img).unsqueeze(0)\n img = ((img/255 - 0.5)/0.5).cuda()\n ref_imgs_var.append(Variable(img, volatile=True))\n\n pred_disp = disp_net(tgt_img_var)\n if args.spatial_normalize:\n pred_disp = spatial_normalize(pred_disp)\n pred_disp = pred_disp.data.cpu().numpy()[0,0]\n gt_depth = sample['gt_depth']\n\n if args.output_dir is not None:\n if j == 0:\n predictions = np.zeros((len(test_files), *pred_disp.shape))\n predictions[j] = 1/pred_disp\n gt_viz = interp_gt_disp(gt_depth)\n gt_viz = torch.FloatTensor(gt_viz)\n gt_viz[gt_viz == 0] = 1000\n gt_viz = (1/gt_viz).clamp(0,10)\n\n tgt_img_viz = tensor2array(tgt_img[0].cpu())\n depth_viz = tensor2array(torch.FloatTensor(pred_disp), max_value=None, colormap='hot')\n gt_viz = tensor2array(gt_viz, max_value=None, colormap='hot')\n tgt_img_viz_im = Image.fromarray((255*tgt_img_viz).astype('uint8'))\n tgt_img_viz_im.save(viz_dir/str(j).zfill(4)+'img.png')\n depth_viz_im = Image.fromarray((255*depth_viz).astype('uint8'))\n depth_viz_im.save(viz_dir/str(j).zfill(4)+'depth.png')\n gt_viz_im = Image.fromarray((255*gt_viz).astype('uint8'))\n gt_viz_im.save(viz_dir/str(j).zfill(4)+'gt.png')\n\n\n pred_depth = 1/pred_disp\n pred_depth_zoomed = zoom(pred_depth, (gt_depth.shape[0]/pred_depth.shape[0],gt_depth.shape[1]/pred_depth.shape[1])).clip(args.min_depth, args.max_depth)\n if sample['mask'] is not None:\n pred_depth_zoomed = pred_depth_zoomed[sample['mask']]\n gt_depth = gt_depth[sample['mask']]\n\n if seq_length > 0:\n _, poses = pose_net(tgt_img_var, ref_imgs_var)\n displacements = poses[0,:,:3].norm(2,1).cpu().data.numpy() # shape [1 - seq_length]\n\n scale_factors = [s1/s2 for s1, s2 in zip(sample['displacements'], displacements) if s1 > 0]\n scale_factor = np.mean(scale_factors) if len(scale_factors) > 0 else 0\n if len(scale_factors) == 0:\n print('not good ! ', sample['path'], sample['displacements'])\n errors[0,:,j] = compute_errors(gt_depth, pred_depth_zoomed*scale_factor)\n\n scale_factor = np.median(gt_depth)/np.median(pred_depth_zoomed)\n errors[1,:,j] = compute_errors(gt_depth, pred_depth_zoomed*scale_factor)\n\n mean_errors = errors.mean(2)\n error_names = ['abs_rel','sq_rel','rms','log_rms','a1','a2','a3']\n if args.pretrained_posenet:\n print(\"Results with scale factor determined by PoseNet : \")\n print(\"{:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}\".format(*error_names))\n print(\"{:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}\".format(*mean_errors[0]))\n\n print(\"Results with scale factor determined by GT/prediction ratio (like the original paper) : \")\n print(\"{:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}\".format(*error_names))\n print(\"{:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}, {:10.4f}\".format(*mean_errors[1]))\n\n if args.output_dir is not None:\n np.save(output_dir/'predictions.npy', predictions)\n\ndef interp_gt_disp(mat, mask_val=0):\n mat[mat==mask_val] = np.nan\n x = np.arange(0, mat.shape[1])\n y = np.arange(0, mat.shape[0])\n mat = np.ma.masked_invalid(mat)\n xx, yy = np.meshgrid(x, y)\n #get only the valid values\n x1 = xx[~mat.mask]\n y1 = yy[~mat.mask]\n newarr = mat[~mat.mask]\n\n GD1 = interpolate.griddata((x1, y1), newarr.ravel(), (xx, yy), method='linear', fill_value=mask_val)\n return GD1\n\ndef compute_errors(gt, pred):\n thresh = np.maximum((gt / pred), (pred / gt))\n a1 = (thresh < 1.25 ).mean()\n a2 = (thresh < 1.25 ** 2).mean()\n a3 = (thresh < 1.25 ** 3).mean()\n\n rmse = (gt - pred) ** 2\n rmse = np.sqrt(rmse.mean())\n\n rmse_log = (np.log(gt) - np.log(pred)) ** 2\n rmse_log = np.sqrt(rmse_log.mean())\n\n abs_rel = np.mean(np.abs(gt - pred) / gt)\n\n sq_rel = np.mean(((gt - pred)**2) / gt)\n\n return abs_rel, sq_rel, rmse, rmse_log, a1, a2, a3\n\n\nif __name__ == '__main__':\n main()\n", "# Author: Anurag Ranjan\n# Copyright (c) 2019, Anurag Ranjan\n# All rights reserved.\n\nimport torch\nimport torch.nn as nn\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\ndef conv(in_planes, out_planes, kernel_size=3, stride=2):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)//2, stride=stride),\n nn.ReLU(inplace=True)\n )\n\n\ndef upconv(in_planes, out_planes):\n return nn.Sequential(\n nn.ConvTranspose2d(in_planes, out_planes, kernel_size=4, stride=2, padding=1),\n nn.ReLU(inplace=True)\n )\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\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.relu(out)\n out = self.conv2(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\ndef make_layer(inplanes, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample))\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(inplanes, planes))\n\n return nn.Sequential(*layers)\n\nclass MaskResNet6(nn.Module):\n\n def __init__(self, nb_ref_imgs=4, output_exp=True):\n super(MaskResNet6, self).__init__()\n self.nb_ref_imgs = nb_ref_imgs\n self.output_exp = output_exp\n\n conv_planes = [16, 32, 64, 128, 256, 256, 256, 256]\n self.conv1 = conv(3*(1+self.nb_ref_imgs), conv_planes[0], kernel_size=7, stride=2)\n self.conv2 = make_layer(conv_planes[0], BasicBlock, conv_planes[1], blocks=2, stride=2)\n self.conv3 = make_layer(conv_planes[1], BasicBlock, conv_planes[2], blocks=2, stride=2)\n self.conv4 = make_layer(conv_planes[2], BasicBlock, conv_planes[3], blocks=2, stride=2)\n self.conv5 = make_layer(conv_planes[3], BasicBlock, conv_planes[4], blocks=2, stride=2)\n self.conv6 = make_layer(conv_planes[4], BasicBlock, conv_planes[5], blocks=2, stride=2)\n\n if self.output_exp:\n upconv_planes = [256, 256, 128, 64, 32, 16]\n self.deconv6 = upconv(conv_planes[5], upconv_planes[0])\n self.deconv5 = upconv(upconv_planes[0]+conv_planes[4], upconv_planes[1])\n self.deconv4 = upconv(upconv_planes[1]+conv_planes[3], upconv_planes[2])\n self.deconv3 = upconv(upconv_planes[2]+conv_planes[2], upconv_planes[3])\n self.deconv2 = upconv(upconv_planes[3]+conv_planes[1], upconv_planes[4])\n self.deconv1 = upconv(upconv_planes[4]+conv_planes[0], upconv_planes[5])\n\n self.pred_mask6 = nn.Conv2d(upconv_planes[0], self.nb_ref_imgs, kernel_size=3, padding=1)\n self.pred_mask5 = nn.Conv2d(upconv_planes[1], self.nb_ref_imgs, kernel_size=3, padding=1)\n self.pred_mask4 = nn.Conv2d(upconv_planes[2], self.nb_ref_imgs, kernel_size=3, padding=1)\n self.pred_mask3 = nn.Conv2d(upconv_planes[3], self.nb_ref_imgs, kernel_size=3, padding=1)\n self.pred_mask2 = nn.Conv2d(upconv_planes[4], self.nb_ref_imgs, kernel_size=3, padding=1)\n self.pred_mask1 = nn.Conv2d(upconv_planes[5], self.nb_ref_imgs, kernel_size=3, padding=1)\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.xavier_uniform(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def init_mask_weights(self):\n for m in self.modules():\n if isinstance(m, nn.ConvTranspose2d):\n nn.init.xavier_uniform(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n for module in [self.pred_mask1, self.pred_mask2, self.pred_mask3, self.pred_mask4, self.pred_mask5, self.pred_mask6]:\n for m in module.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.xavier_uniform(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n\n\n def forward(self, target_image, ref_imgs):\n assert(len(ref_imgs) == self.nb_ref_imgs)\n input = [target_image]\n input.extend(ref_imgs)\n input = torch.cat(input, 1)\n out_conv1 = self.conv1(input)\n out_conv2 = self.conv2(out_conv1)\n out_conv3 = self.conv3(out_conv2)\n out_conv4 = self.conv4(out_conv3)\n out_conv5 = self.conv5(out_conv4)\n out_conv6 = self.conv6(out_conv5)\n\n if self.output_exp:\n out_upconv6 = self.deconv6(out_conv6 )#[:, :, 0:out_conv5.size(2), 0:out_conv5.size(3)]\n out_upconv5 = self.deconv5(torch.cat((out_upconv6, out_conv5), 1))#[:, :, 0:out_conv4.size(2), 0:out_conv4.size(3)]\n out_upconv4 = self.deconv4(torch.cat((out_upconv5, out_conv4), 1))#[:, :, 0:out_conv3.size(2), 0:out_conv3.size(3)]\n out_upconv3 = self.deconv3(torch.cat((out_upconv4, out_conv3), 1))#[:, :, 0:out_conv2.size(2), 0:out_conv2.size(3)]\n out_upconv2 = self.deconv2(torch.cat((out_upconv3, out_conv2), 1))#[:, :, 0:out_conv1.size(2), 0:out_conv1.size(3)]\n out_upconv1 = self.deconv1(torch.cat((out_upconv2, out_conv1), 1))#[:, :, 0:input.size(2), 0:input.size(3)]\n\n exp_mask6 = nn.functional.sigmoid(self.pred_mask6(out_upconv6))\n exp_mask5 = nn.functional.sigmoid(self.pred_mask5(out_upconv5))\n exp_mask4 = nn.functional.sigmoid(self.pred_mask4(out_upconv4))\n exp_mask3 = nn.functional.sigmoid(self.pred_mask3(out_upconv3))\n exp_mask2 = nn.functional.sigmoid(self.pred_mask2(out_upconv2))\n exp_mask1 = nn.functional.sigmoid(self.pred_mask1(out_upconv1))\n else:\n exp_mask6 = None\n exp_mask5 = None\n exp_mask4 = None\n exp_mask3 = None\n exp_mask2 = None\n exp_mask1 = None\n\n if self.training:\n return exp_mask1, exp_mask2, exp_mask3, exp_mask4, exp_mask5, exp_mask6\n else:\n return exp_mask1\n" ]
[ [ "numpy.log", "scipy.misc.imresize", "numpy.maximum", "numpy.abs", "torch.load", "numpy.arange", "numpy.median", "torch.from_numpy", "numpy.save", "numpy.ma.masked_invalid", "numpy.mean", "torch.FloatTensor", "numpy.transpose", "numpy.meshgrid", "scipy.ndimage.interpolation.zoom", "torch.autograd.Variable" ], [ "torch.nn.Sequential", "torch.nn.ConvTranspose2d", "torch.cat", "torch.nn.Conv2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.init.xavier_uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.10", "0.16", "0.19", "0.18", "0.12", "1.0", "0.17", "1.2" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qweas120/Active_VLN
[ "d5dabd5fe6127bcfec023b90f14a4ba5ac671f9b" ]
[ "active/model.py" ]
[ "\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom param import args\nimport numpy as np\n\ndef check(ar):\n ar = ar.cpu().detach().numpy()\n return np.any(np.isnan(ar))\n\ndef check2(ar):\n # ar = ar.cpu().numpy()\n return np.any(np.isnan(ar))\n\nimport utils\nTRAIN_VOCAB = '../tasks/R2R/data/train_vocab.txt'\nvocab = utils.read_vocab(TRAIN_VOCAB)\ntok = utils.Tokenizer(vocab=vocab, encoding_length=args.maxInput)\n\n#\nclass EncoderLSTM(nn.Module):\n ''' Encodes navigation instructions, returning hidden state context (for\n attention methods) and a decoder initial state. '''\n\n def __init__(self, vocab_size, embedding_size, hidden_size, padding_idx, \n dropout_ratio, bidirectional=False, num_layers=1):\n super(EncoderLSTM, self).__init__()\n self.embedding_size = embedding_size\n self.hidden_size = hidden_size\n self.drop = nn.Dropout(p=dropout_ratio)\n if bidirectional:\n print(\"Using Bidir in EncoderLSTM\")\n self.num_directions = 2 if bidirectional else 1\n self.num_layers = num_layers\n self.embedding = nn.Embedding(vocab_size, embedding_size, padding_idx)\n input_size = embedding_size\n self.lstm = nn.LSTM(input_size, hidden_size, self.num_layers,\n batch_first=True, dropout=dropout_ratio, \n bidirectional=bidirectional)\n self.encoder2decoder = nn.Linear(hidden_size * self.num_directions,\n hidden_size * self.num_directions\n )\n\n def init_state(self, inputs):\n ''' Initialize to zero cell states and hidden states.'''\n batch_size = inputs.size(0)\n h0 = Variable(torch.zeros(\n self.num_layers * self.num_directions,\n batch_size,\n self.hidden_size\n ), requires_grad=False)\n c0 = Variable(torch.zeros(\n self.num_layers * self.num_directions,\n batch_size,\n self.hidden_size\n ), requires_grad=False)\n\n return h0.cuda(), c0.cuda()\n\n def forward(self, inputs, lengths):\n ''' Expects input vocab indices as (batch, seq_len). Also requires a \n list of lengths for dynamic batching. '''\n embeds = self.embedding(inputs) # (batch, seq_len, embedding_size)\n if check(embeds):\n print('embeds before drop')\n print(embeds)\n embeds = self.drop(embeds)\n h0, c0 = self.init_state(inputs)\n packed_embeds = pack_padded_sequence(embeds, lengths, batch_first=True)\n enc_h, (enc_h_t, enc_c_t) = self.lstm(packed_embeds, (h0, c0))\n \n if check(embeds):\n print('embeds')\n print(embeds)\n embeds_np = embeds.cpu().detach().numpy()\n inputs_np = inputs.cpu().detach().numpy()\n for i,sen in enumerate(embeds_np):\n sen_o = inputs_np[i]\n for j,v in enumerate(sen):\n v_o = sen_o[j]\n if check2(v):\n print('sentence',i,'vab',j,'id',v_o,tok.index_to_word[v_o])\n \n \n # if check2(enc_h):\n # print('enc_h')\n # print(enc_h)\n\n # if check2(enc_h_t):\n # print('enc_h_t')\n # print(enc_h_t)\n \n # if check2(enc_c_t):\n # print('enc_c_t')\n # print(enc_c_t)\n\n if self.num_directions == 2: # The size of enc_h_t is (num_layers * num_directions, batch, hidden_size)\n h_t = torch.cat((enc_h_t[-1], enc_h_t[-2]), 1)\n c_t = torch.cat((enc_c_t[-1], enc_c_t[-2]), 1)\n else:\n h_t = enc_h_t[-1]\n c_t = enc_c_t[-1] # (batch, hidden_size)\n\n ctx, _ = pad_packed_sequence(enc_h, batch_first=True)\n\n if args.sub_out == \"max\":\n ctx_max, _ = ctx.max(1)\n decoder_init = nn.Tanh()(self.encoder2decoder(ctx_max))\n elif args.sub_out == \"tanh\":\n decoder_init = nn.Tanh()(self.encoder2decoder(h_t))\n else:\n assert False\n\n ctx = self.drop(ctx)\n if args.zero_init:\n return ctx, torch.zeros_like(decoder_init), torch.zeros_like(c_t)\n else:\n return ctx, decoder_init, c_t # (batch, seq_len, hidden_size*num_directions)\n # (batch, hidden_size)\n\n#\nclass SoftDotAttention(nn.Module):\n '''Soft Dot Attention. \n\n Ref: http://www.aclweb.org/anthology/D15-1166\n Adapted from PyTorch OPEN NMT.\n '''\n\n def __init__(self, query_dim, ctx_dim):\n '''Initialize layer.'''\n super(SoftDotAttention, self).__init__()\n self.linear_in = nn.Linear(query_dim, ctx_dim, bias=False)\n self.sm = nn.Softmax()\n self.linear_out = nn.Linear(query_dim + ctx_dim, query_dim, bias=False)\n self.tanh = nn.Tanh()\n\n def forward(self, h, context, mask=None,\n output_tilde=True, output_prob=True):\n '''Propagate h through the network.\n\n h: batch x dim\n context: batch x seq_len x dim\n mask: batch x seq_len indices to be masked\n '''\n target = self.linear_in(h).unsqueeze(2) # batch x dim x 1\n # print(context.shape, target.shape)\n # Get attention\n attn = torch.bmm(context, target).squeeze(2) # batch x seq_len\n logit = attn\n\n if mask is not None:\n # -Inf masking prior to the softmax\n attn.masked_fill_(mask, -float('inf'))\n attn = self.sm(attn) # There will be a bug here, but it's actually a problem in torch source code.\n attn3 = attn.view(attn.size(0), 1, attn.size(1)) # batch x 1 x seq_len\n\n weighted_context = torch.bmm(attn3, context).squeeze(1) # batch x dim\n if not output_prob:\n attn = logit\n if output_tilde:\n h_tilde = torch.cat((weighted_context, h), 1)\n h_tilde = self.tanh(self.linear_out(h_tilde))\n return h_tilde, weighted_context, attn\n else:\n return weighted_context, attn\n\n\n#\nclass AttnDecoderLSTM(nn.Module):\n ''' An unrolled LSTM with attention over instructions for decoding navigation actions. '''\n\n def __init__(self, embedding_size, hidden_size,\n dropout_ratio, feature_size=2048+4):\n super(AttnDecoderLSTM, self).__init__()\n self.embedding_size = embedding_size\n self.feature_size = feature_size\n self.hidden_size = hidden_size\n self.embedding = nn.Sequential(\n nn.Linear(args.angle_feat_size, self.embedding_size),\n nn.Tanh()\n )\n self.drop = nn.Dropout(p=dropout_ratio)\n self.drop_env = nn.Dropout(p=args.featdropout)\n self.lstm = nn.LSTMCell(embedding_size+feature_size, hidden_size)\n self.feat_att_layer = SoftDotAttention(hidden_size, feature_size)\n self.attention_layer = SoftDotAttention(hidden_size, hidden_size)\n self.candidate_att_layer = SoftDotAttention(hidden_size, feature_size)\n\n def forward(self, action, feature, cand_feat,\n h_0, prev_h1, c_0,\n ctx, ctx_mask=None,\n already_dropfeat=False,\n h_1_res=None,\n cand_flag=False\n ):\n '''\n Takes a single step in the decoder LSTM (allowing sampling).\n action: batch x angle_feat_size\n feature: batch x 36 x (feature_size + angle_feat_size)\n cand_feat: batch x cand x (feature_size + angle_feat_size)\n h_0: batch x hidden_size\n prev_h1: batch x hidden_size\n c_0: batch x hidden_size\n ctx: batch x seq_len x dim\n ctx_mask: batch x seq_len - indices to be masked\n already_dropfeat: used in EnvDrop\n h_1_res: batch x hidden_size\n '''\n action_embeds = self.embedding(action)\n\n # Adding Dropout\n action_embeds = self.drop(action_embeds)\n\n # if not already_dropfeat:\n # # Dropout the raw feature as a common regularization\n # feature[..., :-args.angle_feat_size] = self.drop_env(feature[..., :-args.angle_feat_size]) # Do not drop the last args.angle_feat_size (position feat)\n if not already_dropfeat:\n # Dropout the raw feature as a common regularization\n f = self.drop_env(feature[..., :-args.angle_feat_size])\n a = feature[..., -args.angle_feat_size:]\n feature = torch.cat([f, a],-1)\n # feature[..., :-args.angle_feat_size] = self.drop_env(feature[..., :-args.angle_feat_size]) # Do not drop the last args.angle_feat_size (position feat)\n\n\n\n prev_h1_drop = self.drop(prev_h1)\n attn_feat, _ = self.feat_att_layer(prev_h1_drop, feature, output_tilde=False)\n\n concat_input = torch.cat((action_embeds, attn_feat), 1) # (batch, embedding_size+feature_size)\n h_1, c_1 = self.lstm(concat_input, (prev_h1, c_0))\n\n h_1_drop = self.drop(h_1)\n h_tilde, u_tilde, alpha = self.attention_layer(h_1_drop, ctx, ctx_mask)\n\n if not h_1_res is None:\n # for i in range(10):\n # print('res',h_1_res[0][i*8:(i+1)*8])\n # print('aft',h_tilde[0][i*8:(i+1)*8])\n # print()\n h_tilde = h_tilde + h_1_res \n \n\n # Adding Dropout\n h_tilde_drop = self.drop(h_tilde)\n\n # if not already_dropfeat:\n # cand_feat[..., :-args.angle_feat_size] = self.drop_env(cand_feat[..., :-args.angle_feat_size])\n\n if not already_dropfeat and not cand_feat is None:\n f = self.drop_env(cand_feat[..., :-args.angle_feat_size])\n a = cand_feat[..., -args.angle_feat_size:]\n cand_feat = torch.cat([f, a],-1)\n \n if not cand_feat is None:\n _, _, logit = self.candidate_att_layer(h_tilde_drop, cand_feat, output_prob=False)\n\n if cand_flag:\n seq_len = cand_feat.shape[1]\n h_tilde_drop_repeat = h_tilde_drop.repeat(seq_len,1,1).permute(1,0,2)\n feature_in = torch.cat([cand_feat, h_tilde_drop_repeat], -1) # batch x seq_len x feature_size + dim\n return h_1, c_1, logit, h_tilde, attn_feat, u_tilde, feature_in\n\n return h_1, c_1, logit, h_tilde, attn_feat, u_tilde\n \n return h_1, c_1, h_tilde, attn_feat, u_tilde\n\n\n#\nclass AttnGobalPolicyLSTM_v2(nn.Module):\n ''' An unrolled LSTM with attention over instructions for decoding navigation actions. '''\n\n def __init__(self, hidden_size,\n dropout_ratio, feature_size=2048+4):\n super(AttnGobalPolicyLSTM_v2, self).__init__()\n self.feature_size = feature_size\n self.hidden_size = hidden_size\n \n self.drop = nn.Dropout(p=dropout_ratio)\n self.drop_env = nn.Dropout(p=args.featdropout)\n\n self.candidate_att_layer = SoftDotAttention(hidden_size, feature_size)\n self.linear = nn.Linear(hidden_size, feature_size, bias=False)\n self.linear_entropy = nn.Linear(1, 1, bias=True)\n self.lstm = nn.LSTMCell(feature_size, hidden_size)\n\n def forward(self, cand_feat, prev_h1, c_0, entropy\n ):\n '''\n Takes a single step in the decoder LSTM (allowing sampling).\n cand_feat: batch x cand x (feature_size + angle_feat_size)\n h1: batch x hidden_size\n '''\n\n # if not already_dropfeat and not cand_feat is None:\n # f = self.drop_env(cand_feat[..., :-args.angle_feat_size])\n # a = cand_feat[..., -args.angle_feat_size:]\n # cand_feat = torch.cat([f, a],-1)\n\n # h1_drop = self.drop(h1)\n\n entropy = entropy.unsqueeze(1) # batch x 1\n\n\n _, attn_cand_feat, _ = self.candidate_att_layer(prev_h1, cand_feat)\n\n h_1, c_1 = self.lstm(attn_cand_feat, (prev_h1, c_0))\n \n\n attn_cand_feat = attn_cand_feat.unsqueeze(1) # batch x 1 x dim\n\n target = self.linear(h_1).unsqueeze(2) # batch x dim x 1\n logit = torch.bmm(attn_cand_feat,target).squeeze() + self.linear_entropy(entropy).squeeze() # batch\n\n prob = torch.sigmoid(logit)\n \n return prob, attn_cand_feat.squeeze(), h_1, c_1\n\nclass AttnGobalPolicyLSTM_v4(nn.Module):\n ''' An unrolled LSTM with attention over instructions for decoding navigation actions. '''\n\n def __init__(self, hidden_size,\n dropout_ratio, feature_size=2048+4):\n super(AttnGobalPolicyLSTM_v4, self).__init__()\n self.feature_size = feature_size\n self.hidden_size = hidden_size\n \n self.lrelu = nn.LeakyReLU(0.1)\n self.linear_entropy = nn.Linear(1, self.hidden_size, bias=True)\n self.linear_last = nn.Linear(self.hidden_size * 2, 1)\n\n def forward(self, h1, entropy\n ):\n '''\n Takes a single step in the decoder LSTM (allowing sampling).\n cand_feat: batch x cand x (feature_size + angle_feat_size)\n h1: batch x hidden_size\n '''\n\n # if not already_dropfeat and not cand_feat is None:\n # f = self.drop_env(cand_feat[..., :-args.angle_feat_size])\n # a = cand_feat[..., -args.angle_feat_size:]\n # cand_feat = torch.cat([f, a],-1)\n\n # h1_drop = self.drop(h1)\n\n entropy = entropy.unsqueeze(1) # batch x 1\n\n target = self.linear_entropy(entropy).squeeze() # batch x 512\n target = self.lrelu(target)\n target = torch.cat([target,h1],-1) # batch x 1024\n logit = self.linear_last(target).squeeze() # batch x 1\n\n prob = torch.sigmoid(logit)\n \n return prob\n\n\n\nclass FullyConnected2(nn.Module):\n def __init__(self, hidden_size, output_size):\n super(FullyConnected2, self).__init__()\n self.lrelu = nn.LeakyReLU(0.1)\n self.linear_layer = nn.Linear(hidden_size, hidden_size, bias=True)\n self.linear_layer_1 = nn.Linear(hidden_size, output_size, bias=False)\n\n def forward(self, input):\n out = self.lrelu(self.linear_layer(input))\n return self.linear_layer_1(out)\n\nclass FullyConnected(nn.Module):\n def __init__(self, hidden_size, output_size):\n super(FullyConnected, self).__init__()\n self.lrelu = nn.LeakyReLU(0.1)\n self.linear_layer = nn.Linear(hidden_size, output_size, bias=False)\n\n def forward(self, input):\n out = self.lrelu(self.linear_layer(input))\n return out\n\n\n\nclass Critic(nn.Module):\n def __init__(self,in_dim=args.rnn_dim):\n super(Critic, self).__init__()\n self.state2value = nn.Sequential(\n nn.Linear(in_dim, args.rnn_dim),\n nn.ReLU(),\n nn.Dropout(args.dropout),\n nn.Linear(args.rnn_dim, 1),\n )\n\n def forward(self, state):\n return self.state2value(state).squeeze()\n\nclass SpeakerEncoder(nn.Module):\n def __init__(self, feature_size, hidden_size, dropout_ratio, bidirectional):\n super().__init__()\n self.num_directions = 2 if bidirectional else 1\n self.hidden_size = hidden_size\n self.num_layers = 1\n self.feature_size = feature_size\n\n if bidirectional:\n print(\"BIDIR in speaker encoder!!\")\n\n self.lstm = nn.LSTM(feature_size, self.hidden_size // self.num_directions, self.num_layers,\n batch_first=True, dropout=dropout_ratio, bidirectional=bidirectional)\n self.drop = nn.Dropout(p=dropout_ratio)\n self.drop3 = nn.Dropout(p=args.featdropout)\n self.attention_layer = SoftDotAttention(self.hidden_size, feature_size)\n\n self.post_lstm = nn.LSTM(self.hidden_size, self.hidden_size // self.num_directions, self.num_layers,\n batch_first=True, dropout=dropout_ratio, bidirectional=bidirectional)\n\n def forward(self, action_embeds, feature, lengths, already_dropfeat=False):\n \"\"\"\n :param action_embeds: (batch_size, length, 2052). The feature of the view\n :param feature: (batch_size, length, 36, 2052). The action taken (with the image feature)\n :param lengths: Not used in it\n :return: context with shape (batch_size, length, hidden_size)\n \"\"\"\n x = action_embeds\n if not already_dropfeat:\n x[..., :-args.angle_feat_size] = self.drop3(x[..., :-args.angle_feat_size]) # Do not dropout the spatial features\n\n # LSTM on the action embed\n ctx, _ = self.lstm(x)\n ctx = self.drop(ctx)\n\n # Att and Handle with the shape\n batch_size, max_length, _ = ctx.size()\n if not already_dropfeat:\n feature[..., :-args.angle_feat_size] = self.drop3(feature[..., :-args.angle_feat_size]) # Dropout the image feature\n x, _, _ = self.attention_layer( # Attend to the feature map\n ctx.contiguous().view(-1, self.hidden_size), # (batch, length, hidden) --> (batch x length, hidden)\n feature.view(batch_size * max_length, -1, self.feature_size), # (batch, length, # of images, feature_size) --> (batch x length, # of images, feature_size)\n )\n x = x.view(batch_size, max_length, -1)\n x = self.drop(x)\n\n # Post LSTM layer\n x, _ = self.post_lstm(x)\n x = self.drop(x)\n\n return x\n\nclass SpeakerDecoder(nn.Module):\n def __init__(self, vocab_size, embedding_size, padding_idx, hidden_size, dropout_ratio):\n super().__init__()\n self.hidden_size = hidden_size\n self.embedding = torch.nn.Embedding(vocab_size, embedding_size, padding_idx)\n self.lstm = nn.LSTM(embedding_size, hidden_size, batch_first=True)\n self.drop = nn.Dropout(dropout_ratio)\n self.attention_layer = SoftDotAttention(hidden_size, hidden_size)\n self.projection = nn.Linear(hidden_size, vocab_size)\n self.baseline_projection = nn.Sequential(\n nn.Linear(hidden_size, 128),\n nn.ReLU(),\n nn.Dropout(dropout_ratio),\n nn.Linear(128, 1)\n )\n\n def forward(self, words, ctx, ctx_mask, h0, c0):\n embeds = self.embedding(words)\n embeds = self.drop(embeds)\n x, (h1, c1) = self.lstm(embeds, (h0, c0))\n\n x = self.drop(x) # batch x seq_length x feature_size\n\n # Get the size\n batchXlength = words.size(0) * words.size(1)\n multiplier = batchXlength // ctx.size(0) # By using this, it also supports the beam-search\n # print(words.size(1), multiplier, ctx.size(0))\n feature_size = ctx.size(2)\n\n # Att and Handle with the shape\n # Reshaping x <the output> --> (b(word)*l(word), r)\n # Expand the ctx from (b, a, r) --> (b(word)*l(word), a, r)\n # Expand the ctx_mask (b, a) --> (b(word)*l(word), a)\n # x, _, _ = self.attention_layer(\n # x.contiguous().view(batchXlength, self.hidden_size),\n # ctx.unsqueeze(1).expand(-1, multiplier, -1, -1).contiguous().view(batchXlength, -1, self.hidden_size),\n # mask=ctx_mask.unsqueeze(1).expand(-1, multiplier, -1).contiguous().view(batchXlength, -1)\n # )\n x, _, _ = self.attention_layer(\n x.contiguous().view(batchXlength, self.hidden_size),\n ctx.unsqueeze(1).expand(-1, multiplier, -1, -1).contiguous().view(batchXlength, -1, feature_size),\n mask=ctx_mask.unsqueeze(1).expand(-1, multiplier, -1).contiguous().view(batchXlength, -1)\n )\n x = x.view(words.size(0), words.size(1), self.hidden_size)\n\n # Output the prediction logit\n x = self.drop(x)\n logit = self.projection(x)\n\n return logit, h1, c1\n\n\nclass SpeakerDecoder_v2(nn.Module):\n def __init__(self, vocab_size, embedding_size, padding_idx, hidden_size, feature_size, dropout_ratio):\n super().__init__()\n self.hidden_size = hidden_size\n self.embedding = torch.nn.Embedding(vocab_size, embedding_size, padding_idx)\n self.lstm = nn.LSTM(embedding_size, hidden_size, batch_first=True)\n self.drop = nn.Dropout(dropout_ratio)\n self.attention_layer = SoftDotAttention(hidden_size, feature_size)\n self.projection = nn.Linear(hidden_size, vocab_size)\n self.baseline_projection = nn.Sequential(\n nn.Linear(hidden_size, 128),\n nn.ReLU(),\n nn.Dropout(dropout_ratio),\n nn.Linear(128, 1)\n )\n\n def forward(self, words, ctx, ctx_mask, h0, c0):\n embeds = self.embedding(words)\n embeds = self.drop(embeds)\n x, (h1, c1) = self.lstm(embeds, (h0, c0))\n\n x = self.drop(x) # batch x seq_length x feature_size\n\n # Get the size\n batchXlength = words.size(0) * words.size(1)\n multiplier = batchXlength // ctx.size(0) # By using this, it also supports the beam-search\n # print(words.size(1), multiplier, ctx.size(0))\n feature_size = ctx.size(2)\n\n # Att and Handle with the shape\n # Reshaping x <the output> --> (b(word)*l(word), r)\n # Expand the ctx from (b, a, r) --> (b(word)*l(word), a, r)\n # Expand the ctx_mask (b, a) --> (b(word)*l(word), a)\n # x, _, _ = self.attention_layer(\n # x.contiguous().view(batchXlength, self.hidden_size),\n # ctx.unsqueeze(1).expand(-1, multiplier, -1, -1).contiguous().view(batchXlength, -1, self.hidden_size),\n # mask=ctx_mask.unsqueeze(1).expand(-1, multiplier, -1).contiguous().view(batchXlength, -1)\n # )\n x, _, _ = self.attention_layer(\n x.contiguous().view(batchXlength, self.hidden_size),\n ctx.unsqueeze(1).expand(-1, multiplier, -1, -1).contiguous().view(batchXlength, -1, feature_size),\n mask=ctx_mask.unsqueeze(1).expand(-1, multiplier, -1).contiguous().view(batchXlength, -1)\n )\n x = x.view(words.size(0), words.size(1), self.hidden_size)\n\n # Output the prediction logit\n x = self.drop(x)\n logit = self.projection(x)\n\n return logit, h1, c1\n\n\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Dropout", "torch.sigmoid", "torch.nn.LSTM", "numpy.isnan", "torch.cat", "torch.zeros", "torch.zeros_like", "torch.nn.Embedding", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Tanh", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.LSTMCell", "torch.nn.LeakyReLU", "torch.bmm", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
togaras1/gengochi
[ "374309d5996c0b4a8c5bdda27863597d2b7b11fb" ]
[ "datasets.py" ]
[ "import os\nimport sys\n\nimport numpy as np\nimport six\nimport glob\nfrom PIL import Image\n\nimport chainer\nfrom chainer import datasets\n\nclass gengochi_train(object):\n def __init__(self, size_to=128):\n # testdata / traindataを作るとしたらディレクトリを分ける。\n # ラベルはtsvかcsvを作り関連付けするかファイル名。\n self.size = size_to\n path = \"image/gochi/*.png\" #\"image/gochi/*.png\"\n imgs = glob.glob(path)\n self.rawdata = []\n for j in range(100): # generate anime image\n for i in imgs:\n # alphaチャンネルつきPNGだったときのために一応3チャンネルに変換\n self.rawdata.append(np.asarray(Image.open(i).convert(\"RGB\").resize((size_to,size_to))))\n\n # refar to... chainer/datasets/cifar.py\n # cifarライクなデータセットなので参考にした\n def _get_gochiusa(self, withlabel=True, ndim=3, scale=1, dtype=None):\n images = np.asarray(self.rawdata)\n if ndim == 1: # i,x,y,rgb to i,r,g,b\n images = images.transpose(0,3,1,2).reshape(-1,3*self.size*self.size)\n elif ndim == 3:\n images = images.transpose(0,3,1,2)\n images = images.astype(\"f\")\n images *= scale / 255.\n\n #if withlabel:\n # labels = labels.astype(numpy.int32)\n # return tuple_dataset.TupleDataset(images, labels)\n #else:\n print('{} images are loaded'.format(images.shape))\n return images\n" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wvandertoorn/nanoRMS
[ "e3d41b4c0bd9ca16355f313494d288ea73eee6bb" ]
[ "per_read/get_features.py" ]
[ "#!/usr/bin/env python3\ndesc=\"\"\"Requiggle basecalled FastQ files and features in BAM file. \n\nFor all reference bases we store (as BAM comments):\n- normalised signal intensity mean [tag si:B,f]\n- reference base probability [tag tr:B:C] retrieved from guppy (trace scaled 0-255)\n- dwell time [tag dt:B:C] in signal step capped at 255\n\nAll features are matched versus padded reference sequnce blocks \nie excluding introns and large (padded) deletions from reference. \nThose blocks (2-D array of start & ends) are stored as flattened 1-D array [tag bs:B:i]\nie. exons [(8114, 8244), (8645, 8797)] will be stored as array('I', [8114, 8244, 8645, 8797]). \n\n--rna will automatically enable spliced alignments. \n\"\"\"\nepilog=\"\"\"Author: [email protected]\nCologne/Barcelona/Mizerów, 17/06/2020\n\"\"\"\n\nimport itertools, json, os, resource, scipy, subprocess, sys, numpy as np, pysam, tempfile\nfrom tombo import tombo_stats, resquiggle, tombo_helper\nfrom tombo._default_parameters import OUTLIER_THRESH, SHIFT_CHANGE_THRESH, SCALE_CHANGE_THRESH, RNA_SAMP_TYPE, DNA_SAMP_TYPE, COLLAPSE_RNA_STALLS, COLLAPSE_DNA_STALLS, STALL_PARAMS#, FM_OFFSET_DEFAULT\nfrom ont_fast5_api.fast5_interface import get_fast5_file\nfrom datetime import datetime\nfrom multiprocessing import Pool\nfrom array import array\nfrom copy import deepcopy\n# add PATH - needed by fast5_to_fastq.py\nos.environ[\"PATH\"] = \"%s:%s\"%(':'.join(sys.path), os.environ[\"PATH\"]) \n\nVERSION = '0.11b'\nDEFAULT_STALL_PARAMS = tombo_helper.stallParams(**STALL_PARAMS)\nUSE_START_CLIP_BASES = resquiggle.USE_START_CLIP_BASES\n\n# only DNA bases as in SAM U is always referred as T\nbases = \"ACGT\"\nbase2idx = {b: i for i, b in enumerate(bases)}\nbase2complement = {\"A\": \"T\", \"T\": \"A\", \"C\": \"G\", \"G\": \"C\", \"N\": \"N\"}\n# add lower-case for get_aligned_pairs as it reports substitutions as lower-case\nfor b, i in list(base2idx.items()): base2idx[b.lower()] = i\nfor b, c in list(base2complement.items()): base2complement[b.lower()] = c\n\ndef minimap2_proc(ref, fast5, threads=1, spliced=0, sensitive=1): \n \"\"\"Run minimap2 and return its stdout\"\"\"\n mode = [\"-axmap-ont\", ]\n if spliced:\n mode = [\"-axsplice\", \"-uf\"]\n args1 = [\"minimap2\", \"--MD\", \"-Y\", \"-t%s\"%threads] + mode\n if sensitive:\n args1 += [\"-k7\", \"-w5\", \"-m20\", \"-A6\", \"-B4\"]\n args1 += [ref, \"-\"]\n # fast5_to_fastq\n args0 = [\"fast5_to_fastq.py\", \"-i%s\"%fast5]\n proc0 = subprocess.Popen(args0, stdout=subprocess.PIPE)\n # minimap2\n proc1 = subprocess.Popen(args1, stdin=proc0.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return proc1\n\ndef adjust_map_res(map_res, seq_samp_type, rsqgl_params, TRIM_RNA_ADAPTER=False):\n if seq_samp_type.name == RNA_SAMP_TYPE:\n if TRIM_RNA_ADAPTER:\n # trim DNA adapter off of RNA signal\n adapter_end = tombo_stats.trim_rna(map_res.raw_signal, rsqgl_params)\n # trim off adapter\n map_res = map_res._replace(raw_signal=map_res.raw_signal[adapter_end:])\n\n # flip raw signal for re-squiggling\n map_res = map_res._replace(raw_signal=map_res.raw_signal[::-1])\n\n elif seq_samp_type.name == DNA_SAMP_TYPE and USE_START_CLIP_BASES:\n # flip raw signal, genome and start clip seqs for re-squiggling\n map_res = map_res._replace(\n raw_signal=map_res.raw_signal[::-1],\n genome_seq=map_res.genome_seq[::-1])\n\n if ((COLLAPSE_RNA_STALLS and seq_samp_type.name == RNA_SAMP_TYPE) or\n (COLLAPSE_DNA_STALLS and seq_samp_type.name == DNA_SAMP_TYPE)):\n map_res = map_res._replace(stall_ints=tombo_stats.identify_stalls(map_res.raw_signal, DEFAULT_STALL_PARAMS))\n\n return map_res\n\ndef adjust_rsqgl_res(rsqgl_res, all_raw_signal, seq_samp_type, USE_START_CLIP_BASES=False):\n if seq_samp_type.name == DNA_SAMP_TYPE and USE_START_CLIP_BASES:\n # flip raw signal and events back for storage in genome direction\n rev_rsrtr = (all_raw_signal.shape[0] -\n rsqgl_res.read_start_rel_to_raw -\n rsqgl_res.segs[-1])\n rev_segs = -1 * (rsqgl_res.segs[::-1] - rsqgl_res.segs[-1])\n rsqgl_res = rsqgl_res._replace(\n read_start_rel_to_raw=rev_rsrtr, segs=rev_segs,\n genome_seq=rsqgl_res.genome_seq[::-1],\n raw_signal=rsqgl_res.raw_signal[::-1])\n\n return rsqgl_res\n\ndef map_read(a, faidx, seq_samp_type, std_ref, ref2len):\n \"\"\"Get resquiggle result with read alignement info\"\"\"\n seq_data = tombo_helper.sequenceData(seq=a.seq, id=a.qname, mean_q_score=np.mean(a.query_qualities))\n # get chrom, start and end\n chrm, ref_start, ref_end = a.reference_name, a.reference_start, a.reference_end\n # store strand & number of clipped bases relative to read sequence\n if a.is_reverse:\n strand = \"-\"\n num_start_clipped_bases = len(seq_data.seq) - a.qend\n num_end_clipped_bases = a.qstart\n else:\n strand = \"+\"\n num_start_clipped_bases = a.qstart\n num_end_clipped_bases = len(seq_data.seq) - a.qend\n \n # 'ID', 'Subgroup', 'ClipStart', 'ClipEnd', 'Insertions', 'Deletions', 'Matches', 'Mismatches'\n align_info = tombo_helper.alignInfo(seq_data.id, \"\", num_start_clipped_bases, num_end_clipped_bases,\n 0, 0, a.alen, 0) # this isn't used anywhere, so just don't bother computing it!\n \n # extract genome sequence from mappy aligner\n # expand sequence to get model levels for all sites (need to handle new\n # sequence coordinates downstream)\n start_skip = 0\n # get exonic blocks\n blocks = get_exonic_blocks(a)\n align_info.blocks = deepcopy(blocks)\n dnstrm_bases = std_ref.kmer_width - std_ref.central_pos - 1 \n if ((seq_samp_type.name == RNA_SAMP_TYPE and strand == '+') or\n (seq_samp_type.name == DNA_SAMP_TYPE and strand == '-' and USE_START_CLIP_BASES) or\n (seq_samp_type.name == DNA_SAMP_TYPE and strand == '+' and not USE_START_CLIP_BASES)):\n if ref_start < std_ref.central_pos: \n start_skip = std_ref.central_pos-ref_start\n ref_start = std_ref.central_pos\n ref_seq_start = ref_start - std_ref.central_pos\n ref_seq_end = ref_end + dnstrm_bases\n else:\n if ref_start < dnstrm_bases: \n start_skip = dnstrm_bases-ref_start\n ref_start = dnstrm_bases\n ref_seq_start = ref_start - dnstrm_bases\n ref_seq_end = ref_end + std_ref.central_pos\n # update blocks start & end with kmer specific shifts - this sequence won't be saved! \n blocks[0][0] = ref_seq_start\n blocks[-1][1] = ref_seq_end\n # get exonic sequence\n genome_seq = \"\".join([faidx.fetch(chrm, s, e) for s, e in blocks])\n # get missing bases in the end\n end_skip = 0 if blocks[-1][1]<=ref2len[chrm] else blocks[-1][1]-ref2len[chrm]\n # enlarge genome seq by missing bits from ends with (random!) bases - As for now\n if start_skip or end_skip:\n genome_seq = \"A\"*start_skip + genome_seq + \"A\"*end_skip\n if strand == '-':\n genome_seq = tombo_helper.rev_comp(genome_seq)\n # store enlarged genome for P-value calculation, so no trimming needed later :)\n genome_seq = genome_seq.upper() #.upper() is important to correctly process soft-masked sequences\n align_info.refseq = genome_seq.upper() # res.genome_seq is altered during find_adaptive_assignment\n genome_loc = tombo_helper.genomeLocation(ref_start, strand, chrm)\n return tombo_helper.resquiggleResults(align_info, genome_loc, genome_seq, seq_data.mean_q_score)\n \ndef get_exonic_blocks(a):\n \"\"\"Return exonic blocks this is start-end reference-based \n for consecutive exons covered by given read.\n \n Note, those are not necesarily exact exons, just exons infered from read alignment. \n \"\"\"\n blocks = []\n s = e = a.pos\n # iter read blocks\n for code, bases in a.cigar:\n # count blocks that alter reference positions (ignore ie insertions [1])\n if code in (0, 2, 7, 8): e += bases\n # exclude introns - those are reported as reference-padded alignment part\n elif code == 3:\n blocks.append([s, e])\n s = e + bases\n e = s\n # store exon after last intron (or entire transcript if no introns)\n blocks.append([s, e])\n return blocks\n\ndef resquiggle_reads(multifast5_fn, aligner, ref, seq_samp_type, std_ref, rsqgl_params, \n outlier_thresh=OUTLIER_THRESH, max_scaling_iters=3, max_per_ref=0, \n valid_bases=set(list('ACGT'))):\n ref2c = {}\n # process reads from multi fast5\n faidx = pysam.FastaFile(ref)\n ref2len = {r: l for r, l in zip(faidx.references, faidx.lengths)}#; ref2len\n f5file = get_fast5_file(multifast5_fn, mode=\"r\")\n for a in aligner:\n # process only given number of reads per reference\n if max_per_ref:\n contig = a.reference_name #map_results.genome_loc.Chrom\n if contig in ref2c:\n if ref2c[contig]>=max_per_ref: continue\n else: ref2c[contig] = 0\n # skip reads without alignment or secondary/qcfails\n if a.is_unmapped or a.is_secondary or a.is_qcfail:\n yield None, \"No alignment\" if a.is_unmapped else \"Secondary alignment\"\n continue\n # get alignment data\n map_results = map_read(a, faidx, seq_samp_type, std_ref, ref2len)\n # make sure only ACGT chars in reference!\n if set(map_results.genome_seq).difference(valid_bases):\n yield None, \"Non-ACGT sequence\" # instead maybe just replace by random char?\n continue\n # extract data from FAST5\n read = f5file.get_read(a.qname) #read_id)\n all_raw_signal = read.get_raw_data(scale=False)\n map_results = map_results._replace(raw_signal=all_raw_signal)\n try:\n # this causes sometimes TomboError: Read event to sequence alignment extends beyond bandwidth\n map_results = adjust_map_res(map_results, seq_samp_type, rsqgl_params)\n rsqgl_res = resquiggle.resquiggle_read(map_results, std_ref, rsqgl_params, outlier_thresh)\n n_iters = 1\n while n_iters < max_scaling_iters and rsqgl_res.norm_params_changed:\n rsqgl_res = resquiggle.resquiggle_read(map_results._replace(scale_values=rsqgl_res.scale_values),\n std_ref, rsqgl_params, outlier_thresh)\n n_iters += 1\n except Exception as inst:\n yield None, str(inst)\n continue\n rsqgl_res = adjust_rsqgl_res(rsqgl_res, all_raw_signal, seq_samp_type)\n # add alignment and read as those are needed later\n rsqgl_res.a, rsqgl_res.read = a, read\n # update ref counter \n if ref2c: ref2c[contig] += 1\n yield rsqgl_res, \"\"\n\ndef get_norm_mean(raw, segs): \n \"\"\"Return raw signal means for given segments.\"\"\"\n return np.array([raw[segs[i]:segs[i+1]].mean() for i in range(len(segs)-1)])\n\ndef get_trace_for_reference_bases(a, read, rna, func=np.mean):\n \"\"\"Return reference-aligned trace for tr (ref base), tA, tC, tG, tT\"\"\"\n def get_bidx_fwd(b): return base2idx[b] \n def get_bidx_rev(b): return base2idx[base2complement[b]] \n # trace for reference bases\n tr = np.zeros(a.reference_length, dtype=\"uint8\")\n # trace and move data from read\n bcgrp = read.get_latest_analysis(\"Basecall_1D\")\n trace = read.get_analysis_dataset(bcgrp, \"BaseCalled_template/Trace\")\n if trace is None:\n logger(\"[ERROR] Trace table is missing in Fast5 file! Basecall Fast5 files again using --fast5_out option. \")\n return tr\n move = read.get_analysis_dataset(bcgrp, \"BaseCalled_template/Move\")\n move_pos = np.append(np.argwhere(move==1).flatten(), len(trace)) # add end of trace\n # combine flip & flop probabilities\n ## here we get sum of flip & flop. maybe get just one? but flop is usually lower...\n trace[:, :len(bases)] += trace[:, len(bases):]\n trace = trace[:, :len(bases)]\n # here we need to remember that DNA 5'>3', but RNA 3'>5'\n # plus the strand matters\n if a.is_reverse: # for REV alg\n get_bidx = get_bidx_rev # take complement base\n if not rna: move_pos = move_pos[::-1] # reverse move_pos for DNA\n else: # for FWD alg\n get_bidx = get_bidx_fwd # take base\n if rna: move_pos = move_pos[::-1] # reverse move_pos for RNA\n # process aligned bases - that's quite elegant, right? :P\n ## with_seq require MD tags: in minimap2 use --MD and -Y (soft-clip supplementary)\n for qi, ri, b in a.get_aligned_pairs(with_seq=True, matches_only=True): \n # get start & end in trace-space\n s, e = move_pos[qi:qi+2]\n if s>e: s, e = e, s # fix s, e for reversed move_pos\n tr[ri-a.reference_start] = func(trace[s:e, get_bidx(b)], axis=0)\n return tr\n\ndef get_trace_for_all_bases(a, read, rna, func=np.mean):\n \"\"\"Return reference-aligned trace for tr (ref base), tA, tC, tG, tT\"\"\"\n def get_bidx_fwd(b): return base2idx[b] \n def get_bidx_rev(b): return base2idx[base2complement[b]] \n # trace for reference bases\n tr = np.zeros((a.reference_length,5), dtype=\"uint8\") # one column per base + canonical col\n # trace and move data from read\n bcgrp = read.get_latest_analysis(\"Basecall_1D\")\n trace = read.get_analysis_dataset(bcgrp, \"BaseCalled_template/Trace\")\n if trace is None:\n logger(\"[ERROR] Trace table is missing in Fast5 file! Basecall Fast5 files again using --fast5_out option. \")\n return tr\n move = read.get_analysis_dataset(bcgrp, \"BaseCalled_template/Move\")\n move_pos = np.append(np.argwhere(move==1).flatten(), len(trace)) # add end of trace\n # combine flip & flop probabilities\n ## here we get sum of flip & flop. maybe get just one? but flop is usually lower...\n trace[:, :len(bases)] += trace[:, len(bases):]\n trace = trace[:, :len(bases)]\n # here we need to remember that DNA 5'>3', but RNA 3'>5'\n # plus the strand matters\n if a.is_reverse: # for REV alg\n get_bidx = get_bidx_rev # take complement base\n if not rna: move_pos = move_pos[::-1] # reverse move_pos for DNA\n else: # for FWD alg\n get_bidx = get_bidx_fwd # take base\n if rna: move_pos = move_pos[::-1] # reverse move_pos for RNA\n # process aligned bases - that's quite elegant, right? :P\n ## with_seq require MD tags: in minimap2 use --MD and -Y (soft-clip supplementary)\n for qi, ri, b in a.get_aligned_pairs(with_seq=True, matches_only=True): \n # get start & end in trace-space\n s, e = move_pos[qi:qi+2]\n if s>e: s, e = e, s # fix s, e for reversed move_pos\n tr[ri-a.reference_start,0] = func(trace[s:e, 0], axis=0)\n tr[ri-a.reference_start,1] = func(trace[s:e, 1], axis=0)\n tr[ri-a.reference_start,2] = func(trace[s:e, 2], axis=0)\n tr[ri-a.reference_start,3] = func(trace[s:e, 3], axis=0)\n tr[ri-a.reference_start,4] = func(trace[s:e, get_bidx(b)], axis=0)\n return tr\n\ndef process_fast5(fast5, ref, rna=True, sensitive=False):\n \"\"\"Process individual Fast5 files\"\"\"\n outfn = \"%s.bam\"%fast5 #.d2r\n\n # uncomment if you don't wish to recompute previously computed bam files\n # if os.path.isfile(outfn): return outfn\n faidx = pysam.FastaFile(ref)\n ref2len = {r: l for r, l in zip(faidx.references, faidx.lengths)}\n # load model & its parameters\n if rna:\n seq_samp_type = tombo_helper.seqSampleType('RNA', True)\n rsqgl_params = tombo_stats.load_resquiggle_parameters(seq_samp_type)\n std_ref = tombo_stats.TomboModel(seq_samp_type=seq_samp_type)\n spliced = True\n else:\n seq_samp_type = tombo_helper.seqSampleType('DNA', False)\n rsqgl_params = tombo_stats.load_resquiggle_parameters(seq_samp_type)\n spliced = False\n std_ref = tombo_stats.TomboModel(seq_samp_type=seq_samp_type)\n # get resquiggle parameters\n i, errors = 0, {} \n # prep aligner, signal model and parameters\n aligner = minimap2_proc(ref, fast5, sensitive=sensitive, spliced=spliced)\n sam = pysam.AlignmentFile(aligner.stdout)\n # open unsorted bam for saving alignements with features\n tmp = tempfile.NamedTemporaryFile(delete=False); tmp.close()\n bam_unsorted = pysam.AlignmentFile(tmp.name, \"wb\", header=sam.header)\n\n for i, (res, err) in enumerate(resquiggle_reads(fast5, sam, ref, seq_samp_type, std_ref, rsqgl_params), 1):\n #if i>200: break\n if not i%100: sys.stderr.write(\" %s - %s reads skipped: %s \\r\"%(i, sum(errors.values()), str(errors)))\n if not res:\n if err not in errors: errors[err] = 1\n else: errors[err] += 1\n continue\n # get pysam alignment object & exonic blocks\n a, blocks = res.a, res.align_info.blocks\n\n # get signal intensity means\n si = get_norm_mean(res.raw_signal, res.segs)\n # catch problems - here exonic seq will have different length\n if len(si)!=sum([e-s for s, e in blocks]): #a.reference_length:\n region = \"%s:%s-%s\"%(a.reference_name, a.reference_start, a.reference_end)\n print(a.qname, region, sam.lengths[a.reference_id], a.reference_length, len(si), blocks)\n # get dwell times capped at 255 to fit uint8 (1 byte per base)\n dt = res.segs[1:]-res.segs[:-1]\n dt[dt>255] = 255\n # get reference-aligned base probabilities: tr (ref base)\n tr = get_trace_for_all_bases(a, res.read, rna) # trA, trC, trG, trT, (canonical) tr\n if a.is_reverse: si, dt = si[::-1], dt[::-1]\n # and finally set tags matching refseq\n ## but if alignment reaches seq end the end signal/probs will be wrong!\n ## same at exon-intron boundaries\n a.set_tag(\"bs\", array(\"i\", np.array(blocks).flatten()))\n a.set_tag(\"si\", array(\"f\", si))\n a.set_tag(\"dt\", array(\"B\", dt))\n # tr correspond to reference base\n # get exonic tr\n exonic_pos = np.concatenate([np.arange(s, e) for s, e in blocks])\n tr = tr[exonic_pos-a.pos]\n\n a.set_tag(\"tA\", array(\"B\", tr[:,0]))\n a.set_tag(\"tC\", array(\"B\", tr[:,1]))\n a.set_tag(\"tG\", array(\"B\", tr[:,2]))\n a.set_tag(\"tT\", array(\"B\", tr[:,3]))\n a.set_tag(\"tr\", array(\"B\", tr[:,4]))\n\n # add quality scores\n a.set_tag(\"QQ\", array(\"B\", a.query_qualities))\n\n # read id\n a.set_tag('ID', a.qname)\n\n # store read alignment with additional info\n bam_unsorted.write(a)\n\n # close tmp, sort, index & clean-up\n bam_unsorted.close()\n pysam.sort(\"-o\", outfn, tmp.name)\n pysam.index(outfn)\n os.unlink(tmp.name)\n # write error report\n with open('%s.json'%outfn, 'w') as f:\n errors[\"Alignements\"] = i # store number of alignements\n f.write(json.dumps(errors)) #\n return outfn\n\ndef mod_encode(fnames, fasta, threads=1, rna=True, sensitive=False, mem=1):\n \"\"\"Process multiple directories from Fast5 files\"\"\"\n # no need to have more threads than input directories ;) \n if threads > len(fnames):\n threads = len(fnames)\n # use pool if more than 1 thread, otherwise just itertools\n if threads>1: p = Pool(threads, maxtasksperchild=1)\n else: p = itertools\n # get arguments for func\n args = [(fn, fasta, rna, sensitive) for fn in fnames]# if not os.path.isfile(\"%s.bam\"%fn)]\n # return list of outputs\n return list(p.starmap(process_fast5, args)) \n\ndef memory_usage(childrenmem=True, div=1024.):\n \"\"\"Return memory usage in MB including children processes\"\"\"\n mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / div\n if childrenmem:\n mem += resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss / div\n return mem\n \ndef logger(info, add_timestamp=1, add_memory=1, out=sys.stderr):\n \"\"\"Report nicely formatted stream to stderr\"\"\"\n info = info.rstrip('\\n')\n memory = timestamp = \"\"\n if add_timestamp:\n timestamp = \"[%s]\"%str(datetime.now()).split(\".\")[0] \n if add_memory:\n memory = \" [mem: %5.0f MB]\"%memory_usage()\n out.write(\"%s %s%s\\n\"%(timestamp, info, memory))\n\ndef main():\n import argparse\n usage = \"%(prog)s -v\" #usage=usage, \n parser = argparse.ArgumentParser(description=desc, epilog=epilog, \\\n formatter_class=argparse.RawTextHelpFormatter)\n \n parser.add_argument('--version', action='version', version=VERSION) \n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"verbose\") \n parser.add_argument(\"-i\", \"--input\", nargs=\"+\", help=\"input Fast5 file(s)\")\n parser.add_argument(\"--rna\", action='store_true', help=\"project is RNA sequencing [DNA]\")\n parser.add_argument(\"-f\", \"--fasta\", required=1, help=\"reference FASTA file\")\n parser.add_argument(\"-t\", \"--threads\", default=1, type=int, help=\"number of cores to use [%(default)s]\")\n parser.add_argument(\"-s\", \"--sensitive\", action='store_true', help=\"use sensitive alignment\")\n\n o = parser.parse_args()\n if o.verbose: \n sys.stderr.write(\"Options: %s\\n\"%str(o))\n\n # encode tombo output into BAM files\n logger(\"Processing %s file(s)...\"%len(o.input))\n bamfiles = mod_encode(o.input, o.fasta, o.threads, o.rna, o.sensitive)\n \nif __name__=='__main__': \n t0 = datetime.now()\n try:\n main()\n except KeyboardInterrupt:\n sys.stderr.write(\"\\nCtrl-C pressed! \\n\")\n #except IOError as e:\n # sys.stderr.write(\"I/O error({0}): {1}\\n\".format(e.errno, e.strerror))\n dt = datetime.now()-t0\n sys.stderr.write(\"#Time elapsed: %s \\n\"%dt)\n\n" ]
[ [ "numpy.arange", "numpy.argwhere", "numpy.mean", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mikailweston/phy
[ "d774cb989152a4b7344ac9b70c79c204a5036763" ]
[ "phy/cluster/tests/test_supervisor.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"Test GUI component.\"\"\"\n\n#------------------------------------------------------------------------------\n# Imports\n#------------------------------------------------------------------------------\n\n#from contextlib import contextmanager\n\nfrom pytest import yield_fixture, fixture, raises\nimport numpy as np\nfrom numpy.testing import assert_array_equal as ae\n\nfrom .. import supervisor as _supervisor\nfrom ..supervisor import (Supervisor,\n TaskLogger,\n ClusterView,\n SimilarityView,\n ActionCreator,\n )\nfrom phy.gui import GUI\nfrom phy.gui.widgets import Barrier\nfrom phy.gui.qt import qInstallMessageHandler\nfrom phy.gui.tests.test_widgets import _assert, _wait_until_table_ready\nfrom phy.utils.context import Context\nfrom phylib.utils import connect, Bunch, emit\n\n\ndef handler(msg_type, msg_log_context, msg_string):\n pass\n\n\nqInstallMessageHandler(handler)\n\n\n#------------------------------------------------------------------------------\n# Fixtures\n#------------------------------------------------------------------------------\n\n@yield_fixture\ndef gui(tempdir, qtbot):\n # NOTE: mock patch show box exec_\n _supervisor._show_box = lambda _: _\n\n gui = GUI(position=(200, 100), size=(500, 500), config_dir=tempdir)\n gui.set_default_actions()\n gui.show()\n qtbot.waitForWindowShown(gui)\n yield gui\n qtbot.wait(5)\n gui.close()\n del gui\n qtbot.wait(5)\n\n\n@fixture\ndef supervisor(qtbot, gui, cluster_ids, cluster_groups, cluster_labels,\n similarity, tempdir):\n spike_clusters = np.repeat(cluster_ids, 2)\n\n s = Supervisor(\n spike_clusters,\n cluster_groups=cluster_groups,\n cluster_labels=cluster_labels,\n similarity=similarity,\n context=Context(tempdir),\n sort=('id', 'desc'),\n )\n s.attach(gui)\n b = Barrier()\n connect(b('cluster_view'), event='ready', sender=s.cluster_view)\n connect(b('similarity_view'), event='ready', sender=s.similarity_view)\n b.wait()\n return s\n\n\n#------------------------------------------------------------------------------\n# Test tasks\n#------------------------------------------------------------------------------\n\n@fixture\ndef tl():\n class MockClusterView(object):\n _selected = [0]\n\n def select(self, cl, callback=None, **kwargs):\n self._selected = cl\n callback({'selected': cl, 'next': cl[-1] + 1})\n\n def next(self, callback=None):\n callback({'selected': [self._selected[-1] + 1], 'next': self._selected[-1] + 2})\n\n def previous(self, callback=None): # pragma: no cover\n callback({'selected': [self._selected[-1] - 1], 'next': self._selected[-1]})\n\n class MockSimilarityView(MockClusterView):\n pass\n\n class MockSupervisor(object):\n def merge(self, cluster_ids, to, callback=None):\n callback(Bunch(deleted=cluster_ids, added=[to]))\n\n def split(self, old_cluster_ids, new_cluster_ids, callback=None):\n callback(Bunch(deleted=old_cluster_ids, added=new_cluster_ids))\n\n def move(self, which, group, callback=None):\n callback(Bunch(metadata_changed=which, metadata_value=group))\n\n def undo(self, callback=None):\n callback(Bunch())\n\n def redo(self, callback=None):\n callback(Bunch())\n\n out = TaskLogger(MockClusterView(), MockSimilarityView(), MockSupervisor())\n\n return out\n\n\ndef test_task_1(tl):\n assert tl.last_state(None) is None\n\n\ndef test_task_2(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.process()\n assert tl.last_state() == ([0], 1, None, None)\n\n\ndef test_task_3(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.process()\n assert tl.last_state() == ([0], 1, [100], 101)\n\n\ndef test_task_merge(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.enqueue(tl.supervisor, 'merge', [0, 100], 1000)\n tl.process()\n\n assert tl.last_state() == ([1000], 1001, None, None)\n\n tl.enqueue(tl.supervisor, 'undo')\n tl.process()\n assert tl.last_state() == ([0], 1, [100], 101)\n\n tl.enqueue(tl.supervisor, 'redo')\n tl.process()\n assert tl.last_state() == ([1000], 1001, None, None)\n\n\ndef test_task_split(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.enqueue(tl.supervisor, 'split', [0, 100], [1000, 1001])\n tl.process()\n\n assert tl.last_state() == ([1000, 1001], 1002, None, None)\n\n\ndef test_task_move_1(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.supervisor, 'move', [0], 'good')\n tl.process()\n\n assert tl.last_state() == ([1], 2, None, None)\n\n\ndef test_task_move_best(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.enqueue(tl.supervisor, 'move', 'best', 'good')\n tl.process()\n\n assert tl.last_state() == ([1], 2, None, None)\n\n\ndef test_task_move_similar(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.enqueue(tl.supervisor, 'move', 'similar', 'good')\n tl.process()\n\n assert tl.last_state() == ([0], 1, [101], 102)\n\n\ndef test_task_move_all(tl):\n tl.enqueue(tl.cluster_view, 'select', [0])\n tl.enqueue(tl.similarity_view, 'select', [100])\n tl.enqueue(tl.supervisor, 'move', 'all', 'good')\n tl.process()\n\n assert tl.last_state() == ([1], 2, [101], 102)\n\n\n#------------------------------------------------------------------------------\n# Test cluster and similarity views\n#------------------------------------------------------------------------------\n\n@fixture\ndef data():\n _data = [{\"id\": i,\n \"n_spikes\": 100 - 10 * i,\n \"group\": {2: 'noise', 3: 'noise', 5: 'mua', 8: 'good'}.get(i, None),\n \"is_masked\": i in (2, 3, 5),\n } for i in range(10)]\n return _data\n\n\ndef test_cluster_view_1(qtbot, gui, data):\n cv = ClusterView(gui, data=data)\n _wait_until_table_ready(qtbot, cv)\n\n cv.sort_by('n_spikes', 'asc')\n cv.select([1])\n qtbot.wait(10)\n assert cv.state == {'current_sort': ('n_spikes', 'asc'), 'selected': [1]}\n\n cv.set_state({'current_sort': ('id', 'desc'), 'selected': [2]})\n assert cv.state == {'current_sort': ('id', 'desc'), 'selected': [2]}\n\n\ndef test_similarity_view_1(qtbot, gui, data):\n sv = SimilarityView(gui, data=data)\n _wait_until_table_ready(qtbot, sv)\n\n @connect(sender=sv)\n def on_request_similar_clusters(sender, cluster_id):\n return [{'id': id} for id in (100 + cluster_id, 110 + cluster_id, 102 + cluster_id)]\n\n sv.reset([5])\n _assert(sv.get_ids, [105, 115, 107])\n\n\ndef test_cluster_view_extra_columns(qtbot, gui, data):\n\n for cl in data:\n cl['my_metrics'] = cl['id'] * 1000\n\n cv = ClusterView(gui, data=data, columns=['id', 'n_spikes', 'my_metrics'])\n _wait_until_table_ready(qtbot, cv)\n\n\n#------------------------------------------------------------------------------\n# Test ActionCreator\n#------------------------------------------------------------------------------\n\ndef test_action_creator_1(qtbot, gui):\n ac = ActionCreator()\n ac.attach(gui)\n gui.show()\n\n\n#------------------------------------------------------------------------------\n# Test GUI component\n#------------------------------------------------------------------------------\n\ndef _select(supervisor, cluster_ids, similar=None):\n supervisor.task_logger.enqueue(supervisor.cluster_view, 'select', cluster_ids)\n if similar is not None:\n supervisor.task_logger.enqueue(supervisor.similarity_view, 'select', similar)\n supervisor.task_logger.process()\n supervisor.block()\n supervisor.task_logger.show_history()\n\n assert supervisor.task_logger.last_state()[0] == cluster_ids\n assert supervisor.task_logger.last_state()[2] == similar\n\n\ndef _assert_selected(supervisor, sel):\n assert supervisor.selected == sel\n\n\ndef test_select(qtbot, supervisor):\n _select(supervisor, [30], [20])\n _assert_selected(supervisor, [30, 20])\n\n\ndef test_supervisor_busy(qtbot, supervisor):\n _select(supervisor, [30], [20])\n\n o = object()\n\n emit('is_busy', o, True)\n assert supervisor._is_busy\n\n # The action fails while the supervisor is busy.\n with raises(RuntimeError):\n emit('action', supervisor.action_creator, 'merge')\n\n emit('is_busy', o, False)\n assert not supervisor._is_busy\n\n # The action succeeds because the supervisor is no longer busy.\n emit('action', supervisor.action_creator, 'merge')\n supervisor.block()\n assert not supervisor._is_busy\n\n\ndef test_supervisor_cluster_metrics(\n qtbot, gui, cluster_ids, cluster_groups, similarity, tempdir):\n spike_clusters = np.repeat(cluster_ids, 2)\n\n def my_metrics(cluster_id):\n return cluster_id ** 2\n\n cluster_metrics = {'my_metrics': my_metrics}\n\n mc = Supervisor(spike_clusters,\n cluster_groups=cluster_groups,\n cluster_metrics=cluster_metrics,\n similarity=similarity,\n context=Context(tempdir),\n )\n mc.attach(gui)\n b = Barrier()\n connect(b('cluster_view'), event='ready', sender=mc.cluster_view)\n connect(b('similarity_view'), event='ready', sender=mc.similarity_view)\n b.wait()\n\n assert 'my_metrics' in mc.columns\n\n\ndef test_supervisor_select_1(qtbot, supervisor):\n # WARNING: always use actions in tests, because this doesn't call\n # the supervisor method directly, but raises an event, enqueue the task,\n # and call TaskLogger.process() which handles the cascade of callbacks.\n supervisor.select_actions.select([0])\n supervisor.block()\n _assert_selected(supervisor, [0])\n supervisor.task_logger.show_history()\n\n\ndef test_supervisor_color(qtbot, supervisor):\n supervisor.view_actions.colormap_linear()\n supervisor.view_actions.color_field_n_spikes()\n supervisor.view_actions.toggle_categorical_colormap(False)\n supervisor.view_actions.toggle_logarithmic_colormap(True)\n\n\ndef test_supervisor_select_2(qtbot, supervisor):\n supervisor.select_actions.next_best()\n supervisor.block()\n _assert_selected(supervisor, [30])\n\n\ndef test_supervisor_select_order(qtbot, supervisor):\n _select(supervisor, [1, 0])\n _assert_selected(supervisor, [1, 0])\n _select(supervisor, [0, 1])\n _assert_selected(supervisor, [0, 1])\n\n\ndef test_supervisor_edge_cases(supervisor):\n\n # Empty selection at first.\n ae(supervisor.clustering.cluster_ids, [0, 1, 2, 10, 11, 20, 30])\n\n _select(supervisor, [0])\n\n supervisor.undo()\n supervisor.block()\n\n supervisor.redo()\n supervisor.block()\n\n # Merge.\n supervisor.merge()\n supervisor.block()\n _assert_selected(supervisor, [0])\n\n supervisor.merge([])\n supervisor.block()\n _assert_selected(supervisor, [0])\n\n supervisor.merge([10])\n supervisor.block()\n _assert_selected(supervisor, [0])\n\n # Split.\n supervisor.split([])\n supervisor.block()\n _assert_selected(supervisor, [0])\n\n # Move.\n supervisor.move('ignored', [])\n supervisor.block()\n\n supervisor.save()\n\n\ndef test_supervisor_save(qtbot, gui, supervisor):\n emit('request_save', gui)\n\n\ndef test_supervisor_skip(qtbot, gui, supervisor):\n\n # yield [0, 1, 2, 10, 11, 20, 30]\n # # i, g, N, i, g, N, N\n expected = [30, 20, 11, 2, 1]\n\n for clu in expected:\n supervisor.select_actions.next_best()\n supervisor.block()\n _assert_selected(supervisor, [clu])\n\n\ndef test_supervisor_sort(qtbot, supervisor):\n supervisor.sort('id', 'desc')\n qtbot.wait(50)\n assert supervisor.state.cluster_view.current_sort == ('id', 'desc')\n\n supervisor.select_actions.sort_by_n_spikes()\n qtbot.wait(50)\n assert supervisor.state.cluster_view.current_sort == ('n_spikes', 'desc')\n\n\ndef test_supervisor_filter(qtbot, supervisor):\n supervisor.filter('5 <= id && id <= 20')\n qtbot.wait(50)\n _cl = []\n supervisor.cluster_view.get_ids(lambda cluster_ids: _cl.extend(cluster_ids))\n qtbot.wait(50)\n assert _cl == [20, 11, 10]\n\n\ndef test_supervisor_merge_1(qtbot, supervisor):\n\n _select(supervisor, [30], [20])\n _assert_selected(supervisor, [30, 20])\n\n supervisor.actions.merge()\n supervisor.block()\n\n _assert_selected(supervisor, [31])\n\n supervisor.actions.undo()\n supervisor.block()\n _assert_selected(supervisor, [30, 20])\n\n supervisor.actions.redo()\n supervisor.block()\n supervisor.task_logger.show_history()\n _assert_selected(supervisor, [31])\n\n assert supervisor.is_dirty()\n\n\ndef test_supervisor_merge_event(qtbot, supervisor):\n _select(supervisor, [30], [20])\n\n _l = []\n\n @connect(sender=supervisor)\n def on_select(sender, cluster_ids):\n _l.append(cluster_ids)\n\n supervisor.actions.merge()\n supervisor.block()\n\n # After a merge, there should be only one select event.\n assert len(_l) == 1\n\n\ndef test_supervisor_merge_move(qtbot, supervisor):\n \"\"\"Check that merge then move selects the next cluster in the original\n cluster view, not the updated cluster view.\"\"\"\n\n _select(supervisor, [20, 11], [])\n _assert_selected(supervisor, [20, 11])\n\n supervisor.actions.merge()\n supervisor.block()\n _assert_selected(supervisor, [31])\n\n supervisor.actions.move('good', 'all')\n supervisor.block()\n _assert_selected(supervisor, [30])\n\n supervisor.actions.move('good', 'all')\n supervisor.block()\n _assert_selected(supervisor, [2])\n\n\ndef test_supervisor_split_0(qtbot, supervisor):\n\n _select(supervisor, [1, 2])\n _assert_selected(supervisor, [1, 2])\n\n supervisor.actions.split([1, 2])\n supervisor.block()\n\n _assert_selected(supervisor, [31, 32, 33])\n\n supervisor.actions.undo()\n supervisor.block()\n _assert_selected(supervisor, [1, 2])\n\n supervisor.actions.redo()\n supervisor.block()\n _assert_selected(supervisor, [31, 32, 33])\n\n\ndef test_supervisor_split_1(supervisor):\n\n supervisor.select_actions.select([1, 2])\n supervisor.block()\n\n @connect(sender=supervisor)\n def on_request_split(sender):\n return [1, 2]\n\n supervisor.actions.split()\n supervisor.block()\n _assert_selected(supervisor, [31, 32, 33])\n\n\ndef test_supervisor_split_2(gui, similarity):\n spike_clusters = np.array([0, 0, 1])\n\n supervisor = Supervisor(spike_clusters,\n similarity=similarity,\n )\n supervisor.attach(gui)\n\n b = Barrier()\n connect(b('cluster_view'), event='ready', sender=supervisor.cluster_view)\n connect(b('similarity_view'), event='ready', sender=supervisor.similarity_view)\n b.wait()\n\n supervisor.actions.split([0])\n supervisor.block()\n _assert_selected(supervisor, [2, 3])\n\n\ndef test_supervisor_state(tempdir, qtbot, gui, supervisor):\n\n supervisor.select(1)\n\n cv = supervisor.cluster_view\n assert supervisor.state.cluster_view.current_sort == ('id', 'desc')\n assert supervisor.state.cluster_view.selected == [1]\n\n cv.sort_by('id')\n assert supervisor.state.cluster_view.current_sort == ('id', 'asc')\n\n cv.set_state({'current_sort': ('n_spikes', 'desc')})\n assert supervisor.state.cluster_view.current_sort == ('n_spikes', 'desc')\n\n cv.sort_by('id', 'desc')\n assert supervisor.all_cluster_ids == [30, 20, 11, 10, 2, 1, 0]\n\n\ndef test_supervisor_label(supervisor):\n\n _select(supervisor, [20])\n supervisor.label(\"my_field\", 3.14)\n supervisor.block()\n\n supervisor.label(\"my_field\", 1.23, cluster_ids=30)\n supervisor.block()\n\n assert 'my_field' in supervisor.fields\n assert supervisor.get_labels('my_field')[20] == 3.14\n assert supervisor.get_labels('my_field')[30] == 1.23\n\n\ndef test_supervisor_label_cluster_1(supervisor):\n\n _select(supervisor, [20, 30])\n supervisor.label(\"my_field\", 3.14)\n supervisor.block()\n\n # Same value for the old clusters.\n l = supervisor.get_labels('my_field')\n assert l[20] == l[30] == 3.14\n\n up = supervisor.merge()\n supervisor.block()\n\n assert supervisor.get_labels('my_field')[up.added[0]] == 3.14\n\n\ndef test_supervisor_label_cluster_2(supervisor):\n\n _select(supervisor, [20])\n\n supervisor.label(\"my_field\", 3.14)\n supervisor.block()\n\n # One of the parents.\n l = supervisor.get_labels('my_field')\n assert l[20] == 3.14\n assert l[30] is None\n\n up = supervisor.merge([20, 30])\n supervisor.block()\n\n assert supervisor.get_labels('my_field')[up.added[0]] == 3.14\n\n\ndef test_supervisor_label_cluster_3(supervisor):\n\n # Conflict: largest cluster wins.\n _select(supervisor, [20, 30])\n supervisor.label(\"my_field\", 3.14)\n supervisor.block()\n\n # Create merged cluster from 20 and 30.\n up = supervisor.merge()\n new = up.added[0]\n supervisor.block()\n\n # It fot the label of its parents.\n assert supervisor.get_labels('my_field')[new] == 3.14\n\n # Now, we label a smaller cluster.\n supervisor.label(\"my_field\", 2.718, cluster_ids=[10])\n\n # We merge the large and small cluster together.\n up = supervisor.merge(up.added + [10])\n supervisor.block()\n\n # The new cluster should have the value of the first, merged big cluster, i.e. 3.14.\n assert supervisor.get_labels('my_field')[up.added[0]] == 3.14\n\n\ndef test_supervisor_move_1(supervisor):\n\n _select(supervisor, [20])\n _assert_selected(supervisor, [20])\n\n assert not supervisor.move('', '')\n\n supervisor.actions.move('noise', 'all')\n supervisor.block()\n _assert_selected(supervisor, [11])\n\n supervisor.actions.undo()\n supervisor.block()\n _assert_selected(supervisor, [20])\n\n supervisor.actions.redo()\n supervisor.block()\n _assert_selected(supervisor, [11])\n\n\ndef test_supervisor_move_2(supervisor):\n\n _select(supervisor, [20], [10])\n _assert_selected(supervisor, [20, 10])\n\n supervisor.actions.move('noise', 10)\n supervisor.block()\n _assert_selected(supervisor, [20, 2])\n\n supervisor.actions.undo()\n supervisor.block()\n _assert_selected(supervisor, [20, 10])\n\n supervisor.actions.redo()\n supervisor.block()\n _assert_selected(supervisor, [20, 2])\n\n\ndef test_supervisor_move_3(qtbot, supervisor):\n\n supervisor.select_actions.next()\n supervisor.block()\n _assert_selected(supervisor, [30])\n\n supervisor.actions.move_best_to_noise()\n supervisor.block()\n _assert_selected(supervisor, [20])\n\n supervisor.actions.move_best_to_mua()\n supervisor.block()\n _assert_selected(supervisor, [11])\n\n supervisor.actions.move_best_to_good()\n supervisor.block()\n _assert_selected(supervisor, [2])\n\n supervisor.cluster_meta.get('group', 30) == 'noise'\n supervisor.cluster_meta.get('group', 20) == 'mua'\n supervisor.cluster_meta.get('group', 11) == 'good'\n\n\ndef test_supervisor_move_4(supervisor):\n\n _select(supervisor, [30], [20])\n _assert_selected(supervisor, [30, 20])\n\n supervisor.actions.move_similar_to_noise()\n supervisor.block()\n _assert_selected(supervisor, [30, 11])\n\n supervisor.actions.move_similar_to_mua()\n supervisor.block()\n _assert_selected(supervisor, [30, 2])\n\n supervisor.actions.move_similar_to_good()\n supervisor.block()\n _assert_selected(supervisor, [30, 1])\n\n supervisor.cluster_meta.get('group', 20) == 'noise'\n supervisor.cluster_meta.get('group', 11) == 'mua'\n supervisor.cluster_meta.get('group', 2) == 'good'\n\n\ndef test_supervisor_move_5(supervisor):\n _select(supervisor, [30], [20])\n _assert_selected(supervisor, [30, 20])\n\n supervisor.actions.move_all_to_noise()\n supervisor.block()\n _assert_selected(supervisor, [11, 2])\n\n supervisor.select_actions.next()\n supervisor.block()\n _assert_selected(supervisor, [11, 1])\n\n supervisor.actions.move_all_to_mua()\n supervisor.block()\n _assert_selected(supervisor, [2])\n\n supervisor.actions.move_all_to_good()\n supervisor.block()\n _assert_selected(supervisor, [])\n\n supervisor.cluster_meta.get('group', 30) == 'noise'\n supervisor.cluster_meta.get('group', 20) == 'noise'\n\n supervisor.cluster_meta.get('group', 11) == 'mua'\n supervisor.cluster_meta.get('group', 10) == 'mua'\n\n supervisor.cluster_meta.get('group', 2) == 'good'\n supervisor.cluster_meta.get('group', 1) == 'good'\n\n\ndef test_supervisor_reset(qtbot, supervisor):\n\n supervisor.select_actions.select([10, 11])\n\n supervisor.select_actions.reset_wizard()\n supervisor.block()\n _assert_selected(supervisor, [30])\n\n supervisor.select_actions.next()\n supervisor.block()\n _assert_selected(supervisor, [30, 20])\n\n supervisor.select_actions.next()\n supervisor.block()\n _assert_selected(supervisor, [30, 11])\n\n supervisor.select_actions.previous()\n supervisor.block()\n _assert_selected(supervisor, [30, 20])\n\n\ndef test_supervisor_nav(qtbot, supervisor):\n\n supervisor.select_actions.reset_wizard()\n supervisor.block()\n _assert_selected(supervisor, [30])\n\n supervisor.select_actions.next_best()\n supervisor.block()\n _assert_selected(supervisor, [20])\n\n supervisor.select_actions.previous_best()\n supervisor.block()\n _assert_selected(supervisor, [30])\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.repeat", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
OrcusCZ/pyreaper
[ "09a65e421edb355f3475a70427ae3796f4108690" ]
[ "docs/conf.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# pyreaper documentation build configuration file, created by\n# sphinx-quickstart on Fri Sep 4 18:38:55 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport pkg_resources\nimport sys\nimport os\nimport shlex\n\n__version__ = pkg_resources.get_distribution('pyreaper').version\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#sys.path.insert(0, os.path.abspath('.'))\n\nON_RTD = os.environ.get('READTHEDOCS', None) == 'True'\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.doctest',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.viewcode',\n 'numpydoc',\n 'matplotlib.sphinxext.plot_directive',\n]\n\nif ON_RTD:\n # Remove extensions not currently supported on RTD\n extensions.remove('matplotlib.sphinxext.plot_directive')\n\nautosummary_generate = True\nnumpydoc_show_class_members = False\n\n# Most of plotting settings are copy and pasted from librosa\n# https://github.com/bmcfee/librosa\n\nif not ON_RTD:\n # Determine if the matplotlib has a recent enough version of the\n # plot_directive.\n try:\n from matplotlib.sphinxext import plot_directive\n except ImportError:\n use_matplotlib_plot_directive = False\n else:\n try:\n print(\"plot_directive.__version__:\", plot_directive.__version__)\n use_matplotlib_plot_directive = (plot_directive.__version__ >= 2)\n except AttributeError:\n use_matplotlib_plot_directive = False\n\n if use_matplotlib_plot_directive:\n extensions.append('matplotlib.sphinxext.plot_directive')\n else:\n raise RuntimeError(\"You need a recent enough version of matplotlib\")\n\n#------------------------------------------------------------------------------\n# Plot\n#------------------------------------------------------------------------------\nplot_pre_code = \"\"\"\nimport seaborn\nseaborn.set(style='ticks')\nimport numpy as np\nimport pyreaper\nnp.random.seed(123)\nnp.set_printoptions(precision=3, linewidth=64, edgeitems=2, threshold=200)\n\"\"\"\nplot_include_source = True\nplot_formats = [('png', 96), 'pdf']\nplot_html_show_formats = False\n\nfont_size = 13 * 72 / 96.0 # 13 px\n\nplot_rcparams = {\n 'font.size': font_size,\n 'axes.titlesize': font_size,\n 'axes.labelsize': font_size,\n 'xtick.labelsize': font_size,\n 'ytick.labelsize': font_size,\n 'legend.fontsize': font_size,\n 'figure.subplot.bottom': 0.2,\n 'figure.subplot.left': 0.2,\n 'figure.subplot.right': 0.9,\n 'figure.subplot.top': 0.85,\n 'figure.subplot.wspace': 0.4,\n 'text.usetex': False,\n}\n\nif not ON_RTD:\n import matplotlib\n matplotlib.rcParams.update(plot_rcparams)\n\n\n# Generate plots for example sections\nnumpydoc_use_plots = True\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'pyreaper'\ncopyright = u'2015, Ryuichi YAMAMOTO'\nauthor = u'Ryuichi YAMAMOTO'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = __version__\n# The full version, including alpha/beta/rc tags.\nrelease = __version__\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build']\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n#keep_warnings = False\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = 'sphinx_rtd_theme'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n#html_theme_path = []\n\n# The name for this set of Sphinx documents. If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar. Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n#html_extra_path = []\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it. The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Language to be used for generating the HTML full-text search index.\n# Sphinx supports the following languages:\n# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'\n# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'\n#html_search_language = 'en'\n\n# A dictionary with options for the search language support, empty by default.\n# Now only 'ja' uses this config value\n#html_search_options = {'type': 'default'}\n\n# The name of a javascript file (relative to the configuration directory) that\n# implements a search results scorer. If empty, the default will be used.\n#html_search_scorer = 'scorer.js'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'pyreaperdoc'\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #'preamble': '',\n\n # Latex figure (float) alignment\n #'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'pyreaper.tex', u'pyreaper Documentation',\n u'Ryuichi YAMAMOTO', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'pyreaper', u'pyreaper Documentation',\n [author], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'pyreaper', u'pyreaper Documentation',\n author, 'pyreaper', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False\n" ]
[ [ "matplotlib.rcParams.update" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bladezzw/RL_project3
[ "b9947830c5731296b6e68de3fb90b88d2cce4e56" ]
[ "src/process.py" ]
[ "\nimport torch\nfrom src.env import create_train_env\nfrom src.model import ActorCritic\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\nfrom collections import deque\nfrom tensorboardX import SummaryWriter\nimport timeit\n\n\ndef local_train(index, opt, global_model, optimizer, save=False):\n torch.manual_seed(123 + index) #为CPU设置种子用于生成随机数,以使得结果是确定的\n if save:\n start_time = timeit.default_timer()\n writer = SummaryWriter(opt.log_path)\n env, num_states, num_actions = create_train_env(opt.world, opt.stage, opt.action_type)\n local_model = ActorCritic(num_states, num_actions)\n if opt.use_gpu:\n local_model.cuda()\n local_model.train() #Sets the module in training mode\n state = torch.from_numpy(env.reset())\n if opt.use_gpu:\n state = state.cuda()\n done = True\n curr_step = 0\n curr_episode = 0\n while True:\n if save:\n if curr_episode % opt.save_interval == 0 and curr_episode > 0:\n torch.save(global_model.state_dict(),\n \"{}/a3c_super_mario_bros_{}_{}\".format(opt.saved_path, opt.world, opt.stage))\n print(\"Process {}. Episode {}\".format(index, curr_episode))\n curr_episode += 1\n local_model.load_state_dict(global_model.state_dict())\n if done:\n h_0 = torch.zeros((1, 512), dtype=torch.float)\n c_0 = torch.zeros((1, 512), dtype=torch.float)\n else:\n h_0 = h_0.detach()\n c_0 = c_0.detach()\n if opt.use_gpu:\n h_0 = h_0.cuda()\n c_0 = c_0.cuda()\n\n log_policies = []\n values = []\n rewards = []\n entropies = []\n\n for _ in range(opt.num_local_steps):\n curr_step += 1\n logits, value, h_0, c_0 = local_model(state, h_0, c_0)\n policy = F.softmax(logits, dim=1)\n log_policy = F.log_softmax(logits, dim=1)\n entropy = -(policy * log_policy).sum(1, keepdim=True)\n\n m = Categorical(policy)\n action = m.sample().item()\n\n state, reward, done, _ = env.step(action)\n state = torch.from_numpy(state)\n if opt.use_gpu:\n state = state.cuda()\n if curr_step > opt.num_global_steps:\n done = True\n\n if done:\n curr_step = 0\n state = torch.from_numpy(env.reset())\n if opt.use_gpu:\n state = state.cuda()\n\n values.append(value)\n log_policies.append(log_policy[0, action])\n rewards.append(reward)\n entropies.append(entropy)\n\n if done:\n break\n\n R = torch.zeros((1, 1), dtype=torch.float)\n if opt.use_gpu:\n R = R.cuda()\n if not done:\n _, R, _, _ = local_model(state, h_0, c_0)\n\n gae = torch.zeros((1, 1), dtype=torch.float)\n if opt.use_gpu:\n gae = gae.cuda()\n actor_loss = 0\n critic_loss = 0\n entropy_loss = 0\n next_value = R\n\n for value, log_policy, reward, entropy in list(zip(values, log_policies, rewards, entropies))[::-1]:\n gae = gae * opt.gamma * opt.tau\n gae = gae + reward + opt.gamma * next_value.detach() - value.detach()\n next_value = value\n actor_loss = actor_loss + log_policy * gae\n R = R * opt.gamma + reward\n critic_loss = critic_loss + (R - value) ** 2 / 2\n entropy_loss = entropy_loss + entropy\n\n total_loss = -actor_loss + critic_loss - opt.beta * entropy_loss\n writer.add_scalar(\"Train_{}/Loss\".format(index), total_loss, curr_episode)\n optimizer.zero_grad()\n total_loss.backward()\n\n for local_param, global_param in zip(local_model.parameters(), global_model.parameters()):\n if global_param.grad is not None:\n break\n global_param._grad = local_param.grad\n\n optimizer.step()\n\n if curr_episode == int(opt.num_global_steps / opt.num_local_steps):\n print(\"Training process {} terminated\".format(index))\n if save:\n end_time = timeit.default_timer()\n print('The code runs for %.2f s ' % (end_time - start_time))\n return\n\n\ndef local_test(index, opt, global_model):\n torch.manual_seed(123 + index)\n env, num_states, num_actions = create_train_env(opt.world, opt.stage, opt.action_type)\n local_model = ActorCritic(num_states, num_actions)\n local_model.eval()\n state = torch.from_numpy(env.reset())\n done = True\n curr_step = 0\n actions = deque(maxlen=opt.max_actions)\n while True:\n curr_step += 1\n if done:\n local_model.load_state_dict(global_model.state_dict())\n with torch.no_grad():\n if done:\n h_0 = torch.zeros((1, 512), dtype=torch.float)\n c_0 = torch.zeros((1, 512), dtype=torch.float)\n else:\n h_0 = h_0.detach()\n c_0 = c_0.detach()\n\n logits, value, h_0, c_0 = local_model(state, h_0, c_0)\n policy = F.softmax(logits, dim=1)\n action = torch.argmax(policy).item()\n state, reward, done, _ = env.step(action)\n env.render()\n actions.append(action)\n if curr_step > opt.num_global_steps or actions.count(actions[0]) == actions.maxlen:\n done = True\n if done:\n curr_step = 0\n actions.clear()\n state = env.reset()\n state = torch.from_numpy(state)\n" ]
[ [ "torch.nn.functional.softmax", "torch.nn.functional.log_softmax", "torch.zeros", "torch.manual_seed", "torch.from_numpy", "torch.distributions.Categorical", "torch.no_grad", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dweigand/qutip
[ "b57d5e4b4846880e894afa390c62f4d095c642e1" ]
[ "qutip/tests/test_subsys_apply.py" ]
[ "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its 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 FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\nfrom numpy.linalg import norm\nfrom numpy.testing import assert_, run_module_suite\n\nfrom qutip.random_objects import rand_dm, rand_unitary, rand_kraus_map\nfrom qutip.subsystem_apply import subsystem_apply\nfrom qutip.superop_reps import kraus_to_super\nfrom qutip.superoperator import mat2vec, vec2mat\nfrom qutip.tensor import tensor\nfrom qutip.qobj import Qobj\n\n\nclass TestSubsysApply(object):\n \"\"\"\n A test class for the QuTiP function for applying superoperators to\n subsystems.\n The four tests below determine whether efficient numerics, naive numerics\n and semi-analytic results are identical.\n \"\"\"\n\n def test_SimpleSingleApply(self):\n \"\"\"\n Non-composite system, operator on Hilbert space.\n \"\"\"\n tol = 1e-12\n rho_3 = rand_dm(3)\n single_op = rand_unitary(3)\n analytic_result = single_op * rho_3 * single_op.dag()\n naive_result = subsystem_apply(rho_3, single_op, [True],\n reference=True)\n naive_diff = (analytic_result - naive_result).data.todense()\n naive_diff_norm = norm(naive_diff)\n assert_(naive_diff_norm < tol,\n msg=\"SimpleSingle: naive_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n naive_diff_norm, tol))\n \n efficient_result = subsystem_apply(rho_3, single_op, [True])\n efficient_diff = (efficient_result - analytic_result).data.todense()\n efficient_diff_norm = norm(efficient_diff)\n assert_(efficient_diff_norm < tol,\n msg=\"SimpleSingle: efficient_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n efficient_diff_norm, tol))\n\n def test_SimpleSuperApply(self):\n \"\"\"\n Non-composite system, operator on Liouville space.\n \"\"\"\n tol = 1e-12\n rho_3 = rand_dm(3)\n superop = kraus_to_super(rand_kraus_map(3))\n analytic_result = vec2mat(superop.data.todense() *\n mat2vec(rho_3.data.todense()))\n\n naive_result = subsystem_apply(rho_3, superop, [True],\n reference=True)\n naive_diff = (analytic_result - naive_result).data.todense()\n naive_diff_norm = norm(naive_diff)\n assert_(naive_diff_norm < tol,\n msg=\"SimpleSuper: naive_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n naive_diff_norm, tol))\n\n efficient_result = subsystem_apply(rho_3, superop, [True])\n efficient_diff = (efficient_result - analytic_result).data.todense()\n efficient_diff_norm = norm(efficient_diff)\n assert_(efficient_diff_norm < tol,\n msg=\"SimpleSuper: efficient_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n efficient_diff_norm, tol))\n\n def test_ComplexSingleApply(self):\n \"\"\"\n Composite system, operator on Hilbert space.\n \"\"\"\n tol = 1e-12\n rho_list = list(map(rand_dm, [2, 3, 2, 3, 2]))\n rho_input = tensor(rho_list)\n single_op = rand_unitary(3)\n\n analytic_result = rho_list\n analytic_result[1] = single_op * analytic_result[1] * single_op.dag()\n analytic_result[3] = single_op * analytic_result[3] * single_op.dag()\n analytic_result = tensor(analytic_result)\n\n naive_result = subsystem_apply(rho_input, single_op,\n [False, True, False, True, False],\n reference=True)\n naive_diff = (analytic_result - naive_result).data.todense()\n naive_diff_norm = norm(naive_diff)\n assert_(naive_diff_norm < tol,\n msg=\"ComplexSingle: naive_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n naive_diff_norm, tol))\n\n efficient_result = subsystem_apply(rho_input, single_op,\n [False, True, False, True, False])\n efficient_diff = (efficient_result - analytic_result).data.todense()\n efficient_diff_norm = norm(efficient_diff)\n assert_(efficient_diff_norm < tol,\n msg=\"ComplexSingle: efficient_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n efficient_diff_norm, tol))\n\n def test_ComplexSuperApply(self):\n \"\"\"\n Superoperator: Efficient numerics and reference return same result,\n acting on non-composite system\n \"\"\"\n tol = 1e-10\n rho_list = list(map(rand_dm, [2, 3, 2, 3, 2]))\n rho_input = tensor(rho_list)\n superop = kraus_to_super(rand_kraus_map(3))\n \n analytic_result = rho_list\n analytic_result[1] = Qobj(vec2mat(superop.data.todense() *\n mat2vec(analytic_result[1].data.todense())))\n analytic_result[3] = Qobj(vec2mat(superop.data.todense() *\n mat2vec(analytic_result[3].data.todense())))\n analytic_result = tensor(analytic_result)\n\n naive_result = subsystem_apply(rho_input, superop,\n [False, True, False, True, False],\n reference=True)\n naive_diff = (analytic_result - naive_result).data.todense()\n naive_diff_norm = norm(naive_diff)\n assert_(naive_diff_norm < tol,\n msg=\"ComplexSuper: naive_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n naive_diff_norm, tol))\n\n efficient_result = subsystem_apply(rho_input, superop,\n [False, True, False, True, False])\n efficient_diff = (efficient_result - analytic_result).data.todense()\n efficient_diff_norm = norm(efficient_diff)\n assert_(efficient_diff_norm < tol,\n msg=\"ComplexSuper: efficient_diff_norm {} \"\n \"is beyond tolerance {}\".format(\n efficient_diff_norm, tol))\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n" ]
[ [ "numpy.testing.run_module_suite", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
DFLyan/DPA-Net
[ "9629195f374091de216febf35d46446e6d242630" ]
[ "model_DPA.py" ]
[ "#! /usr/bin/python\n# -*- coding: utf8 -*-\n\nimport tensorflow as tf\nimport tensorlayer as tl\nimport numpy as np\nfrom tensorlayer.layers import *\nfrom config import config, log_config\n\nbatch_size = config.TRAIN.batch_size\n\n\ndef T1(y_1, is_train=False, reuse=False):\n w_init = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(value=0.0)\n g_init = tf.random_normal_initializer(1., 0.02)\n with tf.variable_scope(\"t1\", reuse=reuse):\n n_1 = InputLayer(y_1)\n\n t1 = Conv2d(n_1, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='init256/1')\n\n t1 = bottleneck(t1, is_train=is_train, con_number=256, block_num=1)\n t1_a1 = t1\n t1 = SubpixelConv2d(t1, scale=2, n_out_channel=None, act=None, name='pixelshufflerx2/1')\n t1 = Conv2d(t1, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual1/n16/2')\n\n t1 = bottleneck(t1, is_train=is_train, con_number=256, block_num=2)\n t1_a2 = t1\n t1 = SubpixelConv2d(t1, scale=2, n_out_channel=None, act=None, name='pixelshufflerx2/2')\n t1 = Conv2d(t1, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual2/n16/2')\n\n t1 = bottleneck(t1, is_train=is_train, con_number=256, block_num=3)\n t1_a3 = t1\n t1 = SubpixelConv2d(t1, scale=2, n_out_channel=None, act=None, name='pixelshufflerx2/3')\n t1 = Conv2d(t1, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual3/n16/2')\n\n t1 = bottleneck(t1, is_train=is_train, con_number=256, block_num=4)\n t1_a4 = t1\n t1 = SubpixelConv2d(t1, scale=2, n_out_channel=None, act=None, name='pixelshufflerx2/4')\n t1 = Conv2d(t1, 32, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='global_n32/s1')\n\n t1 = Conv2d(t1, 1, (3, 3), (1, 1), act=tl.act.hard_tanh, padding='SAME', W_init=w_init, b_init=b_init, name='out')\n return t1, t1_a1, t1_a2, t1_a3, t1_a4\n\n\ndef T2(y_2, t2_a1, t2_a2, t2_a3, t2_a4, is_train=False, reuse=False):\n w_init = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(value=0.0)\n g_init = tf.random_normal_initializer(1., 0.02)\n j = 1\n with tf.variable_scope(\"t2\", reuse=reuse):\n n_2 = InputLayer(y_2)\n\n t2 = Conv2d(n_2, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='init256/1')\n\n temp_global = t2\n temp = t2\n t2 = block(t2, 5, 64, is_train=is_train, idx_=11, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb1/n256/1')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual1/add1')\n t2, spa1 = attention(t2, t2_a1, con_number=256, block_num=1)\n temp = t2\n t2 = block(t2, 2, 64, is_train=is_train, idx_=12, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb1/n256/2')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual1/add2')\n t2 = ElementwiseLayer([t2, temp_global], combine_fn=tf.add, name='b_residual1/add3')\n t2 = SubpixelConv2d(t2, scale=2, n_out_channel=None, act=tf.nn.selu, name='attention1/pixelshufflerx2/1')\n t2 = Conv2d(t2, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual1/n16/2')\n\n temp_global = t2\n temp = t2\n t2 = block(t2, 5, 64, is_train=is_train, idx_=21, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb2/n256/1')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual2/add1')\n t2, spa2 = attention(t2, t2_a2, con_number=256, block_num=2)\n temp = t2\n t2 = block(t2, 2, 64, is_train=is_train, idx_=22, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb2/n256/2')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual2/add2')\n t2 = ElementwiseLayer([t2, temp_global], combine_fn=tf.add, name='b_residual2/add3')\n t2 = SubpixelConv2d(t2, scale=2, n_out_channel=None, act=tf.nn.selu, name='attention2/pixelshufflerx2/1')\n # t2 = BatchNormLayer(t2, act=tf.nn.selu, is_train=is_train, gamma_init=g_init, name='attention2/b2')\n t2 = Conv2d(t2, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual2/n16/2')\n\n temp_global = t2\n temp = t2\n t2 = block(t2, 5, 64, is_train=is_train, idx_=31, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb3/n256/1')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual3/add1')\n t2, spa3 = attention(t2, t2_a3, con_number=256, block_num=3)\n temp = t2\n t2 = block(t2, 2, 64, is_train=is_train, idx_=32, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb3/n256/2')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual3/add2')\n t2 = ElementwiseLayer([t2, temp_global], combine_fn=tf.add, name='b_residual3/add3')\n t2 = SubpixelConv2d(t2, scale=2, n_out_channel=None, act=tf.nn.selu, name='attention3/pixelshufflerx2/1')\n # t2 = BatchNormLayer(t2, act=tf.nn.selu, is_train=is_train, gamma_init=g_init, name='attention3/b2')\n t2 = Conv2d(t2, 256, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='b_residual3/n16/2')\n\n temp_global = t2\n temp = t2\n t2 = block(t2, 5, 64, is_train=is_train, idx_=41, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb4/n256/1')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual4/add1')\n t2, spa4 = attention(t2, t2_a4, con_number=256, block_num=4)\n temp = t2\n t2 = block(t2, 2, 64, is_train=is_train, idx_=42, task=2)\n t2 = Conv2d(t2, 256, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='rdb4/n256/2')\n t2 = ElementwiseLayer([t2, temp], combine_fn=tf.add, name='b_residual4/add2')\n t2 = ElementwiseLayer([t2, temp_global], combine_fn=tf.add, name='b_residual4/add3')\n t2 = SubpixelConv2d(t2, scale=2, n_out_channel=None, act=tf.nn.selu, name='attention4/pixelshufflerx2/1')\n t2 = Conv2d(t2, 32, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='global_n32/s1')\n t2 = Conv2d(t2, 1, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init, name='t2/out')\n return t2\n\n\ndef add_two_layer(t1, t2):\n t = ElementwiseLayer([t1, t2], combine_fn=tf.add, act=tl.act.hard_tanh, name='add_all1')\n return t\n\n\ndef batch_activ_conv(current, out_features, is_train, idx, idx_, task):\n w_init = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(value=0.0)\n g_init = tf.random_normal_initializer(1., 0.02)\n\n current = BatchNormLayer(current, act=tf.nn.selu, is_train=is_train, gamma_init=g_init,\n name='t%s/BN%s/%s/2' % (task, idx_, idx))\n current = Conv2d(current, out_features, (1, 1), (1, 1), act=None, padding='SAME', W_init=w_init, b_init=b_init,\n name='t%s/Cov2d%s/%s/2' % (task, idx_, idx))\n\n current = BatchNormLayer(current, act=tf.nn.selu, is_train=is_train, gamma_init=g_init,\n name='t%s/BN%s/%s/4' % (task, idx_, idx))\n current = Conv2d(current, out_features, (3, 3), (1, 1), act=None, padding='SAME', W_init=w_init, b_init=b_init,\n name='t%s/Cov2d%s/%s/4' % (task, idx_, idx))\n return current\n\n\ndef block(input, layers, growth, is_train, idx_, task):\n input = Conv2d(input, growth, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', name='t%s/Cov2d%s/input' % (task, idx_))\n current = input\n for idx in range(layers):\n tmp = batch_activ_conv(current, growth, is_train=is_train, idx=idx, idx_=idx_, task=task)\n current = ConcatLayer([current, tmp], 3, name='t%s/concat%s/%s' % (task, idx_, idx))\n return current\n\n\ndef softmax(x):\n return tf.divide(tf.exp(x), tf.expand_dims(tf.expand_dims(tf.expand_dims(\n tf.reduce_sum(tf.exp(x), axis=[1, 2, 3]), -1), -1), -1))\n\n\ndef bottleneck(x, is_train, con_number, block_num):\n w_init = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(value=0.0)\n g_init = tf.random_normal_initializer(1., 0.02)\n x_local_temp = x\n x = BatchNormLayer(x, act=tf.nn.selu, is_train=is_train, gamma_init=g_init, name='residual%s/b1' % block_num)\n x = Conv2d(x, con_number / 4, (1, 1), (1, 1), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='residual%s/c1' % block_num)\n x = BatchNormLayer(x, act=tf.nn.selu, is_train=is_train, gamma_init=g_init, name='residual%s/b2' % block_num)\n x = Conv2d(x, con_number / 4, (3, 3), (1, 1), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='residual%s/c2' % block_num)\n x = BatchNormLayer(x, act=tf.nn.selu, is_train=is_train, gamma_init=g_init, name='residual%s/b3' % block_num)\n x = Conv2d(x, con_number, (1, 1), (1, 1), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='residual%s/c3' % block_num)\n x = ElementwiseLayer([x, x_local_temp], combine_fn=tf.add, name='residual%s/add' % block_num)\n return x\n\n\ndef attention(x, y, con_number, block_num):\n w_init = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(value=0.0)\n g_init = tf.random_normal_initializer(1., 0.02)\n x_temp = x\n x = Conv2d(x, (con_number / 2), (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='attention%s/xreduce' % block_num)\n y = Conv2d(y, (con_number / 2), (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='attention%s/yreduce' % block_num)\n a_c = x\n a_s = x\n a_c = GlobalMeanPool2d(a_c, name='attention%s/pooling' % block_num)\n a_c = DenseLayer(a_c, con_number / 2, act=tf.nn.selu, name='attention%s/dense1' % block_num)\n a_c = DenseLayer(a_c, con_number / 2, act=tf.nn.sigmoid, name='attention%s/dense2' % block_num)\n a_c = ReshapeLayer(a_c, (-1, 1, 1, int(con_number / 2)), name='attention%s/reshape' % block_num)\n\n a_s = Conv2d(a_s, con_number / 4, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='attention%s/spatial1' % block_num)\n a_s = Conv2d(a_s, 1, (1, 1), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='attention%s/spatial2' % block_num)\n spa = a_s\n a_c = ElementwiseLayer([y, a_c], combine_fn=tf.multiply, name='attention%s/fusion/mult1' % block_num)\n a_s = ElementwiseLayer([a_c, a_s], combine_fn=tf.multiply, name='attention%s/fusion/mult2' % block_num)\n a_s = ConcatLayer([x, a_s], concat_dim=3, name='attention%s/concat1' % block_num)\n\n a_s = Conv2d(a_s, con_number, (3, 3), (1, 1), act=tf.nn.selu, padding='SAME', W_init=w_init, b_init=b_init,\n name='attention%s/dimreduce' % block_num)\n x = ElementwiseLayer([x_temp, a_s], combine_fn=tf.add, name='attention%s/fusion/add' % block_num)\n return x, spa\n" ]
[ [ "tensorflow.constant_initializer", "tensorflow.random_normal_initializer", "tensorflow.variable_scope", "tensorflow.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
ofnote/IndicSynthText
[ "8e7b7413e3b0e560c30b05b93932b5a1d06a4ac7" ]
[ "text_utils.py" ]
[ "from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport scipy.io as sio\nimport os.path as osp\nimport random, os\nimport cv2\n#import cPickle as cp\nimport _pickle as cp\nimport scipy.signal as ssig\nimport scipy.stats as sstat\nimport pygame, pygame.locals\nfrom pygame import freetype\n#import Image\nfrom PIL import Image\nimport math\nfrom common import *\nimport pickle\n#import codecs\n#import fibridi\n\ndef sample_weighted(p_dict):\n ps = list(p_dict.keys())\n return p_dict[np.random.choice(ps,p=ps)]\n\ndef move_bb(bbs, t):\n \"\"\"\n Translate the bounding-boxes in by t_x,t_y.\n BB : 2x4xn\n T : 2-long np.array\n \"\"\"\n return bbs + t[:,None,None]\n\ndef crop_safe(arr, rect, bbs=[], pad=0):\n \"\"\"\n ARR : arr to crop\n RECT: (x,y,w,h) : area to crop to\n BBS : nx4 xywh format bounding-boxes\n PAD : percentage to pad\n\n Does safe cropping. Returns the cropped rectangle and\n the adjusted bounding-boxes\n \"\"\"\n rect = np.array(rect)\n rect[:2] -= pad\n rect[2:] += 2*pad\n v0 = [max(0,rect[0]), max(0,rect[1])]\n v1 = [min(arr.shape[0], rect[0]+rect[2]), min(arr.shape[1], rect[1]+rect[3])]\n arr = arr[v0[0]:v1[0],v0[1]:v1[1],...]\n if len(bbs) > 0:\n for i in range(len(bbs)):\n bbs[i,0] -= v0[0]\n bbs[i,1] -= v0[1]\n return arr, bbs\n else:\n return arr\n\n\nclass BaselineState(object):\n curve = lambda this, a: lambda x: a*x*x\n differential = lambda this, a: lambda x: 2*a*x\n a = [0.50, 0.05]\n\n def get_sample(self):\n \"\"\"\n Returns the functions for the curve and differential for a and b\n \"\"\"\n sgn = 1.0\n if np.random.rand() < 0.5:\n sgn = -1\n\n a = self.a[1]*np.random.randn() + sgn*self.a[0]\n return {\n 'curve': self.curve(a),\n 'diff': self.differential(a),\n }\n\nclass RenderFont(object):\n \"\"\"\n Outputs a rasterized font sample.\n Output is a binary mask matrix cropped closesly with the font.\n Also, outputs ground-truth bounding boxes and text string\n \"\"\"\n\n def __init__(self, lang, data_dir='data'):\n # distribution over the type of text:\n # whether to get a single word, paragraph or a line:\n self.p_text = {1.0 : 'WORD',\n 0.0 : 'LINE',\n 0.0 : 'PARA'}\n\n ## TEXT PLACEMENT PARAMETERS:\n self.f_shrink = 0.90\n self.max_shrink_trials = 5 # 0.9^5 ~= 0.6\n # the minimum number of characters that should fit in a mask\n # to define the maximum font height.\n self.min_nchar = 2\n self.min_font_h = 16 #px : 0.6*12 ~ 7px <= actual minimum height\n self.max_font_h = 120 #px\n self.p_flat = 0.10\n\n # curved baseline:\n self.p_curved = 1.0\n self.baselinestate = BaselineState()\n file_path = 'newsgroup/newsgroup'+lang+'.txt'\n # text-source : gets english text:\n self.text_source = TextSource(min_nchar=self.min_nchar,\n fn=osp.join(data_dir,file_path))\n\n # get font-state object:\n self.font_state = FontState(lang,data_dir)\n\n pygame.init()\n\n def render_multiline(self,font,text):\n \"\"\"\n renders multiline TEXT on the pygame surface SURF with the\n font style FONT.\n A new line in text is denoted by \\n, no other characters are \n escaped. Other forms of white-spaces should be converted to space.\n\n returns the updated surface, words and the character bounding boxes.\n \"\"\"\n # get the number of lines\n lines = text.split('\\n')\n lengths = [len(l) for l in lines]\n\n # font parameters:\n line_spacing = font.get_sized_height() + 1\n \n # initialize the surface to proper size:\n line_bounds = font.get_rect(lines[np.argmax(lengths)])\n fsize = (round(2.0*line_bounds.width), round(1.25*line_spacing*len(lines)))\n surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)\n\n bbs = []\n space = font.get_rect('O')\n x, y = 0, 0\n for l in lines:\n x = 0 # carriage-return\n y += line_spacing # line-feed\n\n for ch in l: # render each character\n if ch.isspace(): # just shift\n x += space.width\n else:\n # render the character\n ch_bounds = font.render_to(surf, (x,y), ch)\n ch_bounds.x = x + ch_bounds.x\n ch_bounds.y = y - ch_bounds.y\n x += ch_bounds.width\n bbs.append(np.array(ch_bounds))\n\n # get the union of characters for cropping:\n r0 = pygame.Rect(bbs[0])\n rect_union = r0.unionall(bbs)\n\n # get the words:\n words = ' '.join(text.split())\n\n # crop the surface to fit the text:\n bbs = np.array(bbs)\n surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5)\n surf_arr = surf_arr.swapaxes(0,1)\n #self.visualize_bb(surf_arr,bbs)\n return surf_arr, words, bbs\n\n def render_curved(self, font, word_text):#add lang\n \"\"\"\n use curved baseline for rendering word\n \"\"\"\n #print(font)\n #word_text = word_text.replace('\\u200c,' ') for arab\n wl = len(word_text)\n isword = len(word_text.split())==1\n\n # do curved iff, the length of the word <= 10\n if not isword or wl > 10 or np.random.rand() > self.p_curved:\n return self.render_multiline(font, word_text)\n\n #for arab word_text = fribidi.log2vis(word_text, None, fribidi.ParType.RTL)\n # create the surface:\n lspace = font.get_sized_height() + 1\n lbound = font.get_rect(word_text)\n fsize = (round(2.0*lbound.width), round(3*lspace))\n surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)\n\n # baseline state\n mid_idx = wl//2\n BS = self.baselinestate.get_sample()\n curve = [BS['curve'](i-mid_idx) for i in range(wl)]\n curve[mid_idx] = -np.sum(curve) / (wl-1)\n rots = [-int(math.degrees(math.atan(BS['diff'](i-mid_idx)/(font.size/2)))) for i in range(wl)]\n\n bbs = []\n # place middle char\n rect = font.get_rect(word_text[mid_idx])\n rect.centerx = surf.get_rect().centerx\n rect.centery = surf.get_rect().centery + rect.height\n rect.centery += curve[mid_idx]\n ch_bounds = font.render_to(surf, rect, word_text[mid_idx], rotation=rots[mid_idx])\n ch_bounds.x = rect.x + ch_bounds.x\n ch_bounds.y = rect.y - ch_bounds.y\n mid_ch_bb = np.array(ch_bounds)\n\n # render chars to the left and right:\n \n ch_idx = []\n '''if lang == 'arab' or 'urdu':\n bbs.append(mid_ch_bb)\n ch_idx.append(0) for arab''' \n\n last_rect = rect\n for i in range(wl):\n #skip the middle character\n if i==mid_idx: \n bbs.append(mid_ch_bb)\n ch_idx.append(i)\n continue\n\n if i < mid_idx: #left-chars\n i = mid_idx-1-i\n elif i==mid_idx+1: #right-chars begin\n last_rect = rect\n\n ch_idx.append(i)\n ch = word_text[i]\n\n newrect = font.get_rect(ch)\n newrect.y = last_rect.y\n if i > mid_idx:\n newrect.topleft = (last_rect.topright[0]+2, newrect.topleft[1])\n else:\n newrect.topright = (last_rect.topleft[0]-2, newrect.topleft[1])\n newrect.centery = max(newrect.height, min(fsize[1] - newrect.height, newrect.centery + curve[i]))\n try:\n bbrect = font.render_to(surf, newrect, ch, rotation=rots[i])\n except ValueError:\n bbrect = font.render_to(surf, newrect, ch)\n bbrect.x = newrect.x + bbrect.x\n bbrect.y = newrect.y - bbrect.y\n bbs.append(np.array(bbrect))\n last_rect = newrect\n \n # correct the bounding-box order:\n bbs_sequence_order = [None for i in ch_idx]\n for idx,i in enumerate(ch_idx):\n bbs_sequence_order[i] = bbs[idx]\n bbs = bbs_sequence_order\n\n # get the union of characters for cropping:\n r0 = pygame.Rect(bbs[0])\n rect_union = r0.unionall(bbs)\n\n # crop the surface to fit the text:\n bbs = np.array(bbs)\n surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5)\n surf_arr = surf_arr.swapaxes(0,1)\n #plt.imshow(surf_arr)\n #plt.show()\n #print(word_text)\n return surf_arr, word_text, bbs\n\n\n def get_nline_nchar(self,mask_size,font_height,font_width):\n \"\"\"\n Returns the maximum number of lines and characters which can fit\n in the MASK_SIZED image.\n \"\"\"\n H,W = mask_size\n nline = int(np.ceil(H/(2*font_height)))\n nchar = int(np.floor(W/font_width))\n return nline,nchar\n\n def place_text(self, text_arrs, back_arr, bbs):\n areas = [-np.prod(ta.shape) for ta in text_arrs]\n order = np.argsort(areas)\n\n locs = [None for i in range(len(text_arrs))]\n out_arr = np.zeros_like(back_arr)\n for i in order: \n ba = np.clip(back_arr.copy().astype(np.float), 0, 255)\n ta = np.clip(text_arrs[i].copy().astype(np.float), 0, 255)\n ba[ba > 127] = 1e8\n intersect = ssig.fftconvolve(ba,ta[::-1,::-1],mode='valid')\n safemask = intersect < 1e8\n\n if not np.any(safemask): # no collision-free position:\n #warn(\"COLLISION!!!\")\n return back_arr,locs[:i],bbs[:i],order[:i]\n\n minloc = np.transpose(np.nonzero(safemask))\n loc = minloc[np.random.choice(minloc.shape[0]),:]\n locs[i] = loc\n\n # update the bounding-boxes:\n bbs[i] = move_bb(bbs[i],loc[::-1])\n\n # blit the text onto the canvas\n w,h = text_arrs[i].shape\n out_arr[loc[0]:loc[0]+w,loc[1]:loc[1]+h] += text_arrs[i]\n\n return out_arr, locs, bbs, order\n\n def robust_HW(self,mask):\n m = mask.copy()\n m = (~mask).astype('float')/255\n rH = np.median(np.sum(m,axis=0))\n rW = np.median(np.sum(m,axis=1))\n return rH,rW\n\n def sample_font_height_px(self,h_min,h_max):\n if np.random.rand() < self.p_flat:\n rnd = np.random.rand()\n else:\n rnd = np.random.beta(2.0,2.0)\n\n h_range = h_max - h_min\n f_h = np.floor(h_min + h_range*rnd)\n return f_h\n\n def bb_xywh2coords(self,bbs):\n \"\"\"\n Takes an nx4 bounding-box matrix specified in x,y,w,h\n format and outputs a 2x4xn bb-matrix, (4 vertices per bb).\n \"\"\"\n n,_ = bbs.shape\n coords = np.zeros((2,4,n))\n for i in range(n):\n coords[:,:,i] = bbs[i,:2][:,None]\n coords[0,1,i] += bbs[i,2]\n coords[:,2,i] += bbs[i,2:4]\n coords[1,3,i] += bbs[i,3]\n return coords\n\n\n def render_sample(self,font,mask):\n \"\"\"\n Places text in the \"collision-free\" region as indicated\n in the mask -- 255 for unsafe, 0 for safe.\n The text is rendered using FONT, the text content is TEXT.\n \"\"\"\n #H,W = mask.shape\n H,W = self.robust_HW(mask)\n f_asp = self.font_state.get_aspect_ratio(font)\n\n # find the maximum height in pixels:\n max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))\n max_font_h = min(max_font_h, self.max_font_h)\n if max_font_h < self.min_font_h: # not possible to place any text here\n return #None\n\n # let's just place one text-instance for now\n ## TODO : change this to allow multiple text instances?\n i = 0\n while i < self.max_shrink_trials and max_font_h > self.min_font_h:\n # if i > 0:\n # print colorize(Color.BLUE, \"shrinkage trial : %d\"%i, True)\n\n # sample a random font-height:\n f_h_px = self.sample_font_height_px(self.min_font_h, max_font_h)\n #print \"font-height : %.2f (min: %.2f, max: %.2f)\"%(f_h_px, self.min_font_h,max_font_h)\n # convert from pixel-height to font-point-size:\n f_h = self.font_state.get_font_size(font, f_h_px)\n\n # update for the loop\n max_font_h = f_h_px \n i += 1\n\n font.size = f_h # set the font-size\n\n # compute the max-number of lines/chars-per-line:\n nline,nchar = self.get_nline_nchar(mask.shape[:2],f_h,f_h*f_asp)\n #print (' > nline = {}, nchar = {}'.format(nline, nchar))\n\n assert nline >= 1 and nchar >= self.min_nchar\n\n # sample text:\n text_type = sample_weighted(self.p_text)\n text = self.text_source.sample(nline,nchar,text_type)\n #print(text)\n if len(text)==0 or np.any([len(line)==0 for line in text]):\n continue\n #print colorize(Color.GREEN, text)\n\n # render the text:\n txt_arr,txt,bb = self.render_curved(font, text)\n bb = self.bb_xywh2coords(bb)\n\n # make sure that the text-array is not bigger than mask array:\n if np.any(np.r_[txt_arr.shape[:2]] > np.r_[mask.shape[:2]]):\n #warn(\"text-array is bigger than mask\")\n continue\n\n # position the text within the mask:\n text_mask,loc,bb, _ = self.place_text([txt_arr], mask, [bb])\n if len(loc) > 0:#successful in placing the text collision-free:\n return text_mask,loc[0],bb[0],text\n return #None\n\n\n def visualize_bb(self, text_arr, bbs):\n ta = text_arr.copy()\n for r in bbs:\n cv.rectangle(ta, (r[0],r[1]), (r[0]+r[2],r[1]+r[3]), color=128, thickness=1)\n plt.imshow(ta,cmap='gray')\n plt.show()\n\n\nclass FontState(object):\n \"\"\"\n Defines the random state of the font rendering \n \"\"\"\n size = [50, 10] # normal dist mean, std\n underline = 0.05\n strong = 0.5\n oblique = 0.2\n wide = 0.5\n strength = [0.05, 0.1] # uniform dist in this interval\n underline_adjustment = [1.0, 2.0] # normal dist mean, std\n kerning = [2, 5, 0, 20] # beta distribution alpha, beta, offset, range (mean is a/(a+b))\n border = 0.25\n random_caps = -1 ## don't recapitalize : retain the capitalization of the lexicon\n capsmode = [str.lower, str.upper, str.capitalize] # lower case, upper case, proper noun\n curved = 0.2\n random_kerning = 0.2\n random_kerning_amount = 0.1\n\n def __init__(self, lang, data_dir='data', create_model=False):\n\n char_freq_path = osp.join(data_dir, 'models/char_freq.cp')\n if create_model:\n font_model_path = osp.join(data_dir, 'models/font_px2pt.cp')\n else: \n font_model_path = osp.join(data_dir, 'models/font_px2pt'+lang+'.cp')\n\n # get character-frequencies in the English language:\n #with open(char_freq_path,'rb') as f:\n # self.char_freq = cp.load(f)\n # u = pickle._Unpickler(f)\n # u.encoding = 'latin1'\n # p = u.load()\n # self.char_freq = p\n\n # get the model to convert from pixel to font pt size:\n with open(font_model_path,'rb') as f:\n self.font_model = cp.load(f)\n '''u = pickle._Unpickler(f)\n u.encoding = 'latin1'\n p = u.load()\n self.font_model = p'''\n \n # get the names of fonts to use:\n self.FONT_LIST = osp.join(data_dir, 'fonts/fontlist.txt')\n self.fonts = [os.path.join(data_dir,'fonts',f.strip()) for f in open(self.FONT_LIST) if lang in f]\n print(self.fonts)\n\n\n def get_aspect_ratio(self, font, size=None):\n \"\"\"\n Returns the median aspect ratio of each character of the font.\n \"\"\"\n if size is None:\n size = 12 # doesn't matter as we take the RATIO\n #chars = ''.join(self.char_freq.keys())\n #w = np.array(self.char_freq.values())\n\n # get the [height,width] of each character:\n try:\n sizes = font.get_metrics(chars,size)\n good_idx = [i for i in range(len(sizes)) if sizes[i] is not None]\n sizes,w = [sizes[i] for i in good_idx], w[good_idx]\n sizes = np.array(sizes).astype('float')[:,[3,4]] \n r = np.abs(sizes[:,1]/sizes[:,0]) # width/height\n good = np.isfinite(r)\n r = r[good]\n w = w[good]\n w /= np.sum(w)\n r_avg = np.sum(w*r)\n return r_avg\n except:\n return 1.0\n\n def get_font_size(self, font, font_size_px):\n \"\"\"\n Returns the font-size which corresponds to FONT_SIZE_PX pixels font height.\n \"\"\"\n m = self.font_model[font.name]\n return m[0]*font_size_px + m[1] #linear model\n\n\n def sample(self):\n \"\"\"\n Samples from the font state distribution\n \"\"\"\n return {\n 'font': self.fonts[int(np.random.randint(0, len(self.fonts)))],\n 'size': self.size[1]*np.random.randn() + self.size[0],\n 'underline': np.random.rand() < self.underline,\n 'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1]*np.random.randn() + self.underline_adjustment[0])),\n 'strong': np.random.rand() < self.strong,\n 'oblique': np.random.rand() < self.oblique,\n 'strength': (self.strength[1] - self.strength[0])*np.random.rand() + self.strength[0],\n 'char_spacing': int(self.kerning[3]*(np.random.beta(self.kerning[0], self.kerning[1])) + self.kerning[2]),\n 'border': np.random.rand() < self.border,\n 'random_caps': np.random.rand() < self.random_caps,\n 'capsmode': random.choice(self.capsmode),\n 'curved': np.random.rand() < self.curved,\n 'random_kerning': np.random.rand() < self.random_kerning,\n 'random_kerning_amount': self.random_kerning_amount,\n }\n\n def init_font(self,fs):\n \"\"\"\n Initializes a pygame font.\n FS : font-state sample\n \"\"\"\n font = freetype.Font(fs['font'], size=fs['size'])\n font.underline = fs['underline']\n font.underline_adjustment = fs['underline_adjustment']\n font.strong = fs['strong']\n font.oblique = fs['oblique']\n font.strength = fs['strength']\n char_spacing = fs['char_spacing']\n font.antialiased = True\n font.origin = True\n return font\n\n\nclass TextSource(object):\n \"\"\"\n Provides text for words, paragraphs, sentences.\n \"\"\"\n def __init__(self, min_nchar, fn):\n \"\"\"\n TXT_FN : path to file containing text data.\n \"\"\"\n self.min_nchar = min_nchar\n self.fdict = {'WORD':self.sample_word,\n 'LINE':self.sample_line,\n 'PARA':self.sample_para}\n\n with open(fn,'r') as f:\n self.txt = [l.strip() for l in f.readlines()]\n #print(self.txt)\n\n # distribution over line/words for LINE/PARA:\n self.p_line_nline = np.array([0.85, 0.10, 0.05])\n self.p_line_nword = [4,3,12] # normal: (mu, std)\n self.p_para_nline = [1.0,1.0]#[1.7,3.0] # beta: (a, b), max_nline\n self.p_para_nword = [1.7,3.0,10] # beta: (a,b), max_nword\n\n # probability to center-align a paragraph:\n self.center_para = 0.5\n\n\n def check_symb_frac(self, txt, f=0.35):\n \"\"\"\n T/F return : T iff fraction of symbol/special-charcters in\n txt is less than or equal to f (default=0.25).\n \"\"\"\n return np.sum([not ch.isalnum() for ch in txt])/(len(txt)+0.0) <= f\n\n def is_good(self, txt, f=0.35):\n \"\"\"\n T/F return : T iff the lines in txt (a list of txt lines)\n are \"valid\".\n A given line l is valid iff:\n 1. It is not empty.\n 2. symbol_fraction > f\n 3. Has at-least self.min_nchar characters\n 4. Not all characters are i,x,0,O,-\n \"\"\"\n def is_txt(l):\n char_ex = ['i','I','o','O','0','-']\n chs = [ch in char_ex for ch in l]\n return not np.all(chs)\n\n return [ (len(l)> self.min_nchar\n and self.check_symb_frac(l,f)\n and is_txt(l)) for l in txt ]\n\n def center_align(self, lines):\n \"\"\"\n PADS lines with space to center align them\n lines : list of text-lines.\n \"\"\"\n ls = [len(l) for l in lines]\n max_l = max(ls)\n for i in range(len(lines)):\n l = lines[i].strip()\n dl = max_l-ls[i]\n lspace = dl//2\n rspace = dl-lspace\n lines[i] = ' '*lspace+l+' '*rspace\n return lines\n\n def get_lines(self, nline, nword, nchar_max, f=0.35, niter=100):\n def h_lines(niter=100):\n lines = ['']\n iter = 0\n while not np.all(self.is_good(lines,f)) and iter < niter:\n iter += 1\n line_start = np.random.choice(len(self.txt)-nline)\n lines = [self.txt[line_start+i] for i in range(nline)]\n return lines\n\n lines = ['']\n iter = 0\n while not np.all(self.is_good(lines,f)) and iter < niter:\n iter += 1\n lines = h_lines(niter=100)\n # get words per line:\n nline = len(lines)\n for i in range(nline):\n words = lines[i].split()\n dw = len(words)-nword[i]\n if dw > 0:\n first_word_index = random.choice(range(dw+1))\n lines[i] = ' '.join(words[first_word_index:first_word_index+nword[i]])\n\n while len(lines[i]) > nchar_max: #chop-off characters from end:\n if not np.any([ch.isspace() for ch in lines[i]]):\n lines[i] = ''\n else:\n lines[i] = lines[i][:len(lines[i])-lines[i][::-1].find(' ')].strip()\n \n if not np.all(self.is_good(lines,f)):\n return #None\n else:\n return lines\n\n def sample(self, nline_max,nchar_max,kind='WORD'):\n return self.fdict[kind](nline_max,nchar_max)\n \n def sample_word(self,nline_max,nchar_max,niter=100):\n rand_line = self.txt[np.random.choice(len(self.txt))] \n words = rand_line.split()\n if len(words)==0:\n return []\n rand_word = random.choice(words)\n\n iter = 0\n while iter < niter and (not self.is_good([rand_word])[0] or len(rand_word)>nchar_max):\n rand_line = self.txt[np.random.choice(len(self.txt))] \n words = rand_line.split()\n if len(words)==0:\n continue\n rand_word = random.choice(words)\n iter += 1\n\n if not self.is_good([rand_word])[0] or len(rand_word)>nchar_max:\n return []\n else:\n return rand_word\n\n\n def sample_line(self,nline_max,nchar_max):\n nline = nline_max+1\n while nline > nline_max:\n nline = np.random.choice([1,2,3], p=self.p_line_nline)\n\n # get number of words:\n nword = [self.p_line_nword[2]*sstat.beta.rvs(a=self.p_line_nword[0], b=self.p_line_nword[1])\n for _ in range(nline)]\n nword = [max(1,int(np.ceil(n))) for n in nword]\n\n lines = self.get_lines(nline, nword, nchar_max, f=0.35)\n if lines is not None:\n return '\\n'.join(lines)\n else:\n return []\n\n def sample_para(self,nline_max,nchar_max):\n # get number of lines in the paragraph:\n nline = nline_max*sstat.beta.rvs(a=self.p_para_nline[0], b=self.p_para_nline[1])\n nline = max(1, int(np.ceil(nline)))\n\n # get number of words:\n nword = [self.p_para_nword[2]*sstat.beta.rvs(a=self.p_para_nword[0], b=self.p_para_nword[1])\n for _ in range(nline)]\n nword = [max(1,int(np.ceil(n))) for n in nword]\n\n lines = self.get_lines(nline, nword, nchar_max, f=0.35)\n if lines is not None:\n # center align the paragraph-text:\n if np.random.rand() < self.center_para:\n lines = self.center_align(lines)\n return '\\n'.join(lines)\n else:\n return []\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.all", "numpy.zeros_like", "numpy.any", "numpy.random.randn", "numpy.random.beta", "numpy.ceil", "numpy.argmax", "numpy.zeros", "scipy.signal.fftconvolve", "numpy.random.choice", "numpy.nonzero", "numpy.random.rand", "numpy.floor", "numpy.argsort", "numpy.array", "matplotlib.pyplot.show", "numpy.sum", "numpy.abs", "numpy.isfinite", "scipy.stats.beta.rvs", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Lockon2000/TDGPE-via-SSFM
[ "6706af1c246482b144109d42147a0eacd5bd75ee" ]
[ "TDGPEviaSSFM/animating.py" ]
[ "\"\"\"\n\"\"\"\n\nimport numpy as np\nimport scipy.signal\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as anim\nimport IPython.core.display as IPython_display\nimport pycav.display as pycav_display\n\nfrom .tools import probDensity\nfrom .tools import computeTotalProbability\nfrom .tools import computeTotalEnergy\n\n\ndef animateEvolution(x, k, psi_x_frames, psi_k_frames, V_frames, kappa, m, furtherInfo):\n from .configs import dt\n from .configs import N_t\n from .configs import skippingFactor\n from .configs import partFactor\n from .configs import secsToMsecsConversionFactor\n from .configs import savePath\n from .configs import unitSystem\n from .configs import smoothingParameters\n\n if unitSystem == \"SI\":\n from .siunits import unit_l, unit_t, unit_m, unit_v, unit_p, unit_k, unit_E\n elif unitSystem == \"natural\":\n from .natunits import unit_l, unit_t, unit_m, unit_v, unit_p, unit_k, unit_E\n\n # Parameter Calculations #\n\n dx = x[1] - x[0]\n sx = x / dx\n unit_sl = {\n \"conversionFactor\": unit_l[\"conversionFactor\"] * dx,\n \"symbol\": unit_l[\"symbol\"],\n }\n dsx = 1 # Trivial, as we scale down or up to make this always the case\n sxBoundary = sx[-1]\n sxRange = sx[-1] - sx[0]\n sxSize = sx.size\n\n dk = k[1] - k[0]\n kBoundary = k[-1]\n kRange = k[-1] - k[0]\n kSize = k.size\n\n tRange = dt * N_t\n\n # Initial Data Calculations #\n\n smoothPsi_x_frames = scipy.signal.savgol_filter(\n np.absolute(psi_x_frames), smoothingParameters[0]*2+1, smoothingParameters[1])\n probDens_psi_k_frames = probDensity(psi_k_frames)\n totalProb_psi_x = computeTotalProbability(x, psi_x_frames[0])\n totalEnergy = computeTotalEnergy(x, psi_x_frames[0], V_frames[0], kappa, m)\n\n # Plot Creation and Configuration #\n\n fig, ax = plt.subplots(3)\n ax_0_1 = ax[0].twinx()\n ax_1_1 = ax[1].twinx()\n\n # Injection of Plot Information #\n\n fig.suptitle(\"$\\\\Psi(x,t)$ and $\\\\tilde{\\\\Psi}(k,t)$\", fontsize=16)\n infoText_tl = fig.text(\n 0.01,\n 0.925,\n f\"$t$ = 0 ${unit_t['symbol']}$\\n\"\n f\"$\\\\langle\\\\Psi|\\\\Psi\\\\rangle$ = {totalProb_psi_x:>.4G}\\n\"\n f\"$E$ = {totalEnergy*unit_E['conversionFactor']:.7G} ${unit_E['symbol']}$\",\n fontsize=\"large\",\n )\n fig.text(\n 0.85,\n 0.925,\n f\"$m$ = {m*unit_m['conversionFactor']:.4G} ${unit_m['symbol']}$\\n\"\n f\"$\\\\kappa$ = {kappa:.4G}\",\n fontsize=\"large\",\n )\n fig.text(\n 0.01,\n 0.015,\n f\"$unit_{{x}}$ = {unit_sl['conversionFactor']:.5G} ${unit_sl['symbol']}$, $dx$ = {dsx:.5G}, \"\n f\"$x_{{size}}$ = {sxSize}, $x_{{boundary}}$ = {sxBoundary:.5G}, \"\n f\"$x_{{range}}$ = {sxRange:.5G} = {sxRange*unit_sl['conversionFactor']:.5G} ${unit_sl['symbol']}$\\n\"\n f\"$unit_{{k}}$ = {unit_k['conversionFactor']:.5G} ${unit_k['symbol']}$, $dk$ = {dk:.5G}, \"\n f\"$k_{{size}}$ = {kSize}, $k_{{boundary}}$ = {kBoundary:.5G}, \"\n f\"$k_{{range}}$ = {kRange:.5G} = {kRange*unit_k['conversionFactor']:.5G} ${unit_k['symbol']}$\\n\"\n f\"$unit_{{t}}$ = {unit_t['conversionFactor']:.5G} ${unit_t['symbol']}$, $dt$ = {dt:.5G}, $N_t$ = {N_t}, \"\n f\"$t_{{range}}$ = {tRange:.5G} = {tRange*unit_t['conversionFactor']:.5G} ${unit_t['symbol']}$\",\n fontsize=\"large\",\n )\n fig.text(\n 0.45,\n 0.015,\n \" | \".join(\n f\"{key}: {value}\" if type(value) == str else f\"{key}: {value:.5G}\"\n for key, value in furtherInfo.items()\n ),\n )\n\n # Data Plotting #\n\n # First Subplot\n\n sx_min, sx_max = 1.1 * sx.min(), 1.1 * sx.max()\n psi_x_min, psi_x_max = (\n -2 * np.absolute(psi_x_frames).max(),\n 2 * np.absolute(psi_x_frames).max(),\n )\n if psi_x_min == 0 and psi_x_max == 0:\n psi_x_min, psi_x_max = -1, 1\n ax[0].set(title=\"Position Space\", xlabel=\"$x$\", ylabel=\"$\\\\Psi(x,t)$\")\n ax[0].axis([sx_min, sx_max, psi_x_min, psi_x_max])\n line0_0 = ax[0].plot(\n sx, psi_x_frames[0].imag, label=\"$im(\\\\Psi_x(x,t))$\", color=\"blue\"\n )[0]\n line0_1 = ax[0].plot(\n sx, psi_x_frames[0].real, label=\"$re(\\\\Psi_x(x,t))$\", color=\"goldenrod\"\n )[0]\n line0_2 = ax[0].plot(\n sx, np.absolute(psi_x_frames[0]), label=\"$|\\\\Psi_x(x,t)|$\", color=\"green\"\n )[0]\n ax[0].legend(loc=\"upper left\")\n\n V_min, V_max = -(1 / 0.95) * np.absolute(V_frames).max(), (1 /\n 0.95) * np.absolute(V_frames).max()\n if V_min == 0 and V_max == 0:\n V_min, V_max = -1, 1\n ax_0_1.set_ylabel(\"$V(x,t)$\")\n ax_0_1.axis([sx_min, sx_max, V_min, V_max])\n line0_4 = ax_0_1.plot(\n sx, V_frames[0], label=\"$V(x,t)$\", color=\"firebrick\")[0]\n ax_0_1.legend(loc=\"upper right\")\n\n # Second Subplot\n\n ax[1].set(title=\"Position Space\", xlabel=\"$x$\", ylabel=\"$\\\\Psi(x,t)$\")\n ax[1].axis([sx_min, sx_max, psi_x_min, psi_x_max])\n line1_0 = ax[1].plot(\n sx, np.absolute(smoothPsi_x_frames[0]), label=\"Smooth $|\\\\Psi_x(x,t)|$\", color=\"green\"\n )[0]\n ax[1].legend(loc=\"upper left\")\n\n ax_1_1.set_ylabel(\"$V(x,t)$\")\n ax_1_1.axis([sx_min, sx_max, V_min, V_max])\n line1_1 = ax_1_1.plot(\n sx, V_frames[0], label=\"$V(x,t)$\", color=\"firebrick\")[0]\n ax_1_1.legend(loc=\"upper right\")\n\n # Third Subplot\n\n k_min, k_max = 1.1 * k.min(), 1.1 * k.max()\n probDens_k_min, probDens_k_max = 0, 1.25 * probDens_psi_k_frames.max()\n if probDens_k_max == 0:\n probDens_k_max = 1\n ax[2].set(title=\"k Space\", xlabel=\"$k$\",\n ylabel=\"$|\\\\tilde{\\\\Psi}(k,t)|^2$\")\n ax[2].axis([k_min, k_max, probDens_k_min, probDens_k_max])\n line2_0 = ax[2].plot(\n k, probDens_psi_k_frames[0], label=\"$|\\\\tilde{\\\\Psi}(k,t)|^2$\"\n )[0]\n ax[2].legend(loc=\"best\")\n\n def nextframe(n_t):\n totalProb_psi_x = computeTotalProbability(\n x, psi_x_frames[skippingFactor * n_t])\n totalEnergy = computeTotalEnergy(\n x,\n psi_x_frames[skippingFactor * n_t],\n V_frames[skippingFactor * n_t],\n kappa,\n m,\n )\n infoText_tl.set_text(\n f\"$t$ = {dt*n_t*skippingFactor*unit_t['conversionFactor']:.4G} ${unit_t['symbol']}$\\n\"\n f\"$\\\\langle\\\\Psi|\\\\Psi\\\\rangle$ = {totalProb_psi_x:>.4G}\\n\"\n f\"$E$ = {totalEnergy*unit_E['conversionFactor']:.7G} ${unit_E['symbol']}$\",\n )\n\n line0_0.set_data(sx, psi_x_frames[skippingFactor * n_t].imag)\n line0_1.set_data(sx, psi_x_frames[skippingFactor * n_t].real)\n line0_2.set_data(sx, np.absolute(psi_x_frames[skippingFactor * n_t]))\n line0_4.set_data(sx, V_frames[skippingFactor * n_t])\n\n line1_0.set_data(sx, smoothPsi_x_frames[skippingFactor * n_t])\n line1_1.set_data(sx, V_frames[skippingFactor * n_t])\n\n line2_0.set_data(k, np.absolute(\n psi_k_frames[skippingFactor * n_t]) ** 2)\n\n animation = anim.FuncAnimation(\n fig,\n nextframe,\n interval=dt * secsToMsecsConversionFactor * skippingFactor,\n frames=int((N_t * partFactor) // skippingFactor),\n repeat=False,\n )\n displayable_animation = pycav_display.create_animation(\n animation, fname=eval(f'f\"{savePath}\"'),\n )\n\n IPython_display.display(\n pycav_display.display_animation(displayable_animation)\n ) if displayable_animation is not None else None\n" ]
[ [ "numpy.absolute", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fuglede/scipy
[ "59cd790c210a2f5c200e0ac9a83e1160d38f4563" ]
[ "scipy/special/tests/test_basic.py" ]
[ "# this program corresponds to special.py\n\n### Means test is not done yet\n# E Means test is giving error (E)\n# F Means test is failing (F)\n# EF Means test is giving error and Failing\n#! Means test is segfaulting\n# 8 Means test runs forever\n\n### test_besselpoly\n### test_mathieu_a\n### test_mathieu_even_coef\n### test_mathieu_odd_coef\n### test_modfresnelp\n### test_modfresnelm\n# test_pbdv_seq\n### test_pbvv_seq\n### test_sph_harm\n# test_sph_in\n# test_sph_jn\n# test_sph_kn\n\nfrom __future__ import division, print_function, absolute_import\n\nimport itertools\nimport warnings\n\nimport numpy as np\nfrom numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp,\n log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_)\n\nfrom numpy.testing import (assert_equal, assert_almost_equal,\n assert_array_equal, assert_array_almost_equal, assert_approx_equal,\n assert_, dec, TestCase, run_module_suite, assert_allclose,\n assert_raises, assert_array_almost_equal_nulp)\n\nfrom scipy import special\nimport scipy.special._ufuncs as cephes\nfrom scipy.special import ellipk\n\nfrom scipy.special._testutils import assert_tol_equal, with_special_errors, \\\n assert_func_equal\n\n\nclass TestCephes(TestCase):\n def test_airy(self):\n cephes.airy(0)\n\n def test_airye(self):\n cephes.airye(0)\n\n def test_binom(self):\n n = np.array([0.264, 4, 5.2, 17])\n k = np.array([2, 0.4, 7, 3.3])\n nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])\n ).reshape(2, -1).T\n rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389,\n -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846],\n [10.92, 2.22993515861399, -0.00585728, 10.468891352063146],\n [136, 3.5252179590758828, 19448, 1024.5526916174495]])\n assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13)\n\n # Test branches in implementation\n np.random.seed(1234)\n n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500]\n k = np.arange(0, 102)\n nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])\n ).reshape(2, -1).T\n\n assert_func_equal(cephes.binom,\n cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),\n nk,\n atol=1e-10, rtol=1e-10)\n\n def test_binom_2(self):\n # Test branches in implementation\n np.random.seed(1234)\n n = np.r_[np.logspace(1, 300, 20)]\n k = np.arange(0, 102)\n nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])\n ).reshape(2, -1).T\n\n assert_func_equal(cephes.binom,\n cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),\n nk,\n atol=1e-10, rtol=1e-10)\n\n def test_binom_exact(self):\n @np.vectorize\n def binom_int(n, k):\n n = int(n)\n k = int(k)\n num = int(1)\n den = int(1)\n for i in range(1, k+1):\n num *= i + n - k\n den *= i\n return float(num/den)\n\n np.random.seed(1234)\n n = np.arange(1, 15)\n k = np.arange(0, 15)\n nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])\n ).reshape(2, -1).T\n nk = nk[nk[:,0] >= nk[:,1]]\n assert_func_equal(cephes.binom,\n binom_int(nk[:,0], nk[:,1]),\n nk,\n atol=0, rtol=0)\n\n def test_bdtr(self):\n assert_equal(cephes.bdtr(1,1,0.5),1.0)\n\n def test_bdtri(self):\n assert_equal(cephes.bdtri(1,3,0.5),0.5)\n\n def test_bdtrc(self):\n assert_equal(cephes.bdtrc(1,3,0.5),0.5)\n\n def test_bdtrin(self):\n assert_equal(cephes.bdtrin(1,0,1),5.0)\n\n def test_bdtrik(self):\n cephes.bdtrik(1,3,0.5)\n\n def test_bei(self):\n assert_equal(cephes.bei(0),0.0)\n\n def test_beip(self):\n assert_equal(cephes.beip(0),0.0)\n\n def test_ber(self):\n assert_equal(cephes.ber(0),1.0)\n\n def test_berp(self):\n assert_equal(cephes.berp(0),0.0)\n\n def test_besselpoly(self):\n assert_equal(cephes.besselpoly(0,0,0),1.0)\n\n def test_beta(self):\n assert_equal(cephes.beta(1,1),1.0)\n assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200))\n assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497,\n rtol=1e-13, atol=0)\n\n def test_betainc(self):\n assert_equal(cephes.betainc(1,1,1),1.0)\n assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648)\n\n def test_betaln(self):\n assert_equal(cephes.betaln(1,1),0.0)\n assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200))\n assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447,\n rtol=1e-14, atol=0)\n\n def test_betaincinv(self):\n assert_equal(cephes.betaincinv(1,1,1),1.0)\n assert_allclose(cephes.betaincinv(0.0342, 171, 0.25),\n 8.4231316935498957e-21, rtol=3e-12, atol=0)\n\n def test_beta_inf(self):\n assert_(np.isinf(special.beta(-1, 2)))\n\n def test_btdtr(self):\n assert_equal(cephes.btdtr(1,1,1),1.0)\n\n def test_btdtri(self):\n assert_equal(cephes.btdtri(1,1,1),1.0)\n\n def test_btdtria(self):\n assert_equal(cephes.btdtria(1,1,1),5.0)\n\n def test_btdtrib(self):\n assert_equal(cephes.btdtrib(1,1,1),5.0)\n\n def test_cbrt(self):\n assert_approx_equal(cephes.cbrt(1),1.0)\n\n def test_chdtr(self):\n assert_equal(cephes.chdtr(1,0),0.0)\n\n def test_chdtrc(self):\n assert_equal(cephes.chdtrc(1,0),1.0)\n\n def test_chdtri(self):\n assert_equal(cephes.chdtri(1,1),0.0)\n\n def test_chdtriv(self):\n assert_equal(cephes.chdtriv(0,0),5.0)\n\n def test_chndtr(self):\n assert_equal(cephes.chndtr(0,1,0),0.0)\n p = cephes.chndtr(np.linspace(20, 25, 5), 2, 1.07458615e+02)\n assert_allclose(p, [1.21805009e-09, 2.81979982e-09, 6.25652736e-09,\n 1.33520017e-08, 2.74909967e-08],\n rtol=1e-6, atol=0)\n assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0)\n assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0)\n assert_(np.isnan(cephes.chndtr(np.nan, 1, 2)))\n assert_(np.isnan(cephes.chndtr(5, np.nan, 2)))\n assert_(np.isnan(cephes.chndtr(5, 1, np.nan)))\n\n def test_chndtridf(self):\n assert_equal(cephes.chndtridf(0,0,1),5.0)\n\n def test_chndtrinc(self):\n assert_equal(cephes.chndtrinc(0,1,0),5.0)\n\n def test_chndtrix(self):\n assert_equal(cephes.chndtrix(0,1,0),0.0)\n\n def test_cosdg(self):\n assert_equal(cephes.cosdg(0),1.0)\n\n def test_cosm1(self):\n assert_equal(cephes.cosm1(0),0.0)\n\n def test_cotdg(self):\n assert_almost_equal(cephes.cotdg(45),1.0)\n\n def test_dawsn(self):\n assert_equal(cephes.dawsn(0),0.0)\n assert_allclose(cephes.dawsn(1.23), 0.50053727749081767)\n\n def test_diric(self):\n # Test behavior near multiples of 2pi. Regression test for issue\n # described in gh-4001.\n n_odd = [1, 5, 25]\n x = np.array(2*np.pi + 5e-5).astype(np.float32)\n assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7)\n x = np.array(2*np.pi + 1e-9).astype(np.float64)\n assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)\n x = np.array(2*np.pi + 1e-15).astype(np.float64)\n assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)\n if hasattr(np, 'float128'):\n # No float128 available in 32-bit numpy\n x = np.array(2*np.pi + 1e-12).astype(np.float128)\n assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19)\n\n n_even = [2, 4, 24]\n x = np.array(2*np.pi + 1e-9).astype(np.float64)\n assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15)\n\n # Test at some values not near a multiple of pi\n x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi)\n octave_result = [0.872677996249965, 0.539344662916632,\n 0.127322003750035, -0.206011329583298]\n assert_almost_equal(special.diric(x, 3), octave_result, decimal=15)\n\n def test_diric_broadcasting(self):\n x = np.arange(5)\n n = np.array([1, 3, 7])\n assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size))\n\n def test_ellipe(self):\n assert_equal(cephes.ellipe(1),1.0)\n\n def test_ellipeinc(self):\n assert_equal(cephes.ellipeinc(0,1),0.0)\n\n def test_ellipj(self):\n cephes.ellipj(0,1)\n\n def test_ellipk(self):\n assert_allclose(ellipk(0), pi/2)\n\n def test_ellipkinc(self):\n assert_equal(cephes.ellipkinc(0,0),0.0)\n\n def test_erf(self):\n assert_equal(cephes.erf(0),0.0)\n\n def test_erfc(self):\n assert_equal(cephes.erfc(0),1.0)\n\n def test_exp1(self):\n cephes.exp1(1)\n\n def test_expi(self):\n cephes.expi(1)\n\n def test_expn(self):\n cephes.expn(1,1)\n\n def test_exp1_reg(self):\n # Regression for #834\n a = cephes.exp1(-complex(19.9999990))\n b = cephes.exp1(-complex(19.9999991))\n assert_array_almost_equal(a.imag, b.imag)\n\n def test_exp10(self):\n assert_approx_equal(cephes.exp10(2),100.0)\n\n def test_exp2(self):\n assert_equal(cephes.exp2(2),4.0)\n\n def test_expm1(self):\n assert_equal(cephes.expm1(0),0.0)\n\n def test_fdtr(self):\n assert_equal(cephes.fdtr(1,1,0),0.0)\n\n def test_fdtrc(self):\n assert_equal(cephes.fdtrc(1,1,0),1.0)\n\n def test_fdtri(self):\n # cephes.fdtri(1,1,0.5) #BUG: gives NaN, should be 1\n assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]),\n array([0.9937365, 1.00630298]), rtol=1e-6)\n\n def test_fdtridfd(self):\n assert_equal(cephes.fdtridfd(1,0,0),5.0)\n\n def test_fresnel(self):\n assert_equal(cephes.fresnel(0),(0.0,0.0))\n\n def test_gamma(self):\n assert_equal(cephes.gamma(5),24.0)\n\n def test_gammainc(self):\n assert_equal(cephes.gammainc(5,0),0.0)\n\n def test_gammaincc(self):\n assert_equal(cephes.gammaincc(5,0),1.0)\n\n def test_gammainccinv(self):\n assert_equal(cephes.gammainccinv(5,1),0.0)\n\n def test_gammaln(self):\n cephes.gammaln(10)\n\n def test_gammasgn(self):\n vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64)\n assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals)))\n\n def test_gdtr(self):\n assert_equal(cephes.gdtr(1,1,0),0.0)\n\n def test_gdtr_inf(self):\n assert_equal(cephes.gdtr(1,1,np.inf),1.0)\n\n def test_gdtrc(self):\n assert_equal(cephes.gdtrc(1,1,0),1.0)\n\n def test_gdtria(self):\n assert_equal(cephes.gdtria(0,1,1),0.0)\n\n def test_gdtrib(self):\n cephes.gdtrib(1,0,1)\n # assert_equal(cephes.gdtrib(1,0,1),5.0)\n\n def test_gdtrix(self):\n cephes.gdtrix(1,1,.1)\n\n def test_hankel1(self):\n cephes.hankel1(1,1)\n\n def test_hankel1e(self):\n cephes.hankel1e(1,1)\n\n def test_hankel2(self):\n cephes.hankel2(1,1)\n\n def test_hankel2e(self):\n cephes.hankel2e(1,1)\n\n def test_hyp1f1(self):\n assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0))\n assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095)\n cephes.hyp1f1(1,1,1)\n\n def test_hyp1f2(self):\n cephes.hyp1f2(1,1,1,1)\n\n def test_hyp2f0(self):\n cephes.hyp2f0(1,1,1,1)\n\n def test_hyp2f1(self):\n assert_equal(cephes.hyp2f1(1,1,1,0),1.0)\n\n def test_hyp3f0(self):\n assert_equal(cephes.hyp3f0(1,1,1,0),(1.0,0.0))\n\n def test_hyperu(self):\n assert_equal(cephes.hyperu(0,1,1),1.0)\n\n def test_i0(self):\n assert_equal(cephes.i0(0),1.0)\n\n def test_i0e(self):\n assert_equal(cephes.i0e(0),1.0)\n\n def test_i1(self):\n assert_equal(cephes.i1(0),0.0)\n\n def test_i1e(self):\n assert_equal(cephes.i1e(0),0.0)\n\n def test_it2i0k0(self):\n cephes.it2i0k0(1)\n\n def test_it2j0y0(self):\n cephes.it2j0y0(1)\n\n def test_it2struve0(self):\n cephes.it2struve0(1)\n\n def test_itairy(self):\n cephes.itairy(1)\n\n def test_iti0k0(self):\n assert_equal(cephes.iti0k0(0),(0.0,0.0))\n\n def test_itj0y0(self):\n assert_equal(cephes.itj0y0(0),(0.0,0.0))\n\n def test_itmodstruve0(self):\n assert_equal(cephes.itmodstruve0(0),0.0)\n\n def test_itstruve0(self):\n assert_equal(cephes.itstruve0(0),0.0)\n\n def test_iv(self):\n assert_equal(cephes.iv(1,0),0.0)\n\n def _check_ive(self):\n assert_equal(cephes.ive(1,0),0.0)\n\n def test_j0(self):\n assert_equal(cephes.j0(0),1.0)\n\n def test_j1(self):\n assert_equal(cephes.j1(0),0.0)\n\n def test_jn(self):\n assert_equal(cephes.jn(0,0),1.0)\n\n def test_jv(self):\n assert_equal(cephes.jv(0,0),1.0)\n\n def _check_jve(self):\n assert_equal(cephes.jve(0,0),1.0)\n\n def test_k0(self):\n cephes.k0(2)\n\n def test_k0e(self):\n cephes.k0e(2)\n\n def test_k1(self):\n cephes.k1(2)\n\n def test_k1e(self):\n cephes.k1e(2)\n\n def test_kei(self):\n cephes.kei(2)\n\n def test_keip(self):\n assert_equal(cephes.keip(0),0.0)\n\n def test_ker(self):\n cephes.ker(2)\n\n def test_kerp(self):\n cephes.kerp(2)\n\n def _check_kelvin(self):\n cephes.kelvin(2)\n\n def test_kn(self):\n cephes.kn(1,1)\n\n def test_kolmogi(self):\n assert_equal(cephes.kolmogi(1),0.0)\n assert_(np.isnan(cephes.kolmogi(np.nan)))\n\n def test_kolmogorov(self):\n assert_equal(cephes.kolmogorov(0),1.0)\n\n def _check_kv(self):\n cephes.kv(1,1)\n\n def _check_kve(self):\n cephes.kve(1,1)\n\n def test_log1p(self):\n assert_equal(cephes.log1p(0),0.0)\n\n def test_lpmv(self):\n assert_equal(cephes.lpmv(0,0,1),1.0)\n\n def test_mathieu_a(self):\n assert_equal(cephes.mathieu_a(1,0),1.0)\n\n def test_mathieu_b(self):\n assert_equal(cephes.mathieu_b(1,0),1.0)\n\n def test_mathieu_cem(self):\n assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0))\n\n # Test AMS 20.2.27\n @np.vectorize\n def ce_smallq(m, q, z):\n z *= np.pi/180\n if m == 0:\n return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2)\n elif m == 1:\n return cos(z) - q/8 * cos(3*z) # + O(q^2)\n elif m == 2:\n return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2)\n else:\n return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2)\n m = np.arange(0, 100)\n q = np.r_[0, np.logspace(-30, -9, 10)]\n assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0],\n ce_smallq(m[:,None], q[None,:], 0.123),\n rtol=1e-14, atol=0)\n\n def test_mathieu_sem(self):\n assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0))\n\n # Test AMS 20.2.27\n @np.vectorize\n def se_smallq(m, q, z):\n z *= np.pi/180\n if m == 1:\n return sin(z) - q/8 * sin(3*z) # + O(q^2)\n elif m == 2:\n return sin(2*z) - q*sin(4*z)/12 # + O(q^2)\n else:\n return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2)\n m = np.arange(1, 100)\n q = np.r_[0, np.logspace(-30, -9, 10)]\n assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0],\n se_smallq(m[:,None], q[None,:], 0.123),\n rtol=1e-14, atol=0)\n\n def test_mathieu_modcem1(self):\n assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0))\n\n def test_mathieu_modcem2(self):\n cephes.mathieu_modcem2(1,1,1)\n\n # Test reflection relation AMS 20.6.19\n m = np.arange(0, 4)[:,None,None]\n q = np.r_[np.logspace(-2, 2, 10)][None,:,None]\n z = np.linspace(0, 1, 7)[None,None,:]\n\n y1 = cephes.mathieu_modcem2(m, q, -z)[0]\n\n fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0]\n y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0]\n\n assert_allclose(y1, y2, rtol=1e-10)\n\n def test_mathieu_modsem1(self):\n assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0))\n\n def test_mathieu_modsem2(self):\n cephes.mathieu_modsem2(1,1,1)\n\n # Test reflection relation AMS 20.6.20\n m = np.arange(1, 4)[:,None,None]\n q = np.r_[np.logspace(-2, 2, 10)][None,:,None]\n z = np.linspace(0, 1, 7)[None,None,:]\n\n y1 = cephes.mathieu_modsem2(m, q, -z)[0]\n fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1]\n y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0]\n assert_allclose(y1, y2, rtol=1e-10)\n\n def test_mathieu_overflow(self):\n # Check that these return NaNs instead of causing a SEGV\n assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan))\n assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan))\n\n def test_mathieu_ticket_1847(self):\n # Regression test --- this call had some out-of-bounds access\n # and could return nan occasionally\n for k in range(60):\n v = cephes.mathieu_modsem2(2, 100, -1)\n # Values from ACM TOMS 804 (derivate by numerical differentiation)\n assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10)\n assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4)\n\n def test_modfresnelm(self):\n cephes.modfresnelm(0)\n\n def test_modfresnelp(self):\n cephes.modfresnelp(0)\n\n def _check_modstruve(self):\n assert_equal(cephes.modstruve(1,0),0.0)\n\n def test_nbdtr(self):\n assert_equal(cephes.nbdtr(1,1,1),1.0)\n\n def test_nbdtrc(self):\n assert_equal(cephes.nbdtrc(1,1,1),0.0)\n\n def test_nbdtri(self):\n assert_equal(cephes.nbdtri(1,1,1),1.0)\n\n def __check_nbdtrik(self):\n cephes.nbdtrik(1,.4,.5)\n\n def test_nbdtrin(self):\n assert_equal(cephes.nbdtrin(1,0,0),5.0)\n\n def test_ncfdtr(self):\n assert_equal(cephes.ncfdtr(1,1,1,0),0.0)\n\n def test_ncfdtri(self):\n assert_equal(cephes.ncfdtri(1,1,1,0),0.0)\n\n def test_ncfdtridfd(self):\n cephes.ncfdtridfd(1,0.5,0,1)\n\n def __check_ncfdtridfn(self):\n cephes.ncfdtridfn(1,0.5,0,1)\n\n def __check_ncfdtrinc(self):\n cephes.ncfdtrinc(1,0.5,0,1)\n\n def test_nctdtr(self):\n assert_equal(cephes.nctdtr(1,0,0),0.5)\n assert_equal(cephes.nctdtr(9, 65536, 45), 0.0)\n\n assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5)\n assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.)))\n assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.)\n\n assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.)))\n assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.)))\n assert_(np.isnan(cephes.nctdtr(2., 1., np.nan)))\n\n def __check_nctdtridf(self):\n cephes.nctdtridf(1,0.5,0)\n\n def test_nctdtrinc(self):\n cephes.nctdtrinc(1,0,0)\n\n def test_nctdtrit(self):\n cephes.nctdtrit(.1,0.2,.5)\n\n def test_ndtr(self):\n assert_equal(cephes.ndtr(0), 0.5)\n assert_almost_equal(cephes.ndtr(1), 0.84134474606)\n\n def test_ndtri(self):\n assert_equal(cephes.ndtri(0.5),0.0)\n\n def test_nrdtrimn(self):\n assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0)\n\n def test_nrdtrisd(self):\n assert_tol_equal(cephes.nrdtrisd(0.5,0.5,0.5), 0.0,\n atol=0, rtol=0)\n\n def test_obl_ang1(self):\n cephes.obl_ang1(1,1,1,0)\n\n def test_obl_ang1_cv(self):\n result = cephes.obl_ang1_cv(1,1,1,1,0)\n assert_almost_equal(result[0],1.0)\n assert_almost_equal(result[1],0.0)\n\n def _check_obl_cv(self):\n assert_equal(cephes.obl_cv(1,1,0),2.0)\n\n def test_obl_rad1(self):\n cephes.obl_rad1(1,1,1,0)\n\n def test_obl_rad1_cv(self):\n cephes.obl_rad1_cv(1,1,1,1,0)\n\n def test_obl_rad2(self):\n cephes.obl_rad2(1,1,1,0)\n\n def test_obl_rad2_cv(self):\n cephes.obl_rad2_cv(1,1,1,1,0)\n\n def test_pbdv(self):\n assert_equal(cephes.pbdv(1,0),(0.0,1.0))\n\n def test_pbvv(self):\n cephes.pbvv(1,0)\n\n def test_pbwa(self):\n cephes.pbwa(1,0)\n\n def test_pdtr(self):\n val = cephes.pdtr(0, 1)\n assert_almost_equal(val, np.exp(-1))\n # Edge case: m = 0.\n val = cephes.pdtr([0, 1, 2], 0.0)\n assert_array_equal(val, [1, 1, 1])\n\n def test_pdtrc(self):\n val = cephes.pdtrc(0, 1)\n assert_almost_equal(val, 1 - np.exp(-1))\n # Edge case: m = 0.\n val = cephes.pdtrc([0, 1, 2], 0.0)\n assert_array_equal(val, [0, 0, 0])\n\n def test_pdtri(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n cephes.pdtri(0.5,0.5)\n\n def test_pdtrik(self):\n k = cephes.pdtrik(0.5, 1)\n assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5)\n # Edge case: m = 0 or very small.\n k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6])\n assert_array_equal(k, np.zeros((3, 3)))\n\n def test_pro_ang1(self):\n cephes.pro_ang1(1,1,1,0)\n\n def test_pro_ang1_cv(self):\n assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0),\n array((1.0,0.0)))\n\n def _check_pro_cv(self):\n assert_equal(cephes.pro_cv(1,1,0),2.0)\n\n def test_pro_rad1(self):\n cephes.pro_rad1(1,1,1,0.1)\n\n def test_pro_rad1_cv(self):\n cephes.pro_rad1_cv(1,1,1,1,0)\n\n def test_pro_rad2(self):\n cephes.pro_rad2(1,1,1,0)\n\n def test_pro_rad2_cv(self):\n cephes.pro_rad2_cv(1,1,1,1,0)\n\n def test_psi(self):\n cephes.psi(1)\n\n def test_radian(self):\n assert_equal(cephes.radian(0,0,0),0)\n\n def test_rgamma(self):\n assert_equal(cephes.rgamma(1),1.0)\n\n def test_round(self):\n assert_equal(cephes.round(3.4),3.0)\n assert_equal(cephes.round(-3.4),-3.0)\n assert_equal(cephes.round(3.6),4.0)\n assert_equal(cephes.round(-3.6),-4.0)\n assert_equal(cephes.round(3.5),4.0)\n assert_equal(cephes.round(-3.5),-4.0)\n\n def test_shichi(self):\n cephes.shichi(1)\n\n def test_sici(self):\n cephes.sici(1)\n\n s, c = cephes.sici(np.inf)\n assert_almost_equal(s, np.pi * 0.5)\n assert_almost_equal(c, 0)\n\n s, c = cephes.sici(-np.inf)\n assert_almost_equal(s, -np.pi * 0.5)\n assert_(np.isnan(c), \"cosine integral(-inf) is not nan\")\n\n def test_sindg(self):\n assert_equal(cephes.sindg(90),1.0)\n\n def test_smirnov(self):\n assert_equal(cephes.smirnov(1,.1),0.9)\n assert_(np.isnan(cephes.smirnov(1,np.nan)))\n\n def test_smirnovi(self):\n assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4)\n assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6)\n assert_(np.isnan(cephes.smirnovi(1,np.nan)))\n\n def test_spence(self):\n assert_equal(cephes.spence(1),0.0)\n\n def test_stdtr(self):\n assert_equal(cephes.stdtr(1,0),0.5)\n assert_almost_equal(cephes.stdtr(1,1), 0.75)\n assert_almost_equal(cephes.stdtr(1,2), 0.852416382349)\n\n def test_stdtridf(self):\n cephes.stdtridf(0.7,1)\n\n def test_stdtrit(self):\n cephes.stdtrit(1,0.7)\n\n def test_struve(self):\n assert_equal(cephes.struve(0,0),0.0)\n\n def test_tandg(self):\n assert_equal(cephes.tandg(45),1.0)\n\n def test_tklmbda(self):\n assert_almost_equal(cephes.tklmbda(1,1),1.0)\n\n def test_y0(self):\n cephes.y0(1)\n\n def test_y1(self):\n cephes.y1(1)\n\n def test_yn(self):\n cephes.yn(1,1)\n\n def test_yv(self):\n cephes.yv(1,1)\n\n def _check_yve(self):\n cephes.yve(1,1)\n\n def test_zeta(self):\n cephes.zeta(2,2)\n\n def test_zetac(self):\n assert_equal(cephes.zetac(0),-1.5)\n\n def test_wofz(self):\n z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.),\n complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.),\n complex(-0.0000000234545,1.1234), complex(-3.,5.1),\n complex(-53,30.1), complex(0.0,0.12345),\n complex(11,1), complex(-22,-2), complex(9,-28),\n complex(21,-33), complex(1e5,1e5), complex(1e14,1e14)\n ]\n w = [\n complex(-3.78270245518980507452677445620103199303131110e-7,\n 0.000903861276433172057331093754199933411710053155),\n complex(0.1764906227004816847297495349730234591778719532788,\n -0.02146550539468457616788719893991501311573031095617),\n complex(0.2410250715772692146133539023007113781272362309451,\n 0.06087579663428089745895459735240964093522265589350),\n complex(0.30474420525691259245713884106959496013413834051768,\n -0.20821893820283162728743734725471561394145872072738),\n complex(7.317131068972378096865595229600561710140617977e34,\n 8.321873499714402777186848353320412813066170427e34),\n complex(0.0615698507236323685519612934241429530190806818395,\n -0.00676005783716575013073036218018565206070072304635),\n complex(0.3960793007699874918961319170187598400134746631,\n -5.593152259116644920546186222529802777409274656e-9),\n complex(0.08217199226739447943295069917990417630675021771804,\n -0.04701291087643609891018366143118110965272615832184),\n complex(0.00457246000350281640952328010227885008541748668738,\n -0.00804900791411691821818731763401840373998654987934),\n complex(0.8746342859608052666092782112565360755791467973338452,\n 0.),\n complex(0.00468190164965444174367477874864366058339647648741,\n 0.0510735563901306197993676329845149741675029197050),\n complex(-0.0023193175200187620902125853834909543869428763219,\n -0.025460054739731556004902057663500272721780776336),\n complex(9.11463368405637174660562096516414499772662584e304,\n 3.97101807145263333769664875189354358563218932e305),\n complex(-4.4927207857715598976165541011143706155432296e281,\n -2.8019591213423077494444700357168707775769028e281),\n complex(2.820947917809305132678577516325951485807107151e-6,\n 2.820947917668257736791638444590253942253354058e-6),\n complex(2.82094791773878143474039725787438662716372268e-15,\n 2.82094791773878143474039725773333923127678361e-15)\n ]\n assert_func_equal(cephes.wofz, w, z, rtol=1e-13)\n\n\nclass TestAiry(TestCase):\n def test_airy(self):\n # This tests the airy function to ensure 8 place accuracy in computation\n\n x = special.airy(.99)\n assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8)\n x = special.airy(.41)\n assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8)\n x = special.airy(-.36)\n assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8)\n\n def test_airye(self):\n a = special.airye(0.01)\n b = special.airy(0.01)\n b1 = [None]*4\n for n in range(2):\n b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01))\n for n in range(2,4):\n b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01))))\n assert_array_almost_equal(a,b1,6)\n\n def test_bi_zeros(self):\n bi = special.bi_zeros(2)\n bia = (array([-1.17371322, -3.2710930]),\n array([-2.29443968, -4.07315509]),\n array([-0.45494438, 0.39652284]),\n array([0.60195789, -0.76031014]))\n assert_array_almost_equal(bi,bia,4)\n\n bi = special.bi_zeros(5)\n assert_array_almost_equal(bi[0],array([-1.173713222709127,\n -3.271093302836352,\n -4.830737841662016,\n -6.169852128310251,\n -7.376762079367764]),11)\n\n assert_array_almost_equal(bi[1],array([-2.294439682614122,\n -4.073155089071828,\n -5.512395729663599,\n -6.781294445990305,\n -7.940178689168587]),10)\n\n assert_array_almost_equal(bi[2],array([-0.454944383639657,\n 0.396522836094465,\n -0.367969161486959,\n 0.349499116831805,\n -0.336026240133662]),11)\n\n assert_array_almost_equal(bi[3],array([0.601957887976239,\n -0.760310141492801,\n 0.836991012619261,\n -0.88947990142654,\n 0.929983638568022]),10)\n\n def test_ai_zeros(self):\n ai = special.ai_zeros(1)\n assert_array_almost_equal(ai,(array([-2.33810741]),\n array([-1.01879297]),\n array([0.5357]),\n array([0.7012])),4)\n\n def test_ai_zeros_big(self):\n z, zp, ai_zpx, aip_zx = special.ai_zeros(50000)\n ai_z, aip_z, _, _ = special.airy(z)\n ai_zp, aip_zp, _, _ = special.airy(zp)\n\n ai_envelope = 1/abs(z)**(1./4)\n aip_envelope = abs(zp)**(1./4)\n\n # Check values\n assert_allclose(ai_zpx, ai_zp, rtol=1e-10)\n assert_allclose(aip_zx, aip_z, rtol=1e-10)\n\n # Check they are zeros\n assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0)\n assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0)\n\n # Check first zeros, DLMF 9.9.1\n assert_allclose(z[:6],\n [-2.3381074105, -4.0879494441, -5.5205598281,\n -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10)\n assert_allclose(zp[:6],\n [-1.0187929716, -3.2481975822, -4.8200992112,\n -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10)\n\n def test_bi_zeros_big(self):\n z, zp, bi_zpx, bip_zx = special.bi_zeros(50000)\n _, _, bi_z, bip_z = special.airy(z)\n _, _, bi_zp, bip_zp = special.airy(zp)\n\n bi_envelope = 1/abs(z)**(1./4)\n bip_envelope = abs(zp)**(1./4)\n\n # Check values\n assert_allclose(bi_zpx, bi_zp, rtol=1e-10)\n assert_allclose(bip_zx, bip_z, rtol=1e-10)\n\n # Check they are zeros\n assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0)\n assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0)\n\n # Check first zeros, DLMF 9.9.2\n assert_allclose(z[:6],\n [-1.1737132227, -3.2710933028, -4.8307378417,\n -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10)\n assert_allclose(zp[:6],\n [-2.2944396826, -4.0731550891, -5.5123957297,\n -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10)\n\n\nclass TestAssocLaguerre(TestCase):\n def test_assoc_laguerre(self):\n a1 = special.genlaguerre(11,1)\n a2 = special.assoc_laguerre(.2,11,1)\n assert_array_almost_equal(a2,a1(.2),8)\n a2 = special.assoc_laguerre(1,11,1)\n assert_array_almost_equal(a2,a1(1),8)\n\n\nclass TestBesselpoly(TestCase):\n def test_besselpoly(self):\n pass\n\n\nclass TestKelvin(TestCase):\n def test_bei(self):\n mbei = special.bei(2)\n assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact\n\n def test_beip(self):\n mbeip = special.beip(2)\n assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact\n\n def test_ber(self):\n mber = special.ber(2)\n assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact\n\n def test_berp(self):\n mberp = special.berp(2)\n assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact\n\n def test_bei_zeros(self):\n # Abramowitz & Stegun, Table 9.12\n bi = special.bei_zeros(5)\n assert_array_almost_equal(bi,array([5.02622,\n 9.45541,\n 13.89349,\n 18.33398,\n 22.77544]),4)\n\n def test_beip_zeros(self):\n bip = special.beip_zeros(5)\n assert_array_almost_equal(bip,array([3.772673304934953,\n 8.280987849760042,\n 12.742147523633703,\n 17.193431752512542,\n 21.641143941167325]),8)\n\n def test_ber_zeros(self):\n ber = special.ber_zeros(5)\n assert_array_almost_equal(ber,array([2.84892,\n 7.23883,\n 11.67396,\n 16.11356,\n 20.55463]),4)\n\n def test_berp_zeros(self):\n brp = special.berp_zeros(5)\n assert_array_almost_equal(brp,array([6.03871,\n 10.51364,\n 14.96844,\n 19.41758,\n 23.86430]),4)\n\n def test_kelvin(self):\n mkelv = special.kelvin(2)\n assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j,\n special.ker(2) + special.kei(2)*1j,\n special.berp(2) + special.beip(2)*1j,\n special.kerp(2) + special.keip(2)*1j),8)\n\n def test_kei(self):\n mkei = special.kei(2)\n assert_almost_equal(mkei,-0.20240006776470432,5)\n\n def test_keip(self):\n mkeip = special.keip(2)\n assert_almost_equal(mkeip,0.21980790991960536,5)\n\n def test_ker(self):\n mker = special.ker(2)\n assert_almost_equal(mker,-0.041664513991509472,5)\n\n def test_kerp(self):\n mkerp = special.kerp(2)\n assert_almost_equal(mkerp,-0.10660096588105264,5)\n\n def test_kei_zeros(self):\n kei = special.kei_zeros(5)\n assert_array_almost_equal(kei,array([3.91467,\n 8.34422,\n 12.78256,\n 17.22314,\n 21.66464]),4)\n\n def test_keip_zeros(self):\n keip = special.keip_zeros(5)\n assert_array_almost_equal(keip,array([4.93181,\n 9.40405,\n 13.85827,\n 18.30717,\n 22.75379]),4)\n\n # numbers come from 9.9 of A&S pg. 381\n def test_kelvin_zeros(self):\n tmp = special.kelvin_zeros(5)\n berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp\n assert_array_almost_equal(berz,array([2.84892,\n 7.23883,\n 11.67396,\n 16.11356,\n 20.55463]),4)\n assert_array_almost_equal(beiz,array([5.02622,\n 9.45541,\n 13.89349,\n 18.33398,\n 22.77544]),4)\n assert_array_almost_equal(kerz,array([1.71854,\n 6.12728,\n 10.56294,\n 15.00269,\n 19.44382]),4)\n assert_array_almost_equal(keiz,array([3.91467,\n 8.34422,\n 12.78256,\n 17.22314,\n 21.66464]),4)\n assert_array_almost_equal(berpz,array([6.03871,\n 10.51364,\n 14.96844,\n 19.41758,\n 23.86430]),4)\n assert_array_almost_equal(beipz,array([3.77267,\n # table from 1927 had 3.77320\n # but this is more accurate\n 8.28099,\n 12.74215,\n 17.19343,\n 21.64114]),4)\n assert_array_almost_equal(kerpz,array([2.66584,\n 7.17212,\n 11.63218,\n 16.08312,\n 20.53068]),4)\n assert_array_almost_equal(keipz,array([4.93181,\n 9.40405,\n 13.85827,\n 18.30717,\n 22.75379]),4)\n\n def test_ker_zeros(self):\n ker = special.ker_zeros(5)\n assert_array_almost_equal(ker,array([1.71854,\n 6.12728,\n 10.56294,\n 15.00269,\n 19.44381]),4)\n\n def test_kerp_zeros(self):\n kerp = special.kerp_zeros(5)\n assert_array_almost_equal(kerp,array([2.66584,\n 7.17212,\n 11.63218,\n 16.08312,\n 20.53068]),4)\n\n\nclass TestBernoulli(TestCase):\n def test_bernoulli(self):\n brn = special.bernoulli(5)\n assert_array_almost_equal(brn,array([1.0000,\n -0.5000,\n 0.1667,\n 0.0000,\n -0.0333,\n 0.0000]),4)\n\n\nclass TestBeta(TestCase):\n def test_beta(self):\n bet = special.beta(2,4)\n betg = (special.gamma(2)*special.gamma(4))/special.gamma(6)\n assert_almost_equal(bet,betg,8)\n\n def test_betaln(self):\n betln = special.betaln(2,4)\n bet = log(abs(special.beta(2,4)))\n assert_almost_equal(betln,bet,8)\n\n def test_betainc(self):\n btinc = special.betainc(1,1,.2)\n assert_almost_equal(btinc,0.2,8)\n\n def test_betaincinv(self):\n y = special.betaincinv(2,4,.5)\n comp = special.betainc(2,4,y)\n assert_almost_equal(comp,.5,5)\n\n\nclass TestCombinatorics(TestCase):\n def test_comb(self):\n assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.])\n assert_almost_equal(special.comb(10, 3), 120.)\n assert_equal(special.comb(10, 3, exact=True), 120)\n assert_equal(special.comb(10, 3, exact=True, repetition=True), 220)\n\n def test_comb_with_np_int64(self):\n n = 70\n k = 30\n np_n = np.int64(n)\n np_k = np.int64(k)\n assert_equal(special.comb(np_n, np_k, exact=True),\n special.comb(n, k, exact=True))\n\n def test_comb_zeros(self):\n assert_equal(special.comb(2, 3, exact=True), 0)\n assert_equal(special.comb(-1, 3, exact=True), 0)\n assert_equal(special.comb(2, -1, exact=True), 0)\n assert_equal(special.comb(2, -1, exact=False), 0)\n assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]),\n [0., 0., 0., 120.])\n\n def test_perm(self):\n assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.])\n assert_almost_equal(special.perm(10, 3), 720.)\n assert_equal(special.perm(10, 3, exact=True), 720)\n\n def test_perm_zeros(self):\n assert_equal(special.perm(2, 3, exact=True), 0)\n assert_equal(special.perm(-1, 3, exact=True), 0)\n assert_equal(special.perm(2, -1, exact=True), 0)\n assert_equal(special.perm(2, -1, exact=False), 0)\n assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]),\n [0., 0., 0., 720.])\n\n\nclass TestTrigonometric(TestCase):\n def test_cbrt(self):\n cb = special.cbrt(27)\n cbrl = 27**(1.0/3.0)\n assert_approx_equal(cb,cbrl)\n\n def test_cbrtmore(self):\n cb1 = special.cbrt(27.9)\n cbrl1 = 27.9**(1.0/3.0)\n assert_almost_equal(cb1,cbrl1,8)\n\n def test_cosdg(self):\n cdg = special.cosdg(90)\n cdgrl = cos(pi/2.0)\n assert_almost_equal(cdg,cdgrl,8)\n\n def test_cosdgmore(self):\n cdgm = special.cosdg(30)\n cdgmrl = cos(pi/6.0)\n assert_almost_equal(cdgm,cdgmrl,8)\n\n def test_cosm1(self):\n cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10))\n csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1)\n assert_array_almost_equal(cs,csrl,8)\n\n def test_cotdg(self):\n ct = special.cotdg(30)\n ctrl = tan(pi/6.0)**(-1)\n assert_almost_equal(ct,ctrl,8)\n\n def test_cotdgmore(self):\n ct1 = special.cotdg(45)\n ctrl1 = tan(pi/4.0)**(-1)\n assert_almost_equal(ct1,ctrl1,8)\n\n def test_specialpoints(self):\n assert_almost_equal(special.cotdg(45), 1.0, 14)\n assert_almost_equal(special.cotdg(-45), -1.0, 14)\n assert_almost_equal(special.cotdg(90), 0.0, 14)\n assert_almost_equal(special.cotdg(-90), 0.0, 14)\n assert_almost_equal(special.cotdg(135), -1.0, 14)\n assert_almost_equal(special.cotdg(-135), 1.0, 14)\n assert_almost_equal(special.cotdg(225), 1.0, 14)\n assert_almost_equal(special.cotdg(-225), -1.0, 14)\n assert_almost_equal(special.cotdg(270), 0.0, 14)\n assert_almost_equal(special.cotdg(-270), 0.0, 14)\n assert_almost_equal(special.cotdg(315), -1.0, 14)\n assert_almost_equal(special.cotdg(-315), 1.0, 14)\n assert_almost_equal(special.cotdg(765), 1.0, 14)\n\n def test_sinc(self):\n # the sinc implementation and more extensive sinc tests are in numpy\n assert_array_equal(special.sinc([0]), 1)\n assert_equal(special.sinc(0.0), 1.0)\n\n def test_sindg(self):\n sn = special.sindg(90)\n assert_equal(sn,1.0)\n\n def test_sindgmore(self):\n snm = special.sindg(30)\n snmrl = sin(pi/6.0)\n assert_almost_equal(snm,snmrl,8)\n snm1 = special.sindg(45)\n snmrl1 = sin(pi/4.0)\n assert_almost_equal(snm1,snmrl1,8)\n\n\nclass TestTandg(TestCase):\n\n def test_tandg(self):\n tn = special.tandg(30)\n tnrl = tan(pi/6.0)\n assert_almost_equal(tn,tnrl,8)\n\n def test_tandgmore(self):\n tnm = special.tandg(45)\n tnmrl = tan(pi/4.0)\n assert_almost_equal(tnm,tnmrl,8)\n tnm1 = special.tandg(60)\n tnmrl1 = tan(pi/3.0)\n assert_almost_equal(tnm1,tnmrl1,8)\n\n def test_specialpoints(self):\n assert_almost_equal(special.tandg(0), 0.0, 14)\n assert_almost_equal(special.tandg(45), 1.0, 14)\n assert_almost_equal(special.tandg(-45), -1.0, 14)\n assert_almost_equal(special.tandg(135), -1.0, 14)\n assert_almost_equal(special.tandg(-135), 1.0, 14)\n assert_almost_equal(special.tandg(180), 0.0, 14)\n assert_almost_equal(special.tandg(-180), 0.0, 14)\n assert_almost_equal(special.tandg(225), 1.0, 14)\n assert_almost_equal(special.tandg(-225), -1.0, 14)\n assert_almost_equal(special.tandg(315), -1.0, 14)\n assert_almost_equal(special.tandg(-315), 1.0, 14)\n\n\nclass TestEllip(TestCase):\n def test_ellipj_nan(self):\n \"\"\"Regression test for #912.\"\"\"\n special.ellipj(0.5, np.nan)\n\n def test_ellipj(self):\n el = special.ellipj(0.2,0)\n rel = [sin(0.2),cos(0.2),1.0,0.20]\n assert_array_almost_equal(el,rel,13)\n\n def test_ellipk(self):\n elk = special.ellipk(.2)\n assert_almost_equal(elk,1.659623598610528,11)\n\n assert_equal(special.ellipkm1(0.0), np.inf)\n assert_equal(special.ellipkm1(1.0), pi/2)\n assert_equal(special.ellipkm1(np.inf), 0.0)\n assert_equal(special.ellipkm1(np.nan), np.nan)\n assert_equal(special.ellipkm1(-1), np.nan)\n assert_allclose(special.ellipk(-10), 0.7908718902387385)\n\n def test_ellipkinc(self):\n elkinc = special.ellipkinc(pi/2,.2)\n elk = special.ellipk(0.2)\n assert_almost_equal(elkinc,elk,15)\n alpha = 20*pi/180\n phi = 45*pi/180\n m = sin(alpha)**2\n elkinc = special.ellipkinc(phi,m)\n assert_almost_equal(elkinc,0.79398143,8)\n # From pg. 614 of A & S\n\n assert_equal(special.ellipkinc(pi/2, 0.0), pi/2)\n assert_equal(special.ellipkinc(pi/2, 1.0), np.inf)\n assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0)\n assert_equal(special.ellipkinc(pi/2, np.nan), np.nan)\n assert_equal(special.ellipkinc(pi/2, 2), np.nan)\n assert_equal(special.ellipkinc(0, 0.5), 0.0)\n assert_equal(special.ellipkinc(np.inf, 0.5), np.inf)\n assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf)\n assert_equal(special.ellipkinc(np.inf, np.inf), np.nan)\n assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan)\n assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan)\n assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan)\n assert_equal(special.ellipkinc(np.nan, 0.5), np.nan)\n assert_equal(special.ellipkinc(np.nan, np.nan), np.nan)\n\n assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14)\n assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946)\n\n def test_ellipkinc_2(self):\n # Regression test for gh-3550\n # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value\n mbad = 0.68359375000000011\n phi = 0.9272952180016123\n m = np.nextafter(mbad, 0)\n mvals = []\n for j in range(10):\n mvals.append(m)\n m = np.nextafter(m, 1)\n f = special.ellipkinc(phi, mvals)\n assert_array_almost_equal_nulp(f, 1.0259330100195334 * np.ones_like(f), 1)\n # this bug also appears at phi + n * pi for at least small n\n f1 = special.ellipkinc(phi + pi, mvals)\n assert_array_almost_equal_nulp(f1, 5.1296650500976675 * np.ones_like(f1), 2)\n\n def test_ellipkinc_singular(self):\n # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2)\n xlog = np.logspace(-300, -17, 25)\n xlin = np.linspace(1e-17, 0.1, 25)\n xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False)\n\n assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14)\n assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14)\n assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14)\n assert_equal(special.ellipkinc(np.pi/2, 1), np.inf)\n assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14)\n assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14)\n assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14)\n assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf)\n\n def test_ellipe(self):\n ele = special.ellipe(.2)\n assert_almost_equal(ele,1.4890350580958529,8)\n\n assert_equal(special.ellipe(0.0), pi/2)\n assert_equal(special.ellipe(1.0), 1.0)\n assert_equal(special.ellipe(-np.inf), np.inf)\n assert_equal(special.ellipe(np.nan), np.nan)\n assert_equal(special.ellipe(2), np.nan)\n assert_allclose(special.ellipe(-10), 3.6391380384177689)\n\n def test_ellipeinc(self):\n eleinc = special.ellipeinc(pi/2,.2)\n ele = special.ellipe(0.2)\n assert_almost_equal(eleinc,ele,14)\n # pg 617 of A & S\n alpha, phi = 52*pi/180,35*pi/180\n m = sin(alpha)**2\n eleinc = special.ellipeinc(phi,m)\n assert_almost_equal(eleinc, 0.58823065, 8)\n\n assert_equal(special.ellipeinc(pi/2, 0.0), pi/2)\n assert_equal(special.ellipeinc(pi/2, 1.0), 1.0)\n assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf)\n assert_equal(special.ellipeinc(pi/2, np.nan), np.nan)\n assert_equal(special.ellipeinc(pi/2, 2), np.nan)\n assert_equal(special.ellipeinc(0, 0.5), 0.0)\n assert_equal(special.ellipeinc(np.inf, 0.5), np.inf)\n assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf)\n assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf)\n assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf)\n assert_equal(special.ellipeinc(np.inf, np.inf), np.nan)\n assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan)\n assert_equal(special.ellipeinc(np.nan, 0.5), np.nan)\n assert_equal(special.ellipeinc(np.nan, np.nan), np.nan)\n assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876)\n\n def test_ellipeinc_2(self):\n # Regression test for gh-3550\n # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value\n mbad = 0.68359375000000011\n phi = 0.9272952180016123\n m = np.nextafter(mbad, 0)\n mvals = []\n for j in range(10):\n mvals.append(m)\n m = np.nextafter(m, 1)\n f = special.ellipeinc(phi, mvals)\n assert_array_almost_equal_nulp(f, 0.84442884574781019 * np.ones_like(f), 2)\n # this bug also appears at phi + n * pi for at least small n\n f1 = special.ellipeinc(phi + pi, mvals)\n assert_array_almost_equal_nulp(f1, 3.3471442287390509 * np.ones_like(f1), 4)\n\n\nclass TestErf(TestCase):\n\n def test_erf(self):\n er = special.erf(.25)\n assert_almost_equal(er,0.2763263902,8)\n\n def test_erf_zeros(self):\n erz = special.erf_zeros(5)\n erzr = array([1.45061616+1.88094300j,\n 2.24465928+2.61657514j,\n 2.83974105+3.17562810j,\n 3.33546074+3.64617438j,\n 3.76900557+4.06069723j])\n assert_array_almost_equal(erz,erzr,4)\n\n def _check_variant_func(self, func, other_func, rtol, atol=0):\n np.random.seed(1234)\n n = 10000\n x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1)\n y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1)\n z = x + 1j*y\n\n old_errors = np.seterr(all='ignore')\n try:\n w = other_func(z)\n w_real = other_func(x).real\n\n mask = np.isfinite(w)\n w = w[mask]\n z = z[mask]\n\n mask = np.isfinite(w_real)\n w_real = w_real[mask]\n x = x[mask]\n\n # test both real and complex variants\n assert_func_equal(func, w, z, rtol=rtol, atol=atol)\n assert_func_equal(func, w_real, x, rtol=rtol, atol=atol)\n finally:\n np.seterr(**old_errors)\n\n def test_erfc_consistent(self):\n self._check_variant_func(\n cephes.erfc,\n lambda z: 1 - cephes.erf(z),\n rtol=1e-12,\n atol=1e-14 # <- the test function loses precision\n )\n\n def test_erfcx_consistent(self):\n self._check_variant_func(\n cephes.erfcx,\n lambda z: np.exp(z*z) * cephes.erfc(z),\n rtol=1e-12\n )\n\n def test_erfi_consistent(self):\n self._check_variant_func(\n cephes.erfi,\n lambda z: -1j * cephes.erf(1j*z),\n rtol=1e-12\n )\n\n def test_dawsn_consistent(self):\n self._check_variant_func(\n cephes.dawsn,\n lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z),\n rtol=1e-12\n )\n\n def test_erfcinv(self):\n i = special.erfcinv(1)\n # Use assert_array_equal instead of assert_equal, so the comparsion\n # of -0.0 and 0.0 doesn't fail.\n assert_array_equal(i, 0)\n\n def test_erfinv(self):\n i = special.erfinv(0)\n assert_equal(i,0)\n\n def test_errprint(self):\n a = special.errprint()\n b = 1-a # a is the state 1-a inverts state\n c = special.errprint(b) # returns last state 'a'\n assert_equal(a,c)\n d = special.errprint(a) # returns to original state\n assert_equal(d,b) # makes sure state was returned\n # assert_equal(d,1-a)\n\n\nclass TestEuler(TestCase):\n def test_euler(self):\n eu0 = special.euler(0)\n eu1 = special.euler(1)\n eu2 = special.euler(2) # just checking segfaults\n assert_almost_equal(eu0[0],1,8)\n assert_almost_equal(eu2[2],-1,8)\n eu24 = special.euler(24)\n mathworld = [1,1,5,61,1385,50521,2702765,199360981,\n 19391512145,2404879675441,\n 370371188237525,69348874393137901,\n 15514534163557086905]\n correct = zeros((25,),'d')\n for k in range(0,13):\n if (k % 2):\n correct[2*k] = -float(mathworld[k])\n else:\n correct[2*k] = float(mathworld[k])\n olderr = np.seterr(all='ignore')\n try:\n err = nan_to_num((eu24-correct)/correct)\n errmax = max(err)\n finally:\n np.seterr(**olderr)\n assert_almost_equal(errmax, 0.0, 14)\n\n\nclass TestExp(TestCase):\n def test_exp2(self):\n ex = special.exp2(2)\n exrl = 2**2\n assert_equal(ex,exrl)\n\n def test_exp2more(self):\n exm = special.exp2(2.5)\n exmrl = 2**(2.5)\n assert_almost_equal(exm,exmrl,8)\n\n def test_exp10(self):\n ex = special.exp10(2)\n exrl = 10**2\n assert_approx_equal(ex,exrl)\n\n def test_exp10more(self):\n exm = special.exp10(2.5)\n exmrl = 10**(2.5)\n assert_almost_equal(exm,exmrl,8)\n\n def test_expm1(self):\n ex = (special.expm1(2),special.expm1(3),special.expm1(4))\n exrl = (exp(2)-1,exp(3)-1,exp(4)-1)\n assert_array_almost_equal(ex,exrl,8)\n\n def test_expm1more(self):\n ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2))\n exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1)\n assert_array_almost_equal(ex1,exrl1,8)\n\n\nclass TestFactorialFunctions(TestCase):\n def test_factorial(self):\n assert_array_almost_equal([6., 24., 120.],\n special.factorial([3, 4, 5], exact=False))\n assert_equal(special.factorial(5, exact=True), 120)\n\n def test_factorial2(self):\n assert_array_almost_equal([105., 384., 945.],\n special.factorial2([7, 8, 9], exact=False))\n assert_equal(special.factorial2(7, exact=True), 105)\n\n def test_factorialk(self):\n assert_equal(special.factorialk(5, 1, exact=True), 120)\n assert_equal(special.factorialk(5, 3, exact=True), 10)\n\n\nclass TestFresnel(TestCase):\n def test_fresnel(self):\n frs = array(special.fresnel(.5))\n assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8)\n\n def test_fresnel_inf1(self):\n frs = special.fresnel(np.inf)\n assert_equal(frs, (0.5, 0.5))\n\n def test_fresnel_inf2(self):\n frs = special.fresnel(-np.inf)\n assert_equal(frs, (-0.5, -0.5))\n\n # values from pg 329 Table 7.11 of A & S\n # slightly corrected in 4th decimal place\n def test_fresnel_zeros(self):\n szo, czo = special.fresnel_zeros(5)\n assert_array_almost_equal(szo,\n array([2.0093+0.2885j,\n 2.8335+0.2443j,\n 3.4675+0.2185j,\n 4.0026+0.2009j,\n 4.4742+0.1877j]),3)\n assert_array_almost_equal(czo,\n array([1.7437+0.3057j,\n 2.6515+0.2529j,\n 3.3204+0.2240j,\n 3.8757+0.2047j,\n 4.3611+0.1907j]),3)\n vals1 = special.fresnel(szo)[0]\n vals2 = special.fresnel(czo)[1]\n assert_array_almost_equal(vals1,0,14)\n assert_array_almost_equal(vals2,0,14)\n\n def test_fresnelc_zeros(self):\n szo, czo = special.fresnel_zeros(6)\n frc = special.fresnelc_zeros(6)\n assert_array_almost_equal(frc,czo,12)\n\n def test_fresnels_zeros(self):\n szo, czo = special.fresnel_zeros(5)\n frs = special.fresnels_zeros(5)\n assert_array_almost_equal(frs,szo,12)\n\n\nclass TestGamma(TestCase):\n def test_gamma(self):\n gam = special.gamma(5)\n assert_equal(gam,24.0)\n\n def test_gammaln(self):\n gamln = special.gammaln(3)\n lngam = log(special.gamma(3))\n assert_almost_equal(gamln,lngam,8)\n\n def test_gammainc(self):\n gama = special.gammainc(.5,.5)\n assert_almost_equal(gama,.7,1)\n\n def test_gammaincnan(self):\n gama = special.gammainc(-1,1)\n assert_(isnan(gama))\n\n def test_gammainczero(self):\n # bad arg but zero integration limit\n gama = special.gammainc(-1,0)\n assert_equal(gama,0.0)\n\n def test_gammaincinf(self):\n gama = special.gammainc(0.5, np.inf)\n assert_equal(gama,1.0)\n\n def test_gammaincc(self):\n gicc = special.gammaincc(.5,.5)\n greal = 1 - special.gammainc(.5,.5)\n assert_almost_equal(gicc,greal,8)\n\n def test_gammainccnan(self):\n gama = special.gammaincc(-1,1)\n assert_(isnan(gama))\n\n def test_gammainccinf(self):\n gama = special.gammaincc(0.5,np.inf)\n assert_equal(gama,0.0)\n\n def test_gammainccinv(self):\n gccinv = special.gammainccinv(.5,.5)\n gcinv = special.gammaincinv(.5,.5)\n assert_almost_equal(gccinv,gcinv,8)\n\n @with_special_errors\n def test_gammaincinv(self):\n y = special.gammaincinv(.4,.4)\n x = special.gammainc(.4,y)\n assert_almost_equal(x,0.4,1)\n y = special.gammainc(10, 0.05)\n x = special.gammaincinv(10, 2.5715803516000736e-20)\n assert_almost_equal(0.05, x, decimal=10)\n assert_almost_equal(y, 2.5715803516000736e-20, decimal=10)\n x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18)\n assert_almost_equal(11.0, x, decimal=10)\n\n @with_special_errors\n def test_975(self):\n # Regression test for ticket #975 -- switch point in algorithm\n # check that things work OK at the point, immediately next floats\n # around it, and a bit further away\n pts = [0.25,\n np.nextafter(0.25, 0), 0.25 - 1e-12,\n np.nextafter(0.25, 1), 0.25 + 1e-12]\n for xp in pts:\n y = special.gammaincinv(.4, xp)\n x = special.gammainc(0.4, y)\n assert_tol_equal(x, xp, rtol=1e-12)\n\n def test_rgamma(self):\n rgam = special.rgamma(8)\n rlgam = 1/special.gamma(8)\n assert_almost_equal(rgam,rlgam,8)\n\n def test_infinity(self):\n assert_(np.isinf(special.gamma(-1)))\n assert_equal(special.rgamma(-1), 0)\n\n\nclass TestHankel(TestCase):\n\n def test_negv1(self):\n assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14)\n\n def test_hankel1(self):\n hank1 = special.hankel1(1,.1)\n hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j)\n assert_almost_equal(hank1,hankrl,8)\n\n def test_negv1e(self):\n assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14)\n\n def test_hankel1e(self):\n hank1e = special.hankel1e(1,.1)\n hankrle = special.hankel1(1,.1)*exp(-.1j)\n assert_almost_equal(hank1e,hankrle,8)\n\n def test_negv2(self):\n assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14)\n\n def test_hankel2(self):\n hank2 = special.hankel2(1,.1)\n hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j)\n assert_almost_equal(hank2,hankrl2,8)\n\n def test_neg2e(self):\n assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14)\n\n def test_hankl2e(self):\n hank2e = special.hankel2e(1,.1)\n hankrl2e = special.hankel2e(1,.1)\n assert_almost_equal(hank2e,hankrl2e,8)\n\n\nclass TestHyper(TestCase):\n def test_h1vp(self):\n h1 = special.h1vp(1,.1)\n h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j)\n assert_almost_equal(h1,h1real,8)\n\n def test_h2vp(self):\n h2 = special.h2vp(1,.1)\n h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j)\n assert_almost_equal(h2,h2real,8)\n\n def test_hyp0f1(self):\n # scalar input\n assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12)\n assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15)\n\n # float input, expected values match mpmath\n x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5])\n expected = np.array([0.58493659229143, 0.70566805723127, 1.0,\n 1.37789689539747, 1.60373685288480])\n assert_allclose(x, expected, rtol=1e-12)\n\n # complex input\n x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j)\n assert_allclose(x, expected.astype(complex), rtol=1e-12)\n\n # test broadcasting\n x1 = [0.5, 1.5, 2.5]\n x2 = [0, 1, 0.5]\n x = special.hyp0f1(x1, x2)\n expected = [1.0, 1.8134302039235093, 1.21482702689997]\n assert_allclose(x, expected, rtol=1e-12)\n x = special.hyp0f1(np.row_stack([x1] * 2), x2)\n assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12)\n assert_raises(ValueError, special.hyp0f1,\n np.row_stack([x1] * 3), [0, 1])\n\n def test_hyp1f1(self):\n hyp1 = special.hyp1f1(.1,.1,.3)\n assert_almost_equal(hyp1, 1.3498588075760032,7)\n\n # test contributed by Moritz Deger (2008-05-29)\n # http://projects.scipy.org/scipy/scipy/ticket/659\n\n # reference data obtained from mathematica [ a, b, x, m(a,b,x)]:\n # produced with test_hyp1f1.nb\n ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04],\n [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00],\n [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05],\n [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08],\n [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24],\n [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21],\n [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13],\n [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13],\n [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02],\n [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10],\n [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01],\n [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21],\n [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20],\n [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07],\n [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03],\n [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02],\n [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11],\n [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03],\n [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17],\n [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01],\n [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00],\n [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00],\n [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23],\n [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01],\n [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04],\n [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08],\n [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01],\n [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07],\n [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03],\n [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09],\n [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06],\n [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00],\n [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01],\n [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02],\n [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02],\n [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02],\n [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00],\n [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09],\n [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01],\n [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00],\n [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02],\n [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05],\n [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05],\n [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02],\n [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02],\n [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13],\n [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05],\n [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12],\n [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01],\n [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16],\n [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37],\n [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06],\n [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02],\n [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12],\n [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27],\n [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04],\n [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06],\n [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07],\n [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03],\n [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07],\n [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27],\n [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12],\n [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32],\n [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04],\n [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01],\n [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02],\n [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19],\n [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09],\n [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31],\n [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01],\n [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02],\n [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08],\n [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09],\n [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33],\n [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01],\n [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29],\n [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01],\n [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29],\n [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02],\n [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00],\n [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08],\n [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01],\n [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01],\n [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01],\n [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13],\n [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11],\n [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02],\n [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02],\n [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01],\n [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31],\n [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04],\n [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25],\n [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01],\n [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00],\n [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02],\n [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05],\n [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02],\n [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01],\n [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01],\n [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]])\n\n for a,b,c,expected in ref_data:\n result = special.hyp1f1(a,b,c)\n assert_(abs(expected - result)/expected < 1e-4)\n\n def test_hyp1f1_gh2957(self):\n hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933)\n hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934)\n assert_almost_equal(hyp1, hyp2, 12)\n\n def test_hyp1f1_gh2282(self):\n hyp = special.hyp1f1(0.5, 1.5, -1000)\n assert_almost_equal(hyp, 0.028024956081989643, 12)\n\n def test_hyp1f2(self):\n pass\n\n def test_hyp2f0(self):\n pass\n\n def test_hyp2f1(self):\n # a collection of special cases taken from AMS 55\n values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))],\n [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)],\n [1, 1, 2, 0.2, -1/0.2*log(1-0.2)],\n [3, 3.5, 1.5, 0.2**2,\n 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))],\n [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)],\n [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)],\n [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) *\n special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)],\n [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) *\n special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)],\n [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) *\n special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)],\n # and some others\n # ticket #424\n [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484],\n # negative integer a or b, with c-a-b integer and x > 0.9\n [-2,3,1,0.95,0.715],\n [2,-3,1,0.95,-0.007],\n [-6,3,1,0.95,0.0000810625],\n [2,-5,1,0.95,-0.000029375],\n # huge negative integers\n (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24),\n (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18),\n ]\n for i, (a, b, c, x, v) in enumerate(values):\n cv = special.hyp2f1(a, b, c, x)\n assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)\n\n def test_hyp3f0(self):\n pass\n\n def test_hyperu(self):\n val1 = special.hyperu(1,0.1,100)\n assert_almost_equal(val1,0.0098153,7)\n a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2]\n a,b = asarray(a), asarray(b)\n z = 0.5\n hypu = special.hyperu(a,b,z)\n hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) /\n (special.gamma(1+a-b)*special.gamma(b)) -\n z**(1-b)*special.hyp1f1(1+a-b,2-b,z)\n / (special.gamma(a)*special.gamma(2-b)))\n assert_array_almost_equal(hypu,hprl,12)\n\n def test_hyperu_gh2287(self):\n assert_almost_equal(special.hyperu(1, 1.5, 20.2),\n 0.048360918656699191, 12)\n\n\nclass TestBessel(TestCase):\n def test_itj0y0(self):\n it0 = array(special.itj0y0(.2))\n assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8)\n\n def test_it2j0y0(self):\n it2 = array(special.it2j0y0(.2))\n assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8)\n\n def test_negv_iv(self):\n assert_equal(special.iv(3,2), special.iv(-3,2))\n\n def test_j0(self):\n oz = special.j0(.1)\n ozr = special.jn(0,.1)\n assert_almost_equal(oz,ozr,8)\n\n def test_j1(self):\n o1 = special.j1(.1)\n o1r = special.jn(1,.1)\n assert_almost_equal(o1,o1r,8)\n\n def test_jn(self):\n jnnr = special.jn(1,.2)\n assert_almost_equal(jnnr,0.099500832639235995,8)\n\n def test_negv_jv(self):\n assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14)\n\n def test_jv(self):\n values = [[0, 0.1, 0.99750156206604002],\n [2./3, 1e-8, 0.3239028506761532e-5],\n [2./3, 1e-10, 0.1503423854873779e-6],\n [3.1, 1e-10, 0.1711956265409013e-32],\n [2./3, 4.0, -0.2325440850267039],\n ]\n for i, (v, x, y) in enumerate(values):\n yc = special.jv(v, x)\n assert_almost_equal(yc, y, 8, err_msg='test #%d' % i)\n\n def test_negv_jve(self):\n assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14)\n\n def test_jve(self):\n jvexp = special.jve(1,.2)\n assert_almost_equal(jvexp,0.099500832639235995,8)\n jvexp1 = special.jve(1,.2+1j)\n z = .2+1j\n jvexpr = special.jv(1,z)*exp(-abs(z.imag))\n assert_almost_equal(jvexp1,jvexpr,8)\n\n def test_jn_zeros(self):\n jn0 = special.jn_zeros(0,5)\n jn1 = special.jn_zeros(1,5)\n assert_array_almost_equal(jn0,array([2.4048255577,\n 5.5200781103,\n 8.6537279129,\n 11.7915344391,\n 14.9309177086]),4)\n assert_array_almost_equal(jn1,array([3.83171,\n 7.01559,\n 10.17347,\n 13.32369,\n 16.47063]),4)\n\n jn102 = special.jn_zeros(102,5)\n assert_tol_equal(jn102, array([110.89174935992040343,\n 117.83464175788308398,\n 123.70194191713507279,\n 129.02417238949092824,\n 134.00114761868422559]), rtol=1e-13)\n\n jn301 = special.jn_zeros(301,5)\n assert_tol_equal(jn301, array([313.59097866698830153,\n 323.21549776096288280,\n 331.22338738656748796,\n 338.39676338872084500,\n 345.03284233056064157]), rtol=1e-13)\n\n def test_jn_zeros_slow(self):\n jn0 = special.jn_zeros(0, 300)\n assert_tol_equal(jn0[260-1], 816.02884495068867280, rtol=1e-13)\n assert_tol_equal(jn0[280-1], 878.86068707124422606, rtol=1e-13)\n assert_tol_equal(jn0[300-1], 941.69253065317954064, rtol=1e-13)\n\n jn10 = special.jn_zeros(10, 300)\n assert_tol_equal(jn10[260-1], 831.67668514305631151, rtol=1e-13)\n assert_tol_equal(jn10[280-1], 894.51275095371316931, rtol=1e-13)\n assert_tol_equal(jn10[300-1], 957.34826370866539775, rtol=1e-13)\n\n jn3010 = special.jn_zeros(3010,5)\n assert_tol_equal(jn3010, array([3036.86590780927,\n 3057.06598526482,\n 3073.66360690272,\n 3088.37736494778,\n 3101.86438139042]), rtol=1e-8)\n\n def test_jnjnp_zeros(self):\n jn = special.jn\n\n def jnp(n, x):\n return (jn(n-1,x) - jn(n+1,x))/2\n for nt in range(1, 30):\n z, n, m, t = special.jnjnp_zeros(nt)\n for zz, nn, tt in zip(z, n, t):\n if tt == 0:\n assert_allclose(jn(nn, zz), 0, atol=1e-6)\n elif tt == 1:\n assert_allclose(jnp(nn, zz), 0, atol=1e-6)\n else:\n raise AssertionError(\"Invalid t return for nt=%d\" % nt)\n\n def test_jnp_zeros(self):\n jnp = special.jnp_zeros(1,5)\n assert_array_almost_equal(jnp, array([1.84118,\n 5.33144,\n 8.53632,\n 11.70600,\n 14.86359]),4)\n jnp = special.jnp_zeros(443,5)\n assert_tol_equal(special.jvp(443, jnp), 0, atol=1e-15)\n\n def test_jnyn_zeros(self):\n jnz = special.jnyn_zeros(1,5)\n assert_array_almost_equal(jnz,(array([3.83171,\n 7.01559,\n 10.17347,\n 13.32369,\n 16.47063]),\n array([1.84118,\n 5.33144,\n 8.53632,\n 11.70600,\n 14.86359]),\n array([2.19714,\n 5.42968,\n 8.59601,\n 11.74915,\n 14.89744]),\n array([3.68302,\n 6.94150,\n 10.12340,\n 13.28576,\n 16.44006])),5)\n\n def test_jvp(self):\n jvprim = special.jvp(2,2)\n jv0 = (special.jv(1,2)-special.jv(3,2))/2\n assert_almost_equal(jvprim,jv0,10)\n\n def test_k0(self):\n ozk = special.k0(.1)\n ozkr = special.kv(0,.1)\n assert_almost_equal(ozk,ozkr,8)\n\n def test_k0e(self):\n ozke = special.k0e(.1)\n ozker = special.kve(0,.1)\n assert_almost_equal(ozke,ozker,8)\n\n def test_k1(self):\n o1k = special.k1(.1)\n o1kr = special.kv(1,.1)\n assert_almost_equal(o1k,o1kr,8)\n\n def test_k1e(self):\n o1ke = special.k1e(.1)\n o1ker = special.kve(1,.1)\n assert_almost_equal(o1ke,o1ker,8)\n\n def test_jacobi(self):\n a = 5*np.random.random() - 1\n b = 5*np.random.random() - 1\n P0 = special.jacobi(0,a,b)\n P1 = special.jacobi(1,a,b)\n P2 = special.jacobi(2,a,b)\n P3 = special.jacobi(3,a,b)\n\n assert_array_almost_equal(P0.c,[1],13)\n assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13)\n cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)]\n p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]]\n assert_array_almost_equal(P2.c,array(p2c)/8.0,13)\n cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3),\n 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)]\n p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]]\n assert_array_almost_equal(P3.c,array(p3c)/48.0,13)\n\n def test_kn(self):\n kn1 = special.kn(0,.2)\n assert_almost_equal(kn1,1.7527038555281462,8)\n\n def test_negv_kv(self):\n assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2))\n\n def test_kv0(self):\n kv0 = special.kv(0,.2)\n assert_almost_equal(kv0, 1.7527038555281462, 10)\n\n def test_kv1(self):\n kv1 = special.kv(1,0.2)\n assert_almost_equal(kv1, 4.775972543220472, 10)\n\n def test_kv2(self):\n kv2 = special.kv(2,0.2)\n assert_almost_equal(kv2, 49.51242928773287, 10)\n\n def test_kn_largeorder(self):\n assert_allclose(special.kn(32, 1), 1.7516596664574289e+43)\n\n def test_kv_largearg(self):\n assert_equal(special.kv(0, 1e19), 0)\n\n def test_negv_kve(self):\n assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2))\n\n def test_kve(self):\n kve1 = special.kve(0,.2)\n kv1 = special.kv(0,.2)*exp(.2)\n assert_almost_equal(kve1,kv1,8)\n z = .2+1j\n kve2 = special.kve(0,z)\n kv2 = special.kv(0,z)*exp(z)\n assert_almost_equal(kve2,kv2,8)\n\n def test_kvp_v0n1(self):\n z = 2.2\n assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10)\n\n def test_kvp_n1(self):\n v = 3.\n z = 2.2\n xc = -special.kv(v+1,z) + v/z*special.kv(v,z)\n x = special.kvp(v,z, n=1)\n assert_almost_equal(xc, x, 10) # this function (kvp) is broken\n\n def test_kvp_n2(self):\n v = 3.\n z = 2.2\n xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z\n x = special.kvp(v, z, n=2)\n assert_almost_equal(xc, x, 10)\n\n def test_y0(self):\n oz = special.y0(.1)\n ozr = special.yn(0,.1)\n assert_almost_equal(oz,ozr,8)\n\n def test_y1(self):\n o1 = special.y1(.1)\n o1r = special.yn(1,.1)\n assert_almost_equal(o1,o1r,8)\n\n def test_y0_zeros(self):\n yo,ypo = special.y0_zeros(2)\n zo,zpo = special.y0_zeros(2,complex=1)\n all = r_[yo,zo]\n allval = r_[ypo,zpo]\n assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11)\n assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11)\n\n def test_y1_zeros(self):\n y1 = special.y1_zeros(1)\n assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5)\n\n def test_y1p_zeros(self):\n y1p = special.y1p_zeros(1,complex=1)\n assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3)\n\n def test_yn_zeros(self):\n an = special.yn_zeros(4,2)\n assert_array_almost_equal(an,array([5.64515, 9.36162]),5)\n an = special.yn_zeros(443,5)\n assert_tol_equal(an, [450.13573091578090314, 463.05692376675001542,\n 472.80651546418663566, 481.27353184725625838,\n 488.98055964441374646], rtol=1e-15)\n\n def test_ynp_zeros(self):\n ao = special.ynp_zeros(0,2)\n assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6)\n ao = special.ynp_zeros(43,5)\n assert_tol_equal(special.yvp(43, ao), 0, atol=1e-15)\n ao = special.ynp_zeros(443,5)\n assert_tol_equal(special.yvp(443, ao), 0, atol=1e-9)\n\n def test_ynp_zeros_large_order(self):\n ao = special.ynp_zeros(443,5)\n assert_tol_equal(special.yvp(443, ao), 0, atol=1e-14)\n\n def test_yn(self):\n yn2n = special.yn(1,.2)\n assert_almost_equal(yn2n,-3.3238249881118471,8)\n\n def test_negv_yv(self):\n assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14)\n\n def test_yv(self):\n yv2 = special.yv(1,.2)\n assert_almost_equal(yv2,-3.3238249881118471,8)\n\n def test_negv_yve(self):\n assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14)\n\n def test_yve(self):\n yve2 = special.yve(1,.2)\n assert_almost_equal(yve2,-3.3238249881118471,8)\n yve2r = special.yv(1,.2+1j)*exp(-1)\n yve22 = special.yve(1,.2+1j)\n assert_almost_equal(yve22,yve2r,8)\n\n def test_yvp(self):\n yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0\n yvp1 = special.yvp(2,.2)\n assert_array_almost_equal(yvp1,yvpr,10)\n\n def _cephes_vs_amos_points(self):\n \"\"\"Yield points at which to compare Cephes implementation to AMOS\"\"\"\n # check several points, including large-amplitude ones\n for v in [-120, -100.3, -20., -10., -1., -.5,\n 0., 1., 12.49, 120., 301]:\n for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5,\n 700.6, 1300, 10003]:\n yield v, z\n\n # check half-integers; these are problematic points at least\n # for cephes/iv\n for v in 0.5 + arange(-60, 60):\n yield v, 3.5\n\n def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None):\n for v, z in self._cephes_vs_amos_points():\n if skip is not None and skip(v, z):\n continue\n c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z)\n if np.isinf(c1):\n assert_(np.abs(c2) >= 1e300, (v, z))\n elif np.isnan(c1):\n assert_(c2.imag != 0, (v, z))\n else:\n assert_tol_equal(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol)\n if v == int(v):\n assert_tol_equal(c3, c2, err_msg=(v, z),\n rtol=rtol, atol=atol)\n\n def test_jv_cephes_vs_amos(self):\n self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305)\n\n def test_yv_cephes_vs_amos(self):\n self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305)\n\n def test_yv_cephes_vs_amos_only_small_orders(self):\n skipper = lambda v, z: (abs(v) > 50)\n self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper)\n\n def test_iv_cephes_vs_amos(self):\n olderr = np.seterr(all='ignore')\n try:\n self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305)\n finally:\n np.seterr(**olderr)\n\n @dec.slow\n def test_iv_cephes_vs_amos_mass_test(self):\n N = 1000000\n np.random.seed(1)\n v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N)\n x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N)\n\n imsk = (np.random.randint(8, size=N) == 0)\n v[imsk] = v[imsk].astype(int)\n\n old_err = np.seterr(all='ignore')\n try:\n c1 = special.iv(v, x)\n c2 = special.iv(v, x+0j)\n\n # deal with differences in the inf and zero cutoffs\n c1[abs(c1) > 1e300] = np.inf\n c2[abs(c2) > 1e300] = np.inf\n c1[abs(c1) < 1e-300] = 0\n c2[abs(c2) < 1e-300] = 0\n\n dc = abs(c1/c2 - 1)\n dc[np.isnan(dc)] = 0\n finally:\n np.seterr(**old_err)\n\n k = np.argmax(dc)\n\n # Most error apparently comes from AMOS and not our implementation;\n # there are some problems near integer orders there\n assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j)))\n\n def test_kv_cephes_vs_amos(self):\n self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305)\n self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305)\n\n def test_ticket_623(self):\n assert_tol_equal(special.jv(3, 4), 0.43017147387562193)\n assert_tol_equal(special.jv(301, 1300), 0.0183487151115275)\n assert_tol_equal(special.jv(301, 1296.0682), -0.0224174325312048)\n\n def test_ticket_853(self):\n \"\"\"Negative-order Bessels\"\"\"\n # cephes\n assert_tol_equal(special.jv(-1, 1), -0.4400505857449335)\n assert_tol_equal(special.jv(-2, 1), 0.1149034849319005)\n assert_tol_equal(special.yv(-1, 1), 0.7812128213002887)\n assert_tol_equal(special.yv(-2, 1), -1.650682606816255)\n assert_tol_equal(special.iv(-1, 1), 0.5651591039924851)\n assert_tol_equal(special.iv(-2, 1), 0.1357476697670383)\n assert_tol_equal(special.kv(-1, 1), 0.6019072301972347)\n assert_tol_equal(special.kv(-2, 1), 1.624838898635178)\n assert_tol_equal(special.jv(-0.5, 1), 0.43109886801837607952)\n assert_tol_equal(special.yv(-0.5, 1), 0.6713967071418031)\n assert_tol_equal(special.iv(-0.5, 1), 1.231200214592967)\n assert_tol_equal(special.kv(-0.5, 1), 0.4610685044478945)\n # amos\n assert_tol_equal(special.jv(-1, 1+0j), -0.4400505857449335)\n assert_tol_equal(special.jv(-2, 1+0j), 0.1149034849319005)\n assert_tol_equal(special.yv(-1, 1+0j), 0.7812128213002887)\n assert_tol_equal(special.yv(-2, 1+0j), -1.650682606816255)\n\n assert_tol_equal(special.iv(-1, 1+0j), 0.5651591039924851)\n assert_tol_equal(special.iv(-2, 1+0j), 0.1357476697670383)\n assert_tol_equal(special.kv(-1, 1+0j), 0.6019072301972347)\n assert_tol_equal(special.kv(-2, 1+0j), 1.624838898635178)\n\n assert_tol_equal(special.jv(-0.5, 1+0j), 0.43109886801837607952)\n assert_tol_equal(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j)\n assert_tol_equal(special.yv(-0.5, 1+0j), 0.6713967071418031)\n assert_tol_equal(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j)\n\n assert_tol_equal(special.iv(-0.5, 1+0j), 1.231200214592967)\n assert_tol_equal(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j)\n assert_tol_equal(special.kv(-0.5, 1+0j), 0.4610685044478945)\n assert_tol_equal(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j)\n\n assert_tol_equal(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3))\n assert_tol_equal(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3))\n assert_tol_equal(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3))\n assert_tol_equal(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j))\n\n assert_tol_equal(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j))\n assert_tol_equal(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j))\n\n def test_ticket_854(self):\n \"\"\"Real-valued Bessel domains\"\"\"\n assert_(isnan(special.jv(0.5, -1)))\n assert_(isnan(special.iv(0.5, -1)))\n assert_(isnan(special.yv(0.5, -1)))\n assert_(isnan(special.yv(1, -1)))\n assert_(isnan(special.kv(0.5, -1)))\n assert_(isnan(special.kv(1, -1)))\n assert_(isnan(special.jve(0.5, -1)))\n assert_(isnan(special.ive(0.5, -1)))\n assert_(isnan(special.yve(0.5, -1)))\n assert_(isnan(special.yve(1, -1)))\n assert_(isnan(special.kve(0.5, -1)))\n assert_(isnan(special.kve(1, -1)))\n assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1))\n assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1))\n\n def test_ticket_503(self):\n \"\"\"Real-valued Bessel I overflow\"\"\"\n assert_tol_equal(special.iv(1, 700), 1.528500390233901e302)\n assert_tol_equal(special.iv(1000, 1120), 1.301564549405821e301)\n\n def test_iv_hyperg_poles(self):\n assert_tol_equal(special.iv(-0.5, 1), 1.231200214592967)\n\n def iv_series(self, v, z, n=200):\n k = arange(0, n).astype(float_)\n r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1)\n r[isnan(r)] = inf\n r = exp(r)\n err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10\n return r.sum(), err\n\n def test_i0_series(self):\n for z in [1., 10., 200.5]:\n value, err = self.iv_series(0, z)\n assert_tol_equal(special.i0(z), value, atol=err, err_msg=z)\n\n def test_i1_series(self):\n for z in [1., 10., 200.5]:\n value, err = self.iv_series(1, z)\n assert_tol_equal(special.i1(z), value, atol=err, err_msg=z)\n\n def test_iv_series(self):\n for v in [-20., -10., -1., 0., 1., 12.49, 120.]:\n for z in [1., 10., 200.5, -1+2j]:\n value, err = self.iv_series(v, z)\n assert_tol_equal(special.iv(v, z), value, atol=err, err_msg=(v, z))\n\n def test_i0(self):\n values = [[0.0, 1.0],\n [1e-10, 1.0],\n [0.1, 0.9071009258],\n [0.5, 0.6450352706],\n [1.0, 0.4657596077],\n [2.5, 0.2700464416],\n [5.0, 0.1835408126],\n [20.0, 0.0897803119],\n ]\n for i, (x, v) in enumerate(values):\n cv = special.i0(x) * exp(-x)\n assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)\n\n def test_i0e(self):\n oize = special.i0e(.1)\n oizer = special.ive(0,.1)\n assert_almost_equal(oize,oizer,8)\n\n def test_i1(self):\n values = [[0.0, 0.0],\n [1e-10, 0.4999999999500000e-10],\n [0.1, 0.0452984468],\n [0.5, 0.1564208032],\n [1.0, 0.2079104154],\n [5.0, 0.1639722669],\n [20.0, 0.0875062222],\n ]\n for i, (x, v) in enumerate(values):\n cv = special.i1(x) * exp(-x)\n assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)\n\n def test_i1e(self):\n oi1e = special.i1e(.1)\n oi1er = special.ive(1,.1)\n assert_almost_equal(oi1e,oi1er,8)\n\n def test_iti0k0(self):\n iti0 = array(special.iti0k0(5))\n assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5)\n\n def test_it2i0k0(self):\n it2k = special.it2i0k0(.1)\n assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6)\n\n def test_iv(self):\n iv1 = special.iv(0,.1)*exp(-.1)\n assert_almost_equal(iv1,0.90710092578230106,10)\n\n def test_negv_ive(self):\n assert_equal(special.ive(3,2), special.ive(-3,2))\n\n def test_ive(self):\n ive1 = special.ive(0,.1)\n iv1 = special.iv(0,.1)*exp(-.1)\n assert_almost_equal(ive1,iv1,10)\n\n def test_ivp0(self):\n assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10)\n\n def test_ivp(self):\n y = (special.iv(0,2) + special.iv(2,2))/2\n x = special.ivp(1,2)\n assert_almost_equal(x,y,10)\n\n\nclass TestLaguerre(TestCase):\n def test_laguerre(self):\n lag0 = special.laguerre(0)\n lag1 = special.laguerre(1)\n lag2 = special.laguerre(2)\n lag3 = special.laguerre(3)\n lag4 = special.laguerre(4)\n lag5 = special.laguerre(5)\n assert_array_almost_equal(lag0.c,[1],13)\n assert_array_almost_equal(lag1.c,[-1,1],13)\n assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13)\n assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13)\n assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13)\n assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13)\n\n def test_genlaguerre(self):\n k = 5*np.random.random() - 0.9\n lag0 = special.genlaguerre(0,k)\n lag1 = special.genlaguerre(1,k)\n lag2 = special.genlaguerre(2,k)\n lag3 = special.genlaguerre(3,k)\n assert_equal(lag0.c,[1])\n assert_equal(lag1.c,[-1,k+1])\n assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0)\n assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0)\n\n\n# Base polynomials come from Abrahmowitz and Stegan\nclass TestLegendre(TestCase):\n def test_legendre(self):\n leg0 = special.legendre(0)\n leg1 = special.legendre(1)\n leg2 = special.legendre(2)\n leg3 = special.legendre(3)\n leg4 = special.legendre(4)\n leg5 = special.legendre(5)\n assert_equal(leg0.c, [1])\n assert_equal(leg1.c, [1,0])\n assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13)\n assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0)\n assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0)\n assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0)\n\n\nclass TestLambda(TestCase):\n def test_lmbda(self):\n lam = special.lmbda(1,.1)\n lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]),\n array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1]))\n assert_array_almost_equal(lam,lamr,8)\n\n\nclass TestLog1p(TestCase):\n def test_log1p(self):\n l1p = (special.log1p(10), special.log1p(11), special.log1p(12))\n l1prl = (log(11), log(12), log(13))\n assert_array_almost_equal(l1p,l1prl,8)\n\n def test_log1pmore(self):\n l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2))\n l1pmrl = (log(2),log(2.1),log(2.2))\n assert_array_almost_equal(l1pm,l1pmrl,8)\n\n\nclass TestLegendreFunctions(TestCase):\n def test_clpmn(self):\n z = 0.5+0.3j\n clp = special.clpmn(2, 2, z, 3)\n assert_array_almost_equal(clp,\n (array([[1.0000, z, 0.5*(3*z*z-1)],\n [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)],\n [0.0000, 0.0000, 3*(z*z-1)]]),\n array([[0.0000, 1.0000, 3*z],\n [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)],\n [0.0000, 0.0000, 6*z]])),\n 7)\n\n def test_clpmn_close_to_real_2(self):\n eps = 1e-10\n m = 1\n n = 3\n x = 0.5\n clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n]\n clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n]\n assert_array_almost_equal(array([clp_plus, clp_minus]),\n array([special.lpmv(m, n, x),\n special.lpmv(m, n, x)]),\n 7)\n\n def test_clpmn_close_to_real_3(self):\n eps = 1e-10\n m = 1\n n = 3\n x = 0.5\n clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n]\n clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n]\n assert_array_almost_equal(array([clp_plus, clp_minus]),\n array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi),\n special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]),\n 7)\n\n def test_clpmn_across_unit_circle(self):\n eps = 1e-7\n m = 1\n n = 1\n x = 1j\n for type in [2, 3]:\n assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n],\n special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6)\n\n def test_inf(self):\n for z in (1, -1):\n for n in range(4):\n for m in range(1, n):\n lp = special.clpmn(m, n, z)\n assert_(np.isinf(lp[1][1,1:]).all())\n lp = special.lpmn(m, n, z)\n assert_(np.isinf(lp[1][1,1:]).all())\n\n def test_deriv_clpmn(self):\n # data inside and outside of the unit circle\n zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j,\n 1+1j, -1+1j, -1-1j, 1-1j]\n m = 2\n n = 3\n for type in [2, 3]:\n for z in zvals:\n for h in [1e-3, 1e-3j]:\n approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0]\n - special.clpmn(m, n, z-0.5*h, type)[0])/h\n assert_allclose(special.clpmn(m, n, z, type)[1],\n approx_derivative,\n rtol=1e-4)\n\n def test_lpmn(self):\n lp = special.lpmn(0,2,.5)\n assert_array_almost_equal(lp,(array([[1.00000,\n 0.50000,\n -0.12500]]),\n array([[0.00000,\n 1.00000,\n 1.50000]])),4)\n\n def test_lpn(self):\n lpnf = special.lpn(2,.5)\n assert_array_almost_equal(lpnf,(array([1.00000,\n 0.50000,\n -0.12500]),\n array([0.00000,\n 1.00000,\n 1.50000])),4)\n\n def test_lpmv(self):\n lp = special.lpmv(0,2,.5)\n assert_almost_equal(lp,-0.125,7)\n lp = special.lpmv(0,40,.001)\n assert_almost_equal(lp,0.1252678976534484,7)\n\n # XXX: this is outside the domain of the current implementation,\n # so ensure it returns a NaN rather than a wrong answer.\n olderr = np.seterr(all='ignore')\n try:\n lp = special.lpmv(-1,-1,.001)\n finally:\n np.seterr(**olderr)\n assert_(lp != 0 or np.isnan(lp))\n\n def test_lqmn(self):\n lqmnf = special.lqmn(0,2,.5)\n lqf = special.lqn(2,.5)\n assert_array_almost_equal(lqmnf[0][0],lqf[0],4)\n assert_array_almost_equal(lqmnf[1][0],lqf[1],4)\n\n def test_lqmn_gt1(self):\n \"\"\"algorithm for real arguments changes at 1.0001\n test against analytical result for m=2, n=1\n \"\"\"\n x0 = 1.0001\n delta = 0.00002\n for x in (x0-delta, x0+delta):\n lq = special.lqmn(2, 1, x)[0][-1, -1]\n expected = 2/(x*x-1)\n assert_almost_equal(lq, expected)\n\n def test_lqmn_shape(self):\n a, b = special.lqmn(4, 4, 1.1)\n assert_equal(a.shape, (5, 5))\n assert_equal(b.shape, (5, 5))\n\n a, b = special.lqmn(4, 0, 1.1)\n assert_equal(a.shape, (5, 1))\n assert_equal(b.shape, (5, 1))\n\n def test_lqn(self):\n lqf = special.lqn(2,.5)\n assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]),\n array([1.3333, 1.216, -0.8427])),4)\n\n\nclass TestMathieu(TestCase):\n\n def test_mathieu_a(self):\n pass\n\n def test_mathieu_even_coef(self):\n mc = special.mathieu_even_coef(2,5)\n # Q not defined broken and cannot figure out proper reporting order\n\n def test_mathieu_odd_coef(self):\n # same problem as above\n pass\n\n\nclass TestFresnelIntegral(TestCase):\n\n def test_modfresnelp(self):\n pass\n\n def test_modfresnelm(self):\n pass\n\n\nclass TestOblCvSeq(TestCase):\n def test_obl_cv_seq(self):\n obl = special.obl_cv_seq(0,3,1)\n assert_array_almost_equal(obl,array([-0.348602,\n 1.393206,\n 5.486800,\n 11.492120]),5)\n\n\nclass TestParabolicCylinder(TestCase):\n def test_pbdn_seq(self):\n pb = special.pbdn_seq(1,.1)\n assert_array_almost_equal(pb,(array([0.9975,\n 0.0998]),\n array([-0.0499,\n 0.9925])),4)\n\n def test_pbdv(self):\n pbv = special.pbdv(1,.2)\n derrl = 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0]\n\n def test_pbdv_seq(self):\n pbn = special.pbdn_seq(1,.1)\n pbv = special.pbdv_seq(1,.1)\n assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4)\n\n def test_pbdv_points(self):\n # simple case\n eta = np.linspace(-10, 10, 5)\n z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta)\n assert_tol_equal(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14)\n\n # some points\n assert_tol_equal(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12)\n assert_tol_equal(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12)\n\n def test_pbdv_gradient(self):\n x = np.linspace(-4, 4, 8)[:,None]\n eta = np.linspace(-10, 10, 5)[None,:]\n\n p = special.pbdv(eta, x)\n eps = 1e-7 + 1e-7*abs(x)\n dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2.\n assert_tol_equal(p[1], dp, rtol=1e-6, atol=1e-6)\n\n def test_pbvv_gradient(self):\n x = np.linspace(-4, 4, 8)[:,None]\n eta = np.linspace(-10, 10, 5)[None,:]\n\n p = special.pbvv(eta, x)\n eps = 1e-7 + 1e-7*abs(x)\n dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2.\n assert_tol_equal(p[1], dp, rtol=1e-6, atol=1e-6)\n\n\nclass TestPolygamma(TestCase):\n # from Table 6.2 (pg. 271) of A&S\n def test_polygamma(self):\n poly2 = special.polygamma(2,1)\n poly3 = special.polygamma(3,1)\n assert_almost_equal(poly2,-2.4041138063,10)\n assert_almost_equal(poly3,6.4939394023,10)\n\n # Test polygamma(0, x) == psi(x)\n x = [2, 3, 1.1e14]\n assert_almost_equal(special.polygamma(0, x), special.psi(x))\n\n # Test broadcasting\n n = [0, 1, 2]\n x = [0.5, 1.5, 2.5]\n expected = [-1.9635100260214238, 0.93480220054467933,\n -0.23620405164172739]\n assert_almost_equal(special.polygamma(n, x), expected)\n expected = np.row_stack([expected]*2)\n assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)),\n expected)\n assert_almost_equal(special.polygamma(np.row_stack([n]*2), x),\n expected)\n\n\nclass TestProCvSeq(TestCase):\n def test_pro_cv_seq(self):\n prol = special.pro_cv_seq(0,3,1)\n assert_array_almost_equal(prol,array([0.319000,\n 2.593084,\n 6.533471,\n 12.514462]),5)\n\n\nclass TestPsi(TestCase):\n def test_psi(self):\n ps = special.psi(1)\n assert_almost_equal(ps,-0.57721566490153287,8)\n\n\nclass TestRadian(TestCase):\n def test_radian(self):\n rad = special.radian(90,0,0)\n assert_almost_equal(rad,pi/2.0,5)\n\n def test_radianmore(self):\n rad1 = special.radian(90,1,60)\n assert_almost_equal(rad1,pi/2+0.0005816135199345904,5)\n\n\nclass TestRiccati(TestCase):\n def test_riccati_jn(self):\n jnrl = (special.sph_jn(1,.2)[0]*.2,special.sph_jn(1,.2)[0]+special.sph_jn(1,.2)[1]*.2)\n ricjn = special.riccati_jn(1,.2)\n assert_array_almost_equal(ricjn,jnrl,8)\n\n def test_riccati_yn(self):\n ynrl = (special.sph_yn(1,.2)[0]*.2,special.sph_yn(1,.2)[0]+special.sph_yn(1,.2)[1]*.2)\n ricyn = special.riccati_yn(1,.2)\n assert_array_almost_equal(ricyn,ynrl,8)\n\n\nclass TestRound(TestCase):\n def test_round(self):\n rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6))))\n\n # Note: According to the documentation, scipy.special.round is\n # supposed to round to the nearest even number if the fractional\n # part is exactly 0.5. On some platforms, this does not appear\n # to work and thus this test may fail. However, this unit test is\n # correctly written.\n rndrl = (10,10,10,11)\n assert_array_equal(rnd,rndrl)\n\n\ndef test_sph_harm():\n # Tests derived from tables in\n # http://en.wikipedia.org/wiki/Table_of_spherical_harmonics\n sh = special.sph_harm\n pi = np.pi\n exp = np.exp\n sqrt = np.sqrt\n sin = np.sin\n cos = np.cos\n yield (assert_array_almost_equal, sh(0,0,0,0),\n 0.5/sqrt(pi))\n yield (assert_array_almost_equal, sh(-2,2,0.,pi/4),\n 0.25*sqrt(15./(2.*pi)) *\n (sin(pi/4))**2.)\n yield (assert_array_almost_equal, sh(-2,2,0.,pi/2),\n 0.25*sqrt(15./(2.*pi)))\n yield (assert_array_almost_equal, sh(2,2,pi,pi/2),\n 0.25*sqrt(15/(2.*pi)) *\n exp(0+2.*pi*1j)*sin(pi/2.)**2.)\n yield (assert_array_almost_equal, sh(2,4,pi/4.,pi/3.),\n (3./8.)*sqrt(5./(2.*pi)) *\n exp(0+2.*pi/4.*1j) *\n sin(pi/3.)**2. *\n (7.*cos(pi/3.)**2.-1))\n yield (assert_array_almost_equal, sh(4,4,pi/8.,pi/6.),\n (3./16.)*sqrt(35./(2.*pi)) *\n exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.)\n\n\ndef test_sph_harm_ufunc_loop_selection():\n # see https://github.com/scipy/scipy/issues/4895\n dt = np.dtype(np.complex128)\n assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt)\n assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt)\n assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt)\n assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt)\n assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt)\n assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt)\n\n\nclass TestSpherical(TestCase):\n def test_sph_harm(self):\n # see test_sph_harm function\n pass\n\n def test_sph_in(self):\n i1n = special.sph_in(1,.2)\n inp0 = (i1n[0][1])\n inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1])\n assert_array_almost_equal(i1n[0],array([1.0066800127054699381,\n 0.066933714568029540839]),12)\n assert_array_almost_equal(i1n[1],[inp0,inp1],12)\n\n def test_sph_inkn(self):\n spikn = r_[special.sph_in(1,.2) + special.sph_kn(1,.2)]\n inkn = r_[special.sph_inkn(1,.2)]\n assert_array_almost_equal(inkn,spikn,10)\n\n def test_sph_in_kn_order0(self):\n x = 1.\n sph_i0 = special.sph_in(0, x)\n sph_i0_expected = np.array([np.sinh(x)/x,\n np.cosh(x)/x-np.sinh(x)/x**2])\n assert_array_almost_equal(r_[sph_i0], sph_i0_expected)\n sph_k0 = special.sph_kn(0, x)\n sph_k0_expected = np.array([0.5*pi*exp(-x)/x,\n -0.5*pi*exp(-x)*(1/x+1/x**2)])\n assert_array_almost_equal(r_[sph_k0], sph_k0_expected)\n sph_i0k0 = special.sph_inkn(0, x)\n assert_array_almost_equal(r_[sph_i0+sph_k0],\n r_[sph_i0k0],\n 10)\n\n def test_sph_jn(self):\n s1 = special.sph_jn(2,.2)\n s10 = -s1[0][1]\n s11 = s1[0][0]-2.0/0.2*s1[0][1]\n s12 = s1[0][1]-3.0/0.2*s1[0][2]\n assert_array_almost_equal(s1[0],[0.99334665397530607731,\n 0.066400380670322230863,\n 0.0026590560795273856680],12)\n assert_array_almost_equal(s1[1],[s10,s11,s12],12)\n\n def test_sph_jnyn(self):\n jnyn = r_[special.sph_jn(1,.2) + special.sph_yn(1,.2)] # tuple addition\n jnyn1 = r_[special.sph_jnyn(1,.2)]\n assert_array_almost_equal(jnyn1,jnyn,9)\n\n def test_sph_kn(self):\n kn = special.sph_kn(2,.2)\n kn0 = -kn[0][1]\n kn1 = -kn[0][0]-2.0/0.2*kn[0][1]\n kn2 = -kn[0][1]-3.0/0.2*kn[0][2]\n assert_array_almost_equal(kn[0],[6.4302962978445670140,\n 38.581777787067402086,\n 585.15696310385559829],12)\n assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9)\n\n def test_sph_yn(self):\n sy1 = special.sph_yn(2,.2)[0][2]\n sy2 = special.sph_yn(0,.2)[0][0]\n sphpy = (special.sph_yn(1,.2)[0][0]-2*special.sph_yn(2,.2)[0][2])/3 # correct derivative value\n assert_almost_equal(sy1,-377.52483,5) # previous values in the system\n assert_almost_equal(sy2,-4.9003329,5)\n sy3 = special.sph_yn(1,.2)[1][1]\n assert_almost_equal(sy3,sphpy,4) # compare correct derivative val. (correct =-system val).\n\n\nclass TestStruve(object):\n def _series(self, v, z, n=100):\n \"\"\"Compute Struve function & error estimate from its power series.\"\"\"\n k = arange(0, n)\n r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5)\n err = abs(r).max() * finfo(float_).eps * n\n return r.sum(), err\n\n def test_vs_series(self):\n \"\"\"Check Struve function versus its power series\"\"\"\n for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]:\n for z in [1, 10, 19, 21, 30]:\n value, err = self._series(v, z)\n assert_tol_equal(special.struve(v, z), value, rtol=0, atol=err), (v, z)\n\n def test_some_values(self):\n assert_tol_equal(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7)\n assert_tol_equal(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8)\n assert_tol_equal(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12)\n assert_tol_equal(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11)\n assert_equal(special.struve(-12, -41), -special.struve(-12, 41))\n assert_equal(special.struve(+12, -41), -special.struve(+12, 41))\n assert_equal(special.struve(-11, -41), +special.struve(-11, 41))\n assert_equal(special.struve(+11, -41), +special.struve(+11, 41))\n\n assert_(isnan(special.struve(-7.1, -1)))\n assert_(isnan(special.struve(-10.1, -1)))\n\n def test_regression_679(self):\n \"\"\"Regression test for #679\"\"\"\n assert_tol_equal(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8))\n assert_tol_equal(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8))\n assert_tol_equal(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8))\n\n\ndef test_chi2_smalldf():\n assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110)\n\n\ndef test_ch2_inf():\n assert_equal(special.chdtr(0.7,np.inf), 1.0)\n\n\ndef test_chi2c_smalldf():\n assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110)\n\n\ndef test_chi2_inv_smalldf():\n assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3)\n\n\ndef test_agm_simple():\n assert_allclose(special.agm(24, 6), 13.4581714817)\n assert_allclose(special.agm(1e30, 1), 2.2292230559453832047768593e28)\n\n\ndef test_legacy():\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n\n # Legacy behavior: truncating arguments to integers\n assert_equal(special.bdtrc(1, 2, 0.3), special.bdtrc(1.8, 2.8, 0.3))\n assert_equal(special.bdtr(1, 2, 0.3), special.bdtr(1.8, 2.8, 0.3))\n assert_equal(special.bdtri(1, 2, 0.3), special.bdtri(1.8, 2.8, 0.3))\n assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3))\n assert_equal(special.hyp2f0(1, 2, 0.3, 1), special.hyp2f0(1, 2, 0.3, 1.8))\n assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3))\n assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3))\n assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3))\n assert_equal(special.pdtrc(1, 0.3), special.pdtrc(1.8, 0.3))\n assert_equal(special.pdtr(1, 0.3), special.pdtr(1.8, 0.3))\n assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3))\n assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3))\n assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3))\n assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3))\n assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3))\n\n\n@with_special_errors\ndef test_error_raising():\n assert_raises(special.SpecialFunctionWarning, special.iv, 1, 1e99j)\n\n\ndef test_xlogy():\n def xfunc(x, y):\n if x == 0 and not np.isnan(y):\n return x\n else:\n return x*np.log(y)\n\n z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float)\n z2 = np.r_[z1, [(0, 1j), (1, 1j)]]\n\n w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])\n assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13)\n w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1])\n assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13)\n\n\ndef test_xlog1py():\n def xfunc(x, y):\n if x == 0 and not np.isnan(y):\n return x\n else:\n return x * np.log1p(y)\n\n z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0),\n (1, 1e-30)], dtype=float)\n w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])\n assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13)\n\n\ndef test_entr():\n def xfunc(x):\n if x < 0:\n return -np.inf\n else:\n return -special.xlogy(x, x)\n values = (0, 0.5, 1.0, np.inf)\n signs = [-1, 1]\n arr = []\n for sgn, v in itertools.product(signs, values):\n arr.append(sgn * v)\n z = np.array(arr, dtype=float)\n w = np.vectorize(xfunc, otypes=[np.float64])(z)\n assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13)\n\n\ndef test_kl_div():\n def xfunc(x, y):\n if x < 0 or y < 0 or (y == 0 and x != 0):\n # extension of natural domain to preserve convexity\n return np.inf\n elif np.isposinf(x) or np.isposinf(y):\n # limits within the natural domain\n return np.inf\n elif x == 0:\n return y\n else:\n return special.xlogy(x, x/y) - x + y\n values = (0, 0.5, 1.0)\n signs = [-1, 1]\n arr = []\n for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):\n arr.append((sgna*va, sgnb*vb))\n z = np.array(arr, dtype=float)\n w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])\n assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13)\n\n\ndef test_rel_entr():\n def xfunc(x, y):\n if x > 0 and y > 0:\n return special.xlogy(x, x/y)\n elif x == 0 and y >= 0:\n return 0\n else:\n return np.inf\n values = (0, 0.5, 1.0)\n signs = [-1, 1]\n arr = []\n for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):\n arr.append((sgna*va, sgnb*vb))\n z = np.array(arr, dtype=float)\n w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])\n assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13)\n\n\ndef test_huber():\n assert_equal(special.huber(-1, 1.5), np.inf)\n assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5))\n assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2))\n\n def xfunc(delta, r):\n if delta < 0:\n return np.inf\n elif np.abs(r) < delta:\n return 0.5 * np.square(r)\n else:\n return delta * (np.abs(r) - 0.5 * delta)\n\n z = np.random.randn(10, 2)\n w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])\n assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13)\n\n\ndef test_pseudo_huber():\n def xfunc(delta, r):\n if delta < 0:\n return np.inf\n elif (not delta) or (not r):\n return 0\n else:\n return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1)\n\n z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]])\n w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])\n assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n" ]
[ [ "scipy.special.ivp", "scipy.special._ufuncs.i1", "scipy.special.k1e", "scipy.special._ufuncs.ndtri", "scipy.special.hankel1", "numpy.sin", "scipy.special.berp", "scipy.special._ufuncs.zeta", "scipy.special.it2j0y0", "scipy.special._testutils.assert_tol_equal", "scipy.special._ufuncs.gammasgn", "scipy.special._ufuncs.dawsn", "scipy.special._ufuncs.chndtrinc", "scipy.special.pbdv", "scipy.special._ufuncs.pdtri", "scipy.special.polygamma", "scipy.special.sph_jn", "scipy.special.ellipe", "scipy.special.kvp", "scipy.special._ufuncs.nbdtri", "scipy.special.kerp_zeros", "scipy.special.agm", "scipy.special.genlaguerre", "scipy.special.fresnelc_zeros", "scipy.special._ufuncs.yve", "scipy.special._ufuncs.shichi", "scipy.special.y1p_zeros", "scipy.special.riccati_jn", "scipy.special.hankel2", "scipy.special._ufuncs.cbrt", "scipy.special._ufuncs.itairy", "scipy.special._ufuncs.rgamma", "scipy.special._ufuncs.kelvin", "scipy.special._ufuncs.pdtrik", "scipy.special._ufuncs.bdtrin", "scipy.special._ufuncs.jv", "scipy.special._ufuncs.obl_cv", "scipy.special._ufuncs.chndtrix", "numpy.tan", "scipy.special.kelvin", "numpy.random.rand", "scipy.special.xlogy", "scipy.special._ufuncs.hyp2f0", "scipy.special._ufuncs.pbdv", "scipy.special.sinc", "scipy.special._ufuncs.modstruve", "scipy.special._ufuncs.round", "scipy.special.ellipeinc", "scipy.special._ufuncs.chndtr", "numpy.sinh", "scipy.special.comb", "numpy.vectorize", "scipy.special._ufuncs.exp2", "scipy.special._ufuncs.nrdtrisd", "scipy.special.sph_in", "scipy.special.pdtrc", "scipy.special.jve", "scipy.special.nbdtrc", "scipy.special._ufuncs.pro_ang1", "scipy.special._ufuncs.chdtri", "scipy.special.ker", "scipy.special.gamma", "scipy.special._ufuncs.chdtrc", "scipy.special.ellipkinc", "numpy.isnan", "scipy.special.chdtri", "scipy.special._ufuncs.k1", "scipy.special._ufuncs.mathieu_modcem2", "scipy.special._ufuncs.kv", "scipy.special._ufuncs.btdtrib", "scipy.special.struve", "scipy.special.y0", "scipy.special.cosm1", "scipy.special.hyp2f1", "scipy.special.lpmv", "scipy.special.expm1", "numpy.random.pareto", "scipy.special.i1", "scipy.special._ufuncs.cotdg", "scipy.special._ufuncs.kn", "scipy.special._ufuncs.sici", "scipy.special._ufuncs.kolmogi", "numpy.testing.assert_almost_equal", "scipy.special._ufuncs.btdtria", "scipy.special._ufuncs.erf", "scipy.special.ellipj", "scipy.special._ufuncs.bei", "scipy.special.sindg", "scipy.special._ufuncs.kei", "scipy.special._ufuncs.obl_rad1_cv", "scipy.special._ufuncs.itmodstruve0", "scipy.special._ufuncs.yn", "numpy.isfinite", "scipy.special.chdtr", "scipy.special._ufuncs.betaincinv", "numpy.row_stack", "scipy.special._ufuncs.spence", "scipy.special.ber_zeros", "scipy.special.berp_zeros", "scipy.special.rgamma", "scipy.special.pdtr", "numpy.testing.assert_approx_equal", "scipy.special._ufuncs.binom", "scipy.special.k0e", "scipy.special._ufuncs.kve", "scipy.special._ufuncs.sindg", "numpy.square", "scipy.special._ufuncs.erfi", "scipy.special.nbdtr", "scipy.special._ufuncs.fresnel", "scipy.special._ufuncs.airye", "scipy.special.airy", "numpy.zeros", "numpy.log", "scipy.special.exp10", "scipy.special._ufuncs.iv", "scipy.special._ufuncs.chdtr", "scipy.special._ufuncs.hyperu", "scipy.special._ufuncs.obl_rad2", "scipy.special.yn_zeros", "scipy.special._ufuncs.it2j0y0", "scipy.special.smirnov", "numpy.nan_to_num", "numpy.seterr", "scipy.special.h1vp", "scipy.special.kn", "scipy.special._ufuncs.beta", "scipy.special._ufuncs.k0e", "scipy.special.yn", "scipy.special._ufuncs.gdtrc", "scipy.special.jvp", "scipy.special.jnp_zeros", "scipy.special.exp2", "scipy.special.log1p", "scipy.special.jnjnp_zeros", "numpy.testing.run_module_suite", "numpy.isposinf", "scipy.special.legendre", "scipy.special._ufuncs.nbdtrik", "scipy.special._ufuncs.nctdtridf", "scipy.special.lmbda", "scipy.special._ufuncs.tklmbda", "numpy.linspace", "scipy.special.gammainc", "scipy.special._ufuncs.modfresnelm", "scipy.special._ufuncs.i1e", "scipy.special._ufuncs.exp1", "scipy.special._ufuncs.ellipeinc", "numpy.testing.assert_equal", "scipy.special._ufuncs.hyp3f0", "scipy.special.lqmn", "scipy.special._ufuncs.chdtriv", "scipy.special._ufuncs.yv", "scipy.special.clpmn", "scipy.special.obl_cv_seq", "scipy.special.itj0y0", "scipy.special.fresnel", "scipy.special._ufuncs.nbdtrin", "scipy.special.perm", "scipy.special.it2i0k0", "numpy.cos", "scipy.special.tandg", "scipy.special.bdtr", "scipy.special._ufuncs.bdtrc", "scipy.special._ufuncs.log1p", "scipy.special.keip", "scipy.special._ufuncs.gammaincc", "scipy.special._ufuncs.kolmogorov", "scipy.special.hyp2f0", "numpy.random.randn", "scipy.special.smirnovi", "scipy.special.lpn", "scipy.special._ufuncs.zetac", "numpy.finfo", "scipy.special.euler", "scipy.special.erf_zeros", "scipy.special.hankel1e", "scipy.special._ufuncs.pdtrc", "scipy.special.yve", "scipy.special.erf", "scipy.special.factorial2", "scipy.special.hyp1f1", "scipy.special._ufuncs.hankel2e", "scipy.special._ufuncs.stdtrit", "scipy.special._ufuncs.nctdtrinc", "scipy.special.betaln", "scipy.special.bdtri", "scipy.special.lqn", "scipy.special._ufuncs.exp10", "scipy.special._ufuncs.itj0y0", "numpy.random.random", "scipy.special._ufuncs.nctdtrit", "scipy.special.kelvin_zeros", "scipy.special._ufuncs.betaln", "scipy.special.expn", "scipy.special._ufuncs.y0", "scipy.special.j1", "scipy.special._ufuncs.gammaln", "scipy.special.pdtri", "numpy.sqrt", "scipy.special.airye", "scipy.special.erfinv", "scipy.special.hyp0f1", "scipy.special.chdtrc", "scipy.special._ufuncs.jve", "scipy.special.yv", "scipy.special._ufuncs.btdtri", "scipy.special.beip", "scipy.special._ufuncs.y1", "numpy.log1p", "scipy.special._ufuncs.obl_rad1", "scipy.special._ufuncs.beip", "scipy.special._ufuncs.pro_cv", "scipy.special._ufuncs.stdtridf", "scipy.special.gammaln", "scipy.special._ufuncs.fdtrc", "scipy.special._ufuncs.ncfdtri", "scipy.special.psi", "scipy.special._ufuncs.keip", "numpy.testing.assert_array_equal", "scipy.special.ai_zeros", "scipy.special._ufuncs.mathieu_a", "scipy.special._ufuncs.mathieu_modcem1", "scipy.special.ive", "scipy.special._ufuncs.gdtrib", "scipy.special._ufuncs.ber", "scipy.special._ufuncs.gdtrix", "numpy.arctan", "numpy.nextafter", "scipy.special.sph_inkn", "scipy.special._ufuncs.pro_ang1_cv", "scipy.special._ufuncs.nrdtrimn", "scipy.special._ufuncs.expm1", "numpy.argmax", "scipy.special._ufuncs.radian", "scipy.special._ufuncs.stdtr", "scipy.special._ufuncs.smirnovi", "scipy.special.pbdn_seq", "scipy.special.cotdg", "scipy.special.betainc", "scipy.special.diric", "scipy.special.laguerre", "numpy.cosh", "scipy.special.riccati_yn", "numpy.int64", "scipy.special._ufuncs.it2i0k0", "scipy.special.k0", "scipy.special.ker_zeros", "scipy.special.jn", "scipy.special._ufuncs.hankel2", "scipy.special._ufuncs.k1e", "scipy.special._ufuncs.ncfdtr", "scipy.special._ufuncs.pro_rad2_cv", "scipy.special._ufuncs.mathieu_b", "scipy.special._ufuncs.it2struve0", "scipy.special.yvp", "scipy.special.ellipk", "scipy.special._ufuncs.ndtr", "scipy.special.bei", "scipy.special.k1", "scipy.special._ufuncs.pbwa", "scipy.special._ufuncs.obl_ang1_cv", "scipy.special.sph_kn", "scipy.special.gammainccinv", "numpy.testing.assert_array_almost_equal", "scipy.special.fresnels_zeros", "numpy.logspace", "scipy.special.i0", "scipy.special._ufuncs.fdtr", "numpy.testing.assert_allclose", "numpy.broadcast_arrays", "scipy.special.ber", "scipy.special._ufuncs.itstruve0", "scipy.special._ufuncs.bdtri", "scipy.special.sph_yn", "scipy.special.round", "scipy.special.kei_zeros", "scipy.special.kv", "scipy.special._ufuncs.iti0k0", "scipy.special._ufuncs.cosdg", "scipy.special.cosdg", "numpy.dtype", "scipy.special.hankel2e", "scipy.special._ufuncs.airy", "scipy.special._ufuncs.kerp", "scipy.special._ufuncs.hyp1f2", "scipy.special.pbvv", "scipy.special.keip_zeros", "scipy.special.betaincinv", "scipy.special._ufuncs.ive", "scipy.special.h2vp", "scipy.special.pbdv_seq", "scipy.special._ufuncs.j0", "scipy.special._ufuncs.pbvv", "scipy.special._ufuncs.pdtr", "scipy.special._ufuncs.besselpoly", "scipy.special._ufuncs.mathieu_modsem2", "scipy.special._ufuncs.modfresnelp", "scipy.special._ufuncs.pro_rad2", "scipy.special._ufuncs.fdtri", "scipy.special._ufuncs.bdtr", "scipy.special.huber", "scipy.special._ufuncs.hankel1e", "scipy.special.bi_zeros", "scipy.special._ufuncs.berp", "scipy.special._testutils.assert_func_equal", "scipy.special.assoc_laguerre", "numpy.exp", "scipy.special.i0e", "scipy.special._ufuncs.betainc", "scipy.special.sph_harm", "scipy.special.kei", "scipy.special.fresnel_zeros", "numpy.real", "scipy.special.iv", "scipy.special.i1e", "scipy.special.iti0k0", "scipy.special._ufuncs.k0", "scipy.special.factorialk", "numpy.testing.assert_raises", "numpy.array", "scipy.special._ufuncs.gdtr", "scipy.special._ufuncs.gammainc", "numpy.isinf", "scipy.special.gammaincinv", "numpy.asarray", "scipy.special._ufuncs.gammainccinv", "scipy.special._ufuncs.smirnov", "scipy.special.y0_zeros", "scipy.special.jacobi", "scipy.special._ufuncs.obl_rad2_cv", "scipy.special.gammaincc", "scipy.special._ufuncs.mathieu_sem", "scipy.special.y1", "scipy.special.beip_zeros", "scipy.special.factorial", "scipy.special._ufuncs.erfc", "scipy.special._ufuncs.obl_ang1", "scipy.special._ufuncs.mathieu_cem", "scipy.special._ufuncs.mathieu_modsem1", "scipy.special.nbdtri", "scipy.special._ufuncs.ker", "scipy.special._ufuncs.ncfdtridfn", "scipy.special._ufuncs.ellipj", "scipy.special._ufuncs.gamma", "numpy.testing.assert_", "scipy.special._ufuncs.pro_rad1_cv", "scipy.special.sph_jnyn", "scipy.special.bernoulli", "scipy.special._ufuncs.gdtria", "scipy.special._ufuncs.i0e", "scipy.special._ufuncs.j1", "scipy.special.cbrt", "scipy.special._ufuncs.jn", "scipy.special.kve", "numpy.random.randint", "scipy.special.y1_zeros", "scipy.special._ufuncs.ellipkinc", "scipy.special.lpmn", "scipy.special._ufuncs.psi", "scipy.special.kerp", "scipy.special._ufuncs.nbdtr", "scipy.special.jv", "scipy.special._ufuncs.fdtridfd", "scipy.special.ellipkm1", "scipy.special.errprint", "scipy.special.bei_zeros", "scipy.special._ufuncs.chndtridf", "scipy.special.beta", "scipy.special._ufuncs.ncfdtridfd", "scipy.special._ufuncs.hankel1", "scipy.special._ufuncs.hyp1f1", "scipy.special._ufuncs.nctdtr", "scipy.special._ufuncs.i0", "scipy.special.jn_zeros", "scipy.special.mathieu_even_coef", "scipy.special._ufuncs.tandg", "scipy.special._ufuncs.ncfdtrinc", "scipy.special.ynp_zeros", "scipy.special._ufuncs.ellipe", "numpy.ones_like", "numpy.arange", "scipy.special._ufuncs.pro_rad1", "scipy.special._ufuncs.expi", "scipy.special._ufuncs.expn", "scipy.special._ufuncs.nbdtrc", "scipy.special._ufuncs.cosm1", "scipy.special._ufuncs.bdtrik", "scipy.special.pro_cv_seq", "scipy.special.hyperu", "scipy.special._ufuncs.btdtr", "scipy.special.radian", "scipy.special.j0", "scipy.special._ufuncs.struve", "scipy.special.bdtrc", "numpy.abs", "numpy.random.seed", "scipy.special._ufuncs.hyp2f1", "scipy.special._ufuncs.lpmv", "scipy.special.erfcinv", "scipy.special.jnyn_zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "1.4", "1.3", "0.19", "0.18", "1.2", "0.12", "1.0", "0.17", "0.16" ], "tensorflow": [] } ]
haataa/disaster-response-pipline
[ "1521eefff2347caec60506fa11cc00b8e39edc13" ]
[ "app/run.py" ]
[ "import json\nimport plotly\nimport pandas as pd\n\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nfrom sklearn.externals import joblib\nfrom sqlalchemy import create_engine\n\n\napp = Flask(__name__)\n\ndef tokenize(text):\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///../data/DisasterResponse.db')\ndf = pd.read_sql_table('messages', engine)\n\n# load model\nmodel = joblib.load(\"../models/classifier.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\[email protected]('/')\[email protected]('/index')\ndef index():\n \n # extract data needed for visuals\n # TODO: Below is an example - modify to extract data for your own visuals\n request_counts = df.groupby('request').count()['message']\n request_names = list(request_counts.index)\n \n genre_counts = df.groupby('genre').count()['message']\n genre_names = list(genre_counts.index)\n \n offer_counts = df.groupby('offer').count()['message']\n offer_names = list(offer_counts.index)\n \n # create visuals\n # TODO: Below is an example - modify to create your own visuals\n graphs = [\n {\n 'data': [\n Bar(\n x=request_names,\n y=request_counts\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Request',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Request\"\n }\n }\n },\n {\n 'data': [\n Bar(\n x=genre_names,\n y=genre_counts\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Genres',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Genres\"\n }\n }\n },\n {\n 'data': [\n Bar(\n x=offer_names,\n y=offer_counts\n )\n ],\n\n 'layout': {\n 'title': 'Proportion of Messages by offer',\n 'yaxis': {\n 'title': \"Proportion\"\n },\n 'xaxis': {\n 'title': \"Offer\"\n }\n }\n }\n \n ]\n \n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n \n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\[email protected]('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '') \n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file. \n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\n\ndef main():\n app.run(host='0.0.0.0', port=6016, debug=True)\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "pandas.read_sql_table", "sklearn.externals.joblib.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
albertocarpentieri/executors
[ "3b025b6106fca9dba3c2569b0e60da050273fa6e" ]
[ "jinahub/encoders/audio/VGGISHAudioEncoder/executor/vggish_audio_encoder.py" ]
[ "__copyright__ = \"Copyright (c) 2021 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport os\nfrom pathlib import Path\nfrom typing import Iterable, Optional\n\nimport numpy as np\nimport requests as _requests\nimport tensorflow as tf\nfrom jina import DocumentArray, Executor, requests\nfrom jina.logging.logger import JinaLogger\n\nfrom .vggish.vggish_params import INPUT_TENSOR_NAME, OUTPUT_TENSOR_NAME\nfrom .vggish.vggish_postprocess import Postprocessor\nfrom .vggish.vggish_slim import define_vggish_slim, load_vggish_slim_checkpoint\n\ntf.compat.v1.disable_eager_execution()\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\nclass VggishAudioEncoder(Executor):\n \"\"\"\n Encode audio data with Vggish embeddings\n \"\"\"\n\n def __init__(\n self,\n model_path: str = Path(cur_dir) / 'models',\n traversal_paths: Optional[Iterable[str]] = None,\n device: str = '/CPU:0',\n *args,\n **kwargs,\n ):\n \"\"\"\n :param model_path: path of the models directory. The directory should contain\n 'vggish_model.ckpt' and 'vggish_pca_params.ckpt'. Setting this to a new directory\n will download the files.\n :param traversal_paths: fallback batch size in case there is not\n batch size sent in the request\n :param device: device to run the model on e.g. '/CPU:0','/GPU:0','/GPU:2'\n \"\"\"\n\n super().__init__(*args, **kwargs)\n self.traversal_paths = traversal_paths or ['r']\n self.logger = JinaLogger(self.__class__.__name__)\n self.device = device\n self.model_path = Path(model_path)\n self.vgg_model_path = self.model_path / 'vggish_model.ckpt'\n self.pca_model_path = self.model_path / 'vggish_pca_params.ckpt'\n self.model_path.mkdir(\n exist_ok=True\n ) # Create the model directory if it does not exist yet\n\n cpus = tf.config.experimental.list_physical_devices(device_type='CPU')\n gpus = tf.config.experimental.list_physical_devices(device_type='GPU')\n if 'GPU' in device:\n gpu_index = 0 if 'GPU:' not in device else int(device.split(':')[-1])\n if len(gpus) < gpu_index + 1:\n raise RuntimeError(f'Device {device} not found on your system!')\n cpus.append(gpus[gpu_index])\n tf.config.experimental.set_visible_devices(devices=cpus)\n\n if not self.vgg_model_path.exists():\n self.logger.info(\n 'VGGish model cannot be found from the given model path, '\n 'downloading a new one...'\n )\n try:\n r = _requests.get(\n 'https://storage.googleapis.com/audioset/vggish_model.ckpt'\n )\n r.raise_for_status()\n except _requests.exceptions.HTTPError:\n self.logger.error(\n 'received HTTP error response, cannot download vggish model'\n )\n raise\n except _requests.exceptions.RequestException:\n self.logger.error('Connection error, cannot download vggish model')\n raise\n\n with open(self.vgg_model_path, 'wb') as f:\n f.write(r.content)\n\n if not self.pca_model_path.exists():\n self.logger.info(\n 'PCA model cannot be found from the given model path, '\n 'downloading a new one...'\n )\n try:\n r = _requests.get(\n 'https://storage.googleapis.com/audioset/vggish_pca_params.npz'\n )\n r.raise_for_status()\n except _requests.exceptions.HTTPError:\n self.logger.error(\n 'received HTTP error response, cannot download pca model'\n )\n raise\n except _requests.exceptions.RequestException:\n self.logger.error('Connection error, cannot download pca model')\n raise\n\n with open(self.pca_model_path, 'wb') as f:\n f.write(r.content)\n\n self.sess = tf.compat.v1.Session()\n define_vggish_slim()\n load_vggish_slim_checkpoint(self.sess, str(self.vgg_model_path))\n self.feature_tensor = self.sess.graph.get_tensor_by_name(INPUT_TENSOR_NAME)\n self.embedding_tensor = self.sess.graph.get_tensor_by_name(OUTPUT_TENSOR_NAME)\n self.post_processor = Postprocessor(str(self.pca_model_path))\n\n @requests\n def encode(self, docs: Optional[DocumentArray], parameters: dict, **kwargs):\n \"\"\"\n Compute embeddings and store them in the `docs` array.\n\n :param docs: documents sent to the encoder. The docs must have `text`.\n By default, the input `text` must be a `list` of `str`.\n :param parameters: dictionary to define the `traversal_paths` and the\n `batch_size`. For example, `parameters={'traversal_paths': ['r'],\n 'batch_size': 10}`.\n :param kwargs: Additional key value arguments.\n :return:\n \"\"\"\n if docs:\n cleaned_document_array = self._get_input_data(docs, parameters)\n self._create_embeddings(cleaned_document_array)\n\n def _get_input_data(self, docs: DocumentArray, parameters: dict):\n \"\"\"Create a filtered set of Documents to iterate over.\"\"\"\n\n traversal_paths = parameters.get('traversal_paths', self.traversal_paths)\n\n # traverse thought all documents which have to be processed\n flat_docs = docs.traverse_flat(traversal_paths)\n\n # filter out documents without images\n filtered_docs = DocumentArray(\n [doc for doc in flat_docs if doc.blob is not None]\n )\n\n return filtered_docs\n\n def _create_embeddings(self, filtered_docs: Iterable):\n \"\"\"Update the documents with the embeddings generated by VGGISH\"\"\"\n\n for d in filtered_docs:\n # Vggish broadcasts across different length audios, not batches\n [embedding] = self.sess.run(\n [self.embedding_tensor], feed_dict={self.feature_tensor: d.blob}\n )\n result = self.post_processor.postprocess(embedding)\n d.embedding = np.mean((np.float32(result) - 128.0) / 128.0, axis=0)\n\n def close(self):\n self.sess.close()\n" ]
[ [ "tensorflow.config.experimental.list_physical_devices", "tensorflow.compat.v1.Session", "numpy.float32", "tensorflow.compat.v1.disable_eager_execution", "tensorflow.config.experimental.set_visible_devices" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hboyan/yellowbrick
[ "34e9c33cd6bcb74146826aac34e707e290afc18b" ]
[ "examples/examples.py" ]
[ "#!/usr/bin/env python\n# Ben's scratchpad for testing\n\n## Imports\nimport os\nimport pandas as pd\nimport yellowbrick as yb\nimport matplotlib.pyplot as plt\n\nfrom pandas.tools.plotting import radviz, parallel_coordinates\nfrom yellowbrick.features import ParallelCoordinates, RadViz, Rank2D\n\n## Module Constants - the path to the test data sets\nFIXTURES = os.path.join(os.path.dirname(__file__), \"examples\", \"data\")\n\n## Dataset loading mechanisms\ndatasets = {\n \"credit\": os.path.join(FIXTURES, \"credit.xls\"),\n \"concrete\": os.path.join(FIXTURES, \"concrete.xls\"),\n \"occupancy\": os.path.join(FIXTURES, 'occupancy', 'datatraining.txt'),\n}\n\n## Human readable column names\ncolumns = {\n \"credit\": [\n 'id', 'limit', 'sex', 'edu', 'married', 'age', 'apr_delay', 'may_delay',\n 'jun_delay', 'jul_delay', 'aug_delay', 'sep_delay', 'apr_bill', 'may_bill',\n 'jun_bill', 'jul_bill', 'aug_bill', 'sep_bill', 'apr_pay', 'may_pay', 'jun_pay',\n 'jul_pay', 'aug_pay', 'sep_pay', 'default'\n ],\n \"concrete\": [\n 'cement', 'slag', 'ash', 'water', 'splast',\n 'coarse', 'fine', 'age', 'strength'\n ],\n \"occupancy\": [\n 'date', 'temp', 'humid', 'light', 'co2', 'hratio', 'occupied'\n ],\n}\n\n\ndef load_data(name):\n \"\"\"\n Loads and wrangls the passed in dataset.\n \"\"\"\n\n path = datasets[name]\n data = {\n 'credit': lambda p: pd.read_excel(p, header=1),\n 'concrete': lambda p: pd.read_excel(p),\n 'occupancy': lambda p: pd.read_csv(p),\n }[name](path)\n\n data.columns = columns[name]\n return data\n\n\ndef test_parallel_coords(pandas=False, outpath=None):\n \"\"\"\n Runs the parallel coordinates visualizer on the dataset.\n\n Parameters\n ----------\n pandas : bool\n Run the pandas version of the function\n outpath : path or None\n Save the figure to disk rather than show (if None)\n \"\"\"\n data = load_data('occupancy') # Load the data\n features = ['temp', 'humid', 'light', 'co2', 'hratio']\n classes = ['unoccupied', 'occupied']\n X = data[features].as_matrix()\n y = data.occupied.as_matrix()\n\n if pandas:\n parallel_coordinates(data[features + ['occupied']], 'occupied')\n if outpath:\n plt.savefig(outpath)\n else:\n plt.show()\n\n else:\n visualizer = ParallelCoordinates( # Instantiate the visualizer\n classes=classes, features=features\n )\n visualizer.fit(X, y) # Fit the data to the visualizer\n visualizer.transform(X) # Transform the data\n visualizer.poof(outpath=outpath) # Draw/show/poof the data\n\n\ndef test_radviz(pandas=False, outpath=None):\n \"\"\"\n Runs the radviz visualizer on the dataset.\n\n Parameters\n ----------\n pandas : bool\n Run the pandas version of the function\n outpath : path or None\n Save the figure to disk rather than show (if None)\n \"\"\"\n data = load_data('occupancy') # Load the data\n features = ['temp', 'humid', 'light', 'co2', 'hratio']\n classes = ['unoccupied', 'occupied']\n X = data[features].as_matrix()\n y = data.occupied.as_matrix()\n\n if pandas:\n radviz(data[features + ['occupied']], 'occupied')\n if outpath:\n plt.savefig(outpath)\n else:\n plt.show()\n\n else:\n visualizer = RadViz( # Instantiate the visualizer\n classes=classes, features=features\n )\n visualizer.fit(X, y) # Fit the data to the visualizer\n visualizer.transform(X) # Transform the data\n visualizer.poof(outpath=outpath) # Draw/show/poof the data\n\n\ndef test_rank2d(seaborn=False, outpath=None):\n \"\"\"\n Runs the radviz visualizer on the dataset.\n\n Parameters\n ----------\n pandas : bool\n Run the pandas version of the function\n outpath : path or None\n Save the figure to disk rather than show (if None)\n \"\"\"\n data = load_data('occupancy') # Load the data\n features = ['temp', 'humid', 'light', 'co2', 'hratio']\n classes = ['unoccupied', 'occupied']\n X = data[features].as_matrix()\n y = data.occupied.as_matrix()\n\n if seaborn:\n raise NotImplementedError(\"Not yet!\")\n\n else:\n visualizer = Rank2D(features=features, algorithm='covariance')\n visualizer.fit(X, y) # Fit the data to the visualizer\n visualizer.transform(X) # Transform the data\n visualizer.poof(outpath=outpath) # Draw/show/poof the data\n\n\nif __name__ == '__main__':\n # test_parallel_coords(pandas=True)\n # test_radviz(pandas=False, outpath='/Users/benjamin/Desktop/yb_radviz.png')\n test_rank2d(outpath='/Users/benjamin/Desktop/yb_rank2d_covariance.png')\n" ]
[ [ "pandas.tools.plotting.radviz", "pandas.read_excel", "pandas.read_csv", "matplotlib.pyplot.savefig", "pandas.tools.plotting.parallel_coordinates", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.19" ], "scipy": [], "tensorflow": [] } ]
superligen/asdf
[ "8d1dd589d1fb1d9c286ade7ba787bd95c7e5e88f" ]
[ "asdf/constants.py" ]
[ "import numpy as np\n\n\nASDF_MAGIC = b'#ASDF'\nBLOCK_MAGIC = b'\\xd3BLK'\nBLOCK_HEADER_BOILERPLATE_SIZE = 6\n\nASDF_STANDARD_COMMENT = b'ASDF_STANDARD'\n\nINDEX_HEADER = b'#ASDF BLOCK INDEX'\n\n# The maximum number of blocks supported\nMAX_BLOCKS = 2 ** 16\nMAX_BLOCKS_DIGITS = int(np.ceil(np.log10(MAX_BLOCKS) + 1))\n\nYAML_TAG_PREFIX = 'tag:yaml.org,2002:'\nYAML_END_MARKER_REGEX = br'\\r?\\n\\.\\.\\.((\\r?\\n)|$)'\n\n\nSTSCI_SCHEMA_URI_BASE = 'http://stsci.edu/schemas/'\nSTSCI_SCHEMA_TAG_BASE = 'tag:stsci.edu:asdf'\n\n\nBLOCK_FLAG_STREAMED = 0x1\n\n# All arrays shorter than this default to inline storage.\nDEFAULT_AUTO_INLINE = 100\n" ]
[ [ "numpy.log10" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CovingtonResearchGroup/CaveXC
[ "5d6c2f7cfee269941219cd1aa19f4d2255cfa5e1" ]
[ "CrossSection.py" ]
[ "from numpy import sin, cos, pi, fabs, sign, roll, arctan2, diff, cumsum, hypot, logical_and, where, linspace\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\n\n# Cross-section class that stores x, y points for the cross-section\n# and calculates various geometry data\n\nd = 1000\n\nclass CrossSection:\n\n\t# Number of points that define the cross-section\n\n\tdef __init__(self, x, y):\n\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.roll()\n\n\t# Sets the point of maximum velocity\n\tdef setUMPoint(self, umx, umy):\n\n\t\tself.umx = umx\n\t\tself.umy = umy\n\n\t# Create arrays of x+1, y+1, x-1, x+1\n\tdef roll(self):\n\n\t\tself.xm = roll(self.x, 1)\n\t\tself.ym = roll(self.y, 1)\n\t\tself.xp = roll(self.x, self.x.size-1)\n\t\tself.yp = roll(self.y, self.y.size-1)\n\n\t# Calculate perimeter and area\n\tdef calcShapeParams(self):\n\n\t\tself.genL()\n\t\tself.calcA()\n\n\t# l stores difference between each perimeter point\n\t# pp is the length along perimeter to a point\n\t# pp[-2] is the channel perimeter\n\tdef genL(self):\n\n\t\tself.l = hypot(self.x - self.xp, self.y - self.yp)\n\t\tself.pp = cumsum(self.l)\n\t\tself.P = self.pp[-2]\n\n\t# Calculates area of the cross-section\n\tdef calcA(self):\n\n\t\tself.sA = (self.xm*self.y - self.x*self.ym).sum() * 0.5\n\t\tself.A = fabs(self.sA)\n\n\t# Generate lengths from maximum velocity point to perimeter points\n\tdef genRL(self):\n\n\t\tself.r_l = hypot(self.x-self.umx, self.y-self.umy)\n\n\t# Find left and right points defining a height above the cross-section\n\t# bottom\n\tdef findLR(self, h):\n\n\t\tymin = self.y.min()\n\t\ta_h = ymin + h\n\n\t\tcondL = logical_and(self.y > a_h, a_h > self.yp)\n\t\tcondR = logical_and(self.y < a_h, a_h < self.yp)\n\n\t\tL = where(condL)[0][0] + 1\n\t\tR = where(condR)[0][0]\n\t\treturn L,R\n\n\t# Find centroid, maximum velocity position in phreatic cases\n\tdef findCentroid(self):\n\n\t\tm = self.xm*self.y-self.x*self.ym\n\t\tcx = (1/(6*self.sA))*((self.x + self.xm)*m).sum()\n\t\tcy = (1/(6*self.sA))*((self.y + self.ym)*m).sum()\n\n\t\treturn cx, cy\n\n\t# Redraw some length rl away normal to the perimeter\n\t# It may be advantageous for stability to resample using a spline fit\n\t# Setting dl sets the number of points defining the cross-section\n\t## after resampling.\n\tdef redraw(self, rl, resample=False, dl=d):\n\n\t\talpha = arctan2(self.xp-self.xm, self.yp-self.ym)\n\n\t\tnx = self.x + sign(self.x)*rl*cos(alpha)\n\t\tny = self.y - sign(self.x)*rl*sin(alpha)\n\n\t\t# Check if we drew inside or outside..\n\t\tc = ccw(self.x, self.y, self.xm, self.ym, nx, ny)\n\n\t\tnx[c] = (self.x - sign(self.x)*rl*cos(alpha))[c]\n\t\tny[c] = (self.y + sign(self.x)*rl*sin(alpha))[c]\n\n\t\t#Resample points by fitting spline\n\t\tif resample:\n\t\t\ttck, u = interpolate.splprep([nx, ny], u=None, k=1, s=0.0)\n\t\t\tun = linspace(u.min(), u.max(), dl if dl!=nx.size else nx.size)\n\t\t\tnx, ny = interpolate.splev(un, tck, der=0)\n\n\n\t\t# New coordinates\n\t\ty_roll = ny.size - ny.argmax()\n\t\tnx = roll(nx, y_roll)\n\t\tny = roll(ny, y_roll)\n\t\tself.x = nx\n\t\tself.y = ny\n\t\tself.roll()\n\n\n# Counter clockwise function to determine if we drew points in the correct\n# direction\ndef ccw(x, y, xm, ym, nx, ny):\n\n\t return (x - xm) * (ny - ym) > (y - ym) * (nx - xm)\n\n# Calculate length of curve defined by points\ndef calcL(x,y):\n\tsub_lengths = hypot(x[1:] - x[:-1], y[1:] - y[:-1])\n\tsub_sums = cumsum(sub_lengths)\n\tlength = sub_sums[-1]\n\treturn length\n" ]
[ [ "numpy.fabs", "scipy.interpolate.splprep", "numpy.cumsum", "numpy.cos", "scipy.interpolate.splev", "numpy.arctan2", "numpy.sin", "numpy.sign", "numpy.logical_and", "numpy.where", "numpy.roll", "numpy.hypot" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
aliang-rec/FuxiCTR
[ "15fd0460508715fda52c17f80463655f729f6baa" ]
[ "fuxictr/pytorch/models/FiGNN.py" ]
[ "# =========================================================================\n# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.\n# Copyright (C) 2021. Tsinghua University. All rights reserved.\n#\n# Authors: Kelong Mao <Tsinghua University>\n# Jieming Zhu <Huawei Noah's Ark Lab>\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =========================================================================\n\nimport torch\nfrom torch import nn\nfrom fuxictr.pytorch.models import BaseModel\nfrom fuxictr.pytorch.layers import EmbeddingLayer, FiGNN_Layer\n\n\nclass FiGNN(BaseModel):\n def __init__(self, \n feature_map, \n model_id=\"FiGNN\", \n gpu=-1, \n task=\"binary_classification\", \n learning_rate=1e-3, \n embedding_dim=10, \n gnn_layers=3,\n use_residual=True,\n use_gru=True,\n reuse_graph_layer=False,\n embedding_regularizer=None,\n net_regularizer=None,\n **kwargs):\n super(FiGNN, self).__init__(feature_map, \n model_id=model_id, \n gpu=gpu, \n embedding_regularizer=embedding_regularizer,\n net_regularizer=net_regularizer,\n **kwargs)\n self.embedding_dim = embedding_dim\n self.num_fields = feature_map.num_fields\n self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)\n self.fignn = FiGNN_Layer(self.num_fields, \n self.embedding_dim,\n gnn_layers=gnn_layers,\n reuse_graph_layer=reuse_graph_layer,\n use_gru=use_gru,\n use_residual=use_residual,\n device=self.device)\n self.fc = AttentionalPrediction(self.num_fields, embedding_dim)\n self.output_activation = self.get_output_activation(task)\n self.compile(kwargs[\"optimizer\"], loss=kwargs[\"loss\"], lr=learning_rate)\n self.reset_parameters()\n self.model_to_device()\n \n def forward(self, inputs):\n X, y = self.inputs_to_device(inputs)\n feature_emb = self.embedding_layer(X)\n h_out = self.fignn(feature_emb)\n y_pred = self.fc(h_out)\n if self.output_activation is not None:\n y_pred = self.output_activation(y_pred)\n return_dict = {\"y_true\": y, \"y_pred\": y_pred}\n return return_dict\n\n\nclass AttentionalPrediction(nn.Module):\n def __init__(self, num_fields, embedding_dim):\n super(AttentionalPrediction, self).__init__()\n self.mlp1 = nn.Linear(embedding_dim, 1, bias=False)\n self.mlp2 = nn.Sequential(nn.Linear(num_fields * embedding_dim, num_fields, bias=False),\n nn.Sigmoid())\n\n def forward(self, h):\n score = self.mlp1(h).squeeze(-1) # b x f\n weight = self.mlp2(h.flatten(start_dim=1)) # b x f\n logit = (weight * score).sum(dim=1).unsqueeze(-1)\n return logit\n" ]
[ [ "torch.nn.Linear", "torch.nn.Sigmoid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Jiayuan-Gu/maskrcnn-benchmark
[ "7282f554886b1885357e7e0e73d2b4000c60642b" ]
[ "maskrcnn_benchmark/modeling/balanced_positive_negative_sampler.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport torch\n\n\nclass BalancedPositiveNegativeSampler(object):\n \"\"\"\n This class samples batches, ensuring that they contain a fixed proportion of positives\n \"\"\"\n\n def __init__(self, batch_size_per_image, positive_fraction):\n \"\"\"\n Arguments:\n batch_size_per_image (int): number of elements to be selected per image\n positive_fraction (float): percentace of positive elements per batch\n \"\"\"\n self.batch_size_per_image = batch_size_per_image\n self.positive_fraction = positive_fraction\n\n def __call__(self, matched_idxs):\n \"\"\"\n Arguments:\n matched idxs: list of tensors containing -1, 0 or positive values.\n Each tensor corresponds to a specific image.\n -1 values are ignored, 0 are considered as negatives and > 0 as\n positives.\n\n Returns:\n pos_idx (list[tensor])\n neg_idx (list[tensor])\n\n Returns two lists of binary masks for each image.\n The first list contains the positive elements that were selected,\n and the second list the negative example.\n \"\"\"\n pos_idx = []\n neg_idx = []\n for matched_idxs_per_image in matched_idxs:\n positive = torch.nonzero(matched_idxs_per_image >= 1).squeeze(1)\n negative = torch.nonzero(matched_idxs_per_image == 0).squeeze(1)\n\n num_pos = int(self.batch_size_per_image * self.positive_fraction)\n # protect against not enough positive examples\n num_pos = min(positive.numel(), num_pos)\n num_neg = self.batch_size_per_image - num_pos\n # protect against not enough negative examples\n num_neg = min(negative.numel(), num_neg)\n\n # randomly select positive and negative examples\n perm1 = torch.randperm(positive.numel())[:num_pos]\n perm2 = torch.randperm(negative.numel())[:num_neg]\n\n pos_idx_per_image = positive[perm1]\n neg_idx_per_image = negative[perm2]\n\n # create binary mask from indices\n pos_idx_per_image_mask = torch.zeros_like(\n matched_idxs_per_image, dtype=torch.uint8\n )\n neg_idx_per_image_mask = torch.zeros_like(\n matched_idxs_per_image, dtype=torch.uint8\n )\n pos_idx_per_image_mask[pos_idx_per_image] = 1\n neg_idx_per_image_mask[neg_idx_per_image] = 1\n\n pos_idx.append(pos_idx_per_image_mask)\n neg_idx.append(neg_idx_per_image_mask)\n\n return pos_idx, neg_idx\n" ]
[ [ "torch.zeros_like", "torch.nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sfu-discourse-lab/SFU_Comment_Extractor
[ "27b79c79c04feca2b5458b2c2f3722877dcf7e03" ]
[ "Source_Code/CSV_creation/normalize_csv_comments.py" ]
[ "__author__ = 'Varada Kolhatkar'\nimport argparse, sys, os, glob, ntpath, pprint, codecs, re, csv\nimport pandas as pd\nimport re, html.entities\nfrom timeit import default_timer as timer\nimport string\nimport numpy as np\nimport multiprocessing as mp\nfrom multiprocessing import cpu_count\nimport re\n\n\ndef word_segmentation(text):\n '''\n :param text: (str)\n :param dictionary: (list)\n :return: (str) word segmented text\n Given a text, this code converts into word-segmented text and returns it. It retains the case, punctuation while\n doing the word segmentation.\n '''\n #dictionary = read_dictionary()\n #translator = str.maketrans('', '', string.punctuation)\n word_segmented_text = ''\n missing_space_obj = re.compile(r'(?P<prev_word>(^|\\s)\\w{3,25}[.,?!;:]{1,3})(?P<next_word>(\\w+))')\n\n def repl(m):\n return m.group('prev_word') + ' ' + m.group('next_word')\n\n # Separate words on punctuation. This will take care of following examples:\n # Rich,This => Rich, This\n #\n text = missing_space_obj.sub(repl, text)\n return text\n\ndef unescape(text):\n '''\n :param text:\n :return:\n Description\n ##\n # Removes HTML or XML character references and entities from a text string.\n #\n # @param text The HTML (or XML) source text.\n # @return The plain text, as a Unicode string, if necessary.\n # AUTHOR: Fredrik Lundh\n '''\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return chr(int(text[3:-1], 16))\n else:\n return chr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = chr(html.entities.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n\ndef clean_text(text):\n '''\n :param text:\n :return:\n '''\n text = text.strip()\n text = \" \".join(text.split())\n text = text.replace(r\"`\",r\"'\")\n text = re.sub(r'\\(In reply to:.*?--((\\s\\S+){1,10})?\\)', '', text)\n return text\n\ndef normalize(text):\n '''\n :param input_csv:\n :param output_csv:\n :param column:\n :param dictionary:\n :return:\n '''\n try:\n cleaned = clean_text(text)\n text_ws = word_segmentation(cleaned)\n text_preprocessed = unescape(text_ws)\n except:\n print('------------')\n print('Problem text: ', text)\n print('------------')\n text_preprocessed = text\n return text_preprocessed\n\ndef run_normalize(df):\n '''\n :param df:\n :return:\n '''\n df['text_preprocessed'] = df['text'].apply(normalize)\n return df\n\ndef get_arguments():\n parser = argparse.ArgumentParser(description='Write csv files for crowd annotation')\n parser.add_argument('--input_csv', '-i', type=str, dest='input_csv', action='store',\n #default='/Users/vkolhatk/Data/GnM_CSVs/intermediate_csvs/new_comments.csv',\n #default='/Users/vkolhatk/Data/GnM_CSVs/intermediate_csvs/old_comments.csv',\n default='../../Sample_Resources/Sample_Comments_CSVs/comments_csv_sample.csv',\n help=\"the input csv file\")\n\n parser.add_argument('--output_csv', '-o', type=str, dest='output_csv', action='store',\n #default='/Users/vkolhatk/Data/GnM_CSVs/intermediate_csvs/new_comments_preprocessed.csv',\n #default='/Users/vkolhatk/Data/GnM_CSVs/intermediate_csvs/old_comments_preprocessed.csv',\n default='../../Sample_Resources/Sample_Comments_CSVs/comments_csv_sample_preprocessed.csv',\n help=\"the output csv file\")\n\n parser.add_argument('--columns_to_write', '-cw', type=list, dest='cols', action='store',\n # For new comments\n #default=['article_id','comment_counter','ID','text','text_preprocessed', 'timestamp', 'TotalVotes','negVotes','posVotes','author'],\n # for old comments\n default =['article_id','comment_counter','comment_id','text','text_preprocessed','reactions','post_time','replies','author'],\n help=\"the output csv file\")\n\n #parser.add_argument('--column_to_preprocess', '-c', type=str, dest='column_name', action='store',\n # default='text',\n # help=\"the column to preprocess\")\n\n args = parser.parse_args()\n return args\n\ndef parallelize(data, func):\n data_split = np.array_split(data, partitions)\n pool = mp.Pool(cores)\n data = pd.concat(pool.map(func, data_split))\n pool.close()\n pool.join()\n return data\n\nif __name__ == \"__main__\":\n args = get_arguments()\n print(args)\n\n #Read dictionary\n #dictionary = read_dictionary()\n start = timer()\n print('Start time: ', start)\n cores = cpu_count()\n partitions = cores\n df = pd.read_csv(args.input_csv)\n df_processed = parallelize(df, run_normalize)\n df_processed.to_csv(args.output_csv, columns=args.cols, index=False)\n print('Output csv written: ', args.output_csv)\n end = timer()\n\n print('Total time taken: ', end-start)\n" ]
[ [ "numpy.array_split", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
welegent2010/urban-sprawl
[ "b26bdf7889fdba1382259be7c14e7e0d8f535cd9" ]
[ "urbansprawl/population/data_extract.py" ]
[ "###################################################################################################\n# Repository: https://github.com/lgervasoni/urbansprawl\n# MIT License\n###################################################################################################\n\nfrom shapely.geometry import Polygon, GeometryCollection\nimport geopandas as gpd\nimport pandas as pd\nimport os\nimport numpy as np\nimport osmnx as ox\n\nfrom osmnx import log\n\nfrom .utils import get_population_extract_filename\n\nDATA_SOURCES = ['insee','gpw']\n\n##############################\n### I/O for population data\n##############################\n\ndef get_df_extract(df_data, poly_gdf, operation = \"within\"):\n\t\"\"\"\n\tIndexes input geo-data frame within an input region of interest\n\tIf the region of interest is given as a polygon, its bounding box is indexed\n\n\tParameters\n\t----------\n\tdf_data : geopandas.GeoDataFrame\n\t\tinput data frame to index\n\tpoly_gdf : geopandas.GeoDataFrame\n\t\tgeodataframe containing the region of interest in form of polygon\n\toperation : string\n\t\tthe desired spatial join operation: 'within' or 'intersects'\n\n\tReturns\n\t----------\n\tgeopandas.GeoDataFrame\n\t\treturns the population data frame indexed within the region of interest\n\t\"\"\"\n\t# Project to same system coordinates\n\tpoly_gdf = ox.project_gdf(poly_gdf, to_crs=df_data.crs)\n\t# Spatial join\n\tdf_extract = gpd.sjoin(df_data, poly_gdf, op=operation)\n\t# Keep original columns\n\tdf_extract = df_extract[ df_data.columns ]\n\treturn df_extract\n\ndef get_population_df(pop_shapefile, pop_data_file, data_source, to_crs, poly_gdf):\n\t\"\"\"\n\tRead the population shapefile from input filename/s\n\tIndex the data within the bounding box\n\tProject to desired CRS\n\n\tParameters\n\t----------\n\tpop_shapefile : string\n\t\tpopulation count shapefile\n\tpop_data_file : string\n\t\tpopulation data additional file (required for INSEE format)\n\tdata_source : string\n\t\tdesired population data source\n\tto_crs : dict\n\t\tdesired coordinate reference system\n\tpoly_gdf : geopandas.GeoDataFrame\n\t\tgeodataframe containing the region of interest in form of polygon\n\n\tReturns\n\t----------\n\tgeopandas.GeoDataFrame\n\t\treturns the indexed and projected population data frame\n\t\"\"\"\n\t#######################################\n\t### Load GPW/INSEE population data\n\t#######################################\n\t# Read population data\n\tdf_pop = gpd.read_file(pop_shapefile)\n\t\t\n\t### Extract region of interest (EPSG 4326)\n\t# Filter geometries not contained in bounding box\n\tdf_pop = get_df_extract(df_pop, poly_gdf)\n\n\tif (data_source is 'insee'):\n\t\t#######################################\n\t\t### Additional step for INSEE data\n\t\t#######################################\t\n\t\t# Read dbf files\n\t\tdata_pop = gpd.read_file(pop_data_file)\n\t\t# Get columns of interest\n\t\tdata_pop = data_pop[[\"idINSPIRE\",\"ind_c\"]]\n\t\tdf_pop = df_pop[[\"geometry\",\"idINSPIRE\"]]\n\t\t# Inner join to obtain population count data associated to each geometry\n\t\tdf_pop = pd.merge(df_pop, data_pop, how='inner', on='idINSPIRE')\n\t\n\t# Rename population count column\n\tdf_pop.rename(columns={\"ind_c\":\"pop_count\", \"DN\":\"pop_count\"}, inplace=True)\n\n\treturn ox.project_gdf(df_pop, to_crs=to_crs)\n\ndef get_extract_population_data(city_ref, data_source, pop_shapefile=None, pop_data_file=None, to_crs={'init': 'epsg:4326'}, polygons_gdf=None):\n\t\"\"\"\n\tGet data population extract of desired data source for input city, calculating the convex hull of input buildings geodataframe\n\tThe population data frame is projected to the desired coordinate reference system\n\tStores the extracted shapefile\n\tReturns the stored population data for input 'data source' and 'city reference' if it was previously stored\n\n\tParameters\n\t----------\n\tcity_ref : string\n\t\tname of input city\n\tdata_source : string\n\t\tdesired population data source\n\tpop_shapefile : string\n\t\tpath of population count shapefile\n\tpop_data_file : string\n\t\tpath of population data additional file (required for INSEE format)\n\tto_crs : dict\n\t\tdesired coordinate reference system\n\tpolygons_gdf : geopandas.GeoDataFrame\n\t\tpolygons (e.g. buildings) for input region of interest which will determine the shape to extract\n\n\tReturns\n\t----------\n\tgeopandas.GeoDataFrame\n\t\treturns the extracted population data\n\t\"\"\"\n\t# Input data source type given?\n\tassert( data_source in DATA_SOURCES )\n\n\t# Population extract exists?\n\tif ( os.path.exists( get_population_extract_filename(city_ref, data_source) ) ):\n\t\tlog(\"Population extract exists for input city: \"+city_ref)\n\t\treturn gpd.read_file( get_population_extract_filename(city_ref, data_source) )\n\n\t# Input shape given?\n\tassert( not ( np.all(polygons_gdf is None ) ) )\n\t# Input population shapefile given?\n\tassert( not pop_shapefile is None )\n\t# All input files given?\n\tassert( not ( (data_source == 'insee') and (pop_data_file is None) ) )\n\n\t# Get buildings convex hull\n\tpolygon = GeometryCollection( polygons_gdf.geometry.values.tolist() ).convex_hull\n\t# Convert to geo-dataframe with defined CRS\n\tpoly_gdf = gpd.GeoDataFrame([polygon], columns=[\"geometry\"], crs=polygons_gdf.crs)\n\t\n\t# Compute extract\n\tdf_pop = get_population_df(pop_shapefile, pop_data_file, data_source, to_crs, poly_gdf)\n\t\n\t# Save to shapefile\n\tdf_pop.to_file( get_population_extract_filename(city_ref, data_source), driver='ESRI Shapefile' )\n\treturn df_pop\t\n\n" ]
[ [ "numpy.all", "pandas.merge" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
sunny5156/docker-milvus-image-search
[ "72819510955925983a790617b9e05ba0f33159c0" ]
[ "operators/face-encoder/facenet.py" ]
[ "# github url https://github.com/davidsandberg/facenet.git\r\nimport os\r\nimport re\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\n\r\ndef prewhiten(x):\r\n mean = np.mean(x)\r\n std = np.std(x)\r\n std_adj = np.maximum(std, 1.0 / np.sqrt(x.size))\r\n y = np.multiply(np.subtract(x, mean), 1 / std_adj)\r\n return y\r\n\r\n\r\ndef get_model_filenames(model_dir):\r\n files = os.listdir(model_dir)\r\n meta_files = [s for s in files if s.endswith('.meta')]\r\n if len(meta_files) == 0:\r\n raise ValueError(\r\n 'No meta file found in the model directory (%s)' %\r\n model_dir)\r\n elif len(meta_files) > 1:\r\n raise ValueError(\r\n 'There should not be more than one meta file in the model directory (%s)' %\r\n model_dir)\r\n meta_file = meta_files[0]\r\n ckpt = tf.train.get_checkpoint_state(model_dir)\r\n if ckpt and ckpt.model_checkpoint_path:\r\n ckpt_file = os.path.basename(ckpt.model_checkpoint_path)\r\n return meta_file, ckpt_file\r\n\r\n meta_files = [s for s in files if '.ckpt' in s]\r\n max_step = -1\r\n for f in files:\r\n step_str = re.match(r'(^model-[\\w\\- ]+.ckpt-(\\d+))', f)\r\n if step_str is not None and len(step_str.groups()) >= 2:\r\n step = int(step_str.groups()[1])\r\n if step > max_step:\r\n max_step = step\r\n ckpt_file = step_str.groups()[0]\r\n return meta_file, ckpt_file\r\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "numpy.sqrt", "numpy.subtract", "numpy.std", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
PkuRainBow/ISD-SSD
[ "2cd8beba33e0d4fb8b792301b0d9e5486dbe5e68" ]
[ "train_isd.py" ]
[ "from data import *\nfrom utils.augmentations import SSDAugmentation\nfrom layers.modules import MultiBoxLoss, CSDLoss, ISDLoss\nfrom ssd import build_ssd\n# from ssd_consistency import build_ssd_con\nfrom isd import build_ssd_con\nimport os\nimport sys\nimport time\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.utils.data as data\nimport numpy as np\nimport argparse\nimport math\nimport copy\n\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Training With Pytorch')\ntrain_set = parser.add_mutually_exclusive_group()\nparser.add_argument('--dataset', default='VOC300', choices=['VOC300', 'VOC512'],\n type=str, help='VOC300 or VOC512')\nparser.add_argument('--dataset_root', default=VOC_ROOT,\n help='Dataset root directory path')\nparser.add_argument('--basenet', default='vgg16_reducedfc.pth',\n help='Pretrained base model')\nparser.add_argument('--batch_size', default=32, type=int,\n help='Batch size for training')\nparser.add_argument('--resume', default=None, type=str, # None 'weights/ssd300_COCO_80000.pth'\n help='Checkpoint state_dict file to resume training from')\nparser.add_argument('--start_iter', default=0, type=int,\n help='Resume training at this iter')\nparser.add_argument('--num_workers', default=4, type=int,\n help='Number of workers used in dataloading')\nparser.add_argument('--cuda', default=True, type=str2bool,\n help='Use CUDA to train model')\nparser.add_argument('--lr', '--learning-rate', default=1e-3, type=float,\n help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float,\n help='Momentum value for optim')\nparser.add_argument('--weight_decay', default=5e-4, type=float,\n help='Weight decay for SGD')\nparser.add_argument('--gamma', default=0.1, type=float,\n help='Gamma update for SGD')\nparser.add_argument('--visdom', default=False, type=str2bool,\n help='Use visdom for loss visualization')\nparser.add_argument('--save_folder', default='weights/',\n help='Directory for saving checkpoint models')\nargs = parser.parse_args()\n\n# torch.cuda.set_device(1)\n\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't \" +\n \"using CUDA.\\nRun with --cuda for optimal training speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\n\ndef train():\n if args.dataset == 'COCO':\n if args.dataset_root == VOC_ROOT:\n if not os.path.exists(COCO_ROOT):\n parser.error('Must specify dataset_root if specifying dataset')\n print(\"WARNING: Using default COCO dataset_root because \" +\n \"--dataset_root was not specified.\")\n args.dataset_root = COCO_ROOT\n cfg = coco\n dataset = COCODetection(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n elif args.dataset == 'VOC300':\n if args.dataset_root == COCO_ROOT:\n parser.error('Must specify dataset if specifying dataset_root')\n cfg = voc300\n dataset = VOCDetection(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n elif args.dataset == 'VOC512':\n if args.dataset_root == COCO_ROOT:\n parser.error('Must specify dataset if specifying dataset_root')\n cfg = voc512\n dataset = VOCDetection(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n\n if args.visdom:\n import visdom\n viz = visdom.Visdom()\n\n finish_flag = True\n\n while(finish_flag):\n ssd_net = build_ssd_con('train', cfg['min_dim'], cfg['num_classes'])\n net = ssd_net\n\n if args.cuda:\n net = torch.nn.DataParallel(ssd_net)\n cudnn.benchmark = True\n\n if args.resume:\n print('Resuming training, loading {}...'.format(args.resume))\n ssd_net.load_weights(args.resume)\n else:\n vgg_weights = torch.load(args.save_folder + args.basenet)\n print('Loading base network...')\n ssd_net.vgg.load_state_dict(vgg_weights)\n # ssd_net.vgg_t.load_state_dict(vgg_weights)\n\n if args.cuda:\n net = net.cuda()\n\n if not args.resume:\n print('Initializing weights...')\n # initialize newly added layers' weights with xavier method\n ssd_net.extras.apply(weights_init)\n ssd_net.loc.apply(weights_init)\n ssd_net.conf.apply(weights_init)\n\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum,\n weight_decay=args.weight_decay)\n criterion = MultiBoxLoss(cfg['num_classes'], 0.5, True, 0, True, 3, 0.5,\n False, args.cuda)\n csd_criterion = CSDLoss(args.cuda)\n isd_criterion = ISDLoss(args.cuda)\n conf_consistency_criterion = torch.nn.KLDivLoss(size_average=False, reduce=False).cuda()\n\n\n\n net.train()\n # loss counters\n loc_loss = 0\n conf_loss = 0\n epoch = 0\n supervised_flag = 1\n print('Loading the dataset...')\n\n step_index = 0\n\n\n if args.visdom:\n vis_title = 'SSD.PyTorch on ' + dataset.name\n vis_legend = ['Loc Loss', 'Conf Loss', 'Total Loss']\n iter_plot = create_vis_plot('Iteration', 'Loss', vis_title, vis_legend)\n epoch_plot = create_vis_plot('Epoch', 'Loss', vis_title, vis_legend)\n\n\n total_un_iter_num = 0\n\n\n supervised_batch = args.batch_size\n #unsupervised_batch = args.batch_size - supervised_batch\n #data_shuffle = 0\n\n if(args.start_iter==0):\n dataset = VOCDetection_con_init(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n else:\n supervised_flag = 0\n dataset = VOCDetection_con(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))#,shuffle_flag=data_shuffle)\n #data_shuffle = 1\n\n data_loader = data.DataLoader(dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=True, collate_fn=detection_collate,\n pin_memory=True, drop_last=True)\n\n\n batch_iterator = iter(data_loader)\n\n for iteration in range(args.start_iter, cfg['max_iter']):\n if args.visdom and iteration != 0 and (iteration % epoch_size == 0):\n update_vis_plot(epoch, loc_loss, conf_loss, epoch_plot, None,\n 'append', epoch_size)\n # reset epoch loss counters\n loc_loss = 0\n conf_loss = 0\n epoch += 1\n\n if iteration in cfg['lr_steps']:\n step_index += 1\n adjust_learning_rate(optimizer, args.gamma, step_index)\n\n try:\n images, targets, semis = next(batch_iterator)\n except StopIteration:\n supervised_flag = 0\n dataset = VOCDetection_con(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))#, shuffle_flag=data_shuffle)\n data_loader = data.DataLoader(dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=True, collate_fn=detection_collate,\n pin_memory=True, drop_last=True)\n batch_iterator = iter(data_loader)\n images, targets, semis = next(batch_iterator)\n\n\n if args.cuda:\n images = Variable(images.cuda())\n targets = [Variable(ann.cuda(), volatile=True) for ann in targets]\n else:\n images = Variable(images)\n targets = [Variable(ann, volatile=True) for ann in targets]\n # forward\n t0 = time.time()\n\n images_flip = images.clone()\n images_flip = flip(images_flip, 3)\n\n images_shuffle = images_flip.clone()\n images_shuffle[:int(args.batch_size / 2), :, :, :] = images_flip[int(args.batch_size / 2):, :, :, :]\n images_shuffle[int(args.batch_size / 2):, :, :, :] = images_flip[:int(args.batch_size / 2), :, :, :]\n\n lam = np.random.beta(5.0, 5.0)\n\n\n images_mix = lam * images.clone() + (1 - lam) * images_shuffle.clone()\n\n out, conf, conf_flip, loc, loc_flip, conf_shuffle, conf_interpolation, loc_shuffle, loc_interpolation = net(images, images_flip, images_mix)\n\n\n sup_image_binary_index = np.zeros([len(semis),1])\n\n for super_image in range(len(semis)):\n if(int(semis[super_image])==1):\n sup_image_binary_index[super_image] = 1\n else:\n sup_image_binary_index[super_image] = 0\n\n if(int(semis[len(semis)-1-super_image])==0):\n del targets[len(semis)-1-super_image]\n\n\n sup_image_index = np.where(sup_image_binary_index == 1)[0]\n unsup_image_index = np.where(sup_image_binary_index == 0)[0]\n\n loc_data, conf_data, priors = out\n\n if (len(sup_image_index) != 0):\n loc_data = loc_data[sup_image_index,:,:]\n conf_data = conf_data[sup_image_index,:,:]\n output = (\n loc_data,\n conf_data,\n priors\n )\n\n # backprop\n # loss = Variable(torch.cuda.FloatTensor([0]))\n loss_l = Variable(torch.cuda.FloatTensor([0]))\n loss_c = Variable(torch.cuda.FloatTensor([0]))\n\n\n\n if(len(sup_image_index)!=0):\n try:\n loss_l, loss_c = criterion(output, targets)\n except:\n break\n print('--------------')\n\n\n consistency_loss = csd_criterion(args, conf, conf_flip, loc, loc_flip, conf_consistency_criterion)\n interpolation_consistency_conf_loss, fixmatch_loss = isd_criterion(args, lam, conf, conf_flip, loc, loc_flip, conf_shuffle, conf_interpolation, loc_shuffle, loc_interpolation, conf_consistency_criterion)\n consistency_loss = consistency_loss.mean()\n interpolation_loss = torch.mul(interpolation_consistency_conf_loss.mean(), 0.1) + fixmatch_loss.mean()\n\n\n ramp_weight = rampweight(iteration)\n consistency_loss = torch.mul(consistency_loss, ramp_weight)\n interpolation_loss = torch.mul(interpolation_loss,ramp_weight)\n\n if(supervised_flag ==1):\n loss = loss_l + loss_c + consistency_loss + interpolation_loss\n else:\n if(len(sup_image_index)==0):\n loss = consistency_loss + interpolation_loss\n else:\n loss = loss_l + loss_c + consistency_loss + interpolation_loss\n\n\n if(loss.data>0):\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n t1 = time.time()\n if(len(sup_image_index)==0):\n loss_l.data = Variable(torch.cuda.FloatTensor([0]))\n loss_c.data = Variable(torch.cuda.FloatTensor([0]))\n else:\n loc_loss += loss_l.data # [0]\n conf_loss += loss_c.data # [0]\n\n\n if iteration % 10 == 0:\n print('timer: %.4f sec.' % (t1 - t0))\n print('iter ' + repr(iteration) + ' || Loss: %.4f || consistency_loss : %.4f ||' % (loss.data, consistency_loss.data), end=' ')\n print('loss: %.4f , loss_c: %.4f , loss_l: %.4f , loss_con: %.4f, loss_interpolation: %.4f, lr : %.4f, super_len : %d\\n' % (loss.data, loss_c.data, loss_l.data, consistency_loss.data, interpolation_loss.data, float(optimizer.param_groups[0]['lr']),len(sup_image_index)))\n\n\n if(float(loss)>100):\n break\n\n if args.visdom:\n update_vis_plot(iteration, loss_l.data, loss_c.data,\n iter_plot, epoch_plot, 'append')\n\n if iteration != 0 and (iteration+1) % 120000 == 0:\n print('Saving state, iter:', iteration)\n torch.save(ssd_net.state_dict(), 'weights/ssd300_COCO_' +\n repr(iteration+1) + '.pth')\n # torch.save(ssd_net.state_dict(), args.save_folder + '' + args.dataset + '.pth')\n print('-------------------------------\\n')\n print(loss.data)\n print('-------------------------------')\n\n if((iteration +1) ==cfg['max_iter']):\n finish_flag = False\n\n\ndef rampweight(iteration):\n ramp_up_end = 64000\n ramp_down_start = 220000\n coef = 1\n\n if(iteration<ramp_up_end):\n ramp_weight = math.exp(-5 * math.pow((1 - iteration / ramp_up_end),2))\n elif(iteration>ramp_down_start):\n ramp_weight = math.exp(-12.5 * math.pow((1 - (240000 - iteration) / 20000),2)) \n# ramp_weight = math.exp(-12.5 * math.pow((1 - (120000 - iteration) / 20000),2))\n else:\n ramp_weight = 1 \n\n\n if(iteration==0):\n ramp_weight = 0\n\n return ramp_weight * coef\n\n\n\n\ndef adjust_learning_rate(optimizer, gamma, step):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 at every\n specified step\n # Adapted from PyTorch Imagenet example:\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n lr = args.lr * (gamma ** (step))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef xavier(param):\n init.xavier_uniform(param)\n\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d):\n xavier(m.weight.data)\n m.bias.data.zero_()\n\n\ndef create_vis_plot(_xlabel, _ylabel, _title, _legend):\n return viz.line(\n X=torch.zeros((1,)).cpu(),\n Y=torch.zeros((1, 3)).cpu(),\n opts=dict(\n xlabel=_xlabel,\n ylabel=_ylabel,\n title=_title,\n legend=_legend\n )\n )\n\n\ndef update_vis_plot(iteration, loc, conf, window1, window2, update_type,\n epoch_size=1):\n viz.line(\n X=torch.ones((1, 3)).cpu() * iteration,\n Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu() / epoch_size,\n win=window1,\n update=update_type\n )\n # initialize epoch plot on first iteration\n if iteration == 0:\n viz.line(\n X=torch.zeros((1, 3)).cpu(),\n Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu(),\n win=window2,\n update=True\n )\n\ndef flip(x, dim):\n dim = x.dim() + dim if dim < 0 else dim\n return x[tuple(slice(None, None) if i != dim\n else torch.arange(x.size(i)-1, -1, -1).long()\n for i in range(x.dim()))]\n\n\nif __name__ == '__main__':\n train()\n\n" ]
[ [ "torch.set_default_tensor_type", "torch.nn.KLDivLoss", "numpy.random.beta", "torch.ones", "torch.Tensor", "torch.load", "torch.zeros", "torch.utils.data.DataLoader", "torch.cuda.FloatTensor", "torch.mul", "torch.cuda.is_available", "torch.nn.DataParallel", "numpy.where", "torch.nn.init.xavier_uniform", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
algattik/azure-mlops-terraform
[ "ff19d36d52fb29ce76439b9f921676d9a1031ad1" ]
[ "code/training/train.py" ]
[ "from azureml.core.run import Run\nimport os\nimport argparse\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.linear_model import Ridge\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.externals import joblib\n\n\nparser = argparse.ArgumentParser(\"train\")\nparser.add_argument(\n \"--build_id\",\n type=str,\n help=\"The build ID of the build triggering this pipeline run\",\n)\nparser.add_argument(\n \"--model_name\",\n type=str,\n help=\"Name of the Model\"\n)\nparser.add_argument(\n \"--alpha\",\n type=float,\n default=0.5,\n help=(\"Ridge regression regularization strength hyperparameter; \"\n \"must be a positive float.\")\n)\n\nargs = parser.parse_args()\n\nprint(\"Argument [build_id]: %s\" % args.build_id)\nprint(\"Argument [model_name]: %s\" % args.model_name)\nprint(\"Argument [alpha]: %s\" % args.alpha)\n\nmodel_name = args.model_name\nbuild_id = args.build_id\nalpha = args.alpha\n\nrun = Run.get_context()\nexp = run.experiment\nws = run.experiment.workspace\n\nX, y = load_diabetes(return_X_y=True)\ncolumns = [\"age\", \"gender\", \"bmi\", \"bp\", \"s1\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\"]\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=0)\ndata = {\"train\": {\"X\": X_train, \"y\": y_train},\n \"test\": {\"X\": X_test, \"y\": y_test}}\n\nprint(\"Running train.py\")\n\nrun.log(\"alpha\", alpha)\nrun.parent.log(\"alpha\", alpha)\nreg = Ridge(alpha=alpha)\nreg.fit(data[\"train\"][\"X\"], data[\"train\"][\"y\"])\npreds = reg.predict(data[\"test\"][\"X\"])\nrun.log(\"mse\", mean_squared_error(\n preds, data[\"test\"][\"y\"]), description=\"Mean squared error metric\")\nrun.parent.log(\"mse\", mean_squared_error(\n preds, data[\"test\"][\"y\"]), description=\"Mean squared error metric\")\n\nwith open(model_name, \"wb\") as file:\n joblib.dump(value=reg, filename=model_name)\n\n# upload model file explicitly into artifacts for parent run\nrun.parent.upload_file(name=\"./outputs/\" + model_name,\n path_or_stream=model_name)\nprint(\"Uploaded the model {} to experiment {}\".format(\n model_name, run.experiment.name))\ndirpath = os.getcwd()\nprint(dirpath)\nprint(\"Following files are uploaded \")\nprint(run.parent.get_file_names())\n\n# Add properties to identify this specific training run\nrun.tag(\"BuildId\", value=build_id)\nrun.tag(\"run_type\", value=\"train\")\nprint(f\"tags now present for run: {run.tags}\")\n\nrun.complete()\n" ]
[ [ "sklearn.externals.joblib.dump", "sklearn.model_selection.train_test_split", "sklearn.datasets.load_diabetes", "sklearn.metrics.mean_squared_error", "sklearn.linear_model.Ridge" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prabhat00155/sklearn-onnx
[ "c88c4330b21ed0e4241257d02f4c61ad4f798a30" ]
[ "tests/test_sklearn_decision_tree_converters.py" ]
[ "# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport unittest\nfrom distutils.version import StrictVersion\nimport numpy as np\nfrom pandas import DataFrame\nfrom sklearn.tree import (\n DecisionTreeClassifier, DecisionTreeRegressor,\n ExtraTreeClassifier, ExtraTreeRegressor\n)\nfrom sklearn.datasets import make_classification\nfrom skl2onnx.common.data_types import onnx_built_with_ml\nfrom skl2onnx.common.data_types import (\n BooleanTensorType,\n FloatTensorType,\n Int64TensorType,\n)\nfrom skl2onnx import convert_sklearn\nfrom onnxruntime import InferenceSession, __version__\nfrom test_utils import (\n dump_one_class_classification,\n dump_binary_classification,\n dump_data_and_model,\n dump_multiple_classification,\n dump_multiple_regression,\n dump_single_regression,\n fit_classification_model,\n fit_multilabel_classification_model,\n fit_regression_model,\n TARGET_OPSET\n)\n\n\nclass TestSklearnDecisionTreeModels(unittest.TestCase):\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(\n StrictVersion(__version__) <= StrictVersion(\"0.3.0\"),\n reason=\"No suitable kernel definition found \"\n \"for op Cast(9) (node Cast)\")\n def test_decisiontree_classifier1(self):\n model = DecisionTreeClassifier(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(model, initial_types=initial_types)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict_proba(X)\n if res[1][0][0] != pred[0, 0]:\n raise AssertionError(\"{}\\n--\\n{}\".format(pred, DataFrame(res[1])))\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_decisiontree_regressor0(self):\n model = DecisionTreeRegressor(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(model, initial_types=initial_types)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n if res[0][0, 0] != pred[0]:\n raise AssertionError(\"{}\\n--\\n{}\".format(pred, DataFrame(res[1])))\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_decision_tree_classifier(self):\n model = DecisionTreeClassifier()\n dump_one_class_classification(\n model,\n # Operator cast-1 is not implemented in onnxruntime\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_binary_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_multiple_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n dump_multiple_classification(\n model,\n label_uint8=True,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n dump_multiple_classification(\n model,\n label_string=True,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_extra_tree_classifier(self):\n model = ExtraTreeClassifier()\n dump_one_class_classification(\n model,\n # Operator cast-1 is not implemented in onnxruntime\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_binary_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_multiple_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n\n def test_decision_tree_regressor(self):\n model = DecisionTreeRegressor()\n dump_single_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n dump_multiple_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n\n def test_extra_tree_regressor(self):\n model = ExtraTreeRegressor()\n dump_single_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n dump_multiple_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n\n def test_decision_tree_regressor_int(self):\n model, X = fit_regression_model(\n DecisionTreeRegressor(random_state=42), is_int=True)\n model_onnx = convert_sklearn(\n model,\n \"decision tree regression\",\n [(\"input\", Int64TensorType([None, X.shape[1]]))],\n )\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeRegressionInt\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_multi_class_nocl(self):\n model, X = fit_classification_model(\n DecisionTreeClassifier(),\n 4, label_string=True)\n model_onnx = convert_sklearn(\n model,\n \"multi-class nocl\",\n [(\"input\", FloatTensorType([None, X.shape[1]]))],\n options={id(model): {'nocl': True}})\n self.assertIsNotNone(model_onnx)\n sonx = str(model_onnx)\n assert 'classlabels_strings' not in sonx\n assert 'cl0' not in sonx\n dump_data_and_model(\n X, model, model_onnx, classes=model.classes_,\n basename=\"SklearnDTMultiNoCl\",\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_decision_tree_classifier_multilabel(self):\n model, X_test = fit_multilabel_classification_model(\n DecisionTreeClassifier(random_state=42))\n options = {id(model): {'zipmap': False}}\n model_onnx = convert_sklearn(\n model,\n \"scikit-learn DecisionTreeClassifier\",\n [(\"input\", FloatTensorType([None, X_test.shape[1]]))],\n options=options,\n target_opset=TARGET_OPSET\n )\n self.assertTrue(model_onnx is not None)\n assert 'zipmap' not in str(model_onnx).lower()\n dump_data_and_model(\n X_test,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeClassifierMultiLabel-Out0\",\n allow_failure=\"StrictVersion(\"\n \"onnxruntime.__version__) <= StrictVersion('0.2.1')\",\n )\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_extra_tree_classifier_multilabel(self):\n model, X_test = fit_multilabel_classification_model(\n ExtraTreeClassifier(random_state=42))\n options = {id(model): {'zipmap': False}}\n model_onnx = convert_sklearn(\n model,\n \"scikit-learn ExtraTreeClassifier\",\n [(\"input\", FloatTensorType([None, X_test.shape[1]]))],\n options=options,\n target_opset=TARGET_OPSET\n )\n self.assertTrue(model_onnx is not None)\n assert 'zipmap' not in str(model_onnx).lower()\n dump_data_and_model(\n X_test,\n model,\n model_onnx,\n basename=\"SklearnExtraTreeClassifierMultiLabel-Out0\",\n allow_failure=\"StrictVersion(\"\n \"onnxruntime.__version__) <= StrictVersion('0.2.1')\",\n )\n\n def test_decision_tree_regressor_bool(self):\n model, X = fit_regression_model(\n DecisionTreeRegressor(random_state=42), is_bool=True)\n model_onnx = convert_sklearn(\n model,\n \"decision tree regressor\",\n [(\"input\", BooleanTensorType([None, X.shape[1]]))],\n )\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeRegressionBool-Dec4\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n def test_extra_tree_regressor_bool(self):\n model, X = fit_regression_model(\n ExtraTreeRegressor(random_state=42), is_bool=True)\n model_onnx = convert_sklearn(\n model,\n \"extra tree regressor\",\n [(\"input\", BooleanTensorType([None, X.shape[1]]))],\n )\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnExtraTreeRegressionBool-Dec4\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "sklearn.tree.ExtraTreeRegressor", "sklearn.datasets.make_classification", "sklearn.tree.DecisionTreeRegressor", "pandas.DataFrame", "sklearn.tree.ExtraTreeClassifier", "sklearn.tree.DecisionTreeClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
kulkarni62sushil/wittgenstein
[ "2ae19222b80cf24467b3693da9b2b4909033a695" ]
[ "wittgenstein/ripper.py" ]
[ "\"\"\"\nImplementation of the RIPPERk algorithm for growing classification rulesets.\nSee https://www.let.rug.nl/nerbonne/teach/learning/cohen95fast.pdf\n\"\"\"\n\n# Author: Ilan Moscovitz <[email protected]>\n# License: MIT\n\nimport copy\nimport math\nimport numpy as np\n\nimport pandas as pd\n\nfrom wittgenstein import base, base_functions, preprocess\nfrom .abstract_ruleset_classifier import AbstractRulesetClassifier\nfrom .base import Cond, Rule, Ruleset, asruleset\nfrom .base_functions import score_accuracy\nfrom .catnap import CatNap\nfrom .check import _check_is_model_fit\nfrom wittgenstein import utils\nfrom wittgenstein.utils import rnd\n\n\nclass RIPPER(AbstractRulesetClassifier):\n \"\"\" Class for generating ruleset classification models.\n See Cohen (1995): https://www.let.rug.nl/nerbonne/teach/learning/cohen95fast.pdf\n \"\"\"\n\n def __init__(\n self,\n k=2,\n dl_allowance=64,\n prune_size=0.33,\n n_discretize_bins=10,\n max_rules=None,\n max_rule_conds=None,\n max_total_conds=None,\n random_state=None,\n verbosity=0,\n ):\n \"\"\"Create a RIPPER classifier.\n\n Parameters\n ----------\n k : int, default=2\n Number of RIPPERk optimization iterations.\n prune_size : float, default=.33\n Proportion of training set to be used for pruning.\n dl_allowance : int, default=64\n Terminate Ruleset grow phase early if a Ruleset description length is encountered\n that is more than this amount above the lowest description length so far encountered.\n n_discretize_bins : int, default=10\n Fit apparent numeric attributes into a maximum of n_discretize_bins discrete bins, inclusive on upper part of range. Pass None to disable auto-discretization.\n random_state : int, default=None\n Random seed for repeatable results.\n\n Limits for early-stopping. Intended for enhancing model interpretability and limiting training time on noisy datasets. Not specifically intended for use as a hyperparameter, since pruning already occurs during training, though it is certainly possible that tuning could improve model performance.\n max_rules : int, default=None\n Maximum number of rules.\n max_rule_conds : int, default=None\n Maximum number of conds per rule.\n max_total_conds : int, default=None\n Maximum number of total conds in entire ruleset.\n\n verbosity : int, default=0\n Output progress, model development, and/or computation. Each level includes the information belonging to lower-value levels.\n 1: Show results of each major phase\n 2: Show Ruleset grow/optimization steps\n 3: Show Ruleset grow/optimization calculations\n 4: Show Rule grow/prune steps\n 5: Show Rule grow/prune calculations\n \"\"\"\n\n AbstractRulesetClassifier.__init__(\n self,\n algorithm_name=\"RIPPER\",\n prune_size=prune_size,\n n_discretize_bins=n_discretize_bins,\n max_rules=max_rules,\n max_rule_conds=max_rule_conds,\n max_total_conds=max_total_conds,\n random_state=random_state,\n verbosity=verbosity,\n )\n self.VALID_HYPERPARAMETERS.update({\"k\", \"dl_allowance\"})\n self.k = k\n self.dl_allowance = dl_allowance\n\n def __str__(self):\n \"\"\"Return string representation of a RIPPER classifier.\"\"\"\n params = str(self.get_params()) + \">\"\n params = (\n params.replace(\": \", \"=\")\n .replace(\"'\", \"\")\n .replace(\"{\", \"(\")\n .replace(\"}\", \")\")\n )\n return f\"<RIPPER{params}\"\n\n def out_model(self):\n \"\"\"Print trained Ruleset model line-by-line: V represents 'or'; ^ represents 'and'.\"\"\"\n super().out_model()\n\n def fit(\n self,\n trainset,\n y=None,\n class_feat=None,\n pos_class=None,\n feature_names=None,\n initial_model=None,\n cn_optimize=True,\n **kwargs,\n ):\n \"\"\"Fit a Ruleset model.\n\n Parameters\n ----------\n trainset : DataFrame, numpy array, or other iterable\n Training dataset. Optional whether to include or exclude class labels column.\n y : iterable of str, int, bool\n Class labels corresponding to trainset rows. Use if class labels aren't included in trainset.\n class_feat: str, int\n Column name or index of class feature. Use if class feature is still in trainset.\n pos_class : str, optional for boolean target, default=1 or True\n Name of positive class.\n feature_names : list<str>, optional, default=None\n Specify feature names. If None, feature names default to column names for a DataFrame, or indices in the case of indexed iterables such as an array or list.\n initial_model : Ruleset, str, IREP or RIPPER, default=None\n Preexisting model from which to begin training. See also 'init_ruleset'.\n cn_optimize : bool, default=True\n Use algorithmic speed optimization.\n\n **kwargs\n --------\n The following parameters are moving to the RIPPER constructor (__init__) function. For the time-being, both the constructor and fit functions will accept them, but passing them here using .fit will be deprecated:\n\n k : int, default=2\n Number of RIPPERk optimization iterations.\n prune_size : float, default=.33\n Proportion of training set to be used for pruning.\n dl_allowance : int, default=64\n Terminate Ruleset grow phase early if a Ruleset description length is encountered\n that is more than this amount above the lowest description length so far encountered.\n n_discretize_bins : int, default=10\n Fit apparent numeric attributes into a maximum of n_discretize_bins discrete bins, inclusive on upper part of range. Pass None to disable auto-discretization.\n random_state : int, default=None\n Random seed for repeatable results.\n\n Limits for early-stopping. Intended for enhancing model interpretability and limiting training time on noisy datasets. Not specifically intended for use as a hyperparameter, since pruning already occurs during training, though it is certainly possible that tuning could improve model performance.\n max_rules : int, default=None\n Maximum number of rules.\n max_rule_conds : int, default=None\n Maximum number of conds per rule.\n max_total_conds : int, default=None\n Maximum number of total conds in entire ruleset.\n\n verbosity : int, default=0\n Output progress, model development, and/or computation. Each level includes the information belonging to lower-value levels.\n 1: Show results of each major phase\n 2: Show Ruleset grow/optimization steps\n 3: Show Ruleset grow/optimization calculations\n 4: Show Rule grow/prune steps\n 5: Show Rule grow/prune calculations\n \"\"\"\n\n ################\n # Stage 0: Setup\n ################\n\n # Handle any hyperparam deprecation\n self._set_deprecated_fit_params(kwargs)\n\n # Preprocess training data\n preprocess_params = {\n \"trainset\": trainset,\n \"y\": y,\n \"class_feat\": class_feat,\n \"pos_class\": pos_class,\n \"feature_names\": feature_names,\n \"n_discretize_bins\": self.n_discretize_bins,\n \"verbosity\": self.verbosity,\n }\n (\n df,\n self.class_feat,\n self.pos_class,\n self.bin_transformer_,\n ) = preprocess.preprocess_training_data(preprocess_params)\n\n # Create CatNap\n # possible minor speedup if pass cond_subset of only pos_class conds?\n if cn_optimize:\n self.cn = CatNap(\n df,\n feat_subset=None,\n cond_subset=None,\n class_feat=self.class_feat,\n pos_class=None,\n )\n\n # Split df into pos, neg classes\n pos_df, neg_df = base_functions.pos_neg_split(\n df, self.class_feat, self.pos_class\n )\n pos_df = pos_df.drop(self.class_feat, axis=1)\n neg_df = neg_df.drop(self.class_feat, axis=1)\n\n \n\n ###############################\n # Stage 1: Grow initial Ruleset\n ###############################\n\n if cn_optimize:\n pos_idx = set(pos_df.index.tolist())\n neg_idx = set(neg_df.index.tolist())\n self.ruleset_ = self._grow_ruleset_cn(\n pos_idx,\n neg_idx,\n prune_size=self.prune_size,\n dl_allowance=self.dl_allowance,\n max_rules=self.max_rules,\n max_rule_conds=self.max_rule_conds,\n max_total_conds=self.max_total_conds,\n initial_model=initial_model,\n random_state=self.random_state,\n )\n else:\n self.ruleset_ = self._grow_ruleset(\n pos_df,\n neg_df,\n prune_size=self.prune_size,\n dl_allowance=self.dl_allowance,\n max_rules=self.max_rules,\n max_rule_conds=self.max_rule_conds,\n max_total_conds=self.max_total_conds,\n initial_model=initial_model,\n random_state=self.random_state,\n )\n if self.verbosity >= 1:\n print()\n print(\"GREW INITIAL RULESET:\")\n self.ruleset_.out_pretty()\n print()\n\n ###########################\n # Stage 2: Optimize Ruleset\n ###########################\n\n for iter in range(1, self.k + 1):\n # Create new but reproducible random_state (if applicable)\n iter_random_state = (\n self.random_state + 100 if self.random_state is not None else None\n )\n # Run optimization iteration\n if self.verbosity >= 1:\n print(f\"optimization run {iter} of {self.k}\")\n if cn_optimize:\n newset = self._optimize_ruleset_cn(\n self.ruleset_,\n pos_idx,\n neg_idx,\n prune_size=self.prune_size,\n random_state=iter_random_state,\n )\n else:\n newset = self._optimize_ruleset(\n self.ruleset_,\n pos_df,\n neg_df,\n prune_size=self.prune_size,\n random_state=iter_random_state,\n )\n\n if self.verbosity >= 1:\n print()\n print(\"OPTIMIZED RULESET:\")\n if self.verbosity >= 2:\n print(\n f\"iteration {iter} of {self.k}\\n modified rules {[i for i in range(len(self.ruleset_.rules)) if self.ruleset_.rules[i]!= newset.rules[i]]}\"\n )\n newset.out_pretty()\n print()\n\n if iter != self.k and self.ruleset_ == newset:\n if self.verbosity >= 1:\n print(\"No changes were made. Halting optimization.\")\n break\n else:\n self.ruleset_ = newset\n\n #############################################\n # Stage 3: Cover any last remaining positives\n #############################################\n\n if cn_optimize:\n self._cover_remaining_positives_cn(\n df,\n max_rules=self.max_rules,\n max_rule_conds=self.max_rule_conds,\n max_total_conds=self.max_total_conds,\n random_state=self.random_state,\n )\n else:\n self._cover_remaining_positives(\n df,\n max_rules=self.max_rules,\n max_rule_conds=self.max_rule_conds,\n max_total_conds=self.max_total_conds,\n random_state=self.random_state,\n )\n\n #################################################\n # Stage 4: Remove any rules that don't improve dl\n #################################################\n\n if self.verbosity >= 2:\n print(\"Optimizing dl...\")\n if cn_optimize:\n mdl_subset, _ = _rs_total_bits_cn(\n self.cn,\n self.ruleset_,\n self.ruleset_.possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=True,\n ret_bestsubset=True,\n verbosity=self.verbosity,\n )\n else:\n mdl_subset, _ = _rs_total_bits(\n self.ruleset_,\n self.ruleset_.possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=True,\n ret_bestsubset=True,\n verbosity=self.verbosity,\n )\n self.ruleset_ = mdl_subset\n if self.verbosity >= 1:\n print(\"FINAL RULESET:\")\n self.ruleset_.out_pretty()\n print()\n\n # Issue warning if Ruleset is universal or empty\n self.ruleset_._check_allpos_allneg(warn=True, warnstack=[(\"ripper\", \"fit\")])\n\n # Set Ruleset features\n self.selected_features_ = self.ruleset_.get_selected_features()\n self.trainset_features_ = df.drop(self.class_feat, axis=1).columns.tolist()\n\n # Remove any duplicates and trim\n self.ruleset_.rules = utils.remove_duplicates(self.ruleset_.rules)\n self.ruleset_.trim_conds(max_total_conds=self.max_total_conds)\n\n # Fit probas\n self.recalibrate_proba(\n df, min_samples=None, require_min_samples=False, discretize=False\n )\n self.classes_ = np.array([0, 1])\n\n # Cleanup\n if cn_optimize:\n del self.cn\n\n def score(self, X, y, score_function=score_accuracy):\n \"\"\"Score the performance of a fit model.\n\n X : DataFrame, numpy array, or other iterable\n Examples to score.\n y : Series, numpy array, or other iterable\n Class label actuals.\n\n score_function : function, default=score_accuracy\n Any scoring function that takes two parameters: actuals <iterable<bool>>, predictions <iterable<bool>>, where the elements represent class labels.\n this optional parameter is intended to be compatible with sklearn's scoring functions: https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics\n \"\"\"\n\n _check_is_model_fit(self)\n\n predictions = self.predict(X)\n actuals = [yi == self.pos_class for yi in utils.aslist(y)]\n return score_function(actuals, predictions)\n\n def _set_theory_dl_lookup(self, df, size=15, verbosity=0):\n \"\"\"Precalculate rule theory dls for various-sized rules.\"\"\"\n\n self.dl_dict = {}\n\n temp = Ruleset()\n temp._update_possible_conds(df, df)\n\n for n in range(1, size + 1):\n rule = Rule([Cond(\"_\", \"_\")] * n)\n dl = _r_theory_bits(\n rule, temp.possible_conds, bits_dict=None, verbosity=verbosity\n )\n self.dl_dict[n] = dl\n if verbosity >= 2:\n print(f\"updated dl for rule size {n}: {dl}\")\n\n def _grow_ruleset(\n self,\n pos_df,\n neg_df,\n prune_size,\n dl_allowance,\n max_rules=None,\n max_rule_conds=None,\n max_total_conds=None,\n initial_model=None,\n random_state=None,\n ):\n \"\"\"Grow a Ruleset with pruning.\"\"\"\n ruleset = self._ruleset_frommodel(initial_model)\n ruleset._update_possible_conds(pos_df, neg_df)\n\n ruleset_dl = None\n mdl = None # Minimum encountered description length (in bits)\n dl_diff = 0\n if self.verbosity >= 2:\n print(\"growing ruleset...\")\n print(f\"initial model: {ruleset}\")\n print()\n\n pos_remaining = pos_df.copy()\n neg_remaining = neg_df.copy()\n while len(pos_remaining) > 0 and dl_diff <= self.dl_allowance:\n\n # If applicable, check for user-specified early stopping\n if stop_early(ruleset, max_rules, max_total_conds):\n break\n\n # Grow-prune split remaining uncovered examples\n pos_growset, pos_pruneset = base_functions.df_shuffled_split(\n pos_remaining, (1 - prune_size), random_state=random_state\n )\n neg_growset, neg_pruneset = base_functions.df_shuffled_split(\n neg_remaining, (1 - prune_size), random_state=random_state\n )\n if self.verbosity >= 2:\n print(\n f\"pos_growset {len(pos_growset)} pos_pruneset {len(pos_pruneset)}\"\n )\n print(\n f\"neg_growset {len(neg_growset)} neg_pruneset {len(neg_pruneset)}\"\n )\n if len(pos_growset) == 0:\n break # Probably safe, but a little dicey to only check pos_growset.\n\n # Grow Rule\n grown_rule = base_functions.grow_rule(\n pos_growset,\n neg_growset,\n ruleset.possible_conds,\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n if grown_rule.isempty():\n break # Generated an empty rule b/c no good conds exist\n\n # Prune Rule\n pruned_rule = base_functions.prune_rule(\n grown_rule,\n _RIPPER_growphase_prune_metric,\n pos_pruneset,\n neg_pruneset,\n verbosity=self.verbosity,\n )\n\n # Add rule; calculate new description length\n ruleset.add(\n pruned_rule\n ) # Unlike IREP, IREP*/RIPPER stopping condition is inclusive: \"After each rule is added, the total description length of the rule set and examples is computed.\"\n if self.verbosity >= 2:\n print(f\"updated ruleset: {ruleset.truncstr(direction='right')}\")\n print()\n\n if ruleset_dl is None: # First Rule to be added\n rule_dl = _r_theory_bits(\n pruned_rule, ruleset.possible_conds, verbosity=self.verbosity\n )\n theory_dl = rule_dl\n data_dl = _exceptions_bits(\n ruleset, pos_df, neg_df, verbosity=self.verbosity\n )\n ruleset_dl = theory_dl + data_dl\n mdl = ruleset_dl\n else:\n rule_dl = _r_theory_bits(\n pruned_rule, ruleset.possible_conds, verbosity=self.verbosity\n )\n theory_dl += rule_dl\n data_dl = _exceptions_bits(\n ruleset, pos_df, neg_df, verbosity=self.verbosity\n )\n ruleset_dl = theory_dl + data_dl\n dl_diff = ruleset_dl - mdl\n\n if self.verbosity >= 3:\n print(f\"rule dl: {rnd(rule_dl)}\")\n print(f\"updated theory dl: {rnd(theory_dl)}\")\n print(f\"exceptions: {rnd(data_dl)}\")\n print(f\"total dl: {rnd(ruleset_dl)}\")\n if dl_diff <= self.dl_allowance:\n print(\n f\"mdl {rnd(mdl)} (diff {rnd(dl_diff)} <= {rnd(self.dl_allowance)})\"\n )\n else:\n print(\n f\"mdl {rnd(mdl)} dl-halt: diff {rnd(dl_diff)} exceeds allowance ({rnd(self.dl_allowance)})\"\n )\n\n mdl = ruleset_dl if ruleset_dl < mdl else mdl\n\n # Remove covered examples\n pos_remaining, neg_remaining = base_functions.rm_covered(\n pruned_rule, pos_remaining, neg_remaining\n )\n\n if self.verbosity >= 3:\n print(\n f\"examples remaining: {len(pos_remaining)} pos, {len(neg_remaining)} neg\"\n )\n print()\n\n return ruleset\n\n def _grow_ruleset_cn(\n self,\n pos_idx,\n neg_idx,\n prune_size,\n dl_allowance,\n max_rules=None,\n max_rule_conds=None,\n max_total_conds=None,\n initial_model=None,\n random_state=None,\n ):\n \"\"\"Grow a Ruleset with pruning.\"\"\"\n ruleset = self._ruleset_frommodel(initial_model)\n ruleset.possible_conds = self.cn.conds\n\n pos_remaining_idx = pos_idx\n neg_remaining_idx = neg_idx\n ruleset_dl = None\n mdl = None # Minimum encountered description length (in bits)\n dl_diff = 0\n if self.verbosity >= 2:\n print(\"growing ruleset...\")\n print(f\"initial model: {ruleset}\")\n print()\n\n while len(pos_remaining_idx) > 0 and dl_diff <= self.dl_allowance:\n\n # If applicable, check for user-specified early stopping\n if (max_rules is not None and len(ruleset.rules) >= max_rules) or (\n max_total_conds is not None and ruleset.count_conds() >= max_total_conds\n ):\n break\n\n # Grow-prune split remaining uncovered examples\n pos_growset_idx, pos_pruneset_idx = base_functions.random_split(\n pos_remaining_idx,\n (1 - prune_size),\n res_type=set,\n random_state=random_state,\n )\n neg_growset_idx, neg_pruneset_idx = base_functions.random_split(\n neg_remaining_idx,\n (1 - prune_size),\n res_type=set,\n random_state=random_state,\n )\n if self.verbosity >= 2:\n print(\n f\"pos_growset {len(pos_growset_idx)} pos_pruneset {len(pos_pruneset_idx)}\"\n )\n print(\n f\"neg_growset {len(neg_growset_idx)} neg_pruneset {len(neg_pruneset_idx)}\"\n )\n if len(pos_growset_idx) == 0:\n break # Probably safe, but a little dicey to only check pos_growset.\n\n # Grow Rule\n grown_rule = base_functions.grow_rule_cn(\n self.cn,\n pos_growset_idx,\n neg_growset_idx,\n initial_rule=Rule(),\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n if grown_rule.isempty():\n break # Generated an empty rule b/c no good conds exist\n\n # Prune Rule\n pruned_rule = base_functions.prune_rule_cn(\n self.cn,\n grown_rule,\n _RIPPER_growphase_prune_metric_cn,\n pos_pruneset_idx,\n neg_pruneset_idx,\n verbosity=self.verbosity,\n )\n\n # Add rule; calculate new description length\n ruleset.add(\n pruned_rule\n ) # Unlike IREP, IREP*/RIPPER stopping condition is inclusive: \"After each rule is added, the total description length of the rule set and examples is computed.\"\n if self.verbosity >= 2:\n print(f\"updated ruleset: {ruleset.truncstr(direction='right')}\")\n print()\n\n if ruleset_dl is None: # First Rule to be added\n rule_dl = _r_theory_bits(\n pruned_rule, ruleset.possible_conds, verbosity=self.verbosity\n )\n theory_dl = rule_dl\n data_dl = _exceptions_bits_cn(\n self.cn, ruleset, pos_idx, neg_idx, verbosity=self.verbosity\n )\n ruleset_dl = theory_dl + data_dl\n mdl = ruleset_dl\n else:\n rule_dl = _r_theory_bits(\n pruned_rule, ruleset.possible_conds, verbosity=self.verbosity\n )\n theory_dl += rule_dl\n data_dl = _exceptions_bits_cn(\n self.cn, ruleset, pos_idx, neg_idx, verbosity=self.verbosity\n )\n ruleset_dl = theory_dl + data_dl\n dl_diff = ruleset_dl - mdl\n\n if self.verbosity >= 3:\n print(f\"rule dl: {rnd(rule_dl)}\")\n print(f\"updated theory dl: {rnd(theory_dl)}\")\n print(f\"exceptions: {rnd(data_dl)}\")\n print(f\"total dl: {rnd(ruleset_dl)}\")\n if dl_diff <= self.dl_allowance:\n print(\n f\"mdl {rnd(mdl)} (diff {rnd(dl_diff)} <= {rnd(self.dl_allowance)})\"\n )\n else:\n print(\n f\"mdl {rnd(mdl)} dl-halt: diff {rnd(dl_diff)} exceeds allowance ({rnd(self.dl_allowance)})\"\n )\n\n mdl = ruleset_dl if ruleset_dl < mdl else mdl\n\n # Remove covered examples\n pos_remaining_idx, neg_remaining_idx = base_functions.rm_rule_covers_cn(\n self.cn, pruned_rule, pos_remaining_idx, neg_remaining_idx\n )\n\n if self.verbosity >= 3:\n print(\n f\"examples remaining: {len(pos_remaining_idx)} pos, {len(neg_remaining_idx)} neg\"\n )\n print()\n\n return ruleset\n\n def _optimize_ruleset(\n self,\n ruleset,\n pos_df,\n neg_df,\n prune_size,\n max_rule_conds=None,\n random_state=None,\n ):\n \"\"\"Optimization phase.\"\"\"\n\n if self.verbosity >= 2:\n print(\"optimizing ruleset...\")\n print()\n\n pos_remaining = pos_df.copy()\n neg_remaining = neg_df.copy()\n original_ruleset = copy.deepcopy(ruleset)\n if self.verbosity >= 4:\n print(\"calculate original ruleset potential dl...\")\n original_dl = _rs_total_bits(\n original_ruleset,\n original_ruleset.possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=True,\n verbosity=self.verbosity,\n )\n if self.verbosity >= 3:\n print(f\"original ruleset potential dl: {rnd(original_dl)}\")\n print()\n new_ruleset = copy.deepcopy(ruleset)\n\n for i, rule in enumerate(original_ruleset.rules):\n pos_growset, pos_pruneset = base_functions.df_shuffled_split(\n pos_remaining, (1 - prune_size), random_state=random_state\n )\n neg_growset, neg_pruneset = base_functions.df_shuffled_split(\n neg_remaining, (1 - prune_size), random_state=random_state\n )\n if len(pos_growset) == 0:\n break # Possible where optimization run > 1\n\n # Create alternative rules\n if self.verbosity >= 4:\n print(\n f\"creating replacement for {i} of {len(original_ruleset.rules)}: {ruleset.rules[i]}\"\n )\n g_replacement = base_functions.grow_rule(\n pos_growset,\n neg_growset,\n original_ruleset.possible_conds,\n initial_rule=Rule(),\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n replacement_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, g_replacement)\n )\n pr_replacement = base_functions.prune_rule(\n g_replacement,\n _RIPPER_optimization_prune_metric,\n pos_pruneset,\n neg_pruneset,\n eval_index_on_ruleset=(i, replacement_ruleset),\n verbosity=self.verbosity,\n )\n replacement_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, pr_replacement)\n )\n if self.verbosity >= 3:\n print(f\"grew replacement {g_replacement}\")\n print(f\"pruned replacement is {pr_replacement}\")\n\n if self.verbosity >= 3:\n print(\n f\"creating revision for {i} of {len(original_ruleset.rules)}: {ruleset.rules[i]}\"\n )\n g_revision = base_functions.grow_rule(\n pos_growset,\n neg_growset,\n original_ruleset.possible_conds,\n initial_rule=ruleset.rules[i],\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n revision_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, g_revision)\n )\n pr_revision = base_functions.prune_rule(\n g_revision,\n _RIPPER_optimization_prune_metric,\n pos_pruneset,\n neg_pruneset,\n eval_index_on_ruleset=(i, revision_ruleset),\n verbosity=self.verbosity,\n )\n revision_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, pr_revision)\n )\n if self.verbosity >= 3:\n print(f\"grew revision {g_replacement}\")\n print(f\"pruned revision is {pr_replacement}\")\n print()\n\n # Calculate alternative Rulesets' respective lowest potential dls to identify the best version\n if self.verbosity >= 3:\n print(\n f\"calculate potential dl for ds with replacement {pr_replacement}\"\n )\n replacement_dl = (\n _rs_total_bits(\n replacement_ruleset,\n original_ruleset.possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=True,\n verbosity=self.verbosity,\n )\n if pr_replacement != rule\n else original_dl\n )\n if self.verbosity >= 3:\n print(f\"calculate potential dl for ds with revision {pr_revision}\")\n revision_dl = (\n _rs_total_bits(\n revision_ruleset,\n original_ruleset.possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=True,\n verbosity=self.verbosity,\n )\n if pr_revision != rule\n else original_dl\n )\n best_rule = [rule, pr_replacement, pr_revision][\n base_functions.argmin([original_dl, replacement_dl, revision_dl])\n ]\n\n if self.verbosity >= 2:\n print(f\"\\nrule {i+1} of {len(original_ruleset.rules)}\")\n rep_str = (\n pr_replacement.__str__() if pr_replacement != rule else \"unchanged\"\n )\n rev_str = pr_revision.__str__() if pr_revision != rule else \"unchanged\"\n best_str = best_rule.__str__() if best_rule != rule else \"unchanged\"\n if self.verbosity == 2:\n print(f\"original: {rule}\")\n print(f\"replacement: {rep_str}\")\n print(f\"revision: {rev_str}\")\n print(f\"*best: {best_str}\")\n if best_rule in new_ruleset:\n print(\n f\"best already included in optimization -- retaining original\"\n )\n print()\n else:\n print(f\"original: {rule}) | {rnd(original_dl)} bits\")\n print(f\"replacement: {rep_str} | {rnd(replacement_dl)} bits\")\n print(f\"revision: {rev_str} | {rnd(revision_dl)} bits\")\n print(\n f\"*best: {best_str} | {rnd(min([replacement_dl, revision_dl, original_dl]))} bits\"\n )\n if best_rule in new_ruleset:\n print(\n f\"best already included in optimization -- retaining original\"\n )\n print()\n if best_rule not in new_ruleset:\n new_ruleset.rules[i] = best_rule\n else:\n new_ruleset.rules[i] = rule\n\n # Remove covered examples\n pos_remaining, neg_remaining = base_functions.rm_covered(\n rule, pos_remaining, neg_remaining\n )\n if self.verbosity >= 3:\n print(\n f\"examples remaining: {len(pos_remaining)} pos, {len(neg_remaining)} neg\"\n )\n print()\n\n # If there are no pos data remaining to train optimization (could happen if optimization run >1), keep remaining rules the same\n if len(pos_remaining) == 0:\n break\n\n return new_ruleset\n\n def _optimize_ruleset_cn(\n self,\n ruleset,\n pos_idx,\n neg_idx,\n prune_size,\n max_rule_conds=None,\n random_state=None,\n ):\n \"\"\"Optimization phase.\"\"\"\n\n if self.verbosity >= 2:\n print(\"optimizing ruleset...\")\n print()\n\n pos_remaining_idx = pos_idx\n neg_remaining_idx = neg_idx\n original_ruleset = copy.deepcopy(ruleset)\n if self.verbosity >= 4:\n print(\"calculate original ruleset potential dl...\")\n original_dl = _rs_total_bits_cn(\n self.cn,\n original_ruleset,\n original_ruleset.possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=True,\n verbosity=self.verbosity,\n )\n if self.verbosity >= 3:\n print(f\"original ruleset potential dl: {rnd(original_dl)}\")\n print()\n new_ruleset = copy.deepcopy(ruleset)\n\n for i, rule in enumerate(original_ruleset.rules):\n pos_growset_idx, pos_pruneset_idx = base_functions.set_shuffled_split(\n pos_remaining_idx, (1 - prune_size), random_state=random_state\n )\n neg_growset_idx, neg_pruneset_idx = base_functions.set_shuffled_split(\n neg_remaining_idx, (1 - prune_size), random_state=random_state\n )\n if len(pos_growset_idx) == 0:\n break # Possible where optimization run > 1\n\n # Create alternative rules\n if self.verbosity >= 4:\n print(\n f\"creating replacement for {i} of {len(original_ruleset.rules)}: {ruleset.rules[i]}\"\n )\n # g_replacement = base_functions.grow_rule(pos_growset, neg_growset, original_ruleset.possible_conds, initial_rule=Rule(), max_rule_conds=max_rule_conds, verbosity=self.verbosity)\n g_replacement = base_functions.grow_rule_cn(\n self.cn,\n pos_growset_idx,\n neg_growset_idx,\n initial_rule=Rule(),\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n replacement_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, g_replacement)\n )\n # pr_replacement = base_functions.prune_rule(g_replacement, _RIPPER_optimization_prune_metric, pos_pruneset, neg_pruneset, eval_index_on_ruleset=(i,replacement_ruleset), verbosity=self.verbosity)\n pr_replacement = base_functions.prune_rule_cn(\n self.cn,\n g_replacement,\n _RIPPER_optimization_prune_metric_cn,\n pos_pruneset_idx,\n neg_pruneset_idx,\n eval_index_on_ruleset=(i, replacement_ruleset),\n verbosity=self.verbosity,\n )\n replacement_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, pr_replacement)\n )\n if self.verbosity >= 3:\n print(f\"grew replacement {g_replacement}\")\n print(f\"pruned replacement is {pr_replacement}\")\n\n if self.verbosity >= 3:\n print(\n f\"creating revision for {i} of {len(original_ruleset.rules)}: {ruleset.rules[i]}\"\n )\n # g_revision = base_functions.grow_rule(pos_growset, neg_growset, original_ruleset.possible_conds, initial_rule=ruleset.rules[i], max_rule_conds=max_rule_conds, verbosity=self.verbosity)\n g_revision = base_functions.grow_rule_cn(\n self.cn,\n pos_growset_idx,\n neg_growset_idx,\n initial_rule=ruleset.rules[i],\n max_rule_conds=max_rule_conds,\n verbosity=self.verbosity,\n )\n revision_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, g_revision)\n )\n # pr_revision = base_functions.prune_rule(g_revision, _RIPPER_optimization_prune_metric, pos_pruneset, neg_pruneset, eval_index_on_ruleset=(i,revision_ruleset), verbosity=self.verbosity)\n pr_revision = base_functions.prune_rule_cn(\n self.cn,\n g_revision,\n _RIPPER_optimization_prune_metric_cn,\n pos_pruneset_idx,\n neg_pruneset_idx,\n eval_index_on_ruleset=(i, revision_ruleset),\n verbosity=self.verbosity,\n )\n revision_ruleset = Ruleset(\n base_functions.i_replaced(original_ruleset.rules, i, pr_revision)\n )\n if self.verbosity >= 3:\n print(f\"grew revision {g_replacement}\")\n print(f\"pruned revision is {pr_replacement}\")\n print()\n\n # Calculate alternative Rulesets' respective lowest potential dls to identify the best version\n if self.verbosity >= 3:\n print(\n f\"calculate potential dl for ds with replacement {pr_replacement}\"\n )\n replacement_dl = (\n _rs_total_bits_cn(\n self.cn,\n replacement_ruleset,\n original_ruleset.possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=False,\n ret_bestsubset=False,\n verbosity=0,\n )\n if pr_replacement != rule\n else original_dl\n )\n if self.verbosity >= 3:\n print(f\"calculate potential dl for ds with revision {pr_revision}\")\n revision_dl = (\n _rs_total_bits_cn(\n self.cn,\n revision_ruleset,\n original_ruleset.possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=False,\n ret_bestsubset=False,\n verbosity=0,\n )\n if pr_revision != rule\n else original_dl\n )\n best_rule = [rule, pr_replacement, pr_revision][\n base_functions.argmin([original_dl, replacement_dl, revision_dl])\n ]\n\n if self.verbosity >= 2:\n print(f\"\\nrule {i+1} of {len(original_ruleset.rules)}\")\n rep_str = (\n pr_replacement.__str__() if pr_replacement != rule else \"unchanged\"\n )\n rev_str = pr_revision.__str__() if pr_revision != rule else \"unchanged\"\n best_str = best_rule.__str__() if best_rule != rule else \"unchanged\"\n if self.verbosity == 2:\n print(f\"original: {rule}\")\n print(f\"replacement: {rep_str}\")\n print(f\"revision: {rev_str}\")\n print(f\"*best: {best_str}\")\n if best_rule in new_ruleset:\n print(\n f\"best already included in optimization -- retaining original\"\n )\n print()\n else:\n print(f\"original: {rule}) | {rnd(original_dl)} bits\")\n print(f\"replacement: {rep_str} | {rnd(replacement_dl)} bits\")\n print(f\"revision: {rev_str} | {rnd(revision_dl)} bits\")\n print(\n f\"*best: {best_str} | {rnd(min([replacement_dl, revision_dl, original_dl]))} bits\"\n )\n if best_rule in new_ruleset:\n print(\n f\"best already included in optimization -- retaining original\"\n )\n print()\n if best_rule not in new_ruleset:\n new_ruleset.rules[i] = best_rule\n else:\n new_ruleset.rules[i] = rule\n\n # Remove covered examples\n pos_remaining_idx, neg_remaining_idx = base_functions.rm_rule_covers_cn(\n self.cn, rule, pos_remaining_idx, neg_remaining_idx\n )\n if self.verbosity >= 3:\n print(\n f\"examples remaining: {len(pos_remaining_idx)} pos, {len(neg_remaining_idx)} neg\"\n )\n print()\n\n # If there are no pos data remaining to train optimization (could happen if optimization run >1), keep remaining rules the same\n if len(pos_remaining_idx) == 0:\n break\n\n return new_ruleset\n\n def _cover_remaining_positives(\n self,\n df,\n max_rules=None,\n max_rule_conds=None,\n max_total_conds=None,\n random_state=None,\n ):\n \"\"\"Stage 3: Post-optimization, cover any remaining uncovered positives.\"\"\"\n pos_remaining, neg_remaining = base_functions.pos_neg_split(\n df, self.class_feat, self.pos_class\n )\n pos_remaining = pos_remaining.drop(self.class_feat, axis=1)\n neg_remaining = neg_remaining.drop(self.class_feat, axis=1)\n pos_remaining, neg_remaining = base_functions.rm_covered(\n self.ruleset_, pos_remaining, neg_remaining\n )\n if len(pos_remaining) >= 1:\n if self.verbosity >= 2:\n print(f\"{len(pos_remaining)} pos left. Growing final rules...\")\n newset = self._grow_ruleset(\n pos_remaining,\n neg_remaining,\n initial_model=self.ruleset_,\n prune_size=self.prune_size,\n dl_allowance =self.dl_allowance,\n max_rules=max_rules,\n max_rule_conds=max_rule_conds,\n max_total_conds=max_total_conds,\n random_state=random_state,\n )\n if self.verbosity >= 1:\n print(\"GREW FINAL RULES\")\n newset.out_pretty()\n print()\n self.ruleset_ = newset\n else:\n if self.verbosity >= 1:\n print(\"All pos covered\\n\")\n\n def _cover_remaining_positives_cn(\n self,\n df,\n max_rules=None,\n max_rule_conds=None,\n max_total_conds=None,\n random_state=None,\n ):\n \"\"\"Stage 3: Post-optimization, cover any remaining uncovered positives.\"\"\"\n pos_remaining_idx, neg_remaining_idx = self.cn.pos_idx_neg_idx(\n df, self.class_feat, self.pos_class\n )\n\n if len(pos_remaining_idx) >= 1:\n if self.verbosity >= 2:\n print(f\"{len(pos_remaining_idx)} pos left. Growing final rules...\")\n newset = self._grow_ruleset_cn(\n pos_remaining_idx,\n neg_remaining_idx,\n initial_model=self.ruleset_,\n prune_size=self.prune_size,\n dl_allowance=self.dl_allowance,\n max_rules=max_rules,\n max_rule_conds=max_rule_conds,\n max_total_conds=max_total_conds,\n random_state=random_state,\n )\n if self.verbosity >= 1:\n print(\"GREW FINAL RULES\")\n newset.out_pretty()\n print()\n self.ruleset_ = newset\n else:\n if self.verbosity >= 1:\n print(\"All positives covered\\n\")\n\n def get_params(self, deep=True):\n return {param: self.__dict__.get(param) for param in self.VALID_HYPERPARAMETERS}\n\n def set_params(self, **parameters):\n for parameter, value in parameters.items():\n # if parameter in self.VALID_HYPERPARAMETERS:\n setattr(self, parameter, value)\n return self\n\n\n\n\n###################################\n##### RIPPER-specific Metrics #####\n###################################\n\n\ndef _RIPPER_growphase_prune_metric(rule, pos_pruneset, neg_pruneset):\n \"\"\"RIPPER/IREP* prune metric.\n Returns the prune value of a candidate Rule.\n\n Cohen's formula is (p-n) / (p+n).\n Unclear from the paper how they handle divzero (where p+n=0), so I Laplaced it.\n Weka's solution was to modify the formula to (p+1)/(p+n+2), but running with this because the (non-NaN) values I got appeared closer to those of the original formula.\n \"\"\"\n # I imagine Weka's is 1/2 because that's closer to a 50-50 class distribution?\n p = rule.num_covered(pos_pruneset)\n n = rule.num_covered(neg_pruneset)\n return (p - n + 1) / (p + n + 1)\n\n\ndef _RIPPER_growphase_prune_metric_cn(cn, rule, pos_pruneset_idx, neg_pruneset_idx):\n \"\"\"RIPPER/IREP* prune metric.\n Returns the prune value of a candidate Rule.\n\n Cohen's formula is (p-n) / (p+n).\n Unclear from the paper how they handle divzero (where p+n=0), so I Laplaced it.\n Weka's solution was to modify the formula to (p+1)/(p+n+2), but the (non-NaN) values I got appeared closer to those of the original formula.\n \"\"\"\n # I imagine Weka's is 1/2 because that's closer to a 50-50 class distribution?\n p = len(cn.rule_covers(rule, pos_pruneset_idx))\n n = len(cn.rule_covers(rule, neg_pruneset_idx))\n return (p - n + 1) / (p + n + 1)\n\n\ndef _RIPPER_optimization_prune_metric(rule, pos_pruneset, neg_pruneset):\n return base_functions._accuracy(rule, pos_pruneset, neg_pruneset)\n\n\ndef _RIPPER_optimization_prune_metric_cn(cn, rule, pos_pruneset_idx, neg_pruneset_idx):\n return base_functions._rule_accuracy_cn(\n cn, rule, pos_pruneset_idx, neg_pruneset_idx\n )\n\n\ndef _r_theory_bits(rule, possible_conds, bits_dict=None, verbosity=0):\n \"\"\"Returns description length (in bits) for a single Rule.\"\"\"\n\n if hasattr(rule, \"dl\"):\n return rule.dl\n else:\n # if type(rule) != Rule:\n # raise TypeError(f'param rule in _r_theory_bits is type {type(rule)}; it should be type Rule')\n k = len(rule.conds) # Number of rule conditions\n n = len(possible_conds) # Number of possible conditions\n pr = k / n\n\n S = k * math.log2(1 / pr) + (n - k) * math.log2((1 / (1 - pr))) # S(n, k, pr)\n K = math.log2(k) # Number bits need to send integer k\n rule_dl = 0.5 * (\n K + S\n ) # Divide by 2 a la Quinlan. Cohen: \"to adjust for possible redundency in attributes\"\n if verbosity >= 5:\n print(\n f\"rule theory bits| {rule} k {k} n {n} pr {rnd(pr)}: {rnd(rule_dl)} bits\"\n )\n\n # rule.dl = rule_dl\n return rule_dl\n\n\ndef _rs_theory_bits(ruleset, possible_conds, verbosity=0):\n \"\"\"Returns theory description length (in bits) for a Ruleset.\"\"\"\n\n # if type(ruleset) != Ruleset:\n # raise TypeError(f'param ruleset in _rs_theory_bits should be type Ruleset')\n total = 0\n for rule in ruleset.rules:\n total += _r_theory_bits(rule, possible_conds, verbosity=verbosity)\n # total += rule_bits(rule, possible_conds, rem_pos, rem_neg, verbosity=verbosity)\n # rem_pos, rem_neg = base.rm_covered(rule, rem_pos, rem_neg)\n if verbosity >= 5:\n print(f\"ruleset theory bits| {rnd(total)}\")\n\n # ruleset.dl = total\n return total\n\n\ndef _exceptions_bits(ruleset, pos_df, neg_df, verbosity=0):\n \"\"\"Returns description length (in bits) for exceptions to a Ruleset's coverage.\"\"\"\n\n if type(ruleset) != Ruleset:\n raise TypeError(\n f\"to avoid double-counting, _exceptions_bits should calculate exceptions over entire set of rules with type Ruleset\"\n )\n N = len(pos_df) + len(neg_df) # Total number of examples\n p = ruleset.num_covered(pos_df) + ruleset.num_covered(\n neg_df\n ) # Total number of examples classified as positive = total covered\n fp = ruleset.num_covered(\n neg_df\n ) # Number false positives = negatives covered by the ruleset\n fn = len(pos_df) - ruleset.num_covered(\n pos_df\n ) # Number false negatives = positives not covered by the ruleset\n exceptions_dl = math.log2(base_functions.nCr(p, fp)) + math.log2(\n base_functions.nCr((N - p), fn)\n )\n if verbosity >= 5:\n print(\n f\"exceptions_bits| {ruleset.truncstr()}: \\n N {N} p {p} fp {fp} fn {fn}: exceptions_bits {rnd(exceptions_dl)}\"\n )\n\n return exceptions_dl\n\n\ndef _exceptions_bits_cn(cn, ruleset, pos_idx, neg_idx, verbosity=0):\n \"\"\"Returns description length (in bits) for exceptions to a Ruleset's coverage.\"\"\"\n\n # if type(ruleset) != Ruleset:\n # raise TypeError(f'to avoid double-counting, _exceptions_bits should calculate exceptions over entire set of rules with type Ruleset')\n N = len(pos_idx) + len(neg_idx) # Total number of examples\n pos_cov = cn.ruleset_covers(ruleset, subset=pos_idx)\n neg_cov = cn.ruleset_covers(ruleset, subset=neg_idx)\n p = len(pos_cov) + len(\n neg_cov\n ) # Total number of examples classified as positive = total covered\n fp = len(neg_cov) # Number false positives = negatives covered by the ruleset\n fn = len(pos_idx) - len(\n pos_cov\n ) # Number false negatives = positives not covered by the ruleset\n exceptions_dl = math.log2(base_functions.nCr(p, fp)) + math.log2(\n base_functions.nCr((N - p), fn)\n )\n if verbosity >= 5:\n print(\n f\"exceptions_bits| {ruleset.truncstr()}: \\n N {N} p {p} fp {fp} fn {fn}: exceptions_bits {rnd(exceptions_dl)}\"\n )\n\n return exceptions_dl\n\n\ndef _rs_total_bits(\n ruleset,\n possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=False,\n ret_bestsubset=False,\n verbosity=0,\n):\n \"\"\"Returns total description length (in bits) of ruleset -- the sum of its theory dl and exceptions dl.\n\n bestsubset_dl : bool, default=False\n Whether to return estimated minimum possible dl were all rules that increase dl to be removed.\n ret_bestsubset : bool, default=False\n Whether to return the best subset that was found. Return format will be (<Ruleset>,dl).\n \"\"\"\n\n # The RIPPER paper is brief and unclear w/r how to evaluate a ruleset for best potential dl.\n\n # 1) Do you reevaluate already-visited rules or evaluate each rule independently of one another?\n # Weka's source code comments that you are not supposed to, and that this is \"bizarre.\"\n # Perhaps not recursing so -- and getting a possibly sub-optimal mdl -- could be viewed as a greedy time-saver?\n # After all, this is supposed to be an iterative algorithm, it could optimize more times with future k's,\n # and it's not like we're performing an exhaustive search of every possible combination anyways.\n\n # 2) In what order are you supposed to evaluate? FIFO or LIFO?\n # Footnote 7 suggests optimization is done FIFO; the previous page suggests IREP* final dl reduction is done LIFO;\n # and context suggests dl reduction should be performed the same way both times.\n\n # I chose to greedy for #1, and FIFO for #2 but may choose differently in a future version if it seems more appropriate.\n # In any case, RIPPER's strong performance on the test sets vs. RandomForest suggests it may not matter all that much.\n\n # if type(ruleset) != Ruleset:\n # raise TypeError(f'param ruleset in _rs_total_bits should be type Ruleset')\n if ret_bestsubset and not bestsubset_dl:\n raise ValueError(\n f\"ret_bestsubset must be True in order to return bestsubset_dl\"\n )\n\n if not bestsubset_dl:\n theory_bits = _rs_theory_bits(ruleset, possible_conds, verbosity=verbosity)\n data_bits = _exceptions_bits(ruleset, pos_df, neg_df, verbosity=verbosity)\n if verbosity >= 3:\n print(f\"total ruleset bits | {rnd(theory_bits + data_bits)}\")\n return theory_bits + data_bits\n else:\n # Collect the dl of each subset\n subset_dls = []\n theory_dl = 0\n if verbosity >= 5:\n print(f\"find best potential dl for {ruleset}:\")\n for i, rule in enumerate(\n ruleset.rules\n ): # Separating theory and exceptions dls in this way means you don't have to recalculate theory each time\n subset = Ruleset(ruleset.rules[: i + 1])\n rule_theory_dl = _r_theory_bits(rule, possible_conds, verbosity=verbosity)\n theory_dl += rule_theory_dl\n exceptions_dl = _exceptions_bits(\n subset, pos_df, neg_df, verbosity=verbosity\n )\n subset_dls.append(theory_dl + exceptions_dl)\n if verbosity >= 5:\n print(f\"subset 0-{i} | dl: {rnd(subset_dls[i])}\")\n\n # Build up the best Ruleset and calculate the mdl\n mdl_ruleset = Ruleset()\n for i, rule, in enumerate(ruleset.rules):\n if (\n i == 0 or subset_dls[i] <= subset_dls[i - 1]\n ): # Rule i does not worsen the dl\n mdl_ruleset.add(rule)\n if verbosity >= 5:\n print(f\"subset dls: {[(i,rnd(dl)) for i,dl in enumerate(subset_dls)]}\")\n print(f\"best potential ruleset: {mdl_ruleset}\")\n mdl = _rs_total_bits(\n mdl_ruleset,\n possible_conds,\n pos_df,\n neg_df,\n bestsubset_dl=False,\n verbosity=0,\n ) # About to print value below\n if verbosity >= 5:\n print(f\"best potential dl was {rnd(mdl)}\")\n print()\n if not ret_bestsubset:\n return mdl\n else:\n return (mdl_ruleset, mdl)\n\n\ndef _rs_total_bits_cn(\n cn,\n ruleset,\n possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=False,\n ret_bestsubset=False,\n verbosity=0,\n):\n \"\"\"Returns total description length (in bits) of ruleset -- the sum of its theory dl and exceptions dl.\n\n bestsubset_dl : bool, default=False\n Whether to return estimated minimum possible dl were all rules that increase dl to be removed.\n ret_bestsubset : bool, default=False\n Whether to return the best subset that was found. Return format will be (<Ruleset>,dl).\n \"\"\"\n\n # The RIPPER paper is brief and unclear w/r how to evaluate a ruleset for best potential dl.\n\n # 1) Do you reevaluate already-visited rules or evaluate each rule independently of one another?\n # Weka's source code comments that you are not supposed to, and that this is \"bizarre.\"\n # Perhaps not recursing so -- and getting a possibly sub-optimal mdl -- could be viewed as a greedy time-saver?\n # After all, this is supposed to be an iterative algorithm, it could optimize more times with future k's,\n # and it's not like we're performing an exhaustive search of every possible combination anyways.\n\n # 2) In what order are you supposed to evaluate? FIFO or LIFO?\n # Footnote 7 suggests optimization is done FIFO; the previous page suggests IREP* final dl reduction is done LIFO;\n # and context suggests dl reduction should be performed the same way both times.\n\n # I chose to greedy for #1, and FIFO for #2 but may choose differently in a future version if it seems more appropriate.\n # In any case, RIPPER's strong performance on the test sets vs. RandomForest suggests it may not matter all that much.\n\n # if type(ruleset) != Ruleset:\n # raise TypeError(f'param ruleset in _rs_total_bits should be type Ruleset')\n if ret_bestsubset and not bestsubset_dl:\n raise ValueError(\n f\"ret_bestsubset must be True in order to return bestsubset_dl\"\n )\n\n if not bestsubset_dl:\n theory_bits = _rs_theory_bits(ruleset, possible_conds, verbosity=verbosity)\n data_bits = _exceptions_bits_cn(\n cn, ruleset, pos_idx, neg_idx, verbosity=verbosity\n )\n if verbosity >= 3:\n print(f\"total ruleset bits | {rnd(theory_bits + data_bits)}\")\n return theory_bits + data_bits\n else:\n # Collect the dl of each subset\n subset_dls = []\n theory_dl = 0\n if verbosity >= 5:\n print(f\"find best potential dl for {ruleset}:\")\n for i, rule in enumerate(\n ruleset.rules\n ): # Separating theory and exceptions dls in this way means you don't have to recalculate theory each time\n subset = Ruleset(ruleset.rules[: i + 1])\n rule_theory_dl = _r_theory_bits(rule, possible_conds, verbosity=verbosity)\n theory_dl += rule_theory_dl\n exceptions_dl = _exceptions_bits_cn(\n cn, subset, pos_idx, neg_idx, verbosity=verbosity\n )\n subset_dls.append(theory_dl + exceptions_dl)\n if verbosity >= 5:\n print(f\"subset 0-{i} | dl: {rnd(subset_dls[i])}\")\n\n # Build up the best Ruleset and calculate the mdl\n mdl_ruleset = Ruleset()\n for i, rule, in enumerate(ruleset.rules):\n if (\n i == 0 or subset_dls[i] <= subset_dls[i - 1]\n ): # Rule i does not worsen the dl\n mdl_ruleset.add(rule)\n if verbosity >= 5:\n print(f\"subset dls: {[(i,rnd(dl)) for i,dl in enumerate(subset_dls)]}\")\n print(f\"best potential ruleset: {mdl_ruleset}\")\n mdl = _rs_total_bits_cn(\n cn,\n mdl_ruleset,\n possible_conds,\n pos_idx,\n neg_idx,\n bestsubset_dl=False,\n verbosity=0,\n ) # About to print value below\n if verbosity >= 5:\n print(f\"best potential dl was {rnd(mdl)}\")\n print()\n if not ret_bestsubset:\n return mdl\n else:\n return (mdl_ruleset, mdl)\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
antalszava/pytorch
[ "e28a49003a580a6559f0f4da78b3a8f8d9b25de8" ]
[ "torch/package/package_importer.py" ]
[ "import builtins\nimport importlib\nimport inspect\nimport io\nimport linecache\nimport os.path\nimport types\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import cast, Any, BinaryIO, Callable, Dict, List, Optional, Union\nfrom weakref import WeakValueDictionary\n\nimport torch\nfrom torch.serialization import _get_restore_location, _maybe_decode_ascii\n\nfrom ._directory_reader import DirectoryReader\nfrom ._importlib import (\n _calc___package__,\n _normalize_line_endings,\n _normalize_path,\n _resolve_name,\n _sanity_check,\n)\nfrom ._mangling import PackageMangler, demangle\nfrom ._package_unpickler import PackageUnpickler\nfrom .file_structure_representation import Directory, _create_directory_from_file_list\nfrom .glob_group import GlobPattern\nfrom .importer import Importer\n\n\nclass PackageImporter(Importer):\n \"\"\"Importers allow you to load code written to packages by :class:`PackageExporter`.\n Code is loaded in a hermetic way, using files from the package\n rather than the normal python import system. This allows\n for the packaging of PyTorch model code and data so that it can be run\n on a server or used in the future for transfer learning.\n\n The importer for packages ensures that code in the module can only be loaded from\n within the package, except for modules explicitly listed as external during export.\n The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on.\n This prevents \"implicit\" dependencies where the package runs locally because it is importing\n a locally-installed package, but then fails when the package is copied to another machine.\n \"\"\"\n\n \"\"\"The dictionary of already loaded modules from this package, equivalent to ``sys.modules`` but\n local to this importer.\n \"\"\"\n modules: Dict[str, types.ModuleType]\n\n def __init__(\n self,\n file_or_buffer: Union[str, torch._C.PyTorchFileReader, Path, BinaryIO],\n module_allowed: Callable[[str], bool] = lambda module_name: True,\n ):\n \"\"\"Open ``file_or_buffer`` for importing. This checks that the imported package only requires modules\n allowed by ``module_allowed``\n\n Args:\n file_or_buffer: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`),\n a string, or an ``os.PathLike`` object containing a filename.\n module_allowed (Callable[[str], bool], optional): A method to determine if a externally provided module\n should be allowed. Can be used to ensure packages loaded do not depend on modules that the server\n does not support. Defaults to allowing anything.\n\n Raises:\n ImportError: If the package will use a disallowed module.\n \"\"\"\n self.zip_reader: Any\n if isinstance(file_or_buffer, torch._C.PyTorchFileReader):\n self.filename = \"<pytorch_file_reader>\"\n self.zip_reader = file_or_buffer\n elif isinstance(file_or_buffer, (Path, str)):\n self.filename = str(file_or_buffer)\n if not os.path.isdir(self.filename):\n self.zip_reader = torch._C.PyTorchFileReader(self.filename)\n else:\n self.zip_reader = DirectoryReader(self.filename)\n else:\n self.filename = \"<binary>\"\n self.zip_reader = torch._C.PyTorchFileReader(file_or_buffer)\n\n self.root = _PackageNode(None)\n self.modules = {}\n self.extern_modules = self._read_extern()\n\n for extern_module in self.extern_modules:\n if not module_allowed(extern_module):\n raise ImportError(\n f\"package '{file_or_buffer}' needs the external module '{extern_module}' \"\n f\"but that module has been disallowed\"\n )\n self._add_extern(extern_module)\n\n for fname in self.zip_reader.get_all_records():\n self._add_file(fname)\n\n self.patched_builtins = builtins.__dict__.copy()\n self.patched_builtins[\"__import__\"] = self.__import__\n # Allow packaged modules to reference their PackageImporter\n self.modules[\"torch_package_importer\"] = self # type: ignore[assignment]\n\n self._mangler = PackageMangler()\n\n # used for reduce deserializaiton\n self.storage_context: Any = None\n self.last_map_location = None\n\n # used for torch.serialization._load\n self.Unpickler = lambda *args, **kwargs: PackageUnpickler(self, *args, **kwargs)\n\n def import_module(self, name: str, package=None):\n \"\"\"Load a module from the package if it hasn't already been loaded, and then return\n the module. Modules are loaded locally\n to the importer and will appear in ``self.modules`` rather than ``sys.modules``.\n\n Args:\n name (str): Fully qualified name of the module to load.\n package ([type], optional): Unused, but present to match the signature of importlib.import_module. Defaults to ``None``.\n\n Returns:\n types.ModuleType: The (possibly already) loaded module.\n \"\"\"\n # We should always be able to support importing modules from this package.\n # This is to support something like:\n # obj = importer.load_pickle(...)\n # importer.import_module(obj.__module__) <- this string will be mangled\n #\n # Note that _mangler.demangle will not demangle any module names\n # produced by a different PackageImporter instance.\n name = self._mangler.demangle(name)\n\n return self._gcd_import(name)\n\n def load_binary(self, package: str, resource: str) -> bytes:\n \"\"\"Load raw bytes.\n\n Args:\n package (str): The name of module package (e.g. ``\"my_package.my_subpackage\"``).\n resource (str): The unique name for the resource.\n\n Returns:\n bytes: The loaded data.\n \"\"\"\n\n path = self._zipfile_path(package, resource)\n return self.zip_reader.get_record(path)\n\n def load_text(\n self,\n package: str,\n resource: str,\n encoding: str = \"utf-8\",\n errors: str = \"strict\",\n ) -> str:\n \"\"\"Load a string.\n\n Args:\n package (str): The name of module package (e.g. ``\"my_package.my_subpackage\"``).\n resource (str): The unique name for the resource.\n encoding (str, optional): Passed to ``decode``. Defaults to ``'utf-8'``.\n errors (str, optional): Passed to ``decode``. Defaults to ``'strict'``.\n\n Returns:\n str: The loaded text.\n \"\"\"\n data = self.load_binary(package, resource)\n return data.decode(encoding, errors)\n\n def load_pickle(self, package: str, resource: str, map_location=None) -> Any:\n \"\"\"Unpickles the resource from the package, loading any modules that are needed to construct the objects\n using :meth:`import_module`.\n\n Args:\n package (str): The name of module package (e.g. ``\"my_package.my_subpackage\"``).\n resource (str): The unique name for the resource.\n map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``.\n\n Returns:\n Any: The unpickled object.\n \"\"\"\n pickle_file = self._zipfile_path(package, resource)\n restore_location = _get_restore_location(map_location)\n loaded_storages = {}\n loaded_reduces = {}\n storage_context = torch._C.DeserializationStorageContext()\n\n def load_tensor(dtype, size, key, location, restore_location):\n name = f\"{key}.storage\"\n\n if storage_context.has_storage(name):\n storage = storage_context.get_storage(name, dtype).storage()\n else:\n tensor = self.zip_reader.get_storage_from_record(\n \".data/\" + name, size, dtype\n )\n if isinstance(self.zip_reader, torch._C.PyTorchFileReader):\n storage_context.add_storage(name, tensor)\n storage = tensor.storage()\n loaded_storages[key] = restore_location(storage, location)\n\n def persistent_load(saved_id):\n assert isinstance(saved_id, tuple)\n typename = _maybe_decode_ascii(saved_id[0])\n data = saved_id[1:]\n\n if typename == \"storage\":\n storage_type, key, location, size = data\n dtype = storage_type.dtype\n\n if key not in loaded_storages:\n load_tensor(\n dtype,\n size,\n key,\n _maybe_decode_ascii(location),\n restore_location,\n )\n storage = loaded_storages[key]\n # TODO: Once we decide to break serialization FC, we can\n # stop wrapping with TypedStorage\n return torch.storage.TypedStorage(\n wrap_storage=storage._untyped(), dtype=dtype\n )\n elif typename == \"reduce_package\":\n # to fix BC breaking change, objects on this load path\n # will be loaded multiple times erroneously\n if len(data) == 2:\n func, args = data\n return func(self, *args)\n reduce_id, func, args = data\n if reduce_id not in loaded_reduces:\n loaded_reduces[reduce_id] = func(self, *args)\n return loaded_reduces[reduce_id]\n else:\n f\"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'\"\n\n # Load the data (which may in turn use `persistent_load` to load tensors)\n data_file = io.BytesIO(self.zip_reader.get_record(pickle_file))\n unpickler = self.Unpickler(data_file)\n unpickler.persistent_load = persistent_load\n\n @contextmanager\n def set_deserialization_context():\n # to let reduce_package access deserializaiton context\n self.storage_context = storage_context\n self.last_map_location = map_location\n try:\n yield\n finally:\n self.storage_context = None\n self.last_map_location = None\n\n with set_deserialization_context():\n result = unpickler.load()\n\n # TODO from zdevito:\n # This stateful weird function will need to be removed in our efforts\n # to unify the format. It has a race condition if multiple python\n # threads try to read independent files\n torch._utils._validate_loaded_sparse_tensors()\n\n return result\n\n def id(self):\n \"\"\"\n Returns internal identifier that torch.package uses to distinguish :class:`PackageImporter` instances.\n Looks like::\n\n <torch_package_0>\n \"\"\"\n return self._mangler.parent_name()\n\n def file_structure(\n self, *, include: \"GlobPattern\" = \"**\", exclude: \"GlobPattern\" = ()\n ) -> Directory:\n \"\"\"Returns a file structure representation of package's zipfile.\n\n Args:\n include (Union[List[str], str]): An optional string e.g. ``\"my_package.my_subpackage\"``, or optional list of strings\n for the names of the files to be inluded in the zipfile representation. This can also be\n a glob-style pattern, as described in :meth:`PackageExporter.mock`\n\n exclude (Union[List[str], str]): An optional pattern that excludes files whose name match the pattern.\n\n Returns:\n :class:`Directory`\n \"\"\"\n return _create_directory_from_file_list(\n self.filename, self.zip_reader.get_all_records(), include, exclude\n )\n\n def _read_extern(self):\n return (\n self.zip_reader.get_record(\".data/extern_modules\")\n .decode(\"utf-8\")\n .splitlines(keepends=False)\n )\n\n def _make_module(\n self, name: str, filename: Optional[str], is_package: bool, parent: str\n ):\n mangled_filename = self._mangler.mangle(filename) if filename else None\n spec = importlib.machinery.ModuleSpec(\n name,\n self, # type: ignore[arg-type]\n origin=\"<package_importer>\",\n is_package=is_package,\n )\n module = importlib.util.module_from_spec(spec)\n self.modules[name] = module\n module.__name__ = self._mangler.mangle(name)\n ns = module.__dict__\n ns[\"__spec__\"] = spec\n ns[\"__loader__\"] = self\n ns[\"__file__\"] = mangled_filename\n ns[\"__cached__\"] = None\n ns[\"__builtins__\"] = self.patched_builtins\n ns[\"__torch_package__\"] = True\n\n # Add this module to our private global registry. It should be unique due to mangling.\n assert module.__name__ not in _package_imported_modules\n _package_imported_modules[module.__name__] = module\n\n # pre-emptively install on the parent to prevent IMPORT_FROM from trying to\n # access sys.modules\n self._install_on_parent(parent, name, module)\n\n if filename is not None:\n assert mangled_filename is not None\n # pre-emptively install the source in `linecache` so that stack traces,\n # `inspect`, etc. work.\n assert filename not in linecache.cache # type: ignore[attr-defined]\n linecache.lazycache(mangled_filename, ns)\n\n code = self._compile_source(filename, mangled_filename)\n exec(code, ns)\n\n return module\n\n def _load_module(self, name: str, parent: str):\n cur: _PathNode = self.root\n for atom in name.split(\".\"):\n if not isinstance(cur, _PackageNode) or atom not in cur.children:\n raise ModuleNotFoundError(\n f'No module named \"{name}\" in self-contained archive \"{self.filename}\"'\n f\" and the module is also not in the list of allowed external modules: {self.extern_modules}\",\n name=name,\n )\n cur = cur.children[atom]\n if isinstance(cur, _ExternNode):\n module = self.modules[name] = importlib.import_module(name)\n return module\n return self._make_module(name, cur.source_file, isinstance(cur, _PackageNode), parent) # type: ignore[attr-defined]\n\n def _compile_source(self, fullpath: str, mangled_filename: str):\n source = self.zip_reader.get_record(fullpath)\n source = _normalize_line_endings(source)\n return compile(source, mangled_filename, \"exec\", dont_inherit=True)\n\n # note: named `get_source` so that linecache can find the source\n # when this is the __loader__ of a module.\n def get_source(self, module_name) -> str:\n # linecache calls `get_source` with the `module.__name__` as the argument, so we must demangle it here.\n module = self.import_module(demangle(module_name))\n return self.zip_reader.get_record(demangle(module.__file__)).decode(\"utf-8\")\n\n # note: named `get_resource_reader` so that importlib.resources can find it.\n # This is otherwise considered an internal method.\n def get_resource_reader(self, fullname):\n try:\n package = self._get_package(fullname)\n except ImportError:\n return None\n if package.__loader__ is not self:\n return None\n return _PackageResourceReader(self, fullname)\n\n def _install_on_parent(self, parent: str, name: str, module: types.ModuleType):\n if not parent:\n return\n # Set the module as an attribute on its parent.\n parent_module = self.modules[parent]\n if parent_module.__loader__ is self:\n setattr(parent_module, name.rpartition(\".\")[2], module)\n\n # note: copied from cpython's import code, with call to create module replaced with _make_module\n def _do_find_and_load(self, name):\n path = None\n parent = name.rpartition(\".\")[0]\n if parent:\n if parent not in self.modules:\n self._gcd_import(parent)\n # Crazy side-effects!\n if name in self.modules:\n return self.modules[name]\n parent_module = self.modules[parent]\n try:\n path = parent_module.__path__ # type: ignore[attr-defined]\n except AttributeError:\n msg = (_ERR_MSG + \"; {!r} is not a package\").format(name, parent)\n raise ModuleNotFoundError(msg, name=name) from None\n\n module = self._load_module(name, parent)\n\n self._install_on_parent(parent, name, module)\n\n return module\n\n # note: copied from cpython's import code\n def _find_and_load(self, name):\n module = self.modules.get(name, _NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return self._do_find_and_load(name)\n\n if module is None:\n message = \"import of {} halted; \" \"None in sys.modules\".format(name)\n raise ModuleNotFoundError(message, name=name)\n\n # To handle https://github.com/pytorch/pytorch/issues/57490, where std's\n # creation of fake submodules via the hacking of sys.modules is not import\n # friendly\n if name == \"os\":\n self.modules[\"os.path\"] = cast(Any, module).path\n elif name == \"typing\":\n self.modules[\"typing.io\"] = cast(Any, module).io\n self.modules[\"typing.re\"] = cast(Any, module).re\n\n return module\n\n def _gcd_import(self, name, package=None, level=0):\n \"\"\"Import and return the module based on its name, the package the call is\n being made from, and the level adjustment.\n\n This function represents the greatest common denominator of functionality\n between import_module and __import__. This includes setting __package__ if\n the loader did not.\n\n \"\"\"\n _sanity_check(name, package, level)\n if level > 0:\n name = _resolve_name(name, package, level)\n\n return self._find_and_load(name)\n\n # note: copied from cpython's import code\n def _handle_fromlist(self, module, fromlist, *, recursive=False):\n \"\"\"Figure out what __import__ should return.\n\n The import_ parameter is a callable which takes the name of module to\n import. It is required to decouple the function from assuming importlib's\n import implementation is desired.\n\n \"\"\"\n module_name = demangle(module.__name__)\n # The hell that is fromlist ...\n # If a package was imported, try to import stuff from fromlist.\n if hasattr(module, \"__path__\"):\n for x in fromlist:\n if not isinstance(x, str):\n if recursive:\n where = module_name + \".__all__\"\n else:\n where = \"``from list''\"\n raise TypeError(\n f\"Item in {where} must be str, \" f\"not {type(x).__name__}\"\n )\n elif x == \"*\":\n if not recursive and hasattr(module, \"__all__\"):\n self._handle_fromlist(module, module.__all__, recursive=True)\n elif not hasattr(module, x):\n from_name = \"{}.{}\".format(module_name, x)\n try:\n self._gcd_import(from_name)\n except ModuleNotFoundError as exc:\n # Backwards-compatibility dictates we ignore failed\n # imports triggered by fromlist for modules that don't\n # exist.\n if (\n exc.name == from_name\n and self.modules.get(from_name, _NEEDS_LOADING) is not None\n ):\n continue\n raise\n return module\n\n def __import__(self, name, globals=None, locals=None, fromlist=(), level=0):\n if level == 0:\n module = self._gcd_import(name)\n else:\n globals_ = globals if globals is not None else {}\n package = _calc___package__(globals_)\n module = self._gcd_import(name, package, level)\n if not fromlist:\n # Return up to the first dot in 'name'. This is complicated by the fact\n # that 'name' may be relative.\n if level == 0:\n return self._gcd_import(name.partition(\".\")[0])\n elif not name:\n return module\n else:\n # Figure out where to slice the module's name up to the first dot\n # in 'name'.\n cut_off = len(name) - len(name.partition(\".\")[0])\n # Slice end needs to be positive to alleviate need to special-case\n # when ``'.' not in name``.\n module_name = demangle(module.__name__)\n return self.modules[module_name[: len(module_name) - cut_off]]\n else:\n return self._handle_fromlist(module, fromlist)\n\n def _get_package(self, package):\n \"\"\"Take a package name or module object and return the module.\n\n If a name, the module is imported. If the passed or imported module\n object is not a package, raise an exception.\n \"\"\"\n if hasattr(package, \"__spec__\"):\n if package.__spec__.submodule_search_locations is None:\n raise TypeError(\"{!r} is not a package\".format(package.__spec__.name))\n else:\n return package\n else:\n module = self.import_module(package)\n if module.__spec__.submodule_search_locations is None:\n raise TypeError(\"{!r} is not a package\".format(package))\n else:\n return module\n\n def _zipfile_path(self, package, resource=None):\n package = self._get_package(package)\n assert package.__loader__ is self\n name = demangle(package.__name__)\n if resource is not None:\n resource = _normalize_path(resource)\n return f\"{name.replace('.', '/')}/{resource}\"\n else:\n return f\"{name.replace('.', '/')}\"\n\n def _get_or_create_package(\n self, atoms: List[str]\n ) -> \"Union[_PackageNode, _ExternNode]\":\n cur = self.root\n for i, atom in enumerate(atoms):\n node = cur.children.get(atom, None)\n if node is None:\n node = cur.children[atom] = _PackageNode(None)\n if isinstance(node, _ExternNode):\n return node\n if isinstance(node, _ModuleNode):\n name = \".\".join(atoms[:i])\n raise ImportError(\n f\"inconsistent module structure. module {name} is not a package, but has submodules\"\n )\n assert isinstance(node, _PackageNode)\n cur = node\n return cur\n\n def _add_file(self, filename: str):\n \"\"\"Assembles a Python module out of the given file. Will ignore files in the .data directory.\n\n Args:\n filename (str): the name of the file inside of the package archive to be added\n \"\"\"\n *prefix, last = filename.split(\"/\")\n if len(prefix) > 1 and prefix[0] == \".data\":\n return\n package = self._get_or_create_package(prefix)\n if isinstance(package, _ExternNode):\n raise ImportError(\n f\"inconsistent module structure. package contains a module file {filename}\"\n f\" that is a subpackage of a module marked external.\"\n )\n if last == \"__init__.py\":\n package.source_file = filename\n elif last.endswith(\".py\"):\n package_name = last[: -len(\".py\")]\n package.children[package_name] = _ModuleNode(filename)\n\n def _add_extern(self, extern_name: str):\n *prefix, last = extern_name.split(\".\")\n package = self._get_or_create_package(prefix)\n if isinstance(package, _ExternNode):\n return # the shorter extern covers this extern case\n package.children[last] = _ExternNode()\n\n\n_NEEDS_LOADING = object()\n_ERR_MSG_PREFIX = \"No module named \"\n_ERR_MSG = _ERR_MSG_PREFIX + \"{!r}\"\n\n\nclass _PathNode:\n pass\n\n\nclass _PackageNode(_PathNode):\n def __init__(self, source_file: Optional[str]):\n self.source_file = source_file\n self.children: Dict[str, _PathNode] = {}\n\n\nclass _ModuleNode(_PathNode):\n __slots__ = [\"source_file\"]\n\n def __init__(self, source_file: str):\n self.source_file = source_file\n\n\nclass _ExternNode(_PathNode):\n pass\n\n\n# A private global registry of all modules that have been package-imported.\n_package_imported_modules: WeakValueDictionary = WeakValueDictionary()\n\n# `inspect` by default only looks in `sys.modules` to find source files for classes.\n# Patch it to check our private registry of package-imported modules as well.\n_orig_getfile = inspect.getfile\n\n\ndef patched_getfile(object):\n if inspect.isclass(object):\n if getattr(object, '__module__', None) is not None and object.__module__ in _package_imported_modules:\n return _package_imported_modules[object.__module__].__file__\n return _orig_getfile(object)\n\n\ninspect.getfile = patched_getfile\n\n\nclass _PackageResourceReader:\n \"\"\"Private class used to support PackageImporter.get_resource_reader().\n\n Confirms to the importlib.abc.ResourceReader interface. Allowed to access\n the innards of PackageImporter.\n \"\"\"\n\n def __init__(self, importer, fullname):\n self.importer = importer\n self.fullname = fullname\n\n def open_resource(self, resource):\n from io import BytesIO\n\n return BytesIO(self.importer.load_binary(self.fullname, resource))\n\n def resource_path(self, resource):\n # The contract for resource_path is that it either returns a concrete\n # file system path or raises FileNotFoundError.\n if isinstance(\n self.importer.zip_reader, DirectoryReader\n ) and self.importer.zip_reader.has_record(\n os.path.join(self.fullname, resource)\n ):\n return os.path.join(\n self.importer.zip_reader.directory, self.fullname, resource\n )\n raise FileNotFoundError\n\n def is_resource(self, name):\n path = self.importer._zipfile_path(self.fullname, name)\n return self.importer.zip_reader.has_record(path)\n\n def contents(self):\n from pathlib import Path\n\n filename = self.fullname.replace(\".\", \"/\")\n\n fullname_path = Path(self.importer._zipfile_path(self.fullname))\n files = self.importer.zip_reader.get_all_records()\n subdirs_seen = set()\n for filename in files:\n try:\n relative = Path(filename).relative_to(fullname_path)\n except ValueError:\n continue\n # If the path of the file (which is relative to the top of the zip\n # namespace), relative to the package given when the resource\n # reader was created, has a parent, then it's a name in a\n # subdirectory and thus we skip it.\n parent_name = relative.parent.name\n if len(parent_name) == 0:\n yield relative.name\n elif parent_name not in subdirs_seen:\n subdirs_seen.add(parent_name)\n yield parent_name\n" ]
[ [ "torch._C.PyTorchFileReader", "torch._C.DeserializationStorageContext", "torch.serialization._maybe_decode_ascii", "torch.serialization._get_restore_location", "torch._utils._validate_loaded_sparse_tensors" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tmuntianu/supereeg
[ "cd6e3ca1a898f091ef2696281c9ea32d1baf3eea" ]
[ "docs/auto_examples/debug_predict.py" ]
[ "\n# -*- coding: utf-8 -*-\n\"\"\"\n=============================\ndebug predict\n=============================\n\nThis example shows debugging process for predict. Delete before pip push.\n\n\"\"\"\n\n# Code source: Lucy Owen & Andrew Heusser\n# License: MIT\n\n\nimport supereeg as se\nimport sys\nimport numpy as np\nfrom supereeg.helpers import _corr_column, _count_overlapping\ntry:\n from itertools import zip_longest\nexcept:\n from itertools import izip_longest as zip_longest\n\nfrom scipy.stats import zscore\n#\n# def round_it(locs, places):\n# \"\"\"\n# Rounding function\n#\n# Parameters\n# ----------\n# locs : float\n# Number be rounded\n#\n# places : int\n# Number of places to round\n#\n# Returns\n# ----------\n# result : float\n# Rounded number\n#\n#\n# \"\"\"\n# return np.round(locs, decimals=places)\n#\n# def get_rows(all_locations, subj_locations):\n# \"\"\"\n# This function indexes a subject's electrode locations in the full array of electrode locations\n#\n# Parameters\n# ----------\n# all_locations : ndarray\n# Full array of electrode locations\n#\n# subj_locations : ndarray\n# Array of subject's electrode locations\n#\n# Returns\n# ----------\n# results : list\n# Indexs for subject electrodes in the full array of electrodes\n#\n# \"\"\"\n# if subj_locations.ndim == 1:\n# subj_locations = subj_locations.reshape(1, 3)\n# inds = np.full([1, subj_locations.shape[0]], np.nan)\n# for i in range(subj_locations.shape[0]):\n# possible_locations = np.ones([all_locations.shape[0], 1])\n# try:\n# for c in range(all_locations.shape[1]):\n# possible_locations[all_locations[:, c] != subj_locations[i, c], :] = 0\n# inds[0, i] = np.where(possible_locations == 1)[0][0]\n# except:\n# pass\n# inds = inds[~np.isnan(inds)]\n# return [int(x) for x in inds]\n#\n# def known_unknown(fullarray, knownarray, subarray=None, electrode=None):\n# \"\"\"\n# This finds the indices for known and unknown electrodes in the full array of electrode locations\n#\n# Parameters\n# ----------\n# fullarray : ndarray\n# Full array of electrode locations - All electrodes that pass the kurtosis test\n#\n# knownarray : ndarray\n# Subset of known electrode locations - Subject's electrode locations that pass the kurtosis test (in the leave one out case, this is also has the specified location missing)\n#\n# subarray : ndarray\n# Subject's electrode locations (all)\n#\n# electrode : str\n# Index of electrode in subarray to remove (in the leave one out case)\n#\n# Returns\n# ----------\n# known_inds : list\n# List of known indices\n#\n# unknown_inds : list\n# List of unknown indices\n#\n# \"\"\"\n# ## where known electrodes are located in full matrix\n# known_inds = get_rows(round_it(fullarray, 3), round_it(knownarray, 3))\n# ## where the rest of the electrodes are located\n# unknown_inds = list(set(range(np.shape(fullarray)[0])) - set(known_inds))\n# if not electrode is None:\n# ## where the removed electrode is located in full matrix\n# rm_full_ind = get_rows(round_it(fullarray, 3), round_it(subarray[int(electrode)], 3))\n# ## where the removed electrode is located in the unknown index subset\n# rm_unknown_ind = np.where(np.array(unknown_inds) == np.array(rm_full_ind))[0].tolist()\n# return known_inds, unknown_inds, rm_unknown_ind\n# else:\n# return known_inds, unknown_inds\n#\n#\n# def chunker(iterable, n, fillvalue=None):\n# #\"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n# args = [iter(iterable)] * n\n# return zip_longest(fillvalue=fillvalue, *args)\n#\n# def time_by_file_index_bo(bo, ave_data, known_inds, unknown_inds):\n# \"\"\"\n# Session dependent function that calculates that finds either the timeseries or the correlation of the predicted and actual timeseries for a given location chunked by 25000 timepoints\n#\n# Parameters\n# ----------\n# fname : Data matrix (npz file)\n# The data to be analyzed.\n# Filename containing fields:\n# Y - time series\n# R - electrode locations\n# fname_labels - session number\n# sample_rate - sampling rate\n#\n# ave_data: ndarray\n# Average correlation matrix\n#\n# known_inds: list\n# Indices for known electrodes in average matrix\n#\n# unknown_inds: list\n# Indices for unknown electrodes in average matrix\n#\n# electrode_ind: int\n# Index for estimated location in average matrix (location in unknown_inds)\n#\n# k_flat_removed: list\n# Indices of good channels (pass kurtosis test) in Y\n#\n# electrode: int\n# Index of held out location in known_inds\n#\n# time_series: boolean\n# True: output is predicted and actual timeseries\n# False: output is predicted and actual correlation\n#\n# Returns\n# ----------\n# results : pandas dataframe\n# If timeseries input is:\n# True: output is predicted and actual timeseries\n# False: output is predicted and actual correlation\n#\n#\n# \"\"\"\n# file_inds = np.unique(np.atleast_2d(bo.sessions.values))\n# Kaa = np.float32(ave_data[known_inds, :][:, known_inds])\n# Kaa_inv = np.linalg.pinv(Kaa)\n# Kba = np.float32(ave_data[unknown_inds, :][:, known_inds])\n# results = []\n# for i in file_inds:\n# if np.shape(np.atleast_2d(bo.sessions.values))[1] == 1:\n# fname_labels = np.atleast_2d(bo.sessions.values).T\n# else:\n# fname_labels = np.atleast_2d(bo.sessions.values)\n# next_inds = np.where(fname_labels == i)[1]\n# ### this code should incorporate the average voltage of the known (subject) electrodes and the average for the unknown (the other subjects)\n# block_results = []\n# next = np.zeros((bo.get_data().shape[0], ave_data.shape[0]))\n# ### right now, this doesn't use an overlap in time, but this needs to be addressed when I see edge effects\n# for each in chunker(next_inds, 1000):\n#\n# next[:, unknown_inds] = np.squeeze(np.dot(np.dot(Kba, Kaa_inv),\n# zscore(np.float32(\n# bo.get_data().values[filter(lambda v: v is not None, each), :])).T).T)\n# next[:, known_inds] = np.squeeze(zscore(np.float32(bo.get_data().values[filter(lambda v: v is not None, each), :])))\n# if block_results==[]:\n# block_results = next\n# else:\n# block_results = np.vstack((block_results, next))\n# if results==[]:\n# results = block_results\n# else:\n# results = np.vstack((block_results, results))\n#\n# return results\n\n#\n# # simulate 100 locations\n# locs = se.simulate_locations(n_elecs=100, random_seed=True)\n#\n# # simulate brain object\n# bo = se.simulate_bo(n_samples=1000, sample_rate=100, cov='random', locs=locs, noise=0, random_seed=True)\n#\n# # sample 10 locations, and get indices\n# sub_locs = locs.sample(90, replace=False, random_state=123).sort_values(['x', 'y', 'z']).index.values.tolist()\n#\n# # index brain object to get sample patient\n# bo_sample = bo[: ,sub_locs]\n#\n# # plot sample patient locations\n# bo_sample.plot_locs()\n#\n# # plot sample patient data\n# bo_sample.plot_data()\n#\n# Model = se.Model(data=bo, locs=locs)\n#\n# R = Model.get_locs().values\n#\n# R_K_subj = bo_sample.get_locs().values\n#\n# known_inds, unknown_inds = known_unknown(R, R_K_subj, R_K_subj)\n#\n#\n#\n# recon_data = time_by_file_index_bo(bo_sample, Model.get_model(z_transform=False), known_inds, unknown_inds)\n#\n# bo_r = se.Brain(data=recon_data, locs = R, sample_rate=bo.sample_rate, sessions=bo.sessions.values)\n#\n#\n# corrs_1 = _corr_column(bo.get_data().values, bo_r.get_data().values)\n#\n# print('correlations with timeseries recon = ' + str(corrs_1[unknown_inds].mean()))\n#\n#\n# bo_s = Model.predict(bo_sample, nearest_neighbor=False)\n#\n# recon_labels = np.where(np.array(bo_s.label) != 'observed')\n#\n# corrs = _corr_column(bo.get_data().values, bo_s.get_data().values)\n#\n# print('correlations with predict function = ' + str(corrs[recon_labels].mean()))\n#\n# assert np.allclose(corrs, corrs_1)\n\n\n########## debug case 1 - null set ##################\n\n# set random seed to default and noise to 0\nrandom_seed = np.random.seed(123)\nnoise = 0\n\n# locs\nlocs = se.simulate_locations(n_elecs=100, set_random_seed=random_seed)\n\n# create model locs from 75 locations\nmo_locs = locs.sample(75, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create covariance matrix from random seed\nc = se.create_cov(cov='random', n_elecs=100)\n\n# pull out model from covariance matrix\ndata = c[:, mo_locs.index][mo_locs.index, :]\n\n# create model from subsetted covariance matrix and locations\nmodel = se.Model(data=data, locs=mo_locs, n_subs=1)\n\n# create brain object from the remaining locations - first find remaining 25 locations\nsub_locs = locs[~locs.index.isin(mo_locs.index)]\n\n# create a brain object with all gray locations\nbo = se.simulate_bo(n_samples=1000, sample_rate=100, locs=locs, noise=noise, random_seed=random_seed)\n\n# parse brain object to create synthetic patient data\ndata = bo.data.iloc[:, sub_locs.index]\n\n# put data and locations together in new sample brain object\nbo_sample = se.Brain(data=data.values, locs=sub_locs, sample_rate=100)\n\n# predict activity at all unknown locations\nrecon = model.predict(bo_sample, nearest_neighbor=False)\n\n# get reconstructed indices\nrecon_labels = np.where(np.array(recon.label) != 'observed')\n\n# actual = bo.data.iloc[:, unknown_ind]\nactual_data = bo.get_zscore_data()[:, recon_labels[0]]\n\nrecon_data = recon[:, recon_labels[0]].get_data().values\ncorr_vals = _corr_column(actual_data, recon_data)\n\nprint('case 1 (null set) correlation = ' +str(corr_vals.mean()))\n\n\n\n\n########## debug case 2 - subset ##################\n\n# set random seed to default and noise to 0\nrandom_seed = np.random.seed(123)\nnoise = 0\n\n# locs\nlocs = se.simulate_locations(n_elecs=100, set_random_seed=random_seed)\n\n# create model locs from 50 locations\nmo_locs = locs.sample(100, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create covariance matrix from random seed\nc = se.create_cov(cov='random', n_elecs=100)\n\n# pull out model from covariance matrix\ndata = c[:, mo_locs.index][mo_locs.index, :]\n\n# create model from subsetted covariance matrix and locations\nmodel = se.Model(data=data, locs=mo_locs, n_subs=1)\n\n# create brain object from subset of model locations\nsub_locs = mo_locs.sample(25, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create a brain object with all gray locations\nbo = se.simulate_bo(n_samples=1000, sample_rate=100, locs=mo_locs, noise=noise, random_seed=random_seed)\n\n# parse brain object to create synthetic patient data\ndata = bo.data.iloc[:, sub_locs.index]\n\n# put data and locations together in new sample brain object\nbo_sample = se.Brain(data=data.values, locs=sub_locs, sample_rate=100)\n\n# predict activity at all unknown locations\nrecon = model.predict(bo_sample, nearest_neighbor=False)\n\n# get reconstructed indices\nrecon_labels = np.where(np.array(recon.label) != 'observed')\n\n# actual = bo.data.iloc[:, unknown_ind]\nactual_data = bo.get_zscore_data()[:, recon_labels[0]]\n\nrecon_data = recon[:, recon_labels[0]].get_data().values\ncorr_vals = _corr_column(actual_data, recon_data)\n\nprint('case 2 (subset of model) correlation = ' +str(corr_vals.mean()))\n\n########## debug case 3 - overlapping set ##################\n\n# set random seed to default and noise to 0\nrandom_seed = np.random.seed(123)\nnoise = 0\n\n# locs\nlocs = se.simulate_locations(n_elecs=100, set_random_seed=random_seed)\n\n# create model locs from 75 locations\nmo_locs = locs.sample(75, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create covariance matrix from random seed\nc = se.create_cov(cov='random', n_elecs=100)\n\n# pull out model from covariance matrix\ndata = c[:, mo_locs.index][mo_locs.index, :]\n\n# create model from subsetted covariance matrix and locations\nmodel = se.Model(data=data, locs=mo_locs, n_subs=1)\n\n# create brain object from all the locations - first find remaining 25 location\nsub_locs = locs[~locs.index.isin(mo_locs.index)]\n\n# then add 25 locations subsetted from model locations\nsub_locs = sub_locs.append(mo_locs.sample(25, random_state=random_seed).sort_values(['x', 'y', 'z']))\n\n# then subsample 25 from those locations to get some overlapping\nsub_locs.sample(25, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create a brain object with all gray locations\nbo = se.simulate_bo(n_samples=1000, sample_rate=100, locs=locs, noise=noise, random_seed=random_seed)\n\n# parse brain object to create synthetic patient data\ndata = bo.data.iloc[:, sub_locs.index]\n\n# put data and locations together in new sample brain object\nbo_sample = se.Brain(data=data.values, locs=sub_locs, sample_rate=100)\n\n# predict activity at all unknown locations\nrecon = model.predict(bo_sample, nearest_neighbor=False)\n\n# get reconstructed indices\nrecon_labels = np.where(np.array(recon.label) != 'observed')\n\n# actual = bo.data.iloc[:, unknown_ind]\nactual_data = bo.get_zscore_data()[:, recon_labels[0]]\n\nrecon_data = recon[:, recon_labels[0]].get_data().values\ncorr_vals = _corr_column(actual_data, recon_data)\n\nprint('case 3 (some overlap of model) correlation = ' +str(corr_vals.mean()))\n\n########## debug case 4 - model subset of brain object ##################\n\n# set random seed to default and noise to 0\nrandom_seed = np.random.seed(123)\nnoise = 0\n\n# locs\nlocs = se.simulate_locations(n_elecs=100, set_random_seed=random_seed)\n\n# create brain locs from 75 locations\nbo_locs = locs.sample(75, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create model locs from 50 locations\nmo_locs = bo_locs.sample(50, random_state=random_seed).sort_values(['x', 'y', 'z'])\n\n# create covariance matrix from random seed\nc = se.create_cov(cov='random', n_elecs=100)\n\n# pull out model from covariance matrix\ndata = c[:, mo_locs.index][mo_locs.index, :]\n\n# create model from subsetted covariance matrix and locations\nmodel = se.Model(data=data, locs=mo_locs, n_subs=1)\n\n\n# create a brain object with all gray locations\nbo = se.simulate_bo(n_samples=1000, sample_rate=100, locs=locs, noise=noise, random_seed=random_seed)\n\n# parse brain object to create synthetic patient data\ndata = bo.data.iloc[:, bo_locs.index]\n\n# put data and locations together in new sample brain object\nbo_sample = se.Brain(data=data.values, locs=bo_locs, sample_rate=100)\n\n# predict activity at all unknown locations\nrecon = model.predict(bo_sample, nearest_neighbor=False)\n\n# get reconstructed indices - since model is entirely a subset of brain object,\n# there should be no reconstructed locations\nrecon_labels = np.where(np.array(recon.label) != 'observed')\n\n# actual = bo.data.iloc[:, unknown_ind]\nactual_data = bo_sample.get_zscore_data()\n\nrecon_data = recon.get_data().values\ncorr_vals = _corr_column(actual_data, recon_data)\n\nprint('case 4 (model subset of brain locs) correlation = ' +str(corr_vals.mean()))\n" ]
[ [ "numpy.array", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
adugnag/deSpeckNet-TF-GEE
[ "9758dee3dc1548985b542394a9b93c13bfdb9a56" ]
[ "test.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 31 17:57:51 2022\n\n@author: adugna\n\"\"\"\n\n\n\n# Import, authenticate and initialize the Earth Engine library.\nimport ee\nee.Initialize()\nimport helper\n\nimport tensorflow as tf\nprint('Tensorflow version is: ',tf.__version__)\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n\n###########################################\n# PARAMETERS\n###########################################\n\n#roi\ngeometry = ee.Geometry.Polygon(\n [[[103.08000490033993, -2.8225068747308946],\n [103.08000490033993, -2.9521181019620673],\n [103.29217836225399, -2.9521181019620673],\n [103.29217836225399, -2.8225068747308946]]])\n\ngeometry2 = ee.Geometry.Polygon(\n [[[103.28423388261817, -2.666639235594898],\n [103.28423388261817, -2.7983252476718885],\n [103.47786791582129, -2.7983252476718885],\n [103.47786791582129, -2.666639235594898]]])\n\n#Parameters\nparams = { # GCS bucket\n 'START_DATE': '2021-12-01', \n 'STOP_DATE': '2021-12-31', \n 'ORBIT': 'DESCENDING',\n 'RELATIVE_ORBIT_NUMBER':18, \n 'POLARIZATION': 'VVVH',\n 'ROI': geometry,\n 'FORMAT': 'DB',\n 'CLIP_TO_ROI': True,\n 'EXPORT': 'GCS',\n 'BUCKET' : 'GCS-bucket-name',\n 'DRIVE' : '/content/drive',\n 'FOLDER' : 'deSpeckNet',\n 'USER_ID' : 'users/adugnagirma',\n 'IMAGE_PREFIX' : 'deSpeckNet_TEST_PATCH_v3_',\n # Should be the same bands selected during data prep\n 'BANDS': ['VV', 'VH'],\n 'RESPONSE_TR' : ['VV_median', 'VH_median'],\n 'RESPONSE_TU' : ['VV', 'VH'],\n 'MASK' : ['VV_mask', 'VH_mask'],\n 'KERNEL_SIZE' : 256,\n 'KERNEL_SHAPE' : [256, 256],\n 'KERNEL_BUFFER' : [128, 128],\n 'MODEL_NAME': 'tune'\n }\n\n#process Sentinel 1 image collection\ns1_processed = helper.s1_prep(params)\nbandNames = s1_processed.first().bandNames().remove('angle')\ns1_processed = s1_processed.select(bandNames)\nprint('Number of images in the collection: ', s1_processed.size().getInfo())\n\nimage = s1_processed.first()\n\n###########################################\n# EXPORT AND INFERENCE\n###########################################\n\n# load the saved model\nif params['EXPORT'] == 'GCS':\n MODEL_DIR = 'gs://' + params['BUCKET'] + '/' + params['FOLDER'] + '/' + params['MODEL_NAME']\nelse:\n MODEL_DIR = params['DRIVE'] + '/' + params['FOLDER'] + '/' + params['MODEL_NAME']\n\n#custom_objects={'TransformerBlock': TransformerBlock}\nmodel = tf.keras.models.load_model(MODEL_DIR)\nmodel.summary()\n\n# Run the export. (Run the export only once)\nhelper.export(image, params)\n# Run the prediction.\nhelper.prediction(params)\n\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.config.list_physical_devices" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Strubbl/map-machine
[ "e2c6f8cd373bc5dba322129112cfa58874a8321b" ]
[ "map_machine/feature/road.py" ]
[ "\"\"\"\nWIP: road shape drawing.\n\"\"\"\nimport logging\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom typing import Any, Optional, Union\n\nimport numpy as np\nimport svgwrite\nfrom colour import Color\nfrom svgwrite import Drawing\nfrom svgwrite.filters import Filter\nfrom svgwrite.path import Path\nfrom svgwrite.shapes import Circle\n\nfrom map_machine.drawing import PathCommands\nfrom map_machine.geometry.flinger import Flinger\nfrom map_machine.geometry.vector import (\n Line,\n Polyline,\n compute_angle,\n norm,\n turn_by_angle,\n)\nfrom map_machine.osm.osm_reader import OSMNode, Tagged\nfrom map_machine.scheme import RoadMatcher\n\n__author__ = \"Sergey Vartanov\"\n__email__ = \"[email protected]\"\n\nDEFAULT_LANE_WIDTH: float = 3.7\nUSE_BLUR: bool = False\n\n\n@dataclass\nclass Lane:\n \"\"\"Road lane specification.\"\"\"\n\n width: Optional[float] = None # Width in meters\n is_forward: Optional[bool] = None # Whether lane is forward or backward\n min_speed: Optional[float] = None # Minimal speed on the lane\n # \"none\", \"merge_to_left\", \"slight_left\", \"slight_right\"\n turn: Optional[str] = None\n change: Optional[str] = None # \"not_left\", \"not_right\"\n destination: Optional[str] = None # Lane destination\n\n def set_forward(self, is_forward: bool) -> None:\n \"\"\"If true, lane is forward, otherwise it's backward.\"\"\"\n self.is_forward = is_forward\n\n def get_width(self, scale: float) -> float:\n \"\"\"Get lane width. We use standard 3.7 m lane.\"\"\"\n if self.width is None:\n return 3.7 * scale\n return self.width * scale\n\n\nclass RoadPart:\n \"\"\"Line part of the road.\"\"\"\n\n def __init__(\n self,\n point_1: np.ndarray,\n point_2: np.ndarray,\n lanes: list[Lane],\n scale: float,\n ) -> None:\n \"\"\"\n :param point_1: start point of the road part\n :param point_2: end point of the road part\n :param lanes: lane specification\n \"\"\"\n self.point_1: np.ndarray = point_1\n self.point_2: np.ndarray = point_2\n self.lanes: list[Lane] = lanes\n\n self.width: float\n if lanes:\n self.width = sum(map(lambda x: x.get_width(scale), lanes))\n else:\n self.width = 1.0\n\n self.left_offset: float = self.width / 2.0\n self.right_offset: float = self.width / 2.0\n\n self.turned: np.ndarray = norm(\n turn_by_angle(self.point_2 - self.point_1, np.pi / 2.0)\n )\n self.right_vector: np.ndarray = self.turned * self.right_offset\n self.left_vector: np.ndarray = -self.turned * self.left_offset\n\n self.right_connection: Optional[np.ndarray] = None\n self.left_connection: Optional[np.ndarray] = None\n self.right_projection: Optional[np.ndarray] = None\n self.left_projection: Optional[np.ndarray] = None\n\n self.left_outer: Optional[np.ndarray] = None\n self.right_outer: Optional[np.ndarray] = None\n self.point_a: Optional[np.ndarray] = None\n self.point_middle: Optional[np.ndarray] = None\n\n def update(self) -> None:\n \"\"\"Compute additional points.\"\"\"\n if self.left_connection is not None:\n self.right_projection = (\n self.left_connection + self.right_vector - self.left_vector\n )\n if self.right_connection is not None:\n self.left_projection = (\n self.right_connection - self.right_vector + self.left_vector\n )\n if (\n self.left_connection is not None\n and self.right_connection is not None\n ):\n a = np.linalg.norm(self.right_connection - self.point_1)\n b = np.linalg.norm(self.right_projection - self.point_1)\n if a > b:\n self.right_outer = self.right_connection\n self.left_outer = self.left_projection\n else:\n self.right_outer = self.right_projection\n self.left_outer = self.left_connection\n self.point_middle = self.right_outer - self.right_vector\n\n max_: float = 100.0\n\n if np.linalg.norm(self.point_middle - self.point_1) > max_:\n self.point_a = self.point_1 + max_ * norm(\n self.point_middle - self.point_1\n )\n self.right_outer = self.point_a + self.right_vector\n self.left_outer = self.point_a + self.left_vector\n else:\n self.point_a = self.point_middle\n\n def get_angle(self) -> float:\n \"\"\"Get an angle between line and x axis.\"\"\"\n return compute_angle(self.point_2 - self.point_1)\n\n def draw_normal(self, drawing: svgwrite.Drawing) -> None:\n \"\"\"Draw some debug lines.\"\"\"\n line: Path = drawing.path(\n (\"M\", self.point_1, \"L\", self.point_2),\n fill=\"none\",\n stroke=\"#8888FF\",\n stroke_width=self.width,\n )\n drawing.add(line)\n\n def draw_debug(self, drawing: svgwrite.Drawing) -> None:\n \"\"\"Draw some debug lines.\"\"\"\n line: Path = drawing.path(\n (\"M\", self.point_1, \"L\", self.point_2),\n fill=\"none\",\n stroke=\"#000000\",\n )\n drawing.add(line)\n line: Path = drawing.path(\n (\n \"M\", self.point_1 + self.right_vector,\n \"L\", self.point_2 + self.right_vector,\n ),\n fill=\"none\",\n stroke=\"#FF0000\",\n stroke_width=0.5,\n ) # fmt: skip\n drawing.add(line)\n line = drawing.path(\n (\n \"M\", self.point_1 + self.left_vector,\n \"L\", self.point_2 + self.left_vector,\n ),\n fill=\"none\",\n stroke=\"#0000FF\",\n stroke_width=0.5,\n ) # fmt: skip\n drawing.add(line)\n\n opacity: float = 0.4\n radius: float = 2\n\n if self.right_connection is not None:\n circle = drawing.circle(\n self.right_connection, 2.5, fill=\"#FF0000\", opacity=opacity\n )\n drawing.add(circle)\n if self.left_connection is not None:\n circle = drawing.circle(\n self.left_connection, 2.5, fill=\"#0000FF\", opacity=opacity\n )\n drawing.add(circle)\n\n if self.right_projection is not None:\n circle = drawing.circle(\n self.right_projection, 1.5, fill=\"#FF0000\", opacity=opacity\n )\n drawing.add(circle)\n if self.left_projection is not None:\n circle = drawing.circle(\n self.left_projection, 1.5, fill=\"#0000FF\", opacity=opacity\n )\n drawing.add(circle)\n\n if self.right_outer is not None:\n circle = drawing.circle(\n self.right_outer,\n 3.5,\n stroke_width=0.5,\n fill=\"none\",\n stroke=\"#FF0000\",\n opacity=opacity,\n )\n drawing.add(circle)\n if self.left_outer is not None:\n circle = drawing.circle(\n self.left_outer,\n 3.5,\n stroke_width=0.5,\n fill=\"none\",\n stroke=\"#0000FF\",\n opacity=opacity,\n )\n drawing.add(circle)\n\n if self.point_a is not None:\n circle = drawing.circle(self.point_a, radius, fill=\"#000000\")\n drawing.add(circle)\n\n # self.draw_entrance(drawing, True)\n\n def draw(self, drawing: svgwrite.Drawing) -> None:\n \"\"\"Draw road part.\"\"\"\n if self.left_connection is not None:\n path_commands = [\n \"M\", self.point_2 + self.right_vector,\n \"L\", self.point_2 + self.left_vector,\n \"L\", self.left_connection,\n \"L\", self.right_connection,\n \"Z\",\n ] # fmt: skip\n drawing.add(drawing.path(path_commands, fill=\"#CCCCCC\"))\n\n def draw_entrance(\n self, drawing: svgwrite.Drawing, is_debug: bool = False\n ) -> None:\n \"\"\"Draw intersection entrance part.\"\"\"\n if (\n self.left_connection is not None\n and self.right_connection is not None\n ):\n path_commands = [\n \"M\", self.right_projection,\n \"L\", self.right_connection,\n \"L\", self.left_projection,\n \"L\", self.left_connection,\n \"Z\",\n ] # fmt: skip\n if is_debug:\n path = drawing.path(\n path_commands,\n fill=\"none\",\n stroke=\"#880088\",\n stroke_width=0.5,\n )\n drawing.add(path)\n else:\n drawing.add(drawing.path(path_commands, fill=\"#88FF88\"))\n\n def draw_lanes(self, drawing: svgwrite.Drawing, scale: float) -> None:\n \"\"\"Draw lane delimiters.\"\"\"\n for lane in self.lanes:\n shift = self.right_vector - self.turned * lane.get_width(scale)\n path = drawing.path(\n [\"M\", self.point_middle + shift, \"L\", self.point_2 + shift],\n fill=\"none\",\n stroke=\"#FFFFFF\",\n stroke_width=2,\n stroke_dasharray=\"7,7\",\n )\n drawing.add(path)\n\n\nclass Intersection:\n \"\"\"\n An intersection of the roads, that is described by its parts. All first\n points of the road parts should be the same.\n \"\"\"\n\n def __init__(self, parts: list[RoadPart]) -> None:\n self.parts: list[RoadPart] = sorted(parts, key=lambda x: x.get_angle())\n\n for index, part_1 in enumerate(self.parts):\n next_index: int = 0 if index == len(self.parts) - 1 else index + 1\n part_2: RoadPart = self.parts[next_index]\n line_1: Line = Line(\n part_1.point_1 + part_1.right_vector,\n part_1.point_2 + part_1.right_vector,\n )\n line_2: Line = Line(\n part_2.point_1 + part_2.left_vector,\n part_2.point_2 + part_2.left_vector,\n )\n intersection: np.ndarray = line_1.get_intersection_point(line_2)\n # if np.linalg.norm(intersection - part_1.point_2) < 300:\n part_1.right_connection = intersection\n part_2.left_connection = intersection\n part_1.update()\n part_2.update()\n\n for index, part_1 in enumerate(self.parts):\n next_index: int = 0 if index == len(self.parts) - 1 else index + 1\n part_2: RoadPart = self.parts[next_index]\n part_1.update()\n part_2.update()\n\n if (\n part_1.right_connection is None\n and part_2.left_connection is None\n ):\n part_1.left_connection = part_1.right_projection\n part_2.right_connection = part_2.left_projection\n part_1.left_outer = part_1.right_projection\n part_2.right_outer = part_2.left_projection\n\n part_1.update()\n part_2.update()\n\n def draw(self, drawing: svgwrite.Drawing, is_debug: bool = False) -> None:\n \"\"\"Draw all road parts and intersection.\"\"\"\n inner_commands = [\"M\"]\n for part in self.parts:\n inner_commands += [part.left_connection, \"L\"]\n inner_commands[-1] = \"Z\"\n\n outer_commands = [\"M\"]\n for part in self.parts:\n outer_commands += [part.left_connection, \"L\"]\n outer_commands += [part.left_outer, \"L\"]\n outer_commands += [part.right_outer, \"L\"]\n outer_commands[-1] = \"Z\"\n\n # for part in self.parts:\n # part.draw_normal(drawing)\n\n if is_debug:\n drawing.add(\n drawing.path(outer_commands, fill=\"#0000FF\", opacity=0.2)\n )\n drawing.add(\n drawing.path(inner_commands, fill=\"#FF0000\", opacity=0.2)\n )\n\n for part in self.parts:\n if is_debug:\n part.draw_debug(drawing)\n else:\n part.draw_entrance(drawing)\n if not is_debug:\n # for part in self.parts:\n # part.draw_lanes(drawing, scale)\n drawing.add(drawing.path(inner_commands, fill=\"#FF8888\"))\n\n\nclass Road(Tagged):\n \"\"\"Road or track on the map.\"\"\"\n\n def __init__(\n self,\n tags: dict[str, str],\n nodes: list[OSMNode],\n matcher: RoadMatcher,\n flinger: Flinger,\n ) -> None:\n super().__init__(tags)\n self.nodes: list[OSMNode] = nodes\n self.matcher: RoadMatcher = matcher\n\n self.line: Polyline = Polyline(\n [flinger.fling(node.coordinates) for node in self.nodes]\n )\n self.width: Optional[float] = matcher.default_width\n self.lanes: list[Lane] = []\n\n self.scale: float = flinger.get_scale(self.nodes[0].coordinates)\n\n if \"lanes\" in tags:\n try:\n self.width = int(tags[\"lanes\"]) * DEFAULT_LANE_WIDTH\n self.lanes = [Lane()] * int(tags[\"lanes\"])\n except ValueError:\n pass\n\n if \"width:lanes\" in tags:\n try:\n widths: list[float] = list(\n map(float, tags[\"width:lanes\"].split(\"|\"))\n )\n if len(widths) == len(self.lanes):\n for index, lane in enumerate(self.lanes):\n lane.width = widths[index]\n except ValueError:\n pass\n\n number: int\n if \"lanes:forward\" in tags:\n number = int(tags[\"lanes:forward\"])\n map(lambda x: x.set_forward(True), self.lanes[-number:])\n if \"lanes:backward\" in tags:\n number = int(tags[\"lanes:backward\"])\n map(lambda x: x.set_forward(False), self.lanes[:number])\n\n if \"width\" in tags:\n try:\n self.width = float(tags[\"width\"])\n except ValueError:\n pass\n\n self.layer: float = 0.0\n if \"layer\" in tags:\n self.layer = float(tags[\"layer\"])\n\n self.placement_offset: float = 0.0\n self.is_transition: bool = False\n\n if \"placement\" in tags:\n value: str = tags[\"placement\"]\n if value == \"transition\":\n self.is_transition = True\n elif \":\" in value and len(parts := value.split(\":\")) == 2:\n place, lane_string = parts\n lane_number: int = int(lane_string) - 1\n self.placement_offset = -self.width * self.scale / 2.0\n if lane_number > 0:\n self.placement_offset += sum(\n lane.get_width(self.scale)\n for lane in self.lanes[:lane_number]\n )\n elif lane_number < 0:\n self.placement_offset += (\n DEFAULT_LANE_WIDTH * lane_number * self.scale\n )\n\n if place == \"left_of\":\n pass\n elif place == \"middle_of\":\n self.placement_offset += (\n self.lanes[lane_number].get_width(self.scale) * 0.5\n )\n elif place == \"right_of\":\n self.placement_offset += self.lanes[lane_number].get_width(\n self.scale\n )\n else:\n logging.error(f\"Unknown placement `{place}`.\")\n\n def get_style(\n self, is_border: bool, is_for_stroke: bool = False\n ) -> dict[str, Union[int, float, str]]:\n \"\"\"Get road SVG style.\"\"\"\n width: float\n if self.width is not None:\n width = self.width\n else:\n width = self.matcher.default_width\n\n border_width: float\n if is_border:\n color = self.get_border_color()\n border_width = 2.0\n else:\n color = self.get_color()\n border_width = 0.0\n\n extra_width: float = 0.0\n if is_border:\n if self.tags.get(\"bridge\") == \"yes\":\n extra_width = 0.5\n if self.tags.get(\"ford\") == \"yes\":\n extra_width = 2.0\n if self.tags.get(\"embankment\") == \"yes\":\n extra_width = 4.0\n\n style: dict[str, Union[int, float, str]] = {\n \"fill\": \"none\",\n \"stroke\": color.hex,\n \"stroke-linecap\": \"butt\",\n \"stroke-linejoin\": \"round\",\n \"stroke-width\": self.scale * width + extra_width + border_width,\n }\n if is_for_stroke:\n style[\"stroke-width\"] = 2.0 + extra_width\n if is_border and self.tags.get(\"embankment\") == \"yes\":\n style[\"stroke-dasharray\"] = \"1,3\"\n if self.tags.get(\"tunnel\") == \"yes\":\n if is_border:\n style[\"stroke-dasharray\"] = \"3,3\"\n\n return style\n\n def get_filter(self, svg: Drawing, is_border: bool) -> Optional[Filter]:\n \"\"\"Get blurring filter.\"\"\"\n if not USE_BLUR:\n return None\n\n if is_border and self.tags.get(\"bridge\") == \"yes\":\n filter_ = svg.defs.add(svg.filter())\n filter_.feGaussianBlur(in_=\"SourceGraphic\", stdDeviation=2)\n return filter_\n\n return None\n\n def draw(self, svg: Drawing, is_border: bool) -> None:\n \"\"\"Draw road as simple SVG path.\"\"\"\n filter_: Filter = self.get_filter(svg, is_border)\n\n style: dict[str, Union[int, float, str]] = self.get_style(is_border)\n path_commands: str = self.line.get_path(self.placement_offset)\n path: Path\n if filter_:\n path = Path(d=path_commands, filter=filter_.get_funciri())\n else:\n path = Path(d=path_commands)\n\n path.update(style)\n svg.add(path)\n\n def get_color(self) -> Color:\n \"\"\"Get road main color.\"\"\"\n color: Color = self.matcher.color\n if self.tags.get(\"tunnel\") == \"yes\":\n color = Color(color, luminance=min(1.0, color.luminance + 0.2))\n return color\n\n def get_border_color(self) -> Color:\n \"\"\"Get road border color.\"\"\"\n color: Color = self.matcher.border_color\n if self.tags.get(\"bridge\") == \"yes\":\n color = Color(\"#666666\")\n if self.tags.get(\"ford\") == \"yes\":\n color = Color(\"#88BBFF\")\n if self.tags.get(\"embankment\") == \"yes\":\n color = Color(\"#666666\")\n return color\n\n def draw_lanes(self, svg: Drawing, color: Color) -> None:\n \"\"\"Draw lane separators.\"\"\"\n if len(self.lanes) < 2:\n return\n\n for index in range(1, len(self.lanes)):\n lane_offset: float = self.scale * (\n -self.width / 2.0 + index * self.width / len(self.lanes)\n )\n path: Path = Path(\n d=self.line.get_path(self.placement_offset + lane_offset)\n )\n style: dict[str, Any] = {\n \"fill\": \"none\",\n \"stroke\": color.hex,\n \"stroke-linejoin\": \"round\",\n \"stroke-width\": 1.0,\n \"opacity\": 0.5,\n }\n path.update(style)\n svg.add(path)\n\n def draw_caption(self, svg: Drawing) -> None:\n \"\"\"Draw road name along its path.\"\"\"\n name: Optional[str] = self.tags.get(\"name\")\n if not name:\n return\n\n path: Path = svg.path(\n d=self.line.get_path(self.placement_offset + 3.0), fill=\"none\"\n )\n svg.add(path)\n\n text = svg.add(svg.text.Text(\"\"))\n text_path = svg.text.TextPath(\n path=path,\n text=name,\n startOffset=None,\n method=\"align\",\n spacing=\"exact\",\n font_family=\"Roboto\",\n font_size=10.0,\n )\n text.add(text_path)\n\n\ndef get_curve_points(\n road: Road,\n center: np.ndarray,\n road_end: np.ndarray,\n placement_offset: float,\n is_end: bool,\n) -> list[np.ndarray]:\n \"\"\"\n :param road: road segment\n :param center: road intersection point\n :param road_end: end point of the road segment\n :param placement_offset: offset based on placement tag value\n :param is_end: whether the point represents road end\n \"\"\"\n width: float = road.width / 2.0 * road.scale\n\n direction: np.ndarray = (center - road_end) / np.linalg.norm(\n center - road_end\n )\n if is_end:\n direction = -direction\n left: np.ndarray = turn_by_angle(direction, np.pi / 2.0) * (\n width + placement_offset\n )\n right: np.ndarray = turn_by_angle(direction, -np.pi / 2.0) * (\n width - placement_offset\n )\n\n return [road_end + left, center + left, center + right, road_end + right]\n\n\nclass Connector:\n \"\"\"Two roads connection.\"\"\"\n\n def __init__(\n self,\n connections: list[tuple[Road, int]],\n flinger: Flinger,\n ) -> None:\n self.connections: list[tuple[Road, int]] = connections\n self.road_1: Road\n self.index_1: int\n self.road_1, self.index_1 = connections[0]\n self.priority = self.road_1.matcher.priority\n\n self.min_layer: float = min(\n connection[0].layer for connection in connections\n )\n self.max_layer: float = max(\n connection[0].layer for connection in connections\n )\n self.scale: float = self.road_1.scale\n self.flinger: Flinger = flinger\n\n def draw(self, svg: Drawing) -> None:\n \"\"\"Draw connection fill.\"\"\"\n raise NotImplementedError\n\n def draw_border(self, svg: Drawing) -> None:\n \"\"\"Draw connection outline.\"\"\"\n raise NotImplementedError\n\n\nclass SimpleConnector(Connector):\n \"\"\"Simple connection between roads that don't change width.\"\"\"\n\n def __init__(\n self,\n connections: list[tuple[Road, int]],\n flinger: Flinger,\n ) -> None:\n super().__init__(connections, flinger)\n\n self.road_2: Road = connections[1][0]\n self.index_2: int = connections[1][1]\n\n node: OSMNode = self.road_1.nodes[self.index_1]\n self.point: np.ndarray = flinger.fling(node.coordinates)\n\n def draw(self, svg: Drawing) -> None:\n \"\"\"Draw connection fill.\"\"\"\n circle: Circle = svg.circle(\n self.point,\n self.road_1.width * self.scale / 2.0,\n fill=self.road_1.get_color().hex,\n )\n svg.add(circle)\n\n def draw_border(self, svg: Drawing) -> None:\n \"\"\"Draw connection outline.\"\"\"\n circle: Circle = svg.circle(\n self.point,\n self.road_1.width * self.scale / 2.0 + 1.0,\n fill=self.road_1.matcher.border_color.hex,\n )\n svg.add(circle)\n\n\nclass ComplexConnector(Connector):\n \"\"\"Connection between two roads that change width.\"\"\"\n\n def __init__(\n self,\n connections: list[tuple[Road, int]],\n flinger: Flinger,\n ) -> None:\n super().__init__(connections, flinger)\n\n self.road_2: Road = connections[1][0]\n self.index_2: int = connections[1][1]\n\n length: float = (\n abs(self.road_2.width - self.road_1.width) * self.road_1.scale\n )\n self.road_1.line.shorten(self.index_1, length)\n self.road_2.line.shorten(self.index_2, length)\n\n node_1: OSMNode = self.road_1.nodes[self.index_1]\n point_1: np.ndarray = flinger.fling(node_1.coordinates)\n node_2: OSMNode = self.road_2.nodes[self.index_2]\n point_2: np.ndarray = flinger.fling(node_2.coordinates)\n point = (point_1 + point_2) / 2.0\n\n points_1: list[np.ndarray] = get_curve_points(\n self.road_1,\n point,\n self.road_1.line.points[self.index_1],\n self.road_1.placement_offset,\n self.index_1 != 0,\n )\n points_2: list[np.ndarray] = get_curve_points(\n self.road_2,\n point,\n self.road_2.line.points[self.index_2],\n self.road_2.placement_offset,\n self.index_2 != 0,\n )\n # fmt: off\n self.curve_1: PathCommands = [\n points_1[0], \"C\", points_1[1], points_2[1], points_2[0]\n ]\n self.curve_2: PathCommands = [\n points_2[3], \"C\", points_2[2], points_1[2], points_1[3]\n ]\n # fmt: on\n\n def draw(self, svg: Drawing) -> None:\n \"\"\"Draw connection fill.\"\"\"\n path: Path = svg.path(\n d=[\"M\"] + self.curve_1 + [\"L\"] + self.curve_2 + [\"Z\"],\n fill=self.road_1.get_color(),\n )\n svg.add(path)\n\n def draw_border(self, svg: Drawing) -> None:\n \"\"\"Draw connection outline.\"\"\"\n filter_: Filter = self.road_1.get_filter(svg, True)\n\n if filter_:\n path: Path = svg.path(\n d=[\"M\"] + self.curve_1 + [\"M\"] + self.curve_2,\n filter=filter_.get_funciri(),\n )\n else:\n path: Path = svg.path(d=[\"M\"] + self.curve_1 + [\"M\"] + self.curve_2)\n path.update(self.road_1.get_style(True, True))\n svg.add(path)\n\n\nclass SimpleIntersection(Connector):\n \"\"\"Connection between more than two roads.\"\"\"\n\n def draw(self, svg: Drawing) -> None:\n \"\"\"Draw connection fill.\"\"\"\n for road, _ in sorted(\n self.connections, key=lambda x: x[0].matcher.priority\n ):\n node: OSMNode = self.road_1.nodes[self.index_1]\n point: np.ndarray = self.flinger.fling(node.coordinates)\n circle: Circle = svg.circle(\n point,\n road.width * self.scale / 2.0,\n fill=road.matcher.color.hex,\n )\n svg.add(circle)\n\n def draw_border(self, svg: Drawing) -> None:\n \"\"\"Draw connection outline.\"\"\"\n for road, _ in self.connections:\n node: OSMNode = self.road_1.nodes[self.index_1]\n point: np.ndarray = self.flinger.fling(node.coordinates)\n circle: Circle = svg.circle(\n point,\n road.width * self.scale / 2.0 + 1.0,\n fill=road.matcher.border_color.hex,\n )\n svg.add(circle)\n\n\nclass Roads:\n \"\"\"Whole road structure.\"\"\"\n\n def __init__(self) -> None:\n self.roads: list[Road] = []\n self.nodes: dict[int, list[tuple[Road, int]]] = {}\n\n def append(self, road: Road) -> None:\n \"\"\"Add road and update connections.\"\"\"\n self.roads.append(road)\n for index, node in enumerate(road.nodes):\n if node.id_ not in self.nodes:\n self.nodes[node.id_] = []\n self.nodes[node.id_].append((road, index))\n\n def draw(\n self, svg: Drawing, flinger: Flinger, draw_captions: bool = False\n ) -> None:\n \"\"\"Draw whole road system.\"\"\"\n if not self.roads:\n return\n\n layered_roads: dict[float, list[Road]] = defaultdict(list)\n layered_connectors: dict[float, list[Connector]] = defaultdict(list)\n\n for road in self.roads:\n if not road.is_transition:\n layered_roads[road.layer].append(road)\n else:\n connections = []\n for end in 0, -1:\n connections.append(\n [\n connection\n for connection in self.nodes[road.nodes[end].id_]\n if not connection[0].is_transition\n ]\n )\n if len(connections[0]) == 1 and len(connections[1]) == 1:\n connector: Connector = ComplexConnector(\n [connections[0][0], connections[1][0]], flinger\n )\n layered_connectors[road.layer].append(connector)\n\n for connected in self.nodes.values():\n connector: Connector\n\n if len(connected) <= 1:\n continue\n\n if len(connected) == 2:\n road_1, index_1 = connected[0]\n road_2, index_2 = connected[1]\n if (\n road_1.width == road_2.width\n or index_1 not in [0, len(road_1.nodes) - 1]\n or index_2 not in [0, len(road_2.nodes) - 1]\n ):\n connector = SimpleConnector(connected, flinger)\n elif not road_1.is_transition and not road_2.is_transition:\n connector = ComplexConnector(connected, flinger)\n else:\n continue\n else:\n # We can also use SimpleIntersection(connected, flinger, scale)\n # here.\n continue\n\n layered_connectors[connector.min_layer].append(connector)\n layered_connectors[connector.max_layer].append(connector)\n\n for layer in sorted(layered_roads.keys()):\n roads: list[Road] = sorted(\n layered_roads[layer], key=lambda x: x.matcher.priority\n )\n connectors: list[Connector] = layered_connectors.get(layer)\n\n # Draw borders.\n\n for road in roads:\n road.draw(svg, True)\n if connectors:\n for connector in connectors:\n if connector.min_layer == layer:\n connector.draw_border(svg)\n\n # Draw inner parts.\n\n for road in roads:\n road.draw(svg, False)\n if connectors:\n for connector in connectors:\n if connector.max_layer == layer:\n connector.draw(svg)\n\n # Draw lane separators.\n\n for road in roads:\n road.draw_lanes(svg, road.matcher.border_color)\n\n if draw_captions:\n for road in self.roads:\n road.draw_caption(svg)\n" ]
[ [ "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
coder-yuzhiwei/iechub
[ "d13ba79bef46acb1fbabd206a33cad9fa6e760c1" ]
[ "NLP Learning Schedule/Knowledge Graph/demo/DuIe_baseline/ernie/reader/task_reader.py" ]
[ "# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nimport sys\nimport os\nimport json\nimport random\nimport logging\nimport numpy as np\nimport six\nfrom io import open\nfrom collections import namedtuple\nimport vthread\nimport pandas as pd\nimport codecs\nimport time\nimport re\n\nimport tokenization\nfrom batching import pad_batch_data\n\nimport extract_chinese_and_punct\n\nlog = logging.getLogger(__name__)\n\nif six.PY3:\n import io\n sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')\n\n\nclass BaseReader(object):\n def __init__(self,\n vocab_path,\n label_map_config=None,\n max_seq_len=512,\n do_lower_case=True,\n in_tokens=False,\n is_inference=False,\n random_seed=None,\n tokenizer=\"FullTokenizer\",\n is_classify=True,\n is_regression=False,\n for_cn=True,\n task_id=0):\n self.max_seq_len = max_seq_len\n self.tokenizer = tokenization.FullTokenizer(\n vocab_file=vocab_path, do_lower_case=do_lower_case)\n self.vocab = self.tokenizer.vocab\n self.pad_id = self.vocab[\"[PAD]\"]\n self.cls_id = self.vocab[\"[CLS]\"]\n self.sep_id = self.vocab[\"[SEP]\"]\n self.in_tokens = in_tokens\n self.is_inference = is_inference\n self.for_cn = for_cn\n self.task_id = task_id\n\n np.random.seed(random_seed)\n\n self.is_classify = is_classify\n self.is_regression = is_regression\n self.current_example = 0\n self.current_epoch = 0\n self.num_examples = 0\n\n if label_map_config:\n with open(label_map_config, encoding='utf8') as f:\n self.label_map = json.load(f)\n else:\n self.label_map = None\n\n def get_train_progress(self):\n \"\"\"Gets progress for training phase.\"\"\"\n return self.current_example, self.current_epoch\n\n def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\nclass RelationExtractionMultiCLSReader(BaseReader):\n def __init__(self,\n vocab_path,\n label_map_config=None,\n spo_label_map_config=None,\n max_seq_len=512,\n do_lower_case=True,\n in_tokens=False,\n is_inference=False,\n random_seed=None,\n tokenizer=\"FullTokenizer\",\n is_classify=True,\n is_regression=False,\n for_cn=True,\n task_id=0,\n num_labels=0):\n self.max_seq_len = max_seq_len\n self.tokenizer = tokenization.FullTokenizer(\n vocab_file=vocab_path, do_lower_case=do_lower_case)\n self.chineseandpunctuationextractor = extract_chinese_and_punct.ChineseAndPunctuationExtractor(\n )\n self.vocab = self.tokenizer.vocab\n self.pad_id = self.vocab[\"[PAD]\"]\n self.cls_id = self.vocab[\"[CLS]\"]\n self.sep_id = self.vocab[\"[SEP]\"]\n self.in_tokens = in_tokens\n self.is_inference = is_inference\n self.for_cn = for_cn\n self.task_id = task_id\n self.num_labels = num_labels\n\n np.random.seed(random_seed)\n\n self.is_classify = is_classify\n self.is_regression = is_regression\n self.current_example = 0\n self.current_epoch = 0\n self.num_examples = 0\n # map string to relation id\n if label_map_config:\n with open(label_map_config, encoding='utf8') as f:\n self.label_map = json.load(f)\n else:\n self.label_map = None\n # map relation id to string(including subject name, predicate name, object name)\n if spo_label_map_config:\n with open(label_map_config, encoding='utf8') as f:\n self.label_map = json.load(f)\n else:\n self.spo_label_map = None\n\n def _read_json(self, input_file):\n f = open(input_file, 'r', encoding=\"utf8\")\n examples = []\n for line in f.readlines():\n examples.append(json.loads(line))\n f.close()\n return examples\n\n def get_num_examples(self, input_file):\n examples = self._read_json(input_file)\n return len(examples)\n\n def _prepare_batch_data(self, examples, batch_size, phase=None):\n \"\"\"generate batch records\"\"\"\n batch_records, max_len = [], 0\n for index, example in enumerate(examples):\n if phase == \"train\":\n self.current_example = index\n example_index = 100000 + index\n record = self._convert_example_to_record(\n example_index, example, self.max_seq_len, self.tokenizer)\n max_len = max(max_len, len(record.token_ids))\n if self.in_tokens:\n to_append = (len(batch_records) + 1) * max_len <= batch_size\n else:\n to_append = len(batch_records) < batch_size\n if to_append:\n batch_records.append(record)\n else:\n yield self._pad_batch_records(batch_records)\n batch_records, max_len = [record], len(record.token_ids)\n\n if batch_records:\n yield self._pad_batch_records(batch_records)\n\n\n def data_generator(self,\n input_file,\n batch_size,\n epoch,\n dev_count=1,\n shuffle=True,\n phase=None):\n\n examples = self._read_json(input_file)\n\n def wrapper():\n all_dev_batches = []\n for epoch_index in range(epoch):\n if phase == \"train\":\n self.current_example = 0\n self.current_epoch = epoch_index\n if shuffle:\n np.random.shuffle(examples)\n\n for batch_data in self._prepare_batch_data(\n examples, batch_size, phase=phase):\n if len(all_dev_batches) < dev_count:\n all_dev_batches.append(batch_data)\n if len(all_dev_batches) == dev_count:\n for batch in all_dev_batches:\n yield batch\n all_dev_batches = []\n\n def f():\n try:\n for i in wrapper():\n yield i\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n return f\n\n def test_data_generator(self,\n input_file,\n batch_size,\n epoch,\n dev_count=1,\n shuffle=True,\n phase=None):\n\n # examples = self._read_json(input_file)\n examples, data_len, cost_time = self.get_resourse_data(input_file)\n\n def wrapper():\n all_dev_batches = []\n for epoch_index in range(epoch):\n if phase == \"train\":\n self.current_example = 0\n self.current_epoch = epoch_index\n if shuffle:\n np.random.shuffle(examples)\n\n for batch_data in self._prepare_batch_data(\n examples, batch_size, phase=phase):\n if len(all_dev_batches) < dev_count:\n all_dev_batches.append(batch_data)\n if len(all_dev_batches) == dev_count:\n for batch in all_dev_batches:\n yield batch\n all_dev_batches = []\n\n def f():\n try:\n for i in wrapper():\n yield i\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n return f\n\n def data_post_proccess(self,\n input_file,\n batch_size,\n epoch,\n dev_count=1,\n shuffle=True,\n phase=None):\n examples = self._read_json(input_file)\n\n all_dev_batches = []\n for epoch_index in range(epoch):\n if phase == \"train\":\n self.current_example = 0\n self.current_epoch = epoch_index\n if shuffle:\n np.random.shuffle(examples)\n\n for batch_data in self._prepare_batch_data(\n examples, batch_size, phase=phase):\n if len(all_dev_batches) < dev_count:\n all_dev_batches.append(batch_data)\n if len(all_dev_batches) == dev_count:\n for batch in all_dev_batches:\n input_batch = []\n for i in range(7):\n input_batch.append(batch[i])\n input_batch.append(np.array([[x] for x in batch[7]]))\n input_batch.append(np.array([[[x] for x in i] for i in batch[8]]))\n input_batch.append(np.array([[[x] for x in i] for i in batch[9]]))\n yield input_batch\n all_dev_batches = []\n\n\n def _pad_batch_records(self, batch_records):\n batch_token_ids = [record.token_ids for record in batch_records]\n batch_text_type_ids = [record.text_type_ids for record in batch_records]\n batch_position_ids = [record.position_ids for record in batch_records]\n batch_label_ids = [record.label_ids for record in batch_records]\n batch_example_index = [record.example_index for record in batch_records]\n batch_tok_to_orig_start_index = [\n record.tok_to_orig_start_index for record in batch_records\n ]\n batch_tok_to_orig_end_index = [\n record.tok_to_orig_end_index for record in batch_records\n ]\n # padding\n padded_token_ids, input_mask, batch_seq_lens = pad_batch_data(\n batch_token_ids,\n pad_idx=self.pad_id,\n return_input_mask=True,\n return_seq_lens=True)\n padded_text_type_ids = pad_batch_data(\n batch_text_type_ids, pad_idx=self.pad_id)\n padded_position_ids = pad_batch_data(\n batch_position_ids, pad_idx=self.pad_id)\n\n # label padding for expended dimension\n outside_label = np.array([1] + [0] * (self.num_labels - 1))\n max_len = max(len(inst) for inst in batch_label_ids)\n padded_label_ids = []\n for i, inst in enumerate(batch_label_ids):\n inst = np.concatenate(\n (np.array(inst), np.tile(outside_label, ((max_len - len(inst)),\n 1))),\n axis=0)\n padded_label_ids.append(inst)\n padded_label_ids = np.stack(padded_label_ids).astype(\"float32\")\n\n padded_tok_to_orig_start_index = np.array([\n inst + [0] * (max_len - len(inst))\n for inst in batch_tok_to_orig_start_index\n ])\n padded_tok_to_orig_end_index = np.array([\n inst + [0] * (max_len - len(inst))\n for inst in batch_tok_to_orig_end_index\n ])\n\n padded_task_ids = np.ones_like(\n padded_token_ids, dtype=\"int64\") * self.task_id\n\n return_list = [\n padded_token_ids, padded_text_type_ids, padded_position_ids,\n padded_task_ids, input_mask, padded_label_ids, batch_seq_lens,\n batch_example_index, padded_tok_to_orig_start_index,\n padded_tok_to_orig_end_index\n ]\n return return_list\n\n def _convert_example_to_record(self, example_index, example, max_seq_length,\n tokenizer):\n if example.__contains__('spo_list'):\n spo_list = example['spo_list']\n else:\n spo_list = []\n text_raw = example['text']\n\n sub_text = []\n buff = \"\"\n for char in text_raw:\n if self.chineseandpunctuationextractor.is_chinese_or_punct(char):\n if buff != \"\":\n sub_text.append(buff)\n buff = \"\"\n sub_text.append(char)\n else:\n buff += char\n if buff != \"\":\n sub_text.append(buff)\n\n tok_to_orig_start_index = []\n tok_to_orig_end_index = []\n orig_to_tok_index = []\n tokens = []\n text_tmp = ''\n for (i, token) in enumerate(sub_text):\n orig_to_tok_index.append(len(tokens))\n sub_tokens = tokenizer.tokenize(token)\n text_tmp += token\n for sub_token in sub_tokens:\n tok_to_orig_start_index.append(len(text_tmp) - len(token))\n tok_to_orig_end_index.append(len(text_tmp) - 1)\n tokens.append(sub_token)\n if len(tokens) >= max_seq_length - 2:\n break\n else:\n continue\n break\n\n labels = [[0] * self.num_labels\n for i in range(len(tokens))] # initialize tag\n # find all entities and tag them with corresponding \"B\"/\"I\" labels\n for spo in spo_list:\n for spo_object in spo['object'].keys():\n # assign relation label\n if spo['predicate'] in self.label_map.keys():\n # simple relation\n label_subject = self.label_map[spo['predicate']]\n label_object = label_subject + 58\n subject_sub_tokens = tokenizer.tokenize(spo['subject'])\n object_sub_tokens = tokenizer.tokenize(spo['object'][\n '@value'])\n else:\n # complex relation\n label_subject = self.label_map[spo['predicate'] + '_' +\n spo_object]\n label_object = label_subject + 58\n subject_sub_tokens = tokenizer.tokenize(spo['subject'])\n object_sub_tokens = tokenizer.tokenize(spo['object'][\n spo_object])\n\n # assign token label\n # there are situations where s entity and o entity might overlap, e.g. xyz established xyz corporation\n # to prevent single token from being labeled into two different entity\n # we tag the longer entity first, then match the shorter entity within the rest text\n forbidden_index = None\n if len(subject_sub_tokens) > len(object_sub_tokens):\n for index in range(\n len(tokens) - len(subject_sub_tokens) + 1):\n if tokens[index:index + len(\n subject_sub_tokens)] == subject_sub_tokens:\n labels[index][label_subject] = 1\n for i in range(len(subject_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n forbidden_index = index\n break\n\n for index in range(\n len(tokens) - len(object_sub_tokens) + 1):\n if tokens[index:index + len(\n object_sub_tokens)] == object_sub_tokens:\n if forbidden_index is None:\n labels[index][label_object] = 1\n for i in range(len(object_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n break\n # check if labeled already\n elif index < forbidden_index or index >= forbidden_index + len(\n subject_sub_tokens):\n labels[index][label_object] = 1\n for i in range(len(object_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n break\n\n else:\n for index in range(\n len(tokens) - len(object_sub_tokens) + 1):\n if tokens[index:index + len(\n object_sub_tokens)] == object_sub_tokens:\n labels[index][label_object] = 1\n for i in range(len(object_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n forbidden_index = index\n break\n\n for index in range(\n len(tokens) - len(subject_sub_tokens) + 1):\n if tokens[index:index + len(\n subject_sub_tokens)] == subject_sub_tokens:\n if forbidden_index is None:\n labels[index][label_subject] = 1\n for i in range(len(subject_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n break\n elif index < forbidden_index or index >= forbidden_index + len(\n object_sub_tokens):\n labels[index][label_subject] = 1\n for i in range(len(subject_sub_tokens) - 1):\n labels[index + i + 1][1] = 1\n break\n\n # if token wasn't assigned as any \"B\"/\"I\" tag, give it an \"O\" tag for outside\n for i in range(len(labels)):\n if labels[i] == [0] * self.num_labels:\n labels[i][0] = 1\n\n # add [CLS] and [SEP] token, they are tagged into \"O\" for outside\n if len(tokens) > max_seq_length - 2:\n tokens = tokens[0:(max_seq_length - 2)]\n labels = labels[0:(max_seq_length - 2)]\n tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"]\n outside_label = [[1] + [0] * (self.num_labels - 1)]\n labels = outside_label + labels + outside_label\n\n token_ids = tokenizer.convert_tokens_to_ids(tokens)\n position_ids = list(range(len(token_ids)))\n text_type_ids = [0] * len(token_ids)\n\n Record = namedtuple('Record', [\n 'token_ids', 'text_type_ids', 'position_ids', 'label_ids',\n 'example_index', 'tok_to_orig_start_index', 'tok_to_orig_end_index'\n ])\n record = Record(\n token_ids=token_ids,\n text_type_ids=text_type_ids,\n position_ids=position_ids,\n label_ids=labels,\n example_index=example_index,\n tok_to_orig_start_index=tok_to_orig_start_index,\n tok_to_orig_end_index=tok_to_orig_end_index)\n return record\n\n def get_resourse_data(self, input_file):\n start_time = time.time()\n corpus = []\n sentences_count = 0\n\n @vthread.pool(16)\n def getKeywords(data, stopkey, positivekey, topK):\n idList, titleList, abstractList = data['id'], data['title'], data[\n 'abstract']\n # 将所有文档输出到一个list中,一行就是一个文档\n for index in range(len(idList)):\n text = '%s。%s' % (titleList[index], abstractList[index]) # 拼接标题和摘要\n l = []\n m = 0\n for i in positivekey:\n if i in text: # 去停用词 + 词性筛选\n m = m + 1\n # text = \" \".join(text) # 连接成字符串,空格分隔\n if m >= 6:\n corpus.append(index)\n\n examples = []\n # 读取数据集\n dataFile = input_file\n data = pd.read_csv(dataFile, sep='\\t', error_bad_lines=False, warn_bad_lines=False)\n # 停用词表\n stopkey = [\n w.strip() for w in codecs.open(\n 'stopWord.txt',\n 'r', encoding='utf-8').readlines()\n ]\n positivekey = [\n w.strip() for w in codecs.open(\n 'positiveword11.txt',\n 'r', encoding='utf-8').readlines()\n ]\n t = int(len(data) / 600)\n for i in range(0, t):\n data1 = data.iloc[600 * i:600 * (i + 1), :]\n data1 = data1.reset_index(drop=True)\n tt = []\n for index1, row in data1.iterrows():\n text = str(row['abstract'])\n sentences_count += text.count('。')\n sentences_count += text.count('!')\n tt.append(text[0:30])\n\n data2 = pd.DataFrame()\n data2['id'] = data1['id']\n data2['title'] = data1['title']\n data2['abstract'] = tt\n\n getKeywords(data2, stopkey, positivekey, 5)\n # result.to_csv(\"keys_TFIDF111.csv\", index=False,sep=',')\n # print(key_word)\n if (600 * t < len(data)):\n data1 = data.iloc[600 * t:len(data), :]\n data1 = data1.reset_index(drop=True)\n tt = []\n for index1, row in data1.iterrows():\n text = str(row['abstract'])\n sentences_count += text.count('。')\n sentences_count += text.count('!')\n tt.append(text[0:30])\n data2 = pd.DataFrame()\n data2['id'] = data1['id']\n data2['title'] = data1['title']\n data2['abstract'] = tt\n getKeywords(data2, stopkey, positivekey, 5)\n vthread.pool.waitall()\n for i in corpus:\n # txt = {}\n # txt['spo_list'] = \"\"\n passage = str(data['abstract'][i])\n r = re.compile(\"[。!?!?']\")\n for sentence in r.split(passage):\n txt = {}\n sent = sentence.strip().replace(' ', '').replace('\\t', '').replace('\\u3000', '').replace(\n '\\u00A0', '').replace('\\u2002', '')\n if sent == '':\n continue\n elif len(sent) < 10:\n continue\n else:\n txt['text'] = sent\n examples.append((txt))\n\n # txt['text'] = str(data['abstract'][i])\n # examples.append((txt))\n end_time = time.time()\n log.info(\"前处理耗时:\\t{}秒\".format(end_time-start_time))\n return examples, sentences_count, end_time-start_time\n\n\nif __name__ == '__main__':\n pass\n" ]
[ [ "pandas.read_csv", "numpy.ones_like", "numpy.random.seed", "pandas.DataFrame", "numpy.random.shuffle", "numpy.stack", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
djconly85/CodeSnippets
[ "3c96617f6330448e3ce9c7d01f282e2a6ffe9a79" ]
[ "Conversions/sqlqry_2_pandasdf.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nName:sqlqry_2_pandasdf.py\nPurpose: Run an SQL query file on a SQL Server database and load results into Pandas dataframe\n\nAlternative methods:\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html\n \nAuthor: Darren Conly\nLast Updated: <date>\nUpdated by: <name>\nCopyright: (c) SACOG\nPython Version: 3.x\n\"\"\"\n\nimport os, time\n\nimport pyodbc\nimport pandas as pd\n\n#sql process creates input table that's read into pandas dataframe--for testing this may be CSV\ndef df_from_csv(in_csv):\n df = pd.read_csv(in_csv)\n return df\n\nclass Query(object):\n def __init__(self):\n self.driver = '{SQL Server}'\n self.server = 'SQL-SVR'\n self.database = 'NPMRDS'\n self.trusted_connection = 'yes'\n self.conxn_info = \"DRIVER={0}; SERVER={1}; DATABASE={2}; Trusted_Connection={3}\" \\\n .format(self.driver, self.server, self.database, self.trusted_connection)\n self.tbl_tmcs = 'npmrds_2018_all_tmcs_txt' #logs each run made and asks user for scenario description\n self.tbl_traveltime = 'npmrds_2018_alltmc_paxveh'\n \n \n self.sqldir = r\"P:\\NPMRDS data\\Projects\\Regional Progress Report\\RPR_2020\\SQL\\ForPython\"\n \n self.sql_avspd_x_hr_of_day = os.path.join(self.sqldir, 'HarmAvgSpd_x_HOD.sql')\n \n\n \n def sqlqry_to_df(self, sql_file, params_list):\n print(\"Running {}...\".format(sql_file))\n \n with open(sql_file,'r') as in_sql:\n raw_sql = in_sql.read()\n formatted_sql = raw_sql.format(*params_list)\n formatted_sql = formatted_sql.replace(\",)\", \")\") # to make sure tuples don't make clause like \"IN (XXX,)\" with bad comma\n print(formatted_sql)\n\n conn = pyodbc.connect(self.conxn_info)\n conn.autocommit = True\n cursor = conn.cursor()\n cursor.execute(formatted_sql)\n \n colnames = [column[0] for column in cursor.description]\n output = [colnames]\n for row in cursor:\n # arcpy.AddMessage(row)\n output.append(row)\n\n cursor.commit()\n cursor.close()\n conn.close()\n \n df = pd.DataFrame(output, columns=colnames)\n \n return df\n\n\nif __name__ == '__main__':\n \n test_csv_in = r\"P:\\NPMRDS data\\Projects\\Regional Progress Report\\CSV\\test_corridor_avspd_x_hod.csv\"\n html_folder = r\"P:\\NPMRDS data\\Projects\\Regional Progress Report\\HTML\"\n \n tmcs_fc = 'TMCs_AllRegionNHS_2018'\n \n\n \n\n\n \n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
cnut1648/Multimodal-Transformer
[ "8b86590b4d14dcd9e72ee2c9da9668a458780a16" ]
[ "src/datamodules/msp_improv_datamodule.py" ]
[ "import random\nfrom typing import Optional, Tuple\nimport os\nimport numpy as np\n\nimport torch, librosa\nimport pandas as pd\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split\nfrom torchvision.datasets import MNIST\nfrom torch.utils.data.sampler import RandomSampler, SequentialSampler, BatchSampler, Sampler\nfrom torchvision.transforms import transforms\nfrom ..utils.io import sample_frames, load_img\nfrom torch.utils.data.dataloader import default_collate\n\ndef get_meta(utterance):\n # eg MSP-IMPROV-S03H-M01-S-FM03\n _, _, session, gender_session, dialog, _ = utterance.split('-')\n # M01 -> M, 1\n gender, sessionnum = gender_session[0], gender_session[-1]\n # eg S03H, S, M, 1\n return session, dialog, gender, sessionnum\n\n# kfold: [train, val]\nFOLD_META = {\n 1: [['1F', '1M', '2F', '2M', '3F', '3M', '4F', '4M', '5F', '5M', '6F'], ['6M']],\n 2: [['1M', '2F', '2M', '3F', '3M', '4F', '4M', '5F', '5M', '6F', '6M'], ['1F']],\n 3: [['2F', '2M', '3F', '3M', '4F', '4M', '5F', '5M', '6F', '6M', '1F'], ['1M']],\n 4: [['2M', '3F', '3M', '4F', '4M', '5F', '5M', '6F', '6M', '1F', '1M'], ['2F']],\n 5: [['3F', '3M', '4F', '4M', '5F', '5M', '6F', '6M', '1F', '1M', '2F'], ['2M']],\n 6: [['3M', '4F', '4M', '5F', '5M', '6F', '6M', '1F', '1M', '2F', '2M'], ['3F']],\n 7: [['4F', '4M', '5F', '5M', '6F', '6M', '1F', '1M', '2F', '2M', '3F'], ['3M']],\n 8: [['4M', '5F', '5M', '6F', '6M', '1F', '1M', '2F', '2M', '3F', '3M'], ['4F']],\n 9: [['5F', '5M', '6F', '6M', '1F', '1M', '2F', '2M', '3F', '3M', '4F'], ['4M']],\n 10: [['5M', '6F', '6M', '1F', '1M', '2F', '2M', '3F', '3M', '4F', '4M'], ['5F']],\n 11: [['6F', '6M', '1F', '1M', '2F', '2M', '3F', '3M', '4F', '4M', '5F'], ['5M']],\n 12: [['6M', '1F', '1M', '2F', '2M', '3F', '3M', '4F', '4M', '5F', '5M'], ['6F']],\n}\n\nclass MultiDataset(Dataset):\n def __init__(self, task: str, csv_path, data_root, folds, **kwargs):\n self.task = task\n if type(folds) is not list:\n folds = [folds]\n self.dataset = pd.read_csv(os.path.join(csv_path, f\"post_session{folds[0]}.csv\"))\n for fold in folds[1:]:\n self.dataset = self.dataset.append(\n pd.read_csv(os.path.join(csv_path, f\"post_session{fold}.csv\"))\n )\n self.dataset.reset_index(inplace=True)\n self.data_root = data_root\n\n def __getitem__(self, index):\n utterance = self.dataset['utterance_id'][index]\n session, dialog, gender, sessionnum = get_meta(utterance)\n ret = {\n # e.g. 2F\n \"speaker\": f\"{sessionnum}{gender}\",\n }\n label = int(self.dataset['label'][index])\n return {**ret, \"labels\": label}\n\n def __len__(self):\n return len(self.dataset)\n\n @staticmethod\n def collate_fn(batch):\n return default_collate(list(\n filter(lambda x: x is not None, batch)\n ))\n\n def get_video(self, utterance, num_frames, transform, is_train):\n session, dialog, _, sessionid = get_meta(utterance)\n frame_dir = os.path.join(\n self.data_root, \"video\", f'session{sessionid}', session, utterance) \n frame_list = sample_frames(frame_dir, num_frames)\n\n frames = []\n for frame_path in frame_list:\n frame = load_img(os.path.join(frame_dir, frame_path))\n frame = transform(frame)\n frames.append(frame)\n frames = torch.stack(frames)\n\n if is_train:\n vflip = random.random() < 0.5\n if vflip:\n torch.flip(frames, [2])\n return frames\n\n def get_text(self, utterance):\n session, dialog, _, sessionid = get_meta(utterance)\n text_dir = os.path.join(\n self.data_root, \"text\", f'session{sessionid}', session, f\"{utterance}.txt\"\n )\n with open(text_dir) as f:\n lines = f.readlines()\n return lines[0]\n \n def get_raw_audio(self, utterance, max_audio_len):\n session, dialog, _, sessionid = get_meta(utterance)\n audio_path = os.path.join(\n self.data_root, \"resampled_audio\", f'session{sessionid}', session,\n dialog, f\"{utterance}.wav\")\n signal, sample_rate = librosa.load(audio_path, sr=None, mono=True)\n assert sample_rate == 16000\n if len(signal) > max_audio_len:\n signal = signal[-max_audio_len:]\n return signal\n\n @staticmethod\n def get_batch_sampler(dataset, batch_size: int, shuffle: bool, **kwargs):\n if shuffle == True:\n sampler = RandomSampler(dataset)\n else:\n sampler = SequentialSampler(dataset)\n return BatchSampler(sampler, batch_size, drop_last=False)\n\nclass VideoDataset(MultiDataset):\n def __init__(self, task: str, csv_path, data_root, folds,\n split, num_frames, transform=None, **kwargs):\n super().__init__(task, csv_path, data_root, folds)\n self.is_train = (split == \"train\")\n self.num_frames = num_frames\n self.transform = transform\n \n def __getitem__(self, index):\n utterance = self.dataset['utterance_id'][index]\n ret = super().__getitem__(index)\n return {\n **ret, \"videos\": self.get_video(utterance, self.num_frames, self.transform, self.is_train)\n }\n\nclass TextDataset(MultiDataset):\n def __getitem__(self, index):\n utterance = self.dataset['utterance_id'][index]\n ret = super().__getitem__(index)\n return {\n **ret, \"text\": self.get_text(utterance)\n }\n\nclass AudioDataset(MultiDataset):\n def __init__(self, task: str, csv_path, data_root, folds,\n split, spec_aug=False, max_audio_len=8000, audio_format=\"raw\", **kwargs):\n super().__init__(task, csv_path, data_root, folds)\n self.spec_aug = spec_aug\n self.max_audio_len = max_audio_len\n self.is_train = (split == \"train\")\n self.audio_format = audio_format\n def __getitem__(self, index):\n utterance = self.dataset['utterance_id'][index]\n ret = super().__getitem__(index)\n return {\n **ret, \"audios\": self.get_raw_audio(utterance, self.max_audio_len)\n }\n \n @staticmethod\n def collate_fn(batch, pad_idx=0):\n # for DDP: somehow make batch a dict not list of dict\n if type(batch) is dict:\n batch = [batch]\n batch = list(\n filter(lambda x: x is not None, batch)\n )\n if batch[0][\"audios\"].ndim == 1:\n # raw\n ret = {\n k: [b[k] for b in batch]\n for k in batch[0]\n }\n ret[\"labels\"] = torch.tensor(ret[\"labels\"])\n return ret\n batch = sorted(batch, key=lambda x: x[\"audios\"].size(0), reverse=True)\n max_seq_sample = max(batch, key=lambda x: x[\"audios\"].size(0))['audios']\n max_seq_size, feat_size = max_seq_sample.shape\n batch_size = len(batch)\n audios = torch.zeros(batch_size, max_seq_size, feat_size)\n for i in range(batch_size):\n audio = batch[i][\"audios\"]\n seq_length = audio.size(0)\n audios[i].narrow(0, 0, seq_length).copy_(audio)\n return {\n \"labels\": torch.tensor([x[\"labels\"] for x in batch]).long(),\n \"audios\": audios,\n \"audio_lengths\": torch.tensor([len(x[\"audios\"]) for x in batch]).long()\n }\n\nclass ATDataset(AudioDataset):\n def __getitem__(self, index):\n utterance = self.dataset['utterance_id'][index]\n ret = super().__getitem__(index)\n return {\n **ret,\n \"text\": self.get_text(utterance),\n }\n\nclass DataModule(LightningDataModule):\n def __init__(\n self, task: str, modality: str, fold: int,\n # dataset\n # where the csvs are and where the raw data are\n csv_dir: str = \"dataset/\", data_dir: str = \"data/\", \n # for video only\n num_frames: int = 16, image_size: int = 112,\n # dataloader\n batch_size: int = 64, num_workers: int = 0, pin_memory: bool = False,\n # for audio only\n spec_aug: bool = False, max_audio_len: int = 8000, audio_format: str = \"raw\", use_smart_sampler: bool = False, cache_dir: str = \".\",\n **kwargs\n ):\n assert os.path.exists(data_dir)\n assert os.path.exists(csv_dir)\n assert task in [\"clf\"]\n assert fold in range(1, 13)\n super().__init__()\n\n # this line allows to access init params with 'self.hparams' attribute\n self.save_hyperparameters(logger=False)\n\n # data transformations\n self.transforms = transforms.Compose([\n transforms.Resize((self.hparams.image_size, self.hparams.image_size)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n ])\n\n self.datasets: dict = {}\n self.modality2ds = {\n \"video\": VideoDataset,\n \"text\": TextDataset,\n \"audio\": AudioDataset,\n \"at\": ATDataset\n }\n\n def setup(self, stage: Optional[str] = None):\n ds_cls = self.modality2ds[self.hparams.modality]\n train, val = FOLD_META[self.hparams.fold]\n for folds, split in zip([train, val], [\"train\", \"val\"]):\n self.datasets[split] = ds_cls(\n self.hparams.task,\n self.hparams.csv_dir, self.hparams.data_dir, folds,\n split=split, num_frames=self.hparams.num_frames, transform=self.transforms,\n spec_aug=self.hparams.spec_aug, max_audio_len=self.hparams.max_audio_len, audio_format=self.hparams.audio_format\n )\n \n def load_dataloader(self, split: str):\n ds_cls = self.modality2ds[self.hparams.modality]\n batch_sampler = ds_cls.get_batch_sampler(\n self.datasets[split],\n batch_size=self.hparams.batch_size,\n shuffle=(split == \"train\"),\n split=split,\n cache_dir=self.hparams.cache_dir,\n use_smart_sampler=self.hparams.use_smart_sampler\n )\n return DataLoader(\n self.datasets[split],\n num_workers=self.hparams.num_workers,\n pin_memory=self.hparams.pin_memory,\n collate_fn=ds_cls.collate_fn,\n batch_sampler=batch_sampler\n )\n\n def train_dataloader(self):\n return self.load_dataloader(\"train\")\n\n def val_dataloader(self):\n return self.load_dataloader(\"val\")\n\n def test_dataloader(self):\n return self.load_dataloader(\"val\")" ]
[ [ "torch.flip", "torch.zeros", "torch.utils.data.DataLoader", "torch.tensor", "torch.stack", "torch.utils.data.sampler.SequentialSampler", "torch.utils.data.sampler.RandomSampler", "torch.utils.data.sampler.BatchSampler" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
oort77/COT
[ "b84bc519163f103d485527f325d820b4132dd087" ]
[ "cot2a.py" ]
[ "# COT analysis -- streamlit v2a\n\n### NEEDS REWRITE: put DDATE to h5 file refs instead of to environment variable\n\n# Import libraries\nfrom datetime import datetime\n# import pytz\nimport pandas as pd\nimport numpy as np\nimport h5py\nimport zipfile, urllib.request, shutil, requests\nimport os\nimport altair\nimport streamlit as st\n\n# Streamlit page configuration\nst.set_page_config(page_title='COT', page_icon='./icon.ico',\n layout='centered', initial_sidebar_state='auto')\n\npd.set_option('mode.chained_assignment', None)\n\n# Init\npath = \"/home/gm/notebooks/COT/\"\ncurr_year = datetime.today().year\nstart_year = 2010\npos_format = 'size' # vs. '%'\npos_show = 'net' # vs. 'long/short'\nflag_download_all = False # Set to True to download all data again\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'\n}\n\n# H5 init\ndata_store = pd.HDFStore('data.h5') # <-- 1\nddate = data_store.get_storer('curr_data').attrs['ddate'] # <-- 1\n# Init data\n#data = pd.DataFrame() # NEED FOR THE FIRST DOWNLOAD BEFORE data.h5 exists <-- 0\ndata = data_store['curr_data'] # <-- 1\n####### data_store.close()\n\n# Zipped COT report import function\ndef get_COT(url, file_name):\n# with urllib.request.urlopen(url) as response, open(file_name,\n# 'wb') as out_file:\n with requests.get(url, stream=True, headers=headers) as response, open(file_name,\n 'wb') as out_file:\n# st.write(response)\n shutil.copyfileobj(response.raw, out_file)\n with zipfile.ZipFile(file_name) as zf:\n zf.extractall()\n\n# Import COT reports by year and convert to xls\ndef COT_handling(year):\n year = str(year)\n filename = year + '.zip'\n# get_COT('https://www.cftc.gov/files/dea/history/fut_fin_xls_' + filename,\n# year + '.zip')\n url = 'https://www.cftc.gov/files/dea/history/fut_fin_xls_' + year +'.zip'\n# st.write(url)\n get_COT(url, filename)\n# year + '.zip')\n # Rename\n new_filename = year + '.xls'\n os.rename(path + 'FinFutYY.xls', path + new_filename)\n\n\ndef append_xls_to_dataframe(df, xls_filename):\n if df.empty:\n df = pd.read_excel(xls_filename)\n else:\n df = df.append(pd.read_excel(xls_filename))\n return (df)\n\n#====================REWRITE==========================================\ndef write_h5(df, is_current=True):\n \n for i in range(start_year, curr_year):\n df = append_xls_to_dataframe(df, str(i) + \".xls\")\n\n if is_current == False: # Writing previous years data only\n data_store['prev_years_data'] = df\n data_store.get_storer(\n 'prev_years_data').attrs[\"ddate\"] = datetime.today().date()\n st.error(\"Wrote 'prev_years_data' dataframe to h5 data store\")\n else:\n # data contains all info from all years\n df = append_xls_to_dataframe(df, str(curr_year) + \".xls\")\n data_store['curr_data'] = df\n # ********** hdf5\n data_store.get_storer(\n 'curr_data').attrs['ddate'] = datetime.today().date()\n st.error(\"Wrote 'curr_data' dataframe to h5 data store\")\n\n\n# Download ALL COT files -- if needed\n\n# Set flag_download_all to True above) and change init to:\n# data = pd.DataFrame()\nif flag_download_all == True:\n for i in range(start_year, curr_year):\n COT_handling(i)\n\n write_h5(data, is_current=False)\n\n COT_handling(curr_year)\n write_h5(data, is_current=True)\n\n# Year change\n\nif curr_year > ddate.year:\n # Download prev year report and put to data_store['prev_years_data']\n COT_handling(curr_year - 1)\n append_xls_to_dataframe(data, str(curr_year - 1) + \".xls\")\n write_h5(data, is_current=False)\n\n# Check if there is a new COT report (sure by Saturday) and download the latest\n\nif ddate != str(datetime.today().date()):\n if datetime.today().weekday() == 3 or (\n datetime.today().date() - ddate).days >= 7:\n # Updata with new COT report\n COT_handling(curr_year)\n data = append_xls_to_dataframe(data_store['prev_years_data'],\n str(curr_year) + \".xls\")\n write_h5(data, is_current=True)\n\nstart_year = int(st.sidebar.text_input('Show data from year:',\n value='2010')) #, max_chars=4))\nif start_year < 2010:\n st.error(\"Data is available starting from year 2010\")\n\ndata.set_index('Report_Date_as_MM_DD_YYYY', inplace=True)\ndata.index = pd.to_datetime(data.index)\ndata.index.rename('Date', inplace=True)\ndata['Year'] = data.index.year\n\n# Get last report date\nlast_report_date = data[data['Year'] == curr_year].index.max().strftime(\n \"%Y-%m-%d\")\n\n# Select data to show by start_year\ndata_y = data[data['Year'] >= start_year]\n\n# Choose instrument\ninstruments = list(pd.unique(data_y['Market_and_Exchange_Names']))\ninstruments.sort()\n# Set default instrument ro E-mini S&P500\nES_index = instruments.index(\n 'E-MINI S&P 500 STOCK INDEX - CHICAGO MERCANTILE EXCHANGE')\ninstr = st.sidebar.selectbox('Choose an instrument:',\n instruments,\n index=ES_index)\n\n# Define 'instr' dataframe\ndf = data_y[data_y['Market_and_Exchange_Names'] == instr]\n\n# Select traders categories\nct = [False] * 5\ncat_list = [\n 'Asset managers', 'Leveraged funds', 'Other reportables',\n 'Non-reportables', 'Dealers'\n]\n# Show checkboxes with traders categories\nfor n in range(len(cat_list)):\n ct[n] = st.sidebar.checkbox(cat_list[n], value=True)\n\n# Calculate net positions\navg_period = 1\ndf['Asset managers'] = (\n df['Asset_Mgr_Positions_Long_All'] -\n df['Asset_Mgr_Positions_Short_All']).rolling(avg_period).mean()\ndf['Leveraged funds'] = (\n df['Lev_Money_Positions_Long_All'] -\n df['Lev_Money_Positions_Short_All']).rolling(avg_period).mean()\ndf['Non-reportables'] = (\n df['NonRept_Positions_Long_All'] -\n df['NonRept_Positions_Short_All']).rolling(avg_period).mean()\ndf['Dealers'] = (df['Dealer_Positions_Long_All'] -\n df['Dealer_Positions_Short_All']).rolling(avg_period).mean()\ndf['Other reportables'] = (\n df['Other_Rept_Positions_Long_All'] -\n df['Other_Rept_Positions_Short_All']).rolling(avg_period).mean()\n\n# Categories to plot\ncategories = []\nfor i in range(len(ct)):\n if ct[i]:\n categories.append(cat_list[i])\ndf0 = df[categories]\n\n# Plot data\nst.write(f'### COMMITMENT OF TRADERS - NET POSITIONS IN FUTURES')\nst.write(f'{instr.split(\" -\")[0]} FROM {start_year} TO {curr_year}')\n# st.line_chart(df0)\nst.line_chart(df0, width=640, height=440, use_container_width=False)\nst.sidebar.markdown(\"---\")\n# st.sidebar.write(f\"Last download: {os.getenv('DDATE')} \\n Last report: {last_report_date}\")\nst.sidebar.write(\n f\"Last update: {ddate} \\n Last report: {last_report_date}\"\n)\ndata_store.close()" ]
[ [ "pandas.read_excel", "pandas.to_datetime", "pandas.unique", "pandas.HDFStore", "pandas.set_option" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
louisletoumelin/wind_downscaling_cnn
[ "9d08711620db1ee1f472847f0e822c5f4eb1d300", "9d08711620db1ee1f472847f0e822c5f4eb1d300" ]
[ "train/Models/UNet.py", "downscale_/downscale/operators/micro_met.py" ]
[ "from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import *\n\n\ndef build_Unet(prm):\n '''\n Input: A dictionary containing parameters\n Output: Unet model\n \n Documentation:\n https://arxiv.org/pdf/1505.04597.pdf\n \n '''\n inputs = Input(prm['input_shape'])\n zero_padding = ZeroPadding2D(padding=((0, 1), (0, 1)), input_shape=prm['input_shape'])(inputs)\n\n '''\n 1st conv/pool\n '''\n conv1 = Conv2D(prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv1_0')(zero_padding)\n conv1 = Conv2D(prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv1')(conv1)\n if prm['full_dropout']:\n conv1 = Dropout(prm['dropout'], name='drop1')(conv1)\n if prm['full_batch_norm']:\n conv1 = BatchNormalization()(conv1)\n pool1 = MaxPooling2D(pool_size=prm['pool_size'], name='pool1')(conv1)\n\n '''\n 2nd conv/pool\n '''\n conv2 = Conv2D(2 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv2_0')(pool1)\n conv2 = Conv2D(2 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv2')(conv2)\n if prm['full_dropout']:\n conv2 = Dropout(prm['dropout'], name='drop2')(conv2)\n if prm['full_batch_norm']:\n conv2 = BatchNormalization()(conv2)\n pool2 = MaxPooling2D(pool_size=prm['pool_size'], name='pool2')(conv2)\n\n '''\n 3rd conv/poolextract_MNT_around_station\n '''\n conv3 = Conv2D(4 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv3_0')(pool2)\n conv3 = Conv2D(4 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv3')(conv3)\n if prm[\"minimal_dropout_layers\"]:\n conv3 = Dropout(prm['dropout'], name='drop3')(conv3)\n if prm['full_batch_norm']:\n conv3 = BatchNormalization()(conv3)\n pool3 = MaxPooling2D(pool_size=prm['pool_size'], name='pool3')(conv3)\n\n '''\n 4th conv/pool/up\n '''\n conv4 = Conv2D(8 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv4_0')(pool3)\n conv4 = Conv2D(8 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv4')(conv4)\n if prm[\"minimal_dropout_layers\"]:\n conv4 = Dropout(prm['dropout'], name='drop4')(conv4)\n if prm['full_batch_norm']:\n conv4 = BatchNormalization()(conv4)\n up4 = UpSampling2D(size=prm['up_conv'], name='up4_0')(conv4)\n up4 = Conv2D(4 * prm['nb_filters'], prm['up_conv'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='up4')(up4)\n up4 = ZeroPadding2D(padding=((0, 0), (0, 1)))(up4)\n\n '''\n 3rd up\n '''\n merge3 = concatenate([conv3, up4], axis=3, name='concat_3')\n conv3_up = Conv2D(4 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv3_up_0')(merge3)\n conv3_up = Conv2D(4 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv3_up')(conv3_up)\n if prm['full_dropout']:\n conv3_up = Dropout(prm['dropout'], name='drop3_up')(conv3_up)\n if prm['full_batch_norm']:\n conv3_up = BatchNormalization()(conv3_up)\n up3 = UpSampling2D(size=prm['up_conv'], name='up3_0')(conv3_up)\n up3 = Conv2D(2 * prm['nb_filters'], prm['up_conv'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='up3')(up3)\n up3 = ZeroPadding2D(padding=((0, 0), (0, 1)))(up3)\n\n '''\n 2nd up\n '''\n merge2 = concatenate([conv2, up3], axis=3, name='concat_2')\n conv2_up = Conv2D(2 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv2_up_0')(merge2)\n conv2_up = Conv2D(2 * prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv2_up')(conv2_up)\n if prm['full_dropout']:\n conv2_up = Dropout(prm['dropout'], name='drop2_up')(conv2_up)\n if prm['full_batch_norm']:\n conv2_up = BatchNormalization()(conv2_up)\n up2 = UpSampling2D(size=prm['up_conv'], name='up2_0')(conv2_up)\n up2 = Conv2D(1 * prm['nb_filters'], prm['up_conv'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='up2')(up2)\n\n '''\n 1st up\n '''\n merge1 = concatenate([conv1, up2], axis=3, name='concat_1')\n conv1_up = Conv2D(prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv1_up_0')(merge1)\n conv1_up = Conv2D(prm['nb_filters'], prm['kernel_size'], activation=prm['activation'],\n padding=prm['padding'], kernel_initializer=prm['initializer_func'], name='conv1_up')(conv1_up)\n conv1_1 = Conv2D(prm['nb_channels_output'], 1, activation=prm['activation_regression'], name='conv1_1')(conv1_up)\n up1 = Cropping2D(cropping=((0, 1), (0, 1)))(conv1_1)\n\n model = Model(inputs=inputs, outputs=up1)\n\n return (model)\n\n\ndef Unet(prm):\n model = build_Unet(prm)\n print('\\n Model selected: Unet\\n')\n print(model.summary())\n return (model)\n", "\"\"\"\nListon, G. E., & Elder, K. (2006). A meteorological distribution\nsystem for high-resolution terrestrial modeling (MicroMet).\nJournal of Hydrometeorology, 7(2), 217-234.\n\"\"\"\n\nimport numpy as np\nfrom downscale.operators.topo_utils import Topo_utils\nfrom downscale.utils.utils_func import change_dtype_if_required, lists_to_arrays_if_required\nfrom downscale.utils.decorators import change_dtype_if_required_decorator, print_func_executed_decorator\n\n\nclass SlopeMicroMet(Topo_utils):\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n @change_dtype_if_required_decorator(np.float32)\n def terrain_slope_map(mnt, dx, verbose=True):\n \"\"\"\n tan-1[ { (dz/dx)**2 + (dz/dy)**2 }**(1/2) ]\n \"\"\"\n print(\"____Library: numpy\") if verbose else None\n return np.arctan(np.sqrt(np.sum(np.array(np.gradient(mnt, dx)) ** 2, axis=0)))\n\n @print_func_executed_decorator(\"terrain_slope_idx\",\n level_begin=\"__\",\n level_end=\"__\",\n end=\"\")\n @change_dtype_if_required_decorator(np.float32)\n def terrain_slope_idx(self, mnt, dx, idx_x, idx_y, verbose=True):\n \"\"\"\n tan-1((dz/dx)**2 + (dz/dy)**2)**(1/2)\n\n Terrain slope following Liston and Elder (2006)\n \"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n\n print(\"__INFO: do not have to scale Terrain slope\") if verbose else None\n\n return [self.terrain_slope_map(mnt[y - 2:y + 3, x - 2:x + 3], dx, verbose=False)[2, 2] for (x, y) in\n zip(idx_x, idx_y)]\n\n def terrain_slope(self, mnt, dx, idx_x=None, idx_y=None, verbose=True):\n if ((idx_x is None) and (idx_y is None)) or np.ndim(idx_x) > 1:\n return self.terrain_slope_map(mnt, dx, verbose=verbose)\n else:\n return self.terrain_slope_idx(mnt, dx, idx_x, idx_y, verbose=verbose)\n\n\nclass AzimuthMicroMet(Topo_utils):\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n @change_dtype_if_required_decorator(np.float32)\n def terrain_slope_azimuth_map(mnt, dx, verbose=True):\n \"\"\"\n 3 pi /2 - tan-1[ (dz/dy) / (dz/dx) ]\n \"\"\"\n gradient_y, gradient_x = np.gradient(mnt, dx)\n arctan_value = np.where(gradient_x != 0,\n np.arctan(gradient_y / gradient_x),\n np.where(gradient_y > 0,\n np.pi / 2,\n np.where(gradient_y < 0,\n gradient_y,\n -np.pi / 2)))\n\n print(\"____Library: numpy\") if verbose else None\n\n return 3 * np.pi / 2 - arctan_value\n\n @change_dtype_if_required_decorator(np.float32)\n def terrain_slope_azimuth_idx(self, mnt, dx, idx_x, idx_y, verbose=True):\n \"\"\"\n 3 pi /2 - tan-1(dz/dy / dz/dx)\n \"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n\n print(\"__INFO: do not have to scale Terrain slope azimuth\") if verbose else None\n\n return [self.terrain_slope_azimuth_map(mnt[y - 2:y + 3, x - 2:x + 3], dx, verbose=False)[2, 2] for (x, y) in\n zip(idx_x, idx_y)]\n\n def terrain_slope_azimuth(self, mnt, dx, idx_x, idx_y, verbose=True):\n if ((idx_x is None) and (idx_y is None)) or np.ndim(idx_x) > 1:\n return self.terrain_slope_azimuth_map(mnt, dx, verbose=verbose)\n else:\n return self.terrain_slope_azimuth_idx(mnt, dx, idx_x, idx_y, verbose=verbose)\n\n\nclass CurvatureMicroMet(Topo_utils):\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n @change_dtype_if_required_decorator(np.float32)\n def get_length_scale_curvature(mnt):\n std_mnt = np.nanstd(mnt)\n return 2 * std_mnt if std_mnt != 0 else 1\n\n @change_dtype_if_required_decorator(np.float32)\n def curvature_map(self, mnt, length_scale=None, scaling_factor=None, scale=False, verbose=True):\n \"\"\"\n Curvature following Liston and Elder (2006)\n\n (1/4) * ((z-(n+s)/2)/(2*n) + (z-(e+w)/2)/(2*n) + (z-(nw+se)/2)/((2*sqrt(2)*n)) + (z-(ne+sw)/2)/(2*sqrt(2)*n))\n\n with n = 2*std(dem)\n\n\n Parameters\n ----------\n mnt : dnarray\n Digital elevation model (topography)\n idx_x : dnarray\n Indexes along the x axis\n idx_y : ndarray\n Indexes along the y axis\n method : string\n \"safe\" or anything else. If safe, first compute curvature on a map and the select indexes.\n This allows for clean scaling of curvature if abs(curvatur) > 0.5 (Liston and Elder (2006))\n If an other string is passed, the computation will be faster but the scaling might be unadequate.\n scale : boolean\n If True, scale the output such as -0.5<curvature<0.5\n length_scale : float\n Length used in curvature computation\n scaling_factor : float\n Length used to scale outputs\n verbose : boolean\n Print verbose\n\n Returns\n -------\n curvature : ndarray\n Curvature\n \"\"\"\n\n length_scale = self.get_length_scale_curvature(mnt) if length_scale is None else length_scale\n\n s = np.roll(mnt, -1, axis=0)\n n = np.roll(mnt, 1, axis=0)\n w = np.roll(mnt, 1, axis=1)\n e = np.roll(mnt, -1, axis=1)\n s_e = np.roll(np.roll(mnt, -1, axis=1), -1, axis=0)\n n_w = np.roll(np.roll(mnt, 1, axis=1), 1, axis=0)\n s_w = np.roll(np.roll(mnt, 1, axis=1), -1, axis=0)\n n_e = np.roll(np.roll(mnt, -1, axis=1), 1, axis=0)\n\n curv_e_w = (mnt - (w + e) / 2) / (2 * length_scale)\n curv_n_s = (mnt - (n + s) / 2) / (2 * length_scale)\n curv_ne_sw = (mnt - (n_e + s_w) / 2) / (2 * np.sqrt(2) * length_scale)\n curv_nw_se = (mnt - (n_w + s_e) / 2) / (2 * np.sqrt(2) * length_scale)\n\n curvature = (curv_e_w + curv_n_s + curv_ne_sw + curv_nw_se) / 4\n\n if scale:\n scaling_factor = np.nanmax(np.abs(curvature[1:-1, 1:-1])) if scaling_factor is None else scaling_factor\n curvature = curvature / (2 * scaling_factor)\n assert np.all(-0.5 <= curvature[1:-1, 1:-1])\n assert np.all(curvature[1:-1, 1:-1] <= 0.5)\n print(\"___curvature is now scaled between -0.5 and 0.5 \"\n \"(assumption not true on the borders)\") if verbose else None\n\n print(\"____Library: numpy\") if verbose else None\n return curvature\n\n @change_dtype_if_required_decorator(np.float32)\n def curvature_idx(self, mnt, idx_x, idx_y, method=\"safe\", scale=False, length_scale=None, scaling_factor=None, verbose=True):\n \"\"\"\n Curvature following Liston and Elder (2006)\n\n (1/4) * ((z-(n+s)/2)/(2*n) + (z-(e+w)/2)/(2*n) + (z-(nw+se)/2)/((2*sqrt(2)*n)) + (z-(ne+sw)/2)/(2*sqrt(2)*n))\n\n with n = 2*std(dem)\n\n\n Parameters\n ----------\n mnt : dnarray\n Digital elevation model (topography)\n idx_x : dnarray\n Indexes along the x axis\n idx_y : ndarray\n Indexes along the y axis\n method : string\n \"safe\" or anything else. If safe, first compute curvature on a map and the select indexes.\n This allows for clean scaling of curvature if abs(curvatur) > 0.5 (Liston and Elder (2006))\n If an other string is passed, the computation will be faster but the scaling might be unadequate.\n scale : boolean\n If True, scale the output such as -0.5<curvature<0.5\n length_scale : float\n Length used in curvature computation\n scaling_factor : float\n Length used to scale outputs\n verbose : boolean\n Print verbose\n\n Returns\n -------\n curvature : ndarray\n Curvature\n \"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n if method == \"safe\":\n curvature_map = self.curvature_map(mnt,\n scale=scale, length_scale=length_scale,\n scaling_factor=scaling_factor, verbose=verbose)\n print(\"____Method: Safe (scaling factor calculate on the all map)\") if verbose else None\n return curvature_map[idx_y, idx_x]\n else:\n length_scale = self.get_length_scale_curvature(mnt)\n curvature = [self.curvature_map(mnt[y-2:y+3, x-2:x+3],\n scale=False,\n length_scale=length_scale,\n verbose=False)[2, 2] for (x, y) in zip(idx_x, idx_y)]\n curvature = np.array(curvature, dtype=np.float32)\n\n if scale and (np.any(curvature < -0.5) or np.any(curvature > 0.5)):\n scaling_factor = np.nanmax(np.abs(curvature[1:-1, 1:-1])) if scaling_factor is None else scaling_factor\n curvature = curvature / (2 * scaling_factor)\n assert np.all(-0.5 <= curvature[1:-1, 1:-1])\n assert np.all(curvature[1:-1, 1:-1] <= 0.5)\n print(\"__Used scaling in curvature_idx. Method: NOT safe \"\n \"(scaling factor not defined on the all map)\") if verbose else None\n else:\n print(\"__WARNING: Did not scale curvature\") if verbose else None\n\n print(\"__Curvature indexes selected. Method: NOT safe\") if verbose else None\n\n return curvature\n\n def curvature(self, mnt, idx_x=None, idx_y=None,\n method=\"safe\", scale=False, length_scale=None, scaling_factor=None, verbose=True):\n if ((idx_x is None) and (idx_y is None)) or np.ndim(idx_x) > 1:\n return self.curvature_map(mnt, length_scale=length_scale, scaling_factor=scaling_factor,\n scale=scale, verbose=verbose)\n else:\n return self.curvature_idx(mnt, idx_x, idx_y,\n method=method, scale=scale, length_scale=length_scale,\n scaling_factor=scaling_factor, verbose=verbose)\n\n\nclass MicroMet(SlopeMicroMet, AzimuthMicroMet, CurvatureMicroMet):\n\n def __init__(self):\n super().__init__()\n\n @change_dtype_if_required_decorator(np.float32)\n def _omega_s_map(self, mnt, dx, wind_dir, scale=False, scaling_factor=None, verbose=True):\n \"\"\"The slope in the direction of the wind\"\"\"\n beta = self.terrain_slope_map(mnt, dx, verbose=verbose)\n xi = self.terrain_slope_azimuth_map(mnt, dx, verbose=verbose)\n omega_s = beta * np.cos(wind_dir - xi)\n\n if scale:\n scaling_factor = np.nanmax(np.abs(omega_s[1:-1, 1:-1])) if scaling_factor is None else scaling_factor\n omega_s = omega_s / (2 * scaling_factor)\n assert np.all(-0.5 <= omega_s[-1:1, -1:1])\n assert np.all(omega_s[-1:1, -1:1] <= 0.5)\n\n print(\"____Library: numpy\") if verbose else None\n\n return omega_s\n\n def _omega_s_idx(self, mnt, dx, wind_dir, idx_x, idx_y, method=\"safe\", scale=False, scaling_factor=None, verbose=True):\n \"\"\"\n Omega_s following Liston and Elder (2006)\n\n Parameters\n ----------\n mnt : dnarray\n Digital elevation model (topography)\n dx : float\n Digital elevation model resolution (distance between grid points)\n idx_x : dnarray\n Indexes along the x axis\n idx_y : ndarray\n Indexes along the y axis\n method : string\n \"safe\" or anything else. If safe, first compute omega_s on a map and the select indexes.\n This allows for clean scaling of omega_s if abs(omega_s) > 0.5 (Liston and Elder (2006))\n If an other string is passed, the computation will be faster but the scaling might be unadequate.\n scale : boolean\n If True, scale the output such as -0.5<omega_s<0.5\n scaling_factor : float\n Length used to scale outputs\n verbose : boolean\n Print verbose\n\n Returns\n -------\n omega_s : ndarray\n Omega_s\n \"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n if method == \"safe\":\n omega_s_map_ = self.omega_s_map(mnt, dx, wind_dir, scale=scale, scaling_factor=scaling_factor, verbose=verbose)\n\n print(\"__Omega_s indexes selected. Method: Safe\") if verbose else None\n return omega_s_map_[idx_y, idx_x]\n\n else:\n omega_s_idx_ = [self.omega_s_map(mnt[y - 2:y + 3, x - 2:x + 3], dx, wind_dir, scale=False, verbose=False)[2, 2] for (x, y) in\n zip(idx_x, idx_y)]\n omega_s_idx_ = np.array(omega_s_idx_)\n\n if scale and (np.any(omega_s_idx_ < -0.5) or np.any(omega_s_idx_ > 0.5)):\n scaling_factor = np.nanmax(np.abs(omega_s_idx_[1:-1, 1:-1])) if scaling_factor is None else scaling_factor\n omega_s_idx_ = omega_s_idx_ / (2 * scaling_factor)\n assert np.all(-0.5 <= omega_s_idx_[1:-1, 1:-1])\n assert np.all(omega_s_idx_[1:-1, 1:-1] <= 0.5)\n print(\"__Used scaling in omega_s_idx. Method: NOT safe\") if verbose else None\n else:\n print(\"__WARNING: Did not scale omega_s\") if verbose else None\n\n print(\"__Omega_s indexes selected. Method: NOT safe\") if verbose else None\n\n return omega_s_idx_\n\n def omega_s(self, mnt, dx, wind_dir, idx_x=None, idx_y=None, method=\"safe\", scale=False, scaling_factor=None, verbose=True):\n if ((idx_x is None) and (idx_y is None)) or np.ndim(idx_x) > 1:\n return self._omega_s_map(mnt, dx, wind_dir, scale=scale, scaling_factor=scaling_factor, verbose=verbose)\n else:\n return self._omega_s_idx(mnt, dx, wind_dir, idx_x, idx_y,\n method=method, scale=scale, scaling_factor=scaling_factor, verbose=verbose)\n\n @change_dtype_if_required_decorator(np.float32)\n def wind_weighting_factor(self, mnt, dx, wind_dir, idx_x=None, idx_y=None, gamma_s=0.58, gamma_c=0.42,\n method=\"safe\", scale=True, length_scale=None, scaling_factor=None, verbose=True):\n \"\"\"gamma_s = 0.58 and gamma_c = 0.42\"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n omega_c = self.curvature(mnt, idx_x=idx_x, idx_y=idx_y, method=method, scale=scale,\n length_scale=length_scale, scaling_factor=scaling_factor, verbose=verbose)\n omega_s = self.omega_s(mnt, dx, wind_dir, idx_x=idx_x, idx_y=idx_y, method=method, scale=scale,\n scaling_factor=scaling_factor, verbose=verbose)\n\n print(\"____Library: numpy\") if verbose else None\n\n return 1 + gamma_s * omega_s + gamma_c * omega_c\n\n @change_dtype_if_required_decorator(np.float32)\n def diverting_factor(self, mnt, dx, wind_dir, idx_x=None, idx_y=None,\n method=\"safe\", scale=False, scaling_factor=None, verbose=True):\n \"\"\"Need test map and idx\"\"\"\n idx_x, idx_y = lists_to_arrays_if_required([idx_x, idx_y])\n omega_s = self.omega_s(mnt, dx, wind_dir, idx_x=idx_x, idx_y=idx_y, method=method,\n scale=scale, scaling_factor=scaling_factor, verbose=verbose)\n azimuth = self.terrain_slope_azimuth(mnt, dx, idx_x, idx_y, verbose=verbose)\n\n print(\"____Library: numpy\") if verbose else None\n\n return -0.5 * omega_s * np.sin(2 * (azimuth - wind_dir))\n" ]
[ [ "tensorflow.keras.models.Model" ], [ "numpy.sqrt", "numpy.arctan", "numpy.gradient", "numpy.abs", "numpy.cos", "numpy.sin", "numpy.all", "numpy.ndim", "numpy.any", "numpy.nanstd", "numpy.array", "numpy.where", "numpy.roll" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mehrdad-shokri/mlens
[ "6cbc11354b5f9500a33d9cefb700a1bba9d3199a" ]
[ "mlens/externals/sklearn/scorer.py" ]
[ "\"\"\"\n\nScikit-learn imports to reconstruct the ``make_scorer`` function.\n\n========================================================================\nThe :mod:`sklearn.metrics.scorer` submodule implements a flexible\ninterface for model selection and evaluation using\narbitrary score functions.\n\nA scorer object is a callable that can be passed to\n:class:`sklearn.model_selection.GridSearchCV` or\n:func:`sklearn.model_selection.cross_val_score` as the ``scoring``\nparameter, to specify how a model should be evaluated.\n\nThe signature of the call is ``(estimator, X, y)`` where ``estimator``\nis the model to be evaluated, ``X`` is the test data and ``y`` is the\nground truth labeling (or ``None`` in the case of unsupervised models).\n========================================================================\n\"\"\"\n\n# Authors: Andreas Mueller <[email protected]>\n# Lars Buitinck\n# Arnaud Joly <[email protected]>\n# License: Simplified BSD\n\nimport warnings\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\n\nfrom .. import six\nfrom .base import is_regressor\nfrom .type_of_target import type_of_target\n\n\nclass _BaseScorer(six.with_metaclass(ABCMeta, object)):\n def __init__(self, score_func, sign, kwargs):\n self._kwargs = kwargs\n self._score_func = score_func\n self._sign = sign\n # XXX After removing the deprecated scorers (v0.20) remove the\n # XXX deprecation_msg property again and remove __call__'s body again\n self._deprecation_msg = None\n\n @abstractmethod\n def __call__(self, estimator, X, y, sample_weight=None):\n if self._deprecation_msg is not None:\n warnings.warn(self._deprecation_msg,\n category=DeprecationWarning,\n stacklevel=2)\n\n def __repr__(self):\n kwargs_string = \"\".join([\", %s=%s\" % (str(k), str(v))\n for k, v in self._kwargs.items()])\n return (\"make_scorer(%s%s%s%s)\"\n % (self._score_func.__name__,\n \"\" if self._sign > 0 else \", greater_is_better=False\",\n self._factory_args(), kwargs_string))\n\n def _factory_args(self):\n \"\"\"Return non-default make_scorer arguments for repr.\"\"\"\n return \"\"\n\n\nclass _PredictScorer(_BaseScorer):\n def __call__(self, estimator, X, y_true, sample_weight=None):\n \"\"\"Evaluate predicted target values for X relative to y_true.\n\n Parameters\n ----------\n estimator : object\n Trained estimator to use for scoring. Must have a predict_proba\n method; the output of that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to estimator.predict.\n\n y_true : array-like\n Gold standard target values for X.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n super(_PredictScorer, self).__call__(estimator, X, y_true,\n sample_weight=sample_weight)\n y_pred = estimator.predict(X)\n if sample_weight is not None:\n return self._sign * self._score_func(y_true, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y_true, y_pred,\n **self._kwargs)\n\n\nclass _ProbaScorer(_BaseScorer):\n def __call__(self, clf, X, y, sample_weight=None):\n \"\"\"Evaluate predicted probabilities for X relative to y_true.\n\n Parameters\n ----------\n clf : object\n Trained classifier to use for scoring. Must have a predict_proba\n method; the output of that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to clf.predict_proba.\n\n y : array-like\n Gold standard target values for X. These must be class labels,\n not probabilities.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n super(_ProbaScorer, self).__call__(clf, X, y,\n sample_weight=sample_weight)\n y_pred = clf.predict_proba(X)\n if sample_weight is not None:\n return self._sign * self._score_func(y, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y, y_pred, **self._kwargs)\n\n def _factory_args(self):\n return \", needs_proba=True\"\n\n\nclass _ThresholdScorer(_BaseScorer):\n def __call__(self, clf, X, y, sample_weight=None):\n \"\"\"Evaluate decision function output for X relative to y_true.\n\n Parameters\n ----------\n clf : object\n Trained classifier to use for scoring. Must have either a\n decision_function method or a predict_proba method; the output of\n that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to clf.decision_function or\n clf.predict_proba.\n\n y : array-like\n Gold standard target values for X. These must be class labels,\n not decision function values.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n super(_ThresholdScorer, self).__call__(clf, X, y,\n sample_weight=sample_weight)\n y_type = type_of_target(y)\n if y_type not in (\"binary\", \"multilabel-indicator\"):\n raise ValueError(\"{0} format is not supported\".format(y_type))\n\n if is_regressor(clf):\n y_pred = clf.predict(X)\n else:\n try:\n y_pred = clf.decision_function(X)\n\n # For multi-output multi-class estimator\n if isinstance(y_pred, list):\n y_pred = np.vstack(p for p in y_pred).T\n\n except (NotImplementedError, AttributeError):\n y_pred = clf.predict_proba(X)\n\n if y_type == \"binary\":\n y_pred = y_pred[:, 1]\n elif isinstance(y_pred, list):\n y_pred = np.vstack([p[:, -1] for p in y_pred]).T\n\n if sample_weight is not None:\n return self._sign * self._score_func(y, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y, y_pred, **self._kwargs)\n\n def _factory_args(self):\n return \", needs_threshold=True\"\n\n\ndef make_scorer(score_func, greater_is_better=True, needs_proba=False,\n needs_threshold=False, **kwargs):\n \"\"\"Make a scorer from a performance metric or loss function.\n\n This factory function wraps scoring functions for use in GridSearchCV\n and cross_val_score. It takes a score function, such as ``accuracy_score``,\n ``mean_squared_error``, ``adjusted_rand_index`` or ``average_precision``\n and returns a callable that scores an estimator's output.\n\n Read more in the :ref:`User Guide <scoring>`.\n\n Parameters\n ----------\n score_func : callable,\n Score function (or loss function) with signature\n ``score_func(y, y_pred, **kwargs)``.\n\n greater_is_better : boolean, default=True\n Whether score_func is a score function (default), meaning high is good,\n or a loss function, meaning low is good. In the latter case, the\n scorer object will sign-flip the outcome of the score_func.\n\n needs_proba : boolean, default=False\n Whether score_func requires predict_proba to get probability estimates\n out of a classifier.\n\n needs_threshold : boolean, default=False\n Whether score_func takes a continuous decision certainty.\n This only works for binary classification using estimators that\n have either a decision_function or predict_proba method.\n\n For example ``average_precision`` or the area under the roc curve\n can not be computed using discrete predictions alone.\n\n **kwargs : additional arguments\n Additional parameters to be passed to score_func.\n\n Returns\n -------\n scorer : callable\n Callable object that returns a scalar score; greater is better.\n\n Examples\n --------\n >>> from sklearn.metrics import fbeta_score, make_scorer\n >>> ftwo_scorer = make_scorer(fbeta_score, beta=2)\n >>> ftwo_scorer\n make_scorer(fbeta_score, beta=2)\n >>> from sklearn.model_selection import GridSearchCV\n >>> from sklearn.svm import LinearSVC\n >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},\n ... scoring=ftwo_scorer)\n \"\"\"\n sign = 1 if greater_is_better else -1\n if needs_proba and needs_threshold:\n raise ValueError(\"Set either needs_proba or needs_threshold to True,\"\n \" but not both.\")\n if needs_proba:\n cls = _ProbaScorer\n elif needs_threshold:\n cls = _ThresholdScorer\n else:\n cls = _PredictScorer\n return cls(score_func, sign, kwargs)\n" ]
[ [ "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gauranshkumar/chithi
[ "09438f32cc656f4b00a0d6d591450e006816c52b" ]
[ "src/app.py" ]
[ "# Imports\nimport email\nimport pandas as pd\nimport streamlit as st\nimport markdown\nimport mimetypes\n\n# from streamlit_ace import st_ace, LANGUAGES, THEMES\nimport time\nfrom mailer import Mailer\nfrom info import get_server_info\n\n\ndef setup_page_title():\n # Title for page\n st.title(\"✉️ CHITTHI\")\n st.subheader(\"Send emails in Bulk ⚡\")\n st.markdown(\"*****\")\n\n\ndef get_mail_password():\n # Takinks Mail ID and password of the Sender\n st.markdown(\"##### Who's sending the mail? 🤔\")\n mailid = st.text_input(\"Email:\")\n passwrd = st.text_input(\"Password:\", type=\"password\")\n return mailid, passwrd\n\n\ndef setup_server():\n # Choosing the server of sender\n server = st.selectbox(\"Choose your Mail Provider\", [\n \"Gmail\", \"Yahoo\", \"Outlook\", \"Hotmail\", \"iCloud\"])\n # Some important info to setup the account\n st.warning(get_server_info(st.session_state.get(\"server\", server)))\n return server\n\n\ndef upload_cc(c1):\n ccUpload = c1.file_uploader(\n \"Upload File\", type=['xls', 'xlsx', 'csv', 'tsv'], key=\"cc\")\n if ccUpload is not None:\n if ccUpload.type == mimetypes.types_map['.xls'] or ccUpload.type == \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":\n df_cc = pd.read_excel(ccUpload)\n elif ccUpload.type == mimetypes.types_map['.csv']:\n df_cc = pd.read_csv(ccUpload)\n elif ccUpload.type == mimetypes.types_map['.tsv']:\n df_cc = pd.read_csv(ccUpload, delimiter=\"\\t\")\n\n col = c1.selectbox(\"Select the Column of Mail Id's\", df_cc.columns, )\n try:\n cc = df_cc[col].to_numpy().tolist()\n\n except:\n c1.warning(\"Please select the correct column for Email Id.\")\n\n\ndef upload_bcc(c2):\n bccUpload = c2.file_uploader(\n \"Upload File\", type=['xls', 'xlsx', 'csv', 'tsv'], key=\"bcc\")\n\n if bccUpload is not None:\n if bccUpload.type == mimetypes.types_map['.xls'] or bccUpload.type == \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":\n df_bcc = pd.read_excel(bccUpload)\n elif bccUpload.type == mimetypes.types_map['.csv']:\n df_bcc = pd.read_csv(bccUpload)\n elif bccUpload.type == mimetypes.types_map['.tsv']:\n df_bcc = pd.read_csv(bccUpload, delimiter=\"\\t\")\n\n col = c2.selectbox(\"Select the Column of Mail Id's\", df_bcc.columns)\n try:\n bcc = df_bcc[col].to_numpy().tolist()\n print(bcc)\n except:\n c2.warning(\"Please select the correct column for Email Id.\")\n\n\ndef add_attachments(cc, mailid, passwrd, server):\n # Attachments options for mail\n attachments = st.file_uploader(\"Attachments:\", accept_multiple_files=True)\n\n # Calling the core Mailer Class\n mailer = Mailer(mailid, passwrd, server.lower())\n\n if cc == [\"\"]:\n cc = None\n return mailer, attachments\n\n\ndef process_ccbcc_info(c1, c2):\n cc = c1.text_input(\"Cc\")\n cc = cc.split(\",\")\n c1.markdown(\"<center> OR </center>\", unsafe_allow_html=True)\n upload_cc(c1)\n bcc = c2.text_input(\"Bcc\")\n bcc = bcc.split(\",\")\n c2.markdown(\"<center> OR </center>\", unsafe_allow_html=True)\n upload_bcc(c2)\n return cc, bcc\n\n\ndef collect_recipients_info():\n # Collecting Recipients information\n st.markdown(\"\"\"*****\n # Tell me about recipients ✨\"\"\")\n recipients = st.text_input(\"Recipient:\")\n c1, c2 = st.columns(2)\n cc, bcc = process_ccbcc_info(c1, c2)\n return cc, bcc, recipients\n\n# TODO: Allow option for reading recipients from CSV/XSLX file\n\n\ndef view_html(body):\n view_html = st.checkbox(\"View Raw HTML\")\n if view_html:\n st.code(markdown.markdown(st.session_state.get(\"body\", body)))\n\n st.info(\n \"\"\"We support Markdown Editor 🎉 If you are new to Markdown check this [Guide](https://www.markdownguide.org/basic-syntax/).\"\"\")\n\n\ndef set_markdown():\n # Taking Message to Mail in Markdown\n st.markdown(\"\"\"*****\n # What's the message? 🔥\"\"\")\n\n subject = st.text_input(\"Subject:\")\n # Setting split view for live Output of Markdown\n col1, col2 = st.columns(2)\n body = col1.text_area(\"Body:\", height=300)\n # body = st_ace(language=LANGUAGES[90], theme=THEMES[13], auto_update=True)\n col2.markdown(st.session_state.get(\"body\", body), unsafe_allow_html=True)\n view_html(body)\n return subject, body\n\n# rendering the markdown to HTML\nbody = markdown.markdown(body)\n\n# If user wants to see the markdown eqivalent HTML Code\n\n\ndef mail(cc, bcc, mailer, recipients, subject, body, attachments):\n '''Function to send the mail'''\n print(bcc)\n print(\"\\n\\n\", cc)\n mailer.send_mail(to=recipients, cc=cc, bcc=bcc, subject=subject,\n body=body, attachments=attachments)\n with st.spinner(\"Sending...\"):\n time.sleep(5)\n st.success(\"Mail sent successfully!\")\n\n\ndef email_button(cc, bcc, mailer, recipients, subject, body, attachments):\n st.markdown(\"<br>\", unsafe_allow_html=True)\n # Sending the mail on Button Press\n st.button(\"Send 📮\", on_click=mail(cc, bcc, mailer,\n recipients, subject, body, attachments))\n # TODO: Handle Alert if Mail not sent successfully\n\n\ndef footer():\n # Footer\n st.markdown(\"\"\"\n <br><br>\n <center> Made with ❤️ by <a href=\"https://gauranshkumar.github.io/\" target=\"_blank\">Gauransh Kumar</a> in 🇮🇳 </center>\n \"\"\", unsafe_allow_html=True)\n\n\ndef main():\n setup_page_title()\n mailid, passwrd = get_mail_password()\n server = setup_server()\n cc, bcc, recipients = collect_recipients_info()\n mailer, attachments = add_attachments(cc, mailid, passwrd, server)\n subject, body = set_markdown()\n email_button(cc, bcc, mailer, recipients, subject, body, attachments)\n footer()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "pandas.read_excel", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
thomaskost17/winter2022
[ "1dd92a9ad1aab7a339d24bf7155eb056dbdf0ec6" ]
[ "ECEC247/hw5/nndl/cnn.py" ]
[ "from platform import architecture\nimport numpy as np\n\nfrom nndl.layers import *\nfrom nndl.conv_layers import *\nfrom utils.fast_layers import *\nfrom nndl.layer_utils import *\nfrom nndl.conv_layer_utils import *\n\nimport pdb\n\nclass ThreeLayerConvNet(object):\n \"\"\"\n A three-layer convolutional network with the following architecture:\n \n conv - relu - 2x2 max pool - affine - relu - affine - softmax\n \n The network operates on minibatches of data that have shape (N, C, H, W)\n consisting of N images, each with height H and width W and with C input\n channels.\n \"\"\"\n \n def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7,\n hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0,\n dtype=np.float32, use_batchnorm=False):\n \"\"\"\n Initialize a new network.\n \n Inputs:\n - input_dim: Tuple (C, H, W) giving size of input data\n - num_filters: Number of filters to use in the convolutional layer\n - filter_size: Size of filters to use in the convolutional layer\n - hidden_dim: Number of units to use in the fully-connected hidden layer\n - num_classes: Number of scores to produce from the final affine layer.\n - weight_scale: Scalar giving standard deviation for random initialization\n of weights.\n - reg: Scalar giving L2 regularization strength\n - dtype: numpy datatype to use for computation.\n \"\"\"\n self.use_batchnorm = use_batchnorm\n self.params = {}\n self.reg = reg\n self.dtype = dtype\n\n \n # ================================================================ #\n # YOUR CODE HERE:\n # Initialize the weights and biases of a three layer CNN. To initialize:\n # - the biases should be initialized to zeros.\n # - the weights should be initialized to a matrix with entries\n # drawn from a Gaussian distribution with zero mean and \n # standard deviation given by weight_scale.\n # ================================================================ #\n self.conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}\n self.pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n C,H,W = input_dim\n self.params['W1'] = np.random.randn(num_filters, C, filter_size,filter_size)*weight_scale\n self.params['b1'] = np.zeros(num_filters)\n H_conv = 1 + (H + 2 * self.conv_param['pad'] - filter_size) / self.conv_param['stride']\n W_conv = 1 + (W + 2 * self.conv_param['pad'] - filter_size) / self.conv_param['stride']\n depth_conv = num_filters \n H_pool = 1 + (H_conv - self.pool_param['pool_height'])/self.pool_param['stride']\n W_pool = 1 + (W_conv - self.pool_param['pool_width'])/self.pool_param['stride']\n depth_pool = num_filters\n self.params['W2'] = np.random.randn(int(H_pool*W_pool*depth_pool),hidden_dim)*weight_scale\n self.params['b2'] = np.zeros(hidden_dim)\n self.params['W3'] = np.random.randn(hidden_dim,num_classes)*weight_scale\n self.params['b3'] = np.zeros(num_classes)\n\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n\n for k, v in self.params.items():\n self.params[k] = v.astype(dtype)\n \n \n def loss(self, X, y=None):\n \"\"\"\n Evaluate loss and gradient for the three-layer convolutional network.\n \n Input / output: Same API as TwoLayerNet in fc_net.py.\n \"\"\"\n W1, b1 = self.params['W1'], self.params['b1']\n W2, b2 = self.params['W2'], self.params['b2']\n W3, b3 = self.params['W3'], self.params['b3']\n \n # pass conv_param to the forward pass for the convolutional layer\n filter_size = W1.shape[2]\n conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}\n\n # pass pool_param to the forward pass for the max-pooling layer\n pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\n scores = None\n \n # ================================================================ #\n # YOUR CODE HERE:\n # Implement the forward pass of the three layer CNN. Store the output\n # scores as the variable \"scores\".\n # ================================================================ #\n conv_out, conv_cache = conv_relu_pool_forward(X,W1, b1, conv_param, pool_param)\n h1, h1cache = affine_relu_forward(conv_out, W2, b2)\n h2,h2cache = affine_forward(h1,W3, b3)\n scores = h2\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n\n if y is None:\n return scores\n \n loss, grads = 0, {}\n # ================================================================ #\n # YOUR CODE HERE:\n # Implement the backward pass of the three layer CNN. Store the grads\n # in the grads dictionary, exactly as before (i.e., the gradient of \n # self.params[k] will be grads[k]). Store the loss as \"loss\", and\n # don't forget to add regularization on ALL weight matrices.\n # ================================================================ #\n\n loss, dLdh2 = softmax_loss(scores, y)\n dLdh1, grads['W3'], grads['b3'] = affine_backward(dLdh2,h2cache)\n dLdconvout, grads['W2'], grads['b2'] = affine_relu_backward(dLdh1,h1cache)\n _,grads['W1'], grads['b1'] = conv_relu_pool_backward(dLdconvout, conv_cache)\n grads['W1'] += self.reg*self.params['W1']\n grads['W2'] += self.reg*self.params['W2']\n grads['W3'] += self.reg*self.params['W3']\n loss += 0.5*self.reg*np.linalg.norm(self.params['W1'])**2 +0.5*self.reg*np.linalg.norm(self.params['W2'])**2+0.5*self.reg*np.linalg.norm(self.params['W3'])**2\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n\n return loss, grads\n \n \nclass CNN(object):\n \"\"\"\n A three-layer convolutional network with the following architecture:\n \n conv - relu - 2x2 max pool - affine - relu - affine - softmax\n \n The network operates on minibatches of data that have shape (N, C, H, W)\n consisting of N images, each with height H and width W and with C input\n channels.\n \"\"\"\n \n def __init__(self, input_dim=(3, 32, 32), num_filters=[32], filter_size=[7],\n hidden_dim=[100,100], num_classes=10, weight_scale=1e-3, reg=0.0,\n dtype=np.float32, use_batchnorm=False):\n \"\"\"\n Initialize a new network.\n \n Inputs:\n - input_dim: Tuple (C, H, W) giving size of input data\n - num_filters: Number of filters to use in the convolutional layer\n - filter_size: Size of filters to use in each convolutional layer\n - hidden_dim: Number of units to use in the fully-connected hidden layer\n - num_classes: Number of scores to produce from the final affine layer.\n - weight_scale: Scalar giving standard deviation for random initialization\n of weights.\n - reg: Scalar giving L2 regularization strength\n - dtype: numpy datatype to use for computation.\n \"\"\"\n self.use_batchnorm = use_batchnorm\n self.params = {}\n self.reg = reg\n self.dtype = dtype\n self.num_conv_layers = len(filter_size)\n self.num_fc_layers = len(hidden_dim)\n self.num_layers = self.num_conv_layers+self.num_fc_layers\n self.conv_param = []\n self.pool_param = []\n # ================================================================ #\n # YOUR CODE HERE:\n # Initialize the weights and biases of a three layer CNN. To initialize:\n # - the biases should be initialized to zeros.\n # - the weights should be initialized to a matrix with entries\n # drawn from a Gaussian distribution with zero mean and \n # standard deviation given by weight_scale.\n # ================================================================ #\n C,H,W = input_dim\n H_pool,W_pool,depth_pool = None,None,None\n # Set up CNN\n for i in range(self.num_conv_layers):\n w_i = 'W'+str(i+1)\n b_i = 'b'+str(i+1)\n gamma_i = 'gamma'+str(i+1)\n beta_i = 'beta'+str(i+1)\n self.conv_param.append({'stride': 1, 'pad': (filter_size[i] - 1) / 2})\n self.pool_param.append({'pool_height': 2, 'pool_width': 2, 'stride': 2})\n if(i==0):\n self.params[w_i] = np.random.randn(num_filters[i], C, filter_size[i],filter_size[i])*weight_scale\n self.params[b_i] = np.zeros(num_filters[i])\n if self.use_batchnorm:\n self.params[gamma_i] = np.ones((num_filters[i],))\n self.params[beta_i] = np.zeros((num_filters[i],))\n H_conv = 1 + (H + 2 * self.conv_param[i]['pad'] - filter_size[i]) / self.conv_param[i]['stride']\n W_conv = 1 + (W + 2 * self.conv_param[i]['pad'] - filter_size[i]) / self.conv_param[i]['stride']\n depth_conv = num_filters[i] \n H_pool = 1 + (H_conv - self.pool_param[i]['pool_height'])/self.pool_param[i]['stride']\n W_pool = 1 + (W_conv - self.pool_param[i]['pool_width'])/self.pool_param[i]['stride']\n depth_pool = depth_conv\n else:\n self.params[w_i] = np.random.randn(num_filters[i], num_filters[i-1], filter_size[i],filter_size[i])*weight_scale\n self.params[b_i] = np.zeros(num_filters[i])\n if self.use_batchnorm:\n self.params[gamma_i] = np.ones((num_filters[i],))\n self.params[beta_i] = np.zeros((num_filters[i],))\n H_conv = 1 + (H_pool + 2 * self.conv_param[i]['pad'] - filter_size[i]) / self.conv_param[i]['stride']\n W_conv = 1 + (W_pool + 2 * self.conv_param[i]['pad'] - filter_size[i]) / self.conv_param[i]['stride']\n depth_conv = num_filters[i] \n H_pool = 1 + (H_conv - self.pool_param[i]['pool_height'])/self.pool_param[i]['stride']\n W_pool = 1 + (W_conv - self.pool_param[i]['pool_width'])/self.pool_param[i]['stride']\n depth_pool = depth_conv\n # Setup FCNET\n for i in range(self.num_fc_layers):\n w_i = 'fcW'+str(i+1)\n b_i = 'fcb'+str(i+1)\n gamma_i = 'fcgamma'+str(i+1)\n beta_i = 'fcbeta'+str(i+1)\n if (i==0):\n self.params[w_i] = np.random.randn(int(H_pool*W_pool*depth_pool),hidden_dim[i])*weight_scale\n self.params[b_i] = np.zeros(hidden_dim[i])\n if self.use_batchnorm:\n self.params[gamma_i] = np.ones((hidden_dim[i],))\n self.params[beta_i] = np.zeros((hidden_dim[i],))\n elif (i==self.num_fc_layers-1):\n self.params[w_i] = np.random.randn(hidden_dim[i-1],num_classes)*weight_scale\n self.params[b_i] = np.zeros((num_classes,))\n else:\n self.params[w_i] = np.random.randn(hidden_dim[i-1],hidden_dim[i])*weight_scale\n self.params[b_i] = np.zeros((hidden_dim[i],))\n if(self.use_batchnorm):\n self.params[gamma_i] = np.ones((hidden_dim[i],))\n self.params[beta_i] = np.zeros((hidden_dim[i],))\n\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n self.bn_params = []\n if self.use_batchnorm:\n self.bn_params = [{'mode': 'train'} for i in np.arange(self.num_layers - 1)]\n\n for k, v in self.params.items():\n self.params[k] = v.astype(dtype)\n \n \n def loss(self, X, y=None):\n \"\"\"\n Evaluate loss and gradient for the convolutional network.\n \n Input / output: Same API as TwoLayerNet in fc_net.py.\n \"\"\"\n\n # pass pool_param to the forward pass for the max-pooling layer\n pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}\n\n scores = None\n X = X.astype(self.dtype)\n mode = 'test' if y is None else 'train'\n if self.use_batchnorm:\n for bn_param in self.bn_params:\n bn_param['mode'] = mode\n # ================================================================ #\n # YOUR CODE HERE:\n # Implement the forward pass of the three layer CNN. Store the output\n # scores as the variable \"scores\".\n # ================================================================ #\n conv_caches =[]\n fc_caches =[]\n conv_cache,h1cache,h2cache = None,None,None\n conv_out,h_i = None,None\n if self.use_batchnorm:\n for i in range(self.num_conv_layers):\n #generate keys\n w_i = 'W'+str(i+1)\n b_i = 'b'+str(i+1)\n gamma_i = 'gamma'+str(i+1)\n beta_i = 'beta'+str(i+1)\n if(i==0):\n conv_out, conv_cache = conv_relu_pool_batchnorm_forward(X,self.params[w_i], self.params[b_i], self.conv_param[i], self.pool_param[i], self.params[gamma_i], self.params[beta_i], self.bn_params[i])\n conv_caches.append(conv_cache)\n else:\n conv_out, conv_cache = conv_relu_pool_batchnorm_forward(conv_out,self.params[w_i], self.params[b_i], self.conv_param[i], self.pool_param[i], self.params[gamma_i], self.params[beta_i], self.bn_params[i])\n conv_caches.append(conv_cache)\n for i in range(self.num_fc_layers):\n w_i = 'fcW'+str(i+1)\n b_i = 'fcb'+str(i+1)\n gamma_i = 'fcgamma'+str(i+1)\n beta_i = 'fcbeta'+str(i+1)\n if(i==0):\n h_i, hicache = affine_batchnorm_relu_forward(conv_out, self.params[w_i], self.params[b_i], self.params[gamma_i], self.params[beta_i], self.bn_params[i+self.num_conv_layers])\n fc_caches.append(hicache)\n elif(i!=self.num_fc_layers-1):\n h_i, hicache = affine_batchnorm_relu_forward(h_i, self.params[w_i], self.params[b_i], self.params[gamma_i], self.params[beta_i], self.bn_params[i+self.num_conv_layers])\n fc_caches.append(hicache)\n else:\n h_i,hicache = affine_forward(h_i,self.params[w_i], self.params[b_i])\n fc_caches.append(hicache)\n scores = h_i\n\n else:\n for i in range(self.num_conv_layers):\n #generate keys\n w_i = 'W'+str(i+1)\n b_i = 'b'+str(i+1)\n gamma_i = 'gamma'+str(i+1)\n beta_i = 'beta'+str(i+1)\n if(i==0):\n conv_out, conv_cache = conv_relu_pool_forward(X,self.params[w_i], self.params[b_i], self.conv_param[i], self.pool_param[i])\n conv_caches.append(conv_cache)\n else:\n conv_out, conv_cache = conv_relu_pool_forward(conv_out,self.params[w_i], self.params[b_i], self.conv_param[i], self.pool_param[i])\n conv_caches.append(conv_cache)\n for i in range(self.num_fc_layers):\n w_i = 'fcW'+str(i+1)\n b_i = 'fcb'+str(i+1)\n gamma_i = 'fcgamma'+str(i+1)\n beta_i = 'fcbeta'+str(i+1)\n if(i==0):\n h_i, hicache = affine_relu_forward(conv_out, self.params[w_i], self.params[b_i])\n fc_caches.append(hicache)\n elif(i!=self.num_fc_layers-1):\n h_i, hicache = affine_relu_forward(h_i, self.params[w_i], self.params[b_i])\n fc_caches.append(hicache)\n else:\n h_i,hicache = affine_forward(h_i,self.params[w_i], self.params[b_i])\n fc_caches.append(hicache)\n scores = h_i\n\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n\n if y is None:\n return scores\n \n loss, grads = 0, {}\n # ================================================================ #\n # YOUR CODE HERE:\n # Implement the backward pass of the three layer CNN. Store the grads\n # in the grads dictionary, exactly as before (i.e., the gradient of \n # self.params[k] will be grads[k]). Store the loss as \"loss\", and\n # don't forget to add regularization on ALL weight matrices.\n # ================================================================ #\n\n loss, dLdupstream = softmax_loss(scores, y)\n if self.use_batchnorm:\n for i in reversed(range(self.num_fc_layers)):\n w_i = 'fcW'+str(i+1)\n b_i = 'fcb'+str(i+1)\n gamma_i = 'fcgamma'+str(i+1)\n beta_i = 'fcbeta'+str(i+1)\n if(i==self.num_fc_layers-1):\n dLdupstream, grads[w_i], grads[b_i] = affine_backward(dLdupstream,fc_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n\n else:\n dLdupstream,grads[w_i], grads[b_i], grads[gamma_i], grads[beta_i] = affine_batchnorm_relu_backward(dLdupstream,fc_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n\n for i in reversed(range(self.num_conv_layers)):\n w_i = 'W'+str(i+1)\n b_i = 'b'+str(i+1)\n gamma_i = 'gamma'+str(i+1)\n beta_i = 'beta'+str(i+1)\n dLdupstream,grads[w_i], grads[b_i], grads[gamma_i], grads[beta_i] = conv_relu_pool_batchnorm_backward(dLdupstream, conv_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n else:\n for i in reversed(range(self.num_fc_layers)):\n w_i = 'fcW'+str(i+1)\n b_i = 'fcb'+str(i+1)\n gamma_i = 'fcgamma'+str(i+1)\n beta_i = 'fcbeta'+str(i+1)\n if(i==self.num_fc_layers-1):\n dLdupstream, grads[w_i], grads[b_i] = affine_backward(dLdupstream,fc_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n\n else:\n dLdupstream,grads[w_i], grads[b_i] = affine_relu_backward(dLdupstream,fc_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n\n for i in reversed(range(self.num_conv_layers)):\n w_i = 'W'+str(i+1)\n b_i = 'b'+str(i+1)\n gamma_i = 'gamma'+str(i+1)\n beta_i = 'beta'+str(i+1)\n dLdupstream,grads[w_i], grads[b_i] = conv_relu_pool_backward(dLdupstream, conv_caches[i])\n grads[w_i]+= self.reg*self.params[w_i]\n loss += 0.5*self.reg*np.linalg.norm(self.params[w_i])**2\n\n # ================================================================ #\n # END YOUR CODE HERE\n # ================================================================ #\n\n return loss, grads" ]
[ [ "numpy.arange", "numpy.linalg.norm", "numpy.ones", "numpy.random.randn", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kiddyboots216/ben-decentralized-chatbot
[ "c13f6046e1bf22b4303896096da96dab24a8e221" ]
[ "chatbot/conversation_discriminator.py" ]
[ "# -*- coding: utf-8 -*-\n\n__author__ = 'Oswaldo Ludwig'\n__version__ = '1.01'\n\nfrom keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Dropout, merge\nfrom keras.optimizers import Adam \nfrom keras.models import Model\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dense\nfrom keras.preprocessing import sequence\nfrom keras.layers import concatenate\n\nimport keras.backend as K\nimport numpy as np\nnp.random.seed(1234) # for reproducibility\nimport pickle\nimport theano\nimport os.path\nimport sys\nimport nltk\nimport re\nimport time\n\nfrom keras.utils import plot_model\n\nword_embedding_size = 100\nsentence_embedding_size = 300\ndictionary_size = 7000\nmaxlen_input = 50\nlearning_rate = 0.000001\n\nvocabulary_file = 'vocabulary_movie'\nweights_file = 'my_model_weights20.h5'\nweights_file_GAN = 'my_model_weights.h5'\nweights_file_discrim = 'my_model_weights_discriminator.h5'\nunknown_token = 'something'\nfile_saved_context = 'saved_context'\nfile_saved_answer = 'saved_answer'\nname_of_computer = 'john'\n\ndef greedy_decoder(input):\n\n flag = 0\n prob = 1\n ans_partial = np.zeros((1,maxlen_input))\n ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence)\n for k in range(maxlen_input - 1):\n ye = model.predict([input, ans_partial])\n yel = ye[0,:]\n p = np.max(yel)\n mp = np.argmax(ye)\n ans_partial[0, 0:-1] = ans_partial[0, 1:]\n ans_partial[0, -1] = mp\n if mp == 3: # he index of the symbol EOS (end of sentence)\n flag = 1\n if flag == 0: \n prob = prob * p\n text = ''\n for k in ans_partial[0]:\n k = k.astype(int)\n if k < (dictionary_size-2):\n w = vocabulary[k]\n text = text + w[0] + ' '\n return(text, prob)\n \n \ndef preprocess(raw_word, name):\n \n l1 = ['won’t','won\\'t','wouldn’t','wouldn\\'t','’m', '’re', '’ve', '’ll', '’s','’d', 'n’t', '\\'m', '\\'re', '\\'ve', '\\'ll', '\\'s', '\\'d', 'can\\'t', 'n\\'t', 'B: ', 'A: ', ',', ';', '.', '?', '!', ':', '. ?', ', .', '. ,', 'EOS', 'BOS', 'eos', 'bos']\n l2 = ['will not','will not','would not','would not',' am', ' are', ' have', ' will', ' is', ' had', ' not', ' am', ' are', ' have', ' will', ' is', ' had', 'can not', ' not', '', '', ' ,', ' ;', ' .', ' ?', ' !', ' :', '? ', '.', ',', '', '', '', '']\n l3 = ['-', '_', ' *', ' /', '* ', '/ ', '\\\"', ' \\\\\"', '\\\\ ', '--', '...', '. . .']\n l4 = ['jeffrey','fred','benjamin','paula','walter','rachel','andy','helen','harrington','kathy','ronnie','carl','annie','cole','ike','milo','cole','rick','johnny','loretta','cornelius','claire','romeo','casey','johnson','rudy','stanzi','cosgrove','wolfi','kevin','paulie','cindy','paulie','enzo','mikey','i\\97','davis','jeffrey','norman','johnson','dolores','tom','brian','bruce','john','laurie','stella','dignan','elaine','jack','christ','george','frank','mary','amon','david','tom','joe','paul','sam','charlie','bob','marry','walter','james','jimmy','michael','rose','jim','peter','nick','eddie','johnny','jake','ted','mike','billy','louis','ed','jerry','alex','charles','tommy','bobby','betty','sid','dave','jeffrey','jeff','marty','richard','otis','gale','fred','bill','jones','smith','mickey'] \n\n raw_word = raw_word.lower()\n raw_word = raw_word.replace(', ' + name_of_computer, '')\n raw_word = raw_word.replace(name_of_computer + ' ,', '')\n\n for j, term in enumerate(l1):\n raw_word = raw_word.replace(term,l2[j])\n \n for term in l3:\n raw_word = raw_word.replace(term,' ')\n \n for term in l4:\n raw_word = raw_word.replace(', ' + term, ', ' + name)\n raw_word = raw_word.replace(' ' + term + ' ,' ,' ' + name + ' ,')\n raw_word = raw_word.replace('i am ' + term, 'i am ' + name_of_computer)\n raw_word = raw_word.replace('my name is' + term, 'my name is ' + name_of_computer)\n \n for j in range(30):\n raw_word = raw_word.replace('. .', '')\n raw_word = raw_word.replace('. .', '')\n raw_word = raw_word.replace('..', '')\n \n for j in range(5):\n raw_word = raw_word.replace(' ', ' ')\n \n if raw_word[-1] != '!' and raw_word[-1] != '?' and raw_word[-1] != '.' and raw_word[-2:] != '! ' and raw_word[-2:] != '? ' and raw_word[-2:] != '. ':\n raw_word = raw_word + ' .'\n \n if raw_word == ' !' or raw_word == ' ?' or raw_word == ' .' or raw_word == ' ! ' or raw_word == ' ? ' or raw_word == ' . ':\n raw_word = 'what ?'\n \n if raw_word == ' .' or raw_word == ' .' or raw_word == ' . ':\n raw_word = 'i do not want to talk about it .'\n \n return raw_word\n\ndef tokenize(sentences):\n\n # Tokenizing the sentences into words:\n tokenized_sentences = nltk.word_tokenize(sentences)\n index_to_word = [x[0] for x in vocabulary]\n word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])\n tokenized_sentences = [w if w in word_to_index else unknown_token for w in tokenized_sentences]\n X = np.asarray([word_to_index[w] for w in tokenized_sentences])\n s = X.size\n Q = np.zeros((1,maxlen_input))\n if s < (maxlen_input + 1):\n Q[0,- s:] = X\n else:\n Q[0,:] = X[- maxlen_input:]\n \n return Q\n\n# Open files to save the conversation for further training:\nqf = open(file_saved_context, 'a')\naf = open(file_saved_answer, 'a')\n\n\ndef init_model():\n\n # *******************************************************************\n # Keras model of the discriminator: \n # *******************************************************************\n\n # ad = Adam(lr=learning_rate) \n\n input_context = Input(shape=(maxlen_input,), dtype='int32', name='input-context')\n input_answer = Input(shape=(maxlen_input,), dtype='int32', name='input-answer')\n input_current_token = Input(shape=(dictionary_size,), name='input_current_token')\n\n LSTM_encoder_discriminator = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name = 'encoder-discriminator')\n LSTM_decoder_discriminator = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name = 'decoder-discriminator')\n \n Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, trainable=False, name = 'shared')\n word_embedding_context = Shared_Embedding(input_context)\n word_embedding_answer = Shared_Embedding(input_answer)\n context_embedding_discriminator = LSTM_encoder_discriminator(word_embedding_context)\n answer_embedding_discriminator = LSTM_decoder_discriminator(word_embedding_answer)\n loss = concatenate([context_embedding_discriminator, answer_embedding_discriminator, input_current_token], axis=1, name = 'concatenation-discriminator')\n loss = Dense(1, activation=\"sigmoid\", name = 'discriminator-output')(loss)\n\n model_discrim = Model(inputs=[input_context, input_answer, input_current_token], outputs = [loss])\n\n # model_discrim.compile(loss='binary_crossentropy', optimizer=ad)\n\n if os.path.isfile(weights_file_discrim):\n model_discrim.load_weights(weights_file_discrim)\n \n return model_discrim \n\ndef run_discriminator(q, a):\n\n sa = (a != 0).sum()\n\n # *************************************************************************\n # running discriminator:\n # *************************************************************************\n\n p = 1\n m = 0\n model_discrim = init_model()\n count = 0\n \n for i, sent in enumerate(a):\n l = np.where(sent==3) # the position od the symbol EOS\n limit = l[0][0]\n count += limit + 1\n\n Q = np.zeros((count,maxlen_input))\n A = np.zeros((count,maxlen_input))\n Y = np.zeros((count,dictionary_size))\n\n # Loop over the training examples:\n count = 0\n for i, sent in enumerate(a):\n ans_partial = np.zeros((1,maxlen_input))\n \n # Loop over the positions of the current target output (the current output sequence):\n l = np.where(sent==3) # the position of the symbol EOS\n limit = l[0][0]\n\n for k in range(1,limit+1):\n # Mapping the target output (the next output word) for one-hot codding:\n y = np.zeros((1, dictionary_size))\n y[0, int(sent[k])] = 1\n\n # preparing the partial answer to input:\n ans_partial[0,-k:] = sent[0:k]\n\n # training the model for one epoch using teacher forcing:\n Q[count, :] = q[i:i+1] \n A[count, :] = ans_partial \n Y[count, :] = y\n count += 1\n\n p = model_discrim.predict([ Q, A, Y])\n p = p[-sa:-1]\n P = np.sum(np.log(p))/sa\n \n return P\n\nprint('Starting the model...')\n\n# *******************************************************************\n# Keras model of the chatbot: \n# *******************************************************************\n\nad = Adam(lr=learning_rate) \n\ninput_context = Input(shape=(maxlen_input,), dtype='int32', name='the-context-text')\ninput_answer = Input(shape=(maxlen_input,), dtype='int32', name='the-answer-text-up-to-the-current-token')\nLSTM_encoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode-context')\nLSTM_decoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode-answer-up-to-the-current-token')\n\nShared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, name='Shared')\nword_embedding_context = Shared_Embedding(input_context)\ncontext_embedding = LSTM_encoder(word_embedding_context)\n\nword_embedding_answer = Shared_Embedding(input_answer)\nanswer_embedding = LSTM_decoder(word_embedding_answer)\n\nmerge_layer = concatenate([context_embedding, answer_embedding], axis=1, name='concatenate-the-embeddings-of-the-context-and-the-answer-up-to-current-token')\nout = Dense(int(dictionary_size/2), activation=\"relu\", name='relu-activation')(merge_layer)\nout = Dense(dictionary_size, activation=\"softmax\", name='likelihood-of-the-current-token-using-softmax-activation')(out)\n\nmodel = Model(inputs=[input_context, input_answer], outputs = [out])\n\nmodel.compile(loss='categorical_crossentropy', optimizer=ad)\nfrom keras.models import model_from_json\n\njson_string = model.to_json()\nmodel = model_from_json(json_string)\n#save\nvalues = np.array([K.get_value(w) for w in model.weights+ad.weights])\n# import json\n# with open('npweights.txt', 'w') as outfile:\n # values.save(outfile)\nnp.save('npweights.npy', values)\nvalues = np.load('npweights.npy')\n\n# Loading the data:\nvocabulary = pickle.load(open(vocabulary_file, 'rb'))\n\nprint(\"\\n \\n \\n \\n CHAT: \\n \\n\")\n\n# Processing the user query:\nprob = 0\nque = ''\nlast_query = ' '\nlast_last_query = ''\ntext = ' '\nlast_text = ''\nprint('computer: hi ! please type your name.\\n')\nname = input('user: ')\nprint('computer: hi , ' + name +' ! My name is ' + name_of_computer + '.\\n') \n\n\nwhile que != 'exit .':\n \n que = input('user: ')\n que = preprocess(que, name_of_computer)\n # Collecting data for training:\n q = last_query + ' ' + text\n a = que\n qf.write(q + '\\n')\n af.write(a + '\\n')\n # Composing the context:\n if prob > 0.2:\n query = text + ' ' + que\n else: \n query = que\n \n last_text = text\n \n Q = tokenize(query)\n \n # Using the trained model to predict the answer:\n model.load_weights(weights_file)\n predout, prob = greedy_decoder(Q[0:1])\n start_index = predout.find('EOS')\n text = preprocess(predout[0:start_index], name) + ' EOS'\n \n model.load_weights(weights_file_GAN)\n predout, prob2 = greedy_decoder(Q[0:1])\n start_index = predout.find('EOS')\n text2 = preprocess(predout[0:start_index], name) + ' EOS'\n \n p1 = run_discriminator(Q, tokenize(text))\n p2 = run_discriminator(Q, tokenize(text2))\n \n if max([prob, prob2]) > .9:\n if prob > prob2:\n best = text[0 : -4]\n else:\n best = text2[0 : -4]\n else:\n if p1 > p2:\n best = text[0 : -4]\n else:\n best = text2[0 : -4]\n init = ''\n\n print('\\n' + 'computer: ' + best)\n \n last_last_query = last_query \n last_query = que\n\nqf.close()\naf.close()\n" ]
[ [ "numpy.log", "numpy.random.seed", "numpy.asarray", "numpy.save", "numpy.max", "numpy.argmax", "numpy.load", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AAlben/segementation_1
[ "999db92b2ec792ec1bd65f5e193a97c7be20c4fc" ]
[ "faster_rcnn/infference_1.py" ]
[ "import os\nimport cv2\nimport json\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom labelme import utils as labelme_utils\n\nimport torch\nimport torchvision\nimport torchvision.transforms as T\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nclass SelfTransform(object):\n\n def __init__(self):\n kernel = (5, 5)\n self.kernel = kernel\n\n def __call__(self, img):\n opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, self.kernel)\n return opening\n\n\ntransforms = T.Compose([\n SelfTransform(),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n])\n\n\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\ndevice = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')\nnum_classes = 2 # 1 class (person) + background\nin_features = model.roi_heads.box_predictor.cls_score.in_features\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\nmodel.load_state_dict(torch.load('/root/code/model_state/faster_rcnn_kaggle.pth'))\nmodel.eval()\nmodel = model.to(device)\n\n\nresults = []\nwith torch.no_grad():\n PATH = '/root/code/model_data/train_bmp'\n for file in tqdm(os.listdir(PATH)[:100]):\n if '.bmp' not in file:\n continue\n\n json_path = os.path.splitext(file)[0] + '.json'\n if os.path.exists(os.path.join(PATH, json_path)):\n continue\n\n # print(os.path.join(PATH, file))\n img = cv2.imread(os.path.join(PATH, file))\n image = transforms(img)\n image = image.to(device)[None]\n output = model(image)[0]\n boxes = output['boxes'].cpu().numpy()\n results.append([os.path.join(PATH, file), boxes[0]])\nprint(results)\n" ]
[ [ "torch.device", "torch.no_grad", "torch.cuda.is_available", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
justinbois/altair-catplot
[ "b0afb8a62657ca7d97df7a8151f8347539db01d6" ]
[ "altair_catplot/jitter.py" ]
[ "import warnings\n\nimport numpy as np\nimport pandas as pd\n\nimport altair as alt\nfrom altair.utils.schemapi import Undefined, UndefinedType\n\nfrom .utils import (_check_catplot_transform,\n _check_catplot_sort,\n _check_mark,\n _make_altair_encoding,\n _get_column_name,\n _get_data_type,\n _make_color_encoding)\n\n\ndef _jitter_plot(data, height, width, mark, encoding, jitter_width, sort,\n **kwargs):\n \"\"\"Generate a jitter plot with Altair.\n \"\"\"\n encoding_tuple = _parse_encoding_jitter(encoding, data, sort)\n (encoding, encoding_text, cat, val, \n nominal_axis_values, horizontal, zero) = encoding_tuple\n\n _check_catplot_sort(data, cat, sort)\n\n sort = _jitter_sort(data, cat, sort, horizontal)\n\n mark_jitter, mark_text = _parse_mark_jitter(mark, horizontal)\n\n df, df_text = _jitter_dataframe(data, \n val, \n cat, \n jitter_width, \n nominal_axis_values,\n sort, \n zero)\n\n chart_jitter = alt.Chart(data=df,\n width=width,\n height=height,\n mark=mark_jitter,\n encoding=encoding,\n **kwargs)\n\n chart_text = alt.Chart(data=df_text,\n width=width,\n height=height,\n mark=mark_text,\n encoding=encoding_text)\n\n return alt.layer(chart_jitter, chart_text)\n\n\ndef _jitter_sort(data, cat, sort, horizontal):\n \"\"\"Generate sort \n \"\"\"\n if sort == Undefined:\n sort = list(data[cat].unique())\n\n if horizontal:\n return list(reversed(sort))\n else:\n return sort\n\n\ndef _jitter(x, sort, jitter_width):\n \"\"\"Make x-coordinates for a jitter plot.\"\"\"\n if sort == Undefined:\n centers = pd.Categorical(x).codes\n else:\n cats = list(pd.Categorical(x))\n centers = np.array([sort.index(c) for c in cats], dtype=float)\n\n return (centers\n + np.random.uniform(low=-jitter_width/2,\n high=jitter_width/2,\n size=len(x)))\n\n\ndef _check_altair_jitter_input(data, height, width, mark, encoding,\n jitter_width):\n if mark not in ['point', 'circle', 'square', 'tick']:\n raise RuntimeError(\"\"\"Invalid `mark`. \nAllowed values are ['point', 'circle', 'square', 'tick'].\"\"\")\n if data is None:\n raise RuntimeError('`data` must be specified.')\n if not (0 <= jitter_width <= 1):\n raise RuntimeError('Must have `jitter_width` between 0 and 1.')\n\n\ndef _jitter_domain(data, val, zero, pad=0.05):\n \"\"\"Determine domain for jitter plot\"\"\"\n if zero:\n return [0, Undefined]\n else:\n data_range = data[val].max() - data[val].min()\n return [data[val].min() - pad * data_range,\n data[val].max() + pad * data_range]\n\n\ndef _jitter_dataframe(data, val, cat, jitter_width, nominal_axis_values,\n sort, zero):\n \"\"\"DataFrame for making jitter plots.\"\"\"\n df = data.copy()\n\n if cat is None:\n df['__jitter'] = _jitter(np.zeros(len(df)), sort, jitter_width)\n else:\n df['__jitter'] = _jitter(df[cat], sort, jitter_width)\n\n if zero:\n min_val = 0\n else:\n min_val = _jitter_domain(df, val, zero, pad=0.05)[0]\n\n # Make text data frame\n if sort == Undefined:\n text = df[cat].unique()\n else:\n cats = list(pd.Categorical(df[cat]))\n text = [cats[cats.index(s)] for s in sort]\n\n df_text = pd.DataFrame(data={val: [min_val]*len(nominal_axis_values),\n '__jitter': nominal_axis_values,\n 'text': text})\n\n return df, df_text\n\n\ndef _parse_encoding_jitter(encoding, data, sort):\n \"\"\"Parse encoding for a jitter plot.\"\"\"\n if type(encoding) != dict:\n raise RuntimeError('`encoding` must be specified as a dict.')\n\n extra_encodings = {key: val for key, val in encoding.items()\n if key not in ['x', 'y', 'color']}\n\n err = (\"Exactly one of encoding['x'] or encoding['y'] must have\" \n + \" quantitative encoding.\")\n\n if 'x' not in encoding or 'y' not in encoding:\n raise RuntimeError(\"Both 'x' and 'y' must be in `encoding`.\")\n\n x = _make_altair_encoding(encoding['x'], encoding=alt.X)\n y = _make_altair_encoding(encoding['y'], encoding=alt.Y)\n\n if _get_data_type(x) in 'NO':\n if _get_data_type(y) != 'Q':\n raise RuntimeError(err)\n\n if x.title != Undefined:\n warnings.warn(\n 'Categorical axis titles not allowed for jitter plots.' \n + ' Ignoring....')\n\n cat = _get_column_name(x)\n val = _get_column_name(y)\n\n val_axis = 'y'\n\n nominal_axis_values = list(range(len(data[cat].unique())))\n\n if y.title == Undefined:\n y.title = val\n\n color = _make_color_encoding(encoding, cat, sort)\n\n encoding = dict(x=_make_altair_encoding(\n '__jitter:Q',\n encoding=alt.X, \n axis=alt.Axis(title=None,\n labels=False,\n values=nominal_axis_values,\n grid=False)),\n y=y, \n color=color,\n **extra_encodings)\n encoding_text = dict(x=_make_altair_encoding(\n '__jitter:Q',\n encoding=alt.X, \n axis=alt.Axis(title=None,\n labels=False,\n values=nominal_axis_values,\n grid=False)),\n y=y,\n text=alt.Text('text:N'))\n elif _get_data_type(y) in 'NO':\n if _get_data_type(x) != 'Q':\n raise RuntimeError(err)\n cat = _get_column_name(y)\n val = _get_column_name(x)\n\n if y.title != Undefined:\n warnings.warn(\n 'Categorical axis titles not allowed for jitter plots.' \n + ' Ignoring....')\n\n val_axis = 'x'\n\n nominal_axis_values = list(range(len(data[cat].unique())))\n\n if x.title == Undefined:\n x.title = val\n\n color = _make_color_encoding(encoding, cat, sort)\n\n encoding = dict(x=x,\n y=_make_altair_encoding(\n '__jitter:Q',\n encoding=alt.Y, \n axis=alt.Axis(title=None,\n labels=False,\n values=nominal_axis_values,\n grid=False)),\n color=color,\n **extra_encodings)\n encoding_text = dict(y=_make_altair_encoding(\n '__jitter:Q',\n encoding=alt.Y, \n axis=alt.Axis(title=None,\n labels=False,\n values=nominal_axis_values,\n grid=False)),\n x=x,\n text=alt.Text('text:N'))\n\n # Determine if y-axis is zeroed\n if data[val].min() < 0:\n if (encoding[val_axis]._kwds['scale'] != Undefined\n and encoding[val_axis]._kwds['scale']._kwds['zero']):\n zero = True\n else:\n zero = False\n elif (encoding[val_axis]._kwds['scale'] == Undefined\n or encoding[val_axis]._kwds['scale']._kwds['zero']):\n zero = True\n else:\n zero = False\n\n horizontal = val_axis == 'x'\n\n if not zero:\n domain = _jitter_domain(data, val, zero, pad=0.05)\n if horizontal:\n encoding['x'] = _make_altair_encoding(\n x, \n encoding=alt.X, \n scale=alt.Scale(domain=domain, nice=False))\n else:\n encoding['y'] = _make_altair_encoding(\n y, \n encoding=alt.Y, \n scale=alt.Scale(domain=domain, nice=False))\n\n return (encoding, encoding_text, cat, val, nominal_axis_values,\n horizontal, zero)\n\n\ndef _parse_mark_jitter(mark, horizontal):\n \"\"\"Parse mark for jitter plot.\"\"\"\n if mark in ['point', 'circle', 'square']:\n mark_jitter = alt.MarkDef(type=mark)\n elif type(mark) != dict:\n raise RuntimeError(\"\"\"`mark` must be a dict or be one of:\n 'point'\n 'circle'\n 'square'\"\"\")\n else: \n mark_jitter = alt.MarkDef(**mark)\n\n\n if horizontal:\n mark_text = alt.MarkDef(type='text',\n baseline='middle',\n align='right',\n dx=-8)\n else:\n mark_text = alt.MarkDef(type='text',\n baseline='top',\n align='center',\n dy=8)\n\n return mark_jitter, mark_text\n" ]
[ [ "pandas.Categorical" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
defermelowie/ML-course-project
[ "df35ddbd2c76d6077ca1657133d089bbdf3a2e0b" ]
[ "results/20-12-2021_12u14/plotter.py" ]
[ "import json as json\nimport matplotlib.pyplot as plt\n\n# Load data\nwith open(f'./results.json', 'r') as fd:\n results = json.load(fd)\n\n# Plot setup\nfig, (train_plt, cv_plt) = plt.subplots(2, sharex=True)\n\ntrain_plt.set(xlabel='Iterations', ylabel='Accuracy')\ntrain_plt.grid(visible=True, which='major', axis='both')\ntrain_plt.label_outer()\n\ncv_plt.set(xlabel='Iterations', ylabel='Accuracy')\ncv_plt.grid(visible=True, which='major', axis='both')\ncv_plt.label_outer()\n\nline_styles = ['-', '--', '-.', ':']\n\n# Plot data\nfor i, result in enumerate(results['results']):\n print(f'Result {i}: {result}')\n\n cv_plt.plot(\n result['iterations'],\n result['cv_accuracy'],\n f'k{line_styles[i]}',\n label=f'Cross validation {result[\"cv\"]}'\n )\n train_plt.plot(\n result['iterations'],\n result['train_accuracy'],\n f'k{line_styles[i]}',\n label=f'Training {result[\"cv\"]}'\n )\n\n# Plot setup\ntrain_plt.legend()\ncv_plt.legend()\n\nfig.tight_layout()\n\n# Save and show\nplt.savefig(f'./accuracy_iterations.pdf')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cooltunes/magenta
[ "be6558f1a06984faff6d6949234f5fe9ad0ffdb5" ]
[ "magenta/models/coconet/lib_hparams.py" ]
[ "# Copyright 2021 The Magenta Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Classes for defining hypermaters and model architectures.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools as it\nimport os\n\nfrom magenta.models.coconet import lib_util\nimport numpy as np\nimport six\nimport tensorflow.compat.v1 as tf\nimport yaml\n\n\nclass ModelMisspecificationError(Exception):\n \"\"\"Exception for specifying a model that is not currently supported.\"\"\"\n pass\n\n\ndef load_hparams(checkpoint_path):\n # hparams_fpath = os.path.join(os.path.dirname(checkpoint_path), 'config')\n hparams_fpath = os.path.join(checkpoint_path, 'config')\n with tf.gfile.Open(hparams_fpath, 'r') as p:\n hparams = Hyperparameters.load(p)\n return hparams\n\n\nclass Hyperparameters(object):\n \"\"\"Stores hyperparameters for initialization, batch norm and training.\"\"\"\n _LEGACY_HPARAM_NAMES = ['num_pitches', 'pitch_ranges']\n _defaults = dict(\n # Data.\n dataset=None,\n quantization_level=0.125,\n qpm=60,\n corrupt_ratio=0.25,\n # Input dimensions.\n batch_size=20,\n min_pitch=36,\n max_pitch=81,\n crop_piece_len=64,\n num_instruments=4,\n separate_instruments=True,\n # Batch norm parameters.\n batch_norm=True,\n batch_norm_variance_epsilon=1e-7,\n # Initialization.\n init_scale=0.1,\n # Model architecture.\n architecture='straight',\n # Hparams for depthwise separable convs.\n use_sep_conv=False,\n sep_conv_depth_multiplier=1,\n num_initial_regular_conv_layers=2,\n # Hparams for reducing pointwise in separable convs.\n num_pointwise_splits=1,\n interleave_split_every_n_layers=1,\n # Hparams for dilated convs.\n num_dilation_blocks=3,\n dilate_time_only=False,\n repeat_last_dilation_level=False,\n # num_layers is used only for non dilated convs\n # as the number of layers in dilated convs is computed based on\n # num_dilation_blocks.\n num_layers=28,\n num_filters=256,\n use_residual=True,\n checkpoint_name=None,\n # Loss setup.\n # TODO(annahuang): currently maskout_method here is not functional,\n # still need to go through config_tools.\n maskout_method='orderless',\n optimize_mask_only=False,\n # use_softmax_loss=True,\n rescale_loss=True,\n # Training.\n # learning_rate=2**-6,\n learning_rate=2**-4, # for sigmoids.\n mask_indicates_context=False,\n eval_freq=1,\n num_epochs=0,\n patience=5,\n # Runtime configs.\n run_dir=None,\n log_process=True,\n save_model_secs=30,\n run_id='')\n\n def __init__(self, *unused_args, **init_hparams):\n \"\"\"Update the default parameters through string or keyword arguments.\n\n This __init__ provides two ways to initialize default parameters, either by\n passing a string representation of a a Python dictionary containing\n hyperparameter to value mapping or by passing those hyperparameter values\n directly as keyword arguments.\n\n Args:\n *unused_args: A tuple of arguments. This first expected argument is a\n string representation of a Python dictionary containing hyperparameter\n to value mapping. For example, {\"num_layers\":8, \"num_filters\"=128}.\n **init_hparams: Keyword arguments for setting hyperparameters.\n\n Raises:\n ValueError: When incoming hparams are not in class _defaults.\n \"\"\"\n tf.logging.info('Instantiating hparams...')\n unknown_params = set(init_hparams) - set(Hyperparameters._defaults)\n if unknown_params:\n raise ValueError('Unknown hyperparameters: %s' % unknown_params)\n self.update(Hyperparameters._defaults)\n self.update(init_hparams)\n\n def update(self, dikt, **kwargs):\n all_dikt = dict(it.chain(six.iteritems(dikt), six.iteritems(kwargs)))\n self._filter_and_check_legacy_hparams(all_dikt)\n for key, value in six.iteritems(all_dikt):\n setattr(self, key, value)\n\n def _filter_and_check_legacy_hparams(self, dikt):\n legacy_hparams = dict()\n for l_hparam in Hyperparameters._LEGACY_HPARAM_NAMES:\n if l_hparam in dikt:\n legacy_hparams[l_hparam] = dikt[l_hparam]\n del dikt[l_hparam]\n if legacy_hparams:\n self._check_pitch_range_compatibilities(legacy_hparams, dikt)\n\n def _check_pitch_range_compatibilities(self, legacy_hparams, dikt):\n \"\"\"Check that all the pitch range related hparams match each other.\"\"\"\n min_pitch = dikt.get('min_pitch', self.min_pitch)\n max_pitch = dikt.get('max_pitch', self.max_pitch)\n if 'pitch_ranges' in legacy_hparams:\n for legacy_pitch, given_pitch in zip(\n legacy_hparams['pitch_ranges'], [min_pitch, max_pitch]):\n if legacy_pitch != given_pitch:\n raise ValueError(\n 'Legacy pitch range element %d does not match given '\n 'pitch %d.' % (\n legacy_pitch, given_pitch))\n if 'num_pitches' in legacy_hparams:\n computed_num_pitches = max_pitch - min_pitch + 1\n legacy_num_pitches = legacy_hparams['num_pitches']\n if legacy_num_pitches != computed_num_pitches:\n raise ValueError(\n 'num_pitches %d is not compatible with that computed from '\n 'min_pitch %d and max_pitch %d, which is %d.' % (\n legacy_num_pitches, min_pitch, max_pitch,\n computed_num_pitches))\n\n @property\n def num_pitches(self):\n return self.max_pitch + 1 - self.min_pitch\n\n @property\n def input_depth(self):\n return self.num_instruments * 2\n\n @property\n def output_depth(self):\n return self.num_instruments if self.separate_instruments else 1\n\n @property\n def log_subdir_str(self):\n return '%s_%s' % (self.get_conv_arch().name, self.__str__())\n\n @property\n def name(self):\n return self.conv_arch.name\n\n @property\n def pianoroll_shape(self):\n if self.separate_instruments:\n return [self.crop_piece_len, self.num_pitches, self.num_instruments]\n else:\n return [self.crop_piece_len, self.num_pitches, 1]\n\n @property\n def use_softmax_loss(self):\n if not self.separate_instruments and (self.num_instruments > 1 or\n self.num_instruments == 0):\n return False\n else:\n return True\n\n def __str__(self):\n \"\"\"Get all hyperparameters as a string.\"\"\"\n # include allowed keys only\n shorthand = dict(\n batch_size='bs',\n learning_rate='lr',\n optimize_mask_only='mask_only',\n corrupt_ratio='corrupt',\n crop_piece_len='len',\n use_softmax_loss='soft',\n num_instruments='num_i',\n num_pitches='n_pch',\n quantization_level='quant',\n use_residual='res',\n use_sep_conv='sconv',\n sep_conv_depth_multiplier='depth_mul',\n num_initial_regular_conv_layers='nreg_conv',\n separate_instruments='sep',\n rescale_loss='rescale',\n maskout_method='mm')\n sorted_keys = sorted(shorthand.keys())\n line = ','.join(\n '%s=%s' % (shorthand[key], getattr(self, key)) for key in sorted_keys)\n return line\n\n def get_conv_arch(self):\n \"\"\"Returns the model architecture.\"\"\"\n return Architecture.make(\n self.architecture,\n self.input_depth,\n self.num_layers,\n self.num_filters,\n self.num_pitches,\n self.output_depth,\n crop_piece_len=self.crop_piece_len,\n num_dilation_blocks=self.num_dilation_blocks,\n dilate_time_only=self.dilate_time_only,\n repeat_last_dilation_level=self.repeat_last_dilation_level,\n num_pointwise_splits=self.num_pointwise_splits,\n interleave_split_every_n_layers=self.interleave_split_every_n_layers)\n\n def dump(self, file_object):\n yaml.dump(self.__dict__, file_object)\n\n @staticmethod\n def load(file_object):\n params_dict = yaml.safe_load(file_object)\n hparams = Hyperparameters()\n hparams.update(params_dict)\n return hparams\n\n\nclass Architecture(lib_util.Factory):\n \"\"\"Base class for nets.\"\"\"\n\n def __init__(self):\n pass\n\n\nclass Straight(Architecture):\n \"\"\"A convolutional net where each layer has the same number of filters.\"\"\"\n key = 'straight'\n\n def __init__(self, input_depth, num_layers, num_filters, num_pitches, # pylint:disable=unused-argument\n output_depth, **kwargs):\n super().__init__()\n tf.logging.info('model_type=%s, input_depth=%d, output_depth=%d',\n self.key, input_depth, output_depth)\n assert num_layers >= 4\n if ('num_pointwise_splits' in kwargs and\n kwargs['num_pointwise_splits'] > 1):\n raise ValueError(\n 'Splitting pointwise for non-dilated architectures not yet supported.'\n 'Set num_pointwise_splits to 1.')\n\n self.layers = []\n\n def _add(**kwargs):\n self.layers.append(kwargs)\n\n _add(filters=[3, 3, input_depth, num_filters])\n for _ in range(num_layers - 3):\n _add(filters=[3, 3, num_filters, num_filters])\n _add(filters=[2, 2, num_filters, num_filters])\n _add(\n filters=[2, 2, num_filters, output_depth], activation=lib_util.identity)\n\n tf.logging.info('num_layers=%d, num_filters=%d',\n len(self.layers), num_filters)\n self.name = '%s-%d-%d' % (self.key, len(self.layers), num_filters)\n\n def __str__(self):\n return self.name\n\n\nclass Dilated(Architecture):\n \"\"\"A dilated convnet where each layer has the same number of filters.\"\"\"\n key = 'dilated'\n\n def __init__(self, input_depth, num_layers, num_filters, num_pitches, # pylint:disable=unused-argument\n output_depth, **kwargs):\n super().__init__()\n tf.logging.info('model_type=%s, input_depth=%d, output_depth=%d',\n self.key, input_depth, output_depth)\n kws = \"\"\"num_dilation_blocks dilate_time_only crop_piece_len\n repeat_last_dilation_level num_pointwise_splits\n interleave_split_every_n_layers\"\"\"\n for kw in kws.split():\n assert kw in kwargs\n num_dilation_blocks = kwargs['num_dilation_blocks']\n assert num_dilation_blocks >= 1\n dilate_time_only = kwargs['dilate_time_only']\n num_pointwise_splits = kwargs['num_pointwise_splits']\n interleave_split_every_n_layers = kwargs['interleave_split_every_n_layers']\n\n def compute_max_dilation_level(length):\n return int(np.ceil(np.log2(length))) - 1\n\n max_time_dilation_level = (\n compute_max_dilation_level(kwargs['crop_piece_len']))\n max_pitch_dilation_level = (\n compute_max_dilation_level(num_pitches))\n max_dilation_level = max(max_time_dilation_level, max_pitch_dilation_level)\n if kwargs['repeat_last_dilation_level']:\n tf.logging.info('Increasing max dilation level from %s to %s',\n max_dilation_level, max_dilation_level + 1)\n max_dilation_level += 1\n\n def determine_dilation_rate(level, max_level):\n dilation_level = min(level, max_level)\n return 2 ** dilation_level\n\n self.layers = []\n\n def _add(**kwargs):\n self.layers.append(kwargs)\n\n _add(filters=[3, 3, input_depth, num_filters])\n for _ in range(num_dilation_blocks):\n for level in range(max_dilation_level + 1):\n time_dilation_rate = determine_dilation_rate(\n level, max_time_dilation_level)\n pitch_dilation_rate = determine_dilation_rate(\n level, max_pitch_dilation_level)\n if dilate_time_only:\n layer_dilation_rates = [time_dilation_rate, 1]\n else:\n layer_dilation_rates = [time_dilation_rate, pitch_dilation_rate]\n tf.logging.info('layer_dilation_rates %r', layer_dilation_rates)\n if len(self.layers) % (interleave_split_every_n_layers + 1) == 0:\n current_num_pointwise_splits = num_pointwise_splits\n else:\n current_num_pointwise_splits = 1\n tf.logging.info('num_split %d', current_num_pointwise_splits)\n _add(filters=[3, 3, num_filters, num_filters],\n dilation_rate=layer_dilation_rates,\n num_pointwise_splits=current_num_pointwise_splits)\n _add(filters=[2, 2, num_filters, num_filters])\n _add(\n filters=[2, 2, num_filters, output_depth], activation=lib_util.identity)\n\n tf.logging.info('num_layers=%d, num_filters=%d',\n len(self.layers), num_filters)\n self.name = '%s-%d-%d' % (self.key, len(self.layers), num_filters)\n\n def __str__(self):\n return self.name\n" ]
[ [ "numpy.log2", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.gfile.Open" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tobias-liaudat/deep_mccd
[ "55254a89df4b38e6130f79298b0ee1491753d0fb" ]
[ "scripts/OLD/training/learnlets_512.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom denoising.learnlets.learnlet_model import Learnlet\nfrom tensorflow.keras.optimizers import Adam\nfrom denoising.evaluate import keras_psnr, keras_ssim, center_keras_psnr\nfrom denoising.preprocessing import eigenPSF_data_gen\nfrom astropy.io import fits\n\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\nconfig = ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\n\nprint(tf.test.gpu_device_name()) \n\nimg = fits.open('/n05data/ayed/outputs/eigenpsfs/dataset_eigenpsfs.fits')\nimg = img[1].data['VIGNETS_NOISELESS']\nimg = np.reshape(img, (len(img), 51, 51, 1))\n\nfor i in range (len(img)):\n if np.sum(img[i, :, :, :]) < 0:\n img[i, :, :, :] = -img[i, :, :, :]\n \nnp.random.shuffle(img)\n\nsize_train = np.floor(len(img)*0.95)\ntraining, test = img[:int(size_train),:,:], img[int(size_train):,:,:]\n\nbatch_size = 64\n\ntraining = eigenPSF_data_gen(path=training,\n snr_range=[0,100],\n img_shape=(51, 51),\n batch_size=batch_size,\n n_shuffle=20)\n\ntest = eigenPSF_data_gen(path=test,\n snr_range=[0,100],\n img_shape=(51, 51),\n batch_size=1)\n\nrun_params = {\n 'denoising_activation': 'dynamic_soft_thresholding',\n 'learnlet_analysis_kwargs':{\n 'n_tiling': 512, \n 'mixing_details': False, \n 'skip_connection': True,\n },\n 'learnlet_synthesis_kwargs': {\n 'res': True,\n },\n 'threshold_kwargs':{\n 'noise_std_norm': True,\n },\n# 'wav_type': 'bior',\n 'n_scales': 5,\n 'n_reweights_learn': 1,\n 'clip': False,\n}\n\ncheckpoint_path = \"trained_models/saved_learnlets/cp_512.h5\"\n\nmodel=Learnlet(**run_params)\nn_epochs = 1000\nsteps = int(size_train/batch_size)\n\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_path, \n verbose=1, \n save_weights_only=True,\n save_freq=steps*50)\n\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4),\n loss='mse',\n metrics=[keras_psnr, center_keras_psnr],\n)\n\nhistory = model.fit(\n training,\n validation_data=test,\n steps_per_epoch=steps,\n epochs=n_epochs,\n validation_steps=1,\n callbacks=[cp_callback],\n shuffle=False,\n)\n\n\nplt.plot(history.history['loss'], label='Loss (training data)')\nplt.plot(history.history['val_loss'], label='Loss (validation data)')\nplt.title('Loss of the Learnlets 512 on the EigenPSF Dataset')\nplt.ylabel('Loss value')\nplt.yscale('log')\nplt.xlabel('No. epoch')\nplt.legend(loc=\"upper left\")\nplt.savefig(\"trained_models/saved_learnlets/Loss_512.png\")\n\nwith open('trained_models/saved_learnlets/modelsummary_512.txt', 'w') as f:\n model.summary(print_fn=lambda x: f.write(x + '\\n'))" ]
[ [ "tensorflow.keras.callbacks.ModelCheckpoint", "matplotlib.pyplot.legend", "tensorflow.compat.v1.ConfigProto", "matplotlib.pyplot.title", "tensorflow.test.gpu_device_name", "matplotlib.pyplot.yscale", "numpy.random.shuffle", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "tensorflow.keras.optimizers.Adam", "tensorflow.compat.v1.InteractiveSession", "matplotlib.pyplot.xlabel", "numpy.sum", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hodlar/curso_python
[ "d19d4bdc8011a5ef47b787d448d5feb15a190f2e" ]
[ "proyectos/clase_3/scripts/rotacion.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as axes3d\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\n\nu = np.linspace(-1, 2, 60)\nv = np.linspace(0, 2*np.pi, 60)\nU, V = np.meshgrid(u, v)\n\nX = U\nY1 = (U**2 + 1)*np.cos(V)\nZ1 = (U**2 + 1)*np.sin(V)\n\nY2 = (U + 3)*np.cos(V)\nZ2 = (U + 3)*np.sin(V)\n\nax.plot_surface(X, Y1, Z1, alpha=0.3, color='red', rstride=6, cstride=12)\nax.plot_surface(X, Y2, Z2, alpha=0.3, color='blue', rstride=6, cstride=12)\nplt.show()" ]
[ [ "numpy.linspace", "numpy.cos", "numpy.sin", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ankurgarg101/neural-motifs
[ "967ce0d3ae84e7777997aff3091fda57c7b15a59" ]
[ "lib/fpn/nms/build.py" ]
[ "import os\nimport torch\nfrom torch.utils.ffi import create_extension\n# Might have to export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}\n\nsources = []\nheaders = []\ndefines = []\nwith_cuda = False\n\nif torch.cuda.is_available():\n print('Including CUDA code.')\n sources += ['src/nms_cuda.c']\n headers += ['src/nms_cuda.h']\n defines += [('WITH_CUDA', None)]\n with_cuda = True\n\nextra_compile_args = ['-I/opt/cuda-9.0/include/']\n\nthis_file = os.path.dirname(os.path.realpath(__file__))\nprint(this_file)\nextra_objects = ['src/cuda/nms.cu.o']\nextra_objects = [os.path.join(this_file, fname) for fname in extra_objects]\n\nffi = create_extension(\n '_ext.nms',\n headers=headers,\n sources=sources,\n define_macros=defines,\n relative_to=__file__,\n with_cuda=with_cuda,\n extra_objects=extra_objects,\n extra_compile_args=extra_compile_args\n)\n\nif __name__ == '__main__':\n ffi.build()\n\n" ]
[ [ "torch.utils.ffi.create_extension", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
redfrexx/geoplot
[ "8231baab0e286f1dec870dd5e8c6c8218e5b5da7" ]
[ "examples/plot_melbourne_schools.py" ]
[ "\"\"\"\nVoronoi of Melbourne primary schools\n====================================\n\nThis example shows a ``pointplot`` combined with a ``voronoi`` mapping primary schools in\nMelbourne. Schools in outlying, less densely populated areas serve larger zones than those in\ncentral Melbourne.\n\nThis example inspired by the `Melbourne Schools Zones Webmap <http://melbourneschoolzones.com/>`_.\n\"\"\"\n\nimport geopandas as gpd\nimport geoplot as gplt\nimport geoplot.crs as gcrs\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nmelbourne = gpd.read_file(gplt.datasets.get_path('melbourne'))\nmelbourne_primary_schools = gpd.read_file(gplt.datasets.get_path('melbourne_schools'))\\\n .query('School_Type == \"Primary\"')\n\n\nax = gplt.voronoi(\n melbourne_primary_schools, clip=melbourne, linewidth=0.5, edgecolor='white',\n projection=gcrs.Mercator()\n)\ngplt.polyplot(melbourne, edgecolor='None', facecolor='lightgray', ax=ax)\ngplt.pointplot(melbourne_primary_schools, color='black', ax=ax, s=1, extent=melbourne.total_bounds)\nplt.title('Primary Schools in Greater Melbourne, 2018')\nplt.savefig(\"melbourne-schools.png\", bbox_inches='tight', pad_inches=0)\n" ]
[ [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.title" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
freedombenLiu/autokeras
[ "3a181c8d229d3f45d6457cd329d2336b07b2330b" ]
[ "autokeras/pretrained/face_detector.py" ]
[ "# This is DFace's implementation of MTCNN modified for AutoKeras\n# Link to DFace: https://github.com/kuaikuaikim/DFace\nimport os\n\nimport cv2\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom torch.autograd.variable import Variable\n\nfrom autokeras.constant import Constant\nfrom autokeras.pretrained.base import Pretrained\nfrom autokeras.utils import get_device, download_file_from_google_drive, temp_path_generator, ensure_dir\n\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight.data)\n nn.init.constant_(m.bias, 0.1)\n\n\nclass PNet(nn.Module):\n\n def __init__(self):\n super(PNet, self).__init__()\n\n self.pre_layer = nn.Sequential(\n nn.Conv2d(3, 10, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(10, 16, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.Conv2d(16, 32, kernel_size=3, stride=1),\n nn.PReLU()\n )\n self.conv4_1 = nn.Conv2d(32, 1, kernel_size=1, stride=1)\n self.conv4_2 = nn.Conv2d(32, 4, kernel_size=1, stride=1)\n self.conv4_3 = nn.Conv2d(32, 10, kernel_size=1, stride=1)\n\n self.apply(weights_init)\n\n def forward(self, x):\n x = self.pre_layer(x)\n label = torch.sigmoid(self.conv4_1(x))\n offset = self.conv4_2(x)\n return label, offset\n\n\nclass RNet(nn.Module):\n\n def __init__(self):\n super(RNet, self).__init__()\n\n self.pre_layer = nn.Sequential(\n nn.Conv2d(3, 28, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(28, 48, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(48, 64, kernel_size=2, stride=1),\n nn.PReLU()\n\n )\n self.conv4 = nn.Linear(64 * 2 * 2, 128)\n self.prelu4 = nn.PReLU()\n self.conv5_1 = nn.Linear(128, 1)\n self.conv5_2 = nn.Linear(128, 4)\n self.conv5_3 = nn.Linear(128, 10)\n self.apply(weights_init)\n\n def forward(self, x):\n x = self.pre_layer(x)\n x = x.view(x.size(0), -1)\n x = self.conv4(x)\n x = self.prelu4(x)\n det = torch.sigmoid(self.conv5_1(x))\n box = self.conv5_2(x)\n return det, box\n\n\nclass ONet(nn.Module):\n\n def __init__(self):\n super(ONet, self).__init__()\n\n self.pre_layer = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(32, 64, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 64, kernel_size=3, stride=1),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 128, kernel_size=2, stride=1),\n nn.PReLU()\n )\n self.conv5 = nn.Linear(128 * 2 * 2, 256)\n self.prelu5 = nn.PReLU()\n self.conv6_1 = nn.Linear(256, 1)\n self.conv6_2 = nn.Linear(256, 4)\n self.conv6_3 = nn.Linear(256, 10)\n self.apply(weights_init)\n\n def forward(self, x):\n x = self.pre_layer(x)\n x = x.view(x.size(0), -1)\n x = self.conv5(x)\n x = self.prelu5(x)\n det = torch.sigmoid(self.conv6_1(x))\n box = self.conv6_2(x)\n landmark = self.conv6_3(x)\n return det, box, landmark\n\n\ndef get_square_bbox(bbox):\n square_bbox = bbox.copy()\n\n h = bbox[:, 3] - bbox[:, 1] + 1\n w = bbox[:, 2] - bbox[:, 0] + 1\n l = np.maximum(h, w)\n square_bbox[:, 0] = bbox[:, 0] + w * 0.5 - l * 0.5\n square_bbox[:, 1] = bbox[:, 1] + h * 0.5 - l * 0.5\n\n square_bbox[:, 2] = square_bbox[:, 0] + l - 1\n square_bbox[:, 3] = square_bbox[:, 1] + l - 1\n return square_bbox\n\n\ndef generate_bounding_box(map, reg, scale, threshold):\n stride = 2\n cellsize = 12\n\n t_index = np.where(map > threshold)\n\n if t_index[0].size == 0:\n return np.array([])\n\n dx1, dy1, dx2, dy2 = [reg[0, t_index[0], t_index[1], i] for i in range(4)]\n reg = np.array([dx1, dy1, dx2, dy2])\n\n score = map[t_index[0], t_index[1], 0]\n boundingbox = np.vstack([np.round((stride * t_index[1]) / scale),\n np.round((stride * t_index[0]) / scale),\n np.round((stride * t_index[1] + cellsize) / scale),\n np.round((stride * t_index[0] + cellsize) / scale),\n score,\n reg\n ])\n\n return boundingbox.T\n\n\ndef resize_image(img, scale):\n height, width, channels = img.shape\n new_height = int(height * scale)\n new_width = int(width * scale)\n new_dim = (new_width, new_height)\n img_resized = cv2.resize(img, new_dim, interpolation=cv2.INTER_LINEAR)\n return img_resized\n\n\ndef pad(bboxes, w, h):\n tmpw = (bboxes[:, 2] - bboxes[:, 0] + 1).astype(np.int32)\n tmph = (bboxes[:, 3] - bboxes[:, 1] + 1).astype(np.int32)\n numbox = bboxes.shape[0]\n\n dx = np.zeros((numbox,))\n dy = np.zeros((numbox,))\n edx, edy = tmpw.copy() - 1, tmph.copy() - 1\n\n x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]\n\n tmp_index = np.where(ex > w - 1)\n edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]\n ex[tmp_index] = w - 1\n\n tmp_index = np.where(ey > h - 1)\n edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]\n ey[tmp_index] = h - 1\n\n tmp_index = np.where(x < 0)\n dx[tmp_index] = 0 - x[tmp_index]\n x[tmp_index] = 0\n\n tmp_index = np.where(y < 0)\n dy[tmp_index] = 0 - y[tmp_index]\n y[tmp_index] = 0\n\n return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]\n return_list = [item.astype(np.int32) for item in return_list]\n\n return return_list\n\n\ndef nms(dets, thresh, mode=\"Union\"):\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n if mode == \"Union\":\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n elif mode == \"Minimum\":\n ovr = inter / np.minimum(areas[i], areas[order[1:]])\n\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n\n return keep\n\n\ndef convert_image_to_tensor(image):\n transform = transforms.ToTensor()\n return transform(image)\n\n\ndef convert_chw_tensor_to_hwc_numpy(tensor):\n if isinstance(tensor, Variable):\n return np.transpose(tensor.data.numpy(), (0, 2, 3, 1))\n elif isinstance(tensor, torch.FloatTensor):\n return np.transpose(tensor.numpy(), (0, 2, 3, 1))\n else:\n raise Exception(\"covert b*c*h*w tensor to b*h*w*c numpy error.This tensor must have 4 dimension.\")\n\n\ndef vis_face(im_array, dets, output_file_path, landmarks=None):\n fig, ax = plt.subplots(1)\n ax.imshow(im_array)\n\n for i in range(dets.shape[0]):\n bbox = dets[i, :4]\n\n rect = plt.Rectangle((bbox[0], bbox[1]),\n bbox[2] - bbox[0],\n bbox[3] - bbox[1], fill=False,\n edgecolor='yellow', linewidth=0.9)\n ax.add_patch(rect)\n\n if landmarks is not None:\n for i in range(landmarks.shape[0]):\n landmarks_one = landmarks[i, :]\n landmarks_one = landmarks_one.reshape((5, 2))\n for j in range(5):\n cir1 = patches.Circle(xy=(landmarks_one[j, 0], landmarks_one[j, 1]), radius=2, alpha=0.4, color=\"red\")\n ax.add_patch(cir1)\n plt.axis('off')\n fig.savefig(output_file_path, bbox_inches='tight', pad_inches=0)\n\n\nclass FaceDetector(Pretrained):\n \"\"\"A class to predict faces using the MTCNN pre-trained model.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n pnet, rnet, onet = self.local_paths[0], self.local_paths[1], self.local_paths[2]\n\n self.pnet_detector = PNet()\n if torch.cuda.is_available():\n self.pnet_detector.load_state_dict(torch.load(pnet))\n else:\n self.pnet_detector.load_state_dict(torch.load(pnet, map_location=lambda storage, loc: storage))\n self.pnet_detector = self.pnet_detector.to(self.device)\n self.pnet_detector.eval()\n\n self.rnet_detector = RNet()\n if torch.cuda.is_available():\n self.rnet_detector.load_state_dict(torch.load(rnet))\n else:\n self.rnet_detector.load_state_dict(torch.load(rnet, map_location=lambda storage, loc: storage))\n self.rnet_detector = self.rnet_detector.to(self.device)\n self.rnet_detector.eval()\n\n self.onet_detector = ONet()\n if torch.cuda.is_available():\n self.onet_detector.load_state_dict(torch.load(onet))\n else:\n self.onet_detector.load_state_dict(torch.load(onet, map_location=lambda storage, loc: storage))\n self.onet_detector = self.onet_detector.to(self.device)\n self.onet_detector.eval()\n\n self.min_face_size = 24\n self.stride = 2\n self.threshold = [0.6, 0.7, 0.7]\n self.scale_factor = 0.709\n\n @property\n def _google_drive_files(self):\n return Constant.FACE_DETECTOR_MODELS\n\n def predict(self, img_path, output_file_path=None):\n \"\"\"Predicts faces in an image.\n\n Args:\n img_path: A string. The path to the image on which the prediction is to be done.\n output_file_path: A string. The path where the output image is to be saved after the prediction. `None` by default.\n\n Returns:\n A tuple containing numpy arrays of bounding boxes and landmarks. Bounding boxes are of shape `(n, 5)` and\n landmarks are of shape `(n, 10)` where `n` is the number of faces predicted. Each bounding box is of length\n 5 and the corresponding rectangle is defined by the first four values. Each bounding box has five landmarks\n represented by 10 coordinates.\n \"\"\"\n if not os.path.exists(img_path):\n raise ValueError('Image does not exist')\n img = cv2.imread(img_path)\n img_bg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n bounding_boxes, landmarks = self.detect_face(img)\n if output_file_path is not None:\n vis_face(img_bg, bounding_boxes, output_file_path, landmarks)\n return bounding_boxes, landmarks\n\n def detect_pnet(self, im):\n h, w, c = im.shape\n net_size = 12\n\n current_scale = float(net_size) / self.min_face_size\n im_resized = resize_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n\n all_boxes = list()\n while min(current_height, current_width) > net_size:\n feed_imgs = []\n image_tensor = convert_image_to_tensor(im_resized)\n feed_imgs.append(image_tensor)\n feed_imgs = torch.stack(feed_imgs)\n feed_imgs = Variable(feed_imgs)\n\n if torch.cuda.is_available():\n feed_imgs = feed_imgs.cuda()\n\n cls_map, reg = self.pnet_detector(feed_imgs)\n\n cls_map_np = convert_chw_tensor_to_hwc_numpy(cls_map.cpu())\n reg_np = convert_chw_tensor_to_hwc_numpy(reg.cpu())\n\n boxes = generate_bounding_box(cls_map_np[0, :, :], reg_np, current_scale, self.threshold[0])\n\n current_scale *= self.scale_factor\n im_resized = resize_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n\n if boxes.size == 0:\n continue\n keep = nms(boxes[:, :5], 0.5, 'Union')\n boxes = boxes[keep]\n all_boxes.append(boxes)\n\n if len(all_boxes) == 0:\n return None, None\n\n all_boxes = np.vstack(all_boxes)\n\n keep = nms(all_boxes[:, 0:5], 0.7, 'Union')\n all_boxes = all_boxes[keep]\n\n bw = all_boxes[:, 2] - all_boxes[:, 0] + 1\n bh = all_boxes[:, 3] - all_boxes[:, 1] + 1\n\n boxes = np.vstack([all_boxes[:, 0],\n all_boxes[:, 1],\n all_boxes[:, 2],\n all_boxes[:, 3],\n all_boxes[:, 4]\n ])\n\n boxes = boxes.T\n\n align_topx = all_boxes[:, 0] + all_boxes[:, 5] * bw\n align_topy = all_boxes[:, 1] + all_boxes[:, 6] * bh\n align_bottomx = all_boxes[:, 2] + all_boxes[:, 7] * bw\n align_bottomy = all_boxes[:, 3] + all_boxes[:, 8] * bh\n\n boxes_align = np.vstack([align_topx,\n align_topy,\n align_bottomx,\n align_bottomy,\n all_boxes[:, 4]\n ])\n boxes_align = boxes_align.T\n\n return boxes, boxes_align\n\n def detect_rnet(self, im, dets):\n h, w, c = im.shape\n\n if dets is None:\n return None, None\n\n dets = get_square_bbox(dets)\n dets[:, 0:4] = np.round(dets[:, 0:4])\n\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = pad(dets, w, h)\n num_boxes = dets.shape[0]\n\n cropped_ims_tensors = []\n for i in range(num_boxes):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]\n crop_im = cv2.resize(tmp, (24, 24))\n crop_im_tensor = convert_image_to_tensor(crop_im)\n cropped_ims_tensors.append(crop_im_tensor)\n feed_imgs = Variable(torch.stack(cropped_ims_tensors))\n\n if torch.cuda.is_available():\n feed_imgs = feed_imgs.to(self.device)\n\n cls_map, reg = self.rnet_detector(feed_imgs)\n\n cls_map = cls_map.cpu().data.numpy()\n reg = reg.cpu().data.numpy()\n\n keep_inds = np.where(cls_map > self.threshold[1])[0]\n\n if len(keep_inds) > 0:\n boxes = dets[keep_inds]\n cls = cls_map[keep_inds]\n reg = reg[keep_inds]\n else:\n return None, None\n\n keep = nms(boxes, 0.7)\n\n if len(keep) == 0:\n return None, None\n\n keep_cls = cls[keep]\n keep_boxes = boxes[keep]\n keep_reg = reg[keep]\n\n bw = keep_boxes[:, 2] - keep_boxes[:, 0] + 1\n bh = keep_boxes[:, 3] - keep_boxes[:, 1] + 1\n\n boxes = np.vstack([keep_boxes[:, 0],\n keep_boxes[:, 1],\n keep_boxes[:, 2],\n keep_boxes[:, 3],\n keep_cls[:, 0]\n ])\n\n align_topx = keep_boxes[:, 0] + keep_reg[:, 0] * bw\n align_topy = keep_boxes[:, 1] + keep_reg[:, 1] * bh\n align_bottomx = keep_boxes[:, 2] + keep_reg[:, 2] * bw\n align_bottomy = keep_boxes[:, 3] + keep_reg[:, 3] * bh\n\n boxes_align = np.vstack([align_topx,\n align_topy,\n align_bottomx,\n align_bottomy,\n keep_cls[:, 0]\n ])\n\n boxes = boxes.T\n boxes_align = boxes_align.T\n\n return boxes, boxes_align\n\n def detect_onet(self, im, dets):\n h, w, c = im.shape\n\n if dets is None:\n return None, None\n\n dets = get_square_bbox(dets)\n dets[:, 0:4] = np.round(dets[:, 0:4])\n\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = pad(dets, w, h)\n num_boxes = dets.shape[0]\n\n cropped_ims_tensors = []\n for i in range(num_boxes):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]\n crop_im = cv2.resize(tmp, (48, 48))\n crop_im_tensor = convert_image_to_tensor(crop_im)\n cropped_ims_tensors.append(crop_im_tensor)\n feed_imgs = Variable(torch.stack(cropped_ims_tensors))\n\n if torch.cuda.is_available():\n feed_imgs = feed_imgs.to(self.device)\n\n cls_map, reg, landmark = self.onet_detector(feed_imgs)\n\n cls_map = cls_map.cpu().data.numpy()\n reg = reg.cpu().data.numpy()\n landmark = landmark.cpu().data.numpy()\n\n keep_inds = np.where(cls_map > self.threshold[2])[0]\n\n if len(keep_inds) > 0:\n boxes = dets[keep_inds]\n cls = cls_map[keep_inds]\n reg = reg[keep_inds]\n landmark = landmark[keep_inds]\n else:\n return None, None\n\n keep = nms(boxes, 0.7, mode=\"Minimum\")\n\n if len(keep) == 0:\n return None, None\n\n keep_cls = cls[keep]\n keep_boxes = boxes[keep]\n keep_reg = reg[keep]\n keep_landmark = landmark[keep]\n\n bw = keep_boxes[:, 2] - keep_boxes[:, 0] + 1\n bh = keep_boxes[:, 3] - keep_boxes[:, 1] + 1\n\n align_topx = keep_boxes[:, 0] + keep_reg[:, 0] * bw\n align_topy = keep_boxes[:, 1] + keep_reg[:, 1] * bh\n align_bottomx = keep_boxes[:, 2] + keep_reg[:, 2] * bw\n align_bottomy = keep_boxes[:, 3] + keep_reg[:, 3] * bh\n\n align_landmark_topx = keep_boxes[:, 0]\n align_landmark_topy = keep_boxes[:, 1]\n\n boxes_align = np.vstack([align_topx,\n align_topy,\n align_bottomx,\n align_bottomy,\n keep_cls[:, 0]\n ])\n\n boxes_align = boxes_align.T\n\n landmark = np.vstack([\n align_landmark_topx + keep_landmark[:, 0] * bw,\n align_landmark_topy + keep_landmark[:, 1] * bh,\n align_landmark_topx + keep_landmark[:, 2] * bw,\n align_landmark_topy + keep_landmark[:, 3] * bh,\n align_landmark_topx + keep_landmark[:, 4] * bw,\n align_landmark_topy + keep_landmark[:, 5] * bh,\n align_landmark_topx + keep_landmark[:, 6] * bw,\n align_landmark_topy + keep_landmark[:, 7] * bh,\n align_landmark_topx + keep_landmark[:, 8] * bw,\n align_landmark_topy + keep_landmark[:, 9] * bh,\n ])\n\n landmark_align = landmark.T\n\n return boxes_align, landmark_align\n\n def detect_face(self, img):\n boxes_align = np.array([])\n landmark_align = np.array([])\n\n if self.pnet_detector:\n boxes, boxes_align = self.detect_pnet(img)\n if boxes_align is None:\n return np.array([]), np.array([])\n\n if self.rnet_detector:\n boxes, boxes_align = self.detect_rnet(img, boxes_align)\n if boxes_align is None:\n return np.array([]), np.array([])\n\n if self.onet_detector:\n boxes_align, landmark_align = self.detect_onet(img, boxes_align)\n if boxes_align is None:\n return np.array([]), np.array([])\n\n return boxes_align, landmark_align\n" ]
[ [ "numpy.minimum", "torch.load", "torch.autograd.variable.Variable", "numpy.round", "torch.cuda.is_available", "numpy.where", "matplotlib.pyplot.axis", "numpy.zeros", "torch.nn.init.constant_", "torch.nn.PReLU", "torch.nn.Conv2d", "matplotlib.patches.Circle", "torch.nn.Linear", "torch.stack", "numpy.array", "matplotlib.pyplot.Rectangle", "numpy.maximum", "matplotlib.pyplot.subplots", "torch.nn.MaxPool2d", "torch.nn.init.xavier_uniform_", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lambda-shuttle/Fisci
[ "bf95e2e8aa10c3bd22afcaa9174ef1a4d7e6f748" ]
[ "api/app.py" ]
[ "import time\nimport os\nfrom flask import Flask, request, Response, jsonify\nfrom flask_cors import CORS\nfrom connect_database import get_database_client\nimport pandas as pd\nimport numpy as np\nfrom errors import error_response, bad_request\nfrom cassandra.query import ordered_dict_factory\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\[email protected]('/time')\ndef get_current_time():\n return {'time': time.time()}\n\[email protected]('/trans/upload', methods = [\"POST\", \"GET\"])\ndef upload_transaction_csv():\n \"\"\"\n batch upload the transaction by a csv file\n \"\"\"\n\n if request.method == \"POST\":\n # parse the csv file\n f = request.files['csv']\n df = pd.read_csv(f)\n # connect the database\n session = get_database_client()\n # update the db\n for i in range(df.shape[0]):\n # Check if category is nan\n if df.category[i] != df.category[i]:\n category = \"\"\n else:\n category = df.category[i]\n try:\n session.execute(\n \"\"\"\n INSERT INTO fisci.transactions \n (transaction_id, user_id, shop_name, category, labeled, amount, date)\n VALUES (now(), %s, %s, %s, %s, %s, %s)\n \"\"\",\n (df.user_id[i], df.shop_name[i], category,\n bool(df.labeled[i]), float(df.amount[i]), df.date[i])\n )\n except Exception as err:\n error_response(500, \"Error parsing csv. \" + str(err))\n return {\"message\": \"success\"}\n else:\n return {\"message\": \"Nothing happened. Please POST the csv file\"}\n\n\[email protected]('/trans/add', methods = [\"POST\"])\ndef add_transaction():\n\n \"\"\"User send transaction details to be uploaded to the database\n Data is received in json format\"\"\"\n\n # parse the request\n data = request.get_json() or {}\n # check required fields\n required_fields = [\"user_id\", \"shop_name\", \"category\", \"amount\", \"date\"]\n for f in required_fields:\n if f not in data:\n return bad_request(\"Required field \" + f + \" is missing\")\n # add labeled field\n data[\"labeled\"] = len(data[\"category\"]) == 0 # user provided the category or not\n # connect to db\n session = get_database_client()\n # update db\n try:\n session.execute(\"\"\"\n INSERT INTO fisci.transactions (transaction_id, user_id, shop_name, category, labeled, amount, date)\n VALUES (now(), %s, %s, %s, %s, %s, %s);\n \"\"\", (data[\"user_id\"], data[\"shop_name\"], data[\"category\"], \n data[\"labeled\"], float(data[\"amount\"]), data[\"date\"]))\n except Exception as err:\n return error_response(500, \"Error in updating the database. \" + str(err)) \n \n return {\"message\": \"success\"}\n\n\[email protected]('/trans/get/<user_id>', methods = [\"GET\"])\ndef get_transaction(user_id):\n\n \"\"\"User gets all previous transactions in json\"\"\"\n\n session = get_database_client()\n session.row_factory = ordered_dict_factory\n\n #query result\n rows = session.execute_async(\"SELECT * FROM fisci.transactions WHERE user_id = %s ALLOW FILTERING;\", (user_id, ))\n data = list(rows.result().all())\n # convert the date filed\n for entry in data:\n entry[\"date\"] = str(entry[\"date\"])\n \n #jsonify\n return jsonify(data)\n\ndef fetch_by_user(user_id, session):\n \"\"\"\n fetch transactions by user\n return a padas dataframe, otherwise return a string\n \"\"\"\n try:\n result = session.execute(\n \"SELECT * FROM fisci.transactions WHERE user_id=%s ALLOW FILTERING\",\n [user_id]\n )\n except Exception as err:\n return str(err)\n # convert to dataframe\n result = list(result)\n df = pd.DataFrame({\n \"shop_name\": [ entry.shop_name for entry in result ],\n \"category\": [ entry.category for entry in result ],\n \"labeled\": [ bool(entry.labeled) for entry in result ],\n \"amount\": [ round(float(entry.amount), 2) for entry in result ],\n \"date\": [ str(entry.date) for entry in result ]\n })\n return df\n\[email protected]('/stats/category/<user_id>')\ndef stats_by_category(user_id):\n \"\"\"\n Fetch all the transactions categorized\n \"\"\"\n\n # connect the database\n session = get_database_client()\n # fetch user-related transactions\n df = fetch_by_user(user_id, session)\n if type(df) != pd.DataFrame:\n return error_response(500, \"Error fetching transactions. \" + df)\n # sum by category\n result = df.groupby(\"category\").sum()[\"amount\"]\n result_list = [ {\"category\": key, \"spending\": val} for key, val in dict(result).items() ]\n return {\"data\": result_list}\n\[email protected]('/stats/time/<user_id>')\ndef stats_by_time(user_id):\n \"\"\"\n Fetch all transactions and sum by time\n \"\"\"\n\n # connect the database\n session = get_database_client()\n # fetch user data\n df = fetch_by_user(user_id, session)\n if type(df) != pd.DataFrame:\n return error_response(500, \"Error fetching transactions. \" + df)\n # sum over time\n result = df.groupby(\"date\").sum()[\"amount\"]\n result_list = [ {\"date\": key, \"spending\": val} for key, val in dict(result).items() ]\n return {\"data\": result_list}\n\n\[email protected]('/trans/del/<uuid:transaction_id>', methods=['DELETE'])\ndef remove_transaction(transaction_id):\n\n \"\"\"Remove transaction based on transaction_id\"\"\"\n \n try:\n session = get_database_client()\n session.execute(\"DELETE FROM fisci.transactions WHERE transaction_id=%s;\", (transaction_id, ))\n\n except Exception as err:\n return error_response(500, \"Error in deleting the transaction. \" + str(err)) \n \n return {\"message\": \"success\"}\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
campustirolmotorsport/DL-LidarSimulation
[ "3d42d686d2bcbc8f8acc0e7a7f37e419bfb61c64" ]
[ "src/image/image.py" ]
[ "from typing import List, Tuple\nimport numpy as np\nimport cv2\n\n\nclass Image:\n # ToDo: Specify Type for numpy array\n def __init__(self, data: np.ndarray) -> None:\n self.raw = data\n self.shape = data.shape\n\n def save(self, path: str) -> None:\n cv2.imwrite(path, self.raw)\n\n def show(self, name: str = \"Image\"):\n cv2.imshow(name, self.raw)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def copy(self):\n return Image(self.raw.copy())\n\n @staticmethod\n def blank(size: Tuple[int, int]) -> np.ndarray:\n return np.zeros((size[0], size[1]), dtype=np.uint8) + np.uint8(255)\n" ]
[ [ "numpy.uint8", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jphacks/TK_1909
[ "45c06c248d799a017c9784bcdf36774031a18aea" ]
[ "extract_api.py" ]
[ "import pandas as pd\nfrom flask import Flask, jsonify, render_template, redirect, request, url_for,current_app\nimport datetime\nimport requests\nimport matplotlib.pyplot as plt\n\n\napp = Flask(__name__)\n\n#if __name__ in \"__main__\":\n # app.run(debug=True, threaded=True, port=3000)\[email protected](\"/jp_api/<manth_flg>\", methods=[\"GET\"])\ndef schedule_index(manth_flg):\n r_day = 7\n r_end = datetime.datetime.today()\n if manth_flg == 1:\n r_day = 30\n r_start = r_end - datetime.timedelta(days=r_day)\n r_start = r_start.strftime(\"%Y-%m-%d %H:%M\")\n r_end = r_end.strftime(\"%Y-%m-%d %H:%M\")\n df = pd.read_csv(\"test.csv\")\n df = df[(df['date'] >= r_start) & (df['date'] <= r_end)]\n big_time = df.date[df['kind'] == \"big\"]\n small_time = df.date[df['kind'] == \"small\"]\n df['date'] = pd.to_datetime(df['date'])\n df['date'] = df['date'].dt.strftime('%Y-%m-%d')\n df = df.sort_values('date')\n date_df = pd.DataFrame(pd.date_range(df['date'].iloc[0],df['date'].iloc[-1] , freq='D').date, columns=['date'])\n kind_df = pd.DataFrame(df['kind'].unique(), columns=['kind'])\n date_df['key'] = 0\n kind_df['key'] = 0\n tmp_df = date_df.merge(kind_df, on='key').drop('key', axis=1)\n cnt_df = pd.DataFrame(df.groupby(['date','kind']).count()).reset_index()\n cnt_df.rename( columns={'Unnamed: 0':'cnt'}, inplace=True )\n cnt_df['date'] = cnt_df['date'].astype(str)\n tmp_df['date'] = tmp_df['date'].astype(str)\n\n cnt_df = pd.merge(tmp_df,cnt_df, on=['kind', 'date'], how=\"left\")\n cnt_df = cnt_df.fillna(0)\n l_cnt =cnt_df[cnt_df['kind'] == \"big\"].reset_index()\n t_cnt =cnt_df[cnt_df['kind'] == \"small\"].reset_index()\n l_cnt['small'] = t_cnt['cnt']\n l_cnt.rename( columns={'cnt':'big'}, inplace=True )\n l_cnt = l_cnt.set_index('date')\n l_cnt = l_cnt[['small','big']]\n\n \n if(manth_flg==1):\n l_cnt.plot()\n plt.savefig('term_graph.png')\n \n else:\n l_cnt.plot.bar()\n plt.savefig('term_graph.png')\n \n big_time2 = pd.to_datetime(big_time)\n big_time2 = big_time2.dt.strftime('%H')\n small_time2 = pd.to_datetime(small_time)\n small_time2 = small_time2.dt.strftime('%H')\n big_time = list(big_time)\n small_time = list(small_time)\n plt.figure()\n plt.hist(big_time2,bins=24)\n plt.savefig('big_hist.png')\n plt.figure()\n plt.hist(small_time2,bins=24)\n plt.savefig('small_hist.png')\n\n data = {\n 'graph': 'term_graph.png',\n 'big':{\n 'graph': 'big_hist.png',\n 'time' : big_time\n\n },\n 'small':{\n 'graph': 'small_hist.png',\n 'time' : small_time\n\n }\n }\n\n return jsonify(data)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port=3000,threaded=True)\n" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.to_datetime", "matplotlib.pyplot.savefig", "pandas.date_range", "matplotlib.pyplot.hist", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
allenai/language_fragments
[ "99c2251fc0effcf845265cc04c964b49b80912db" ]
[ "language_fragments/tools/random_sat_nl.py" ]
[ "import os\nimport sys\nimport random\nimport logging\nimport itertools\nimport json\nimport tempfile\nimport tqdm\nimport inflect\nimport wandb\nfrom collections import defaultdict\nimport numpy as np\nfrom optparse import OptionParser,OptionGroup\nfrom z3 import Solver\nfrom language_fragments import initialize_config\nfrom language_fragments.util.lex import *\nfrom language_fragments.tools.sampler import params as sparams,set_seed\nfrom transformers import T5Tokenizer\n\ntokenizer = T5Tokenizer.from_pretrained('t5-large')\n\nutil_logger = logging.getLogger('reasoning_transformers.tools.random_sat_nl')\n\ndef translate_to_dimacs(problem,num_variables,num_clauses):\n \"\"\"Translates problem into dimacs format \n\n :param problem: raw list representation of problem \n :param num_variables: the number of unique variables \n :param num_clauses: the number of clauses in the overall formula\n \"\"\"\n ret = \"p cnf %s %s\" % (num_variables,num_clauses)\n for clause in problem:\n line = ' '.join([str(p[-1]) if p[0] == 1 else \"-%d\" % p[-1] for p in clause]+[\"0\"])\n ret += '\\n'+line\n return ret\n\n\nSOLVER = Solver()\n\nWANDB_ENTITY=\"nlsat\"\nWANDB_PROJECT=\"random-ksat\"\n\ndef fixed_clause_length_interp_sampler(\n num_examples,\n m,\n k,\n n,\n interp_param=1.0,\n no_repeats=True,\n ):\n \"\"\"Implementation of the Selman et al. `fixed clause length` SAT generator, with \n the following parameters: clause size=`k`, number of clauses=`m`, negation probability=`p`,\n number of variables=`n`\n\n :param config: the global configuration, with all of these parameters inside \n \"\"\"\n sampled_examples = []\n bool_variables = np.array([k for k in range(n)],dtype=np.int32)\n negate_prob = np.array([1,0,],dtype=np.int32)\n\n pbar = tqdm.tqdm(total=num_examples)\n pbar.set_description(\"sampling %d, m=%d, k=%d, n=%d\" % (num_examples,m,k,n))\n contain_full_variables = 0\n \n while len(sampled_examples) < num_examples:\n\n ## new problem\n new_problem = []\n predicate_assignment = {}\n variables_sampled = set() #<-- keep track of `non-trivial` cases\n \n for size in range(m):\n k_vars = []\n var_set = set()\n\n clause_size = np.random.choice([3,2],p=[interp_param,1.0-interp_param])\n\n # for variable in np.random.choice(bool_variables,clause_size,replace=not no_repeats):\n # variable += 1\n # negate = np.random.choice(negate_prob)\n\n # var_set.add((negate,variable))\n # k_vars.append((int(negate),int(variable)))\n # variables_sampled.add(int(variable))\n \n #while len(k_vars) != k: \n while len(k_vars) != clause_size:\n variable = np.random.choice(bool_variables)\n variable += 1\n negate = np.random.choice(negate_prob)\n opposite = 0 if negate == 1 else 1\n if (opposite,variable) in var_set: continue #<- ignore `trivial` cases\n if no_repeats and (negate,variable) in var_set: continue #<- ignore repeated props\n \n var_set.add((negate,variable))\n k_vars.append((int(negate),int(variable)))\n variables_sampled.add(int(variable))\n\n ## assign to predicaets\n new_problem += [k_vars]\n\n ###\n if no_repeats:\n assert len(var_set) == clause_size,\"repeat props!\"\n\n ## assign predicates\n ## add example\n alpha = m/len(variables_sampled)\n if len(variables_sampled) == n:\n contain_full_variables += 1\n\n # ## map to dimacs\n dimacs = translate_to_dimacs(new_problem,len(variables_sampled),m)\n SOLVER.from_string(dimacs)\n sout = SOLVER.check()\n stats = SOLVER.statistics()\n\n try: \n sat_decisions = stats.sat_decisions\n except:\n sat_decisions = 0\n ## record conflicts, if they exist \n try: \n sat_conflicts = stats.sat_conflicts\n except:\n sat_conflicts = 0\n try:\n sat_3ary = stats.sat_propagations_3ary\n except:\n sat_3ary = 0\n try:\n sat_nary = stats.sat_propagations_nary\n except:\n sat_nary = 0\n\n SOLVER.reset()\n\n ###\n instance = {\n \"id\" : \"%d_%d_%d_%s\" % (k,n,m,len(sampled_examples)),\n \"alpha\" : alpha,\n \"sat_decisions\" : sat_decisions,\n \"sat_conflicts\" : sat_conflicts,\n \"dimacs\" : dimacs,\n \"problem\" : new_problem,\n \"output\" : str(sout),\n \"k\" : k if interp_param > 0.0 else 2,\n #\"n\" : n,\n \"m\" : m,\n \"n\" : len(variables_sampled),\n \"sat_3ary\" : sat_3ary,\n \"sat_nary\" : sat_nary,\n \"sat_prop\" : sat_3ary+sat_nary,\n \"total_sat\" : sat_decisions+sat_3ary+sat_nary+sat_conflicts,\n \"iterpolated\" : False if (interp_param == 1.0 or interp_param == 0.0) else True\n }\n\n sampled_examples.append(instance)\n pbar.update(1)\n\n util_logger.info('Finished, total with full variables: %d / %d' % (contain_full_variables,len(sampled_examples)))\n return sampled_examples\n\n# def interpolated_sampler(\n# num_examples,\n# m,\n# k,\n# n\n# ):\n# \"\"\"2+p sampler\n\n# :param config: the global configuration, with all of these parameters inside \n# \"\"\"\n# sampled_examples = []\n# bool_variables = np.array([k for k in range(n)],dtype=np.int32)\n# negate_prob = np.array([1,0,],dtype=np.int32)\n\n# pbar = tqdm.tqdm(total=num_examples)\n# pbar.set_description(\"sampling %d, m=%d, k=%d, n=%d\" % (num_examples,m,k,n))\n \n# while len(sampled_examples) < num_examples:\n\n# ## new problem\n# new_problem = []\n# predicate_assignment = {}\n# variables_sampled = set() #<-- keep track of `non-trivial` cases\n \n# for size in range(m):\n# k_vars = []\n# var_set = set()\n\n# while len(k_vars) != k:\n# variable = np.random.choice(bool_variables)\n# variable += 1\n# negate = np.random.choice(negate_prob)\n# opposite = 0 if negate == 1 else 1\n# if (opposite,variable) in var_set: continue #<- ignore `trivial` cases\n\n# ## no repeats\n \n# var_set.add((negate,variable))\n# k_vars.append((int(negate),int(variable)))\n# variables_sampled.add(int(variable))\n\n# ## assign to predicaets\n# new_problem += [k_vars]\n\n\n# ## assign predicates\n# ## add example\n# alpha = m/len(variables_sampled)\n\n# # ## map to dimacs\n# dimacs = translate_to_dimacs(new_problem,len(variables_sampled),m)\n# SOLVER.from_string(dimacs)\n# sout = SOLVER.check()\n# stats = SOLVER.statistics()\n\n# try: \n# sat_decisions = stats.sat_decisions\n# except:\n# sat_decisions = 0\n# ## record conflicts, if they exist \n# try: \n# sat_conflicts = stats.sat_conflicts\n# except:\n# sat_conflicts = 0\n# try:\n# sat_3ary = stats.sat_propagations_3ary\n# except:\n# sat_3ary = 0\n# try:\n# sat_nary = stats.sat_propagations_nary\n# except:\n# sat_nary = 0\n\n# SOLVER.reset()\n\n# ###\n# instance = {\n# \"id\" : \"%d_%d_%d_%s\" % (k,n,m,len(sampled_examples)),\n# \"alpha\" : alpha,\n# \"sat_decisions\" : sat_decisions,\n# \"sat_conflicts\" : sat_conflicts,\n# \"dimacs\" : dimacs,\n# \"problem\" : new_problem,\n# \"output\" : str(sout),\n# \"k\" : k,\n# #\"n\" : n,\n# \"n\" : len(variables_sampled),\n# \"m\" : m,\n# \"sat_3ary\" : sat_3ary,\n# \"sat_nary\" : sat_nary,\n# \"sat_prop\" : sat_3ary+sat_nary,\n# \"total_sat\" : sat_decisions+sat_3ary+sat_nary+sat_conflicts,\n# }\n\n# sampled_examples.append(instance)\n# pbar.update(1)\n\n# return sampled_examples\n\nSAT_TEMPLATE = \"If %s and %s, then %s.\"\n\nINFLECT = inflect.engine()\n\nNAMES = [\n male_names,\n female_names,\n]\n\nPROPERTIES = emotion_adj + [INFLECT.a(a) for a in count_professions] + colors + [INFLECT.a(a) for a in count_animals]\n\n \ndef synthesize_3sat(config,problems):\n \"\"\"Synthesize 3sat problems into natural language \n\n :param config: the global configuration \n :param problems: the instances\n \"\"\"\n for example in problems:\n variable_map = {}\n already = set()\n full_expression = []\n \n for problem in example[\"problem\"]:\n v1,v2,v3 = problem\n needs_assignment = True\n \n ## sample a template\n vnames = [v1,v2,v3]\n local_expr = []\n\n ## randomly assign propositions \n while True:\n try:\n negation,new_var = vnames.pop()\n except:\n break \n\n ## already assigned \n if new_var in variable_map: continue\n\n ## assign name \n name_list = NAMES[np.random.randint(0,2)]\n rand_name = name_list[np.random.randint(0,len(name_list))]\n\n ## assign property\n rand_prop = PROPERTIES[np.random.randint(0,len(PROPERTIES))]\n rand_prop = rand_prop.replace(\"_\",\" \").lower()\n\n if (rand_name,rand_prop) in already:\n vnames.append((negation,new_var))\n continue\n already.add((rand_name,rand_prop))\n variable_map[new_var] = (rand_name,rand_prop)\n\n ## formulate expression\n new_expression = []\n for k,(negation,variable) in enumerate([v1,v2,v3]):\n if (k == 0 or k == 1):\n expr = \"%s is %s\" if negation == 0 else \"%s is not %s\" #<- reverse \n else: \n expr = \"%s is %s\" if negation == 1 else \"%s is not %s\"\n expr = expr % variable_map[variable]\n new_expression.append(expr)\n\n \n final = SAT_TEMPLATE % (new_expression[0],new_expression[1],new_expression[2])\n full_expression.append(final)\n\n ## add to instance\n full_expr = ' '.join(full_expression)\n example[\"question\"] = {}\n example[\"question\"][\"stem\"] = full_expr\n example[\"variable_map\"] = ' '.join([\"%d-%s\" % (k,'_'.join(v).replace(\" \",\"&\")) for k,v in variable_map.items()])\n #print(example[\"variable_map\"])\n del example[\"problem\"]\n\ndef synthesize_non(config,problems):\n \"\"\"Synthesize 3sat problems into natural language \n\n :param config: the global configuration \n :param problems: the instances\n \"\"\"\n for example in problems:\n variable_map = {}\n already = set()\n full_expression = []\n\n for problem in example[\"problem\"]:\n #v1,v2,v3 = problem\n needs_assignment = True\n full_expression.append(' '.join([\"not %d\" % v[-1] if v[0] == 0 else str(v[-1]) for v in problem]))\n \n full_expr = ' and '.join(full_expression)\n #print(len(tokenizer.tokenize(' and '.join(full_expression))))\n example[\"question\"] = {}\n example[\"question\"][\"stem\"] = full_expr\n example[\"variable_map\"] = None\n del example[\"problem\"]\n\ndef wandb_backup(config,problems,instances):\n \"\"\"Log a graph of the results to wandb \n\n :param problems: the list of problems characterized by alpha parameter\n \"\"\"\n ## params along with their instances \n used = [(a,[p[-1] for p in problems[a][:config.min_examples]]) for a in problems.keys() \\\n if len(problems[a]) >= config.min_examples]\n\n alpha_decisions = [[a,np.median([p[1] for p in problems[a][:config.min_examples]])] for a in problems.keys() \\\n if len(problems[a]) >= config.min_examples]\n alpha_conflicts = [[a,np.median([p[2] for p in problems[a][:config.min_examples]])] for a in problems.keys()\\\n if len(problems[a]) >= config.min_examples]\n alpha_prob = [[a,float(len([p[0] for p in problems[a][:config.min_examples] \\\n if p[0] == \"sat\"])/len(problems[a][:config.min_examples]))] \\\n for a in problems.keys() if len(problems[a]) >= config.min_examples]\n\n alpha_total = [[a,np.median([p[3] for p in problems[a][:config.min_examples]])] for a in problems.keys() \\\n if len(problems[a]) >= config.min_examples]\n\n\n ## 3 tables \n table1 = wandb.Table(data=alpha_decisions,\n columns=[\"Clause/Variable Ratio\",\"#SAT Decisions\"]\n )\n table2 = wandb.Table(data=alpha_conflicts,\n columns=[\"Clause/Variable Ratio\",\"#SAT Conflicts\"]\n )\n table3 = wandb.Table(data=alpha_prob,\n columns=[\"Clause/Variable Ratio\",\"Probability\"]\n )\n\n table4 = wandb.Table(data=alpha_total,\n columns=[\"Clause/Variable Ratio\",\"# Total Decisions\"]\n )\n\n ## load this to wandb \n run = wandb.init(\n project=config.wandb_project,\n entity=config.wandb_entity,\n name=config.sample_name\n )\n\n ### only log if fixed clause length\n if config.interpolate_param == 1.0: \n\n run.log({\"hardness_table1\" : wandb.plot.line(\n table1,\"Clause/Variable Ratio\",\"#SAT Decisions\",\n title=\"SAT Decisions\")})\n \n run.log({\"hardness_table2\" : wandb.plot.line(\n table2,\"Clause/Variable Ratio\",\"#SAT Conflicts\",\n title=\"SAT Conflicts\")})\n\n run.log({\"total_table4\" : wandb.plot.line(\n table4,\"Clause/Variable Ratio\",\"# Total Decisions\",\n title=\"SAT Total Decisions\")})\n \n run.log({\"probability_table3\" : wandb.plot.line(\n table3,\"Clause/Variable Ratio\",\"Probability\",\n title=\"SAT Probaility\")})\n\n a_avg = np.mean([len(v) for k,v in problems.items()])\n\n run.log({\n \"n\" : config.n,\n \"m\" : config.m,\n \"k\" : config.k,\n \"num_sampled\" : config.num_examples,\n \"avg_per_alpha\" : a_avg,\n \"seed\" : config.seed,\n })\n\n ### back up the data\n artifact = wandb.Artifact(\"%s_dump\" % config.sample_name.replace(\"=\",\"-\"),type='dataset')\n\n ### add to temporary directory \n with tempfile.TemporaryDirectory() as temp_dir:\n util_logger.info('Backing up to %s' % temp_dir)\n\n ## raw instances \n raw_instances = os.path.join(temp_dir,\"raw_instances.jsonl\")\n with open(raw_instances,'w') as temp_out:\n for instance in instances:\n temp_out.write(json.dumps(instance))\n temp_out.write(\"\\n\")\n\n ## the used instances \n used_instances = os.path.join(temp_dir,\"used_instances.jsonl\")\n with open(used_instances,'w') as temp_used:\n temp_used.write(json.dumps(used))\n temp_used.write(\"\\n\")\n\n #artifact.add_file(tf_instances.name)\n artifact.add_dir(temp_dir)\n run.log_artifact(artifact)\n run.finish()\n\n # with tempfile.NamedTemporaryFile() as tf_instances:\n # with tempfile.NamedTemporaryFile() as tf_used:\n # util_logger.info('Backing up data to: %s, used_instances=%s' % (tf_instances.name,tf_used.name))\n # with open(tf_instances.name,'w') as temp_out:\n # for instance in instances:\n # temp_out.write(json.dumps(instance))\n # temp_out.write(\"\\n\")\n\n # with open(tf_used.name,'w') as temp_used:\n # temp_used.write(json.dumps(used))\n # temp_used.write(\"\\n\")\n\n # artifact.add_file(tf_instances.name)\n # artifact.add_file(tf_used.name)\n # run.log_artifact(artifact)\n # run.finish()\n\n\ndef sample(config):\n \"\"\"Main entry point for running the solvers \n \n :param config: the global configuration \n \"\"\"\n util_logger.info(\n 'sampling, sampler=%s, no_repeats=%s' % (\n config.sample_type,\n str(config.no_repeats),\n ))\n \n ## if no minimum set, plot only items that are near maximum\n if config.min_examples == -1:\n config.min_examples = int(config.num_examples*0.9)\n \n num_examples = config.num_examples\n total_problems = []\n alpha_tracker = defaultdict(list)\n\n if config.sample_type == \"fixed_length_sampler\":\n \n for clause_size in str(config.k).split(\";\"):\n for num_clauses in str(config.m).split(\";\"):\n for num_variables in str(config.n).split(\";\"):\n\n ## sample the problems \n problems = fixed_clause_length_interp_sampler(\n num_examples,\n int(num_clauses),\n int(clause_size),\n int(num_variables),\n interp_param=float(config.interpolate_param),\n no_repeats=config.no_repeats,\n )\n\n for instance in problems:\n alpha = instance[\"alpha\"]\n alpha_tracker[alpha].append([\n instance[\"output\"],\n instance[\"sat_decisions\"],\n instance[\"sat_conflicts\"],\n instance[\"total_sat\"],\n instance[\"id\"],\n ])\n total_problems.append(instance)\n\n elif config.sample_type == \"naive_sampler\":\n sampled = 0\n\n while sampled < config.total_examples:\n\n num_clauses = np.random.randint(\n config.clause_min,\n config.clause_max+1\n )\n\n problems = fixed_clause_length_interp_sampler(\n 20,\n num_clauses,\n int(config.k),\n int(config.n),\n interp_param=float(config.interpolate_param),\n no_repeats=config.no_repeats\n )\n\n for instance in problems:\n alpha = instance[\"alpha\"]\n alpha_tracker[alpha].append([\n instance[\"output\"],\n instance[\"sat_decisions\"],\n instance[\"sat_conflicts\"],\n instance[\"total_sat\"],\n instance[\"id\"],\n ])\n total_problems.append(instance)\n sampled += 1\n\n else:\n raise ValueError('Unknown sampler type!')\n\n ### synthesisze\n if config.synthesize_to_nl: \n synthesize_3sat(config,total_problems)\n elif config.synthesize_to_non_nl:\n synthesize_non(config,total_problems)\n\n ### graph the results?\n if config.print_data:\n wandb_backup(config,alpha_tracker,total_problems)\n\ndef params(config):\n \"\"\"Main configuration settings for this module \n\n :param config: a global configuration instance\n :rtype: None \n \"\"\"\n from language_fragments.tools.sampler import params as sparams\n sparams(config)\n\ndef main(argv):\n \"\"\"The main execution point \n\n :param argv: the cli input \n \"\"\"\n ## set up config and get working directory set up\n config = initialize_config(argv,params)\n\n ## set seed and grab predicates\n set_seed(config)\n\n #fixed_clause_length_sampler(config)\n sample(config)\n" ]
[ [ "numpy.median", "numpy.array", "numpy.random.randint", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
FumiyukiKato/HDPView
[ "9e70ec567086375764fb4adf7ecd879947a48b1b" ]
[ "src/script/make_p_view_by_hdpview.py" ]
[ "import numpy as np\nimport time\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport pickle\nimport json\nimport argparse\n\nfrom dataset import Dataset\nfrom count_table import CountTable\nimport hdpview\n\nparser = argparse.ArgumentParser(description='Execute HDPView and save generated p-view')\n\nparser.add_argument('--dataset', type=str, help=\"used dataset [adult, small-adult, nume-adult, trafic, bitcoin, electricity, phoneme, jm, adding-adult, all] (default: adult)\", default=\"adult\")\nparser.add_argument('--epsilon', type=float, help=\"privacy budget (default: 1.0)\", default=1.0)\nparser.add_argument('--times', type=int, help=\"number of try (default: 10)\", default=10)\nparser.add_argument('--time_measure_only', action='store_true', default=False)\nargs = parser.parse_args()\n\nroot_dir = Path('__file__').resolve().parent\ngiven_data_dir = root_dir / \"data\" / \"preprocessed\" / args.dataset\np_view_hdpview_dir = root_dir / \"save\" / \"p_view\" / \"hdpview\" / args.dataset\np_view_hdpview_dir.mkdir(parents=True, exist_ok=True)\nresult_dir = root_dir / \"exp\" / \"result\" / \"time\" / \"hdpview\" / args.dataset\nresult_dir.mkdir(parents=True, exist_ok=True)\n\nratio = 0.9\nalpha=1.6\nbeta=1.2\ngamma=0.9\n\ntimes = args.times\nepsilon = args.epsilon\n\nif __name__ == '__main__':\n dataset = Dataset.load(given_data_dir / 'data.csv', given_data_dir / 'domain.json')\n initial_block = CountTable.from_dataset(dataset)\n initial_block.info()\n \n print('epsilon: ', epsilon)\n\n time_list = []\n for i in tqdm(range(times)):\n time_result = {}\n prng = np.random.RandomState(i)\n start = time.time()\n p_view, block_result_list = hdpview.run(initial_block, epsilon, ratio, prng, alpha, beta, gamma)\n if not args.time_measure_only:\n with open(p_view_hdpview_dir / f'p_view_eps_{epsilon}_{i}.pickle', 'wb') as f:\n pickle.dump((p_view, block_result_list), f)\n time_result['execution_time'] = time.time() - start\n time_list.append(time_result)\n\n with open(result_dir / f'hdpview_eps_{epsilon}.json', 'w') as f:\n json.dump({\"time\": time_list}, f)\n\n print('done')" ]
[ [ "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AbhishekRS4/fcn_seg
[ "c1719e522fb1d446d9618e16659fbe5d92abb065" ]
[ "src/fcn_utils.py" ]
[ "# @author : Abhishek R S\n\nimport os\nimport json\nimport numpy as np\nimport tensorflow as tf\n\nIMAGENET_MEAN = np.array([103.939, 116.779, 123.68]).reshape(1, 3)\n\n# read the json file and return the content\ndef read_config_file(json_file_name):\n # open and read the json file\n config = json.load(open(json_file_name))\n\n # return the content\n return config\n\n# create the model directory if not present\ndef init(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n# parse function for tensorflow dataset api\ndef parse_fn(img_name, lbl_name):\n # read\n img_string = tf.read_file(img_name)\n lbl_string = tf.read_file(lbl_name)\n\n # decode\n img = tf.image.decode_png(img_string, channels=3)\n lbl = tf.image.decode_png(lbl_string, channels=0)\n lbl = tf.squeeze(lbl)\n\n # datatype casting\n img = tf.cast(img, dtype=tf.float32)\n lbl = tf.cast(lbl, dtype=tf.int32)\n\n # preprocessing\n img_r, img_g, img_b = tf.split(value=img, axis=2, num_or_size_splits=3)\n img = tf.concat(values=[img_b, img_g, img_r], axis=2)\n img = img - IMAGENET_MEAN\n\n # CHW format\n img = tf.transpose(img, perm=[2, 0, 1])\n\n return img, lbl\n\n# return tf dataset\ndef get_tf_dataset(images_list, labels_list, num_epochs, batch_size):\n dataset = tf.data.Dataset.from_tensor_slices((images_list, labels_list))\n dataset = dataset.shuffle(1000)\n dataset = dataset.map(parse_fn, num_parallel_calls=8)\n dataset = dataset.batch(batch_size)\n dataset = dataset.repeat(num_epochs)\n dataset = dataset.prefetch(batch_size)\n\n return dataset\n" ]
[ [ "tensorflow.concat", "tensorflow.transpose", "tensorflow.read_file", "tensorflow.image.decode_png", "tensorflow.cast", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.squeeze", "tensorflow.split", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
mortonjt/deepblast
[ "9521ccd7bb5178f80b1657237d75c019c47935da" ]
[ "deepblast/dataset/dataset.py" ]
[ "import numpy as np\nimport pandas as pd\nimport math\nimport torch\nfrom torch.utils.data import Dataset\nfrom deepblast.dataset.alphabet import UniprotTokenizer\nfrom deepblast.constants import m\nfrom deepblast.dataset.utils import (\n state_f, tmstate_f,\n clip_boundaries, states2matrix, states2edges,\n path_distance_matrix, gap_mask\n)\n\n\ndef reshape(x, N, M):\n # Motherfucker ...\n if x.shape != (N, M) and x.shape != (M, N):\n raise ValueError(f'The shape of `x` {x.shape} '\n f'does not agree with ({N}, {M})')\n if tuple(x.shape) != (N, M):\n return x.t()\n else:\n return x\n\n\nclass AlignmentDataset(Dataset):\n def __init__(self, pairs, tokenizer=UniprotTokenizer()):\n self.tokenizer = tokenizer\n self.pairs = pairs\n\n def __iter__(self):\n worker_info = torch.utils.data.get_worker_info()\n start = 0\n end = len(self.pairs)\n\n if worker_info is None: # single-process data loading\n for i in range(end):\n yield self.__getitem__(i)\n else:\n worker_id = worker_info.id\n w = float(worker_info.num_workers)\n t = (end - start)\n w = float(worker_info.num_workers)\n per_worker = int(math.ceil(t / w))\n worker_id = worker_info.id\n iter_start = start + worker_id * per_worker\n iter_end = min(iter_start + per_worker, end)\n for i in range(iter_start, iter_end):\n yield self.__getitem__(i)\n\n\nclass TMAlignDataset(AlignmentDataset):\n \"\"\" Dataset for training and testing.\n\n This is appropriate for the Malisam / Malidup datasets.\n \"\"\"\n def __init__(self, path, tokenizer=UniprotTokenizer(),\n tm_threshold=0.4, max_len=1024, pad_ends=False,\n clip_ends=True, mask_gaps=True, return_names=False,\n construct_paths=False):\n \"\"\" Read in pairs of proteins.\n\n\n This assumes that columns are labeled as\n | chain1_name | chain2_name | tmscore1 | tmscore2 | rmsd |\n | chain1 | chain2 | alignment |\n\n Parameters\n ----------\n path: path\n Data path to aligned protein pairs. This includes gaps\n and require that the proteins have the same length\n tokenizer: UniprotTokenizer\n Converts residues to one-hot encodings\n tm_threshold: float\n Minimum threshold to investigate alignments\n max_len : float\n Maximum sequence length to be aligned\n pad_ends : bool\n Specifies if the ends of the sequences should be padded or not.\n clip_ends : bool\n Specifies if the ends of the alignments should be clipped or not.\n mask_gaps : bool\n Specifies if the mask for the gaps should be constructed.\n return_names : bool\n Specifies if the names of the proteins should be returned.\n construct_paths : bool\n Specifies if path distances should be calculated.\n\n Notes\n -----\n There are start/stop tokens that are incorporated into the\n alignment. The needleman-wunsch algorithm assumes this to be true.\n \"\"\"\n self.tokenizer = tokenizer\n self.tm_threshold = tm_threshold\n self.max_len = max_len\n self.pairs = pd.read_table(path, header=None)\n self.construct_paths = construct_paths\n cols = [\n 'chain1_name', 'chain2_name', 'tmscore1', 'tmscore2', 'rmsd',\n 'chain1', 'chain2', 'alignment'\n ]\n self.pairs.columns = cols\n self.pairs['tm'] = np.maximum(\n self.pairs['tmscore1'], self.pairs['tmscore2'])\n self.pairs['length'] = self.pairs.apply(\n lambda x: max(len(x['chain1']), len(x['chain2'])), axis=1)\n idx = np.logical_and(self.pairs['tm'] > self.tm_threshold,\n self.pairs['length'] < self.max_len)\n self.pairs = self.pairs.loc[idx]\n # TODO: pad_ends needs to be documented properly\n self.pad_ends = pad_ends\n self.clip_ends = clip_ends\n self.mask_gaps = mask_gaps\n self.return_names = return_names\n\n def __len__(self):\n return self.pairs.shape[0]\n\n def __getitem__(self, i):\n \"\"\" Gets alignment pair.\n\n Parameters\n ----------\n i : int\n Index of item\n\n Returns\n -------\n gene : torch.Tensor\n Encoded representation of protein of interest\n pos : torch.Tensor\n Encoded representation of protein that aligns with `gene`.\n states : torch.Tensor\n Alignment string\n alignment_matrix : torch.Tensor\n Ground truth alignment matrix\n path_matrix : torch.Tensor\n Pairwise path distances, where the smallest distance\n to the path is computed for every element in the matrix.\n \"\"\"\n gene = self.pairs.iloc[i]['chain1']\n pos = self.pairs.iloc[i]['chain2']\n st = self.pairs.iloc[i]['alignment']\n\n states = list(map(tmstate_f, st))\n if self.clip_ends:\n gene, pos, states, st = clip_boundaries(gene, pos, states, st)\n\n if self.pad_ends:\n states = [m] + states + [m]\n\n states = torch.Tensor(states).long()\n gene = self.tokenizer(str.encode(gene))\n pos = self.tokenizer(str.encode(pos))\n gene = torch.Tensor(gene).long()\n pos = torch.Tensor(pos).long()\n alignment_matrix = torch.from_numpy(\n states2matrix(states))\n path_matrix = torch.empty(*alignment_matrix.shape)\n g_mask = torch.ones(*alignment_matrix.shape)\n if self.construct_paths:\n pi = states2edges(states)\n path_matrix = torch.from_numpy(path_distance_matrix(pi))\n path_matrix = reshape(path_matrix, len(gene), len(pos))\n if self.mask_gaps:\n g_mask = torch.from_numpy(gap_mask(st)).bool()\n\n alignment_matrix = reshape(alignment_matrix, len(gene), len(pos))\n g_mask = reshape(g_mask, len(gene), len(pos))\n if not self.return_names:\n return gene, pos, states, alignment_matrix, path_matrix, g_mask\n else:\n gene_name = self.pairs.iloc[i]['chain1_name']\n pos_name = self.pairs.iloc[i]['chain2_name']\n return (gene, pos, states, alignment_matrix,\n path_matrix, g_mask, gene_name, pos_name)\n\n\nclass MaliAlignmentDataset(AlignmentDataset):\n \"\"\" Dataset for training and testing Mali datasets\n\n This is appropriate for the Malisam / Malidup datasets.\n \"\"\"\n def __init__(self, pairs, tokenizer=UniprotTokenizer()):\n \"\"\" Read in pairs of proteins\n\n Parameters\n ----------\n pairs: np.array of str\n Pairs of proteins that are aligned. This includes gaps\n and require that the proteins have the same length\n \"\"\"\n self.pairs = pairs\n self.tokenizer = tokenizer\n\n def __len__(self):\n return self.pairs.shape[0]\n\n def __getitem__(self, i):\n \"\"\" Gets alignment pair.\n\n Parameters\n ----------\n i : int\n Index of item\n\n Returns\n -------\n gene : torch.Tensor\n Encoded representation of protein of interest\n pos : torch.Tensor\n Encoded representation of protein that aligns with `gene`.\n states : torch.Tensor\n Alignment string\n alignment_matrix : torch.Tensor\n Ground truth alignment matrix\n \"\"\"\n gene = self.pairs.loc[i, 0]\n pos = self.pairs.loc[i, 1]\n assert len(gene) == len(pos)\n alnstr = list(zip(list(gene), list(pos)))\n states = torch.Tensor(list(map(state_f, alnstr)))\n gene = self.tokenizer(str.encode(gene.replace('-', '')))\n pos = self.tokenizer(str.encode(pos.replace('-', '')))\n gene = torch.Tensor(gene).long()\n pos = torch.Tensor(pos).long()\n alignment_matrix = torch.from_numpy(states2matrix(states))\n return gene, pos, states, alignment_matrix\n" ]
[ [ "numpy.maximum", "torch.empty", "torch.ones", "torch.Tensor", "torch.utils.data.get_worker_info", "pandas.read_table", "numpy.logical_and" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
liangshi7/botorch
[ "7472b843121ff8b67ee8fbe41a830c386783e97b" ]
[ "test/models/test_multitask.py" ]
[ "#! /usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nimport warnings\n\nimport torch\nfrom botorch.exceptions.warnings import OptimizationWarning\nfrom botorch.fit import fit_gpytorch_model\nfrom botorch.models.multitask import FixedNoiseMultiTaskGP, MultiTaskGP\nfrom botorch.posteriors import GPyTorchPosterior\nfrom botorch.utils.testing import BotorchTestCase\nfrom gpytorch.distributions import MultitaskMultivariateNormal, MultivariateNormal\nfrom gpytorch.kernels import IndexKernel, MaternKernel, ScaleKernel\nfrom gpytorch.likelihoods import FixedNoiseGaussianLikelihood, GaussianLikelihood\nfrom gpytorch.means import ConstantMean\nfrom gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood\nfrom gpytorch.priors import GammaPrior\n\n\ndef _get_random_mt_data(**tkwargs):\n train_x = torch.linspace(0, 0.95, 10, **tkwargs) + 0.05 * torch.rand(10, **tkwargs)\n train_y1 = torch.sin(train_x * (2 * math.pi)) + torch.randn_like(train_x) * 0.2\n train_y2 = torch.cos(train_x * (2 * math.pi)) + torch.randn_like(train_x) * 0.2\n train_i_task1 = torch.full_like(train_x, dtype=torch.long, fill_value=0)\n train_i_task2 = torch.full_like(train_x, dtype=torch.long, fill_value=1)\n full_train_x = torch.cat([train_x, train_x])\n full_train_i = torch.cat([train_i_task1, train_i_task2])\n full_train_y = torch.cat([train_y1, train_y2])\n train_X = torch.stack([full_train_x, full_train_i.type_as(full_train_x)], dim=-1)\n train_Y = full_train_y\n return train_X, train_Y\n\n\ndef _get_model(**tkwargs):\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n model = MultiTaskGP(train_X, train_Y, task_feature=1)\n return model.to(**tkwargs)\n\n\ndef _get_model_single_output(**tkwargs):\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n model = MultiTaskGP(train_X, train_Y, task_feature=1, output_tasks=[1])\n return model.to(**tkwargs)\n\n\ndef _get_fixed_noise_model(**tkwargs):\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n train_Yvar = torch.full_like(train_Y, 0.05)\n model = FixedNoiseMultiTaskGP(train_X, train_Y, train_Yvar, task_feature=1)\n return model.to(**tkwargs)\n\n\ndef _get_fixed_noise_model_single_output(**tkwargs):\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n train_Yvar = torch.full_like(train_Y, 0.05)\n model = FixedNoiseMultiTaskGP(\n train_X, train_Y, train_Yvar, task_feature=1, output_tasks=[1]\n )\n return model.to(**tkwargs)\n\n\nclass TestMultiTaskGP(BotorchTestCase):\n def test_MultiTaskGP(self):\n for double in (False, True):\n tkwargs = {\n \"device\": self.device,\n \"dtype\": torch.double if double else torch.float,\n }\n model = _get_model(**tkwargs)\n self.assertIsInstance(model, MultiTaskGP)\n self.assertIsInstance(model.likelihood, GaussianLikelihood)\n self.assertIsInstance(model.mean_module, ConstantMean)\n self.assertIsInstance(model.covar_module, ScaleKernel)\n matern_kernel = model.covar_module.base_kernel\n self.assertIsInstance(matern_kernel, MaternKernel)\n self.assertIsInstance(matern_kernel.lengthscale_prior, GammaPrior)\n self.assertIsInstance(model.task_covar_module, IndexKernel)\n self.assertEqual(model._rank, 2)\n self.assertEqual(\n model.task_covar_module.covar_factor.shape[-1], model._rank\n )\n\n # test model fitting\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=OptimizationWarning)\n mll = fit_gpytorch_model(mll, options={\"maxiter\": 1}, max_retries=1)\n\n # test posterior\n test_x = torch.rand(2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultitaskMultivariateNormal)\n self.assertEqual(posterior_f.mean.shape, torch.Size([2, 2]))\n self.assertEqual(posterior_f.variance.shape, torch.Size([2, 2]))\n\n # test posterior w/ observation noise\n posterior_o = model.posterior(test_x, observation_noise=True)\n self.assertIsInstance(posterior_o, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultitaskMultivariateNormal)\n self.assertEqual(posterior_f.mean.shape, torch.Size([2, 2]))\n self.assertEqual(posterior_f.variance.shape, torch.Size([2, 2]))\n\n # test posterior w/ single output index\n posterior_f = model.posterior(test_x, output_indices=[0])\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n self.assertEqual(posterior_f.mean.shape, torch.Size([2, 1]))\n self.assertEqual(posterior_f.variance.shape, torch.Size([2, 1]))\n\n # test posterior w/ bad output index\n with self.assertRaises(ValueError):\n model.posterior(test_x, output_indices=[2])\n\n # test posterior (batch eval)\n test_x = torch.rand(3, 2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultitaskMultivariateNormal)\n\n # test that unsupported batch shape MTGPs throw correct error\n with self.assertRaises(ValueError):\n MultiTaskGP(torch.rand(2, 2, 2), torch.rand(2, 1), 0)\n\n # test that bad feature index throws correct error\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n with self.assertRaises(ValueError):\n MultiTaskGP(train_X, train_Y, 2)\n\n # test that bad output task throws correct error\n with self.assertRaises(RuntimeError):\n MultiTaskGP(train_X, train_Y, 0, output_tasks=[2])\n\n def test_MultiTaskGP_single_output(self):\n for double in (False, True):\n tkwargs = {\n \"device\": self.device,\n \"dtype\": torch.double if double else torch.float,\n }\n model = _get_model_single_output(**tkwargs)\n self.assertIsInstance(model, MultiTaskGP)\n self.assertIsInstance(model.likelihood, GaussianLikelihood)\n self.assertIsInstance(model.mean_module, ConstantMean)\n self.assertIsInstance(model.covar_module, ScaleKernel)\n matern_kernel = model.covar_module.base_kernel\n self.assertIsInstance(matern_kernel, MaternKernel)\n self.assertIsInstance(matern_kernel.lengthscale_prior, GammaPrior)\n self.assertIsInstance(model.task_covar_module, IndexKernel)\n self.assertEqual(model._rank, 2)\n self.assertEqual(\n model.task_covar_module.covar_factor.shape[-1], model._rank\n )\n\n # test model fitting\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=OptimizationWarning)\n mll = fit_gpytorch_model(mll, options={\"maxiter\": 1}, max_retries=1)\n\n # test posterior\n test_x = torch.rand(2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n\n # test posterior (batch eval)\n test_x = torch.rand(3, 2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n\n\nclass TestFixedNoiseMultiTaskGP(BotorchTestCase):\n def test_FixedNoiseMultiTaskGP(self):\n for double in (False, True):\n tkwargs = {\n \"device\": self.device,\n \"dtype\": torch.double if double else torch.float,\n }\n model = _get_fixed_noise_model(**tkwargs)\n self.assertIsInstance(model, FixedNoiseMultiTaskGP)\n self.assertIsInstance(model.likelihood, FixedNoiseGaussianLikelihood)\n self.assertIsInstance(model.mean_module, ConstantMean)\n self.assertIsInstance(model.covar_module, ScaleKernel)\n matern_kernel = model.covar_module.base_kernel\n self.assertIsInstance(matern_kernel, MaternKernel)\n self.assertIsInstance(matern_kernel.lengthscale_prior, GammaPrior)\n self.assertIsInstance(model.task_covar_module, IndexKernel)\n self.assertEqual(model._rank, 2)\n self.assertEqual(\n model.task_covar_module.covar_factor.shape[-1], model._rank\n )\n\n # test model fitting\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=OptimizationWarning)\n mll = fit_gpytorch_model(mll, options={\"maxiter\": 1}, max_retries=1)\n\n # test posterior\n test_x = torch.rand(2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultitaskMultivariateNormal)\n self.assertEqual(posterior_f.mean.shape, torch.Size([2, 2]))\n self.assertEqual(posterior_f.variance.shape, torch.Size([2, 2]))\n\n # TODO: test posterior w/ observation noise\n\n # test posterior w/ single output index\n posterior_f = model.posterior(test_x, output_indices=[0])\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n self.assertEqual(posterior_f.mean.shape, torch.Size([2, 1]))\n self.assertEqual(posterior_f.variance.shape, torch.Size([2, 1]))\n\n # test posterior w/ bad output index\n with self.assertRaises(ValueError):\n model.posterior(test_x, output_indices=[2])\n\n # test posterior (batch eval)\n test_x = torch.rand(3, 2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultitaskMultivariateNormal)\n\n # test that unsupported batch shape MTGPs throw correct error\n with self.assertRaises(ValueError):\n FixedNoiseMultiTaskGP(\n torch.rand(2, 2, 2), torch.rand(2, 1), torch.rand(2, 1), 0\n )\n\n # test that bad feature index throws correct error\n train_X, train_Y = _get_random_mt_data(**tkwargs)\n train_Yvar = torch.full_like(train_Y, 0.05)\n with self.assertRaises(ValueError):\n FixedNoiseMultiTaskGP(train_X, train_Y, train_Yvar, 2)\n\n # test that bad output task throws correct error\n with self.assertRaises(RuntimeError):\n FixedNoiseMultiTaskGP(train_X, train_Y, train_Yvar, 0, output_tasks=[2])\n\n def test_FixedNoiseMultiTaskGP_single_output(self):\n for double in (False, True):\n tkwargs = {\n \"device\": self.device,\n \"dtype\": torch.double if double else torch.float,\n }\n model = _get_fixed_noise_model_single_output(**tkwargs)\n self.assertIsInstance(model, FixedNoiseMultiTaskGP)\n self.assertIsInstance(model.likelihood, FixedNoiseGaussianLikelihood)\n self.assertIsInstance(model.mean_module, ConstantMean)\n self.assertIsInstance(model.covar_module, ScaleKernel)\n matern_kernel = model.covar_module.base_kernel\n self.assertIsInstance(matern_kernel, MaternKernel)\n self.assertIsInstance(matern_kernel.lengthscale_prior, GammaPrior)\n self.assertIsInstance(model.task_covar_module, IndexKernel)\n self.assertEqual(model._rank, 2)\n self.assertEqual(\n model.task_covar_module.covar_factor.shape[-1], model._rank\n )\n\n # test model fitting\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=OptimizationWarning)\n mll = fit_gpytorch_model(mll, options={\"maxiter\": 1}, max_retries=1)\n\n # test posterior\n test_x = torch.rand(2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n\n # test posterior (batch eval)\n test_x = torch.rand(3, 2, 1, **tkwargs)\n posterior_f = model.posterior(test_x)\n self.assertIsInstance(posterior_f, GPyTorchPosterior)\n self.assertIsInstance(posterior_f.mvn, MultivariateNormal)\n" ]
[ [ "torch.randn_like", "torch.linspace", "torch.Size", "torch.sin", "torch.cat", "torch.rand", "torch.full_like", "torch.cos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hualongdeng/hualongdeng-COMP90051-Statistical-Machine-Learning
[ "8de7c39f35572480bbfb76b50557cb627e766795" ]
[ "ALL.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import Lasso\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\n\ndef encode(item):\n index = [0, 3, 4, 5]\n year = np.zeros((3))\n year[item[0] - 1] = 1\n band = np.zeros((3))\n band[item[3] - 1] = 1\n group = np.zeros((11))\n group[item[4] - 1] = 1\n denomination = np.zeros((3))\n denomination[item[5] - 1] = 1\n new_item = np.delete(item, index)\n newdata = np.concatenate((year,band,group,denomination,new_item),axis=0)\n return newdata\n\n\ndef encode_data(data):\n new = []\n for item in data:\n new.append(encode(item))\n return new\n\n\ndef read_data(file):\n raw_data = pd.read_csv(file)\n data_len = len(raw_data)\n data = []\n for i in range(0, data_len):\n row = np.array(raw_data.iloc[i])\n data.append(row)\n data = np.array(data)\n return data\n\n\ndef split_data(data):\n label = data[:, 22]\n data = data[:, :22]\n pre_x_train, x_test, pre_y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=0)\n x_train, x_dev, y_train, y_dev = train_test_split(pre_x_train, pre_y_train, test_size=0.25, random_state=0)\n return x_train, x_dev, x_test, y_train, y_dev, y_test\n\n\ndef get_lr_mse(train_x, dev_x, test_x, train_y, dev_y, test_y):\n _, dev_x_100, _, dev_y_100 = train_test_split(dev_x, dev_y, test_size=100, random_state=0)\n logreg = Lasso()\n logreg.fit(train_x, train_y)\n prediction = logreg.predict(test_x)\n result = mean_squared_error(test_y, prediction)\n print(result)\n return result\n\n\nclass MyClassifier(nn.Module):\n def __init__(self, hidden_layer):\n super(MyClassifier, self).__init__()\n self.fc1 = nn.Linear(22, hidden_layer)\n self.fc2 = nn.Linear(hidden_layer, 1)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.fc2(x)\n return x\n\ndef get_mse_net(train_x, dev_x, test_x, train_y, dev_y, test_y):\n train_x = torch.from_numpy(train_x).type(torch.FloatTensor)\n dev_x = torch.from_numpy(dev_x).type(torch.FloatTensor)\n test_x = torch.from_numpy(test_x).type(torch.FloatTensor)\n train_y = torch.from_numpy(train_y).type(torch.FloatTensor)\n dev_y = torch.from_numpy(dev_y).type(torch.FloatTensor)\n test_y = torch.from_numpy(test_y).type(torch.FloatTensor)\n _, dev_x_100, _, dev_y_100 = train_test_split(dev_x, dev_y, test_size=100, random_state=0)\n model = MyClassifier(20)\n loss_fn = torch.nn.MSELoss()\n learning_rate = 1e-2\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n for t in range(200):\n y_pred = model(train_x)\n loss = loss_fn(y_pred, train_y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n prediction = model(test_x)\n result = mean_squared_error(test_y, prediction.detach().numpy())\n print(result)\n return result\n\n\n# read data.\nfemaleData = np.array(encode_data(read_data(\"FEMALE.csv\")))\nmaleData = np.array(encode_data(read_data(\"MALE.csv\")))\nmixedData = np.array(encode_data(read_data(\"MIXED.csv\")))\n\n# split data\nmale_train_x, male_dev_x, male_test_x, male_train_y, male_dev_y, male_test_y = split_data(maleData)\nfemale_train_x, female_dev_x, female_test_x, female_train_y, female_dev_y, female_test_y = split_data(femaleData)\nmix_train_x, mix_dev_x, mix_test_x, mix_train_y, mix_dev_y, mix_test_y = split_data(mixedData)\n\n_, t_male_train_x, _, t_male_train_y = train_test_split(male_train_x, male_train_y, test_size=1000, random_state=0)\n_, t_female_train_x, _, t_female_train_y = train_test_split(female_train_x, female_train_y, test_size=1000, random_state=0)\n_, t_mix_train_x, _, t_mix_train_y = train_test_split(mix_train_x, mix_train_y, test_size=1000, random_state=0)\n\nmix_target_x = np.append(male_train_x, female_train_x, axis=0)\nmix_target_x = np.append(mix_target_x, t_mix_train_x, axis=0)\nmix_target_y = np.append(male_train_y, female_train_y, axis=0)\nmix_target_y = np.append(mix_target_y, t_mix_train_y, axis=0)\n\nmale_target_x = np.append(mix_train_x, female_train_x, axis=0)\nmale_target_x = np.append(male_target_x, t_male_train_x, axis=0)\nmale_target_y = np.append(mix_train_y, female_train_y, axis=0)\nmale_target_y = np.append(male_target_y, t_male_train_y, axis=0)\n\nfemale_target_x = np.append(mix_train_x, male_train_x, axis=0)\nfemale_target_x = np.append(female_target_x, t_female_train_x, axis=0)\nfemale_target_y = np.append(mix_train_y, male_train_y, axis=0)\nfemale_target_y = np.append(female_target_y, t_female_train_y, axis=0)\n\n# calculate LogisticRegression result\nreg_result = 0\nreg_result = get_lr_mse(mix_target_x, mix_dev_x, mix_test_x, mix_target_y, mix_dev_y, mix_test_y)\nreg_result = reg_result + get_lr_mse(male_target_x, male_dev_x, male_test_x, male_target_y, male_dev_y, male_test_y)\nreg_result = reg_result + get_lr_mse(female_target_x, female_dev_x, female_test_x, female_target_y, female_dev_y, female_test_y)\nprint(reg_result/3)\n\n# calculate Neural Network result\n# net_result = 0\n# net_result = get_mse_net(mix_target_x, mix_dev_x, mix_test_x, mix_target_y, mix_dev_y, mix_test_y)\n# net_result = net_result + get_mse_net(male_target_x, male_dev_x, male_test_x, male_target_y, male_dev_y, male_test_y)\n# net_result = net_result + get_mse_net(female_target_x, female_dev_x, female_test_x, female_target_y, female_dev_y, female_test_y)\n# print(net_result/3)" ]
[ [ "pandas.read_csv", "sklearn.model_selection.train_test_split", "torch.from_numpy", "sklearn.linear_model.Lasso", "numpy.concatenate", "sklearn.metrics.mean_squared_error", "numpy.append", "numpy.delete", "torch.nn.Linear", "numpy.array", "numpy.zeros", "torch.nn.MSELoss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
shaulr/tensorflow
[ "4ac9c09d5ca57a03b8daa5fb9e295947b1619854" ]
[ "tensorflow/tensorboard/plugins/projector/plugin_test.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Integration tests for the Embedding Projector.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gzip\nimport io\nimport json\nimport os\nimport numpy as np\n\nfrom werkzeug import test as werkzeug_test\nfrom werkzeug import wrappers\n\nfrom google.protobuf import text_format\nfrom tensorflow.contrib.tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.summary import event_multiplexer\nfrom tensorflow.python.training import saver as saver_lib\nfrom tensorflow.tensorboard.backend import application\nfrom tensorflow.tensorboard.plugins.projector import plugin as projector_plugin\n\n\nclass ProjectorAppTest(test.TestCase):\n\n def setUp(self):\n self.log_dir = self.get_temp_dir()\n\n def testRunsWithValidCheckpoint(self):\n self._GenerateProjectorTestData()\n self._SetupWSGIApp()\n run_json = self._GetJson('/data/plugin/projector/runs')\n self.assertEqual(run_json, ['.'])\n\n def testRunsWithNoCheckpoint(self):\n self._SetupWSGIApp()\n run_json = self._GetJson('/data/plugin/projector/runs')\n self.assertEqual(run_json, [])\n\n def testRunsWithInvalidModelCheckpointPath(self):\n checkpoint_file = os.path.join(self.log_dir, 'checkpoint')\n f = open(checkpoint_file, 'w')\n f.write('model_checkpoint_path: \"does_not_exist\"\\n')\n f.write('all_model_checkpoint_paths: \"does_not_exist\"\\n')\n f.close()\n self._SetupWSGIApp()\n\n run_json = self._GetJson('/data/plugin/projector/runs')\n self.assertEqual(run_json, [])\n\n def testInfoWithValidCheckpoint(self):\n self._GenerateProjectorTestData()\n self._SetupWSGIApp()\n\n info_json = self._GetJson('/data/plugin/projector/info?run=.')\n self.assertItemsEqual(info_json['embeddings'], [{\n 'tensorShape': [1, 2],\n 'tensorName': 'var1'\n }, {\n 'tensorShape': [10, 10],\n 'tensorName': 'var2'\n }, {\n 'tensorShape': [100, 100],\n 'tensorName': 'var3'\n }])\n\n def testTensorWithValidCheckpoint(self):\n self._GenerateProjectorTestData()\n self._SetupWSGIApp()\n\n url = '/data/plugin/projector/tensor?run=.&name=var1'\n tensor_bytes = self._Get(url).data\n tensor = np.reshape(np.fromstring(tensor_bytes, dtype='float32'), [1, 2])\n expected_tensor = np.array([[6, 6]], dtype='float32')\n self.assertTrue(np.array_equal(tensor, expected_tensor))\n\n def _SetupWSGIApp(self):\n multiplexer = event_multiplexer.EventMultiplexer(\n size_guidance=application.DEFAULT_SIZE_GUIDANCE,\n purge_orphaned_data=True)\n projector = projector_plugin.ProjectorPlugin()\n projector.get_plugin_apps({}, self.log_dir)\n plugins = {'projector': projector}\n wsgi_app = application.TensorBoardWSGIApp(\n self.log_dir, plugins, multiplexer, reload_interval=0)\n self.server = werkzeug_test.Client(wsgi_app, wrappers.BaseResponse)\n\n def _Get(self, path):\n return self.server.get(path)\n\n def _GetJson(self, path):\n response = self.server.get(path)\n data = response.data\n if response.headers.get('Content-Encoding') == 'gzip':\n data = gzip.GzipFile('', 'rb', 9, io.BytesIO(data)).read()\n return json.loads(data.decode('utf-8'))\n\n def _GenerateProjectorTestData(self):\n config_path = os.path.join(self.log_dir, 'projector_config.pbtxt')\n config = ProjectorConfig()\n embedding = config.embeddings.add()\n # Add an embedding by its canonical tensor name.\n embedding.tensor_name = 'var1:0'\n config_pbtxt = text_format.MessageToString(config)\n with gfile.GFile(config_path, 'w') as f:\n f.write(config_pbtxt)\n\n # Write a checkpoint with some dummy variables.\n with ops.Graph().as_default():\n sess = session.Session()\n checkpoint_path = os.path.join(self.log_dir, 'model')\n variable_scope.get_variable(\n 'var1', [1, 2], initializer=init_ops.constant_initializer(6.0))\n variable_scope.get_variable('var2', [10, 10])\n variable_scope.get_variable('var3', [100, 100])\n sess.run(variables.global_variables_initializer())\n saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V1)\n saver.save(sess, checkpoint_path)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.contrib.tensorboard.plugins.projector.projector_config_pb2.ProjectorConfig", "numpy.array_equal", "tensorflow.tensorboard.backend.application.TensorBoardWSGIApp", "tensorflow.python.platform.gfile.GFile", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.variable_scope.get_variable", "numpy.fromstring", "tensorflow.python.platform.test.main", "tensorflow.tensorboard.plugins.projector.plugin.ProjectorPlugin", "tensorflow.python.client.session.Session", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.ops.variables.global_variables_initializer", "numpy.array", "tensorflow.python.summary.event_multiplexer.EventMultiplexer", "tensorflow.python.training.saver.Saver" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12", "1.0" ] } ]
vishakhpk/counterfactually-augmented-data
[ "4b464f4a02cd87fdb1dcbf49b045b1d3eca55d2e" ]
[ "imdb/train_full_imdb.py" ]
[ "import random\nimport argparse\n\nimport torch\nimport numpy as np\nimport pandas as pd\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom torchtext.data import Field\nfrom keras.preprocessing.text import Tokenizer\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.metrics import (accuracy_score, classification_report,\n confusion_matrix)\n\nfrom simple_lstm import LSTM\nfrom simple_lstm import (save_metrics, load_metrics, save_checkpoint,\n load_checkpoint)\n\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--epochs', type=int, default = 5, help='Num Epochs')\nparser.add_argument('--lr', type=float, default = 0.0005, help='Learning rate')\nparser.add_argument('--batch_size', type=int, default = 64, help='Batch size')\nparser.add_argument('--vocab_size', type=int, default = 3000,\n help='Vocab size for lstm')\nparser.add_argument('--output_path', type=str, default = \"models\",\n help='Output path')\nparser.add_argument('--aug_test', type=int, default=1,\n help='Whether or not to cf-augment the test set (0 or 1)')\nargs = parser.parse_args()\n\nEPOCHS = args.epochs\nLR = args.lr\nOUT_DIR = args.output_path\nVOCAB_SIZE = args.vocab_size\nBSZ = args.batch_size\nAUG_TEST = args.aug_test\n\nrandom.seed(123)\nnp.random.seed(123)\ntorch.manual_seed(123)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nparams = f'epochs={EPOCHS},lr={LR},vocab={VOCAB_SIZE},bsz={BSZ},aug_test={AUG_TEST}'\nprint(f'params: {params}')\nmodel_name = f'imdb-pretrain'\n\n# load full dataset\npath = 'data/full_imdb_{}.csv'\ntrain_df = pd.read_csv(path.format('train'))\nX_train = train_df['text'].tolist()\ny_train = train_df['label'].tolist()\n\nval_df = pd.read_csv(path.format('val'))\nX_val = val_df['text'].tolist()\ny_val = val_df['label'].tolist()\n\n# always use the same augmented test set\nif AUG_TEST:\n test_path = 'data/aug_test.csv'\nelse:\n test_path = 'data/fact_test.csv'\ntest_df = pd.read_csv(test_path)\ny_test = test_df['label'].tolist()\n\nprint('Dataset size:')\nprint(f'{len(y_train)} train, {len(y_val)} val, {len(test_df)} test')\n\n# setup tokenizer\ntokenizer = Tokenizer(num_words=VOCAB_SIZE, oov_token=True)\ntokenizer.fit_on_texts(X_train)\n\n# tokenize, convert to sequences, and pad\n# note: using the same padding for factual/counterfactual data\ndef get_padded_sequences(text):\n sequences = tokenizer.texts_to_sequences(text)\n padding = max([len(i) for i in sequences])\n data = pad_sequences(sequences, maxlen=padding, padding='post')\n return data\n\n\ndef get_cf_padded_sequences(df):\n sequences = tokenizer.texts_to_sequences(df['text'])\n cf_sequences = tokenizer.texts_to_sequences(df['cf-text'])\n padding = max([len(i) for i in sequences] +\n [len(j) for j in cf_sequences])\n data = pad_sequences(sequences, maxlen=padding, padding='post')\n cf_data = pad_sequences(cf_sequences, maxlen=padding, padding='post')\n\n return data, cf_data\n\ntrain_sequences = get_padded_sequences(X_train)\nval_sequences = get_padded_sequences(X_val)\ntest_sequences, cf_test_sequences = get_cf_padded_sequences(test_df)\n\n\ndef get_dataloader(data, labels, batch_size):\n batches = []\n for i in range(0, len(data), batch_size):\n text_tensor = torch.tensor(data[i:i + batch_size], device=device,\n dtype=torch.long)\n length_tensor = torch.tensor([len(j) for j in data[i:i+batch_size]],\n device=device)\n labels_tensor = torch.tensor(labels[i:i + batch_size], device=device,\n dtype=torch.float)\n batches.append((text_tensor, length_tensor, labels_tensor))\n return batches\n\n\ndef get_cf_dataloader(data, cf_data, labels, batch_size):\n batches = []\n for i in range(0, len(data), batch_size):\n text_tensor = torch.tensor(\n data[i:i + batch_size], device=device, dtype=torch.long)\n length_tensor = torch.tensor(\n [len(j) for j in data[i:i+batch_size]], device=device)\n labels_tensor = torch.tensor(\n labels[i:i + batch_size], device=device, dtype=torch.float)\n\n cf_text_tensor = torch.tensor(\n cf_data[i:i + batch_size], device=device, dtype=torch.long)\n cf_length_tensor = torch.tensor(\n [len(j) for j in cf_data[i:i+batch_size]], device=device)\n\n batches.append((text_tensor, length_tensor, cf_text_tensor,\n cf_length_tensor, labels_tensor))\n return batches\n\n\ntrain_loader = get_dataloader(train_sequences, y_train, BSZ)\nval_loader = get_dataloader(val_sequences, y_val, BSZ)\ntest_loader = get_cf_dataloader(test_sequences, cf_test_sequences, y_test, BSZ)\n\n# train and test ------------------------------------------------------------- #\ndestination_folder = OUT_DIR\ncriterion = torch.nn.BCELoss()\n\ndef train(model,\n optimizer,\n criterion = criterion,\n train_loader = train_loader,\n train_batches = len(train_loader),\n valid_loader = val_loader,\n valid_batches = len(val_loader),\n num_epochs = 5,\n eval_every = len(train_loader) // 2,\n file_path = destination_folder,\n best_valid_loss = float(\"Inf\")):\n\n # initialize running values\n running_loss = 0.0\n valid_running_loss = 0.0\n global_step = 0\n train_loss_list = []\n valid_loss_list = []\n global_steps_list = []\n\n # training loop\n model.train()\n for epoch in range(num_epochs):\n for text, text_len, labels in train_loader:\n labels = labels.to(device)\n text = text.to(device)\n\n output = model(text, text_len)\n output = torch.sigmoid(output)\n loss = criterion(output, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # update running values\n running_loss += loss.item()\n global_step += 1\n\n # evaluation step\n if global_step % eval_every == 0:\n model.eval()\n with torch.no_grad():\n # validation loop\n for text, text_len, labels in valid_loader:\n labels = labels.to(device)\n text = text.to(device)\n\n output = model(text, text_len)\n output = torch.sigmoid(output)\n\n loss = criterion(output, labels)\n valid_running_loss += loss.item()\n\n # evaluation\n average_train_loss = running_loss / eval_every\n average_valid_loss = valid_running_loss / valid_batches\n train_loss_list.append(average_train_loss)\n valid_loss_list.append(average_valid_loss)\n global_steps_list.append(global_step)\n\n # resetting running values\n running_loss = 0.0\n valid_running_loss = 0.0\n model.train()\n\n # print progress\n print('Epoch [{}/{}], Step [{}/{}], Train Loss: {:.4f}, Valid Loss: {:.4f}'\n .format(epoch+1, num_epochs, global_step,\n num_epochs*train_batches, average_train_loss,\n average_valid_loss))\n\n # checkpoint\n if best_valid_loss > average_valid_loss:\n best_valid_loss = average_valid_loss\n save_checkpoint(file_path + f'/model-{model_name}.pt',\n model, optimizer, best_valid_loss)\n save_metrics(file_path + f'/metrics-{model_name}.pt',\n train_loss_list, valid_loss_list,\n global_steps_list)\n\n save_metrics(file_path + f'/metrics-{model_name}.pt', train_loss_list,\n valid_loss_list, global_steps_list)\n print('Finished Training!')\n\n# Evaluation Function\ndef evaluate(model, test_loader, version='title', threshold=0.5):\n y_true_fact = []\n\n y_pred_fact = []\n y_pred_cfact = []\n\n y_raw_fact = []\n y_raw_cfact = []\n\n model.eval()\n with torch.no_grad():\n for text, text_len, cf_text, cf_text_len, labels in test_loader:\n # labels\n labels = labels.to(device)\n y_true_fact.extend(labels.tolist())\n\n # factual predictions\n text = text.to(device)\n output = model(text, text_len)\n\n sigmoid_out = torch.sigmoid(output)\n y_raw_fact.extend(sigmoid_out.tolist())\n\n output = (sigmoid_out > threshold).int()\n y_pred_fact.extend(output.tolist())\n\n # cf predictions\n cf_text = cf_text.to(device)\n cf_output = model(cf_text, cf_text_len)\n\n cf_sigmoid_out = torch.sigmoid(cf_output)\n y_raw_cfact.extend(cf_sigmoid_out.tolist())\n\n cf_output = (cf_sigmoid_out > threshold).int()\n y_pred_cfact.extend(cf_output.tolist())\n\n\n print('Classification Report:')\n print(classification_report(y_true_fact, y_pred_fact, labels=[1, 0],\n digits=4))\n\n # CF Consistency:\n # fraction of cf pairs that receive different predictions\n # 1 indicates consistency, 0 indicates lack of consistency\n # note all pairs are asymmetric\n print(f'CF Consistency: {np.not_equal(y_pred_fact, y_pred_cfact).mean()}')\n\n # CF Gap:\n # mean absolute difference in prediction\n # larger is better\n # differences = []\n # for batch_a, batch_b in zip(y_fact_out, y_cfact_out):\n # batch_diff = (batch_a - batch_b).abs().tolist()\n # differences.extend(batch_diff)\n mean_difference = np.abs(np.subtract(y_raw_fact, y_raw_cfact)).mean()\n print(f'CF Gap: {mean_difference}')\n\n # save output\n results_df = pd.DataFrame({\n 'y_true_fact': y_true_fact,\n 'y_pred_fact': y_pred_fact,\n 'y_pred_cfact': y_pred_cfact,\n 'y_raw_fact': y_raw_fact,\n 'y_raw_cfact': y_raw_cfact,\n })\n\n results_df.to_csv(f'results/{model_name}.csv', index=False)\n\n\nmodel = LSTM(vocab_size = VOCAB_SIZE).to(device)\noptimizer = optim.Adam(model.parameters(), lr = LR)\n\ntrain(model=model, optimizer=optimizer, num_epochs = EPOCHS)\ntrain_loss_list, valid_loss_list, global_steps_list = load_metrics(\n destination_folder + f'/metrics-{model_name}.pt')\n\nbest_model = LSTM(vocab_size=VOCAB_SIZE).to(device)\noptimizer = optim.Adam(best_model.parameters(), lr=LR)\n\nload_checkpoint(destination_folder + f'/model-{model_name}.pt', best_model,\n optimizer)\nevaluate(best_model, test_loader)\n" ]
[ [ "torch.sigmoid", "pandas.read_csv", "numpy.random.seed", "torch.manual_seed", "numpy.subtract", "pandas.DataFrame", "torch.nn.BCELoss", "torch.tensor", "torch.no_grad", "torch.cuda.is_available", "numpy.not_equal", "sklearn.metrics.classification_report" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
sjeblee/chrononet
[ "df71d227f28e7ee3545ca41efe79574f2f48381f", "df71d227f28e7ee3545ca41efe79574f2f48381f" ]
[ "chrononet/models/ordering/transformer_models.py", "chrononet/evaluation/ordering_metrics.py" ]
[ "#!/usr/bin/python3\n\n#import hurry.filesize\nimport math\nimport numpy\nimport random\nimport os\nimport time\nimport torch\nimport torch.nn as nn\n#import torch.nn.functional as F\nfrom allennlp.modules.elmo import Elmo, batch_to_ids\nfrom GPUtil import showUtilization as gpu_usage\nfrom torch import optim\nfrom transformers import BertModel, BertTokenizer\n#from sklearn.utils import shuffle\n\nfrom .pytorch_models import Autoencoder, Embedder\nfrom models.loss_functions import listMLE\nfrom swarm_mod.models import MaskedSequential, Dropout2dChannelsLast\nfrom swarm_mod.swarmlayer import SwarmLayer\nfrom swarm_mod.set_transformer import InducedSetAttentionBlock, RFF\n\nnumpy.set_printoptions(threshold=numpy.inf)\ndebug = True\ntdevice = 'cpu'\nuse_cuda = torch.cuda.is_available()\n#use_cuda = False\nif use_cuda:\n tdevice = torch.device('cuda')\noptions_file = \"/h/sjeblee/research/data/elmo/weights/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\nweight_file = \"/h/sjeblee/research/data/elmo/weights/elmo_2x4096_512_2048cnn_2xhighway_weights_PubMed_only.hdf5\"\n#ae_file = '/h/sjeblee/research/data/va/chrono/ordergru_va_autoencoder_timeencoder/autoencoder.model'\n\nimport sys\nprint('__Python VERSION:', sys.version)\nprint('__pyTorch VERSION:', torch.__version__)\nprint('__CUDNN VERSION:', torch.backends.cudnn.version())\nprint('__Number CUDA Devices:', torch.cuda.device_count())\nprint('__Devices')\nprint('Active CUDA Device: GPU', torch.cuda.current_device())\nprint('Available devices ', torch.cuda.device_count())\nprint('Current cuda device ', torch.cuda.current_device())\n\n\n# Set transformer models\nclass SetOrder(nn.Module):\n def __init__(self, input_size, encoding_size, time_encoding_size, hidden_size, output_size, encoder_file, dropout_p=0.1, use_autoencoder=False, autoencoder_file=None, checkpoint_dir=None, encoder_name='elmo', set_layer='st'):\n super(SetOrder, self).__init__()\n\n self.hidden_size = hidden_size\n self.input_size = input_size\n self.encoding_size = encoding_size\n self.time_encoding_size = time_encoding_size\n self.output_size = output_size\n self.dropout = dropout_p\n self.checkpoint_dir = checkpoint_dir\n self.set_layer = set_layer\n self.ae_trained = False\n print('SetOrder checkpoint_dir:', self.checkpoint_dir)\n\n self.use_autoencoder = use_autoencoder\n #self.use_autoencoder = False\n\n if autoencoder_file is None:\n autoencoder_file = ''\n print('SetOrder ae file:', autoencoder_file, os.path.exists(autoencoder_file))\n if self.use_autoencoder is True:\n if os.path.exists(autoencoder_file):\n print('loading previous ae from autoencoder_file')\n self.autoencoder = torch.load(autoencoder_file)\n self.ae_trained = True\n else:\n #self.elmo = Elmo(options_file, weight_file, 1, dropout=0).to(tdevice)\n print('training a new ae')\n self.autoencoder = Autoencoder(input_size, encoding_size, use_double=False, autoencoder_file=autoencoder_file, encoder_name=encoder_name)\n else:\n self.embedder = Embedder(encoder_name, encoding_size)\n\n if set_layer == 'swarm':\n self.set_layer = SwarmLayer(hidden_size, hidden_size, hidden_size, n_iter=10, n_dim=1, dropout=0.0, pooling='MEAN', channel_first=True, cache=False)\n\n elif set_layer == 'st':\n n_layers = 1\n n_heads = 4\n n_ind_points = 16\n\n #layers = [nn.Linear(self.hidden_size, self.hidden_size)]\n layers = []\n for _ in range(n_layers):\n layers.append(InducedSetAttentionBlock(d=self.hidden_size, m=n_ind_points, h=n_heads, first_rff=RFF(d=self.hidden_size), second_rff=RFF(d=self.hidden_size)))\n if self.dropout>0.0:\n layers.append(Dropout2dChannelsLast(p=self.dropout))\n layers.append(nn.Linear(self.hidden_size, self.output_size))\n self.set_layer = MaskedSequential(*layers)\n\n print('time encoder file:', encoder_file)\n self.time_encoder = torch.load(encoder_file).model # TimeEncoder(self.input_size, self.time_encoding_size, self.elmo)\n self.linear = nn.Linear(hidden_size, output_size)\n self.softmax = nn.Softmax(dim=1)\n\n ''' Input is a list of lists of numpy arrays\n '''\n def forward(self, input, X2=None, is_test=False):\n # input expected as (events, words, embedding_dim)\n encodings = []\n #hn = None\n #hn_e = None\n index = 0\n #extra_size = 0\n\n # Mini-batching for memory saving\n '''\n mini_batch = 16\n i = 0\n #if not (is_test and len(input) > mini_batch):\n if len(input) < mini_batch:\n mini_batch = len(input)\n '''\n\n output = None\n out1 = None\n '''\n while i < len(input):\n end = i + mini_batch\n if end > len(input):\n end = len(input)\n input_batch = input[i:i+mini_batch]\n print('mini_batch:', i, 'to', i+mini_batch, 'input_batch:', len(input_batch), 'should be', mini_batch)\n encodings = []\n '''\n for row in input:\n # ELMo embedding for each event (sequence of words)\n context = row[0]\n #print('context:', context)\n word_flags = row[1]\n time_words = row[2]\n tflags = row[3]\n time_val = row[4]\n #time_type = row[5]\n to_concat = []\n\n # Append the target flags\n #c_flags = torch.tensor(word_flags, dtype=torch.float, device=tdevice).view(1, -1, 1)\n #print('X:', uttX.size(), 'c_flags:', c_flags.size())\n #uttX = torch.cat((uttX, c_flags), dim=2)\n\n # Event encoding (BioBERT or ELMo)\n if self.use_autoencoder:\n enc = self.autoencoder.encode([row]).squeeze()\n else:\n enc = self.embedder(row).view(self.encoding_size)\n\n to_concat.append(enc)\n if debug: print('enc:', str(enc.size()))\n\n # Time phrase encoding\n if self.time_encoding_size > 0:\n if time_words is None:\n time_emb = torch.zeros(self.time_encoding_size, dtype=torch.float, device=tdevice)\n else:\n time_X = self.time_encoder.encode(time_words)\n #time_char_ids = batch_to_ids([time_words]).to(tdevice)\n #time_embeddings = self.elmo(time_char_ids)['elmo_representations']\n #time_X = time_embeddings[0]\n #time_X = time_X.view(1, -1, self.input_size) # should be (1, #words, input_dim)\n print('time tensor:', time_X.size())\n time_emb = time_X.view(self.time_encoding_size)\n\n # Add the flags\n #print('tflags:', str(tflags), 'twords:', time_words)\n #t_flags = torch.tensor(tflags, dtype=torch.float, device=tdevice).view(1, -1, 1)\n #print('time X:', time_X.size(), 't_flags:', t_flags.size())\n #time_X = torch.cat((time_X, t_flags), dim=2)\n\n #time_encoding, hn_t = self.gru_time(time_X, hn_t) # should be (1, #words, encoding_dim)\n #time_emb = time_encoding[:, -1, :].view(self.time_encoding_size)\n\n '''\n if time_val is None:\n time_enc = torch.zeros(2, dtype=torch.float64, device=tdevice)\n else:\n time_enc = torch.tensor(time_val, dtype=torch.float64, device=tdevice)\n\n # Concatenate the time val and embedding\n time_enc = torch.cat((time_emb, time_enc), dim=0)\n '''\n to_concat.append(time_emb)\n\n # Structured features\n #flag_tensor = torch.tensor(flags, dtype=torch.float64, device=tdevice)\n\n # Concatenate the features\n event_vector = torch.cat(to_concat, dim=0)\n\n # Add other features\n if X2 is not None:\n x2_np = numpy.asarray([X2[index]]).astype('float')\n x2_vec = torch.tensor(x2_np, dtype=torch.float, device=tdevice)\n if debug: print('x2:', x2_vec.size())\n #extra_size = x2_vec.size()[0]\n enc = torch.cat((enc, x2_vec), dim=0)\n encodings.append(event_vector)\n index += 1\n\n conversation_orig = torch.stack(encodings)\n #print('conversation:', conversation.size())\n conversation = conversation_orig.view(-1, self.hidden_size, 1) # Treat whole conversation as a batch\n print('conversation resized:', conversation.size())\n\n # Set layer\n if self.set_layer == 'swarm':\n output_batch = self.set_layer(conversation)\n output_batch = output_batch.squeeze()\n print('output:', output_batch.size())\n #out1 = output_batch\n out1 = self.linear(output_batch)\n #output = output_batch\n '''\n if output is None:\n output = output_batch\n else:\n output = torch.cat((output, output_batch), dim=1)\n if out1 is None:\n out1 = out1_batch\n else:\n out1 = torch.cat((out1, out1_batch), dim=1)\n print('output size so far:', output.size())\n '''\n #out1 = self.softmax(self.linear(output))\n else:\n conversation = conversation.view(1, -1, self.hidden_size)\n print('conversation resized:', conversation.size())\n output_batch = self.set_layer(conversation, mask=None)\n output_batch = self.softmax(output_batch)\n output_batch = output_batch.squeeze()\n print('output:', output_batch.size())\n out1 = output_batch\n\n if is_test:\n encodings = []\n #del X\n del conversation\n #del embeddings\n torch.cuda.empty_cache()\n #i = i + mini_batch\n\n print('final out:', out1.size(), out1)\n if is_test:\n del encodings\n return out1, conversation_orig #conversation.detach()\n\n ''' Creates and trains a recurrent neural network model. Supports SimpleRNN, LSTM, and GRU\n X: a list of training data\n Y: a list of training labels\n WARNING: Currently you can't use the encoding layer and use_prev_labels at the same time\n '''\n def fit(self, X, Y, activation='relu', num_epochs=10, batch_size=1, loss_function='listmle', X2=None):\n start = time.time()\n\n # Parameters\n hidden_size = self.hidden_size\n encoding_size = self.encoding_size\n dropout = self.dropout\n output_dim = self.output_size\n learning_rate = 0.01\n print_every = 1\n #teacher_forcing_ratio = 0.9\n\n print(\"hidden_size:\", str(hidden_size), \"dropout:\", str(dropout), \"epochs:\", str(num_epochs))\n print(\"encoding size:\", str(encoding_size), \"(0 means utterances are already encoded and input should be 3 dims)\")\n\n if batch_size > 1:\n if type(X) is list and batch_size > 1:\n X = numpy.asarray(X)\n if type(Y) is list and batch_size > 1:\n Y = numpy.asarray(Y)\n X = X.astype('float')\n Y = Y.astype('float')\n\n num_examples = X.shape[0]\n input_dim = X.shape[-1]\n max_length = Y.shape[1]\n #output_dim = Y.shape[-1]\n print(\"X:\", str(X.shape), \"Y:\", str(Y.shape))\n #print(\"max_length: \", str(max_length))\n\n else: # Leave X and Y as lists\n num_examples = len(X)\n if encoding_size > 0:\n print(\"X 000:\", str(type(X[0][0][0])), \"Y 00:\", str(type(Y[0][0])))\n #input_dim = X[0][0][0].shape[0]\n #output_dim = Y[0][0].shape[0]\n #else:\n #input_dim = len(X[0][0])\n #output_dim = len(Y[0][0])\n print(\"X list:\", str(len(X)), \"Y list:\", str(len(Y)))\n\n if X2 is not None:\n print(\"X2 list:\", len(X2))\n\n #print(\"input_dim: \", str(input_dim))\n print(\"output_dim: \", str(output_dim))\n\n # Set up optimizer and loss function\n optimizer = optim.Adam(self.parameters(), lr=learning_rate)\n #optimizer = optim.SGD(self.parameters(), lr=learning_rate, momentum=0.9)\n if loss_function == 'cosine':\n criterion = nn.CosineEmbeddingLoss()\n elif loss_function == 'crossentropy':\n criterion = nn.CrossEntropyLoss()\n elif loss_function == 'mse':\n criterion = nn.MSELoss()\n elif loss_function == 'l1':\n criterion = nn.L1Loss()\n elif loss_function == 'listmle':\n criterion = listMLE\n else:\n print(\"WARNING: need to add loss function!\")\n\n if use_cuda:\n self = self.to(tdevice)\n\n # Train the autoencoder\n if self.use_autoencoder and not self.ae_trained:\n self.autoencoder.fit(X)\n\n start_epoch = 0\n\n # Check for model checkpoint\n checkpoint_file = os.path.join(self.checkpoint_dir, 'checkpoint_setorder.pth')\n if os.path.exists(checkpoint_file):\n check = torch.load(checkpoint_file)\n self.load_state_dict(check['state_dict'])\n optimizer.load_state_dict(check['optimizer'])\n loss = check['loss']\n start_epoch = check['epoch'] + 1\n print('loading from checkpoint, restarting at epoch', start_epoch)\n\n # Train the model\n for epoch in range(start_epoch, num_epochs):\n print(\"epoch\", str(epoch))\n i = 0\n while (i+batch_size) < num_examples:\n if i % print_every == 0:\n print(\"batch i=\", str(i))\n\n # Make sure the data is in the proper numpy array format\n if batch_size == 1:\n batchXnp = X[i]\n batchYnp = Y[i]\n if debug: print(\"batchX len:\", str(len(batchXnp)), \"batchY len:\", str(len(batchYnp)))\n batchX2 = None\n if X2 is not None:\n batchX2np = X2[i]\n if debug:\n print(\"batchX2:\", len(batchX2np), batchX2np)\n #if type(batchXnp) is list:\n # batchXnp = numpy.asarray(batchXnp)\n if type(batchYnp) is list:\n batchYnp = numpy.asarray(batchYnp)\n #print(\"batchX shape:\", str(batchXnp.shape), \"batchY shape;\", str(batchYnp.shape))\n if debug: print(\"batchY shape:\", str(batchYnp.shape))\n else:\n batchXnp = X[i:i+batch_size]\n batchYnp = Y[i:i+batch_size]\n if X2 is not None:\n batchX2np = X2[i:i+batch_size]\n\n if encoding_size > 0:\n batchX = batchXnp\n batchY = batchYnp\n if X2 is not None:\n batchX2 = batchX2np\n else:\n batchX2 = None\n\n # Convert to tensors\n #batchXnp = batchXnp.astype('float')\n # batchX = torch.cuda.FloatTensor(batchXnp)\n batchYnp = batchYnp.astype('float')\n batchY = torch.tensor(batchYnp, dtype=torch.float, device=tdevice)\n\n #print(\"batchX size:\", str(batchX.size()), \"batchY size:\", str(batchY.size()))\n if debug: print(\"batchX[0]:\", str(batchX[0]))\n if debug: print(\"batchY size:\", str(batchY.size()))\n\n labels = batchY.view(batch_size, -1, output_dim)\n max_length = labels.size(1)\n if debug: print(\"max_length:\", str(max_length))\n #if debug: print(\"batchX:\", str(batchX.size()), \"batchY:\", str(batchY.size()))\n\n # Forward + Backward + Optimize\n optimizer.zero_grad() # zero the gradient buffer\n loss = 0\n\n if encoding_size > 0:\n outputs, _ = self(batchX, batchX2)\n #print('max_length:', max_length)\n outputs.squeeze(0)\n #outputs = outputs.view(max_length, -1)\n print('outputs:', outputs.size())\n else:\n print('ERROR: Encoding size is 0 and I dont know what to do')\n #outputs = self(samples).view(max_length, -1)\n #if debug: print(\"outputs:\", str(outputs.size()))\n if loss_function == 'crossentropy':\n for b in range(batch_size):\n true_labels = torch.zeros(max_length).long()\n if use_cuda:\n true_labels = true_labels.cuda()\n print('true_labels size:', str(true_labels.size()))\n print('labels[b]', str(len(labels[b])))\n for y in range(len(labels[b])):\n true_label = labels[b][y].data\n #print(\"true_label:\", str(true_label.size()))\n true_index = torch.max(true_label, 0)[1].long()\n #print(\"true_index\", str(true_index.size()))\n true_labels[y] = true_index[0]\n true_var = true_labels\n print(\"true_var\", str(true_var.size()))\n loss = criterion(outputs, true_var)\n loss.backward()\n optimizer.step()\n else:\n labels = labels.view(max_length, 1)\n\n loss = criterion(outputs, labels)\n #print('loss:', loss.item())\n loss.backward()\n optimizer.step()\n\n if (i) % print_every == 0:\n if debug: print('outputs:', outputs.size(), 'labels:', labels.size())\n if debug: print('outputs:', outputs, 'labels:', labels)\n print('Epoch [%d/%d], Loss: %.4f' %(epoch, num_epochs, loss.item()))\n i = i+batch_size\n\n del batchX\n del batchY\n\n # Save checkpoint\n torch.save({'epoch': epoch, 'state_dict': self.state_dict(), 'optimizer': optimizer.state_dict(), 'loss': loss},\n os.path.join(self.checkpoint_dir, 'checkpoint_setorder.pth'))\n print('Saved checkpoint for epoch', epoch)\n print(\"GRU_GRU training took\", str(time.time()-start), \"s\")\n\n def predict(self, testX, X2=None, batch_size=1, keep_list=True, return_encodings=False):\n # Test the Model\n encodings = []\n print_every = 1\n pred = []\n i = 0\n length = len(testX)# .shape[0]\n if debug: print(\"testX len:\", str(len(testX)))\n while i < length:\n if i % print_every == 0:\n if debug: print(\"test batch\", str(i))\n if (i+batch_size) > length:\n batch_size = length-i\n if keep_list:\n if batch_size == 1:\n samples = testX[i]\n if X2 is not None:\n x2_batch = X2[i]\n else:\n samples = testX[i:i+batch_size]\n if X2 is not None:\n x2_batch = X2[i:i+batch_size]\n if debug: print(\"samples:\", str(len(samples)))\n else:\n x_array = numpy.asarray(testX[i:i+batch_size]).astype('float')\n #if debug: print(\"test x_array:\", str(x_array.shape))\n samples = torch.tensor(x_array, dtype=torch.float, device=tdevice)\n\n if X2 is not None:\n outputs = self(samples, x2_batch)\n else:\n with torch.no_grad():\n outputs, enc = self(samples, is_test=True)\n enc_cpu = enc.to('cpu')\n encodings.append(enc_cpu)\n del enc\n torch.cuda.empty_cache()\n outputs = outputs.squeeze()\n print(\"test outputs:\", str(outputs.size()))\n #num_items = outputs.size()[1]\n #predicted = outputs.view(num_items).tolist()\n predicted = outputs.tolist()\n #_, predicted = torch.max(outputs.data, -1) # TODO: fix this\n print('predicted:', predicted)\n pred.append(predicted)\n del samples\n #print('mem allocated:', hurry.filesize.size(torch.cuda.memory_allocated()), 'mem cached:', hurry.filesize.size(torch.cuda.memory_cached()))\n #gpu_usage()\n\n i = i+batch_size\n if not return_encodings:\n del encodings\n if return_encodings:\n return pred, encodings\n else:\n return pred\n", "#!/usr/bin/python3\n# Temporal ordering evaluation functions\n# All functions should be of the form function(y_true, y_pred)\n\nimport ast\nimport math\nimport numpy\nimport scipy\n\nfrom evaluation import eval_util\nfrom data_tools import data_util\nfrom data_tools import temporal_util as tutil\n\ndebug = True\n\n# Metric functions #########################\n\ndef kendalls_tau(true_ranks, pred_ranks, avg=True):\n accuracies = []\n for n in range(len(true_ranks)):\n if len(true_ranks[n]) > 0:\n pr = numpy.asarray(pred_ranks[n])\n tr = true_ranks[n]\n print('tau: true:', tr)\n print('tau: pred:', pr)\n #assert(len(pr) == len(tr))\n if len(tr) < len(pr): # TEMP: force them to be the same size\n pr = pr[0:len(tr)]\n pval = None\n if len(tr) == 0:\n tau = 0\n elif len(tr) == 1:\n tau = 1\n else:\n tau, pval = scipy.stats.kendalltau(tr, pr, nan_policy='raise')\n print('Kendalls tau: n=', n, 'tau:', tau, 'p-value:', pval)\n if not numpy.isnan(tau):\n accuracies.append(tau)\n else:\n print('WARNING: tau score dropped because it was NaN')\n if avg:\n if len(accuracies) > 1:\n acc = numpy.average(numpy.asarray(accuracies))\n elif len(accuracies) == 0:\n acc = 0.0\n else:\n acc = accuracies[0]\n return acc\n else:\n return accuracies\n\n\n''' Calculate the mean ABSOLUTE error of the predicted ranks\n Scale the ranks to 0-1\n'''\ndef rank_mae(true_ranks, pred_ranks):\n print('rank_mse: true:', len(true_ranks), 'pred:', len(pred_ranks))\n if len(true_ranks) != len(pred_ranks):\n print('ERROR: length mismatch of true and pred ranks')\n assert(len(true_ranks) == len(pred_ranks))\n mae_scores = []\n\n # Decide whether or not to scale the ranks\n scale_pred = False\n scale_true = False\n pred_vals = [item for sublist in pred_ranks for item in sublist]\n true_vals = [item for sublist in true_ranks for item in sublist]\n if max(pred_vals) > 1:\n scale_pred = True\n if max(true_vals) > 1:\n scale_true = True\n\n print('mae scaling: true_ranks:', scale_true, 'pred_ranks:', scale_pred)\n\n for n in range(len(true_ranks)):\n print('entry types: true:', type(true_ranks[n]), len(true_ranks[n]), 'pred:', type(pred_ranks[n]), len(pred_ranks[n]))\n # Scale the ranks if needed\n if scale_true:\n true_n = scale_ranks(true_ranks[n])\n else:\n true_n = true_ranks[n]\n if scale_pred:\n pred_n = scale_ranks(pred_ranks[n])\n else:\n pred_n = pred_ranks[n]\n num_samples = len(true_ranks[n])\n assert(num_samples == len(pred_ranks[n]))\n error_sum = 0\n if num_samples > 0:\n for x in range(num_samples):\n error_sum += abs(true_n[x] - pred_n[x])\n mae_scores.append(error_sum/float(num_samples))\n return numpy.average(numpy.asarray(mae_scores))\n\n\n''' Calculate the mean squared error of the predicted ranks\n Scale the ranks to 0-1\n'''\ndef rank_mse(true_ranks, pred_ranks):\n print('rank_mse: true:', len(true_ranks), 'pred:', len(pred_ranks))\n if len(true_ranks) != len(pred_ranks):\n print('ERROR: length mismatch of true and pred ranks')\n assert(len(true_ranks) == len(pred_ranks))\n mse_scores = []\n\n # Decide whether or not to scale the ranks\n scale_pred = False\n scale_true = False\n pred_vals = [item for sublist in pred_ranks for item in sublist]\n true_vals = [item for sublist in true_ranks for item in sublist]\n #if max(pred_vals) > 1 or min(pred_vals) < -1:\n scale_pred = True\n #if max(true_vals) > 1:\n scale_true = True\n\n print('mse scaling: true_ranks:', scale_true, 'pred_ranks:', scale_pred)\n\n for n in range(len(true_ranks)):\n print('entry types: true:', type(true_ranks[n]), len(true_ranks[n]), 'pred:', type(pred_ranks[n]), len(pred_ranks[n]))\n # Scale the ranks if needed\n if scale_true:\n true_n = scale_ranks(true_ranks[n])\n else:\n true_n = true_ranks[n]\n if scale_pred:\n pred_n = scale_ranks(pred_ranks[n])\n else:\n pred_n = pred_ranks[n]\n num_samples = len(true_ranks[n])\n #assert(num_samples == len(pred_ranks[n]))\n error_sum = 0\n if num_samples > 0:\n for x in range(num_samples):\n error_sum += (true_n[x] - pred_n[x]) ** 2\n mse_scores.append(error_sum/float(num_samples))\n return numpy.average(numpy.asarray(mse_scores))\n\n\n''' Calculate the pairwise accuracy of a listwise ranking\n Currently this is a macro average (every document has equal weight)\n'''\ndef rank_pairwise_accuracy(true_ranks, pred_ranks, eps=0.01, avg=True):\n print('poa calculation: eps:', eps)\n accuracies = []\n for n in range(len(true_ranks)):\n if len(true_ranks[n]) > 0:\n pr = pred_ranks[n]\n se, so = get_ordered_pairs(true_ranks[n])\n num_pairs = len(so) + len(se)\n so_correct = 0\n se_correct = 0\n if num_pairs == 0:\n accuracy = 0\n print('WARNING: no ranks for evaluation')\n else:\n for pair in so:\n if pr[pair[0]] < pr[pair[1]]:\n so_correct += 1\n for pair in se:\n if math.fabs(pr[pair[0]] - pr[pair[1]]) <= eps:\n se_correct += 1\n accuracy = (so_correct + se_correct)/float(num_pairs)\n accuracies.append(accuracy)\n if avg:\n if len(accuracies) > 1:\n acc = numpy.average(numpy.asarray(accuracies))\n else:\n acc = accuracies[0]\n return acc\n else:\n return accuracies\n\ndef epr(true_ranks, pred_ranks):\n print('EPR:', events_per_rank(pred_ranks))\n return (events_per_rank(true_ranks), events_per_rank(pred_ranks))\n\ndef gpr(y_true, y_pred, ref_df):\n # Load gold pairs\n print(\"Extracting pair relations...\")\n rec_ids, true_pairs, true_relations = eval_util.extract_relation_pairs(ref_df)\n events = []\n for i, row in ref_df.iterrows():\n event_elem = data_util.load_xml_tags(row['events'])\n event_list = []\n for child in event_elem:\n event_list.append(child)\n print('loaded events:', len(event_list))\n events.append(event_list)\n pred_pairs, pred_labels = eval_util.pair_relations(events, y_pred)\n\n gpr = score_relation_pairs(pred_pairs, pred_labels, true_pairs, true_relations)\n return gpr\n\n# Utility functions ########################\n\ndef events_per_rank(labels, thresh=0.0):\n epr = []\n for ranks in labels:\n rank_to_num = {}\n num = 0\n for val in ranks:\n if val not in rank_to_num:\n rank_to_num[val] = 0\n rank_to_num[val] += 1\n num += 1\n for key in rank_to_num.keys():\n epr.append(rank_to_num[key])\n\n print('epr:', epr)\n avg_epr = numpy.average(numpy.asarray(epr))\n return avg_epr\n\n\n''' From the ranks, generate pairs of events with equal rank, and ordered ranks\n'''\ndef get_ordered_pairs(ranks):\n num = len(ranks)\n equal_pairs = []\n ordered_pairs = []\n for x in range(num):\n first = ranks[x]\n for y in range(num):\n if x != y:\n second = ranks[y]\n if first == second:\n equal_pairs.append((x, y))\n elif first < second:\n ordered_pairs.append((x, y))\n return equal_pairs, ordered_pairs\n\n\n''' Generate all pair relations for ranked events\n'''\ndef pair_relations(events, ranks, eps=0.0):\n pairs = []\n relations = []\n for n in range(len(events)):\n event_list = events[n]\n rank_list = ranks[n]\n doc_pairs = []\n doc_labels = []\n for x in range(len(event_list)):\n for y in range(len(event_list)):\n if x != y:\n event1 = event_list[x]\n event2 = event_list[y]\n rank1 = float(rank_list[x])\n rank2 = float(rank_list[y])\n rel_type = 'OVERLAP'\n if math.fabs(rank1-rank2) <= eps:\n rel_type = 'OVERLAP'\n elif rank1 < rank2:\n rel_type = 'BEFORE'\n elif rank1 > rank2:\n rel_type = 'AFTER'\n #print(\"rank pair\", str(rank1), str(rank2), rel_type)\n doc_pairs.append((event1, event2))\n doc_labels.append(rel_type)\n pairs.append(doc_pairs)\n relations.append(doc_labels)\n return pairs, relations\n\ndef str_pair(event_pair):\n return event_pair[0].attrib['eid'] + ' ' + event_pair[0].text + ' ' + event_pair[1].attrib['eid'] + ' ' + event_pair[1].text\n\n\ndef scale_ranks(rank_list):\n if len(rank_list) == 0:\n return rank_list\n max_rank = max(rank_list)\n min_rank = min(rank_list)\n if max_rank <= 1 and min_rank >= 0:\n return rank_list\n if min_rank < 0:\n shift_val = -1*min_rank\n else:\n shift_val = min_rank\n new_ranks = []\n for rank in rank_list:\n new_ranks.append((float(rank)+shift_val)/float(max_rank))\n return new_ranks\n\n\n''' Score relations pairs against gold standard relation pairs\n'''\ndef score_relation_pairs(pred_pairs, pred_labels, true_pairs, true_labels):\n doc_recalls = []\n doc_true_pairs = []\n doc_class_recalls = {}\n doc_class_recalls['BEFORE'] = []\n doc_class_recalls['AFTER'] = []\n doc_class_recalls['OVERLAP'] = []\n doc_class_totals = {}\n doc_class_totals['BEFORE'] = 0\n doc_class_totals['AFTER'] = 0\n doc_class_totals['OVERLAP'] = 0\n if debug: print('score_relation_pairs:', str(len(pred_pairs)), str(len(pred_labels)), str(len(true_pairs)), str(len(true_labels)))\n #assert(len(pred_labels) == len(true_labels))\n #assert(len(pred_pairs) == len(true_pairs))\n for x in range(len(pred_labels)):\n total = 0\n found = 0\n class_totals = {}\n class_totals['BEFORE'] = 0\n class_totals['AFTER'] = 0\n class_totals['OVERLAP'] = 0\n class_founds = {}\n class_founds['BEFORE'] = 0\n class_founds['AFTER'] = 0\n class_founds['OVERLAP'] = 0\n #print('tpairs:', str(len(true_pairs[x])))\n for y in range(len(true_pairs[x])):\n tpair = true_pairs[x][y]\n tlabel = tutil.map_rel_type(true_labels[x][y], 'simple')\n if debug: print('- tpair:', eval_util.str_pair(tpair), 'tlabel:', str(tlabel))\n total += 1\n class_totals[tlabel] += 1\n #print('pred_pair[0]:', str(pred_pairs[x][0][0]), str(pred_pairs[x][0][1]))\n for z in range(len(pred_pairs[x])):\n ppair = pred_pairs[x][z]\n if tutil.are_pairs_equal(tpair, ppair):\n plabel = pred_labels[x][z]\n if debug: print(\"-- checking pair:\", eval_util.str_pair(ppair), str(plabel))\n if tlabel == plabel:\n found += 1\n class_founds[tlabel] += 1\n if debug: print('--- correct')\n # Count before and before/overlap as the same since we're ranking on start time\n elif tlabel == 'BEFORE/OVERLAP' and plabel == 'BEFORE':\n if debug: print('--- correct (before/overlap)')\n found += 1\n class_founds[plabel] += 1\n if total == 0:\n print('WARNING: no reference relations found!')\n doc_recall = 0\n else:\n doc_recall = found/total\n for key in class_totals.keys():\n if class_totals[key] == 0:\n val = 0.0\n else:\n val = float(class_founds[key]) / class_totals[key]\n doc_class_recalls[key].append(val)\n doc_class_totals[key] += class_totals[key]\n doc_recalls.append(doc_recall)\n doc_true_pairs.append(total)\n\n # Calculate the weighted average recall\n avg_recall = numpy.average(doc_recalls, weights=doc_true_pairs)\n for key in doc_class_recalls.keys():\n avg_class_recall = numpy.average(numpy.asarray(doc_class_recalls[key]))\n print('GPR Recall', key, str(avg_class_recall), 'num=', str(doc_class_totals[key]))\n\n return avg_recall\n" ]
[ [ "torch.nn.Softmax", "torch.max", "torch.load", "torch.cat", "numpy.asarray", "torch.zeros", "torch.no_grad", "torch.cuda.is_available", "torch.device", "torch.nn.L1Loss", "torch.nn.CrossEntropyLoss", "torch.backends.cudnn.version", "torch.tensor", "torch.cuda.current_device", "torch.cuda.empty_cache", "torch.nn.Linear", "torch.nn.CosineEmbeddingLoss", "torch.stack", "torch.cuda.device_count", "numpy.set_printoptions", "torch.nn.MSELoss" ], [ "numpy.asarray", "numpy.isnan", "numpy.average", "scipy.stats.kendalltau" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
willettk/gzh_jpg
[ "ae5599844995ca741c8f05a5cf3c76b15744496c" ]
[ "python/nw.py" ]
[ "import numpy as np\n\n#+\n#NAME:\n# arcsinh_fit\n#PURPOSE:\n# scales the FITS image by a specified degree of nonlinearity\n#INPUTS:\n# colors - (3xNXxNY) numpy array that contains the R/G/B images\n#OPTIONAL INPUTS:\n# nonlinearity- 'b'\n# - b=0 for linear fit\n# - default is 3\n#KEYWORDS:\n#\n#OUTPUTS:\n# Scaled FITS image\n#BUGS:\n# \n#REVISION HISTORY:\n# 2 Jul 2014 - ported from Nick Wherry's IDL routine NW_ARCSINH_FIT - K. Willett\n#-\n\ndef arcsinh_fit(colors,nonlinearity=3.):\n \n color_arr = np.array(colors)\n\n if nonlinearity != 0:\n radius = color_arr.sum(axis=0)\n radius[radius == 0] += 1\n\n val = np.arcsinh(radius*nonlinearity)/nonlinearity\n fitted_colors = color_arr * val / radius\n else:\n fitted_colors = color_arr\n\n return fitted_colors\n\n#+\n#NAME:\n# fit_to_box\n#PURPOSE:\n# Limits the pixel values of the image to a 'box', so that the colors\n# do not saturate to white but to a specific color.\n#INPUTS:\n# colors - (NXxNYx3) array that contains the R/G/B images\n#OPTIONAL INPUTS:\n# origin - (3x1) array containing R0/G0/B0\n# - default is [0,0,0]\n#KEYWORDS:\n#\n#OUTPUTS:\n# The color limited image\n#BUGS:\n# \n#REVISION HISTORY:\n# 2 Jul 2014 - ported from Nick Wherry's IDL routine NW_FIT_TO_BOX - K. Willett\n#-\ndef fit_to_box(colors,origin=[0,0,0]):\n\n color_arr = np.array(colors)\n \n # Creates an 'origin' array\n origin_arr = np.zeros_like(color_arr)\n for idx,o in enumerate(origin):\n origin_arr[idx,:,:] = o\n\n pos_dist = 1 - origin_arr\n \n factor = (color_arr / pos_dist).max(axis=0)\n factor[factor < 1.0] = 1.0\n\n boxed_colors = colors / factor\n\n return boxed_colors\n\n\n#+\n#NAME:\n# float_to_byte\n#PURPOSE:\n# Converts floats of an array to bytes\n#INPUTS:\n# image - image array\n#OPTIONAL INPUTS:\n# none\n#KEYWORDS:\n# none\n#OUTPUTS:\n# The float-value image\n#REVISION HISTORY:\n# 2 Jul 2014 - ported from Nick Wherry's IDL routine NW_FLOAT_TO_BYTE - K. Willett\n#-\ndef float_to_byte(image):\n byte_image = bytearray(image)\n return byte_image\n\n\n#+\n#NAME:\n# scale_rgb\n#PURPOSE:\n# mulitiplies the RGB image by their respective scales\n#CALLING SEQUENCE:\n# nw_scale_rgb, colors, [scales=]\n#INPUTS:\n# colors - (3xNXxNY) array containing the R, G, and B\n#OPTIONAL INPUTS:\n# scales - list of len(3) to scale the R/G/B\n# - defaults are [4.9,5.7,7.8]\n#KEYWORDS:\n# none\n#OUTPUTS:\n# The RGB image \n#BUGS:\n# \n#DEPENDENCIES:\n#\n#REVISION HISTORY:\n# 2 Jul 2014 - ported from Nick Wherry's IDL routine NW_SCALE_RGB - K. Willett\n#-\ndef scale_rgb(colors,scales=[4.9,5.7,7.8]):\n\n scaled_colors = np.zeros_like(colors)\n for idx,s in enumerate(scales):\n scaled_colors[idx,:,:] = colors[idx,:,:] * s\n \n return scaled_colors\n" ]
[ [ "numpy.array", "numpy.zeros_like", "numpy.arcsinh" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LynnHo/DTLC-GAN-Tensorflow
[ "ca053af68a47e4678c172d756d64e3576a51e009" ]
[ "model.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom functools import partial\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tflib as tl\n\n\n# ==============================================================================\n# = alias =\n# ==============================================================================\n\nconv = partial(slim.conv2d, activation_fn=None)\ndconv = partial(slim.conv2d_transpose, activation_fn=None)\nfc = partial(tl.flatten_fully_connected, activation_fn=None)\nrelu = tf.nn.relu\nlrelu = tf.nn.leaky_relu\n# batch_norm = partial(slim.batch_norm, scale=True)\nbatch_norm = partial(slim.batch_norm, scale=True, updates_collections=None)\nlayer_norm = slim.layer_norm\ninstance_norm = slim.instance_norm\n\n\n# ==============================================================================\n# = models =\n# ==============================================================================\n\ndef _get_norm_fn(norm_name, is_training):\n if norm_name == 'none':\n norm = None\n elif norm_name == 'batch_norm':\n norm = partial(batch_norm, is_training=is_training)\n elif norm_name == 'instance_norm':\n norm = instance_norm\n elif norm_name == 'layer_norm':\n norm = layer_norm\n return norm\n\n\ndef G(z, c, dim=64, is_training=True):\n norm = _get_norm_fn('batch_norm', is_training)\n fc_norm_relu = partial(fc, normalizer_fn=norm, activation_fn=relu)\n dconv_norm_relu = partial(dconv, normalizer_fn=norm, activation_fn=relu)\n\n with tf.variable_scope('G', reuse=tf.AUTO_REUSE):\n y = tf.concat([z, c], axis=1)\n y = fc_norm_relu(y, 4 * 4 * dim * 8)\n y = tf.reshape(y, [-1, 4, 4, dim * 8])\n y = dconv_norm_relu(y, dim * 4, 4, 2)\n y = dconv_norm_relu(y, dim * 2, 4, 2)\n y = dconv_norm_relu(y, dim * 1, 4, 2)\n x = tf.tanh(dconv(y, 3, 4, 2))\n return x\n\n\ndef D(x, c_dim, dim=64, norm_name='batch_norm', is_training=True):\n norm = _get_norm_fn(norm_name, is_training)\n conv_norm_lrelu = partial(conv, normalizer_fn=norm, activation_fn=lrelu)\n\n with tf.variable_scope('D', reuse=tf.AUTO_REUSE):\n y = conv_norm_lrelu(x, dim, 4, 2)\n y = conv_norm_lrelu(y, dim * 2, 4, 2)\n y = conv_norm_lrelu(y, dim * 4, 4, 2)\n y = conv_norm_lrelu(y, dim * 8, 4, 2)\n logit = fc(y, 1)\n c_logit = fc(y, c_dim)\n return logit, c_logit\n\n\n# ==============================================================================\n# = loss function =\n# ==============================================================================\n\ndef get_loss_fn(mode):\n if mode == 'gan':\n def d_loss_fn(r_logit, f_logit):\n r_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(r_logit), r_logit)\n f_loss = tf.losses.sigmoid_cross_entropy(tf.zeros_like(f_logit), f_logit)\n return r_loss, f_loss\n\n def g_loss_fn(f_logit):\n f_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(f_logit), f_logit)\n return f_loss\n\n elif mode == 'lsgan':\n def d_loss_fn(r_logit, f_logit):\n r_loss = tf.losses.mean_squared_error(tf.ones_like(r_logit), r_logit)\n f_loss = tf.losses.mean_squared_error(tf.zeros_like(f_logit), f_logit)\n return r_loss, f_loss\n\n def g_loss_fn(f_logit):\n f_loss = tf.losses.mean_squared_error(tf.ones_like(f_logit), f_logit)\n return f_loss\n\n elif mode == 'wgan':\n def d_loss_fn(r_logit, f_logit):\n r_loss = - tf.reduce_mean(r_logit)\n f_loss = tf.reduce_mean(f_logit)\n return r_loss, f_loss\n\n def g_loss_fn(f_logit):\n f_loss = - tf.reduce_mean(f_logit)\n return f_loss\n\n elif mode == 'hinge':\n def d_loss_fn(r_logit, f_logit):\n r_loss = tf.reduce_mean(tf.maximum(1 - r_logit, 0))\n f_loss = tf.reduce_mean(tf.maximum(1 + f_logit, 0))\n return r_loss, f_loss\n\n def g_loss_fn(f_logit):\n # f_loss = tf.reduce_mean(tf.maximum(1 - f_logit, 0))\n f_loss = tf.reduce_mean(- f_logit)\n return f_loss\n\n return d_loss_fn, g_loss_fn\n\n\n# ==============================================================================\n# = others =\n# ==============================================================================\n\ndef gradient_penalty(f, real, fake, mode):\n def _gradient_penalty(f, real, fake=None):\n def _interpolate(a, b=None):\n with tf.name_scope('interpolate'):\n if b is None: # interpolation in DRAGAN\n beta = tf.random_uniform(shape=tf.shape(a), minval=0., maxval=1.)\n _, variance = tf.nn.moments(a, list(range(a.shape.ndims)))\n b = a + 0.5 * tf.sqrt(variance) * beta\n shape = [tf.shape(a)[0]] + [1] * (a.shape.ndims - 1)\n alpha = tf.random_uniform(shape=shape, minval=0., maxval=1.)\n inter = a + alpha * (b - a)\n inter.set_shape(a.get_shape().as_list())\n return inter\n\n with tf.name_scope('gradient_penalty'):\n x = _interpolate(real, fake)\n pred = f(x)\n if isinstance(pred, tuple):\n pred = pred[0]\n grad = tf.gradients(pred, x)[0]\n norm = tf.norm(slim.flatten(grad), axis=1)\n gp = tf.reduce_mean((norm - 1.)**2)\n return gp\n\n if mode == 'none':\n gp = tf.constant(0, dtype=tf.float32)\n elif mode == 'wgan-gp':\n gp = _gradient_penalty(f, real, fake)\n elif mode == 'dragan':\n gp = _gradient_penalty(f, real)\n\n return gp\n\n\ndef sample_c(ks, c_1=None, continuous_last=False):\n assert c_1 is None or ks[0] == len(c_1), '`ks[0]` is inconsistent with `c_1`!'\n\n c_tree = [[np.array([1.])]]\n mask_tree = []\n\n for l, k in enumerate(ks):\n if c_1 is not None and l == 0:\n c_l = [c_1]\n mask_l = [np.ones_like(c_1)]\n else:\n c_l = []\n mask_l = []\n for i in range(len(c_tree[-1])):\n for j in range(len(c_tree[-1][-1])):\n if c_tree[-1][i][j] == 1.:\n if continuous_last is True and l == len(ks) - 1:\n c_l.append(np.random.uniform(-1, 1, size=[k]))\n else:\n c_l.append(np.eye(k)[np.random.randint(k)])\n mask_l.append(np.ones([k]))\n else:\n c_l.append(np.zeros([k]))\n mask_l.append(np.zeros([k]))\n c_tree.append(c_l)\n mask_tree.append(mask_l)\n\n c_tree[0:1] = []\n c = np.concatenate([k for l in c_tree for k in l])\n mask = np.concatenate([k for l in mask_tree for k in l])\n\n return c, mask, c_tree, mask_tree\n\n\ndef traversal_trees(ks, continuous_last=False):\n trees = []\n if len(ks) == 1:\n if continuous_last:\n trees.append([[np.random.uniform(-1, 1, size=[ks[0]])]])\n else:\n for i in range(ks[0]):\n trees.append([[np.eye(ks[0])[i]]])\n else:\n def _merge_trees(trees):\n tree = []\n for l in range(len(trees[0])):\n tree_l = []\n for t in trees:\n tree_l += t[l]\n tree.append(tree_l)\n return tree\n\n def _zero_tree(tree):\n zero_tree = []\n for l in tree:\n zero_tree_l = []\n for i in l:\n zero_tree_l.append(i * 0.)\n zero_tree.append(zero_tree_l)\n return zero_tree\n\n for i in range(ks[0]):\n trees_i = []\n sub_trees, _ = traversal_trees(ks[1:], continuous_last=continuous_last)\n for j, s_t in enumerate(sub_trees):\n to_merge = [_zero_tree(s_t)] * ks[0]\n to_merge[i] = s_t\n sub_trees[j] = _merge_trees(to_merge)\n for s_t in sub_trees:\n trees_i.append([[np.eye(ks[0])[i]]] + s_t)\n trees += trees_i\n\n cs = []\n for t in trees:\n cs.append(np.concatenate([k for l in t for k in l]))\n return trees, cs\n\n\ndef to_tree(x, ks):\n size_splits = []\n n_l = 1\n for k in ks:\n for _ in range(n_l):\n size_splits.append(k)\n n_l *= k\n\n splits = tf.split(x, size_splits, axis=1)\n\n tree = []\n n_l = 1\n i = 0\n for k in ks:\n tree_l = []\n for _ in range(n_l):\n tree_l.append(splits[i])\n i += 1\n n_l *= k\n tree.append(tree_l)\n\n return tree\n\n\ndef tree_loss(logits, c, mask, ks, continuous_last=False):\n logits_tree = to_tree(logits, ks)\n c_tree = to_tree(c, ks)\n mask_tree = to_tree(mask, ks)\n\n losses = []\n for l, logits_l, c_l, mask_l in zip(range(len(logits_tree)), logits_tree, c_tree, mask_tree):\n loss_l = 0\n for lo, c, m in zip(logits_l, c_l, mask_l):\n weights = tf.reduce_mean(m, axis=1)\n if continuous_last is True and l == len(ks) - 1:\n loss_l += tf.losses.mean_squared_error(c, lo, weights=weights)\n else:\n loss_l += tf.losses.softmax_cross_entropy(c, lo, weights=weights)\n losses.append(loss_l)\n return losses\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n s = tf.Session()\n ks = [2, 2, 2]\n c_1 = np.array([1., 0])\n continuous_last = False\n if len(ks) == 1 and c_1 is not None:\n continuous_last = False\n\n c, mask, c_tree, mask_tree = sample_c(ks, c_1, continuous_last)\n pp(c)\n pp(mask)\n pp(c_tree)\n pp(mask_tree)\n\n tree = to_tree(tf.constant(np.array([c]), dtype=tf.float32), ks)\n pp(tree)\n pp(s.run(tree))\n\n pp(tree_loss(tf.constant(np.array([c]), dtype=tf.float32),\n tf.constant(np.array([c]), dtype=tf.float32),\n tf.constant(np.array([mask]), dtype=tf.float32),\n ks,\n continuous_last))\n\n pp(s.run(tf.losses.softmax_cross_entropy([[0, 10]], [[0.5, 0.5]])))\n pp(s.run(tf.losses.mean_squared_error([[2, 1]], [[0, 0]])))\n\n for tree, c in zip(*traversal_trees(ks, continuous_last=continuous_last)):\n pp(tree)\n pp(c)\n" ]
[ [ "tensorflow.concat", "numpy.concatenate", "tensorflow.contrib.slim.flatten", "numpy.random.randint", "numpy.ones_like", "numpy.eye", "tensorflow.gradients", "tensorflow.losses.softmax_cross_entropy", "tensorflow.name_scope", "tensorflow.Session", "numpy.zeros", "tensorflow.shape", "tensorflow.zeros_like", "tensorflow.split", "numpy.array", "tensorflow.losses.mean_squared_error", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.ones_like", "numpy.ones", "tensorflow.variable_scope", "numpy.random.uniform", "tensorflow.sqrt", "tensorflow.random_uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
shuipi100/kaldi
[ "8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0" ]
[ "egs/yomdle_tamil/v1/local/yomdle/gedi2csv_enriched.py" ]
[ "#!/usr/bin/env python3\n\n'''\nConvert GEDI-type bounding boxes to CSV format\n'''\n\nimport logging\nimport os\nimport sys\nimport time\nimport glob\nimport csv\nimport imghdr\nfrom PIL import Image\nimport argparse\nimport pdb\nimport cv2\nimport numpy as np\nimport xml.etree.ElementTree as ET\n\nsin = np.sin\ncos = np.cos\npi = np.pi\n\ndef Rotate2D(pts, cnt, ang=90):\n M = np.array([[cos(ang),-sin(ang)],[sin(ang),cos(ang)]])\n res = np.dot(pts-cnt,M)+cnt\n return M, res\n\ndef npbox2string(npar):\n if np.shape(npar)[0] != 1:\n print('Error during CSV conversion\\n')\n c1,r1 = npar[0][0],npar[0][1]\n c2,r2 = npar[0][2],npar[0][3]\n c3,r3 = npar[0][4],npar[0][5]\n c4,r4 = npar[0][6],npar[0][7]\n\n return c1,r1,c2,r2,c3,r3,c4,r4\n\n# cv2.minAreaRect() returns a Box2D structure which contains following detals - ( center (x,y), (width, height), angle of rotation )\n# Get 4 corners of the rectangle using cv2.boxPoints()\nclass GEDI2CSV():\n ''' Initialize the extractor'''\n def __init__(self, logger, args):\n self._logger = logger\n self._args = args\n\n '''\n Segment image with GEDI bounding box information\n '''\n def csvfile(self, coords, polys, baseName, pgrot):\n\n ''' for writing the files '''\n writePath = self._args.outputDir\n writePath = os.path.join(writePath,'')\n if os.path.isdir(writePath) != True:\n os.makedirs(writePath)\n\n rotlist = []\n\n header=['ID','name','col1','row1','col2','row2','col3','row3','col4','row4','confidence','truth','pgrot','bbrot','qual','script','text_type']\n conf=100\n write_ctr = 0\n if len(coords) == 0 and len(polys) == 0:\n self._logger.info('Found %s with no text content',(baseName))\n print('...Found %s with no text content' % (baseName))\n return\n \n strPos = writePath + baseName\n\n ''' for each group of coordinates '''\n for i in coords:\n\n [id,x,y,w,h,degrees,text,qual,script,text_type] = i\n contour = np.array([(x,y),(x+w,y),(x+w,y+h),(x,y+h)])\n \"\"\"First rotate around upper left corner based on orientationD keyword\"\"\"\n M, rot = Rotate2D(contour, np.array([x,y]), degrees*pi/180)\n rot = np.int0(rot)\n\n # rot is the 8 points rotated by degrees\n # pgrot is the rotation after extraction, so save\n # save rotated points to list or array\n rot = np.reshape(rot,(-1,1)).T\n c1,r1,c2,r2,c3,r3,c4,r4 = npbox2string(rot)\n \n bbrot = degrees\n rotlist.append([id,baseName + '_' + id + '.png',c1,r1,c2,r2,c3,r3,c4,r4,conf,text,pgrot,bbrot,qual,script,text_type])\n\n # if there are polygons, first save the text\n for j in polys:\n arr = []\n [id,poly_val,text,qual,script,text_type] = j\n for i in poly_val:\n arr.append(eval(i))\n\n contour = np.asarray(arr)\n convex = cv2.convexHull(contour)\n rect = cv2.minAreaRect(convex)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n box = np.reshape(box,(-1,1)).T\n c1,r1,c2,r2,c3,r3,c4,r4 = npbox2string(box)\n \n bbrot = 0.0\n rotlist.append([id,baseName + '_' + id + '.png',c1,r1,c2,r2,c3,r3,c4,r4,conf,text,pgrot,bbrot,qual,script,text_type])\n # then write out all of list to file\n with open(strPos + \".csv\", \"w\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n writer.writerow(header)\n for row in rotlist:\n writer.writerow(row)\n write_ctr += 1\n return write_ctr\n \n\ndef main(args):\n startTime = time.clock()\n writePath = args.outputDir\n if os.path.isdir(writePath) != True:\n os.makedirs(writePath)\n ''' Setup logging '''\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n if args.log:\n handler = logging.FileHandler(args.log)\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n gtconverter = GEDI2CSV(logger, args)\n namespaces = {\"gedi\" : \"http://lamp.cfar.umd.edu/media/projects/GEDI/\"}\n keyCnt=0\n fileCnt = 0\n line_write_ctr = 0\n line_error_ctr = 0\n \n '''\n Get all XML files in the directory and sub folders\n '''\n for root, dirnames, filenames in os.walk(args.inputDir, followlinks=True):\n for file in filenames:\n if file.lower().endswith('.xml'):\n fullName = os.path.join(root,file)\n baseName = os.path.splitext(fullName)\n fileCnt += 1\n ''' read the XML file '''\n tree = ET.parse(fullName)\n gedi_root = tree.getroot()\n child = gedi_root.findall('gedi:DL_DOCUMENT',namespaces)[0]\n totalpages = int(child.attrib['NrOfPages'])\n coordinates=[]\n polygons = []\n if args.ftype == 'boxed':\n fileTypeStr = 'col'\n elif args.ftype == 'transcribed':\n fileTypeStr = 'Text_Content'\n else:\n print('Filetype must be either boxed or transcribed!')\n logger.info('Filetype must be either boxed or transcribed!')\n sys.exit(-1)\n \n if args.quality == 'both':\n qualset = {'Regular','Low-Quality'}\n elif args.quality == 'low':\n qualset = {'Low-Quality'}\n elif args.quality == 'regular':\n qualset = {'Regular'}\n else:\n print('Quality must be both, low or regular!')\n logger.info('Quality must be both, low or regular!')\n sys.exit(-1)\n \n \n\n ''' and for each page '''\n for i, pgs in enumerate(child.iterfind('gedi:DL_PAGE',namespaces)):\n \n if 'GEDI_orientation' not in pgs.attrib:\n pageRot=0\n else:\n pageRot = int(pgs.attrib['GEDI_orientation'])\n logger.info(' PAGE ROTATION %s, %s' % (fullName, str(pageRot)))\n\n ''' find children for each page '''\n for zone in pgs.findall('gedi:DL_ZONE',namespaces):\n\n if zone.attrib['gedi_type']=='Text' and zone.attrib['Type'] in \\\n ('Machine_Print','Confusable_Allograph','Handwriting') and zone.attrib['Quality'] in qualset:\n if zone.get('polygon'):\n keyCnt+=1\n polygons.append([zone.attrib['id'],zone.get('polygon').split(';'),\n zone.get('Text_Content'),zone.get('Quality'),zone.get('Script'),zone.get('Type')])\n elif zone.get(fileTypeStr) != None:\n keyCnt+=1\n coord = [zone.attrib['id'],int(zone.attrib['col']),int(zone.attrib['row']),\n int(zone.attrib['width']), int(zone.attrib['height']),\n float(zone.get('orientationD',0.0)),\n zone.get('Text_Content'),zone.get('Quality'),zone.get('Script'),zone.get('Type')]\n coordinates.append(coord)\n\n if len(coordinates) > 0 or len(polygons) > 0:\n line_write_ctr += gtconverter.csvfile(coordinates, polygons, os.path.splitext(file)[0], pageRot)\n else:\n print('...%s has no applicable content' % (baseName[0]))\n\n print('complete...total files %d, lines written %d' % (fileCnt, line_write_ctr))\n\n\n''' Args and defaults '''\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--inputDir', type=str, help='Input directory', required=True)\n parser.add_argument('--outputDir', type=str, help='Output directory', required=True)\n parser.add_argument('--ftype', type=str, help='GEDI file type (either \"boxed\" or \"transcribed\")', default='transcribed')\n parser.add_argument('--quality', type=str, help='GEDI file quality (either \"both\" or \"low\" or \"regular\")', default='regular')\n parser.add_argument('--log', type=str, help='Log directory', default='./GEDI2CSV_enriched.log')\n\n return parser.parse_args(argv)\n\n''' Run '''\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n\n\n\n \n\n\n" ]
[ [ "numpy.int0", "numpy.dot", "numpy.asarray", "numpy.reshape", "numpy.shape", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Tiernan8r/Variational-Principle-GUI
[ "6572a8b67ce870590ff30ad7c3bcfdeda47b3360" ]
[ "variational_principle_gui/components/embedded_graphs/array_graph.py" ]
[ "import matplotlib\n\nmatplotlib.use('Qt5Agg')\nimport logging\nfrom variational_principle_gui.components.graphs_tab.list_entry import ListEntry\nfrom variational_principle_gui.components.embedded_graphs.embedded_graph import EmbeddedGraph\n\n\nclass ArrayGraph(EmbeddedGraph):\n\n def __init__(self, graph_widget, computed_data):\n super().__init__(graph_widget, computed_data)\n self.logger = logging.getLogger(__name__)\n\n def display(self, list_entry: ListEntry = None, plot_number=-1):\n\n if list_entry is None:\n self.logger.warning(\"Attempted to plot with None data given, using previous value instead.\")\n if self.current_list_entry is not None:\n list_entry = self.current_list_entry\n else:\n self.logger.warning(\"Couldn't find previous list entry, returning.\")\n return\n self.current_list_entry = list_entry\n\n if self.computed_data is None:\n self.logger.warning(\"The ComputedData object is None!\")\n return\n\n key = list_entry.key\n if key == self.computed_data.r_key:\n self.computed_data.r = list_entry.value\n self.logger.debug(\"Given position array, storing it.\")\n return\n if key == self.computed_data.v_key:\n self.logger.debug(\"Given potential array, storing for future reference.\")\n self.computed_data.V = list_entry.value\n\n # TODO remove hardcoding of total number of plot options?\n if plot_number < 0:\n plot_number = self.current_plot_index\n elif plot_number > 2:\n plot_number = 2\n self.current_plot_index = plot_number\n\n self.figure.clear(keep_observers=True)\n self.axes = self.figure.add_subplot()\n\n if self.computed_data.r is None:\n self.logger.warning(\"Attempted to plot graph when position vector not given, returning.\")\n return\n\n psi = list_entry.value\n\n if psi is None:\n self.logger.warning(\"Cannot display, psi is None!\")\n return\n self.current_item = key\n\n r, V = self.computed_data.r, self.computed_data.V\n if r is None or V is None:\n self.logger.warning(\"Cannot display, V or r is None!\")\n return\n\n self.axes.clear()\n\n title = \"Plot of {} of the {}:\".format(key, self.computed_data.label)\n xlabel, ylabel, zlabel = \"$x$\", \"$y$\", \"$z$\"\n\n D = self.computed_data.num_dimensions\n if D == 1:\n\n legend = [key]\n\n psi_scale = 1\n ylabel = \"$\\psi$\"\n\n if self.computed_data.plot_with_potential and key != \"potential\":\n self.axes.plot(r[0], V)\n\n psi_scale = self.computed_data.plot_scale\n ylabel = \"$V$\"\n\n legend.insert(0, \"potential\")\n\n self._plot_line(r[0], psi * psi_scale, title, xlabel, ylabel, legend)\n\n elif D == 2:\n\n zlabel = \"$\\psi$\"\n if key == \"potential\":\n zlabel = \"$V$\"\n\n if plot_number == 0:\n self._plot_image(*r, psi, title, xlabel, ylabel)\n elif plot_number == 1:\n self._plot_wireframe(*r, psi, title, xlabel, ylabel, zlabel)\n else:\n self._plot_surface(*r, psi, title, xlabel, ylabel, zlabel)\n\n elif D == 3:\n self._plot_3D_scatter(*r, psi, title, xlabel, ylabel, zlabel)\n else:\n self.logger.warning(\"Attempt to call plotting for over 3 dimensions, not implemented.\")\n pass\n\n self.figure_canvas.draw()\n" ]
[ [ "matplotlib.use" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SCCH-KVS/segmentation_models
[ "e868f169a219a06ed1a96d810c61a4bd465edeec" ]
[ "segmentation_models/models/xnet.py" ]
[ "#!/usr/bin/env python\n# Adopted from https://github.com/MrGiovanni/UNetPlusPlus\n\nfrom keras_applications import get_submodules_from_kwargs\nimport numpy as np\n\nfrom ._utils import freeze_model\nfrom ..backbones.backbones_factory import Backbones\n\nbackend = None\nlayers = None\nmodels = None\nkeras_utils = None\n\nDEFAULT_SKIP_CONNECTIONS = {\n 'vgg16': ('block5_conv3', 'block4_conv3', 'block3_conv3', 'block2_conv2', 'block1_conv2',\n 'block5_pool', 'block4_pool', 'block3_pool', 'block2_pool', 'block1_pool',\n ),\n 'vgg19': ('block5_conv4', 'block4_conv4', 'block3_conv4', 'block2_conv2', 'block1_conv2',\n 'block5_pool', 'block4_pool', 'block3_pool', 'block2_pool', 'block1_pool',\n ),\n 'resnet18': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnet34': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnet50': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnet101': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnet152': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnext50': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'stage4_unit1_relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'resnext101': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0',\n 'stage4_unit1_relu1', 'stage3_unit2_relu1', 'stage2_unit2_relu1', 'stage1_unit2_relu1',\n ),\n 'inceptionv3': (228, 86, 16, 9),\n 'inceptionresnetv2': (594, 260, 16, 9),\n 'densenet121': (311, 139, 51, 4),\n 'densenet169': (367, 139, 51, 4),\n 'densenet201': (479, 139, 51, 4),\n}\n\n\n# ---------------------------------------------------------------------\n# Utility functions\n# ---------------------------------------------------------------------\n\ndef get_submodules():\n return {\n 'backend': backend,\n 'models': models,\n 'layers': layers,\n 'utils': keras_utils,\n }\n\n\ndef get_layer_number(model, layer_name):\n \"\"\"\n Help find layer in Keras model by name\n Args:\n model: Keras `Model`\n layer_name: str, name of layer\n Returns:\n index of layer\n Raises:\n ValueError: if model does not contains layer with such name\n \"\"\"\n for i, l in enumerate(model.layers):\n if l.name == layer_name:\n return i\n raise ValueError('No layer with name {} in model {}.'.format(layer_name, model.name))\n\n\ndef to_tuple(x):\n if isinstance(x, tuple):\n if len(x) == 2:\n return x\n elif np.isscalar(x):\n return (x, x)\n\n raise ValueError('Value should be tuple of length 2 or int value, got \"{}\"'.format(x))\n\n\n# ---------------------------------------------------------------------\n# Blocks\n# ---------------------------------------------------------------------\ndef handle_block_names(stage, cols):\n conv_name = 'decoder_stage{}-{}_conv'.format(stage, cols)\n bn_name = 'decoder_stage{}-{}_bn'.format(stage, cols)\n relu_name = 'decoder_stage{}-{}_relu'.format(stage, cols)\n up_name = 'decoder_stage{}-{}_upsample'.format(stage, cols)\n merge_name = 'merge_{}-{}'.format(stage, cols)\n return conv_name, bn_name, relu_name, up_name, merge_name\n\n\ndef ConvRelu(filters, kernel_size, use_batchnorm=False, conv_name='conv', bn_name='bn', relu_name='relu'):\n def layer(x):\n x = layers.Conv2D(filters, kernel_size, padding=\"same\", name=conv_name, use_bias=not (use_batchnorm))(x)\n if use_batchnorm:\n x = layers.BatchNormalization(name=bn_name)(x)\n x = layers.Activation('relu', name=relu_name)(x)\n return x\n\n return layer\n\n\ndef Upsample2D_block(filters, stage, cols, kernel_size=(3, 3), upsample_rate=(2, 2),\n use_batchnorm=False, skip=None):\n def layer(input_tensor):\n\n conv_name, bn_name, relu_name, up_name, merge_name = handle_block_names(stage, cols)\n\n x = layers.UpSampling2D(size=upsample_rate, name=up_name)(input_tensor)\n\n if (type(skip) != list and skip is not None) or (type(skip) == list and None not in skip):\n if type(skip) is list:\n x = layers.Concatenate(name=merge_name)([x] + skip)\n else:\n x = layers.Concatenate(name=merge_name)([x, skip])\n\n x = ConvRelu(filters, kernel_size, use_batchnorm=use_batchnorm,\n conv_name=conv_name + '1', bn_name=bn_name + '1', relu_name=relu_name + '1')(x)\n\n x = ConvRelu(filters, kernel_size, use_batchnorm=use_batchnorm,\n conv_name=conv_name + '2', bn_name=bn_name + '2', relu_name=relu_name + '2')(x)\n\n return x\n\n return layer\n\n\ndef Transpose2D_block(filters, stage, cols, kernel_size=(3, 3), upsample_rate=(2, 2),\n transpose_kernel_size=(4, 4), use_batchnorm=False, skip=None):\n def layer(input_tensor):\n\n conv_name, bn_name, relu_name, up_name, merge_name = handle_block_names(stage, cols)\n\n x = layers.Conv2DTranspose(filters, transpose_kernel_size, strides=upsample_rate,\n padding='same', name=up_name, use_bias=not (use_batchnorm))(input_tensor)\n if use_batchnorm:\n x = layers.BatchNormalization(name=bn_name + '1')(x)\n x = layers.Activation('relu', name=relu_name + '1')(x)\n\n if (type(skip) != list and skip is not None) or (type(skip) == list and None not in skip):\n # print(\"\\nskip = {}\".format(skip))\n if type(skip) is list:\n merge_list = []\n merge_list.append(x)\n for l in skip:\n merge_list.append(l)\n x = layers.Concatenate(name=merge_name)(merge_list)\n else:\n x = layers.Concatenate(name=merge_name)([x, skip])\n\n x = ConvRelu(filters, kernel_size, use_batchnorm=use_batchnorm,\n conv_name=conv_name + '2', bn_name=bn_name + '2', relu_name=relu_name + '2')(x)\n\n return x\n\n return layer\n\n\n# ---------------------------------------------------------------------\n# Xnet Decoder\n# ---------------------------------------------------------------------\n\ndef build_xnet(backbone, classes, skip_connection_layers,\n decoder_filters=(256, 128, 64, 32, 16),\n upsample_rates=(2, 2, 2, 2, 2),\n n_upsample_blocks=5,\n block_type='upsampling',\n activation='sigmoid',\n use_batchnorm=True):\n input = backbone.input\n # print(n_upsample_blocks)\n\n if block_type == 'transpose':\n up_block = Transpose2D_block\n else:\n up_block = Upsample2D_block\n\n if len(skip_connection_layers) > n_upsample_blocks:\n downsampling_layers = skip_connection_layers[int(len(skip_connection_layers) / 2):]\n skip_connection_layers = skip_connection_layers[:int(len(skip_connection_layers) / 2)]\n else:\n downsampling_layers = skip_connection_layers\n\n # convert layer names to indices\n skip_connection_idx = ([get_layer_number(backbone, l) if isinstance(l, str) else l\n for l in skip_connection_layers])\n skip_layers_list = [backbone.layers[skip_connection_idx[i]].output for i in range(len(skip_connection_idx))]\n downsampling_idx = ([get_layer_number(backbone, l) if isinstance(l, str) else l\n for l in downsampling_layers])\n downsampling_list = [backbone.layers[downsampling_idx[i]].output for i in range(len(downsampling_idx))]\n downterm = [None] * (n_upsample_blocks + 1)\n for i in range(len(downsampling_idx)):\n # print(downsampling_list[0])\n # print(backbone.output)\n # print(\"\")\n if downsampling_list[0] == backbone.output:\n # print(\"VGG16 should be!\")\n downterm[n_upsample_blocks - i] = downsampling_list[i]\n else:\n downterm[n_upsample_blocks - i - 1] = downsampling_list[i]\n downterm[-1] = backbone.output\n # print(\"downterm = {}\".format(downterm))\n\n interm = [None] * (n_upsample_blocks + 1) * (n_upsample_blocks + 1)\n for i in range(len(skip_connection_idx)):\n interm[-i * (n_upsample_blocks + 1) + (n_upsample_blocks + 1) * (n_upsample_blocks - 1)] = skip_layers_list[i]\n interm[(n_upsample_blocks + 1) * n_upsample_blocks] = backbone.output\n\n for j in range(n_upsample_blocks):\n for i in range(n_upsample_blocks - j):\n upsample_rate = to_tuple(upsample_rates[i])\n # print(j, i)\n\n if i == 0 and j < n_upsample_blocks - 1 and len(skip_connection_layers) < n_upsample_blocks:\n interm[(n_upsample_blocks + 1) * i + j + 1] = None\n elif j == 0:\n if downterm[i + 1] is not None:\n interm[(n_upsample_blocks + 1) * i + j + 1] = up_block(decoder_filters[n_upsample_blocks - i - 2],\n i + 1, j + 1, upsample_rate=upsample_rate,\n skip=interm[(n_upsample_blocks + 1) * i + j],\n use_batchnorm=use_batchnorm)(downterm[i + 1])\n else:\n interm[(n_upsample_blocks + 1) * i + j + 1] = None\n else:\n interm[(n_upsample_blocks + 1) * i + j + 1] = up_block(decoder_filters[n_upsample_blocks - i - 2],\n i + 1, j + 1, upsample_rate=upsample_rate,\n skip=interm[(n_upsample_blocks + 1) * i: (n_upsample_blocks + 1) * i + j + 1],\n use_batchnorm=use_batchnorm)(\n interm[(n_upsample_blocks + 1) * (i + 1) + j])\n\n x = layers.Conv2D(classes, (3, 3), padding='same', name='final_conv')(interm[n_upsample_blocks])\n x = layers.Activation(activation, name=activation)(x)\n\n model = models.Model(input, x)\n\n return model\n\n\n# ---------------------------------------------------------------------\n# Xnet Model\n# ---------------------------------------------------------------------\n\ndef Xnet(backbone_name='vgg16',\n input_shape=(None, None, 3),\n classes=1,\n activation='sigmoid',\n weights=None,\n encoder_weights='imagenet',\n encoder_freeze=False,\n encoder_features='default',\n decoder_block_type='upsampling',\n decoder_filters=(256, 128, 64, 32, 16),\n decoder_use_batchnorm=True,\n n_upsample_blocks=5,\n upsample_rates=(2, 2, 2, 2, 2),\n\n **kwargs\n ):\n \"\"\"\n Args:\n backbone_name: (str) look at list of available backbones.\n input_shape: (tuple) dimensions of input data (H, W, C)\n classes: (int) a number of classes for output\n activation: (str) one of keras activations for last model layer\n weights: optional, path to model weights.\n encoder_weights: one of `None` (random initialization),\n 'imagenet' (pre-training on ImageNet),\n 'dof' (pre-training on DoF)\n encoder_freeze: (bool) Set encoder layers weights as non-trainable. Useful for fine-tuning\n encoder_features: a list of layer numbers or names starting from top of the model.\n Each of these layers will be concatenated with corresponding decoder block. If ``default`` is used\n layer names are taken from ``DEFAULT_SKIP_CONNECTIONS``.\n decoder_block_type: (str) one of 'upsampling' and 'transpose'\n decoder_filters: (int) number of convolution layer filters in decoder blocks\n decoder_use_batchnorm: (bool) if True add batch normalisation layer between `Conv2D` ad `Activation` layers\n n_upsample_blocks: (int) a number of upsampling blocks\n upsample_rates: (tuple of int) upsampling rates decoder blocks\n\n Returns:\n ``keras.models.Model``: **Xnet**\n\n .. _Xnet:\n https://arxiv.org/pdf/1505.04597\n \"\"\"\n\n global backend, layers, models, keras_utils\n backend, layers, models, keras_utils = get_submodules_from_kwargs(kwargs)\n\n backbone = Backbones.get_backbone(backbone_name,\n input_shape=input_shape,\n weights=encoder_weights,\n include_top=False,\n **kwargs,\n )\n\n # if encoder_features == 'default':\n # encoder_features = DEFAULT_SKIP_CONNECTIONS[backbone_name]\n if encoder_features == 'default':\n encoder_features = Backbones.get_feature_layers(backbone_name, n='all')\n\n model = build_xnet(backbone=backbone,\n classes=classes,\n skip_connection_layers=encoder_features,\n decoder_filters=decoder_filters,\n block_type=decoder_block_type,\n activation=activation,\n n_upsample_blocks=n_upsample_blocks,\n upsample_rates=upsample_rates,\n use_batchnorm=decoder_use_batchnorm)\n\n # lock encoder weights for fine-tuning\n if encoder_freeze:\n freeze_model(backbone, **kwargs)\n\n # loading model weights\n if weights is not None:\n model.load_weights(weights)\n\n return model\n" ]
[ [ "numpy.isscalar" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
adamchang2000/DenseFusion
[ "6e9f3b1598e8e4a627ca18bbad8440059ef8063f" ]
[ "datasets/customCAD/mask_generator.py" ]
[ "import os\nimport cv2\nimport numpy as np\n\nclass UnityMaskGenerator:\n def __init__(self, root):\n self.root = root\n assert(os.path.isdir(root))\n assert(os.path.isdir(os.path.join(root, \"data\")))\n def generate_masks(self):\n data_dir = os.path.join(self.root, \"data\")\n for obj_dir in os.listdir(data_dir):\n depth_dir = os.path.join(self.root, \"data\", obj_dir, \"depth\") \n mask_dir = os.path.join(self.root, \"data\", obj_dir, \"mask\")\n\n for image_file in os.listdir(depth_dir):\n\n print('generating mask for', image_file)\n\n img = cv2.imread(os.path.join(depth_dir, image_file), cv2.IMREAD_UNCHANGED)\n a = np.where(img != np.max(img))\n if (np.sum(a) > 0):\n bbox = np.array([[np.min(a[0]), np.min(a[1])], [np.max(a[0]), np.max(a[1])]])\n else:\n bbox = np.zeros((2,2)).astype(np.int64)\n \n mask = np.zeros(img.shape).astype(np.uint16)\n mask[bbox[0][0]:bbox[1][0],bbox[0][1]:bbox[1][1]] = 65535\n\n output_filename = os.path.join(mask_dir, image_file[-8:])\n cv2.imwrite(output_filename, mask)\n\ndef main():\n umg = UnityMaskGenerator('dataset_processed')\n umg.generate_masks()\n\nif __name__ == '__main__':\n main()" ]
[ [ "numpy.max", "numpy.zeros", "numpy.sum", "numpy.min" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xw931018/lrw_data_preprocesing
[ "54faacfd53143a3e751ed03a5ea4226aaad92168" ]
[ "util_lip_data.py" ]
[ "\"\"\"\nUtility functions for landmark-based human action recognition using path signatures\n\"\"\"\n\nimport requests\n\nimport cv2\nfrom moviepy.editor import VideoFileClip, clips_array\nimport numpy as np\nfrom tqdm.notebook import tqdm\n\ndef download(source_url, target_filename, chunk_size=1024):\n \"\"\"\n Download a file via HTTP.\n\n Parameters\n ----------\n source_url: str\n URL of the file to download\n target_filename: str\n Target filename\n chunk_size: int\n Chunk size\n \"\"\"\n response = requests.get(source_url, stream=True)\n file_size = int(response.headers['Content-Length'])\n\n with open(target_filename, 'wb') as handle:\n for data in tqdm(response.iter_content(chunk_size=chunk_size),\n total=int(file_size / chunk_size), unit='KB',\n desc='Downloading dataset:'):\n handle.write(data)\n\nclass SkeletonFace():\n \"\"\"\n Skeleton representation for visualisation and animation consisting of dots\n representing landmarks and lines representing connections.\n \"\"\"\n\n # When transforming key points, use a fraction of the image size as a minimum of empty,\n # black region around the skeleton\n IMG_BORDER_FRAC = 0.1\n\n def __init__(self,\n target_width,\n target_height,\n radius=10,\n confidence_coord=None,\n transform_keypoints=False,\n n_points_per_image = 68):\n \"\"\"\n Parameters\n ----------\n target_width: int\n Image width for visualisation\n target_height: int\n Image height for visualisation\n radius: int\n Landmark radius\n confidence_coord: int\n Index of confidence estimates\n draw_connections: bool\n Whether to draw connections between the key points\n transform_keypoints: bool\n Whether to transform key points\n \"\"\"\n self.n_points_per_image = n_points_per_image\n self.landmarks = [(226, 0, 255)] * 17 + [(155, 0, 255)] * 5 + [(198, 0, 255)] * 5 + [(70, 0, 255)] * 4 + \\\n [(141, 255, 0)] * 5 + [(99, 255, 0)] * 6 + [(127, 0, 255)] * 6 + [(255, 42, 0)] * 12 + \\\n [(255, 113, 0)] * 8\n \n self.radius = radius\n self.confidence_coord = confidence_coord\n self.target_width = target_width\n self.target_height = target_height\n self.transform_keypoints = transform_keypoints\n\n def draw(self, keypoints):\n\n \"\"\"\n Plot a static keypoint image.\n\n Parameters\n ----------\n keypoints: numpy array\n Keypoints to be drawn\n \"\"\"\n img = np.zeros((self.target_height, self.target_width, 3), dtype=np.uint8)\n\n keypoints = keypoints[:, 0:2].copy()\n if self.transform_keypoints:\n keypoints = self._transform_keypoints(keypoints)\n\n keypoints = np.around(keypoints).astype(np.int32)\n\n self._draw_landmarks(keypoints, img)\n\n return img\n\n def _draw_landmarks(self, keypoints, img):\n for i, colour in enumerate(self.landmarks[0:self.n_points_per_image]):\n # Skip points with confidence 0 (usually means not detected)\n if self.confidence_coord is not None and keypoints[i, self.confidence_coord] == 0:\n continue\n point = tuple(keypoints[i])\n if point[0] != 0 or point[1] != 0:\n cv2.circle(img, point[0:2], self.radius, colour, -1)\n\n def _transform_keypoints(self, keypoints):\n keypoints -= np.amin(keypoints, axis=0)\n keypoint_scale = np.amax(keypoints, axis=0)\n keypoints *= np.array((self.target_width, self.target_height)) * (\n 1 - 2 * SkeletonFace.IMG_BORDER_FRAC) / keypoint_scale\n keypoints += np.array((self.target_width, self.target_height)) * SkeletonFace.IMG_BORDER_FRAC\n\n return keypoints\n\n def animate(self, keypoints, filename=None, fps=25, codec='XVID'):\n \"\"\"\n Convert key points to a animation and output to a video file.\n\n Parameters\n ----------\n keypoints: numpy array\n Array of keypoints in the form [frame,landmark,coords]\n filename: string, optional (default is None)\n If given the video is saved to the specified file\n fps: float\n Number of frames per second\n codec: str\n Video codec represented in fourcc format\n \"\"\"\n if filename is not None:\n fourcc = cv2.VideoWriter_fourcc(*codec)\n vid_file = cv2.VideoWriter(filename, fourcc, fps,\n (self.target_width, self.target_height))\n\n vid = np.zeros((keypoints.shape[0], self.target_height, self.target_width, 3),\n dtype=np.uint8)\n\n for i in range(vid.shape[0]):\n vid[i] = self.draw(keypoints[i])\n if filename is not None:\n frame = cv2.cvtColor(vid[i], cv2.COLOR_RGB2BGR)\n vid_file.write(frame)\n if filename is not None:\n vid_file.release()\n\n return vid\n\ndef generate_one_clip(keypoints, clip_height=768, display_height=240,\n temp_file='__temp__.avi', word = '', transform_keypoints = False):\n \"\"\"\n Display a side-by-side animation comprising the skeleton and (optionally) the source\n video.\n\n Parameters\n ----------\n keypoints : numpy array\n Array of keypoints in the form [frame,landmark,coords]\n clip_height : int\n Desired clip height (applies to both source video and skeleton, the former is upscaled)\n display_height : int\n Desired display height\n temp_file : int\n Temporary file for transcoding\n include_source_video: bool\n Whether to include the source video\n word: str,\n The word that the person says\n \"\"\"\n keypoints = np.copy(keypoints) \n rescaling_factor = clip_height/display_height\n keypoints = keypoints * rescaling_factor\n n_points_per_image = len(keypoints[0])\n \n #duration = 1\n skeleton = SkeletonFace(target_width=clip_height, target_height=clip_height, transform_keypoints = transform_keypoints,\n n_points_per_image = n_points_per_image)\n skeleton.animate(keypoints, temp_file, )#fps=len(keypoints)/duration)\n \n clip_skeleton = VideoFileClip(temp_file)\n \n return clip_skeleton\n\ndef display_animation_multiple_faces(keypoints_array, clip_height=768, display_height=240,\n temp_file='__temp__.avi', word = '', transform_keypoints = False):\n clip_list = []\n for i, keypoints in enumerate(keypoints_array):\n clip = generate_one_clip(keypoints, clip_height = clip_height, display_height = display_height,\n temp_file = temp_file.replace('__.', '__{}.'.format(i)), word = word,\n transform_keypoints = transform_keypoints)\n clip_list.append(clip)\n clip_final = clips_array([clip_list])\n return clip_final.ipython_display(height=display_height, rd_kwargs=dict(logger=None)) \n\ndef display_animation_face(keypoints, clip_height=768, display_height=240,\n temp_file='__temp__.avi', word = '', transform_keypoints = False):\n \"\"\"\n Display a side-by-side animation comprising the skeleton and (optionally) the source\n video.\n\n Parameters\n ----------\n keypoints : numpy array\n Array of keypoints in the form [frame,landmark,coords]\n clip_height : int\n Desired clip height (applies to both source video and skeleton, the former is upscaled)\n display_height : int\n Desired display height\n temp_file : int\n Temporary file for transcoding\n include_source_video: bool\n Whether to include the source video\n word: str,\n The word that the person says\n \"\"\"\n\n if len(word) > 0:\n print(word)\n clip = generate_one_clip(keypoints, clip_height = clip_height, display_height = display_height,\n temp_file = temp_file, word = word, \n transform_keypoints = transform_keypoints)\n\n return clip.ipython_display(height=display_height, rd_kwargs=dict(logger=None))\n" ]
[ [ "numpy.amax", "numpy.amin", "numpy.around", "numpy.copy", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HardPlant/gym-js
[ "932a3780d784fb6524e1bdd0a413671f39b788ca" ]
[ "gym/0.dummy.py" ]
[ "import numpy as np\nimport random as pr\nimport matplotlib.pyplot as plt\n\nimport gym\nfrom gym.envs.registration import register\n\n\ndef rargmax(vector):\n # 가장 큰 값 중 랜덤하게 반환\n m = np.amax(vector)\n indices = np.nonzero(vector == m)[0]\n return pr.choice(indices)\n\nregister(\n id=\"FrozenLake-v3\",\n entry_point=\"gym.envs.toy_text:FrozenLakeEnv\",\n kwargs={\"map_name\" : \"4x4\", \"is_slippery\" : False}\n)\n\nenv = gym.make(\"FrozenLake-v3\")\nobservation = env.reset()\n\n# table to wzro\nQ = np.zeros([env.observation_space.n, env.action_space.n])\nnum_episodes = 2000\n\n# 모든 결과의 저장\nrList = []\nfor i in range(num_episodes):\n state = env.reset()\n rAll = 0\n done = False\n\n while not done:\n action = rargmax(Q[state, :])\n #state, reward, done, info\n new_state, reward, done, _ = env.step(action)\n\n # Q table 추가\n Q[state, action] = reward + np.max(Q[new_state, :])\n\n rAll += reward\n state = new_state\n \n rList.append(rAll)\n\n#print\n\nprint(\"Success rate: \" + str(sum(rList)/num_episodes))\nprint(\"Final Q-Table Values\")\nprint(\"Left Down Right Up\")\nprint(Q)\n\nplt.bar(range(len(rList)), rList, color=\"blue\")\nplt.show()" ]
[ [ "numpy.amax", "numpy.nonzero", "numpy.max", "matplotlib.pyplot.show", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MagazzuGaetano/Weather-Classifier
[ "2bfac1918eea4aaa37563ef4ffabdc290e411d76" ]
[ "models/ResNet.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n def __init__(self, in_channels, out_channels, i_downsample=None, stride=1):\n super(Bottleneck, self).__init__()\n \n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\n self.batch_norm1 = nn.BatchNorm2d(out_channels)\n \n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1)\n self.batch_norm2 = nn.BatchNorm2d(out_channels)\n \n self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0)\n self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion)\n \n self.i_downsample = i_downsample\n self.stride = stride\n self.relu = nn.ReLU()\n \n def forward(self, x):\n identity = x.clone()\n x = self.relu(self.batch_norm1(self.conv1(x)))\n \n x = self.relu(self.batch_norm2(self.conv2(x)))\n \n x = self.conv3(x)\n x = self.batch_norm3(x)\n \n #downsample if needed\n if self.i_downsample is not None:\n identity = self.i_downsample(identity)\n #add identity\n x+=identity\n x=self.relu(x)\n \n return x\n\nclass Block(nn.Module):\n expansion = 1\n def __init__(self, in_channels, out_channels, i_downsample=None, stride=1):\n super(Block, self).__init__()\n \n\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False)\n self.batch_norm1 = nn.BatchNorm2d(out_channels)\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False)\n self.batch_norm2 = nn.BatchNorm2d(out_channels)\n\n self.i_downsample = i_downsample\n self.stride = stride\n self.relu = nn.ReLU()\n\n def forward(self, x):\n identity = x.clone()\n\n x = self.relu(self.batch_norm2(self.conv1(x)))\n x = self.batch_norm2(self.conv2(x))\n\n if self.i_downsample is not None:\n identity = self.i_downsample(identity)\n print(x.shape)\n print(identity.shape)\n x += identity\n x = self.relu(x)\n return x\n\n\nclass ResNet(nn.Module):\n def __init__(self, ResBlock, layer_list, num_classes, num_channels=3):\n super(ResNet, self).__init__()\n self.in_channels = 64\n\n self.conv1 = nn.Conv2d(num_channels, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.batch_norm1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU()\n self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1)\n self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64)\n self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2)\n \n self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2)\n self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2)\n \n self.avgpool = nn.AdaptiveAvgPool2d((1,1))\n self.fc = nn.Linear(512*ResBlock.expansion, num_classes)\n\n def forward(self, x):\n x = self.relu(self.batch_norm1(self.conv1(x)))\n x = self.max_pool(x)\n \n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n \n x = self.avgpool(x)\n x = x.reshape(x.shape[0], -1)\n x = self.fc(x)\n \n return x\n\n def _make_layer(self, ResBlock, blocks, planes, stride=1):\n ii_downsample = None\n layers = []\n \n if stride != 1 or self.in_channels != planes*ResBlock.expansion:\n ii_downsample = nn.Sequential(\n nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride),\n nn.BatchNorm2d(planes*ResBlock.expansion)\n )\n \n layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride))\n self.in_channels = planes*ResBlock.expansion\n \n for i in range(blocks-1):\n layers.append(ResBlock(self.in_channels, planes))\n \n return nn.Sequential(*layers)\n\ndef ResNet50(num_classes, channels=3):\n return ResNet(Bottleneck, [3,4,6,3], num_classes, channels)\n\ndef ResNet101(num_classes, channels=3):\n return ResNet(Bottleneck, [3,4,23,3], num_classes, channels)\n\ndef ResNet152(num_classes, channels=3):\n return ResNet(Bottleneck, [3,8,36,3], num_classes, channels)\n\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.Linear", "torch.nn.AdaptiveAvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vitorgt/SCC0251
[ "0f39e9da8ae9862c5b97afe308b48ed2948714e9" ]
[ "a01/submission/a01.py" ]
[ "# # Assignment 1: Intensity Transformations\n# ## SCC0251.2020.1 - Image Processing\n# ### Prof. Dr. Moacir Ponti\n# ### 10284952 - Vitor Gratiere Torres\n# https://github.com/vitorgt/SCC0251\n\n# Imports\nimport numpy as np\nimport imageio\n# import matplotlib.pyplot as plt\n\n\n# Transformation functions\n# Formulae described on assignment's pdf only translated to python\ndef t1(image):\n return (255 - image)\n\n\ndef t2(image):\n a = np.min(r)\n b = np.max(r)\n c = int(input())\n d = int(input())\n return (image-a)*((d-c)/(b-a))+c\n\n\ndef t3(image):\n image = image.astype(np.int32)\n return 255*(np.log2(1+image)/np.log2(1+np.max(image)))\n\n\ndef t4(image):\n W = int(input())\n l = float(input())\n return W*(image**l)\n\n\n# Root Squared Error function\ndef rse(r, m):\n return np.sqrt(np.sum((m.astype(np.float)-r.astype(np.float))**2))\n\n\n# Inputs, following assignment's pdf requested sequence\nr = imageio.imread(str(input()).rstrip()).astype(np.uint8)\nm = int(input())\ns = (False, True)[int(input())]\n# Note on 's': that is an if. If it's inputted a '0', 's' receives the 0th position of tuple (False, True), as so for '1'.\n\n# Dictionary for functions based on method input\nt = {1: t1, 2: t2, 3: t3, 4: t4}\n\n# Appling 'm' transformation to original image 'r'\n# Storing back on 'm'\nm = t[m](r)\n\n# Calculating RSE and printing\nprint(\"{:.4f}\".format(rse(r, m)))\n\n# Saving\nif s:\n imageio.imwrite(\"output_img.png\", m)\n\n# Plotting\n# plt.figure(figsize=(20,20))\n\n# plt.subplot(121)\n# plt.imshow(r, cmap=\"gray\")\n# plt.axis('off')\n\n# plt.subplot(122)\n# plt.imshow(m.astype(np.uint8), cmap=\"gray\")\n# plt.axis('off')\n" ]
[ [ "numpy.max", "numpy.log2", "numpy.min" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]