code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
"""Main module """ # Standard library imports import string # Third party imports import numpy as np import justpy as jp import pandas as pd START_INDEX: int = 1 END_INDEX: int = 20 GRID_OPTIONS = """ { class: 'ag-theme-alpine', defaultColDef: { filter: true, sortable: false, resizable: true, headerClass: 'font-bold', editable: true }, rowSelection: 'single', } """ def on_input_key(self, msg): """On input key event. Update the clicked cell with the new value from the input field. Args: msg (object): Event data object. """ if self.last_cell is not None: self.grid.options['rowData'][self.last_cell['row'] ][self.last_cell['col']] = msg.value def on_cell_clicked(self, msg): """On cell clicked event. Update the cell label value with the coordinates of the cell and set the value of the cell in the input field. Args: msg (object): Event data object. """ self.cell_label.value = msg.colId + str(msg.rowIndex) self.input_field.value = msg.data[msg.colId] self.input_field.last_cell = {"row": msg.rowIndex, "col": msg.colId} self.last_row = msg.row def on_cell_value_changed(self, msg): """On input key event. Update the input field value to match the cell value. Args: msg (object): Event data object. """ self.input_field.value = msg.data[msg.colId] def grid_test(): """Grid test app. """ headings = list(string.ascii_uppercase) index = np.arange(START_INDEX, END_INDEX) data_frame = pd.DataFrame(index=index, columns=headings) data_frame = data_frame.fillna('') # data = np.array([np.arange(10)]*3).T # css_values = """ # .ag-theme-alpine .ag-ltr .ag-cell { # border-right: 1px solid #aaa; # } # .ag-theme-balham .ag-ltr .ag-cell { # border-right: 1px solid #aaa; # } # """ web_page = jp.WebPage() root_div = jp.Div(classes='q-pa-md', a=web_page) in_root_div = jp.Div(classes='q-gutter-md', a=root_div) cell_label = jp.Input( a=in_root_div, style='width: 32px; margin-left: 16px', disabled=True) input_field = jp.Input(classes=jp.Styles.input_classes, a=in_root_div, width='32px') input_field.on("input", on_input_key) input_field.last_cell = None grid = jp.AgGrid(a=web_page, options=GRID_OPTIONS) grid.load_pandas_frame(data_frame) grid.options.pagination = True grid.options.paginationAutoPageSize = True grid.cell_label = cell_label grid.input_field = input_field grid.on('cellClicked', on_cell_clicked) grid.on('cellValueChanged', on_cell_value_changed) input_field.grid = grid return web_page def main(): """Main app. """ jp.justpy(grid_test) if __name__ == "__main__": main()
[ "justpy.WebPage", "justpy.justpy", "justpy.Input", "justpy.Div", "pandas.DataFrame", "justpy.AgGrid", "numpy.arange" ]
[((1576, 1609), 'numpy.arange', 'np.arange', (['START_INDEX', 'END_INDEX'], {}), '(START_INDEX, END_INDEX)\n', (1585, 1609), True, 'import numpy as np\n'), ((1628, 1671), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'index', 'columns': 'headings'}), '(index=index, columns=headings)\n', (1640, 1671), True, 'import pandas as pd\n'), ((1985, 1997), 'justpy.WebPage', 'jp.WebPage', ([], {}), '()\n', (1995, 1997), True, 'import justpy as jp\n'), ((2014, 2051), 'justpy.Div', 'jp.Div', ([], {'classes': '"""q-pa-md"""', 'a': 'web_page'}), "(classes='q-pa-md', a=web_page)\n", (2020, 2051), True, 'import justpy as jp\n'), ((2070, 2111), 'justpy.Div', 'jp.Div', ([], {'classes': '"""q-gutter-md"""', 'a': 'root_div'}), "(classes='q-gutter-md', a=root_div)\n", (2076, 2111), True, 'import justpy as jp\n'), ((2129, 2207), 'justpy.Input', 'jp.Input', ([], {'a': 'in_root_div', 'style': '"""width: 32px; margin-left: 16px"""', 'disabled': '(True)'}), "(a=in_root_div, style='width: 32px; margin-left: 16px', disabled=True)\n", (2137, 2207), True, 'import justpy as jp\n'), ((2235, 2305), 'justpy.Input', 'jp.Input', ([], {'classes': 'jp.Styles.input_classes', 'a': 'in_root_div', 'width': '"""32px"""'}), "(classes=jp.Styles.input_classes, a=in_root_div, width='32px')\n", (2243, 2305), True, 'import justpy as jp\n'), ((2420, 2463), 'justpy.AgGrid', 'jp.AgGrid', ([], {'a': 'web_page', 'options': 'GRID_OPTIONS'}), '(a=web_page, options=GRID_OPTIONS)\n', (2429, 2463), True, 'import justpy as jp\n'), ((2845, 2865), 'justpy.justpy', 'jp.justpy', (['grid_test'], {}), '(grid_test)\n', (2854, 2865), True, 'import justpy as jp\n')]
import logging import json import glob import pandas as pd import multiprocessing import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report from sklearn.model_selection import GridSearchCV, KFold from sklearn.model_selection import cross_val_predict from sklearn.decomposition import IncrementalPCA from scipy.stats import spearmanr import config from util import * np.random.seed(config.RANDOM_SEED) repo_lang = Repository_language() def store_classification_result(model_name, language, model_classification_report, classification_results): """ Stores the result of the classifier :param model_name: the classification type :param language: programming language :param model_classification_report: results :param classification_results: results """ open('{}classification_result_raw_{}_{}.txt'.format(config.PREDICTION_RESULT_PATH, model_name, language), 'w')\ .write(model_classification_report) open('{}classification_result_json_{}_{}.json'.format(config.PREDICTION_RESULT_PATH, model_name, language), 'w')\ .write(json.dumps(classification_results)) def data_classification_wo_cv(language, repo, data_train, label_train, data_test, label_test, random_seed=config.RANDOM_SEED, job_num=multiprocessing.cpu_count()): """ Trains the classifier :param language: programming language :param data: input data :param label: input labels :param random_seed: the random_seed :param job_num: the number of cores to use """ # CV inner_cv = KFold(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed) outer_cv = KFold(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed) # Hyper-parameters tree_param = {'min_samples_leaf': config.MIN_SAMPLE_LEAVES, 'min_samples_split': config.MIN_SAMPLE_SPLIT, 'max_depth': config.TREE_MAX_DEPTH} forest_param = {'n_estimators': config.ESTIMATOR_NUM, 'min_samples_leaf': config.MIN_SAMPLE_LEAVES, 'min_samples_split': config.MIN_SAMPLE_SPLIT} boosting_param = {'n_estimators': config.ESTIMATOR_NUM, 'learning_rate': config.LEARNING_RATE} # Grid search definition grid_searches = [ GridSearchCV(DecisionTreeClassifier(class_weight='balanced', random_state = random_seed), tree_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION) , GridSearchCV(RandomForestClassifier(class_weight='balanced', n_jobs=job_num, random_state=random_seed), forest_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION) , GridSearchCV(ExtraTreesClassifier(n_jobs=job_num, class_weight='balanced', random_state=random_seed), forest_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION), GridSearchCV(AdaBoostClassifier(base_estimator=DecisionTreeClassifier(class_weight = 'balanced', random_state=random_seed, max_depth=2), algorithm='SAMME.R', random_state=random_seed), boosting_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION) ] # Fitting the classifiers classification_results = {} res = [] for model in grid_searches: # Model training/testing model.score_sample_weight = True model.fit(data_train, label_train) model_name = str(type(model.best_estimator_)).replace('<class \'', '').replace('\'>', '').split('.')[-1] model_best_param = model.best_params_ predicted_label = model.best_estimator_.predict(data_test) t = get_metrics(label_test, predicted_label) t['model_name'] = model_name t['language'] = language t['repository'] = repo res.append(t) return res def data_classification(language, data, label, random_seed=config.RANDOM_SEED, job_num=multiprocessing.cpu_count()): """ Trains the classifier :param language: programming language :param data: input data :param label: input labels :param random_seed: the random_seed :param job_num: the number of cores to use """ # CV inner_cv = KFold(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed) outer_cv = KFold(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed) # Hyper-parameters tree_param = {'min_samples_leaf': config.MIN_SAMPLE_LEAVES, 'min_samples_split': config.MIN_SAMPLE_SPLIT, 'max_depth': config.TREE_MAX_DEPTH} forest_param = {'n_estimators': config.ESTIMATOR_NUM, 'min_samples_leaf': config.MIN_SAMPLE_LEAVES, 'min_samples_split': config.MIN_SAMPLE_SPLIT} boosting_param = {'n_estimators': config.ESTIMATOR_NUM, 'learning_rate': config.LEARNING_RATE} # Grid search definition grid_searches = [ GridSearchCV(DecisionTreeClassifier(class_weight='balanced', random_state = random_seed), tree_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION), GridSearchCV(RandomForestClassifier(class_weight='balanced', n_jobs=job_num, random_state = random_seed), forest_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION), GridSearchCV(ExtraTreesClassifier(n_jobs=job_num, class_weight='balanced', random_state = random_seed), forest_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION), GridSearchCV(AdaBoostClassifier(base_estimator=DecisionTreeClassifier(class_weight = 'balanced', random_state = random_seed, max_depth=2), algorithm='SAMME.R', random_state=random_seed), boosting_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION) ] # Fitting the classifiers classification_results = {} for model in grid_searches: # Model training/testing model.score_sample_weight = True model.fit(data, label) model_name = str(type(model.best_estimator_)).replace('<class \'', '').replace('\'>', '').split('.')[-1] model_best_param = model.best_params_ predicted_label = cross_val_predict(model.best_estimator_, X=data, y=label, cv=outer_cv, n_jobs=job_num) model_accuracy = accuracy_score(label, predicted_label) model_confusion_matrix = confusion_matrix(label, predicted_label) model_classification_report = classification_report(label, predicted_label) classification_results[model_name] = {} classification_results[model_name]['best_params'] = model_best_param classification_results[model_name]['accuracy'] = model_accuracy classification_results[model_name]['confusion_matrix'] = model_confusion_matrix.tolist() classification_results[model_name]['classification_report'] = model_classification_report print(model_classification_report) ## Save the classification result #store_classification_result(model_name, language, model_classification_report, classification_results) def get_best_decision_tree(data, label, random_seed=config.RANDOM_SEED, job_num=multiprocessing.cpu_count()): """ Trains the best decision tree :param data: the data :param label: the labels :param random_seed: the random seed :param job_num: :return: the number of cores to use """ # CV inner_cv = KFold(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed) # Train/test tree_param = {'min_samples_leaf': config.MIN_SAMPLE_LEAVES, 'min_samples_split': config.MIN_SAMPLE_SPLIT, 'max_depth': config.TREE_MAX_DEPTH} grid_search = GridSearchCV(DecisionTreeClassifier(class_weight='balanced', random_state=random_seed), tree_param, cv=inner_cv, n_jobs=job_num, scoring=config.SCORING_FUNCTION) grid_search.score_sample_weight = True grid_search.fit(data, label) return grid_search.best_estimator_ def get_feature_importance_by_model(model): """ Returns the features importance of a model :param model: the classifier :return: The list of feature importance """ return model.feature_importances_ def get_feature_set(data): """ Returns the feature sets separately :param data: The input data """ # Data separation of feature sets parallel_changes = data[:, 0].reshape(-1, 1) commit_num = data[:, 1].reshape(-1, 1) commit_density = data[:, 2].reshape(-1, 1) file_edits = IncrementalPCA(n_components=1).fit_transform(data[:, 3:8]) line_edits = IncrementalPCA(n_components=1).fit_transform(data[:, 8:10]) dev_num = data[:, 10].reshape(-1, 1) keywords = IncrementalPCA(n_components=1).fit_transform(data[:, 11:23]) message = IncrementalPCA(n_components=1).fit_transform(data[:, 23:27]) duration = data[:, 27].reshape(-1, 1) feature_sets = ['prl_changes', 'commit_num', 'commit_density', 'file_edits', 'line_edits', 'dev_num', 'keywords', 'message', 'duration'] return feature_sets, parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords\ , message, duration def save_feature_correlation(language, data, label): """ Store the feature correlation of the data with the label :param language: the programming language :param data: the data :param label: the label """ feature_sets, parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message\ , duration = get_feature_set(data) features = [parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message , duration] for i, feature in enumerate(features): corr, p_value = spearmanr(feature, label) open('{}feature_correlation_{}.txt'.format(config.PREDICTION_RESULT_PATH, language), 'a') \ .write('{}:\t\t{} \t {}\n'.format(feature_sets[i], round(corr, 2), round(p_value, 2))) def save_feature_correlation_dict(data, label): """ Store the feature correlation of the data with the label :param data: the data :param label: the label """ feature_sets = ['prl_changes', 'commit_num', 'commit_density', 'file_edits', 'line_edits', 'dev_num', 'keywords', 'message', 'duration'] feature_sets, parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message\ , duration = get_feature_set(data) features = [parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message , duration] correlation = {} try: for i, feature in enumerate(features): corr, p_value = spearmanr(feature, label) correlation[feature_sets[i] + '_corr'] = corr correlation[feature_sets[i] + '_p_value'] = p_value except: pass finally: return correlation def save_feature_importance(repo_name, data, label): """ Store the feature importance :param language: the programming language :param data: the data :param label: the label """ data = data.values feature_sets, parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message, duration \ = get_feature_set(data) feature_data = np.concatenate((parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message, duration), axis=1) return get_feature_importance_by_model(get_best_decision_tree(feature_data, label)) def baseline_classification(language, data, label): """ Classify the baseline data (parallel changed files) :param language: The programming language :param data: The data :param label: The labels """ feature_sets, parallel_changes, commit_num, commit_density, file_edits, line_edits, dev_num, keywords, message \ , duration = get_feature_set(data) language = language + '__baseline' data_classification(language, parallel_changes, label) ############################################ ############################################ from sklearn import metrics import autosklearn.classification from sklearn.svm import SVC def get_metrics(label_test, predicted_labels): result = {} result['roc_curve'] = metrics.roc_curve(label_test, predicted_labels) result['confusion_matrix'] = metrics.confusion_matrix(label_test, predicted_labels) result['classification_report'] = metrics.classification_report(label_test, predicted_labels) result['accuracy_score'] = metrics.accuracy_score(label_test, predicted_labels) result['roc_auc_score'] = metrics.roc_auc_score(label_test, predicted_labels) result['precision_score_conflict'] = metrics.precision_score(label_test, predicted_labels) result['precision_score_not_conflict'] = metrics.precision_score(label_test, predicted_labels,pos_label=0) result['precision_score_average'] = metrics.precision_score(label_test, predicted_labels, average='weighted') result['recall_score_conflict'] = metrics.recall_score(label_test, predicted_labels) result['recall_score_not_conflict'] = metrics.recall_score(label_test, predicted_labels,pos_label=0) result['recall_score_average'] = metrics.recall_score(label_test, predicted_labels, average='weighted') result['f1_score_conflict'] = metrics.f1_score(label_test, predicted_labels) result['f1_score_not_conflict'] = metrics.f1_score(label_test, predicted_labels,pos_label=0) result['f1_score_average'] = metrics.f1_score(label_test, predicted_labels, average='weighted') result['conflict_rate'] = len([i for i in label_test if i == 1]) / len(label_test) return result def get_decision_tree_result(data_train, label_train, data_test, label_test): clf = DecisionTreeClassifier(class_weight='balanced').fit(data_train, label_train) predicted_labels = clf.predict(data_test) return get_metrics(label_test, predicted_labels) def get_random_forest_result(data_train, label_train, data_test, label_test): clf = RandomForestClassifier(class_weight='balanced').fit(data_train, label_train) predicted_labels = clf.predict(data_test) return get_metrics(label_test, predicted_labels) def get_svm_result(data_train, label_train, data_test, label_test): clf = SVC(C=1.0, kernel='linear', class_weight='balanced').fit(data_train, label_train) predicted_labels = clf.predict(data_test) return get_metrics(label_test, predicted_labels) def get_auto_scikit_result(data_train, label_train, data_test, label_test): automl = autosklearn.classification.AutoSklearnClassifier( time_left_for_this_task= 60 * 60, per_run_time_limit=300, tmp_folder='/tmp/autosklearn_sequential_example_tmp1111', output_folder='/tmp/autosklearn_sequential_example_out1111', ) automl.fit(data_train, label_train, metric=autosklearn.metrics.roc_auc) predicted_labels = automl.predict(data_test) result = get_metrics(label_test, predicted_labels) result['show_models'] = automl.show_models() result['sprint_statistics'] = automl.sprint_statistics() return result if __name__ == "__main__": # Logging logging.basicConfig(level=logging.INFO, format='%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s', datefmt='%y-%m-%d %H:%M:%S') logging.info('Train/test of merge conflict prediction') # Data classification data_files = glob.glob(config.PREDICTION_CSV_PATH + 'data_*') label_files = glob.glob(config.PREDICTION_CSV_PATH + 'label_*') repos_set = [files.split('/')[-1].split('_')[3].replace('.csv', '') for files in data_files] classification_result = [] feature_importance = [] languages = [] corr = [] for ind, data_path in enumerate(data_files): data_tmp = pd.read_csv(data_path).sort_values(by=['merge_commit_date']) label_tmp = pd.read_csv(data_path.replace('data_prediction', 'label_prediction')).sort_values(by=['merge_commit_date']) data_tmp = data_tmp.drop('merge_commit_date', axis=1) label_tmp = label_tmp.drop('merge_commit_date', axis=1) # Correlation try: tmp_corr = save_feature_correlation_dict(data_tmp.to_numpy(), label_tmp.to_numpy()) if len(tmp_corr) > 0: tmp_corr['langugae'] = repo_lang.get_lang(repos_set[ind].lower()) tmp_corr['repository'] = repos_set[ind] corr.append(tmp_corr) except: pass continue train_ind = int(data_tmp.shape[0] * config.TRAIN_RATE) data_train = data_tmp.iloc[0:train_ind, :] data_test = data_tmp.iloc[train_ind:-1, :] label_train = label_tmp.iloc[0:train_ind, :]['is_conflict'].tolist() label_test = label_tmp.iloc[train_ind:-1, :]['is_conflict'].tolist() if len(label_test) != data_test.shape[0]: print('Inconsistent data: {}'.format(repos_set[ind])) continue if data_test.shape[0] < 50: print('Not enough merge scenarios: {}'.format(repos_set[ind])) continue if len(set(label_test)) != 2 or len(set(label_train)) != 2: print('One class is missed: {}'.format(repos_set[ind])) continue if len([i for i in label_test if i == 1]) < 10: print('Nor enough conflicting merge in the test batch for evaluation: {}'.format(repos_set[ind])) continue # k = k + data_tmp.shape[0] try: res = data_classification_wo_cv(repo_lang.get_lang(repos_set[ind].lower()), repos_set[ind] ,data_train, label_train, data_test, label_test) classification_result = classification_result + res feature_importance.append(save_feature_importance(repos_set[ind], data_train, label_train)) languages.append(repo_lang.get_lang(repos_set[ind].lower())) except Exception as e: print('Error - {}'.format(e)) continue corr_df = pd.DataFrame(corr) corr_df.to_csv(f'corr_{config.RANDOM_SEED}.csv') exit() # Feature importance feature_importance = pd.DataFrame(feature_importance, columns=['prl_changes', 'commit_num', 'commit_density', 'file_edits', 'line_edits', 'dev_num', 'keywords', 'message', 'duration']) feature_importance['language'] = pd.Series(languages) feature_importance['repository'] = pd.Series(repos_set) feature_importance.dropna() feature_importance.to_csv(f'feature_importance_{config.RANDOM_SEED}.csv') feature_importance_summery = feature_importance.drop('repository', axis=1).groupby('language').agg('median') feature_importance_summery.to_csv(f'feature_importance_summery_{config.RANDOM_SEED}.csv') # Classification result classification_result_df = pd.DataFrame(classification_result) classification_result_df.to_csv(f'res_{config.RANDOM_SEED}.csv')
[ "sklearn.ensemble.ExtraTreesClassifier", "pandas.read_csv", "sklearn.metrics.classification_report", "multiprocessing.cpu_count", "sklearn.metrics.roc_auc_score", "sklearn.metrics.precision_score", "sklearn.metrics.recall_score", "sklearn.metrics.roc_curve", "sklearn.model_selection.KFold", "logging.info", "json.dumps", "sklearn.tree.DecisionTreeClassifier", "numpy.random.seed", "numpy.concatenate", "pandas.DataFrame", "scipy.stats.spearmanr", "sklearn.decomposition.IncrementalPCA", "glob.glob", "sklearn.metrics.confusion_matrix", "sklearn.ensemble.RandomForestClassifier", "sklearn.model_selection.cross_val_predict", "sklearn.metrics.accuracy_score", "sklearn.svm.SVC", "logging.basicConfig", "pandas.Series", "sklearn.metrics.f1_score" ]
[((666, 700), 'numpy.random.seed', 'np.random.seed', (['config.RANDOM_SEED'], {}), '(config.RANDOM_SEED)\n', (680, 700), True, 'import numpy as np\n'), ((1547, 1574), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (1572, 1574), False, 'import multiprocessing\n'), ((1832, 1903), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'config.FOLD_NUM', 'shuffle': '(True)', 'random_state': 'random_seed'}), '(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed)\n', (1837, 1903), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((1919, 1990), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'config.FOLD_NUM', 'shuffle': '(True)', 'random_state': 'random_seed'}), '(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed)\n', (1924, 1990), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((4362, 4389), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (4387, 4389), False, 'import multiprocessing\n'), ((4647, 4718), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'config.FOLD_NUM', 'shuffle': '(True)', 'random_state': 'random_seed'}), '(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed)\n', (4652, 4718), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((4734, 4805), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'config.FOLD_NUM', 'shuffle': '(True)', 'random_state': 'random_seed'}), '(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed)\n', (4739, 4805), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((7800, 7827), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (7825, 7827), False, 'import multiprocessing\n'), ((8059, 8130), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'config.FOLD_NUM', 'shuffle': '(True)', 'random_state': 'random_seed'}), '(n_splits=config.FOLD_NUM, shuffle=True, random_state=random_seed)\n', (8064, 8130), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((12024, 12160), 'numpy.concatenate', 'np.concatenate', (['(parallel_changes, commit_num, commit_density, file_edits, line_edits,\n dev_num, keywords, message, duration)'], {'axis': '(1)'}), '((parallel_changes, commit_num, commit_density, file_edits,\n line_edits, dev_num, keywords, message, duration), axis=1)\n', (12038, 12160), True, 'import numpy as np\n'), ((13043, 13090), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13060, 13090), False, 'from sklearn import metrics\n'), ((13124, 13178), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13148, 13178), False, 'from sklearn import metrics\n'), ((13217, 13276), 'sklearn.metrics.classification_report', 'metrics.classification_report', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13246, 13276), False, 'from sklearn import metrics\n'), ((13309, 13361), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13331, 13361), False, 'from sklearn import metrics\n'), ((13392, 13443), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13413, 13443), False, 'from sklearn import metrics\n'), ((13486, 13539), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13509, 13539), False, 'from sklearn import metrics\n'), ((13585, 13651), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['label_test', 'predicted_labels'], {'pos_label': '(0)'}), '(label_test, predicted_labels, pos_label=0)\n', (13608, 13651), False, 'from sklearn import metrics\n'), ((13691, 13764), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['label_test', 'predicted_labels'], {'average': '"""weighted"""'}), "(label_test, predicted_labels, average='weighted')\n", (13714, 13764), False, 'from sklearn import metrics\n'), ((13804, 13854), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (13824, 13854), False, 'from sklearn import metrics\n'), ((13897, 13960), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['label_test', 'predicted_labels'], {'pos_label': '(0)'}), '(label_test, predicted_labels, pos_label=0)\n', (13917, 13960), False, 'from sklearn import metrics\n'), ((13997, 14067), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['label_test', 'predicted_labels'], {'average': '"""weighted"""'}), "(label_test, predicted_labels, average='weighted')\n", (14017, 14067), False, 'from sklearn import metrics\n'), ((14103, 14149), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['label_test', 'predicted_labels'], {}), '(label_test, predicted_labels)\n', (14119, 14149), False, 'from sklearn import metrics\n'), ((14188, 14247), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['label_test', 'predicted_labels'], {'pos_label': '(0)'}), '(label_test, predicted_labels, pos_label=0)\n', (14204, 14247), False, 'from sklearn import metrics\n'), ((14280, 14346), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['label_test', 'predicted_labels'], {'average': '"""weighted"""'}), "(label_test, predicted_labels, average='weighted')\n", (14296, 14346), False, 'from sklearn import metrics\n'), ((15967, 16131), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s"""', 'datefmt': '"""%y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s'\n , datefmt='%y-%m-%d %H:%M:%S')\n", (15986, 16131), False, 'import logging\n'), ((16174, 16229), 'logging.info', 'logging.info', (['"""Train/test of merge conflict prediction"""'], {}), "('Train/test of merge conflict prediction')\n", (16186, 16229), False, 'import logging\n'), ((16275, 16323), 'glob.glob', 'glob.glob', (["(config.PREDICTION_CSV_PATH + 'data_*')"], {}), "(config.PREDICTION_CSV_PATH + 'data_*')\n", (16284, 16323), False, 'import glob\n'), ((16342, 16391), 'glob.glob', 'glob.glob', (["(config.PREDICTION_CSV_PATH + 'label_*')"], {}), "(config.PREDICTION_CSV_PATH + 'label_*')\n", (16351, 16391), False, 'import glob\n'), ((18853, 18871), 'pandas.DataFrame', 'pd.DataFrame', (['corr'], {}), '(corr)\n', (18865, 18871), True, 'import pandas as pd\n'), ((18987, 19158), 'pandas.DataFrame', 'pd.DataFrame', (['feature_importance'], {'columns': "['prl_changes', 'commit_num', 'commit_density', 'file_edits', 'line_edits',\n 'dev_num', 'keywords', 'message', 'duration']"}), "(feature_importance, columns=['prl_changes', 'commit_num',\n 'commit_density', 'file_edits', 'line_edits', 'dev_num', 'keywords',\n 'message', 'duration'])\n", (18999, 19158), True, 'import pandas as pd\n'), ((19208, 19228), 'pandas.Series', 'pd.Series', (['languages'], {}), '(languages)\n', (19217, 19228), True, 'import pandas as pd\n'), ((19268, 19288), 'pandas.Series', 'pd.Series', (['repos_set'], {}), '(repos_set)\n', (19277, 19288), True, 'import pandas as pd\n'), ((19666, 19701), 'pandas.DataFrame', 'pd.DataFrame', (['classification_result'], {}), '(classification_result)\n', (19678, 19701), True, 'import pandas as pd\n'), ((1375, 1409), 'json.dumps', 'json.dumps', (['classification_results'], {}), '(classification_results)\n', (1385, 1409), False, 'import json\n'), ((6818, 6908), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['model.best_estimator_'], {'X': 'data', 'y': 'label', 'cv': 'outer_cv', 'n_jobs': 'job_num'}), '(model.best_estimator_, X=data, y=label, cv=outer_cv,\n n_jobs=job_num)\n', (6835, 6908), False, 'from sklearn.model_selection import cross_val_predict\n'), ((6930, 6968), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['label', 'predicted_label'], {}), '(label, predicted_label)\n', (6944, 6968), False, 'from sklearn.metrics import accuracy_score\n'), ((7002, 7042), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['label', 'predicted_label'], {}), '(label, predicted_label)\n', (7018, 7042), False, 'from sklearn.metrics import confusion_matrix\n'), ((7081, 7126), 'sklearn.metrics.classification_report', 'classification_report', (['label', 'predicted_label'], {}), '(label, predicted_label)\n', (7102, 7126), False, 'from sklearn.metrics import classification_report\n'), ((8344, 8417), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""', 'random_state': 'random_seed'}), "(class_weight='balanced', random_state=random_seed)\n", (8366, 8417), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((10440, 10465), 'scipy.stats.spearmanr', 'spearmanr', (['feature', 'label'], {}), '(feature, label)\n', (10449, 10465), False, 'from scipy.stats import spearmanr\n'), ((2521, 2594), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""', 'random_state': 'random_seed'}), "(class_weight='balanced', random_state=random_seed)\n", (2543, 2594), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((2713, 2806), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'class_weight': '"""balanced"""', 'n_jobs': 'job_num', 'random_state': 'random_seed'}), "(class_weight='balanced', n_jobs=job_num,\n random_state=random_seed)\n", (2735, 2806), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2924, 3016), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'n_jobs': 'job_num', 'class_weight': '"""balanced"""', 'random_state': 'random_seed'}), "(n_jobs=job_num, class_weight='balanced', random_state=\n random_seed)\n", (2944, 3016), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((5336, 5409), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""', 'random_state': 'random_seed'}), "(class_weight='balanced', random_state=random_seed)\n", (5358, 5409), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((5527, 5620), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'class_weight': '"""balanced"""', 'n_jobs': 'job_num', 'random_state': 'random_seed'}), "(class_weight='balanced', n_jobs=job_num,\n random_state=random_seed)\n", (5549, 5620), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((5739, 5831), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'n_jobs': 'job_num', 'class_weight': '"""balanced"""', 'random_state': 'random_seed'}), "(n_jobs=job_num, class_weight='balanced', random_state=\n random_seed)\n", (5759, 5831), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((9174, 9204), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'n_components': '(1)'}), '(n_components=1)\n', (9188, 9204), False, 'from sklearn.decomposition import IncrementalPCA\n'), ((9250, 9280), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'n_components': '(1)'}), '(n_components=1)\n', (9264, 9280), False, 'from sklearn.decomposition import IncrementalPCA\n'), ((9366, 9396), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'n_components': '(1)'}), '(n_components=1)\n', (9380, 9396), False, 'from sklearn.decomposition import IncrementalPCA\n'), ((9441, 9471), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'n_components': '(1)'}), '(n_components=1)\n', (9455, 9471), False, 'from sklearn.decomposition import IncrementalPCA\n'), ((11405, 11430), 'scipy.stats.spearmanr', 'spearmanr', (['feature', 'label'], {}), '(feature, label)\n', (11414, 11430), False, 'from scipy.stats import spearmanr\n'), ((14546, 14593), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""'}), "(class_weight='balanced')\n", (14568, 14593), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((14813, 14860), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'class_weight': '"""balanced"""'}), "(class_weight='balanced')\n", (14835, 14860), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((15069, 15121), 'sklearn.svm.SVC', 'SVC', ([], {'C': '(1.0)', 'kernel': '"""linear"""', 'class_weight': '"""balanced"""'}), "(C=1.0, kernel='linear', class_weight='balanced')\n", (15072, 15121), False, 'from sklearn.svm import SVC\n'), ((16656, 16678), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {}), '(data_path)\n', (16667, 16678), True, 'import pandas as pd\n'), ((3166, 3256), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""', 'random_state': 'random_seed', 'max_depth': '(2)'}), "(class_weight='balanced', random_state=random_seed,\n max_depth=2)\n", (3188, 3256), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((5983, 6073), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'class_weight': '"""balanced"""', 'random_state': 'random_seed', 'max_depth': '(2)'}), "(class_weight='balanced', random_state=random_seed,\n max_depth=2)\n", (6005, 6073), False, 'from sklearn.tree import DecisionTreeClassifier\n')]
import numpy as np import tensorflow as tf from tensorflow.contrib import gan as tfgan from GeneralTools.graph_funcs.my_session import MySession from GeneralTools.math_funcs.graph_func_support import mean_cov_np, trace_sqrt_product_np from GeneralTools.misc_fun import FLAGS class GenerativeModelMetric(object): def __init__(self, image_format=None, model='v1', model_path=None): """ This class defines several metrics using pre-trained classifier inception v1. :param image_format: """ if model_path is None: self.model = model if model == 'v1': self.inception_graph_def = tfgan.eval.get_graph_def_from_disk(FLAGS.INCEPTION_V1) elif model == 'v3': self.inception_graph_def = tfgan.eval.get_graph_def_from_disk(FLAGS.INCEPTION_V3) elif model in {'swd', 'ms_ssim', 'ssim'}: pass else: raise NotImplementedError('Model {} not implemented.'.format(model)) else: self.model = 'custom' self.inception_graph_def = tfgan.eval.get_graph_def_from_disk(model_path) if image_format is None: self.image_format = FLAGS.IMAGE_FORMAT else: self.image_format = image_format # preserved for inception v3 self._pool3_v3_ = None self._logits_v3_ = None def inception_v1_one_batch(self, image, output_tensor=None): """ This function runs the inception v1 model on images and give logits output. Note: if other layers of inception model is needed, change the output_tensor option in tfgan.eval.run_inception :param image: :param output_tensor: :return: """ if output_tensor is None: output_tensor = ['logits:0', 'pool_3:0'] image_size = tfgan.eval.INCEPTION_DEFAULT_IMAGE_SIZE if self.image_format in {'channels_first', 'NCHW'}: image = tf.transpose(image, perm=(0, 2, 3, 1)) if image.get_shape().as_list()[1] != image_size: image = tf.compat.v1.image.resize_bilinear(image, [image_size, image_size]) # inception score uses the logits:0 while FID uses pool_3:0. return tfgan.eval.run_inception( image, graph_def=self.inception_graph_def, input_tensor='Mul:0', output_tensor=output_tensor) def inception_v1(self, images): """ This function runs the inception v1 model on images and give logits output. Note: if other layers of inception model is needed, change the output_tensor option in tfgan.eval.run_inception. Note: for large inputs, e.g. [10000, 64, 64, 3], it is better to run iterations containing this function. :param images: :return: """ num_images = images.get_shape().as_list()[0] if num_images > 2500: raise MemoryError('The input is too big to possibly fit into memory. Consider using multiple runs.') if num_images >= 400: print(num_images) # Note: need to validate the code below # somehow tfgan.eval.classifier_score does not work properly when splitting the datasets. # The following code is inspired by: # https://github.com/tensorflow/tensorflow/blob/r1.7/tensorflow/contrib/gan/python/eval/python/classifier_metrics_impl.py if num_images % 100 == 0: generated_images_list = tf.split(images, num_or_size_splits=num_images // 100, axis=0) logits, pool3 = tf.map_fn( fn=self.inception_v1_one_batch, elems=tf.stack(generated_images_list), dtype=(tf.float32, tf.float32), parallel_iterations=1, back_prop=False, swap_memory=True, name='RunClassifier') logits = tf.concat(tf.unstack(logits), 0) pool3 = tf.concat(tf.unstack(pool3), 0) else: generated_images_list = tf.split( images, num_or_size_splits=[100] * (num_images // 100) + [num_images % 100], axis=0) # tf.stack requires the dimension of tensor in list to be the same logits, pool3 = tf.map_fn( fn=self.inception_v1_one_batch, elems=tf.stack(generated_images_list[0:-1]), dtype=(tf.float32, tf.float32), parallel_iterations=1, back_prop=False, swap_memory=True, name='RunClassifier') logits_last, pool3_last = self.inception_v1_one_batch(generated_images_list[-1]) logits = tf.concat(tf.unstack(logits) + [logits_last], 0) pool3 = tf.concat(tf.unstack(pool3) + [pool3_last], 0) else: logits, pool3 = self.inception_v1_one_batch(images) return logits, pool3 @staticmethod def inception_score_from_logits(logits): """ This function estimates the inception score from logits output by inception_v1 :param logits: :return: """ if type(logits) == np.ndarray: logits = tf.constant(logits, dtype=tf.float32) return tfgan.eval.classifier_score_from_logits(logits) @staticmethod def fid_from_pool3(x_pool3, y_pool3): """ This function estimates Fréchet inception distance from pool3 of inception model :param x_pool3: :param y_pool3: :return: """ if type(x_pool3) == np.ndarray: x_pool3 = tf.constant(x_pool3, dtype=tf.float32) if type(y_pool3) == np.ndarray: y_pool3 = tf.constant(y_pool3, dtype=tf.float32) return tfgan.eval.frechet_classifier_distance_from_activations(x_pool3, y_pool3) @ staticmethod def my_fid_from_pool3(x_pool3_np, y_pool3_np): """ This function estimates Fréchet inception distance from pool3 of inception model. Different from fid_from_pool3, here pool3_np could be a list [mean, cov] :param x_pool3_np: :param y_pool3_np: :return: """ # from scipy.linalg import sqrtm x_mean, x_cov = x_pool3_np if isinstance(x_pool3_np, (list, tuple)) else mean_cov_np(x_pool3_np) y_mean, y_cov = y_pool3_np if isinstance(y_pool3_np, (list, tuple)) else mean_cov_np(y_pool3_np) fid = np.sum((x_mean-y_mean) ** 2)+np.trace(x_cov)+np.trace(y_cov)-2.0*trace_sqrt_product_np(x_cov, y_cov) return fid # return np.sum((x_mean - y_mean) ** 2) + np.trace(x_cov + y_cov - 2.0 * sqrtm(np.dot(x_cov, y_cov))) def inception_score_and_fid_v1(self, x_batch, y_batch, num_batch=10, ckpt_folder=None, ckpt_file=None): """ This function calculates inception scores and FID based on inception v1. Note: batch_size * num_batch needs to be larger than 2048, otherwise the convariance matrix will be ill-conditioned. According to TensorFlow v1.7 (below), this is actually inception v3 model. Somehow the downloaded file says it's v1. code link: https://github.com/tensorflow/tensorflow/blob/r1.7/tensorflow/contrib \ /gan/python/eval/python/classifier_metrics_impl.py Steps: 1, the pool3 and logits are calculated for x_batch and y_batch with sess 2, the pool3 and logits are passed to corresponding metrics :param ckpt_file: :param x_batch: tensor, one batch of x in range [-1, 1] :param y_batch: tensor, one batch of y in range [-1, 1] :param num_batch: :param ckpt_folder: check point folder :param ckpt_file: in case an older ckpt file is needed, provide it here, e.g. 'cifar.ckpt-6284' :return: """ assert self.model == 'v1', 'GenerativeModelMetric is not initialized with model="v1".' assert ckpt_folder is not None, 'ckpt_folder must be provided.' x_logits, x_pool3 = self.inception_v1(x_batch) y_logits, y_pool3 = self.inception_v1(y_batch) with MySession(load_ckpt=True) as sess: inception_outputs = sess.run_m_times( [x_logits, y_logits, x_pool3, y_pool3], ckpt_folder=ckpt_folder, ckpt_file=ckpt_file, max_iter=num_batch, trace=True) # get logits and pool3 x_logits_np = np.concatenate([inc[0] for inc in inception_outputs], axis=0) y_logits_np = np.concatenate([inc[1] for inc in inception_outputs], axis=0) x_pool3_np = np.concatenate([inc[2] for inc in inception_outputs], axis=0) y_pool3_np = np.concatenate([inc[3] for inc in inception_outputs], axis=0) FLAGS.print('logits calculated. Shape = {}.'.format(x_logits_np.shape)) FLAGS.print('pool3 calculated. Shape = {}.'.format(x_pool3_np.shape)) # calculate scores inc_x = self.inception_score_from_logits(x_logits_np) inc_y = self.inception_score_from_logits(y_logits_np) xp3_1, xp3_2 = np.split(x_pool3_np, indices_or_sections=2, axis=0) fid_xx = self.fid_from_pool3(xp3_1, xp3_2) fid_xy = self.fid_from_pool3(x_pool3_np, y_pool3_np) with MySession() as sess: scores = sess.run_once([inc_x, inc_y, fid_xx, fid_xy]) return scores def sliced_wasserstein_distance(self, x_batch, y_batch, num_batch=128, ckpt_folder=None, ckpt_file=None): """ This function calculates the sliced wasserstein distance between real and fake images. This function does not work as expected, swd gives nan :param x_batch: :param y_batch: :param num_batch: :param ckpt_folder: :param ckpt_file: :return: """ with MySession(load_ckpt=True) as sess: batches = sess.run_m_times( [x_batch, y_batch], ckpt_folder=ckpt_folder, ckpt_file=ckpt_file, max_iter=num_batch, trace=True) # get x_images and y_images x_images = (tf.constant(np.concatenate([batch[0] for batch in batches], axis=0)) + 1.0) * 128.5 y_images = (tf.constant(np.concatenate([batch[1] for batch in batches], axis=0)) + 1.0) * 128.5 if self.image_format in {'channels_first', 'NCHW'}: x_images = tf.transpose(x_images, perm=(0, 2, 3, 1)) y_images = tf.transpose(y_images, perm=(0, 2, 3, 1)) print('images obtained, shape: {}'.format(x_images.shape)) # sliced_wasserstein_distance returns a list of tuples (distance_real, distance_fake) # for each level of the Laplacian pyramid from the highest resolution to the lowest swd = tfgan.eval.sliced_wasserstein_distance( x_images, y_images, patches_per_image=64, random_sampling_count=4, use_svd=True) with MySession() as sess: swd = sess.run_once(swd) return swd def ms_ssim(self, x_batch, y_batch, num_batch=128, ckpt_folder=None, ckpt_file=None, image_size=256): """ This function calculates the multiscale structural similarity between a pair of images. The image is downscaled four times; at each scale, a 11x11 filter is applied to extract patches. USE WITH CAUTION !!! 1. This code was lost once and redone. Need to test on real datasets to verify it. 2. This code can be improved to calculate pairwise ms-ssim using tf.image.ssim. tf.image.ssim_multicale is just tf.image.ssim with pool downsampling. :param x_batch: :param y_batch: :param num_batch: :param ckpt_folder: :param ckpt_file: :param image_size: ssim is defined on images of size at least 176 :return: """ # get x_images and y_images x_images = (x_batch + 1.0) * 128.5 y_images = (y_batch + 1.0) * 128.5 if self.image_format in {'channels_first', 'NCHW'}: x_images = tf.transpose(x_images, perm=(0, 2, 3, 1)) y_images = tf.transpose(y_images, perm=(0, 2, 3, 1)) if x_images.get_shape().as_list()[1] != 256: x_images = tf.compat.v1.image.resize_bilinear(x_images, [image_size, image_size]) y_images = tf.compat.v1.image.resize_bilinear(y_images, [image_size, image_size]) scores = tf.image.ssim_multiscale(x_images, y_images, max_val=255) # scores in range [0, 1] with MySession(load_ckpt=True) as sess: scores = sess.run_m_times( scores, ckpt_folder=ckpt_folder, ckpt_file=ckpt_file, max_iter=num_batch, trace=True) ssim_score = np.mean(np.concatenate(scores, axis=0), axis=0) return ssim_score
[ "tensorflow.unstack", "numpy.trace", "tensorflow.transpose", "tensorflow.contrib.gan.eval.run_inception", "tensorflow.split", "tensorflow.contrib.gan.eval.get_graph_def_from_disk", "tensorflow.contrib.gan.eval.sliced_wasserstein_distance", "tensorflow.image.ssim_multiscale", "numpy.concatenate", "GeneralTools.graph_funcs.my_session.MySession", "tensorflow.stack", "GeneralTools.math_funcs.graph_func_support.trace_sqrt_product_np", "tensorflow.compat.v1.image.resize_bilinear", "tensorflow.contrib.gan.eval.frechet_classifier_distance_from_activations", "tensorflow.contrib.gan.eval.classifier_score_from_logits", "numpy.sum", "numpy.split", "tensorflow.constant", "GeneralTools.math_funcs.graph_func_support.mean_cov_np" ]
[((2250, 2372), 'tensorflow.contrib.gan.eval.run_inception', 'tfgan.eval.run_inception', (['image'], {'graph_def': 'self.inception_graph_def', 'input_tensor': '"""Mul:0"""', 'output_tensor': 'output_tensor'}), "(image, graph_def=self.inception_graph_def,\n input_tensor='Mul:0', output_tensor=output_tensor)\n", (2274, 2372), True, 'from tensorflow.contrib import gan as tfgan\n'), ((5310, 5357), 'tensorflow.contrib.gan.eval.classifier_score_from_logits', 'tfgan.eval.classifier_score_from_logits', (['logits'], {}), '(logits)\n', (5349, 5357), True, 'from tensorflow.contrib import gan as tfgan\n'), ((5807, 5880), 'tensorflow.contrib.gan.eval.frechet_classifier_distance_from_activations', 'tfgan.eval.frechet_classifier_distance_from_activations', (['x_pool3', 'y_pool3'], {}), '(x_pool3, y_pool3)\n', (5862, 5880), True, 'from tensorflow.contrib import gan as tfgan\n'), ((8440, 8501), 'numpy.concatenate', 'np.concatenate', (['[inc[0] for inc in inception_outputs]'], {'axis': '(0)'}), '([inc[0] for inc in inception_outputs], axis=0)\n', (8454, 8501), True, 'import numpy as np\n'), ((8524, 8585), 'numpy.concatenate', 'np.concatenate', (['[inc[1] for inc in inception_outputs]'], {'axis': '(0)'}), '([inc[1] for inc in inception_outputs], axis=0)\n', (8538, 8585), True, 'import numpy as np\n'), ((8607, 8668), 'numpy.concatenate', 'np.concatenate', (['[inc[2] for inc in inception_outputs]'], {'axis': '(0)'}), '([inc[2] for inc in inception_outputs], axis=0)\n', (8621, 8668), True, 'import numpy as np\n'), ((8690, 8751), 'numpy.concatenate', 'np.concatenate', (['[inc[3] for inc in inception_outputs]'], {'axis': '(0)'}), '([inc[3] for inc in inception_outputs], axis=0)\n', (8704, 8751), True, 'import numpy as np\n'), ((9084, 9135), 'numpy.split', 'np.split', (['x_pool3_np'], {'indices_or_sections': '(2)', 'axis': '(0)'}), '(x_pool3_np, indices_or_sections=2, axis=0)\n', (9092, 9135), True, 'import numpy as np\n'), ((10744, 10867), 'tensorflow.contrib.gan.eval.sliced_wasserstein_distance', 'tfgan.eval.sliced_wasserstein_distance', (['x_images', 'y_images'], {'patches_per_image': '(64)', 'random_sampling_count': '(4)', 'use_svd': '(True)'}), '(x_images, y_images,\n patches_per_image=64, random_sampling_count=4, use_svd=True)\n', (10782, 10867), True, 'from tensorflow.contrib import gan as tfgan\n'), ((12372, 12429), 'tensorflow.image.ssim_multiscale', 'tf.image.ssim_multiscale', (['x_images', 'y_images'], {'max_val': '(255)'}), '(x_images, y_images, max_val=255)\n', (12396, 12429), True, 'import tensorflow as tf\n'), ((1104, 1150), 'tensorflow.contrib.gan.eval.get_graph_def_from_disk', 'tfgan.eval.get_graph_def_from_disk', (['model_path'], {}), '(model_path)\n', (1138, 1150), True, 'from tensorflow.contrib import gan as tfgan\n'), ((1981, 2019), 'tensorflow.transpose', 'tf.transpose', (['image'], {'perm': '(0, 2, 3, 1)'}), '(image, perm=(0, 2, 3, 1))\n', (1993, 2019), True, 'import tensorflow as tf\n'), ((2097, 2164), 'tensorflow.compat.v1.image.resize_bilinear', 'tf.compat.v1.image.resize_bilinear', (['image', '[image_size, image_size]'], {}), '(image, [image_size, image_size])\n', (2131, 2164), True, 'import tensorflow as tf\n'), ((5257, 5294), 'tensorflow.constant', 'tf.constant', (['logits'], {'dtype': 'tf.float32'}), '(logits, dtype=tf.float32)\n', (5268, 5294), True, 'import tensorflow as tf\n'), ((5652, 5690), 'tensorflow.constant', 'tf.constant', (['x_pool3'], {'dtype': 'tf.float32'}), '(x_pool3, dtype=tf.float32)\n', (5663, 5690), True, 'import tensorflow as tf\n'), ((5753, 5791), 'tensorflow.constant', 'tf.constant', (['y_pool3'], {'dtype': 'tf.float32'}), '(y_pool3, dtype=tf.float32)\n', (5764, 5791), True, 'import tensorflow as tf\n'), ((6333, 6356), 'GeneralTools.math_funcs.graph_func_support.mean_cov_np', 'mean_cov_np', (['x_pool3_np'], {}), '(x_pool3_np)\n', (6344, 6356), False, 'from GeneralTools.math_funcs.graph_func_support import mean_cov_np, trace_sqrt_product_np\n'), ((6438, 6461), 'GeneralTools.math_funcs.graph_func_support.mean_cov_np', 'mean_cov_np', (['y_pool3_np'], {}), '(y_pool3_np)\n', (6449, 6461), False, 'from GeneralTools.math_funcs.graph_func_support import mean_cov_np, trace_sqrt_product_np\n'), ((8135, 8160), 'GeneralTools.graph_funcs.my_session.MySession', 'MySession', ([], {'load_ckpt': '(True)'}), '(load_ckpt=True)\n', (8144, 8160), False, 'from GeneralTools.graph_funcs.my_session import MySession\n'), ((9262, 9273), 'GeneralTools.graph_funcs.my_session.MySession', 'MySession', ([], {}), '()\n', (9271, 9273), False, 'from GeneralTools.graph_funcs.my_session import MySession\n'), ((9819, 9844), 'GeneralTools.graph_funcs.my_session.MySession', 'MySession', ([], {'load_ckpt': '(True)'}), '(load_ckpt=True)\n', (9828, 9844), False, 'from GeneralTools.graph_funcs.my_session import MySession\n'), ((10369, 10410), 'tensorflow.transpose', 'tf.transpose', (['x_images'], {'perm': '(0, 2, 3, 1)'}), '(x_images, perm=(0, 2, 3, 1))\n', (10381, 10410), True, 'import tensorflow as tf\n'), ((10434, 10475), 'tensorflow.transpose', 'tf.transpose', (['y_images'], {'perm': '(0, 2, 3, 1)'}), '(y_images, perm=(0, 2, 3, 1))\n', (10446, 10475), True, 'import tensorflow as tf\n'), ((10890, 10901), 'GeneralTools.graph_funcs.my_session.MySession', 'MySession', ([], {}), '()\n', (10899, 10901), False, 'from GeneralTools.graph_funcs.my_session import MySession\n'), ((12006, 12047), 'tensorflow.transpose', 'tf.transpose', (['x_images'], {'perm': '(0, 2, 3, 1)'}), '(x_images, perm=(0, 2, 3, 1))\n', (12018, 12047), True, 'import tensorflow as tf\n'), ((12071, 12112), 'tensorflow.transpose', 'tf.transpose', (['y_images'], {'perm': '(0, 2, 3, 1)'}), '(y_images, perm=(0, 2, 3, 1))\n', (12083, 12112), True, 'import tensorflow as tf\n'), ((12189, 12259), 'tensorflow.compat.v1.image.resize_bilinear', 'tf.compat.v1.image.resize_bilinear', (['x_images', '[image_size, image_size]'], {}), '(x_images, [image_size, image_size])\n', (12223, 12259), True, 'import tensorflow as tf\n'), ((12283, 12353), 'tensorflow.compat.v1.image.resize_bilinear', 'tf.compat.v1.image.resize_bilinear', (['y_images', '[image_size, image_size]'], {}), '(y_images, [image_size, image_size])\n', (12317, 12353), True, 'import tensorflow as tf\n'), ((12470, 12495), 'GeneralTools.graph_funcs.my_session.MySession', 'MySession', ([], {'load_ckpt': '(True)'}), '(load_ckpt=True)\n', (12479, 12495), False, 'from GeneralTools.graph_funcs.my_session import MySession\n'), ((12708, 12738), 'numpy.concatenate', 'np.concatenate', (['scores'], {'axis': '(0)'}), '(scores, axis=0)\n', (12722, 12738), True, 'import numpy as np\n'), ((654, 708), 'tensorflow.contrib.gan.eval.get_graph_def_from_disk', 'tfgan.eval.get_graph_def_from_disk', (['FLAGS.INCEPTION_V1'], {}), '(FLAGS.INCEPTION_V1)\n', (688, 708), True, 'from tensorflow.contrib import gan as tfgan\n'), ((3468, 3530), 'tensorflow.split', 'tf.split', (['images'], {'num_or_size_splits': '(num_images // 100)', 'axis': '(0)'}), '(images, num_or_size_splits=num_images // 100, axis=0)\n', (3476, 3530), True, 'import tensorflow as tf\n'), ((4069, 4167), 'tensorflow.split', 'tf.split', (['images'], {'num_or_size_splits': '([100] * (num_images // 100) + [num_images % 100])', 'axis': '(0)'}), '(images, num_or_size_splits=[100] * (num_images // 100) + [\n num_images % 100], axis=0)\n', (4077, 4167), True, 'import tensorflow as tf\n'), ((6521, 6536), 'numpy.trace', 'np.trace', (['y_cov'], {}), '(y_cov)\n', (6529, 6536), True, 'import numpy as np\n'), ((6541, 6576), 'GeneralTools.math_funcs.graph_func_support.trace_sqrt_product_np', 'trace_sqrt_product_np', (['x_cov', 'y_cov'], {}), '(x_cov, y_cov)\n', (6562, 6576), False, 'from GeneralTools.math_funcs.graph_func_support import mean_cov_np, trace_sqrt_product_np\n'), ((784, 838), 'tensorflow.contrib.gan.eval.get_graph_def_from_disk', 'tfgan.eval.get_graph_def_from_disk', (['FLAGS.INCEPTION_V3'], {}), '(FLAGS.INCEPTION_V3)\n', (818, 838), True, 'from tensorflow.contrib import gan as tfgan\n'), ((3932, 3950), 'tensorflow.unstack', 'tf.unstack', (['logits'], {}), '(logits)\n', (3942, 3950), True, 'import tensorflow as tf\n'), ((3989, 4006), 'tensorflow.unstack', 'tf.unstack', (['pool3'], {}), '(pool3)\n', (3999, 4006), True, 'import tensorflow as tf\n'), ((6476, 6506), 'numpy.sum', 'np.sum', (['((x_mean - y_mean) ** 2)'], {}), '((x_mean - y_mean) ** 2)\n', (6482, 6506), True, 'import numpy as np\n'), ((6505, 6520), 'numpy.trace', 'np.trace', (['x_cov'], {}), '(x_cov)\n', (6513, 6520), True, 'import numpy as np\n'), ((10109, 10164), 'numpy.concatenate', 'np.concatenate', (['[batch[0] for batch in batches]'], {'axis': '(0)'}), '([batch[0] for batch in batches], axis=0)\n', (10123, 10164), True, 'import numpy as np\n'), ((10213, 10268), 'numpy.concatenate', 'np.concatenate', (['[batch[1] for batch in batches]'], {'axis': '(0)'}), '([batch[1] for batch in batches], axis=0)\n', (10227, 10268), True, 'import numpy as np\n'), ((3652, 3683), 'tensorflow.stack', 'tf.stack', (['generated_images_list'], {}), '(generated_images_list)\n', (3660, 3683), True, 'import tensorflow as tf\n'), ((4388, 4425), 'tensorflow.stack', 'tf.stack', (['generated_images_list[0:-1]'], {}), '(generated_images_list[0:-1])\n', (4396, 4425), True, 'import tensorflow as tf\n'), ((4771, 4789), 'tensorflow.unstack', 'tf.unstack', (['logits'], {}), '(logits)\n', (4781, 4789), True, 'import tensorflow as tf\n'), ((4844, 4861), 'tensorflow.unstack', 'tf.unstack', (['pool3'], {}), '(pool3)\n', (4854, 4861), True, 'import tensorflow as tf\n')]
from typing import Any, Callable import matplotlib.pyplot as plt from numpy import arange from .membership import Membership class BaseSet: def __init__( self, name: str, membership: Membership, aggregation: Callable[[Any, Any], Any], ): self.name = name self.membership = membership self.aggregation = aggregation def __add__(self, arg: "BaseSet"): memb = Membership( lambda x: self.aggregation( self.membership(x), arg.membership(x), ), self.membership.items + arg.membership.items, ) return BaseSet( f"({self.name})_union_({arg.name})", memb, aggregation=self.aggregation, ) def domain(self, step=0.05): start = self.membership.items[0] end = self.membership.items[-1] result = list(arange(start, end, step)) result += self.membership.items result.sort() return result def __iter__(self): return iter(self.domain()) def __len__(self): return len(self.domain()) def __str__(self) -> str: return self.name def graph(self, step: float = 0.05): x_data = self.domain(step=step) y_data = [self.membership(x) for x in x_data] plt.figure() plt.title(self.name) plt.xlabel("Domain values") plt.ylabel("Membership grade") plt.plot(x_data, y_data) plt.savefig(f"set_{self.name}.png")
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.arange" ]
[((1352, 1364), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1362, 1364), True, 'import matplotlib.pyplot as plt\n'), ((1373, 1393), 'matplotlib.pyplot.title', 'plt.title', (['self.name'], {}), '(self.name)\n', (1382, 1393), True, 'import matplotlib.pyplot as plt\n'), ((1402, 1429), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Domain values"""'], {}), "('Domain values')\n", (1412, 1429), True, 'import matplotlib.pyplot as plt\n'), ((1438, 1468), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Membership grade"""'], {}), "('Membership grade')\n", (1448, 1468), True, 'import matplotlib.pyplot as plt\n'), ((1477, 1501), 'matplotlib.pyplot.plot', 'plt.plot', (['x_data', 'y_data'], {}), '(x_data, y_data)\n', (1485, 1501), True, 'import matplotlib.pyplot as plt\n'), ((1510, 1545), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""set_{self.name}.png"""'], {}), "(f'set_{self.name}.png')\n", (1521, 1545), True, 'import matplotlib.pyplot as plt\n'), ((924, 948), 'numpy.arange', 'arange', (['start', 'end', 'step'], {}), '(start, end, step)\n', (930, 948), False, 'from numpy import arange\n')]
import numpy as np import chess import chess.engine from tkinter.filedialog import asksaveasfilename from parsing.math_encode import tensor_encode, tensor_decode from inference.infer_action import get_action class PlayLoop: __doc__ = ''' An interactive REPL environment for play with a trained chess AI ''' TRACE_FORMAT = '{:<7}{:<18}{:<42}{:<45}{:<7}{:<18}{:<42}{}' TRACE_HEADER = ('move', 'WHITE', 'source', 'target', 'move', 'BLACK', 'source', 'target') def __init__(self, policy, secondary_policy=None, engine_path='../engine/stockfish.exe'): ''' Constructs a PlayLoop instance :param policy: PolicyModel - primary AI agent to simulate :param secondary_policy: None/PolicyModel/'same'/'stockfish' - Agent used to replace player moves (if None, human is playing; if 'same', secondary_policy=policy) ''' self.policy = policy self.player_white = None self.board = None self.keep_trace = False self.trace = None self.engine = None if secondary_policy is not None: if secondary_policy == 'same': self.player_move_func = lambda: self._get_action_from_policy(policy) elif secondary_policy == 'stockfish': self.player_move_func = self._get_stockfish self.engine = chess.engine.SimpleEngine.popen_uci(engine_path) else: self.player_move_func = lambda: self._get_action_from_policy(secondary_policy) else: self.player_move_func = self._get_player_move def init_game(self, player_side, keep_trace=True): ''' Sets up a game and indicating the side to play as by the player :param player_side: 'w'/'b' - side to play as :param keep_trace: bool - if True, accumulates the trace for the entire game :return: None ''' if self.board is not None: raise RuntimeWarning('Board already initiatized, set force_new=True to force override') if player_side == 'w': self.player_white = True elif player_side == 'b': self.player_white = False else: raise ValueError(f'Expected "w" or "b" for player_side but given {player_side}') self.board = chess.Board() self.keep_trace = keep_trace if keep_trace: self.trace = list() def reset(self): ''' Resets the PlayLoop state (except the trace) :return: None ''' self.board = None self.keep_trace = False def loop(self, verbose=True): ''' Runs the loop until the termination of a game :param verbose: bool - prints messages if True :return: None ''' if self.board is None: raise RuntimeError('init_game was not called to configure game settings!') if self.board.is_game_over(): raise RuntimeError('Game has already ended. Call reset and init_gram before calling loop') trace_collector = list() if not self.player_white: move, policy = self._get_action_from_policy() if self.keep_trace: self._store_trace(move, trace_collector, policy=policy) if verbose: print(f'\nAI made {move} move\n') while not self.board.is_game_over(): if verbose: print(self.board) # player/secondary_policy move move, policy = self.player_move_func() if self.keep_trace: self._store_trace(move, trace_collector, policy=policy) if verbose: print(f'\nPlayer made {move} move\n') if self.board.is_game_over(): break # policy move move, policy = self._get_action_from_policy() if self.keep_trace: self._store_trace(move, trace_collector, policy=policy) if verbose: print(f'\nAI made {move} move\n') if len(trace_collector) != 0: self._store_trace(move, trace_collector, policy=policy, force_flush=True) if verbose: print('Game completed') def get_trace(self, printable=True): ''' Returns the trace :param printable: bool - If True, returns a printable and formamted string of the trace :return: str/list(str) ''' if printable: return '\n'.join(self.trace) return self.trace def save_trace(self, file_path=None, interactive=True): ''' Saves trace in a text file Automatically appends ".txt" at the end of the file_path if the suffix is not found :param file_path: None/str - file path to save to :param interactive: bool - if True, using Tkinter GUI to select file path :return: None ''' if interactive: file_path = asksaveasfilename(filetypes=[('Text file', '*.txt')]) if file_path[-4:] != '.txt': file_path = file_path + '.txt' with open(file_path, 'w') as f: f.write(self.get_trace(printable=True)) def _get_action_from_policy(self, external_policy=None): ''' Gets UCI representation of the move using the policy loaded and pushes the move on the board :param external_policy - None/PolicyModel - policy to use (if None, defaults to loaded policy) :return: str ''' policy = self.policy flip = self.player_white if external_policy: # player is an AI policy = external_policy flip = not flip src, tgt, _ = policy.infer(tensor_encode(self.board, mirror=flip)) if flip: # perform mirror flips src = np.flip(src[0, ...], 0) tgt = np.flip(tgt[0, ...], 0) else: src = src[0, ...] tgt = tgt[0, ...] move = get_action(self.board, src, tgt) self.board.push(chess.Move.from_uci(move)) return move, (src, tgt) def _get_player_move(self): ''' Obtains the move from the player by command line and pushes the move on the board :return: str, None ''' while True: # handles invalid player moves try: move_input = input('Enter your move: ') move = chess.Move.from_uci(move_input) if move in self.board.legal_moves: self.board.push(move) else: raise AssertionError(f'{move_input} is not a valid move') except AssertionError as e: print(f'ERROR: {e}') else: break return move_input, None def _get_stockfish(self, time=0.001, depth=1): ''' Obtains the move from the Stockfish engine with the lowest ELO ratings :param time: float - time limit for the engine :param depth: int - maximum search depth :return: str, None ''' move = self.engine.play(self.board, chess.engine.Limit(time=time, depth=depth), ponder=False, options={'uci_elo': 1350}).move self.board.push(move) return move.uci(), None def _store_trace(self, move, trace_collector, policy=None, force_flush=False): ''' Collects the trace onto trace_collector and once white and black has made the move, append to the main trace list :param move: str - UCI representation of the move :param trace_collector: list(str) - string accumulator :param policy: None/tuple(np.ndarray, np.ndarray) - policy output :param force_flush: bool - if True, appends incomplete trace :return: None ''' trace_collector.append(str(self.board)) trace_collector.append(move) if policy is None: trace_collector.append('N/A\n\n\n\n\n\n\n') trace_collector.append('N/A\n\n\n\n\n\n\n') else: trace_collector.append(str(np.around(policy[0], 2)).replace('[[', '') .replace(' [ ', '').replace(' [', '').replace(']', '')) trace_collector.append(str(np.around(policy[1], 2)).replace('[[', '') .replace(' [ ', '').replace(' [', '').replace(']', '')) if len(trace_collector) == 8: # two half-moves has been made self.trace.append(PlayLoop.TRACE_FORMAT.format(*PlayLoop.TRACE_HEADER)) for b1, src1, tgt1, b2, src2, tgt2 in zip(trace_collector[0].split('\n'), trace_collector[2].split('\n'), trace_collector[3].split('\n'), trace_collector[4].split('\n'), trace_collector[6].split('\n'), trace_collector[7].split('\n')): self.trace.append(PlayLoop.TRACE_FORMAT.format(trace_collector[1], b1, src1, tgt1, trace_collector[5], b2, src2, tgt2)) trace_collector[1] = '' trace_collector[5] = '' self.trace.append('\n') trace_collector.clear() elif force_flush: self.trace.append(PlayLoop.TRACE_FORMAT.format(*PlayLoop.TRACE_HEADER)) for b1, src1, tgt1 in zip(trace_collector[0].split('\n'), trace_collector[2].split('\n'), trace_collector[3].split('\n')): self.trace.append(PlayLoop.TRACE_FORMAT.format(trace_collector[1], b1, src1, tgt1, '', '', '', '')) trace_collector[1] = '' self.trace.append('\n')
[ "numpy.flip", "inference.infer_action.get_action", "chess.Move.from_uci", "chess.engine.SimpleEngine.popen_uci", "tkinter.filedialog.asksaveasfilename", "chess.Board", "chess.engine.Limit", "parsing.math_encode.tensor_encode", "numpy.around" ]
[((2322, 2335), 'chess.Board', 'chess.Board', ([], {}), '()\n', (2333, 2335), False, 'import chess\n'), ((5869, 5901), 'inference.infer_action.get_action', 'get_action', (['self.board', 'src', 'tgt'], {}), '(self.board, src, tgt)\n', (5879, 5901), False, 'from inference.infer_action import get_action\n'), ((4863, 4916), 'tkinter.filedialog.asksaveasfilename', 'asksaveasfilename', ([], {'filetypes': "[('Text file', '*.txt')]"}), "(filetypes=[('Text file', '*.txt')])\n", (4880, 4916), False, 'from tkinter.filedialog import asksaveasfilename\n'), ((5613, 5651), 'parsing.math_encode.tensor_encode', 'tensor_encode', (['self.board'], {'mirror': 'flip'}), '(self.board, mirror=flip)\n', (5626, 5651), False, 'from parsing.math_encode import tensor_encode, tensor_decode\n'), ((5713, 5736), 'numpy.flip', 'np.flip', (['src[0, ...]', '(0)'], {}), '(src[0, ...], 0)\n', (5720, 5736), True, 'import numpy as np\n'), ((5755, 5778), 'numpy.flip', 'np.flip', (['tgt[0, ...]', '(0)'], {}), '(tgt[0, ...], 0)\n', (5762, 5778), True, 'import numpy as np\n'), ((5926, 5951), 'chess.Move.from_uci', 'chess.Move.from_uci', (['move'], {}), '(move)\n', (5945, 5951), False, 'import chess\n'), ((6309, 6340), 'chess.Move.from_uci', 'chess.Move.from_uci', (['move_input'], {}), '(move_input)\n', (6328, 6340), False, 'import chess\n'), ((7014, 7056), 'chess.engine.Limit', 'chess.engine.Limit', ([], {'time': 'time', 'depth': 'depth'}), '(time=time, depth=depth)\n', (7032, 7056), False, 'import chess\n'), ((1370, 1418), 'chess.engine.SimpleEngine.popen_uci', 'chess.engine.SimpleEngine.popen_uci', (['engine_path'], {}), '(engine_path)\n', (1405, 1418), False, 'import chess\n'), ((8005, 8028), 'numpy.around', 'np.around', (['policy[0]', '(2)'], {}), '(policy[0], 2)\n', (8014, 8028), True, 'import numpy as np\n'), ((8178, 8201), 'numpy.around', 'np.around', (['policy[1]', '(2)'], {}), '(policy[1], 2)\n', (8187, 8201), True, 'import numpy as np\n')]
import bpy from aiohttp import web import numpy as np from mathutils import Matrix, Vector import asyncio from cinebot_mini_render_server.blender_timer_executor import EXECUTOR routes = web.RouteTableDef() def delete_animation_helper(obj): if not obj.animation_data: return False if not obj.animation_data.action: return False if not obj.animation_data.action.fcurves: return False action = obj.animation_data.action remove_types = ["location", "scale", "rotation"] fcurves = [fc for fc in action.fcurves for type in remove_types if fc.data_path.startswith(type)] while fcurves: fc = fcurves.pop() action.fcurves.remove(fc) return True def handle_object_animation_get_helper(obj_name): scene = bpy.context.scene obj = bpy.data.objects[obj_name] fc = obj.animation_data.action.fcurves[0] start, end = fc.range() transforms = [] for t in range(int(start), int(end)): scene.frame_set(t) matrix_world = np.array(obj.matrix_world) tf_data = { "frame_number": t, "matrix_world": matrix_world.tolist() } transforms.append(tf_data) return transforms @routes.get('/api/object/{obj_name}/animation') async def handle_object_animation_get(request): obj_name = request.match_info.get('obj_name', "None") if obj_name not in bpy.data.objects: raise web.HTTPBadRequest() loop = asyncio.get_event_loop() result = await loop.run_in_executor(EXECUTOR, handle_object_animation_get_helper, obj_name) data = { "result": result, "url": '/api/object/{}/animation'.format(obj_name), "method": "GET" } return web.json_response(data) def handle_object_animation_put_helper(input_data, obj_name): scene = bpy.context.scene obj = bpy.data.objects[obj_name] print("before delete") delete_animation_helper(obj) print("after delete") if not obj.animation_data: obj.animation_data_create() if not obj.animation_data.action: obj.animation_data.action = bpy.data.actions.new(name=obj_name + "_action") f_curves_loc = [obj.animation_data.action.fcurves.new(data_path="location", index=i) for i in range(3)] f_curves_rot = [obj.animation_data.action.fcurves.new(data_path="rotation_euler", index=i) for i in range(3)] [x.keyframe_points.add(len(input_data["transforms"])) for x in f_curves_loc] [x.keyframe_points.add(len(input_data["transforms"])) for x in f_curves_rot] for i, frame in enumerate(input_data["transforms"]): frame_number = frame["frame_number"] location = None rotation_euler = None if "matrix_world" in frame: matrix_world = frame["matrix_world"] m = Matrix(matrix_world) location = m.to_translation() rotation_euler = m.to_euler() elif "location" in frame and "rotation_euler" in frame: location = frame["location"] rotation_euler = frame["rotation_euler"] else: return False for j in range(3): f_curves_loc[j].keyframe_points[i].co = [float(frame_number), location[j]] f_curves_rot[j].keyframe_points[i].co = [float(frame_number), rotation_euler[j]] return True @routes.put('/api/object/{obj_name}/animation') async def handle_object_animation_put(request): input_data = await request.json() obj_name = request.match_info.get('obj_name', "None") if obj_name not in bpy.data.objects: raise web.HTTPBadRequest() loop = asyncio.get_event_loop() result = await loop.run_in_executor(EXECUTOR, handle_object_animation_put_helper, input_data, obj_name) data = { "result": "SUCCESS" if result else "FAILED", "url": '/api/object/{}/animation'.format(obj_name), "method": "PUT" } return web.json_response(data=data) def handle_object_animation_delete_helper(obj_name): scene = bpy.context.scene obj = bpy.data.objects[obj_name] result = delete_animation_helper(obj) return result @routes.delete('/api/object/{obj_name}/animation') async def handle_object_animation_delete(request): obj_name = request.match_info.get('obj_name', "None") if obj_name not in bpy.data.objects: raise web.HTTPBadRequest() loop = asyncio.get_event_loop() result = await loop.run_in_executor(EXECUTOR, handle_object_animation_delete_helper, obj_name) data = { "result": "SUCCESS" if result else "FAILED", "url": '/api/object/{}/animation'.format(obj_name), "method": "DELETE" } return web.json_response(data=data)
[ "numpy.array", "aiohttp.web.RouteTableDef", "aiohttp.web.json_response", "mathutils.Matrix", "aiohttp.web.HTTPBadRequest", "asyncio.get_event_loop", "bpy.data.actions.new" ]
[((187, 206), 'aiohttp.web.RouteTableDef', 'web.RouteTableDef', ([], {}), '()\n', (204, 206), False, 'from aiohttp import web\n'), ((1489, 1513), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1511, 1513), False, 'import asyncio\n'), ((1791, 1814), 'aiohttp.web.json_response', 'web.json_response', (['data'], {}), '(data)\n', (1808, 1814), False, 'from aiohttp import web\n'), ((3685, 3709), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3707, 3709), False, 'import asyncio\n'), ((3991, 4019), 'aiohttp.web.json_response', 'web.json_response', ([], {'data': 'data'}), '(data=data)\n', (4008, 4019), False, 'from aiohttp import web\n'), ((4452, 4476), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4474, 4476), False, 'import asyncio\n'), ((4752, 4780), 'aiohttp.web.json_response', 'web.json_response', ([], {'data': 'data'}), '(data=data)\n', (4769, 4780), False, 'from aiohttp import web\n'), ((1049, 1075), 'numpy.array', 'np.array', (['obj.matrix_world'], {}), '(obj.matrix_world)\n', (1057, 1075), True, 'import numpy as np\n'), ((1456, 1476), 'aiohttp.web.HTTPBadRequest', 'web.HTTPBadRequest', ([], {}), '()\n', (1474, 1476), False, 'from aiohttp import web\n'), ((2176, 2223), 'bpy.data.actions.new', 'bpy.data.actions.new', ([], {'name': "(obj_name + '_action')"}), "(name=obj_name + '_action')\n", (2196, 2223), False, 'import bpy\n'), ((3652, 3672), 'aiohttp.web.HTTPBadRequest', 'web.HTTPBadRequest', ([], {}), '()\n', (3670, 3672), False, 'from aiohttp import web\n'), ((4419, 4439), 'aiohttp.web.HTTPBadRequest', 'web.HTTPBadRequest', ([], {}), '()\n', (4437, 4439), False, 'from aiohttp import web\n'), ((2875, 2895), 'mathutils.Matrix', 'Matrix', (['matrix_world'], {}), '(matrix_world)\n', (2881, 2895), False, 'from mathutils import Matrix, Vector\n')]
from copy import deepcopy from numba import jit,njit import numpy as np import pymctdh.opfactory as opfactory from pymctdh.cy.sparsemat import CSRmat#,matvec @njit(fastmath=True) def matvec(nrows,IA,JA,data,vec,outvec): """ """ d_ind = 0 for i in range(nrows): ncol = IA[i+1]-IA[i] for j in range(ncol): col_ind = JA[d_ind] outvec[i] = outvec[i] + data[d_ind]*vec[col_ind] d_ind += 1 return outvec def matadd(nrows,op1,a,op2,b): """ """ if op1 is None: opout = deepcopy(op2) opout.data *= b else: data = [] JA = [] IA = [0] ind1 = 0 ind2 = 0 for i in range(nrows): op1_col = op1.JA[op1.IA[i]:op1.IA[i+1]] op2_col = op2.JA[op2.IA[i]:op2.IA[i+1]] inds = np.union1d(op1_col,op2_col) IA.append( IA[i]+len(inds) ) for ind in inds: JA.append( ind ) dat = 0.0 if ind in op1_col: dat += a*op1.data[ind1] ind1 +=1 if ind in op2_col: dat += b*op2.data[ind2] ind2 +=1 data.append( dat ) data = np.array(data) IA = np.array(IA, dtype=np.intc) JA = np.array(JA, dtype=np.intc) opout = CSRmat(data, IA, JA) return opout #@njit(fastmath=True) def kron(nrows1,IA1,JA1,data1,nrows2,IA2,JA2,data2): """ """ data = [] JA = [] IA = [0] d_ind1 = 0 for i in range(nrows1): ncol1 = IA1[i+1]-IA1[i] for j in range(ncol1): col_ind1 = JA1[d_ind1] d_ind2 = 0 for k in range(nrows2): ncol2 = IA2[i+1]-IA2[i] IA.append( IA[-1] + ncol2 ) for l in range(ncol2): data.append( data1[d_ind1]*data2[d_ind2] ) JA.append( JA1[d_ind1]*nrows2 + JA2[d_ind2] ) d_ind2 += 1 d_ind += 1 return CSRmat(np.array(data), np.array(IA, dtype=int), np.array(JA, dtype=int)) class PBasis: """ """ def __init__(self, args, sparse=False): """ """ self.params = {} self.params['basis'] = args[0].lower() self.sparse = sparse # set up parameters for basis if self.params['basis'] == 'ho': self.params['npbf'] = args[1] self.params['mass'] = args[2] self.params['omega'] = args[3] if len(args) == 5: self.combined = args[4] else: self.combined = False if self.combined: self.npbfs = 1 for n in self.params['npbf']: self.npbfs *= n self.make_ops = opfactory.make_ho_ops_combined if not isinstance(self.params['mass'], list): mlist = [args[2] for i in range(len(args[1]))] self.params['mass'] = mlist if not isinstance(self.params['omega'], list): omlist = [args[2] for i in range(len(args[1]))] self.params['omega'] = omlist else: self.npbfs = self.params['npbf'] self.make_ops = opfactory.make_ho_ops #self.grid = make_ho_grid(self.params['npbf']) elif self.params['basis'] == 'sinc': self.params['npbf'] = args[1] self.params['qmin'] = args[2] self.params['qmax'] = args[3] self.params['dq'] = args[4] self.params['mass'] = args[5] if isinstance(self.params['npbf'], list): self.make_ops = opfactory.make_sinc_ops_combined else: self.make_ops = opfactory.make_sinc_ops self.grid = np.arange(qmin,qmax+dq,dq) elif self.params['basis'] == 'plane wave': if args[1]%2 == 0: self.params['npbf'] = args[1]+1 else: self.params['npbf'] = args[1] self.params['nm'] = int((args[1]-1)/2) self.params['mass'] = args[2] if len(args) == 4: self.combined = args[3] else: self.combined = False if self.combined: raise NotImplementedError else: self.make_ops = opfactory.make_planewave_ops elif self.params['basis'] == 'plane wave dvr': raise NotImplementedError #if args[1]%2 == 0: # self.params['npbf'] = args[1]+1 #else: # self.params['npbf'] = args[1] #self.params['nm'] = int((args[1]-1)/2) #self.params['mass'] = args[2] #if len(args) == 4: # self.combined = args[3] #else: # self.combined = False #if self.combined: # raise NotImplementedError #else: # self.make_ops = opfactory.make_planewave_ops # #self.grid = np.arange(qmin,qmax+dq,dq) elif self.params['basis'] == 'radial': raise NotImplementedError #self.params['npbf'] = args[1] #self.params['dq'] = args[2] #self.params['mass'] = args[3] else: raise ValueError("Not a valid basis.") def make_operators(self, ops, matrix=None): """Creates matrices for all the relevant operators used in the calculation. These matrices are then stored in a dictionary called self.ops. Input ----- ops - list of strings, all the operators that are used for this pbf """ try: self.ops except: self.ops = {} if matrix is None: matrix = [None for i in range(len(ops))] for i,op in enumerate(ops): if not op in self.ops: if matrix[i] is None: self.ops[op] = self.make_ops(self.params,op,sparse=self.sparse) else: self.ops[op] = matrix[i] ## TODO make this for custom operators #if isinstance(op,str): # self.ops[op] = self.make_ops(params,op) #else: # ind = 'c%d'%(count) # count += 1 # self.ops[op] = op.copy() def make_1b_ham(self, nel, terms): """Make the 1-body hamiltonians that act on the spfs with this pbf. """ op1b = [] for alpha in range(nel): if self.sparse: op = None else: #op = np.zeros((self.params['npbf'],)*2) op = np.zeros((self.npbfs,)*2) for term in terms[alpha]: opstr = term['ops'][0] coeff = term['coeff'] if self.sparse: #op = matadd(self.params['npbf'],op,1.0,self.ops[opstr],coeff) op = matadd(self.npbfs,op,1.0,self.ops[opstr],coeff) else: #print(type(coeff)) op = op.astype(type(coeff)) op += coeff*self.ops[opstr] op1b.append( op ) self.ops['1b'] = op1b return def operate1b(self, spf, alpha): """Operate the single-body hamiltonian on a single spf. """ if self.sparse: op = self.ops['1b'][alpha] outvec = np.zeros(op.nrows, dtype=complex) return matvec(op.nrows,op.IA,op.JA,op.data,spf,outvec) #return matvec(op,spf) else: return np.dot(self.ops['1b'][alpha], spf) def operate(self, spf, term): """Operate a single-body term on a single spf. """ #return self.ops[term]@spf if self.sparse: op = self.ops[term] outvec = np.zeros(op.nrows, dtype=complex) return matvec(op.nrows,op.IA,op.JA,op.data,spf,outvec) #return matvec(self.ops[term], spf) else: return np.dot(self.ops[term], spf) if __name__ == "__main__": # no mode combination pbf = PBasis(['ho',22,1.0,1.0]) pbf.make_operators(['q','KE','q^2']) print(pbf.params['basis']) print(pbf.params['npbf']) print(pbf.params['mass']) print(pbf.params['omega']) opkeys = pbf.ops.keys() for op in opkeys: print(op) print(pbf.ops[op].shape) print('') print('') # mode combination pbf = PBasis(['ho',[6,6],1.0,1.0,True]) pbf.make_operators(['(q)*(1)','(1)*(q)']) print(pbf.params['basis']) print(pbf.params['npbf']) print(pbf.params['mass']) print(pbf.params['omega']) opkeys = pbf.ops.keys() for op in opkeys: print(op) print(pbf.ops[op].shape) print('') print('') # mode combination pbf = PBasis(['ho',[6,6],[1.0,2.0],[1.0,2.0],True]) pbf.make_operators(['(q)*(1)','(1)*(q)']) print(pbf.params['basis']) print(pbf.params['npbf']) print(pbf.params['mass']) print(pbf.params['omega']) opkeys = pbf.ops.keys() for op in opkeys: print(op) print(pbf.ops[op].shape) print('') print('')
[ "numpy.union1d", "numba.njit", "pymctdh.cy.sparsemat.CSRmat", "numpy.array", "numpy.zeros", "numpy.dot", "copy.deepcopy", "numpy.arange" ]
[((162, 181), 'numba.njit', 'njit', ([], {'fastmath': '(True)'}), '(fastmath=True)\n', (166, 181), False, 'from numba import jit, njit\n'), ((557, 570), 'copy.deepcopy', 'deepcopy', (['op2'], {}), '(op2)\n', (565, 570), False, 'from copy import deepcopy\n'), ((1268, 1282), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1276, 1282), True, 'import numpy as np\n'), ((1299, 1326), 'numpy.array', 'np.array', (['IA'], {'dtype': 'np.intc'}), '(IA, dtype=np.intc)\n', (1307, 1326), True, 'import numpy as np\n'), ((1343, 1370), 'numpy.array', 'np.array', (['JA'], {'dtype': 'np.intc'}), '(JA, dtype=np.intc)\n', (1351, 1370), True, 'import numpy as np\n'), ((1387, 1407), 'pymctdh.cy.sparsemat.CSRmat', 'CSRmat', (['data', 'IA', 'JA'], {}), '(data, IA, JA)\n', (1393, 1407), False, 'from pymctdh.cy.sparsemat import CSRmat\n'), ((2081, 2095), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2089, 2095), True, 'import numpy as np\n'), ((2097, 2120), 'numpy.array', 'np.array', (['IA'], {'dtype': 'int'}), '(IA, dtype=int)\n', (2105, 2120), True, 'import numpy as np\n'), ((2122, 2145), 'numpy.array', 'np.array', (['JA'], {'dtype': 'int'}), '(JA, dtype=int)\n', (2130, 2145), True, 'import numpy as np\n'), ((844, 872), 'numpy.union1d', 'np.union1d', (['op1_col', 'op2_col'], {}), '(op1_col, op2_col)\n', (854, 872), True, 'import numpy as np\n'), ((7567, 7600), 'numpy.zeros', 'np.zeros', (['op.nrows'], {'dtype': 'complex'}), '(op.nrows, dtype=complex)\n', (7575, 7600), True, 'import numpy as np\n'), ((7736, 7770), 'numpy.dot', 'np.dot', (["self.ops['1b'][alpha]", 'spf'], {}), "(self.ops['1b'][alpha], spf)\n", (7742, 7770), True, 'import numpy as np\n'), ((7985, 8018), 'numpy.zeros', 'np.zeros', (['op.nrows'], {'dtype': 'complex'}), '(op.nrows, dtype=complex)\n', (7993, 8018), True, 'import numpy as np\n'), ((8167, 8194), 'numpy.dot', 'np.dot', (['self.ops[term]', 'spf'], {}), '(self.ops[term], spf)\n', (8173, 8194), True, 'import numpy as np\n'), ((3908, 3938), 'numpy.arange', 'np.arange', (['qmin', '(qmax + dq)', 'dq'], {}), '(qmin, qmax + dq, dq)\n', (3917, 3938), True, 'import numpy as np\n'), ((6807, 6834), 'numpy.zeros', 'np.zeros', (['((self.npbfs,) * 2)'], {}), '((self.npbfs,) * 2)\n', (6815, 6834), True, 'import numpy as np\n')]
# Copyright (c) 2020 DeNA Co., Ltd. # Licensed under The MIT License [see LICENSE for details] # kaggle_environments licensed under Copyright 2020 Kaggle Inc. and the Apache License, Version 2.0 # (see https://github.com/Kaggle/kaggle-environments/blob/master/LICENSE for details) # wrapper of Hungry Geese environment from kaggle import random import itertools import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import handyrl.envs.kaggle.public_flood_goose as pfg # You need to install kaggle_environments, requests from kaggle_environments import make from kaggle_environments.envs.hungry_geese.hungry_geese import Observation, Configuration, Action, GreedyAgent from ...environment import BaseEnvironment class TorusConv2d(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, bn): super().__init__() self.edge_size = (kernel_size[0] // 2, kernel_size[1] // 2) self.conv = nn.Conv2d(input_dim, output_dim, kernel_size=kernel_size, padding = self.edge_size, padding_mode = 'circular') self.bn = nn.BatchNorm2d(output_dim) if bn else None def forward(self, x): h = self.conv(x) h = self.bn(h) if self.bn is not None else h return h ''' class GeeseNet(nn.Module): def __init__(self): super().__init__() layers, filters = 12, 32 self.conv0 = TorusConv2d(53, filters, (3, 3), True) # TBD self.blocks = nn.ModuleList([TorusConv2d(filters, filters, (3, 3), True) for _ in range(layers)]) self.head_p = nn.Linear(filters, 4, bias=False) self.head_v = nn.Linear(filters * 2, 1, bias=False) def forward(self, x, _=None): h = F.relu_(self.conv0(x)) for block in self.blocks: h = F.relu_(h + block(h)) h_head = (h * x[:,:1]).view(h.size(0), h.size(1), -1).sum(-1) h_avg = h.view(h.size(0), h.size(1), -1).mean(-1) p = self.head_p(h_head) v = torch.tanh(self.head_v(torch.cat([h_head, h_avg], 1))) return {'policy': p, 'value': v} ''' class GeeseNet(nn.Module): def __init__(self): super().__init__() layers, filters = 14, 32 self.conv0 = TorusConv2d(53, filters, (3, 3), True) # TBD self.blocks = nn.ModuleList([TorusConv2d(filters, filters, (3, 3), True) for _ in range(layers)]) self.head_p = nn.Linear(filters, 4, bias=False) self.head_v = nn.Linear(filters * 2, 1, bias=False) def forward(self, x, _=None): h = F.relu_(self.conv0(x)) for block in self.blocks: h = F.relu_(h + block(h)) h_head = (h * x[:,:1]).view(h.size(0), h.size(1), -1).sum(-1) h_avg = h.view(h.size(0), h.size(1), -1).mean(-1) p = self.head_p(h_head) v = torch.tanh(self.head_v(torch.cat([h_head, h_avg], 1))) return {'policy': p, 'value': v} class Environment(BaseEnvironment): ACTION = ['NORTH', 'SOUTH', 'WEST', 'EAST'] DIRECTION = [[-1, 0], [1, 0], [0, -1], [0, 1]] NUM_AGENTS = 4 ACTION_MAP = {'N': Action.NORTH, 'S': Action.SOUTH, 'W': Action.WEST, 'E': Action.EAST} pfg_action_map = { Action.NORTH: 'NORTH', Action.SOUTH: 'SOUTH', Action.WEST: 'WEST', Action.EAST: 'EAST'} def __init__(self, args={}): super().__init__() self.env = make("hungry_geese") self.reset() def reset(self, args={}): obs = self.env.reset(num_agents=self.NUM_AGENTS) self.update((obs, {}), True) def update(self, info, reset): obs, last_actions = info if reset: self.obs_list = [] self.obs_list.append(obs) self.last_actions = last_actions def action2str(self, a, player=None): return self.ACTION[a] def str2action(self, s, player=None): return self.ACTION.index(s) def direction(self, pos_from, pos_to): if pos_from is None or pos_to is None: return None x, y = pos_from // 11, pos_from % 11 for i, d in enumerate(self.DIRECTION): nx, ny = (x + d[0]) % 7, (y + d[1]) % 11 if nx * 11 + ny == pos_to: return i return None def __str__(self): # output state obs = self.obs_list[-1][0]['observation'] colors = ['\033[33m', '\033[34m', '\033[32m', '\033[31m'] color_end = '\033[0m' def check_cell(pos): for i, geese in enumerate(obs['geese']): if pos in geese: if pos == geese[0]: return i, 'h' if pos == geese[-1]: return i, 't' index = geese.index(pos) pos_prev = geese[index - 1] if index > 0 else None pos_next = geese[index + 1] if index < len(geese) - 1 else None directions = [self.direction(pos, pos_prev), self.direction(pos, pos_next)] return i, directions if pos in obs['food']: return 'f' return None def cell_string(cell): if cell is None: return '.' elif cell == 'f': return 'f' else: index, directions = cell if directions == 'h': return colors[index] + '@' + color_end elif directions == 't': return colors[index] + '*' + color_end elif max(directions) < 2: return colors[index] + '|' + color_end elif min(directions) >= 2: return colors[index] + '-' + color_end else: return colors[index] + '+' + color_end cell_status = [check_cell(pos) for pos in range(7 * 11)] s = 'turn %d\n' % len(self.obs_list) for x in range(7): for y in range(11): pos = x * 11 + y s += cell_string(cell_status[pos]) s += '\n' for i, geese in enumerate(obs['geese']): s += colors[i] + str(len(geese) or '-') + color_end + ' ' return s def step(self, actions): # state transition obs = self.env.step([self.action2str(actions.get(p, None) or 0) for p in self.players()]) self.update((obs, actions), False) def diff_info(self, _): return self.obs_list[-1], self.last_actions def turns(self): # players to move return [p for p in self.players() if self.obs_list[-1][p]['status'] == 'ACTIVE'] def terminal(self): # check whether terminal state or not for obs in self.obs_list[-1]: if obs['status'] == 'ACTIVE': return False return True def outcome(self): # return terminal outcomes # 1st: 1.0 2nd: 0.33 3rd: -0.33 4th: -1.00 rewards = {o['observation']['index']: o['reward'] for o in self.obs_list[-1]} outcomes = {p: 0 for p in self.players()} for p, r in rewards.items(): for pp, rr in rewards.items(): if p != pp: if r > rr: outcomes[p] += 1 / (self.NUM_AGENTS - 1) elif r < rr: outcomes[p] -= 1 / (self.NUM_AGENTS - 1) return outcomes def legal_actions(self, player): # return legal action list return list(range(len(self.ACTION))) def action_length(self): # maximum action label (it determines output size of policy function) return len(self.ACTION) def players(self): return list(range(self.NUM_AGENTS)) def rule_based_action(self, player): agent = GreedyAgent(Configuration({'rows': 7, 'columns': 11})) agent.last_action = self.ACTION_MAP[self.ACTION[self.last_actions[player]][0]] if player in self.last_actions else None obs = {**self.obs_list[-1][0]['observation'], **self.obs_list[-1][player]['observation']} action = agent(Observation(obs)) return self.ACTION.index(action) def public_flood_goose_based_action(self, player): obs = {**self.obs_list[-1][0]['observation'], **self.obs_list[-1][player]['observation']} conf = {'rows': 7, 'columns': 11} if player in self.last_actions and len(self.obs_list) > 1: prev_obs = {**self.obs_list[-2][0]['observation'], **self.obs_list[-2][player]['observation']} pos_int = prev_obs['geese'][prev_obs['index']][0] pfg.public_flood_agent_goose.last_pos = pfg.Pos(pos_int//11, pos_int%11) else: pfg.public_flood_agent_goose.last_pos = None # print("prev action = ", pfg.public_flood_agent_goose.last_action) state = pfg.State.from_obs_conf(obs, conf) action = pfg.public_flood_agent_goose.step(state) action = state.geo.action_to(state.my_goose.head, action) # print("action = ", action) # print("action = ",self.ACTION.index(self.pfg_action_map[action])) return self.ACTION.index(self.pfg_action_map[action]) def net(self): return GeeseNet def observation(self, player): # = None # if player is None: # player = 0 b = np.zeros((self.NUM_AGENTS * 13 + 1, 7 * 11), dtype=np.float32) # TBD obs = self.obs_list[-1][0]['observation'] for p, geese in enumerate(obs['geese']): # head position for pos in geese[:1]: b[0 + (p - player) % self.NUM_AGENTS, pos] = 1 # whole position for pos in geese: b[4 + (p - player) % self.NUM_AGENTS, pos] = 1 # body position for pos in geese[1:-1]: b[8 + (p - player) % self.NUM_AGENTS, pos] = 1 # tip position for pos in geese[-1:]: b[12 + (p - player) % self.NUM_AGENTS, pos] = 1 # previous head positon: see below # code attached below: line 16,17,18,19 # potential next move for pos in geese[:1]: b[20 + (p - player) % self.NUM_AGENTS, (pos - 1)%77] = 1 b[20 + (p - player) % self.NUM_AGENTS, (pos + 1)%77] = 1 b[20 + (p - player) % self.NUM_AGENTS, (pos - 11)%77] = 1 b[20 + (p - player) % self.NUM_AGENTS, (pos + 11)%77] = 1 # the impossible part will be removed in the previous head positions # snake length for each player b[24 + (p - player) % self.NUM_AGENTS, :] = len(geese)/77 # snake last second grid for pos in geese[-2:-1]: b[28 + (p - player) % self.NUM_AGENTS, pos] = 1 # snake last third grid for pos in geese[-3:-2]: b[32 + (p - player) % self.NUM_AGENTS, pos] = 1 # ordered grid snake for gridi, gridpos in enumerate(geese): b[36 + (p - player) % self.NUM_AGENTS, gridpos] = (len(geese) - gridi)/20 # previous head position if len(self.obs_list) > 1: obs_prev = self.obs_list[-2][0]['observation'] for p, geese in enumerate(obs_prev['geese']): for pos in geese[:1]: b[16 + (p - player) % self.NUM_AGENTS, pos] = 1 b[20 + (p - player) % self.NUM_AGENTS, pos] = 0 b[40, :] = b[0:4, :].sum(axis = 0) # all heads b[41, ] = b[4:8, :].sum(axis = 0) # all wholes b[42, ] = b[8:12, :].sum(axis = 0) # all bodies b[43, ] = b[12:16, :].sum(axis = 0) # all tails b[44, ] = b[16:20, :].sum(axis = 0) # all previous heads b[45, ] = b[20:24, :].max(axis = 0) # all potential steps b[46, ] = b[28:32, :].sum(axis = 0) # all last second grid b[47, ] = b[32:36, :].sum(axis = 0) # all last third grid b[48, ] = b[36:40, :].sum(axis = 0) # all ordered grid # food for pos in obs['food']: b[49, pos] = 1 # step, distance to next starving b[50, :] = obs['step']%40 / 40 # step, wether next turn will be starving b[51, :] = (obs['step']+1)% 40 == 0 b[52, :] = obs['step']/200 # TBD: centralizing player_head = obs['geese'][player][0] player_head_x = player_head//11 player_head_y = player_head%11 return b.reshape(-1, 7, 11) if __name__ == '__main__': e = Environment() for _ in range(100): e.reset() while not e.terminal(): print(e) actions = {p: e.legal_actions(p) for p in e.turns()} print([[e.action2str(a, p) for a in alist] for p, alist in actions.items()]) e.step({p: random.choice(alist) for p, alist in actions.items()}) print(e) print(e.outcome())
[ "torch.nn.BatchNorm2d", "random.choice", "kaggle_environments.envs.hungry_geese.hungry_geese.Observation", "handyrl.envs.kaggle.public_flood_goose.public_flood_agent_goose.step", "torch.nn.Conv2d", "torch.cat", "numpy.zeros", "torch.nn.Linear", "handyrl.envs.kaggle.public_flood_goose.State.from_obs_conf", "handyrl.envs.kaggle.public_flood_goose.Pos", "kaggle_environments.envs.hungry_geese.hungry_geese.Configuration", "kaggle_environments.make" ]
[((962, 1073), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_dim', 'output_dim'], {'kernel_size': 'kernel_size', 'padding': 'self.edge_size', 'padding_mode': '"""circular"""'}), "(input_dim, output_dim, kernel_size=kernel_size, padding=self.\n edge_size, padding_mode='circular')\n", (971, 1073), True, 'import torch.nn as nn\n'), ((2383, 2416), 'torch.nn.Linear', 'nn.Linear', (['filters', '(4)'], {'bias': '(False)'}), '(filters, 4, bias=False)\n', (2392, 2416), True, 'import torch.nn as nn\n'), ((2439, 2476), 'torch.nn.Linear', 'nn.Linear', (['(filters * 2)', '(1)'], {'bias': '(False)'}), '(filters * 2, 1, bias=False)\n', (2448, 2476), True, 'import torch.nn as nn\n'), ((3336, 3356), 'kaggle_environments.make', 'make', (['"""hungry_geese"""'], {}), "('hungry_geese')\n", (3340, 3356), False, 'from kaggle_environments import make\n'), ((8813, 8847), 'handyrl.envs.kaggle.public_flood_goose.State.from_obs_conf', 'pfg.State.from_obs_conf', (['obs', 'conf'], {}), '(obs, conf)\n', (8836, 8847), True, 'import handyrl.envs.kaggle.public_flood_goose as pfg\n'), ((8865, 8905), 'handyrl.envs.kaggle.public_flood_goose.public_flood_agent_goose.step', 'pfg.public_flood_agent_goose.step', (['state'], {}), '(state)\n', (8898, 8905), True, 'import handyrl.envs.kaggle.public_flood_goose as pfg\n'), ((9303, 9365), 'numpy.zeros', 'np.zeros', (['(self.NUM_AGENTS * 13 + 1, 7 * 11)'], {'dtype': 'np.float32'}), '((self.NUM_AGENTS * 13 + 1, 7 * 11), dtype=np.float32)\n', (9311, 9365), True, 'import numpy as np\n'), ((1091, 1117), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['output_dim'], {}), '(output_dim)\n', (1105, 1117), True, 'import torch.nn as nn\n'), ((7762, 7803), 'kaggle_environments.envs.hungry_geese.hungry_geese.Configuration', 'Configuration', (["{'rows': 7, 'columns': 11}"], {}), "({'rows': 7, 'columns': 11})\n", (7775, 7803), False, 'from kaggle_environments.envs.hungry_geese.hungry_geese import Observation, Configuration, Action, GreedyAgent\n'), ((8054, 8070), 'kaggle_environments.envs.hungry_geese.hungry_geese.Observation', 'Observation', (['obs'], {}), '(obs)\n', (8065, 8070), False, 'from kaggle_environments.envs.hungry_geese.hungry_geese import Observation, Configuration, Action, GreedyAgent\n'), ((8617, 8653), 'handyrl.envs.kaggle.public_flood_goose.Pos', 'pfg.Pos', (['(pos_int // 11)', '(pos_int % 11)'], {}), '(pos_int // 11, pos_int % 11)\n', (8624, 8653), True, 'import handyrl.envs.kaggle.public_flood_goose as pfg\n'), ((2814, 2843), 'torch.cat', 'torch.cat', (['[h_head, h_avg]', '(1)'], {}), '([h_head, h_avg], 1)\n', (2823, 2843), False, 'import torch\n'), ((12919, 12939), 'random.choice', 'random.choice', (['alist'], {}), '(alist)\n', (12932, 12939), False, 'import random\n')]
"""Utilities for approximating gradients.""" import numpy as np from utils.misc import process_inputs from utils.simrunners import SimulationRunner def local_linear_gradients(X, f, p=None, weights=None): """Estimate a collection of gradients from input/output pairs. Given a set of input/output pairs, choose subsets of neighboring points and build a local linear model for each subset. The gradients of these local linear models comprise estimates of sampled gradients. Parameters ---------- X : ndarray M-by-m matrix that contains the m-dimensional inputs f : ndarray M-by-1 matrix that contains scalar outputs p : int, optional how many nearest neighbors to use when constructing the local linear model (default 1) weights : ndarray, optional M-by-1 matrix that contains the weights for each observation (default None) Returns ------- df : ndarray M-by-m matrix that contains estimated partial derivatives approximated by the local linear models Notes ----- If `p` is not specified, the default value is floor(1.7*m). """ X, M, m = process_inputs(X) if M<=m: raise Exception('Not enough samples for local linear models.') if p is None: p = int(np.minimum(np.floor(1.7*m), M)) elif not isinstance(p, int): raise TypeError('p must be an integer.') if p < m+1 or p > M: raise Exception('p must be between m+1 and M') if weights is None: weights = np.ones((M, 1)) / M MM = np.minimum(int(np.ceil(10*m*np.log(m))), M-1) df = np.zeros((MM, m)) for i in range(MM): ii = np.random.randint(M) x = X[ii,:] D2 = np.sum((X - x)**2, axis=1) ind = np.argsort(D2) ind = ind[D2 != 0] A = np.hstack((np.ones((p,1)), X[ind[:p],:])) * np.sqrt(weights[ii]) b = f[ind[:p]] * np.sqrt(weights[ii]) u = np.linalg.lstsq(A, b)[0] df[i,:] = u[1:].T return df def finite_difference_gradients(X, fun, h=1e-6): """Compute finite difference gradients with a given interface. Parameters ---------- X : ndarray M-by-m matrix that contains the points to estimate the gradients with finite differences fun : function function that returns the simulation's quantity of interest given inputs h : float, optional the finite difference step size (default 1e-6) Returns ------- df : ndarray M-by-m matrix that contains estimated partial derivatives approximated by finite differences """ X, M, m = process_inputs(X) # points to run simulations including the perturbed inputs XX = np.kron(np.ones((m+1, 1)),X) + \ h*np.kron(np.vstack((np.zeros((1, m)), np.eye(m))), np.ones((M, 1))) # run the simulation if isinstance(fun, SimulationRunner): F = fun.run(XX) else: F = SimulationRunner(fun).run(XX) df = (F[M:].reshape((m, M)).transpose() - F[:M]) / h return df.reshape((M,m))
[ "numpy.eye", "numpy.sqrt", "numpy.ones", "numpy.log", "numpy.floor", "numpy.argsort", "numpy.sum", "numpy.zeros", "numpy.random.randint", "utils.simrunners.SimulationRunner", "numpy.linalg.lstsq", "utils.misc.process_inputs" ]
[((1186, 1203), 'utils.misc.process_inputs', 'process_inputs', (['X'], {}), '(X)\n', (1200, 1203), False, 'from utils.misc import process_inputs\n'), ((1646, 1663), 'numpy.zeros', 'np.zeros', (['(MM, m)'], {}), '((MM, m))\n', (1654, 1663), True, 'import numpy as np\n'), ((2664, 2681), 'utils.misc.process_inputs', 'process_inputs', (['X'], {}), '(X)\n', (2678, 2681), False, 'from utils.misc import process_inputs\n'), ((1701, 1721), 'numpy.random.randint', 'np.random.randint', (['M'], {}), '(M)\n', (1718, 1721), True, 'import numpy as np\n'), ((1755, 1783), 'numpy.sum', 'np.sum', (['((X - x) ** 2)'], {'axis': '(1)'}), '((X - x) ** 2, axis=1)\n', (1761, 1783), True, 'import numpy as np\n'), ((1796, 1810), 'numpy.argsort', 'np.argsort', (['D2'], {}), '(D2)\n', (1806, 1810), True, 'import numpy as np\n'), ((1561, 1576), 'numpy.ones', 'np.ones', (['(M, 1)'], {}), '((M, 1))\n', (1568, 1576), True, 'import numpy as np\n'), ((1894, 1914), 'numpy.sqrt', 'np.sqrt', (['weights[ii]'], {}), '(weights[ii])\n', (1901, 1914), True, 'import numpy as np\n'), ((1940, 1960), 'numpy.sqrt', 'np.sqrt', (['weights[ii]'], {}), '(weights[ii])\n', (1947, 1960), True, 'import numpy as np\n'), ((1973, 1994), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'b'], {}), '(A, b)\n', (1988, 1994), True, 'import numpy as np\n'), ((2763, 2782), 'numpy.ones', 'np.ones', (['(m + 1, 1)'], {}), '((m + 1, 1))\n', (2770, 2782), True, 'import numpy as np\n'), ((1326, 1343), 'numpy.floor', 'np.floor', (['(1.7 * m)'], {}), '(1.7 * m)\n', (1334, 1343), True, 'import numpy as np\n'), ((2848, 2863), 'numpy.ones', 'np.ones', (['(M, 1)'], {}), '((M, 1))\n', (2855, 2863), True, 'import numpy as np\n'), ((2979, 3000), 'utils.simrunners.SimulationRunner', 'SimulationRunner', (['fun'], {}), '(fun)\n', (2995, 3000), False, 'from utils.simrunners import SimulationRunner\n'), ((1619, 1628), 'numpy.log', 'np.log', (['m'], {}), '(m)\n', (1625, 1628), True, 'import numpy as np\n'), ((1861, 1876), 'numpy.ones', 'np.ones', (['(p, 1)'], {}), '((p, 1))\n', (1868, 1876), True, 'import numpy as np\n'), ((2817, 2833), 'numpy.zeros', 'np.zeros', (['(1, m)'], {}), '((1, m))\n', (2825, 2833), True, 'import numpy as np\n'), ((2835, 2844), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (2841, 2844), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from os.path import join as oj import os import pygsheets import pandas as pd import sys import inspect from datetime import datetime, timedelta currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) sys.path.append(parentdir + '/modeling') import load_data from fit_and_predict import fit_and_predict_ensemble from functions import merge_data from viz import viz_interactive import matplotlib.pyplot as plt import plotly.express as px import plotly def predictions_plot(df_county, NUM_DAYS_LIST, num_days_in_past, output_key): today = datetime.today().strftime("%B %d") day_past = (datetime.now() - timedelta(days=num_days_in_past)).strftime("%B %d") pred_key = f'Predicted deaths by {today}\n(predicted on {day_past})' deaths_key = f'Actual deaths by {today}' d = df_county.rename(columns={ output_key: pred_key, 'tot_deaths': deaths_key, }) minn = min(min(d[pred_key]), min(d[deaths_key])) + 1 maxx = max(max(d[pred_key]), max(d[deaths_key])) px.colors.DEFAULT_PLOTLY_COLORS[:3] = ['rgb(239,138,98)','rgb(247,247,247)','rgb(103,169,207)'] fig = px.scatter(d, x=deaths_key, y=pred_key, size='PopulationEstimate2018', hover_name="CountyName", hover_data=["CountyName", 'StateName'], log_x=True, log_y=True) fig.update_layout(shapes=[ dict( type= 'line', yref= 'y', y0=minn, y1=maxx, xref= 'x', x0=minn, x1=maxx, opacity=0.2 ) ]) fig.update_layout( paper_bgcolor='rgba(0,0,0,255)', plot_bgcolor='rgba(0,0,0,255)', template='plotly_dark', title='County-level predictions' ) plotly.offline.plot(fig, filename=oj(parentdir, 'results', 'predictions.html'), auto_open=False) if __name__ == '__main__': print('loading data...') NUM_DAYS_LIST = [1, 2, 3, 4, 5, 6, 7] df_county = load_data.load_county_level(data_dir=oj(parentdir, 'data')) num_days_in_past = 3 output_key = f'<PASSWORD>ed Deaths {num_days_in_past}-day' df_county = fit_and_predict_ensemble(df_county, outcome='deaths', mode='eval_mode', target_day=np.array([num_days_in_past]), output_key=output_key) df_county[output_key] = [v[0] for v in df_county[output_key].values] predictions_plot(df_county, NUM_DAYS_LIST, num_days_in_past, output_key)
[ "plotly.express.scatter", "inspect.currentframe", "os.path.join", "os.path.dirname", "numpy.array", "datetime.datetime.now", "datetime.datetime.today", "datetime.timedelta", "sys.path.append" ]
[((284, 311), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (299, 311), False, 'import os\n'), ((312, 338), 'sys.path.append', 'sys.path.append', (['parentdir'], {}), '(parentdir)\n', (327, 338), False, 'import sys\n'), ((339, 379), 'sys.path.append', 'sys.path.append', (["(parentdir + '/modeling')"], {}), "(parentdir + '/modeling')\n", (354, 379), False, 'import sys\n'), ((1248, 1416), 'plotly.express.scatter', 'px.scatter', (['d'], {'x': 'deaths_key', 'y': 'pred_key', 'size': '"""PopulationEstimate2018"""', 'hover_name': '"""CountyName"""', 'hover_data': "['CountyName', 'StateName']", 'log_x': '(True)', 'log_y': '(True)'}), "(d, x=deaths_key, y=pred_key, size='PopulationEstimate2018',\n hover_name='CountyName', hover_data=['CountyName', 'StateName'], log_x=\n True, log_y=True)\n", (1258, 1416), True, 'import plotly.express as px\n'), ((246, 268), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (266, 268), False, 'import inspect\n'), ((681, 697), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (695, 697), False, 'from datetime import datetime, timedelta\n'), ((1969, 2013), 'os.path.join', 'oj', (['parentdir', '"""results"""', '"""predictions.html"""'], {}), "(parentdir, 'results', 'predictions.html')\n", (1971, 2013), True, 'from os.path import join as oj\n'), ((2188, 2209), 'os.path.join', 'oj', (['parentdir', '"""data"""'], {}), "(parentdir, 'data')\n", (2190, 2209), True, 'from os.path import join as oj\n'), ((2501, 2529), 'numpy.array', 'np.array', (['[num_days_in_past]'], {}), '([num_days_in_past])\n', (2509, 2529), True, 'import numpy as np\n'), ((732, 746), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (744, 746), False, 'from datetime import datetime, timedelta\n'), ((749, 781), 'datetime.timedelta', 'timedelta', ([], {'days': 'num_days_in_past'}), '(days=num_days_in_past)\n', (758, 781), False, 'from datetime import datetime, timedelta\n')]
""" .. module:: cnn_train :synopsis: Example nuts-ml pipeline for training a MLP on MNIST """ import torch import torch.nn.functional as F import torch.nn as nn import torch.optim as optim import nutsflow as nf import nutsml as nm import numpy as np from nutsml.network import PytorchNetwork from utils import download_mnist, load_mnist class Model(nn.Module): """Pytorch model""" def __init__(self, device): """Construct model on given device, e.g. 'cpu' or 'cuda'""" super(Model, self).__init__() self.fc1 = nn.Linear(28 * 28, 500) self.fc2 = nn.Linear(500, 256) self.fc3 = nn.Linear(256, 10) self.to(device) # set device before constructing optimizer # required properties of a model to be wrapped as PytorchNetwork! self.device = device # 'cuda', 'cuda:0' or 'gpu' self.losses = nn.CrossEntropyLoss() # can be list of loss functions self.optimizer = optim.Adam(self.parameters()) def forward(self, x): """Forward pass through network for input x""" x = x.view(-1, 28 * 28) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def accuracy(y_true, y_pred): """Compute accuracy""" from sklearn.metrics import accuracy_score y_pred = [yp.argmax() for yp in y_pred] return 100 * accuracy_score(y_true, y_pred) def evaluate(network, x, y): """Evaluate network performance (here accuracy)""" metrics = [accuracy] build_batch = (nm.BuildBatch(64) .input(0, 'vector', 'float32') .output(1, 'number', 'int64')) acc = zip(x, y) >> build_batch >> network.evaluate(metrics) return acc def train(network, epochs=3): """Train network for given number of epochs""" print('loading data...') filepath = download_mnist() x_train, y_train, x_test, y_test = load_mnist(filepath) plot = nm.PlotLines(None, every_sec=0.2) build_batch = (nm.BuildBatch(128) .input(0, 'vector', 'float32') .output(1, 'number', 'int64')) for epoch in range(epochs): print('epoch', epoch + 1) losses = (zip(x_train, y_train) >> nf.PrintProgress(x_train) >> nf.Shuffle(1000) >> build_batch >> network.train() >> plot >> nf.Collect()) acc_test = evaluate(network, x_test, y_test) acc_train = evaluate(network, x_train, y_train) print('train loss : {:.6f}'.format(np.mean(losses))) print('train acc : {:.1f}'.format(acc_train)) print('test acc : {:.1f}'.format(acc_test)) if __name__ == '__main__': print('creating model...') device = 'cuda' if torch.cuda.is_available() else 'cpu' model = Model(device) network = PytorchNetwork(model) # network.load_weights() network.print_layers((28 * 28,)) print('training network...') train(network, epochs=3)
[ "numpy.mean", "utils.load_mnist", "torch.nn.CrossEntropyLoss", "nutsml.network.PytorchNetwork", "nutsflow.Collect", "nutsml.PlotLines", "utils.download_mnist", "torch.cuda.is_available", "nutsflow.Shuffle", "nutsflow.PrintProgress", "torch.nn.Linear", "nutsml.BuildBatch", "sklearn.metrics.accuracy_score" ]
[((1856, 1872), 'utils.download_mnist', 'download_mnist', ([], {}), '()\n', (1870, 1872), False, 'from utils import download_mnist, load_mnist\n'), ((1912, 1932), 'utils.load_mnist', 'load_mnist', (['filepath'], {}), '(filepath)\n', (1922, 1932), False, 'from utils import download_mnist, load_mnist\n'), ((1945, 1978), 'nutsml.PlotLines', 'nm.PlotLines', (['None'], {'every_sec': '(0.2)'}), '(None, every_sec=0.2)\n', (1957, 1978), True, 'import nutsml as nm\n'), ((2807, 2828), 'nutsml.network.PytorchNetwork', 'PytorchNetwork', (['model'], {}), '(model)\n', (2821, 2828), False, 'from nutsml.network import PytorchNetwork\n'), ((550, 573), 'torch.nn.Linear', 'nn.Linear', (['(28 * 28)', '(500)'], {}), '(28 * 28, 500)\n', (559, 573), True, 'import torch.nn as nn\n'), ((593, 612), 'torch.nn.Linear', 'nn.Linear', (['(500)', '(256)'], {}), '(500, 256)\n', (602, 612), True, 'import torch.nn as nn\n'), ((632, 650), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(10)'], {}), '(256, 10)\n', (641, 650), True, 'import torch.nn as nn\n'), ((875, 896), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (894, 896), True, 'import torch.nn as nn\n'), ((1371, 1401), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1385, 1401), False, 'from sklearn.metrics import accuracy_score\n'), ((2730, 2755), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2753, 2755), False, 'import torch\n'), ((2354, 2366), 'nutsflow.Collect', 'nf.Collect', ([], {}), '()\n', (2364, 2366), True, 'import nutsflow as nf\n'), ((2520, 2535), 'numpy.mean', 'np.mean', (['losses'], {}), '(losses)\n', (2527, 2535), True, 'import numpy as np\n'), ((1532, 1549), 'nutsml.BuildBatch', 'nm.BuildBatch', (['(64)'], {}), '(64)\n', (1545, 1549), True, 'import nutsml as nm\n'), ((1998, 2016), 'nutsml.BuildBatch', 'nm.BuildBatch', (['(128)'], {}), '(128)\n', (2011, 2016), True, 'import nutsml as nm\n'), ((2274, 2290), 'nutsflow.Shuffle', 'nf.Shuffle', (['(1000)'], {}), '(1000)\n', (2284, 2290), True, 'import nutsflow as nf\n'), ((2227, 2252), 'nutsflow.PrintProgress', 'nf.PrintProgress', (['x_train'], {}), '(x_train)\n', (2243, 2252), True, 'import nutsflow as nf\n')]
""" All the data sources are scattered around the D drive, this script organizes it and consolidates it into the "Data" subfolder in the "Chapter 2 Dune Aspect Ratio" folder. <NAME>, 5/6/2020 """ import shutil as sh import pandas as pd import numpy as np import os # Set the data directory to save files into DATA_DIR = os.path.join('..', 'Data') # Set the directory with most of the XBeach data XB_DIR = os.path.join('..', '..', 'XBeach Modelling', 'Dune Complexity Experiments') def bogue_lidar_data(): """ Load all Bogue Banks morphometrics from 1997-2016 and return a dataframe of aspect ratios and natural dune volumes """ # Set a list of years years = [1997, 1998, 1999, 2000, 2004, 2005, 2010, 2011, 2014, 2016] # Set an empty dataframe morpho = pd.DataFrame() # Loop through the years and load the data for year in years: # Set a path to the data and load path = os.path.join('..', '..', 'Chapter 1 Sand Fences', 'Data', f'Morphometrics for Bogue {year}.csv') temp = pd.read_csv(path, delimiter=',', header=0) # Add a column for the year temp['Year'] = year # Append the data to the main dataframe morpho = pd.concat([morpho, temp]) # Make a new dataframe with just aspect ratios and volumes data = pd.DataFrame() data['Year'] = morpho['Year'] data['Ratio'] = (morpho['y_crest'] - morpho['y_toe']) / (morpho['x_heel'] - morpho['x_toe']) data['Volume'] = morpho['Natural Dune Volume'] # Save the Dataframe to the data folder save_name = os.path.join(DATA_DIR, 'Bogue Banks Volumes and Aspect Ratios.csv') data.to_csv(save_name, index=False) print(f'File Saved: {save_name}') def initial_profiles(): """ Take all the initial profiles and place them into a Dataframe to save as a .csv Make a column for the experiment names, a column for the X-grids, and columns for the profiles """ # Set the experiment names. The initial profiles are the same regardless of # the surge level so just take from the half surge simulations experiments = ['Toes Joined', 'Crests Joined', 'Heels Joined', 'Fenced'] # Set an empty dataframe profiles = pd.DataFrame() # Loop through the experiments for experiment in experiments: # Set a path to the profiles PROFILE_DIR = os.path.join(XB_DIR, f'{experiment} Half Surge') # Load the x-grid x_grid_fname = os.path.join(PROFILE_DIR, 'Dune Complexity 1 1', 'x.grd') x_grid = np.loadtxt(x_grid_fname) # Load the dunes dune_1 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity 1 1', 'bed.dep')) dune_2 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity 20 1', 'bed.dep')) dune_3 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity 40 1', 'bed.dep')) dune_4 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity 60 1', 'bed.dep')) dune_5 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity -20 1', 'bed.dep')) dune_6 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity -40 1', 'bed.dep')) dune_7 = np.loadtxt(fname=os.path.join(PROFILE_DIR, 'Dune Complexity -60 1', 'bed.dep')) # Put all of the stretched dunes into a dataframe dune_dict = { 'Experiment': experiment.replace('Joined', 'Aligned'), 'X': x_grid, '1 pct': dune_1, '20 pct': dune_2, '40 pct': dune_3, '60 pct': dune_4, '-20 pct': dune_5, '-40 pct': dune_6, '-60 pct': dune_7, } dune_data = pd.DataFrame(data=dune_dict) # Concatenate the Dataframes profiles = pd.concat([profiles, dune_data]) # Save the Dataframe to the data folder save_name = os.path.join(DATA_DIR, 'Initial Profiles.csv') profiles.to_csv(save_name, index=False) print(f'File Saved: {save_name}') def initial_ratios(): """ Make a .csv file with the initial dune aspect ratios and dune volumes for the profiles used in the simulations """ # Set the experiment names. The initial profiles are the same regardless of # the surge level so just take from the half surge simulations experiments = ['Toes Joined', 'Crests Joined', 'Heels Joined', 'Fenced'] # Set an empty dataframe ratios = pd.DataFrame() # Loop through the experiments for experiment in experiments: # Load the initial dune ratios init_ratio_fname = os.path.join(XB_DIR, f'{experiment} Half Surge', 'Setup Data', 'Initial Dune Ratios.csv') init_ratios = pd.read_csv(init_ratio_fname, delimiter=',', header=None, names=['Stretch', 'Ratio', 'Volume']) # Add a column for the experiment name init_ratios['Experiment'] = experiment.replace('Joined', 'Aligned') # Concatenate the data ratios = pd.concat([ratios, init_ratios]) # Save the Dataframe to the data folder save_name = os.path.join(DATA_DIR, 'Initial Dune Ratios.csv') ratios.to_csv(save_name, index=False) print(f'File Saved: {save_name}') def joaquin_and_florence(): """ Load the storm surge time series' from Tropical Storm Joaquin and Hurricane Florence, put them in a .csv file """ # Loop through the storms for storm in ['Joaquin', 'Florence']: # Load the tide predictions and observations as a Pandas dataframe filename = os.path.join(XB_DIR, 'Setup Data', f'{storm}.csv') if storm == 'Joaquin': parse_dates_cols = ['Date', 'Time'] data_columns = ['Time', 'Predicted', 'Observed'] else: parse_dates_cols = ['Date', 'Time (GMT)'] data_columns = ['Time', 'Predicted', 'Preliminary', 'Observed'] data = pd.read_csv(filename, delimiter=',', parse_dates=[parse_dates_cols], header=0) data.columns = data_columns # Calculate the non-tidal residual data['NTR'] = data['Observed'] - data['Predicted'] # Load the time data times = data['Time'].tolist() data['String Times'] = [t.strftime('%Y-%m-%d %H') for t in times] # Save the DataFrame as a .csv save_name = os.path.join(DATA_DIR, f'{storm}.csv') data.to_csv(save_name, index=False) def move_csv_output(): """ Take the .csv files and move them into the "Data" folder, then rename them from "xboutput.nc" to the name of the simulation """ # Set lists with the dune configurations, storm surge # modifications, storm duration increases, and dune aspect # ratio stretches dunes = ['Toes Joined', 'Crests Joined', 'Heels Joined', 'Fenced'] surges = ['Half', 'Normal', 'One Half'] durations = [1, 12, 18, 24, 36, 48] stretches = [-60, -40, -20, 1, 20, 40, 60] # Loop through the dunes and surges for dune in dunes: for surge in surges: # Set the experiment folder name experiment_name = f'{dune} {surge} Surge' experiment_folder = os.path.join(XB_DIR, experiment_name) # Make a target folder to move the runs into save_folder = os.path.join(DATA_DIR, 'XBeach Morphometrics', experiment_name) if not os.path.exists(save_folder): os.mkdir(save_folder) # Loop through the dunes and durations within the experiment for stretch in stretches: for duration in durations: # Set the simulation folder run_name = f'Dune Complexity {stretch} {duration}' simulation_folder = os.path.join(experiment_folder, run_name) # Set the XBeach output file as the source. Set the destination # name. Then copy the file over source = os.path.join(simulation_folder, f'{run_name} Morphometrics.csv') if os.path.exists(source): destination = os.path.join(save_folder, f'{run_name} Morphometrics.csv') if not os.path.exists(destination): sh.copy(source, destination) print(f'File Successfully Copied: {destination}') else: print(f'File already exists: {destination}') else: print(f'FILE DOES NOT EXIST: {source}') def move_field_data(): """ Move the field data morphometrics from 2017 and 2018 into the data folder """ # Set the years years = [2017, 2018] # Set a path to the field data field_dir = os.path.join('..', '..', 'Bogue Banks Field Data') # Loop through the years for year in years: # Identify the source file source = os.path.join(field_dir, str(year), f'Morphometrics for Bogue Banks {year}.csv') # Set the target destination = os.path.join(DATA_DIR, f'Morphometrics for Bogue Banks {year}.csv') # Copy the file sh.copy(source, destination) def move_netcdf_output(): """ Take the netCDF files and move them into the "Data" folder, then rename them from "xboutput.nc" to the name of the simulation """ # Set lists with the dune configurations, storm surge # modifications, storm duration increases, and dune aspect # ratio stretches dunes = ['Toes Joined', 'Crests Joined', 'Heels Joined', 'Fenced'] surges = ['Half', 'Normal', 'One Half'] durations = [1, 12, 18, 24, 36, 48] stretches = [-60, -40, -20, 1, 20, 40, 60] # Loop through the dunes and surges for dune in dunes: for surge in surges: # Set the experiment folder name experiment_name = f'{dune} {surge} Surge' experiment_folder = os.path.join(XB_DIR, experiment_name) # Make a target folder to move the runs into save_folder = os.path.join(DATA_DIR, 'XBeach Output', experiment_name) if not os.path.exists(save_folder): os.mkdir(save_folder) # Loop through the dunes and durations within the experiment for stretch in stretches: for duration in durations: # Set the simulation folder run_name = f'Dune Complexity {stretch} {duration}' simulation_folder = os.path.join(experiment_folder, run_name) # Set the XBeach output file as the source. Set the destination # name. Then copy the file over source = os.path.join(simulation_folder, 'xboutput.nc') if os.path.exists(source): destination = os.path.join(save_folder, f'{run_name}.nc') if not os.path.exists(destination): sh.copy(source, destination) print(f'File Successfully Copied: {destination}') else: print(f'File already exists: {destination}') else: print(f'FILE DOES NOT EXIST: {source}') def surge_time_series(): """ Put all the storm time series' into a .csv file that can be loaded as a DataFrame """ # Set a list of storm surge modifiers # and storm duration increases surges, surge_labels = [0.5, 1.0, 1.5], ['Half', 'Normal', 'One Half'] durations = [1, 12, 18, 24, 36, 48] # Make an empty DataFrame to loop into surge_df = pd.DataFrame() # Loop through the surges for surge, label in zip(surges, surge_labels): # Loop through the durations for duration in durations: # The DataFrame won't work if the columns are different # lengths so place them all in a preset 125 "hour" long # array so that they'll fit in the DataFrame time_series = np.full((1, 125), fill_value=np.nan)[0] # Load the data and place it in the time series NaN array filename = os.path.join(XB_DIR, f'Toes Joined {label} Surge', f'Dune Complexity 1 {duration}', 'ntr.txt') ntr = np.genfromtxt(filename, dtype=np.float32) time_series[:len(ntr)] = ntr # Place the time series in the dict surge_df[f'{label} {duration}'] = time_series # Save the DataFrame as a .csv file save_name = os.path.join(DATA_DIR, 'Storm Surge Time Series.csv') surge_df.to_csv(save_name, index=False) def main(): """ Main program function to consolidate all the data sources """ # Make a .csv file with the initial profiles used # initial_profiles() # Make a .csv file with the initial dune ratios # initial_ratios() # Make a .csv file with all the natural dune volumes # and aspect ratios measured from Bogue Banks LiDAR # bogue_lidar_data() # Make a .csv file with the storm surge time # series' for all the model runs # surge_time_series() # Make a .csv file with storm surge data # for Tropical Storm Joaquin and <NAME> # joaquin_and_florence() # Move the netCDF output files into the Data folder # and rename them for the run name. Move the .csv # files with the morphometrics from the runs too # move_csv_output() # move_netcdf_output() # Move the Bogue Banks field data morphometrics # from 2017 and 2018 into the data folder move_field_data() if __name__ == '__main__': main()
[ "os.path.exists", "numpy.genfromtxt", "pandas.read_csv", "os.path.join", "os.mkdir", "shutil.copy", "pandas.DataFrame", "numpy.full", "numpy.loadtxt", "pandas.concat" ]
[((337, 363), 'os.path.join', 'os.path.join', (['""".."""', '"""Data"""'], {}), "('..', 'Data')\n", (349, 363), False, 'import os\n'), ((426, 501), 'os.path.join', 'os.path.join', (['""".."""', '""".."""', '"""XBeach Modelling"""', '"""Dune Complexity Experiments"""'], {}), "('..', '..', 'XBeach Modelling', 'Dune Complexity Experiments')\n", (438, 501), False, 'import os\n'), ((828, 842), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (840, 842), True, 'import pandas as pd\n'), ((1375, 1389), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1387, 1389), True, 'import pandas as pd\n'), ((1639, 1706), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""Bogue Banks Volumes and Aspect Ratios.csv"""'], {}), "(DATA_DIR, 'Bogue Banks Volumes and Aspect Ratios.csv')\n", (1651, 1706), False, 'import os\n'), ((2308, 2322), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2320, 2322), True, 'import pandas as pd\n'), ((3987, 4033), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""Initial Profiles.csv"""'], {}), "(DATA_DIR, 'Initial Profiles.csv')\n", (3999, 4033), False, 'import os\n'), ((4559, 4573), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4571, 4573), True, 'import pandas as pd\n'), ((5203, 5252), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""Initial Dune Ratios.csv"""'], {}), "(DATA_DIR, 'Initial Dune Ratios.csv')\n", (5215, 5252), False, 'import os\n'), ((8976, 9026), 'os.path.join', 'os.path.join', (['""".."""', '""".."""', '"""Bogue Banks Field Data"""'], {}), "('..', '..', 'Bogue Banks Field Data')\n", (8988, 9026), False, 'import os\n'), ((11958, 11972), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (11970, 11972), True, 'import pandas as pd\n'), ((12864, 12917), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""Storm Surge Time Series.csv"""'], {}), "(DATA_DIR, 'Storm Surge Time Series.csv')\n", (12876, 12917), False, 'import os\n'), ((978, 1078), 'os.path.join', 'os.path.join', (['""".."""', '""".."""', '"""Chapter 1 Sand Fences"""', '"""Data"""', 'f"""Morphometrics for Bogue {year}.csv"""'], {}), "('..', '..', 'Chapter 1 Sand Fences', 'Data',\n f'Morphometrics for Bogue {year}.csv')\n", (990, 1078), False, 'import os\n'), ((1091, 1133), 'pandas.read_csv', 'pd.read_csv', (['path'], {'delimiter': '""","""', 'header': '(0)'}), "(path, delimiter=',', header=0)\n", (1102, 1133), True, 'import pandas as pd\n'), ((1271, 1296), 'pandas.concat', 'pd.concat', (['[morpho, temp]'], {}), '([morpho, temp])\n', (1280, 1296), True, 'import pandas as pd\n'), ((2460, 2508), 'os.path.join', 'os.path.join', (['XB_DIR', 'f"""{experiment} Half Surge"""'], {}), "(XB_DIR, f'{experiment} Half Surge')\n", (2472, 2508), False, 'import os\n'), ((2562, 2619), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity 1 1"""', '"""x.grd"""'], {}), "(PROFILE_DIR, 'Dune Complexity 1 1', 'x.grd')\n", (2574, 2619), False, 'import os\n'), ((2638, 2662), 'numpy.loadtxt', 'np.loadtxt', (['x_grid_fname'], {}), '(x_grid_fname)\n', (2648, 2662), True, 'import numpy as np\n'), ((3801, 3829), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'dune_dict'}), '(data=dune_dict)\n', (3813, 3829), True, 'import pandas as pd\n'), ((3890, 3922), 'pandas.concat', 'pd.concat', (['[profiles, dune_data]'], {}), '([profiles, dune_data])\n', (3899, 3922), True, 'import pandas as pd\n'), ((4718, 4811), 'os.path.join', 'os.path.join', (['XB_DIR', 'f"""{experiment} Half Surge"""', '"""Setup Data"""', '"""Initial Dune Ratios.csv"""'], {}), "(XB_DIR, f'{experiment} Half Surge', 'Setup Data',\n 'Initial Dune Ratios.csv')\n", (4730, 4811), False, 'import os\n'), ((4831, 4930), 'pandas.read_csv', 'pd.read_csv', (['init_ratio_fname'], {'delimiter': '""","""', 'header': 'None', 'names': "['Stretch', 'Ratio', 'Volume']"}), "(init_ratio_fname, delimiter=',', header=None, names=['Stretch',\n 'Ratio', 'Volume'])\n", (4842, 4930), True, 'import pandas as pd\n'), ((5106, 5138), 'pandas.concat', 'pd.concat', (['[ratios, init_ratios]'], {}), '([ratios, init_ratios])\n', (5115, 5138), True, 'import pandas as pd\n'), ((5685, 5735), 'os.path.join', 'os.path.join', (['XB_DIR', '"""Setup Data"""', 'f"""{storm}.csv"""'], {}), "(XB_DIR, 'Setup Data', f'{storm}.csv')\n", (5697, 5735), False, 'import os\n'), ((6042, 6120), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'delimiter': '""","""', 'parse_dates': '[parse_dates_cols]', 'header': '(0)'}), "(filename, delimiter=',', parse_dates=[parse_dates_cols], header=0)\n", (6053, 6120), True, 'import pandas as pd\n'), ((6473, 6511), 'os.path.join', 'os.path.join', (['DATA_DIR', 'f"""{storm}.csv"""'], {}), "(DATA_DIR, f'{storm}.csv')\n", (6485, 6511), False, 'import os\n'), ((9270, 9337), 'os.path.join', 'os.path.join', (['DATA_DIR', 'f"""Morphometrics for Bogue Banks {year}.csv"""'], {}), "(DATA_DIR, f'Morphometrics for Bogue Banks {year}.csv')\n", (9282, 9337), False, 'import os\n'), ((9374, 9402), 'shutil.copy', 'sh.copy', (['source', 'destination'], {}), '(source, destination)\n', (9381, 9402), True, 'import shutil as sh\n'), ((7324, 7361), 'os.path.join', 'os.path.join', (['XB_DIR', 'experiment_name'], {}), '(XB_DIR, experiment_name)\n', (7336, 7361), False, 'import os\n'), ((7449, 7512), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""XBeach Morphometrics"""', 'experiment_name'], {}), "(DATA_DIR, 'XBeach Morphometrics', experiment_name)\n", (7461, 7512), False, 'import os\n'), ((10175, 10212), 'os.path.join', 'os.path.join', (['XB_DIR', 'experiment_name'], {}), '(XB_DIR, experiment_name)\n', (10187, 10212), False, 'import os\n'), ((10300, 10356), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""XBeach Output"""', 'experiment_name'], {}), "(DATA_DIR, 'XBeach Output', experiment_name)\n", (10312, 10356), False, 'import os\n'), ((12496, 12594), 'os.path.join', 'os.path.join', (['XB_DIR', 'f"""Toes Joined {label} Surge"""', 'f"""Dune Complexity 1 {duration}"""', '"""ntr.txt"""'], {}), "(XB_DIR, f'Toes Joined {label} Surge',\n f'Dune Complexity 1 {duration}', 'ntr.txt')\n", (12508, 12594), False, 'import os\n'), ((12610, 12651), 'numpy.genfromtxt', 'np.genfromtxt', (['filename'], {'dtype': 'np.float32'}), '(filename, dtype=np.float32)\n', (12623, 12651), True, 'import numpy as np\n'), ((2726, 2785), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity 1 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity 1 1', 'bed.dep')\n", (2738, 2785), False, 'import os\n'), ((2822, 2882), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity 20 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity 20 1', 'bed.dep')\n", (2834, 2882), False, 'import os\n'), ((2919, 2979), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity 40 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity 40 1', 'bed.dep')\n", (2931, 2979), False, 'import os\n'), ((3016, 3076), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity 60 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity 60 1', 'bed.dep')\n", (3028, 3076), False, 'import os\n'), ((3113, 3174), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity -20 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity -20 1', 'bed.dep')\n", (3125, 3174), False, 'import os\n'), ((3211, 3272), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity -40 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity -40 1', 'bed.dep')\n", (3223, 3272), False, 'import os\n'), ((3309, 3370), 'os.path.join', 'os.path.join', (['PROFILE_DIR', '"""Dune Complexity -60 1"""', '"""bed.dep"""'], {}), "(PROFILE_DIR, 'Dune Complexity -60 1', 'bed.dep')\n", (3321, 3370), False, 'import os\n'), ((7533, 7560), 'os.path.exists', 'os.path.exists', (['save_folder'], {}), '(save_folder)\n', (7547, 7560), False, 'import os\n'), ((7579, 7600), 'os.mkdir', 'os.mkdir', (['save_folder'], {}), '(save_folder)\n', (7587, 7600), False, 'import os\n'), ((10377, 10404), 'os.path.exists', 'os.path.exists', (['save_folder'], {}), '(save_folder)\n', (10391, 10404), False, 'import os\n'), ((10423, 10444), 'os.mkdir', 'os.mkdir', (['save_folder'], {}), '(save_folder)\n', (10431, 10444), False, 'import os\n'), ((12359, 12395), 'numpy.full', 'np.full', (['(1, 125)'], {'fill_value': 'np.nan'}), '((1, 125), fill_value=np.nan)\n', (12366, 12395), True, 'import numpy as np\n'), ((7924, 7965), 'os.path.join', 'os.path.join', (['experiment_folder', 'run_name'], {}), '(experiment_folder, run_name)\n', (7936, 7965), False, 'import os\n'), ((8136, 8200), 'os.path.join', 'os.path.join', (['simulation_folder', 'f"""{run_name} Morphometrics.csv"""'], {}), "(simulation_folder, f'{run_name} Morphometrics.csv')\n", (8148, 8200), False, 'import os\n'), ((8225, 8247), 'os.path.exists', 'os.path.exists', (['source'], {}), '(source)\n', (8239, 8247), False, 'import os\n'), ((10768, 10809), 'os.path.join', 'os.path.join', (['experiment_folder', 'run_name'], {}), '(experiment_folder, run_name)\n', (10780, 10809), False, 'import os\n'), ((10980, 11026), 'os.path.join', 'os.path.join', (['simulation_folder', '"""xboutput.nc"""'], {}), "(simulation_folder, 'xboutput.nc')\n", (10992, 11026), False, 'import os\n'), ((11051, 11073), 'os.path.exists', 'os.path.exists', (['source'], {}), '(source)\n', (11065, 11073), False, 'import os\n'), ((8288, 8346), 'os.path.join', 'os.path.join', (['save_folder', 'f"""{run_name} Morphometrics.csv"""'], {}), "(save_folder, f'{run_name} Morphometrics.csv')\n", (8300, 8346), False, 'import os\n'), ((11114, 11157), 'os.path.join', 'os.path.join', (['save_folder', 'f"""{run_name}.nc"""'], {}), "(save_folder, f'{run_name}.nc')\n", (11126, 11157), False, 'import os\n'), ((8379, 8406), 'os.path.exists', 'os.path.exists', (['destination'], {}), '(destination)\n', (8393, 8406), False, 'import os\n'), ((8437, 8465), 'shutil.copy', 'sh.copy', (['source', 'destination'], {}), '(source, destination)\n', (8444, 8465), True, 'import shutil as sh\n'), ((11190, 11217), 'os.path.exists', 'os.path.exists', (['destination'], {}), '(destination)\n', (11204, 11217), False, 'import os\n'), ((11248, 11276), 'shutil.copy', 'sh.copy', (['source', 'destination'], {}), '(source, destination)\n', (11255, 11276), True, 'import shutil as sh\n')]
def end_of_import(): return 0 def end_of_init(): return 0 def end_of_computing(): return 0 import numpy as np from sklearn.linear_model import LinearRegression end_of_import() X = np.array(range(0,100000)).reshape(-1, 1) # y = 2x + 3 y = np.dot(X, 2) + 3 end_of_init() reg = LinearRegression().fit(X, y) end_of_computing()
[ "numpy.dot", "sklearn.linear_model.LinearRegression" ]
[((254, 266), 'numpy.dot', 'np.dot', (['X', '(2)'], {}), '(X, 2)\n', (260, 266), True, 'import numpy as np\n'), ((292, 310), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (308, 310), False, 'from sklearn.linear_model import LinearRegression\n')]
# # # Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the License); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an AS IS BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from sympy.ntheory import factorint import numpy as np from sympy.combinatorics import Permutation import io import math from config.strtools import * import itertools import struct import config.formats # Conversion of double to fixed point values # # - 8000 gives 8000 in C (int16) # So when it is multiplied it will give the wrong sign for the result # of the multiplication except if DSPE instructions with saturation are used # to compute the negate (and we should get 7FFF). # # So for cortex-m without DSP extension, we should try to use 8001 # It is done but not yet tested. def to_q63(v,dspe): r = int(round(v * 2**63)) if (r > 0x07FFFFFFFFFFFFFFF): r = 0x07FFFFFFFFFFFFFFF if (r < -0x08000000000000000): if dspe: r = -0x08000000000000000 else: r = -0x07FFFFFFFFFFFFFFF return ("0x%s" % format(struct.unpack('<Q', struct.pack('<q', r))[0],'016X')) def to_q31(v,dspe): r = int(round(v * 2**31)) if (r > 0x07FFFFFFF): r = 0x07FFFFFFF if (r < -0x080000000): if dspe: r = -0x080000000 else: r = -0x07FFFFFFF return ("0x%s" % format(struct.unpack('<I', struct.pack('<i', r))[0],'08X')) def to_q15(v,dspe): r = int(round(v * 2**15)) if (r > 0x07FFF): r = 0x07FFF if (r < -0x08000): if dspe: r = -0x08000 else: r = -0x07FFF return ("0x%s" % format(struct.unpack('<H', struct.pack('<h', r))[0],'04X')) def to_q7(v,dspe): r = int(round(v * 2**7)) if (r > 0x07F): r = 0x07F if (r < -0x080):# if dspe: r = -0x080 else: r = -0x07F return ("0x%s" % format(struct.unpack('<B', struct.pack('<b', r))[0],'02X')) Q7=1 Q15=2 Q31=3 F16=4 F32=5 F64=6 # In the final C++ code, we have a loop for a given radix. # The input list here has not grouped the factors. # The list need to be transformed into a list of pair. # The pair being (radix,exponent) def groupFactors(factors): n = 0 current=-1 result=[] for f in factors: if f != current: if current != -1: result = result + [current,n] current=f n=1 else: n=n+1 result = result + [current,n] return(result) # Compute the grouped factors for the the FFT length originaln # where the only possible radix are in primitiveFactors list. def getFactors(primitiveFactors,originaln): factors=[] length=[] primitiveFactors.sort(reverse=True) n = originaln while (n > 1) and primitiveFactors: if (n % primitiveFactors[0] == 0): factors.append(primitiveFactors[0]) n = n // primitiveFactors[0] else: primitiveFactors=primitiveFactors[1:] # When lowest factors are at the beginning (like 2) # we use a special implementation of the loopcore template # and it is removing some cycles. # So, we will get (for instance) 2x8x8x8 instead of 8x8x8x2 factors.reverse() for f in factors: originaln = originaln // f length.append(originaln) groupedfactors=groupFactors(factors) return(groupedfactors,factors,length) # Apply the radix decomposition to compute the input -> output permutation # computed by the FFT. def radixReverse(f,n): a=np.array(range(0,n)).reshape(f) r = list(range(0,len(f))) r.reverse() r = tuple(r) a = np.transpose(a,r) return(a.reshape(n)) def radixPermutation(factors,n): a = radixReverse(factors,n) tps = [] vectorizable=True for c in Permutation.from_sequence(a).cyclic_form: if (len(c)>2): vectorizable = False for i in range(len(c)-1,0,-1): # 2 because those are indexes in an array of complex numbers but # with a real type. tps.append([2*c[i], 2*c[i-1]]) return(np.array(tps,dtype=int).flatten(),vectorizable) # CFFT Twiddle table def cfft_twiddle(n): a=2.0*math.pi*np.linspace(0,n,num=n,endpoint=False)/n c=np.cos(-a) s=np.sin(-a) r = np.empty((c.size + s.size,), dtype=c.dtype) r[0::2] = c r[1::2] = s return(r) # RFFT twiddle for the merge and split steps. def rfft_twiddle(n): a=2.0j*math.pi*np.linspace(0,n//2,num=n // 2,endpoint=False)/n z=-1.0j * np.exp(-a) r = z.view(dtype=np.float64) return(r) # Compute the twiddle tables def twiddle(transform,n): if transform=="CFFT": return(cfft_twiddle(n)) if transform=="RFFT": return(rfft_twiddle(n)) return(None) NB_ELEMS_PER_LINE=3 # Generate C array content for a given datatype def printFloat64Array(f,n): nb=0 for s in n: print("%.20f, " % s,end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) def printFloat32Array(f,n): nb=0 for s in n: print("%.20ff, " % s,end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) def printFloat16Array(f,n): nb=0 for s in n: print("%.8ff16, " % s,end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) def printQ31Array(f,mode,n): DSPE=False if mode == "DSP": DSPE=True nb=0 for s in n: print(to_q31(s,DSPE) + ", ",end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) def printQ15Array(f,mode,n): DSPE=False if mode == "DSP": DSPE=True nb=0 for s in n: print(to_q15(s,DSPE) + ", ",end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) def printQ7Array(f,mode,n): DSPE=False if mode == "DSP": DSPE=True nb=0 for s in n: print(to_q7(s,DSPE) + ", ",end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) # Print a C array # Using the type, dpse mode, name # (dpse mode is for knowing if 0x8000 must be generated as 8000 or 8001 # to avoid sign issues when multiplying with the twiddles) def printArray(f,ctype,mode,name,a): nbSamples = len(a) define = "NB_" + name.upper() n = a.reshape(len(a)) print("__ALIGNED(8) const %s %s[%s]={" % (ctype,name,define),file=f) if ctype == "float64_t": printFloat64Array(f,n) if ctype == "float32_t": printFloat32Array(f,n) if ctype == "float16_t": printFloat16Array(f,n) if ctype == "Q31": printQ31Array(f,mode,n) if ctype == "Q15": printQ15Array(f,mode,n) if ctype == "Q7": printQ7Array(f,mode,n) print("};",file=f) # Convert a float value to a given datatype. def convertToDatatype(r,ctype,mode): DSPE=False if mode == "DSP": DSPE=True if ctype == "float64_t": result = "%.20f" % r if ctype == "float32_t": result = "%.20ff" % r if ctype == "float16_t": result = "%.20ff16" % r if ctype == "Q31": result = "Q31(%s)" % to_q31(r,DSPE) if ctype == "Q15": result = "Q15(%s)" % to_q15(r,DSPE) if ctype == "Q7": result = "Q7(%s)" % to_q7(r,DSPE) return(result) def printArrayHeader(f,ctype,name,nbSamples): define = "NB_" + name.upper() print("#define %s %d" % (define, nbSamples),file=f) print("extern __ALIGNED(8) const %s %s[%s];\n" % (ctype,name,define),file=f) # Print UINT arrays for permutations. def printUInt32Array(f,name,a): nbSamples = len(a) define = "NB_" + name.upper() n = a.reshape(len(a)) print("__ALIGNED(8) const uint32_t %s[%s]={" % (name,define),file=f) nb=0 for s in n: print("%d, " % s,end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) print("};",file=f) def printUInt16Array(f,name,a): nbSamples = len(a) define = "NB_" + name.upper() n = a.reshape(len(a)) print("__ALIGNED(8) const uint16_t %s[%s]={" % (name,define),file=f) nb=0 for s in n: print("%d, " % s,end="",file=f) nb = nb + 1 if nb == NB_ELEMS_PER_LINE: nb=0 print("",file=f) print("};",file=f) def printUInt32ArrayHeader(f,name,a): nbSamples = len(a) define = "NB_" + name.upper() n = a.reshape(len(a)) print("#define %s %d" % (define, nbSamples),file=f) print("extern __ALIGNED(8) const uint32_t %s[%s];\n" % (name,define),file=f) def printUInt16ArrayHeader(f,name,a): nbSamples = len(a) define = "NB_" + name.upper() n = a.reshape(len(a)) print("#define %s %d" % (define, nbSamples),file=f) print("extern __ALIGNED(8) const uint16_t %s[%s];\n" % (name,define),file=f) def getCtype(t): if t == 'f64': return("float64_t") if t == 'f32': return("float32_t") if t == 'f16': return("float16_t") if t == 'q31': return("Q31") if t == 'q15': return("Q15") if t == 'q7': return("Q7") return("void") # Configuration structures for CFFT and RFFT cfftconfig = """cfftconfig<%s> config%d={ .normalization=%s, .nbPerms=%s, .perms=perm%d, .nbTwiddle=%s, .twiddle=twiddle%d, .nbGroupedFactors=%d, .nbFactors=%d, .factors=factors%d, .lengths=lengths%d, .format=%d, .reversalVectorizable=%d };""" rfftconfig = """rfftconfig<%s> config%d={ .nbTwiddle=%s, .twiddle=twiddle%d };""" fftconfigHeader = """extern %sconfig<%s> config%d;""" fftFactorArray = """const uint16_t factors%d[%d]=%s;\n""" fftLengthArray = """const uint16_t lengths%d[%d]=%s;\n""" # Descriptino of a permutation class Perm: PermID = 0 # Grouped factors and factors. def getFactors(core,nb,datatype): _groupedFactors,_factors,_lens=getFactors(core.radix(datatype,nb),nb) return(_factors) def __init__(self,core,nb,datatype): Perm.PermID = Perm.PermID + 1 self._nb=nb self._id = Perm.PermID self._radixUsed=set([]) self._groupedFactors,self._factors,self._lens=getFactors(core.radix(datatype,nb),nb) self._perms = None self._core=core self._isvectorizable=False def permutations(self): _permFactors=list(itertools.chain(*[self._core.getPermFactor(x) for x in self._factors])) #print(_permFactors) self._perms,self._isvectorizable = radixPermutation(_permFactors[::-1],self._nb) @property def isVectorizable(self): return(self._isvectorizable) @property def permID(self): return(self._id) @property def perms(self): if self._perms is not None: return(self._perms) else: self.permutations() return(self._perms) @property def factors(self): return(self._factors) @property def nbGroupedFactors(self): return(int(len(self._groupedFactors)/2)) @property def nbFactors(self): return(len(self._factors)) def writePermHeader(self,h): printUInt16ArrayHeader(h,"perm%d" % self.permID,self.perms) def writePermCode(self,c): printUInt16Array(c,"perm%d" % self.permID,self.perms) def writeFactorDesc(self,c): radixList="{%s}" % joinStr([str(x) for x in self._groupedFactors]) lengthList="{%s}" % joinStr([str(x) for x in self._lens]) print(fftFactorArray % (self.permID,2*self.nbGroupedFactors,radixList),file=c); print(fftLengthArray % (self.permID,len(self._lens),lengthList),file=c); class Twiddle: TwiddleId = 0 def __init__(self,transform,nb,datatype,mode): Twiddle.TwiddleId = Twiddle.TwiddleId + 1 self._id = Twiddle.TwiddleId self._datatype = datatype self._nb=nb self._twiddle = None self._transform=transform self._mode=mode @property def twiddleID(self): return(self._id) @property def datatype(self): return(self._datatype) @property def samples(self): if self._twiddle is None: self._twiddle=twiddle(self._transform,self._nb) return(self._twiddle) @property def nbSamples(self): return(self._nb) @property def nbTwiddles(self): if self._transform=="RFFT": return(self._nb // 2) else: return(self._nb) def writeTwidHeader(self,h): ctype=getCtype(self.datatype) # Twiddle is a complex array so 2*nbSamples must be used printArrayHeader(h,ctype,"twiddle%d" % self.twiddleID,2*self.nbTwiddles) def writeTwidCode(self,c): ctype=getCtype(self.datatype) printArray(c,ctype,self._mode,"twiddle%d" % self.twiddleID,self.samples) class Config: ConfigID = 0 def __init__(self,transform,twiddle,perms,coreMode): Config.ConfigID = Config.ConfigID + 1 self._id = Config.ConfigID self._twiddle=twiddle self._perms=perms self._transform=transform self._coreMode=coreMode @property def transform(self): return(self._transform) @property def configID(self): return(self._id) @property def perms(self): return(self._perms) @property def twiddle(self): return(self._twiddle) @property def nbSamples(self): return(self.twiddle.nbSamples) def writeConfigHeader(self,c): ctype=getCtype(self.twiddle.datatype) print(fftconfigHeader % (self.transform.lower(),ctype,self.configID),file=c) def writeConfigCode(self,c): ctype=getCtype(self.twiddle.datatype) twiddleLen = "NB_" + ("twiddle%d"% self.twiddle.twiddleID).upper() if self.transform == "RFFT": print(rfftconfig % (ctype,self.configID,twiddleLen,self.twiddle.twiddleID),file=c) else: normfactor = 1.0 / self.twiddle.nbSamples normFactorStr = convertToDatatype(normfactor,ctype,self._coreMode) permsLen = "NB_" + ("perm%d"% self.perms.permID).upper() outputFormat = 0 #print(self.twiddle.datatype) #print(self.twiddle.nbSamples) #print(self.perms.factors) # For fixed point, each stage will change the output format. # We need to cmpute the final format of the FFT # and record it in the initialization structure # so that the user can easily know how to recover the # input format (q31, q15). It is encoded as a shift value. # The shift to apply to recover the input format # But applying this shift will saturate the result in general. if self.twiddle.datatype == "q15" or self.twiddle.datatype == "q31": for f in self.perms.factors: #print(f,self.twiddle.datatype,self._coreMode) # The file "formats.py" is decribing the format of each radix # and is used to compute the format of the FFT based # on the decomposition of its length. # # Currently (since there is no vector version for fixed point) # this is not taking into account the format change that may # be implied by the vectorization in case it may be different # from the scalar version. formatForSize = config.formats.formats[f][self._coreMode] outputFormat += formatForSize[self.twiddle.datatype] vectorizable=0 if self.perms.isVectorizable: vectorizable = 1 print(cfftconfig % (ctype,self.configID,normFactorStr,permsLen,self.perms.permID, twiddleLen,self.twiddle.twiddleID,self.perms.nbGroupedFactors,self.perms.nbFactors, self.perms.permID,self.perms.permID,outputFormat,vectorizable ),file=c)
[ "struct.pack", "numpy.exp", "numpy.array", "numpy.linspace", "numpy.empty", "numpy.cos", "numpy.sin", "numpy.transpose", "sympy.combinatorics.Permutation.from_sequence" ]
[((4077, 4095), 'numpy.transpose', 'np.transpose', (['a', 'r'], {}), '(a, r)\n', (4089, 4095), True, 'import numpy as np\n'), ((4688, 4698), 'numpy.cos', 'np.cos', (['(-a)'], {}), '(-a)\n', (4694, 4698), True, 'import numpy as np\n'), ((4705, 4715), 'numpy.sin', 'np.sin', (['(-a)'], {}), '(-a)\n', (4711, 4715), True, 'import numpy as np\n'), ((4725, 4768), 'numpy.empty', 'np.empty', (['(c.size + s.size,)'], {'dtype': 'c.dtype'}), '((c.size + s.size,), dtype=c.dtype)\n', (4733, 4768), True, 'import numpy as np\n'), ((4234, 4262), 'sympy.combinatorics.Permutation.from_sequence', 'Permutation.from_sequence', (['a'], {}), '(a)\n', (4259, 4262), False, 'from sympy.combinatorics import Permutation\n'), ((4964, 4974), 'numpy.exp', 'np.exp', (['(-a)'], {}), '(-a)\n', (4970, 4974), True, 'import numpy as np\n'), ((4642, 4682), 'numpy.linspace', 'np.linspace', (['(0)', 'n'], {'num': 'n', 'endpoint': '(False)'}), '(0, n, num=n, endpoint=False)\n', (4653, 4682), True, 'import numpy as np\n'), ((4902, 4952), 'numpy.linspace', 'np.linspace', (['(0)', '(n // 2)'], {'num': '(n // 2)', 'endpoint': '(False)'}), '(0, n // 2, num=n // 2, endpoint=False)\n', (4913, 4952), True, 'import numpy as np\n'), ((4528, 4552), 'numpy.array', 'np.array', (['tps'], {'dtype': 'int'}), '(tps, dtype=int)\n', (4536, 4552), True, 'import numpy as np\n'), ((1534, 1554), 'struct.pack', 'struct.pack', (['"""<q"""', 'r'], {}), "('<q', r)\n", (1545, 1554), False, 'import struct\n'), ((1819, 1839), 'struct.pack', 'struct.pack', (['"""<i"""', 'r'], {}), "('<i', r)\n", (1830, 1839), False, 'import struct\n'), ((2085, 2105), 'struct.pack', 'struct.pack', (['"""<h"""', 'r'], {}), "('<h', r)\n", (2096, 2105), False, 'import struct\n'), ((2340, 2360), 'struct.pack', 'struct.pack', (['"""<b"""', 'r'], {}), "('<b', r)\n", (2351, 2360), False, 'import struct\n')]
''' This inference script takes in images of dynamic size Runs inference in batch ** In this images have been resized but not need for this script ''' import onnx import onnxruntime as ort import numpy as np import cv2 from imagenet_classlist import get_class import os model_path = 'resnet18.onnx' model = onnx.load(model_path) image_path = "../sample_images" try: print("Checking model...") onnx.checker.check_model(model) onnx.helper.printable_graph(model.graph) print("Model checked...") print("Running inference...") ort_session = ort.InferenceSession(model_path) img_list = [] for image in os.listdir(image_path): img = cv2.imread(os.path.join(image_path, image), cv2.IMREAD_COLOR) img = cv2.resize(img, ((224, 224))) img = np.moveaxis(img, -1, 0) # (Batch_size, channels, width, heigth) img_list.append(img/255.0) # Normalize the image outputs = ort_session.run(None, {"input":img_list}) out = np.array(outputs) for image_num, image_name in zip(range(out.shape[1]), os.listdir(image_path)): index = out[0][image_num] print("Image : {0}, Class : {1}".format(image_name, get_class(np.argmax(index)))) except Exception as e: print("Exception occured : ", e)
[ "os.listdir", "onnx.helper.printable_graph", "onnxruntime.InferenceSession", "os.path.join", "numpy.argmax", "numpy.array", "onnx.load", "numpy.moveaxis", "cv2.resize", "onnx.checker.check_model" ]
[((310, 331), 'onnx.load', 'onnx.load', (['model_path'], {}), '(model_path)\n', (319, 331), False, 'import onnx\n'), ((405, 436), 'onnx.checker.check_model', 'onnx.checker.check_model', (['model'], {}), '(model)\n', (429, 436), False, 'import onnx\n'), ((441, 481), 'onnx.helper.printable_graph', 'onnx.helper.printable_graph', (['model.graph'], {}), '(model.graph)\n', (468, 481), False, 'import onnx\n'), ((574, 606), 'onnxruntime.InferenceSession', 'ort.InferenceSession', (['model_path'], {}), '(model_path)\n', (594, 606), True, 'import onnxruntime as ort\n'), ((643, 665), 'os.listdir', 'os.listdir', (['image_path'], {}), '(image_path)\n', (653, 665), False, 'import os\n'), ((989, 1006), 'numpy.array', 'np.array', (['outputs'], {}), '(outputs)\n', (997, 1006), True, 'import numpy as np\n'), ((757, 784), 'cv2.resize', 'cv2.resize', (['img', '(224, 224)'], {}), '(img, (224, 224))\n', (767, 784), False, 'import cv2\n'), ((801, 824), 'numpy.moveaxis', 'np.moveaxis', (['img', '(-1)', '(0)'], {}), '(img, -1, 0)\n', (812, 824), True, 'import numpy as np\n'), ((1066, 1088), 'os.listdir', 'os.listdir', (['image_path'], {}), '(image_path)\n', (1076, 1088), False, 'import os\n'), ((692, 723), 'os.path.join', 'os.path.join', (['image_path', 'image'], {}), '(image_path, image)\n', (704, 723), False, 'import os\n'), ((1195, 1211), 'numpy.argmax', 'np.argmax', (['index'], {}), '(index)\n', (1204, 1211), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf from tqdm import trange from fedsimul.utils.model_utils import batch_data from fedsimul.utils.tf_utils import graph_size from fedsimul.utils.tf_utils import process_grad class Model(object): ''' This is the tf model for the MNIST dataset with multiple class learner regression. Images are 28px by 28px. ''' def __init__(self, num_classes, optimizer, gpu_id=0, seed=1): """ Initialize the learner. Args: num_classes: int optimizer: tf.train.Optimizer gpu_id: int, default 0 seed: int, default 1 """ # params self.num_classes = num_classes # create computation graph self.graph = tf.Graph() with self.graph.as_default(): tf.set_random_seed(123 + seed) _created = self.create_model(optimizer) self.features = _created[0] self.labels = _created[1] self.train_op = _created[2] self.grads = _created[3] self.eval_metric_ops = _created[4] self.loss = _created[5] self.saver = tf.train.Saver() # set the gpu resources gpu_options = tf.compat.v1.GPUOptions(visible_device_list="{}".format(gpu_id), allow_growth=True) config = tf.compat.v1.ConfigProto(gpu_options=gpu_options) self.sess = tf.Session(graph=self.graph, config=config) # self.sess = tf.Session(graph=self.graph) # REVIEW: find memory footprint and compute cost of the model self.size = graph_size(self.graph) with self.graph.as_default(): self.sess.run(tf.global_variables_initializer()) metadata = tf.RunMetadata() opts = tf.profiler.ProfileOptionBuilder.float_operation() self.flops = tf.profiler.profile(self.graph, run_meta=metadata, cmd='scope', options=opts).total_float_ops def create_model(self, optimizer): """ Model function for Logistic Regression. Args: optimizer: tf.train.Optimizer Returns: tuple: (features, labels, train_op, grads, eval_metric_ops, loss) """ features = tf.placeholder(tf.float32, shape=[None, 784], name='features') labels = tf.placeholder(tf.int64, shape=[None, ], name='labels') logits = tf.layers.dense(inputs=features, units=self.num_classes, kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001)) predictions = { "classes": tf.argmax(input=logits, axis=1), "probabilities": tf.nn.softmax(logits, name="softmax_tensor") } loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) grads_and_vars = optimizer.compute_gradients(loss) grads, _ = zip(*grads_and_vars) train_op = optimizer.apply_gradients(grads_and_vars, global_step=tf.train.get_global_step()) eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions["classes"])) return features, labels, train_op, grads, eval_metric_ops, loss def set_params(self, latest_params=None, momentum=False, gamma=0.9): """ Set parameters from server Args: latest_params: list list of tf.Variables momentum: boolean gamma: float TODO: update variable with its local variable and the value from latest_params TODO: DO NOT set_params from the global, instead, use the global gradient to update """ if latest_params is not None: with self.graph.as_default(): # previous gradient all_vars = tf.trainable_variables() for variable, value in zip(all_vars, latest_params): if momentum: curr_val = self.sess.run(variable) new_val = gamma * curr_val + (1 - gamma) * value # TODO: use `assign` function instead of `load` variable.load(new_val, self.sess) else: variable.load(value, self.sess) def get_params(self): """ Get model parameters. Returns: model_params: list list of tf.Variables """ with self.graph.as_default(): model_params = self.sess.run(tf.trainable_variables()) return model_params def get_gradients(self, data, model_len): """ Access gradients of a given dataset. Args: data: dict model_len: int Returns: num_samples: int grads: tuple """ grads = np.zeros(model_len) num_samples = len(data['y']) with self.graph.as_default(): model_grads = self.sess.run(self.grads, feed_dict={self.features: data['x'], self.labels: data['y']}) grads = process_grad(model_grads) return num_samples, grads def solve_inner(self, data, num_epochs=1, batch_size=32): '''Solves local optimization problem. Args: data: dict with format {'x':[], 'y':[]} num_epochs: int batch_size: int Returns: soln: list comp: float ''' for _ in trange(num_epochs, desc='Epoch: ', leave=False, ncols=120): for X, y in batch_data(data, batch_size): with self.graph.as_default(): self.sess.run(self.train_op, feed_dict={self.features: X, self.labels: y}) soln = self.get_params() comp = num_epochs * (len(data['y']) // batch_size) * batch_size * self.flops return soln, comp def test(self, data): ''' Args: data: dict of the form {'x': [], 'y': []} Returns: tot_correct: int loss: float ''' with self.graph.as_default(): tot_correct, loss = self.sess.run([self.eval_metric_ops, self.loss], feed_dict={self.features: data['x'], self.labels: data['y']}) return tot_correct, loss def close(self): self.sess.close()
[ "tensorflow.equal", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.nn.softmax", "tensorflow.set_random_seed", "tensorflow.RunMetadata", "tensorflow.Graph", "tensorflow.Session", "tensorflow.placeholder", "fedsimul.utils.model_utils.batch_data", "tensorflow.train.get_global_step", "tensorflow.trainable_variables", "fedsimul.utils.tf_utils.process_grad", "tqdm.trange", "tensorflow.compat.v1.ConfigProto", "tensorflow.profiler.profile", "tensorflow.profiler.ProfileOptionBuilder.float_operation", "fedsimul.utils.tf_utils.graph_size", "tensorflow.train.Saver", "tensorflow.global_variables_initializer", "numpy.zeros", "tensorflow.argmax", "tensorflow.losses.sparse_softmax_cross_entropy" ]
[((751, 761), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (759, 761), True, 'import tensorflow as tf\n'), ((1331, 1380), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {'gpu_options': 'gpu_options'}), '(gpu_options=gpu_options)\n', (1355, 1380), True, 'import tensorflow as tf\n'), ((1401, 1444), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph', 'config': 'config'}), '(graph=self.graph, config=config)\n', (1411, 1444), True, 'import tensorflow as tf\n'), ((1587, 1609), 'fedsimul.utils.tf_utils.graph_size', 'graph_size', (['self.graph'], {}), '(self.graph)\n', (1597, 1609), False, 'from fedsimul.utils.tf_utils import graph_size\n'), ((2214, 2276), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 784]', 'name': '"""features"""'}), "(tf.float32, shape=[None, 784], name='features')\n", (2228, 2276), True, 'import tensorflow as tf\n'), ((2294, 2347), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int64'], {'shape': '[None]', 'name': '"""labels"""'}), "(tf.int64, shape=[None], name='labels')\n", (2308, 2347), True, 'import tensorflow as tf\n'), ((2729, 2797), 'tensorflow.losses.sparse_softmax_cross_entropy', 'tf.losses.sparse_softmax_cross_entropy', ([], {'labels': 'labels', 'logits': 'logits'}), '(labels=labels, logits=logits)\n', (2767, 2797), True, 'import tensorflow as tf\n'), ((4781, 4800), 'numpy.zeros', 'np.zeros', (['model_len'], {}), '(model_len)\n', (4789, 4800), True, 'import numpy as np\n'), ((5461, 5519), 'tqdm.trange', 'trange', (['num_epochs'], {'desc': '"""Epoch: """', 'leave': '(False)', 'ncols': '(120)'}), "(num_epochs, desc='Epoch: ', leave=False, ncols=120)\n", (5467, 5519), False, 'from tqdm import trange\n'), ((812, 842), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(123 + seed)'], {}), '(123 + seed)\n', (830, 842), True, 'import tensorflow as tf\n'), ((1158, 1174), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1172, 1174), True, 'import tensorflow as tf\n'), ((1732, 1748), 'tensorflow.RunMetadata', 'tf.RunMetadata', ([], {}), '()\n', (1746, 1748), True, 'import tensorflow as tf\n'), ((1768, 1818), 'tensorflow.profiler.ProfileOptionBuilder.float_operation', 'tf.profiler.ProfileOptionBuilder.float_operation', ([], {}), '()\n', (1816, 1818), True, 'import tensorflow as tf\n'), ((2597, 2628), 'tensorflow.argmax', 'tf.argmax', ([], {'input': 'logits', 'axis': '(1)'}), '(input=logits, axis=1)\n', (2606, 2628), True, 'import tensorflow as tf\n'), ((2659, 2703), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {'name': '"""softmax_tensor"""'}), "(logits, name='softmax_tensor')\n", (2672, 2703), True, 'import tensorflow as tf\n'), ((3042, 3082), 'tensorflow.equal', 'tf.equal', (['labels', "predictions['classes']"], {}), "(labels, predictions['classes'])\n", (3050, 3082), True, 'import tensorflow as tf\n'), ((5074, 5099), 'fedsimul.utils.tf_utils.process_grad', 'process_grad', (['model_grads'], {}), '(model_grads)\n', (5086, 5099), False, 'from fedsimul.utils.tf_utils import process_grad\n'), ((5545, 5573), 'fedsimul.utils.model_utils.batch_data', 'batch_data', (['data', 'batch_size'], {}), '(data, batch_size)\n', (5555, 5573), False, 'from fedsimul.utils.model_utils import batch_data\n'), ((1674, 1707), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1705, 1707), True, 'import tensorflow as tf\n'), ((1844, 1921), 'tensorflow.profiler.profile', 'tf.profiler.profile', (['self.graph'], {'run_meta': 'metadata', 'cmd': '"""scope"""', 'options': 'opts'}), "(self.graph, run_meta=metadata, cmd='scope', options=opts)\n", (1863, 1921), True, 'import tensorflow as tf\n'), ((2509, 2548), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['(0.001)'], {}), '(0.001)\n', (2541, 2548), True, 'import tensorflow as tf\n'), ((2971, 2997), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (2995, 2997), True, 'import tensorflow as tf\n'), ((3757, 3781), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (3779, 3781), True, 'import tensorflow as tf\n'), ((4466, 4490), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (4488, 4490), True, 'import tensorflow as tf\n')]
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import math import networkx as nx import functools import scipy.stats import random import sys import copy import numpy as np import torch import utils try: sys.path.append('/opt/MatterSim/build/') # local docker or Philly import MatterSim except: # local conda env only sys.path.append('/home/hoyeung/Documents/vnla/code/build') import MatterSim class ShortestPathOracle(object): ''' Shortest navigation teacher ''' def __init__(self, agent_nav_actions, env_nav_actions=None): self.scans = set() self.graph = {} self.paths = {} self.distances = {} self.agent_nav_actions = agent_nav_actions if env_nav_actions is not None: self.env_nav_actions = env_nav_actions def add_scans(self, scans, path=None): new_scans = set.difference(scans, self.scans) if new_scans: print('Loading navigation graphs for %d scans' % len(new_scans)) for scan in new_scans: graph, paths, distances = self._compute_shortest_paths(scan, path=path) self.graph[scan] = graph self.paths[scan] = paths self.distances[scan] = distances self.scans.update(new_scans) def _compute_shortest_paths(self, scan, path=None): ''' Load connectivity graph for each scan, useful for reasoning about shortest paths ''' graph = utils.load_nav_graphs(scan, path=path) paths = dict(nx.all_pairs_dijkstra_path(graph)) distances = dict(nx.all_pairs_dijkstra_path_length(graph)) return graph, paths, distances def _find_nearest_point(self, scan, start_point, end_points): best_d = 1e9 best_point = None for end_point in end_points: d = self.distances[scan][start_point][end_point] if d < best_d: best_d = d best_point = end_point return best_d, best_point def _find_nearest_point_on_a_path(self, scan, current_point, start_point, goal_point): path = self.paths[scan][start_point][goal_point] return self._find_nearest_point(scan, current_point, path) def _shortest_path_action(self, ob): ''' Determine next action on the shortest path to goals. ''' scan = ob['scan'] start_point = ob['viewpoint'] # Find nearest goal _, goal_point = self._find_nearest_point(scan, start_point, ob['goal_viewpoints']) # Stop if a goal is reached if start_point == goal_point: return (0, 0, 0) path = self.paths[scan][start_point][goal_point] next_point = path[1] # Can we see the next viewpoint? for i, loc in enumerate(ob['navigableLocations']): if loc.viewpointId == next_point: # Look directly at the viewpoint before moving if loc.rel_heading > math.pi/6.0: return (0, 1, 0) # Turn right elif loc.rel_heading < -math.pi/6.0: return (0,-1, 0) # Turn left elif loc.rel_elevation > math.pi/6.0 and ob['viewIndex'] // 12 < 2: return (0, 0, 1) # Look up elif loc.rel_elevation < -math.pi/6.0 and ob['viewIndex'] // 12 > 0: return (0, 0,-1) # Look down else: return (i, 0, 0) # Move # Can't see it - first neutralize camera elevation if ob['viewIndex'] // 12 == 0: return (0, 0, 1) # Look up elif ob['viewIndex'] // 12 == 2: return (0, 0,-1) # Look down # If camera is already neutralized, decide which way to turn target_rel = self.graph[ob['scan']].node[next_point]['position'] - ob['point'] # state.location.point # 180deg - target_heading = math.pi / 2.0 - math.atan2(target_rel[1], target_rel[0]) if target_heading < 0: target_heading += 2.0 * math.pi if ob['heading'] > target_heading and ob['heading'] - target_heading < math.pi: return (0, -1, 0) # Turn left if target_heading > ob['heading'] and target_heading - ob['heading'] > math.pi: return (0, -1, 0) # Turn left return (0, 1, 0) # Turn right def _map_env_action_to_agent_action(self, action, ob): ix, heading_chg, elevation_chg = action if heading_chg > 0: return self.agent_nav_actions.index('right') if heading_chg < 0: return self.agent_nav_actions.index('left') if elevation_chg > 0: return self.agent_nav_actions.index('up') if elevation_chg < 0: return self.agent_nav_actions.index('down') if ix > 0: return self.agent_nav_actions.index('forward') if ob['ended']: return self.agent_nav_actions.index('<ignore>') return self.agent_nav_actions.index('<end>') def interpret_agent_action(self, action_idx, ob): '''Translate action index back to env action for simulator to take''' # If the action is not `forward`, simply map it to the simulator's # action space if action_idx != self.agent_nav_actions.index('forward'): return self.env_nav_actions[action_idx] # If the action is forward, more complicated scan = ob['scan'] start_point = ob['viewpoint'] # Find nearest goal view point _, goal_point = self._find_nearest_point(scan, start_point, ob['goal_viewpoints']) optimal_path = self.paths[scan][start_point][goal_point] # If the goal is right in front of us, go to it. # The dataset guarantees that the goal is always reachable. if len(optimal_path) < 2: return (1, 0, 0) next_optimal_point = optimal_path[1] # If the next optimal viewpoint is within 30 degrees of # the center of the view, go to it. for i, loc in enumerate(ob['navigableLocations']): if loc.viewpointId == next_optimal_point: if loc.rel_heading > math.pi/6.0 or loc.rel_heading < -math.pi/6.0 or \ (loc.rel_elevation > math.pi/6.0 and ob['viewIndex'] // 12 < 2) or \ (loc.rel_elevation < -math.pi/6.0 and ob['viewIndex'] // 12 > 0): continue else: return (i, 0, 0) # Otherwise, go the navigable (seeable) viewpt that has the least angular distance from the center of the current image (viewpt). return (1, 0, 0) def __call__(self, obs): self.actions = list(map(self._shortest_path_action, obs)) return list(map(self._map_env_action_to_agent_action, self.actions, obs)) class FrontierShortestPathsOracle(ShortestPathOracle): def __init__(self, agent_nav_actions, env_nav_actions=None): super(FrontierShortestPathsOracle, self).__init__(agent_nav_actions, env_nav_actions) # self.env_nav_actions = env_nav_actions self.valid_rotation_action_indices = [self.agent_nav_actions.index(r) for r in ('left', 'right', 'up', 'down', '<ignore>')] # inherit parent add_scans() function def interpret_agent_rotations(self, rotation_action_indices, ob): ''' rotation_action_indices : a list of int action indices Returns: list of fixed length agent.max_macro_action_seq_len (e.g. 8) e.g. [(0, 1, 0), (0, 1, -1), ..... (0,0,0)] e.g. [(0,0,0), ... (0,0,0)] if ob has ended. ''' max_macro_action_seq_len = len(rotation_action_indices) # [(0,0,0)] * 8 macro_rotations = [self.env_nav_actions[self.agent_nav_actions.index('<ignore>')]] * max_macro_action_seq_len if not ob['ended']: for i, action_idx in enumerate(rotation_action_indices): assert action_idx in self.valid_rotation_action_indices macro_rotations[i] = self.env_nav_actions[action_idx] return macro_rotations def interpret_agent_forward(self, ob): ''' Returns: (0, 0, 0) to ignore if trajectory has already ended or (1, 0, 0) to step forward to the direct facing vertex ''' if ob['ended']: return self.env_nav_actions[self.agent_nav_actions.index('<ignore>')] else: return self.env_nav_actions[self.agent_nav_actions.index('forward')] def make_explore_instructions(self, obs): ''' Make env level rotation instructions of each ob to explore its own panoramic sphere. The output should be informative enough for agent to collect information from all 36 facets of its panoramic sphere. Returns: heading_adjusts: list len=batch_size, each an env action tuple. elevation_adjusts_1: same. elevation_adjusts_2: list len=batch_size, each either a single action tuple e.g.(0,1,0), or double action tuple e.g.((0,0,-1), (0,0,-1)). ''' batch_size = len(obs) # How agent explore the entire pano sphere # Right*11, Up/Down, Right*11, Up/Down (*2), Right*11 heading_adjusts = [()] * batch_size elevation_adjusts_1 = [()] * batch_size elevation_adjusts_2 = [()] * batch_size # (0,0,1) up_tup = self.env_nav_actions[self.agent_nav_actions.index('up')] # (0,0,-1) down_tup = self.env_nav_actions[self.agent_nav_actions.index('down')] # (0,1,0) right_tup = self.env_nav_actions[self.agent_nav_actions.index('right')] # (0,0,0) ignore_tup = self.env_nav_actions[self.agent_nav_actions.index('<ignore>')] # Loop through each ob in the batch for i, ob in enumerate(obs): if ob['ended']: # don't move at all. heading_adjusts[i] = ignore_tup elevation_adjusts_1[i] = ignore_tup elevation_adjusts_2[i] = ignore_tup else: # turn right for 11 times at every elevation level. heading_adjusts[i] = right_tup # check agent elevation if ob['viewIndex'] // 12 == 0: # facing down, so need to look up twice. elevation_adjusts_1[i] = up_tup elevation_adjusts_2[i] = up_tup elif ob['viewIndex'] // 12 == 2: # facing up, so need to look down twice. elevation_adjusts_1[i] = down_tup elevation_adjusts_2[i] = down_tup else: # neutral, so need to look up once, and then look down twice elevation_adjusts_1[i] = up_tup elevation_adjusts_2[i] = (down_tup, down_tup) return heading_adjusts, elevation_adjusts_1, elevation_adjusts_2 def compute_frontier_cost_single(self, ob, next_viewpoint_index_str): ''' next_viewpoint_index_str: single str indicating viewpoint index. e.g. '1e6b606b44df4a6086c0f97e826d4d15' ''' # current point to next point cost_stepping = self.distances[ob['scan']][ob['viewpoint']][next_viewpoint_index_str] # next point to the closest goal cost_togo, _ = self._find_nearest_point(ob['scan'], next_viewpoint_index_str, ob['goal_viewpoints']) assert cost_stepping > 0 and cost_togo >= 0 return cost_togo , cost_stepping def compute_frontier_costs(self, obs, viewix_next_vertex_map, timestep=None): ''' For each ob, compute: cost = cost-to-go + cost-stepping for all reachable vertices ''' assert len(obs) == len(viewix_next_vertex_map) # arr shape (batch_size, 36) q_values_target_batch = np.ones((len(obs), len(viewix_next_vertex_map[0]))) * 1e9 # arr shape (batch_size, 36) cost_togos_batch = np.ones((len(obs), len(viewix_next_vertex_map[0]))) * 1e9 # arr shape (batch_size, 36) cost_stepping_batch = np.ones((len(obs), len(viewix_next_vertex_map[0]))) * 1e9 # arr shape (batch_size, ) end_target_batch = np.array([False for _ in range(len(obs))]) # Loop through batch for i, ob in enumerate(obs): # NOTE ended ob won't be added to hist buffer for training if not ob['ended']: costs = [] cost_togos = [] cost_steppings = [] for proposed_vertex in viewix_next_vertex_map[i]: if proposed_vertex == '': costs.append(1e9) cost_togos.append(1e9) cost_steppings.append(1e9) else: # add up cost-togo + cost-stepping cost_togo , cost_stepping = self.compute_frontier_cost_single(ob, proposed_vertex) costs.append(cost_togo + cost_stepping) # keep tab cost-togo to determine ending later cost_togos.append(cost_togo) cost_steppings.append(cost_stepping) assert len(cost_togos) == len(viewix_next_vertex_map[0]) # 36 assert len(cost_steppings) == len(viewix_next_vertex_map[0]) # 36 assert len(costs) == len(viewix_next_vertex_map[0]) # 36 q_values_target_batch[i, :] = costs # get min costs for each row # if the min index of costs also has a cost-togo = 0, then mark end for this row in end_target end_target_batch[i] = cost_togos[costs.index(min(costs))] == 0 # for results logging cost_togos_batch[i] = cost_togos cost_stepping_batch[i] = cost_steppings return q_values_target_batch, end_target_batch, cost_togos_batch, cost_stepping_batch def _map_env_action_to_agent_action(self, action): ''' Translate rotation env action seq into agent action index seq. ''' ix, heading_chg, elevation_chg = action assert ix == 0, 'Accept only rotation or ignore actions' assert heading_chg == 0 or elevation_chg == 0, 'Accept only one rotation action at a time' if heading_chg > 0: return self.agent_nav_actions.index('right') if heading_chg < 0: return self.agent_nav_actions.index('left') if elevation_chg > 0: return self.agent_nav_actions.index('up') if elevation_chg < 0: return self.agent_nav_actions.index('down') else: return self.agent_nav_actions.index('<ignore>') def translate_env_actions(self, obs, viewix_env_actions_map, max_macro_action_seq_len, sphere_size): ''' viewix_env_actions_map : list (batch_size, 36, varies). Each [(0,1,0), (0,0,-1), ...] Returns: viewix_actions_map : array shape(36, batch_size, self.max_macro_action_seq_len) ''' # tensor shape(36, batch_size, self.max_macro_action_seq_len) viewix_actions_map = np.ones((sphere_size, len(obs), max_macro_action_seq_len), dtype='int') * \ self.agent_nav_actions.index('<ignore>') for i, ob in enumerate(obs): # 1-100 if not ob['ended']: for j, env_action_tup_seq in enumerate(viewix_env_actions_map[i]): # 1-36 assert len(env_action_tup_seq) <= 8 # map seq, length varies agent_action_seq = list(map(self._map_env_action_to_agent_action, env_action_tup_seq)) assert len(agent_action_seq) <= 8 # assign action index, seq is already padded to 8 during initialization viewix_actions_map[j, i, :len(agent_action_seq)] = agent_action_seq return viewix_actions_map class AskOracle(object): DONT_ASK = 0 ASK = 1 def __init__(self, hparams, agent_ask_actions): self.deviate_threshold = hparams.deviate_threshold self.uncertain_threshold = hparams.uncertain_threshold self.unmoved_threshold = hparams.unmoved_threshold self.agent_ask_actions = agent_ask_actions self.rule_a_e = hasattr(hparams, 'rule_a_e') and hparams.rule_a_e self.rule_b_d = hasattr(hparams, 'rule_b_d') and hparams.rule_b_d def _should_ask_rule_a_e(self, ob, nav_oracle=None): if ob['queries_unused'] <= 0: return self.DONT_ASK, 'exceed' scan = ob['scan'] current_point = ob['viewpoint'] _, goal_point = nav_oracle._find_nearest_point(scan, current_point, ob['goal_viewpoints']) agent_decision = int(np.argmax(ob['nav_dist'])) if current_point == goal_point and \ agent_decision == nav_oracle.agent_nav_actions.index('forward'): return self.ASK, 'arrive' start_point = ob['init_viewpoint'] d, _ = nav_oracle._find_nearest_point_on_a_path(scan, current_point, start_point, goal_point) if d > self.deviate_threshold: return self.ASK, 'deviate' return self.DONT_ASK, 'pass' def _should_ask_rule_b_d(self, ob, nav_oracle=None): if ob['queries_unused'] <= 0: return self.DONT_ASK, 'exceed' agent_dist = ob['nav_dist'] uniform = [1. / len(agent_dist)] * len(agent_dist) entropy_gap = scipy.stats.entropy(uniform) - scipy.stats.entropy(agent_dist) if entropy_gap < self.uncertain_threshold - 1e-9: return self.ASK, 'uncertain' if len(ob['agent_path']) >= self.unmoved_threshold: last_nodes = [t[0] for t in ob['agent_path']][-self.unmoved_threshold:] if all(node == last_nodes[0] for node in last_nodes): return self.ASK, 'unmoved' if ob['queries_unused'] >= ob['traj_len'] - ob['time_step']: return self.ASK, 'why_not' return self.DONT_ASK, 'pass' def _should_ask(self, ob, nav_oracle=None): if self.rule_a_e: return self._should_ask_rule_a_e(ob, nav_oracle=nav_oracle) if self.rule_b_d: return self._should_ask_rule_b_d(ob, nav_oracle=nav_oracle) if ob['queries_unused'] <= 0: return self.DONT_ASK, 'exceed' # Find nearest point on the current shortest path scan = ob['scan'] current_point = ob['viewpoint'] # Find nearest goal to current point _, goal_point = nav_oracle._find_nearest_point(scan, current_point, ob['goal_viewpoints']) # Rule (e): ask if the goal has been reached but the agent decides to # go forward agent_decision = int(np.argmax(ob['nav_dist'])) if current_point == goal_point and \ agent_decision == nav_oracle.agent_nav_actions.index('forward'): return self.ASK, 'arrive' start_point = ob['init_viewpoint'] # Find closest point to the current point on the path from start point # to goal point d, _ = nav_oracle._find_nearest_point_on_a_path(scan, current_point, start_point, goal_point) # Rule (a): ask if the agent deviates too far from the optimal path if d > self.deviate_threshold: return self.ASK, 'deviate' # Rule (b): ask if uncertain agent_dist = ob['nav_dist'] uniform = [1. / len(agent_dist)] * len(agent_dist) entropy_gap = scipy.stats.entropy(uniform) - scipy.stats.entropy(agent_dist) if entropy_gap < self.uncertain_threshold - 1e-9: return self.ASK, 'uncertain' # Rule (c): ask if not moving for too long if len(ob['agent_path']) >= self.unmoved_threshold: last_nodes = [t[0] for t in ob['agent_path']][-self.unmoved_threshold:] if all(node == last_nodes[0] for node in last_nodes): return self.ASK, 'unmoved' # Rule (d): ask to spend all budget at the end if ob['queries_unused'] >= ob['traj_len'] - ob['time_step']: return self.ASK, 'why_not' return self.DONT_ASK, 'pass' def _map_env_action_to_agent_action(self, action, ob): if ob['ended']: return self.agent_ask_actions.index('<ignore>') if action == self.DONT_ASK: return self.agent_ask_actions.index('dont_ask') return self.agent_ask_actions.index('ask') def __call__(self, obs, nav_oracle): should_ask_fn = functools.partial(self._should_ask, nav_oracle=nav_oracle) actions, reasons = zip(*list(map(should_ask_fn, obs))) actions = list(map(self._map_env_action_to_agent_action, actions, obs)) return actions, reasons class MultistepShortestPathOracle(ShortestPathOracle): '''For Ask Agents with direct advisors''' def __init__(self, n_steps, agent_nav_actions, env_nav_actions): super(MultistepShortestPathOracle, self).__init__(agent_nav_actions) self.sim = MatterSim.Simulator() self.sim.setRenderingEnabled(False) self.sim.setDiscretizedViewingAngles(True) self.sim.setCameraResolution(640, 480) self.sim.setCameraVFOV(math.radians(60)) self.sim.setNavGraphPath( os.path.join(os.getenv('PT_DATA_DIR'), 'connectivity')) self.sim.init() self.n_steps = n_steps self.env_nav_actions = env_nav_actions def _shortest_path_actions(self, ob): actions = [] self.sim.newEpisode(ob['scan'], ob['viewpoint'], ob['heading'], ob['elevation']) assert not ob['ended'] for _ in range(self.n_steps): # Query oracle for next action action = self._shortest_path_action(ob) # Convert to agent action agent_action = self._map_env_action_to_agent_action(action, ob) actions.append(agent_action) # Take action self.sim.makeAction(*action) if action == (0, 0, 0): break state = self.sim.getState() ob = { 'viewpoint': state.location.viewpointId, 'viewIndex': state.viewIndex, 'heading' : state.heading, 'elevation': state.elevation, 'navigableLocations': state.navigableLocations, 'point' : state.location.point, 'ended' : ob['ended'] or action == (0, 0, 0), 'goal_viewpoints': ob['goal_viewpoints'], 'scan' : ob['scan'] } return actions def __call__(self, ob): return self._shortest_path_actions(ob) class NextOptimalOracle(object): def __init__(self, hparams, agent_nav_actions, env_nav_actions, agent_ask_actions): self.type = 'next_optimal' self.ask_oracle = make_oracle('ask', hparams, agent_ask_actions) self.nav_oracle = make_oracle('shortest', agent_nav_actions, env_nav_actions) def __call__(self, obs): ask_actions, ask_reasons = self.ask_oracle(obs, self.nav_oracle) self.nav_oracle.add_scans(set(ob['scan'] for ob in obs)) nav_actions = self.nav_oracle(obs) return nav_actions, ask_actions, ask_reasons def add_scans(self, scans): self.nav_oracle.add_scans(scans) def next_ask(self, obs): return self.ask_oracle(obs, self.nav_oracle) def next_nav(self, obs): return self.nav_oracle(obs) def interpret_agent_action(self, *args, **kwargs): return self.nav_oracle.interpret_agent_action(*args, **kwargs) class StepByStepSubgoalOracle(object): def __init__(self, n_steps, agent_nav_actions, env_nav_actions, mode=None): self.type = 'step_by_step' self.nav_oracle = make_oracle('direct', n_steps, agent_nav_actions, env_nav_actions) self.agent_nav_actions = agent_nav_actions if mode == 'easy': self._map_actions_to_instruction = self._map_actions_to_instruction_easy elif mode == 'hard': self._map_actions_to_instruction = self._map_actions_to_instruction_hard else: sys.exit('unknown step by step mode!') def add_scans(self, scans): self.nav_oracle.add_scans(scans) def _make_action_name(self, a): action_name = self.agent_nav_actions[a] if action_name in ['up', 'down']: return 'look ' + action_name elif action_name in ['left', 'right']: return 'turn ' + action_name elif action_name == 'forward': return 'go ' + action_name elif action_name == '<end>': return 'stop' elif action_name == '<ignore>': return '' return None def _map_actions_to_instruction_hard(self, actions): agg_actions = [] cnt = 1 for i in range(1, len(actions)): if actions[i] != actions[i - 1]: agg_actions.append((actions[i - 1], cnt)) cnt = 1 else: cnt += 1 agg_actions.append((actions[-1], cnt)) instruction = [] for a, c in agg_actions: action_name = self._make_action_name(a) if c > 1: if 'turn' in action_name: degree = 30 * c if 'left' in action_name: instruction.append('turn %d degrees left' % degree) elif 'right' in action_name: instruction.append('turn %d degrees right' % degree) else: raise ValueError('action name {} error'.format(action_name)) elif 'go' in action_name: instruction.append('%s %d steps' % (action_name, c)) elif action_name != '': instruction.append(action_name) return ' , '.join(instruction) def _map_actions_to_instruction_easy(self, actions): instruction = [] for a in actions: instruction.append(self._make_action_name(a)) return ' , '.join(instruction) def __call__(self, ob): action_seq = self.nav_oracle(ob) verbal_instruction = self._map_actions_to_instruction(action_seq) return action_seq, verbal_instruction def make_oracle(oracle_type, *args, **kwargs): if oracle_type == 'shortest': return ShortestPathOracle(*args, **kwargs) if oracle_type == 'next_optimal': return NextOptimalOracle(*args, **kwargs) if oracle_type == 'ask': return AskOracle(*args, **kwargs) if oracle_type == 'direct': return MultistepShortestPathOracle(*args, **kwargs) if oracle_type == 'verbal': return StepByStepSubgoalOracle(*args, **kwargs) if oracle_type == 'frontier_shortest': return FrontierShortestPathsOracle(*args, **kwargs) # TODO implement next # if oracle_type == 'diverse_shortest': # return DiverseShortestPathsOracle(*args, **kwargs) return None
[ "networkx.all_pairs_dijkstra_path", "os.getenv", "MatterSim.Simulator", "utils.load_nav_graphs", "numpy.argmax", "math.radians", "functools.partial", "math.atan2", "sys.exit", "networkx.all_pairs_dijkstra_path_length", "sys.path.append" ]
[((247, 287), 'sys.path.append', 'sys.path.append', (['"""/opt/MatterSim/build/"""'], {}), "('/opt/MatterSim/build/')\n", (262, 287), False, 'import sys\n'), ((375, 433), 'sys.path.append', 'sys.path.append', (['"""/home/hoyeung/Documents/vnla/code/build"""'], {}), "('/home/hoyeung/Documents/vnla/code/build')\n", (390, 433), False, 'import sys\n'), ((1506, 1544), 'utils.load_nav_graphs', 'utils.load_nav_graphs', (['scan'], {'path': 'path'}), '(scan, path=path)\n', (1527, 1544), False, 'import utils\n'), ((20699, 20757), 'functools.partial', 'functools.partial', (['self._should_ask'], {'nav_oracle': 'nav_oracle'}), '(self._should_ask, nav_oracle=nav_oracle)\n', (20716, 20757), False, 'import functools\n'), ((21202, 21223), 'MatterSim.Simulator', 'MatterSim.Simulator', ([], {}), '()\n', (21221, 21223), False, 'import MatterSim\n'), ((1566, 1599), 'networkx.all_pairs_dijkstra_path', 'nx.all_pairs_dijkstra_path', (['graph'], {}), '(graph)\n', (1592, 1599), True, 'import networkx as nx\n'), ((1626, 1666), 'networkx.all_pairs_dijkstra_path_length', 'nx.all_pairs_dijkstra_path_length', (['graph'], {}), '(graph)\n', (1659, 1666), True, 'import networkx as nx\n'), ((3965, 4005), 'math.atan2', 'math.atan2', (['target_rel[1]', 'target_rel[0]'], {}), '(target_rel[1], target_rel[0])\n', (3975, 4005), False, 'import math\n'), ((16921, 16946), 'numpy.argmax', 'np.argmax', (["ob['nav_dist']"], {}), "(ob['nav_dist'])\n", (16930, 16946), True, 'import numpy as np\n'), ((18917, 18942), 'numpy.argmax', 'np.argmax', (["ob['nav_dist']"], {}), "(ob['nav_dist'])\n", (18926, 18942), True, 'import numpy as np\n'), ((21397, 21413), 'math.radians', 'math.radians', (['(60)'], {}), '(60)\n', (21409, 21413), False, 'import math\n'), ((21474, 21498), 'os.getenv', 'os.getenv', (['"""PT_DATA_DIR"""'], {}), "('PT_DATA_DIR')\n", (21483, 21498), False, 'import os\n'), ((24408, 24446), 'sys.exit', 'sys.exit', (['"""unknown step by step mode!"""'], {}), "('unknown step by step mode!')\n", (24416, 24446), False, 'import sys\n')]
import tensorflow as tf import numpy as np import unittest from dnc.controller import BaseController class DummyController(BaseController): def network_vars(self): self.W = tf.Variable(tf.truncated_normal([self.nn_input_size, 64])) self.b = tf.Variable(tf.zeros([64])) def network_op(self, X): return tf.matmul(X, self.W) + self.b class DummyRecurrentController(BaseController): def network_vars(self): self.lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(64) self.state = tf.Variable(tf.zeros([self.batch_size, 64]), trainable=False) self.output = tf.Variable(tf.zeros([self.batch_size, 64]), trainable=False) def network_op(self, X, state): X = tf.convert_to_tensor(X) return self.lstm_cell(X, state) def update_state(self, new_state): return tf.group( self.output.assign(new_state[0]), self.state.assign(new_state[1]) ) def get_state(self): return (self.output, self.state) class DNCControllerTest(unittest.TestCase): def test_construction(self): graph = tf.Graph() with graph.as_default(): with tf.Session(graph=graph) as session: controller = DummyController(10, 10, 2, 5) rcontroller = DummyRecurrentController(10, 10, 2, 5, 1) self.assertFalse(controller.has_recurrent_nn) self.assertEqual(controller.nn_input_size, 20) self.assertEqual(controller.interface_vector_size, 38) self.assertEqual(controller.interface_weights.get_shape().as_list(), [64, 38]) self.assertEqual(controller.nn_output_weights.get_shape().as_list(), [64, 10]) self.assertEqual(controller.mem_output_weights.get_shape().as_list(), [10, 10]) self.assertTrue(rcontroller.has_recurrent_nn) self.assertEqual(rcontroller.nn_input_size, 20) self.assertEqual(rcontroller.interface_vector_size, 38) self.assertEqual(rcontroller.interface_weights.get_shape().as_list(), [64, 38]) self.assertEqual(rcontroller.nn_output_weights.get_shape().as_list(), [64, 10]) self.assertEqual(rcontroller.mem_output_weights.get_shape().as_list(), [10, 10]) def test_get_nn_output_size(self): graph = tf.Graph() with graph.as_default(): with tf.Session(graph=graph) as Session: controller = DummyController(10, 10, 2, 5) rcontroller = DummyRecurrentController(10, 10, 2, 5, 1) self.assertEqual(controller.get_nn_output_size(), 64) self.assertEqual(rcontroller.get_nn_output_size(), 64) def test_parse_interface_vector(self): graph = tf.Graph() with graph.as_default(): with tf.Session(graph=graph) as session: controller = DummyController(10, 10, 2, 5) zeta = np.random.uniform(-2, 2, (2, 38)).astype(np.float32) read_keys = np.reshape(zeta[:, :10], (-1, 5, 2)) read_strengths = 1 + np.log(np.exp(np.reshape(zeta[:, 10:12], (-1, 2, ))) + 1) write_key = np.reshape(zeta[:, 12:17], (-1, 5, 1)) write_strength = 1 + np.log(np.exp(np.reshape(zeta[:, 17], (-1, 1))) + 1) erase_vector = 1.0 / (1 + np.exp(-1 * np.reshape(zeta[:, 18:23], (-1, 5)))) write_vector = np.reshape(zeta[:, 23:28], (-1, 5)) free_gates = 1.0 / (1 + np.exp(-1 * np.reshape(zeta[:, 28:30], (-1, 2)))) allocation_gate = 1.0 / (1 + np.exp(-1 * zeta[:, 30, np.newaxis])) write_gate = 1.0 / (1 + np.exp(-1 * zeta[:, 31, np.newaxis])) read_modes = np.reshape(zeta[:, 32:], (-1, 3, 2)) read_modes = np.transpose(read_modes, [0, 2, 1]) read_modes = np.reshape(read_modes, (-1, 3)) read_modes = np.exp(read_modes) / np.sum(np.exp(read_modes), axis=-1, keepdims=True) read_modes = np.reshape(read_modes, (2, 2, 3)) read_modes = np.transpose(read_modes, [0, 2, 1]) op = controller.parse_interface_vector(zeta) session.run(tf.initialize_all_variables()) parsed = session.run(op) self.assertTrue(np.allclose(parsed['read_keys'], read_keys)) self.assertTrue(np.allclose(parsed['read_strengths'], read_strengths)) self.assertTrue(np.allclose(parsed['write_key'], write_key)) self.assertTrue(np.allclose(parsed['write_strength'], write_strength)) self.assertTrue(np.allclose(parsed['erase_vector'], erase_vector)) self.assertTrue(np.allclose(parsed['write_vector'], write_vector)) self.assertTrue(np.allclose(parsed['free_gates'], free_gates)) self.assertTrue(np.allclose(parsed['allocation_gate'], allocation_gate)) self.assertTrue(np.allclose(parsed['write_gate'], write_gate)) self.assertTrue(np.allclose(parsed['read_modes'], read_modes)) def test_process_input(self): graph = tf.Graph() with graph.as_default(): with tf.Session(graph=graph) as session: controller = DummyController(10, 10, 2, 5) rcontroller = DummyRecurrentController(10, 10, 2, 5, 2) input_batch = np.random.uniform(0, 1, (2, 10)).astype(np.float32) last_read_vectors = np.random.uniform(-1, 1, (2, 5, 2)).astype(np.float32) v_op, zeta_op = controller.process_input(input_batch, last_read_vectors) rv_op, rzeta_op, rs_op = rcontroller.process_input(input_batch, last_read_vectors, rcontroller.get_state()) session.run(tf.initialize_all_variables()) v, zeta = session.run([v_op, zeta_op]) rv, rzeta, rs = session.run([rv_op, rzeta_op, rs_op]) self.assertEqual(v.shape, (2, 10)) self.assertEqual(np.concatenate([np.reshape(val, (2, -1)) for _, val in zeta.items()], axis=1).shape, (2, 38)) self.assertEqual(rv.shape, (2, 10)) self.assertEqual(np.concatenate([np.reshape(val, (2, -1)) for _, val in rzeta.items()], axis=1).shape, (2, 38)) self.assertEqual([_s.shape for _s in rs], [(2, 64), (2, 64)]) def test_final_output(self): graph = tf.Graph() with graph.as_default(): with tf.Session(graph=graph) as session: controller = DummyController(10, 10, 2, 5) output_batch = np.random.uniform(0, 1, (2, 10)).astype(np.float32) new_read_vectors = np.random.uniform(-1, 1, (2, 5, 2)).astype(np.float32) op = controller.final_output(output_batch, new_read_vectors) session.run(tf.initialize_all_variables()) y = session.run(op) self.assertEqual(y.shape, (2, 10)) if __name__ == '__main__': unittest.main(verbosity=2)
[ "tensorflow.Graph", "tensorflow.initialize_all_variables", "numpy.reshape", "numpy.allclose", "tensorflow.nn.rnn_cell.BasicLSTMCell", "tensorflow.convert_to_tensor", "tensorflow.Session", "numpy.exp", "tensorflow.matmul", "numpy.random.uniform", "unittest.main", "numpy.transpose", "tensorflow.zeros", "tensorflow.truncated_normal" ]
[((7097, 7123), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (7110, 7123), False, 'import unittest\n'), ((469, 501), 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(64)'], {}), '(64)\n', (497, 501), True, 'import tensorflow as tf\n'), ((718, 741), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['X'], {}), '(X)\n', (738, 741), True, 'import tensorflow as tf\n'), ((1110, 1120), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1118, 1120), True, 'import tensorflow as tf\n'), ((2368, 2378), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2376, 2378), True, 'import tensorflow as tf\n'), ((2800, 2810), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2808, 2810), True, 'import tensorflow as tf\n'), ((5218, 5228), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (5226, 5228), True, 'import tensorflow as tf\n'), ((6509, 6519), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (6517, 6519), True, 'import tensorflow as tf\n'), ((199, 244), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[self.nn_input_size, 64]'], {}), '([self.nn_input_size, 64])\n', (218, 244), True, 'import tensorflow as tf\n'), ((275, 289), 'tensorflow.zeros', 'tf.zeros', (['[64]'], {}), '([64])\n', (283, 289), True, 'import tensorflow as tf\n'), ((336, 356), 'tensorflow.matmul', 'tf.matmul', (['X', 'self.W'], {}), '(X, self.W)\n', (345, 356), True, 'import tensorflow as tf\n'), ((535, 566), 'tensorflow.zeros', 'tf.zeros', (['[self.batch_size, 64]'], {}), '([self.batch_size, 64])\n', (543, 566), True, 'import tensorflow as tf\n'), ((619, 650), 'tensorflow.zeros', 'tf.zeros', (['[self.batch_size, 64]'], {}), '([self.batch_size, 64])\n', (627, 650), True, 'import tensorflow as tf\n'), ((1171, 1194), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (1181, 1194), True, 'import tensorflow as tf\n'), ((2429, 2452), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (2439, 2452), True, 'import tensorflow as tf\n'), ((2861, 2884), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (2871, 2884), True, 'import tensorflow as tf\n'), ((3062, 3098), 'numpy.reshape', 'np.reshape', (['zeta[:, :10]', '(-1, 5, 2)'], {}), '(zeta[:, :10], (-1, 5, 2))\n', (3072, 3098), True, 'import numpy as np\n'), ((3222, 3260), 'numpy.reshape', 'np.reshape', (['zeta[:, 12:17]', '(-1, 5, 1)'], {}), '(zeta[:, 12:17], (-1, 5, 1))\n', (3232, 3260), True, 'import numpy as np\n'), ((3474, 3509), 'numpy.reshape', 'np.reshape', (['zeta[:, 23:28]', '(-1, 5)'], {}), '(zeta[:, 23:28], (-1, 5))\n', (3484, 3509), True, 'import numpy as np\n'), ((3790, 3826), 'numpy.reshape', 'np.reshape', (['zeta[:, 32:]', '(-1, 3, 2)'], {}), '(zeta[:, 32:], (-1, 3, 2))\n', (3800, 3826), True, 'import numpy as np\n'), ((3857, 3892), 'numpy.transpose', 'np.transpose', (['read_modes', '[0, 2, 1]'], {}), '(read_modes, [0, 2, 1])\n', (3869, 3892), True, 'import numpy as np\n'), ((3922, 3953), 'numpy.reshape', 'np.reshape', (['read_modes', '(-1, 3)'], {}), '(read_modes, (-1, 3))\n', (3932, 3953), True, 'import numpy as np\n'), ((4084, 4117), 'numpy.reshape', 'np.reshape', (['read_modes', '(2, 2, 3)'], {}), '(read_modes, (2, 2, 3))\n', (4094, 4117), True, 'import numpy as np\n'), ((4147, 4182), 'numpy.transpose', 'np.transpose', (['read_modes', '[0, 2, 1]'], {}), '(read_modes, [0, 2, 1])\n', (4159, 4182), True, 'import numpy as np\n'), ((5279, 5302), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (5289, 5302), True, 'import tensorflow as tf\n'), ((6570, 6593), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (6580, 6593), True, 'import tensorflow as tf\n'), ((3983, 4001), 'numpy.exp', 'np.exp', (['read_modes'], {}), '(read_modes)\n', (3989, 4001), True, 'import numpy as np\n'), ((4273, 4302), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (4300, 4302), True, 'import tensorflow as tf\n'), ((4378, 4421), 'numpy.allclose', 'np.allclose', (["parsed['read_keys']", 'read_keys'], {}), "(parsed['read_keys'], read_keys)\n", (4389, 4421), True, 'import numpy as np\n'), ((4455, 4508), 'numpy.allclose', 'np.allclose', (["parsed['read_strengths']", 'read_strengths'], {}), "(parsed['read_strengths'], read_strengths)\n", (4466, 4508), True, 'import numpy as np\n'), ((4542, 4585), 'numpy.allclose', 'np.allclose', (["parsed['write_key']", 'write_key'], {}), "(parsed['write_key'], write_key)\n", (4553, 4585), True, 'import numpy as np\n'), ((4619, 4672), 'numpy.allclose', 'np.allclose', (["parsed['write_strength']", 'write_strength'], {}), "(parsed['write_strength'], write_strength)\n", (4630, 4672), True, 'import numpy as np\n'), ((4706, 4755), 'numpy.allclose', 'np.allclose', (["parsed['erase_vector']", 'erase_vector'], {}), "(parsed['erase_vector'], erase_vector)\n", (4717, 4755), True, 'import numpy as np\n'), ((4789, 4838), 'numpy.allclose', 'np.allclose', (["parsed['write_vector']", 'write_vector'], {}), "(parsed['write_vector'], write_vector)\n", (4800, 4838), True, 'import numpy as np\n'), ((4872, 4917), 'numpy.allclose', 'np.allclose', (["parsed['free_gates']", 'free_gates'], {}), "(parsed['free_gates'], free_gates)\n", (4883, 4917), True, 'import numpy as np\n'), ((4951, 5006), 'numpy.allclose', 'np.allclose', (["parsed['allocation_gate']", 'allocation_gate'], {}), "(parsed['allocation_gate'], allocation_gate)\n", (4962, 5006), True, 'import numpy as np\n'), ((5040, 5085), 'numpy.allclose', 'np.allclose', (["parsed['write_gate']", 'write_gate'], {}), "(parsed['write_gate'], write_gate)\n", (5051, 5085), True, 'import numpy as np\n'), ((5119, 5164), 'numpy.allclose', 'np.allclose', (["parsed['read_modes']", 'read_modes'], {}), "(parsed['read_modes'], read_modes)\n", (5130, 5164), True, 'import numpy as np\n'), ((5864, 5893), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (5891, 5893), True, 'import tensorflow as tf\n'), ((6945, 6974), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (6972, 6974), True, 'import tensorflow as tf\n'), ((2980, 3013), 'numpy.random.uniform', 'np.random.uniform', (['(-2)', '(2)', '(2, 38)'], {}), '(-2, 2, (2, 38))\n', (2997, 3013), True, 'import numpy as np\n'), ((3645, 3681), 'numpy.exp', 'np.exp', (['(-1 * zeta[:, 30, np.newaxis])'], {}), '(-1 * zeta[:, 30, np.newaxis])\n', (3651, 3681), True, 'import numpy as np\n'), ((3723, 3759), 'numpy.exp', 'np.exp', (['(-1 * zeta[:, 31, np.newaxis])'], {}), '(-1 * zeta[:, 31, np.newaxis])\n', (3729, 3759), True, 'import numpy as np\n'), ((4011, 4029), 'numpy.exp', 'np.exp', (['read_modes'], {}), '(read_modes)\n', (4017, 4029), True, 'import numpy as np\n'), ((5478, 5510), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(2, 10)'], {}), '(0, 1, (2, 10))\n', (5495, 5510), True, 'import numpy as np\n'), ((5566, 5601), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '(2, 5, 2)'], {}), '(-1, 1, (2, 5, 2))\n', (5583, 5601), True, 'import numpy as np\n'), ((6697, 6729), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(2, 10)'], {}), '(0, 1, (2, 10))\n', (6714, 6729), True, 'import numpy as np\n'), ((6784, 6819), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '(2, 5, 2)'], {}), '(-1, 1, (2, 5, 2))\n', (6801, 6819), True, 'import numpy as np\n'), ((3150, 3185), 'numpy.reshape', 'np.reshape', (['zeta[:, 10:12]', '(-1, 2)'], {}), '(zeta[:, 10:12], (-1, 2))\n', (3160, 3185), True, 'import numpy as np\n'), ((3312, 3344), 'numpy.reshape', 'np.reshape', (['zeta[:, 17]', '(-1, 1)'], {}), '(zeta[:, 17], (-1, 1))\n', (3322, 3344), True, 'import numpy as np\n'), ((3405, 3440), 'numpy.reshape', 'np.reshape', (['zeta[:, 18:23]', '(-1, 5)'], {}), '(zeta[:, 18:23], (-1, 5))\n', (3415, 3440), True, 'import numpy as np\n'), ((3562, 3597), 'numpy.reshape', 'np.reshape', (['zeta[:, 28:30]', '(-1, 2)'], {}), '(zeta[:, 28:30], (-1, 2))\n', (3572, 3597), True, 'import numpy as np\n'), ((6121, 6145), 'numpy.reshape', 'np.reshape', (['val', '(2, -1)'], {}), '(val, (2, -1))\n', (6131, 6145), True, 'import numpy as np\n'), ((6301, 6325), 'numpy.reshape', 'np.reshape', (['val', '(2, -1)'], {}), '(val, (2, -1))\n', (6311, 6325), True, 'import numpy as np\n')]
import inspect import pytest import numpy as np from datar.core.backends.pandas import Categorical, DataFrame, Series from datar.core.backends.pandas.testing import assert_frame_equal from datar.core.backends.pandas.core.groupby import SeriesGroupBy from datar.core.factory import func_factory from datar.core.tibble import ( SeriesCategorical, SeriesRowwise, TibbleGrouped, TibbleRowwise, ) from datar.tibble import tibble from ..conftest import assert_iterable_equal def test_transform_default(): @func_factory("transform", "x") def double(x): return x * 2 # scalar out = double(3) assert out[0] == 6 out = double(np.array([1, 2], dtype=int)) assert_iterable_equal(out, [2, 4]) @func_factory("transform", "x") def double(x): return x * 2 out = double([1, 2]) assert_iterable_equal(out, [2, 4]) # default on series x = Series([2, 3], index=["a", "b"]) out = double(x) assert isinstance(out, Series) assert_iterable_equal(out.index, ["a", "b"]) assert_iterable_equal(out, [4, 6]) # default on dataframe x = DataFrame({"a": [3, 4]}) out = double(x) assert isinstance(out, DataFrame) assert_iterable_equal(out.a, [6, 8]) # default on seriesgroupby x = Series([1, 2, 1, 2]).groupby([1, 1, 2, 2]) out = double(x) assert isinstance(out, SeriesGroupBy) assert_iterable_equal(out.obj, [2, 4, 2, 4]) assert out.grouper.ngroups == 2 # on tibble grouped x = tibble(x=[1, 2, 1, 2], g=[1, 1, 2, 2]).group_by("g") out = double(x) # grouping variables not included assert_iterable_equal(out.x.obj, [2, 4, 2, 4]) x = tibble(x=[1, 2, 1, 2], g=[1, 1, 2, 2]).rowwise("g") out = double(x) assert isinstance(out, TibbleRowwise) assert_frame_equal(out, out._datar["grouped"].obj) assert_iterable_equal(out.x.obj, [2, 4, 2, 4]) assert_iterable_equal(out.group_vars, ["g"]) def test_transform_register(): @func_factory(kind="transform", data_args="x") def double(x): return x * 2 @double.register(DataFrame) def _(x): return x * 3 x = Series([2, 3]) out = double(x) assert_iterable_equal(out, [4, 6]) double.register(Series, lambda x: x * 4) out = double(x) assert_iterable_equal(out, [8, 12]) x = tibble(a=[1, 3]) out = double(x) assert_iterable_equal(out.a, [3, 9]) out = double([1, 4]) assert_iterable_equal(out, [4, 16]) # register an available string func for tranform double.register(SeriesGroupBy, "sum") x = Series([1, -2]).groupby([1, 2]) out = double(x) assert_iterable_equal(out.obj, [1, -2]) # seriesrowwise double.register(SeriesRowwise, lambda x: x + 1) x.is_rowwise = True out = double(x) assert_iterable_equal(out.obj, [2, -1]) assert out.is_rowwise def test_transform_hooks(): @func_factory(kind="transform", data_args="x") def times(x, t): return x * t with pytest.raises(ValueError): times.register(Series, meta=False, pre=1, func=None) times.register( Series, func=None, pre=lambda x, t: (x, (-t,), {}), post=lambda out, x, t: out + t, ) x = Series([1, 2]) out = times(x, -1) assert_iterable_equal(out, [2, 3]) @times.register(Series, meta=False) def _(x, t): return x + t out = times(x, 10) assert_iterable_equal(out, [11, 12]) @times.register(SeriesGroupBy, meta=True) def _(x, t): return x + 10 x = Series([1, 2, 1, 2]).groupby([1, 1, 2, 2]) out = times(x, 1) assert_iterable_equal(out.obj, [11, 12, 11, 12]) times.register( SeriesGroupBy, func=None, pre=lambda x, t: (x, (t + 1,), {}), post=lambda out, x, *args, **kwargs: out, ) out = times(x, 1) assert_iterable_equal(out, [2, 4, 2, 4]) times.register( Series, func=None, pre=lambda *args, **kwargs: None, post=lambda out, x, t: out + t, ) x = Series([1, 2]) out = times(x, 3) assert_iterable_equal(out, [4, 5]) @times.register(DataFrame, meta=True) def _(x, t): return x ** t x = tibble(a=[1, 2], b=[2, 3]) out = times(x, 3) assert_iterable_equal(out.a, [1, 8]) assert_iterable_equal(out.b, [8, 27]) # TibbleGrouped times.register( TibbleGrouped, func=None, pre=lambda x, t: (x, (t - 1,), {}), post=lambda out, x, t: out.reindex([1, 0]), ) x = x.group_by("a") out = times(x, 3) assert_iterable_equal(out.b, [6, 4]) @times.register( TibbleGrouped, meta=False, ) def _(x, t): out = x.transform(lambda d, t: d * t, 0, t - 1) out.iloc[0, 1] = 10 return out # x = tibble(a=[1, 2], b=[2, 3]) # grouped by a out = times(x, 3) assert isinstance(out, TibbleGrouped) assert_iterable_equal(out.group_vars, ["a"]) assert_iterable_equal(out.b.obj, [10, 6]) def test_agg(): men = func_factory( "agg", "a", name="men", func=np.mean, signature=inspect.signature(lambda a: None), ) x = [1, 2, 3] out = men(x) assert out == 2.0 x = Series([1, 2, 3]) out = men(x) assert out == 2.0 # SeriesGroupBy men.register(SeriesGroupBy, func="mean") x = Series([1, 2, 4]).groupby([1, 2, 2]) out = men(x) assert_iterable_equal(out.index, [1, 2]) assert_iterable_equal(out, [1.0, 3.0]) # SeriesRowwise df = tibble(x=[1, 2, 4]).rowwise() out = men(df.x) assert_iterable_equal(out, df.x.obj) men.register(SeriesRowwise, func="sum") out = men(df.x) assert_iterable_equal(out.index, [0, 1, 2]) assert_iterable_equal(out, [1.0, 2.0, 4.0]) # TibbleRowwise x = tibble(a=[1, 2, 3], b=[4, 5, 6]).rowwise() out = men(x) assert_iterable_equal(out, [2.5, 3.5, 4.5]) # TibbleGrouped x = tibble(a=[1, 2, 3], b=[4, 5, 5]).group_by("b") out = men(x) assert_iterable_equal(out.a, [1.0, 2.5]) def test_varargs_data_args(): @func_factory("agg", {"x", "args[0]"}) def mulsum(x, *args): return (x + args[0]) * args[1] out = mulsum([1, 2], 2, 3) assert_iterable_equal(out, [9, 12]) @func_factory("agg", {"x", "args"}) def mulsum(x, *args): return x + args[0] + args[1] out = mulsum([1, 2], [1, 2], [2, 3]) assert_iterable_equal(out, [4, 7]) def test_dataargs_not_exist(): fun = func_factory("agg", "y")(lambda x: None) with pytest.raises(ValueError): fun(1) def test_args_frame(): @func_factory("agg", {"x", "y"}) def frame(x, y, __args_frame=None): return __args_frame out = frame(1, 2) assert_iterable_equal(sorted(out.columns), ["x", "y"]) def test_args_raw(): @func_factory("agg", {"x"}) def raw(x, __args_raw=None): return x, __args_raw["x"] outx, rawx = raw(1) assert isinstance(outx, Series) assert rawx == 1 def test_apply(): @func_factory("apply", "x") def rn(x): return tibble(x=[1, 2, 3]) x = tibble(a=[1, 2], b=[2, 3]).rowwise() out = rn(x) assert out.shape == (2,) assert out.iloc[0].shape == (3, 1) def test_no_func_registered(): fun = func_factory("agg", "x", func=lambda x: None) with pytest.raises(ValueError): fun.register(SeriesGroupBy, func=None, meta=False) def test_run_error(): @func_factory("agg", "x") def error(x): raise RuntimeError with pytest.raises(ValueError, match="registered function"): error(1) def test_series_cat(): @func_factory("agg", "x") def sum1(x): return x.sum() @sum1.register(SeriesCategorical) def _(x): return x[0] out = sum1([1, 2]) assert out == 3 out = sum1(Categorical([1, 2])) assert out == 1 def test_str_fun(): sum2 = func_factory( "agg", "x", name="sum2", qualname="sum2", func="sum", signature=inspect.signature(lambda x: None), ) assert sum2([1, 2, 3]) == 6
[ "datar.tibble.tibble", "inspect.signature", "datar.core.backends.pandas.testing.assert_frame_equal", "datar.core.backends.pandas.DataFrame", "numpy.array", "datar.core.backends.pandas.Categorical", "pytest.raises", "datar.core.backends.pandas.Series", "datar.core.factory.func_factory" ]
[((524, 554), 'datar.core.factory.func_factory', 'func_factory', (['"""transform"""', '"""x"""'], {}), "('transform', 'x')\n", (536, 554), False, 'from datar.core.factory import func_factory\n'), ((744, 774), 'datar.core.factory.func_factory', 'func_factory', (['"""transform"""', '"""x"""'], {}), "('transform', 'x')\n", (756, 774), False, 'from datar.core.factory import func_factory\n'), ((913, 945), 'datar.core.backends.pandas.Series', 'Series', (['[2, 3]'], {'index': "['a', 'b']"}), "([2, 3], index=['a', 'b'])\n", (919, 945), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((1125, 1149), 'datar.core.backends.pandas.DataFrame', 'DataFrame', (["{'a': [3, 4]}"], {}), "({'a': [3, 4]})\n", (1134, 1149), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((1801, 1851), 'datar.core.backends.pandas.testing.assert_frame_equal', 'assert_frame_equal', (['out', "out._datar['grouped'].obj"], {}), "(out, out._datar['grouped'].obj)\n", (1819, 1851), False, 'from datar.core.backends.pandas.testing import assert_frame_equal\n'), ((1990, 2035), 'datar.core.factory.func_factory', 'func_factory', ([], {'kind': '"""transform"""', 'data_args': '"""x"""'}), "(kind='transform', data_args='x')\n", (2002, 2035), False, 'from datar.core.factory import func_factory\n'), ((2153, 2167), 'datar.core.backends.pandas.Series', 'Series', (['[2, 3]'], {}), '([2, 3])\n', (2159, 2167), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((2343, 2359), 'datar.tibble.tibble', 'tibble', ([], {'a': '[1, 3]'}), '(a=[1, 3])\n', (2349, 2359), False, 'from datar.tibble import tibble\n'), ((2909, 2954), 'datar.core.factory.func_factory', 'func_factory', ([], {'kind': '"""transform"""', 'data_args': '"""x"""'}), "(kind='transform', data_args='x')\n", (2921, 2954), False, 'from datar.core.factory import func_factory\n'), ((3247, 3261), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2]'], {}), '([1, 2])\n', (3253, 3261), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((4063, 4077), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2]'], {}), '([1, 2])\n', (4069, 4077), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((4230, 4256), 'datar.tibble.tibble', 'tibble', ([], {'a': '[1, 2]', 'b': '[2, 3]'}), '(a=[1, 2], b=[2, 3])\n', (4236, 4256), False, 'from datar.tibble import tibble\n'), ((5276, 5293), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (5282, 5293), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((6143, 6180), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', "{'x', 'args[0]'}"], {}), "('agg', {'x', 'args[0]'})\n", (6155, 6180), False, 'from datar.core.factory import func_factory\n'), ((6324, 6358), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', "{'x', 'args'}"], {}), "('agg', {'x', 'args'})\n", (6336, 6358), False, 'from datar.core.factory import func_factory\n'), ((6668, 6699), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', "{'x', 'y'}"], {}), "('agg', {'x', 'y'})\n", (6680, 6699), False, 'from datar.core.factory import func_factory\n'), ((6878, 6904), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', "{'x'}"], {}), "('agg', {'x'})\n", (6890, 6904), False, 'from datar.core.factory import func_factory\n'), ((7079, 7105), 'datar.core.factory.func_factory', 'func_factory', (['"""apply"""', '"""x"""'], {}), "('apply', 'x')\n", (7091, 7105), False, 'from datar.core.factory import func_factory\n'), ((7329, 7374), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', '"""x"""'], {'func': '(lambda x: None)'}), "('agg', 'x', func=lambda x: None)\n", (7341, 7374), False, 'from datar.core.factory import func_factory\n'), ((7499, 7523), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', '"""x"""'], {}), "('agg', 'x')\n", (7511, 7523), False, 'from datar.core.factory import func_factory\n'), ((7682, 7706), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', '"""x"""'], {}), "('agg', 'x')\n", (7694, 7706), False, 'from datar.core.factory import func_factory\n'), ((670, 697), 'numpy.array', 'np.array', (['[1, 2]'], {'dtype': 'int'}), '([1, 2], dtype=int)\n', (678, 697), True, 'import numpy as np\n'), ((3007, 3032), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3020, 3032), False, 'import pytest\n'), ((6546, 6570), 'datar.core.factory.func_factory', 'func_factory', (['"""agg"""', '"""y"""'], {}), "('agg', 'y')\n", (6558, 6570), False, 'from datar.core.factory import func_factory\n'), ((6596, 6621), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6609, 6621), False, 'import pytest\n'), ((7136, 7155), 'datar.tibble.tibble', 'tibble', ([], {'x': '[1, 2, 3]'}), '(x=[1, 2, 3])\n', (7142, 7155), False, 'from datar.tibble import tibble\n'), ((7384, 7409), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7397, 7409), False, 'import pytest\n'), ((7579, 7633), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""registered function"""'}), "(ValueError, match='registered function')\n", (7592, 7633), False, 'import pytest\n'), ((7880, 7899), 'datar.core.backends.pandas.Categorical', 'Categorical', (['[1, 2]'], {}), '([1, 2])\n', (7891, 7899), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((1289, 1309), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2, 1, 2]'], {}), '([1, 2, 1, 2])\n', (1295, 1309), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((1512, 1550), 'datar.tibble.tibble', 'tibble', ([], {'x': '[1, 2, 1, 2]', 'g': '[1, 1, 2, 2]'}), '(x=[1, 2, 1, 2], g=[1, 1, 2, 2])\n', (1518, 1550), False, 'from datar.tibble import tibble\n'), ((1683, 1721), 'datar.tibble.tibble', 'tibble', ([], {'x': '[1, 2, 1, 2]', 'g': '[1, 1, 2, 2]'}), '(x=[1, 2, 1, 2], g=[1, 1, 2, 2])\n', (1689, 1721), False, 'from datar.tibble import tibble\n'), ((2591, 2606), 'datar.core.backends.pandas.Series', 'Series', (['[1, -2]'], {}), '([1, -2])\n', (2597, 2606), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((3563, 3583), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2, 1, 2]'], {}), '([1, 2, 1, 2])\n', (3569, 3583), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((5168, 5201), 'inspect.signature', 'inspect.signature', (['(lambda a: None)'], {}), '(lambda a: None)\n', (5185, 5201), False, 'import inspect\n'), ((5407, 5424), 'datar.core.backends.pandas.Series', 'Series', (['[1, 2, 4]'], {}), '([1, 2, 4])\n', (5413, 5424), False, 'from datar.core.backends.pandas import Categorical, DataFrame, Series\n'), ((5579, 5598), 'datar.tibble.tibble', 'tibble', ([], {'x': '[1, 2, 4]'}), '(x=[1, 2, 4])\n', (5585, 5598), False, 'from datar.tibble import tibble\n'), ((5860, 5892), 'datar.tibble.tibble', 'tibble', ([], {'a': '[1, 2, 3]', 'b': '[4, 5, 6]'}), '(a=[1, 2, 3], b=[4, 5, 6])\n', (5866, 5892), False, 'from datar.tibble import tibble\n'), ((5997, 6029), 'datar.tibble.tibble', 'tibble', ([], {'a': '[1, 2, 3]', 'b': '[4, 5, 5]'}), '(a=[1, 2, 3], b=[4, 5, 5])\n', (6003, 6029), False, 'from datar.tibble import tibble\n'), ((7165, 7191), 'datar.tibble.tibble', 'tibble', ([], {'a': '[1, 2]', 'b': '[2, 3]'}), '(a=[1, 2], b=[2, 3])\n', (7171, 7191), False, 'from datar.tibble import tibble\n'), ((8080, 8113), 'inspect.signature', 'inspect.signature', (['(lambda x: None)'], {}), '(lambda x: None)\n', (8097, 8113), False, 'import inspect\n')]
#!/usr/bin/env python3 """ Created on Tue Sep 1 2020 @author: kstoreyf """ import numpy as np import nbodykit import pandas as pd import pickle from nbodykit import cosmology def main(): save_fn = '../data/cosmology_train.pickle' x = generate_training_parameters(n_train=1000) y, extra_input = generate_data(x) input_data, output_data = format_data(x, y, objs_id=None) data_to_save = make_data_to_save(input_data, output_data, extra_input) save_data(data_to_save, save_fn) save_fn = '../data/cosmology_test.pickle' x = generate_testing_parameters(n_test=100) y, extra_input = generate_data(x) input_data, output_data = format_data(x, y, objs_id=None) data_to_save = make_data_to_save(input_data, output_data, extra_input) save_data(data_to_save, save_fn) # Generate the parameters that govern the output training set data def generate_training_parameters(n_train=1000): n_params = 3 n_points = n_train**(1./float(n_params)) assert abs(round(n_points) - n_points) < 1e-12, f"n_train must be a power of {n_params} because we're making a high-dimensional grid." n_points = round(n_points) omega_m = np.linspace(0.26, 0.34, n_points) sigma_8 = np.linspace(0.7, 0.95, n_points) omega_b = np.linspace(0.038, 0.058, n_points) grid = np.meshgrid(omega_m, sigma_8, omega_b) # x has shape (n_params, n_train), where n_train = n_points**n_params x = np.array([grid[p].flatten() for p in range(n_params)]) return x # Generate the parameters that govern the output testing set data def generate_testing_parameters(n_test=100): omega_m = random_between(0.26, 0.34, n_test) sigma_8 = random_between(0.7, 0.95, n_test) omega_b = random_between(0.038, 0.058, n_test) # x has shape (n_params, n_test) x = np.array([omega_m, sigma_8, omega_b]) return x def random_between(xmin, xmax, n): return np.random.rand(n)*(xmax-xmin)+xmin # Generate the output data that we're interested in emulating def generate_data(x): redshift = 0.0 r_vals = np.linspace(50, 140, 10) extra_input = {'redshift': redshift, 'r_vals': r_vals} n_data = x.shape[1] y = np.empty((len(r_vals), n_data)) for i in range(n_data): print(i) om, s8, ob = x[:,i] ocdm = om - ob m_ncdm = [] #no massive neutrinos cosmo = cosmology.Cosmology(Omega0_b=ob, Omega0_cdm=ocdm, m_ncdm=m_ncdm) cosmo = cosmo.match(sigma8=s8) plin = cosmology.LinearPower(cosmo, redshift, transfer='EisensteinHu') cf = cosmology.correlation.CorrelationFunction(plin) y[:,i] = cf(r_vals) return y, extra_input # Format data into pandas data frames def format_data(x_input, y_output, objs_id=None): number_objs = len(x_input[0,:]) number_outputs = len(y_output[:,0]) if objs_id is None: objs_id = [f'obj_{i}'for i in np.arange(number_objs)] input_data = pd.DataFrame() input_data['object_id'] = objs_id input_data[r'$\Omega_m$'] = x_input[0,:] input_data[r'$\sigma_8$'] = x_input[1,:] input_data[r'$\Omega_b$'] = x_input[2,:] output_data = pd.DataFrame() output_data['object_id'] = objs_id for i in np.arange(number_outputs): output_data[r'$\xi(r_{})$'.format(i)] = y_output[i, :] return input_data, output_data # Format the data to save it def make_data_to_save(input_data, output_data, extra_input=None): data_to_save = {'input_data': input_data, 'output_data': output_data} if extra_input is not None: data_to_save['extra_input'] = extra_input return data_to_save # Save the data to a file def save_data(data, save_fn): with open(save_fn, 'wb') as f: pickle.dump(data, f, protocol=3) if __name__=='__main__': main()
[ "nbodykit.cosmology.correlation.CorrelationFunction", "pickle.dump", "numpy.random.rand", "nbodykit.cosmology.Cosmology", "numpy.array", "numpy.linspace", "nbodykit.cosmology.LinearPower", "pandas.DataFrame", "numpy.meshgrid", "numpy.arange" ]
[((1335, 1368), 'numpy.linspace', 'np.linspace', (['(0.26)', '(0.34)', 'n_points'], {}), '(0.26, 0.34, n_points)\n', (1346, 1368), True, 'import numpy as np\n'), ((1383, 1415), 'numpy.linspace', 'np.linspace', (['(0.7)', '(0.95)', 'n_points'], {}), '(0.7, 0.95, n_points)\n', (1394, 1415), True, 'import numpy as np\n'), ((1430, 1465), 'numpy.linspace', 'np.linspace', (['(0.038)', '(0.058)', 'n_points'], {}), '(0.038, 0.058, n_points)\n', (1441, 1465), True, 'import numpy as np\n'), ((1477, 1515), 'numpy.meshgrid', 'np.meshgrid', (['omega_m', 'sigma_8', 'omega_b'], {}), '(omega_m, sigma_8, omega_b)\n', (1488, 1515), True, 'import numpy as np\n'), ((1972, 2009), 'numpy.array', 'np.array', (['[omega_m, sigma_8, omega_b]'], {}), '([omega_m, sigma_8, omega_b])\n', (1980, 2009), True, 'import numpy as np\n'), ((2224, 2248), 'numpy.linspace', 'np.linspace', (['(50)', '(140)', '(10)'], {}), '(50, 140, 10)\n', (2235, 2248), True, 'import numpy as np\n'), ((3099, 3113), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3111, 3113), True, 'import pandas as pd\n'), ((3310, 3324), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3322, 3324), True, 'import pandas as pd\n'), ((3377, 3402), 'numpy.arange', 'np.arange', (['number_outputs'], {}), '(number_outputs)\n', (3386, 3402), True, 'import numpy as np\n'), ((2527, 2591), 'nbodykit.cosmology.Cosmology', 'cosmology.Cosmology', ([], {'Omega0_b': 'ob', 'Omega0_cdm': 'ocdm', 'm_ncdm': 'm_ncdm'}), '(Omega0_b=ob, Omega0_cdm=ocdm, m_ncdm=m_ncdm)\n', (2546, 2591), False, 'from nbodykit import cosmology\n'), ((2646, 2709), 'nbodykit.cosmology.LinearPower', 'cosmology.LinearPower', (['cosmo', 'redshift'], {'transfer': '"""EisensteinHu"""'}), "(cosmo, redshift, transfer='EisensteinHu')\n", (2667, 2709), False, 'from nbodykit import cosmology\n'), ((2723, 2770), 'nbodykit.cosmology.correlation.CorrelationFunction', 'cosmology.correlation.CorrelationFunction', (['plin'], {}), '(plin)\n', (2764, 2770), False, 'from nbodykit import cosmology\n'), ((3901, 3933), 'pickle.dump', 'pickle.dump', (['data', 'f'], {'protocol': '(3)'}), '(data, f, protocol=3)\n', (3912, 3933), False, 'import pickle\n'), ((2071, 2088), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (2085, 2088), True, 'import numpy as np\n'), ((3053, 3075), 'numpy.arange', 'np.arange', (['number_objs'], {}), '(number_objs)\n', (3062, 3075), True, 'import numpy as np\n')]
#from data_loader import * from scipy import signal import matplotlib.pyplot as plt import copy import os import shutil import numpy as np def data_filter(exp_path, probe_type='point', Xtype='loc',ytype='f',num_point=0): shutil.rmtree(exp_path+probe_type+'_expand', ignore_errors=True) os.mkdir(exp_path+probe_type+'_expand') for i in range(num_point): #load force/torque data force_path = exp_path+probe_type+'/force_'+str(i)+'.txt' new_force_path = exp_path+probe_type+'_expand'+'/force_'+str(i)+'.txt' force=[] torque=[] force_normal=[] torque_normal=[] displacement=[] dataFile=open(force_path,'r') for line in dataFile: line=line.rstrip() l=[num for num in line.split(' ')] l2=[float(num) for num in l] force.append(l2[0:3]) force_normal.append(l2[3]) displacement.append(l2[4]) dataFile.close() if probe_type == 'line': torque_path = exp_path+probe_type+'/torque_'+str(i)+'.txt' dataFile=open(torque_path,'r') for line in dataFile: line=line.rstrip() l=[num for num in line.split(' ')] l2=[float(num) for num in l] torque.append(l2[0:3]) torque_normal.append(l2[3]) dataFile.close() elif probe_type == 'ellipse': torque_path = exp_path+probe_type+'/torque_'+str(i)+'.txt' dataFile=open(torque_path,'r') for line in dataFile: line=line.rstrip() l=[num for num in line.split(' ')] l2=[float(num) for num in l] torque.append(l2[0:3]) displacement.append(l2[3]) dataFile.close() force_normal_1d =np.array(force_normal) #to np force=np.array(force,ndmin=2) torque=np.array(torque,ndmin=2) force_normal=np.array(force_normal,ndmin=2).T torque_normal=np.array(torque_normal,ndmin=2).T displacement=np.array(displacement) #filter Wn=0.01 [b,a]=signal.butter(5,Wn,'low') for i in range(3): tmp_filteredForces=signal.filtfilt(b,a,force[:,i].T,padlen=150) if i == 0: filteredForces = np.array(tmp_filteredForces,ndmin=2).T print(filteredForces.shape) else: filteredForces = np.hstack((filteredForces,np.array(tmp_filteredForces,ndmin=2).T)) if probe_type == 'line' or probe_type == 'ellipse': for i in range(3): tmp_filteredTorques=signal.filtfilt(b,a,torque[:,i].T,padlen=150) if i == 0: filteredTorques = tmp_filteredTorques.T else: filteredTorques = np.hstack((filteredTorques,tmp_filteredTorques.T)) filtered_force_normal=signal.filtfilt(b,a,force_normal.T,padlen=150) if probe_type == 'line': filtered_torque_normal=signal.filtfilt(b,a,torque_normal.T,padlen=150) #filtered_force_normal = filtered_force_normal.T print(filtered_force_normal.shape) new_dataFile=open(new_force_path,'w+') num_data = len(displacement) #delta_d = (displacement[num_data-1]-displacement[num_data-101])/1 delta_d = 0.0002 d_expand_start = displacement[num_data-1] + delta_d d_expand_end = 0.020 d_expand = np.arange(d_expand_start,d_expand_end,delta_d) num_expand = d_expand.shape[0] print('[*]',num_expand) slope = (force_normal[num_data-1] - force_normal[num_data-301])/(displacement[num_data-1]-displacement[num_data-301]) sd = slope*delta_d fn_expand_start = force_normal[num_data-1] + sd*1 fn_expand_end = force_normal[num_data-1] + sd*(num_expand+1) force_normal_expand = np.arange(fn_expand_start,fn_expand_end,sd) print('[*]',len(d_expand)) d_all = displacement.tolist()+d_expand.tolist() fn_all = force_normal_1d.tolist()+force_normal_expand.tolist() num_all = len(d_all) - 2 print(num_all) d_all = d_all[0:num_all] fn_all = fn_all[0:num_all] for i in range(num_all): new_dataFile.write(str(0)+' '+str(0)+' '+str(0)+' ') new_dataFile.write(str(fn_all[i])+' '+str(d_all[i])+'\n') new_dataFile.close() ''' for i in range(displacement.shape[0]): new_dataFile.write(str(filteredForces[i,0])+' '+str(filteredForces[i,1])+' '+str(filteredForces[i,2])+' ') new_dataFile.write(str(filtered_force_normal[0,i])+' '+str(displacement[i])+'\n') new_dataFile.close() ''' return d_all, fn_all d,fn = data_filter('./', probe_type='point', Xtype='loc',ytype='fn',num_point=94) print(len(d),len(fn)) plt.plot(np.array(d),np.array(fn),color='b',marker='o',markersize=1) plt.show()
[ "numpy.hstack", "scipy.signal.filtfilt", "scipy.signal.butter", "numpy.array", "os.mkdir", "shutil.rmtree", "numpy.arange", "matplotlib.pyplot.show" ]
[((5134, 5144), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5142, 5144), True, 'import matplotlib.pyplot as plt\n'), ((226, 294), 'shutil.rmtree', 'shutil.rmtree', (["(exp_path + probe_type + '_expand')"], {'ignore_errors': '(True)'}), "(exp_path + probe_type + '_expand', ignore_errors=True)\n", (239, 294), False, 'import shutil\n'), ((295, 338), 'os.mkdir', 'os.mkdir', (["(exp_path + probe_type + '_expand')"], {}), "(exp_path + probe_type + '_expand')\n", (303, 338), False, 'import os\n'), ((5074, 5085), 'numpy.array', 'np.array', (['d'], {}), '(d)\n', (5082, 5085), True, 'import numpy as np\n'), ((5086, 5098), 'numpy.array', 'np.array', (['fn'], {}), '(fn)\n', (5094, 5098), True, 'import numpy as np\n'), ((1898, 1920), 'numpy.array', 'np.array', (['force_normal'], {}), '(force_normal)\n', (1906, 1920), True, 'import numpy as np\n'), ((1950, 1974), 'numpy.array', 'np.array', (['force'], {'ndmin': '(2)'}), '(force, ndmin=2)\n', (1958, 1974), True, 'import numpy as np\n'), ((1989, 2014), 'numpy.array', 'np.array', (['torque'], {'ndmin': '(2)'}), '(torque, ndmin=2)\n', (1997, 2014), True, 'import numpy as np\n'), ((2145, 2167), 'numpy.array', 'np.array', (['displacement'], {}), '(displacement)\n', (2153, 2167), True, 'import numpy as np\n'), ((2223, 2250), 'scipy.signal.butter', 'signal.butter', (['(5)', 'Wn', '"""low"""'], {}), "(5, Wn, 'low')\n", (2236, 2250), False, 'from scipy import signal\n'), ((3037, 3086), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'force_normal.T'], {'padlen': '(150)'}), '(b, a, force_normal.T, padlen=150)\n', (3052, 3086), False, 'from scipy import signal\n'), ((3637, 3685), 'numpy.arange', 'np.arange', (['d_expand_start', 'd_expand_end', 'delta_d'], {}), '(d_expand_start, d_expand_end, delta_d)\n', (3646, 3685), True, 'import numpy as np\n'), ((4083, 4128), 'numpy.arange', 'np.arange', (['fn_expand_start', 'fn_expand_end', 'sd'], {}), '(fn_expand_start, fn_expand_end, sd)\n', (4092, 4128), True, 'import numpy as np\n'), ((2035, 2066), 'numpy.array', 'np.array', (['force_normal'], {'ndmin': '(2)'}), '(force_normal, ndmin=2)\n', (2043, 2066), True, 'import numpy as np\n'), ((2090, 2122), 'numpy.array', 'np.array', (['torque_normal'], {'ndmin': '(2)'}), '(torque_normal, ndmin=2)\n', (2098, 2122), True, 'import numpy as np\n'), ((2316, 2364), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'force[:, i].T'], {'padlen': '(150)'}), '(b, a, force[:, i].T, padlen=150)\n', (2331, 2364), False, 'from scipy import signal\n'), ((3161, 3211), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'torque_normal.T'], {'padlen': '(150)'}), '(b, a, torque_normal.T, padlen=150)\n', (3176, 3211), False, 'from scipy import signal\n'), ((2754, 2803), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'torque[:, i].T'], {'padlen': '(150)'}), '(b, a, torque[:, i].T, padlen=150)\n', (2769, 2803), False, 'from scipy import signal\n'), ((2417, 2454), 'numpy.array', 'np.array', (['tmp_filteredForces'], {'ndmin': '(2)'}), '(tmp_filteredForces, ndmin=2)\n', (2425, 2454), True, 'import numpy as np\n'), ((2947, 2998), 'numpy.hstack', 'np.hstack', (['(filteredTorques, tmp_filteredTorques.T)'], {}), '((filteredTorques, tmp_filteredTorques.T))\n', (2956, 2998), True, 'import numpy as np\n'), ((2577, 2614), 'numpy.array', 'np.array', (['tmp_filteredForces'], {'ndmin': '(2)'}), '(tmp_filteredForces, ndmin=2)\n', (2585, 2614), True, 'import numpy as np\n')]
import numpy as np import cv2 import argparse from collections import deque import keyboard as kb import time from pynput.keyboard import Key, Controller, Listener class points(object): def __init__(self, x, y): self.x = x self.y = y sm_threshold = 100 lg_threshold = 200 guiding = True keyboard = Controller() cap = cv2.VideoCapture(0) pts = deque(maxlen=64) Lower_green = np.array([110, 50, 50]) Upper_green = np.array([130, 255, 255]) startPoint =endPoint = points(0,0) recentPoints = deque() # counter = 0 # prev_x = 0 # prev_y = 0 while True: if kb.is_pressed('q'): guiding = False if kb.is_pressed('w'): guiding = True ret, img = cap.read() hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) kernel = np.ones((5, 5), np.uint8) mask = cv2.inRange(hsv, Lower_green, Upper_green) mask = cv2.erode(mask, kernel, iterations=2) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) # mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernel) mask = cv2.dilate(mask, kernel, iterations=1) res = cv2.bitwise_and(img, img, mask=mask) cnts, heir = cv2.findContours( mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:] center = None if len(cnts) > 0: c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # Added code recentPoints.append(points(x,y)) if len(recentPoints)>16: recentPoints.popleft() if len(recentPoints) == 16: min_X = min([p.x for p in recentPoints]) max_X = max([p.x for p in recentPoints]) min_Y = min([p.y for p in recentPoints]) max_Y = max([p.y for p in recentPoints]) if max_X-min_X <= sm_threshold or max_Y-min_Y<=sm_threshold: # EndPoint as average of recentPoints # endPoint_X = sum([p.x for p in recentPoints])/len(recentPoints) # endPoint_Y = sum([p.y for p in recentPoints])/ len(recentPoints) # endPoint = points(endPoint_X, endPoint_Y) endPoint = points(x,y) if abs(startPoint.x-endPoint.x)*0.625 > abs(startPoint.y- endPoint.y): if startPoint.x - endPoint.x > lg_threshold: print('right') keyboard.press(Key.right) keyboard.release(Key.right) startPoint = endPoint recentPoints = deque() elif startPoint.x - endPoint.x < -lg_threshold: print('left') keyboard.press(Key.left) keyboard.release(Key.left) startPoint = endPoint recentPoints = deque() else: if startPoint.y - endPoint.y > lg_threshold*0.625 : print('up') keyboard.press(Key.up) keyboard.release(Key.up) startPoint = endPoint recentPoints = deque() elif startPoint.y - endPoint.y < -lg_threshold*0.625: print('down') keyboard.press(Key.down) keyboard.release(Key.down) startPoint = endPoint recentPoints = deque() #print(x, y) # time.sleep(0.1) # counter += 1 # if counter == 32: # prev_x = x # prev_y = y # if counter > 32: # if abs(x - prev_x) > abs(y - prev_y): # if x - prev_x > 100: # print('left') # keyboard.press(Key.left) # keyboard.release(Key.left) # # time.sleep(0.7) # counter = 0 # elif x - prev_x < -100: # print('right') # keyboard.press(Key.right) # keyboard.release(Key.right) # counter = 0 # else: # if y - prev_y > 100: # print('down') # keyboard.press(Key.down) # keyboard.release(Key.down) # counter = 0 # # time.sleep(0.7) # elif y - prev_y < -100: # print('up') # keyboard.press(Key.up) # keyboard.release(Key.up) # counter = 0 # # time.sleep(0.7) if radius > 5: cv2.circle(img, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv2.circle(img, center, 5, (0, 0, 255), -1) pts.appendleft(center) for i in range(1, len(pts)): if pts[i - 1]is None or pts[i] is None: continue thick = int(np.sqrt(len(pts) / float(i + 1)) * 2.5) cv2.line(img, pts[i - 1], pts[i], (0, 0, 225), thick) cv2.imshow("Frame", img) # cv2.imshow("mask",mask) # cv2.imshow("res",res) k = cv2.waitKey(1) & 0xFF if k == ord("p"): break # cleanup the camera and close any open windows cap.release() cv2.destroyAllWindows()
[ "cv2.imshow", "numpy.array", "cv2.destroyAllWindows", "collections.deque", "cv2.erode", "cv2.line", "cv2.waitKey", "numpy.ones", "cv2.minEnclosingCircle", "keyboard.is_pressed", "cv2.morphologyEx", "cv2.circle", "cv2.cvtColor", "cv2.moments", "pynput.keyboard.Controller", "cv2.inRange", "cv2.bitwise_and", "cv2.VideoCapture", "cv2.dilate" ]
[((324, 336), 'pynput.keyboard.Controller', 'Controller', ([], {}), '()\n', (334, 336), False, 'from pynput.keyboard import Key, Controller, Listener\n'), ((344, 363), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (360, 363), False, 'import cv2\n'), ((371, 387), 'collections.deque', 'deque', ([], {'maxlen': '(64)'}), '(maxlen=64)\n', (376, 387), False, 'from collections import deque\n'), ((403, 426), 'numpy.array', 'np.array', (['[110, 50, 50]'], {}), '([110, 50, 50])\n', (411, 426), True, 'import numpy as np\n'), ((441, 466), 'numpy.array', 'np.array', (['[130, 255, 255]'], {}), '([130, 255, 255])\n', (449, 466), True, 'import numpy as np\n'), ((520, 527), 'collections.deque', 'deque', ([], {}), '()\n', (525, 527), False, 'from collections import deque\n'), ((5289, 5312), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5310, 5312), False, 'import cv2\n'), ((588, 606), 'keyboard.is_pressed', 'kb.is_pressed', (['"""q"""'], {}), "('q')\n", (601, 606), True, 'import keyboard as kb\n'), ((639, 657), 'keyboard.is_pressed', 'kb.is_pressed', (['"""w"""'], {}), "('w')\n", (652, 657), True, 'import keyboard as kb\n'), ((718, 754), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (730, 754), False, 'import cv2\n'), ((768, 793), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (775, 793), True, 'import numpy as np\n'), ((805, 847), 'cv2.inRange', 'cv2.inRange', (['hsv', 'Lower_green', 'Upper_green'], {}), '(hsv, Lower_green, Upper_green)\n', (816, 847), False, 'import cv2\n'), ((859, 896), 'cv2.erode', 'cv2.erode', (['mask', 'kernel'], {'iterations': '(2)'}), '(mask, kernel, iterations=2)\n', (868, 896), False, 'import cv2\n'), ((908, 954), 'cv2.morphologyEx', 'cv2.morphologyEx', (['mask', 'cv2.MORPH_OPEN', 'kernel'], {}), '(mask, cv2.MORPH_OPEN, kernel)\n', (924, 954), False, 'import cv2\n'), ((1023, 1061), 'cv2.dilate', 'cv2.dilate', (['mask', 'kernel'], {'iterations': '(1)'}), '(mask, kernel, iterations=1)\n', (1033, 1061), False, 'import cv2\n'), ((1072, 1108), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'img'], {'mask': 'mask'}), '(img, img, mask=mask)\n', (1087, 1108), False, 'import cv2\n'), ((5077, 5101), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'img'], {}), "('Frame', img)\n", (5087, 5101), False, 'import cv2\n'), ((1325, 1350), 'cv2.minEnclosingCircle', 'cv2.minEnclosingCircle', (['c'], {}), '(c)\n', (1347, 1350), False, 'import cv2\n'), ((1363, 1377), 'cv2.moments', 'cv2.moments', (['c'], {}), '(c)\n', (1374, 1377), False, 'import cv2\n'), ((5018, 5071), 'cv2.line', 'cv2.line', (['img', 'pts[i - 1]', 'pts[i]', '(0, 0, 225)', 'thick'], {}), '(img, pts[i - 1], pts[i], (0, 0, 225), thick)\n', (5026, 5071), False, 'import cv2\n'), ((5169, 5183), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5180, 5183), False, 'import cv2\n'), ((4776, 4819), 'cv2.circle', 'cv2.circle', (['img', 'center', '(5)', '(0, 0, 255)', '(-1)'], {}), '(img, center, 5, (0, 0, 255), -1)\n', (4786, 4819), False, 'import cv2\n'), ((2574, 2581), 'collections.deque', 'deque', ([], {}), '()\n', (2579, 2581), False, 'from collections import deque\n'), ((3145, 3152), 'collections.deque', 'deque', ([], {}), '()\n', (3150, 3152), False, 'from collections import deque\n'), ((2851, 2858), 'collections.deque', 'deque', ([], {}), '()\n', (2856, 2858), False, 'from collections import deque\n'), ((3461, 3468), 'collections.deque', 'deque', ([], {}), '()\n', (3466, 3468), False, 'from collections import deque\n')]
import os import shutil import tensorflow as tf from tensorflow import keras from logs import logDecorator as lD import jsonref import numpy as np import pickle import warnings from tqdm import tqdm from modules.data import getData config = jsonref.load(open('../config/config.json')) logBase = config['logging']['logBase'] + '.modules.model.getPretrained' ### turn off tensorflow info/warning/error or all python warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' warnings.filterwarnings("ignore") @lD.log(logBase + '.model') def modelImageNet(logger, modelName, weightsFile=None, input_shape=(224, 224, 3)): try: if weightsFile is not None: weights = weightsFile else: weights = 'imagenet' if modelName == 'Xception': base_model = keras.applications.xception.Xception(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'VGG16': base_model = keras.applications.vgg16.VGG16(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'VGG16_includeTop': base_model = keras.applications.vgg16.VGG16(input_shape=input_shape, include_top=True, weights=weights) elif modelName == 'VGG19': base_model = keras.applications.vgg19.VGG19(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'ResNet50': base_model = keras.applications.resnet50.ResNet50(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'InceptionV3': base_model = keras.applications.inception_v3.InceptionV3(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'InceptionResNetV2': base_model = keras.applications.inception_resnet_v2.InceptionResNetV2(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'MobileNet': base_model = keras.applications.mobilenet.MobileNet(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'DenseNet': base_model = keras.applications.densenet.DenseNet121(input_shape=input_shape, include_top=False, weights=weights) elif modelName == 'NASNet': base_model = keras.applications.nasnet.NASNetMobile(input_shape=input_shape, include_top=False, weights=weights) return base_model except Exception as e: logger.error('Unable to get model: {} \n{}'.format(modelName, str(e))) @lD.log(logBase + '.outputTensorBoard') def outputTensorBoard(logger, subfolder=None): try: tfboardFolder = '../notebooks/tensorlog/' if subfolder is not None: tfboardFolder = os.path.join(tfboardFolder, subfolder) if os.path.exists(tfboardFolder): shutil.rmtree(tfboardFolder) os.makedirs(tfboardFolder) with tf.Session() as sess: tfWriter = tf.summary.FileWriter(tfboardFolder, sess.graph) tfWriter.close() except Exception as e: logger.error('Unable to output tensorboard \n{}'.format(str(e))) @lD.log(logBase + '.visualise_graph') def visualise_graph(logger, modelName, subfolder=None): try: tf.keras.backend.clear_session() tfboardFolder = '../notebooks/tensorlog/' if subfolder is not None: tfboardFolder = os.path.join(tfboardFolder, subfolder) if os.path.exists(tfboardFolder): shutil.rmtree(tfboardFolder) os.makedirs(tfboardFolder) img = np.random.randint(0, 5, (1, 224, 224, 3)) modelDict = getModelFileDict() modelLoaded = modelImageNet(modelName, modelDict[modelName]) with tf.Session() as sess: tfWriter = tf.summary.FileWriter(tfboardFolder, sess.graph) tfWriter.close() except Exception as e: logger.error('Unable to write graph into tensorboard\n{}'.format(str(e))) @lD.log(logBase + '.visualise_layers') def visualise_layers(logger, sess, listOfTensorNodes, inputData): try: outputResults = sess.run( listOfTensorNodes, feed_dict={ 'input_1:0' : inputData }) for res, tf_node in zip(outputResults, listOfTensorNodes): print('-'*50) print('node: {}; shape: {}'.format(tf_node, res[0].shape)) getData.visualiseStackedArray(res[0], cmap=None) except Exception as e: logger.error('Unable to visualise layers \n{}'.format(str(e))) @lD.log(logBase + '.getModelFileDict') def getModelFileDict(logger): try: modelDict = { 'Xception' : '../models/xception_weights_tf_dim_ordering_tf_kernels_notop.h5', 'VGG16' : '../models/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5', 'VGG16_includeTop' : '../models/vgg16_weights_tf_dim_ordering_tf_kernels.h5', 'VGG19' : '../models/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5', 'InceptionV3' : '../models/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5', 'MobileNet' : '../models/mobilenet_1_0_224_tf_no_top.h5', 'DenseNet' : '../models/densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5', 'NASNet' : '../models/nasnet_mobile_no_top.h5', 'ResNet50' : '../models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', 'InceptionResNetV2' : '../models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5' } return modelDict except Exception as e: logger.error('Unable to get model file dictionary \n{}'.format(str(e))) @lD.log(logBase + '.checkReady') def checkReady(logger): try: modelString = ['Xception', 'VGG16', 'VGG19', 'InceptionV3', 'MobileNet', 'DenseNet', 'NASNet', 'ResNet50', 'InceptionResNetV2', 'VGG16_includeTop'] modelDict = getModelFileDict() for m in modelString: try: print('{} loading from {}...'.format(m, modelDict[m]), end='', flush=True) modelLoaded = modelImageNet(modelName=m, weightsFile=modelDict[m]) print('sucessfully! '.format(m), end='', flush=True) print('type: {}'.format(type(modelLoaded))) except Exception as e: print('failed. --> {}'.format(m, str(e))) except Exception as e: logger.error('Unable to check ready \n{}'.format(str(e))) @lD.log(logBase + '.main') def main(logger, resultsDict): try: checkReady() except Exception as e: logger.error('Unable to run main \n{}'.format(str(e))) if __name__ == '__main__': print('tf.__version__ :', tf.__version__) print('keras.__version__:', keras.__version__)
[ "logs.logDecorator.log", "modules.data.getData.visualiseStackedArray", "tensorflow.keras.applications.xception.Xception", "tensorflow.keras.applications.nasnet.NASNetMobile", "os.path.exists", "tensorflow.Session", "tensorflow.keras.applications.mobilenet.MobileNet", "tensorflow.keras.applications.vgg19.VGG19", "tensorflow.keras.applications.densenet.DenseNet121", "tensorflow.keras.applications.vgg16.VGG16", "tensorflow.summary.FileWriter", "tensorflow.keras.applications.inception_resnet_v2.InceptionResNetV2", "warnings.filterwarnings", "tensorflow.keras.applications.resnet50.ResNet50", "os.makedirs", "os.path.join", "tensorflow.keras.applications.inception_v3.InceptionV3", "numpy.random.randint", "shutil.rmtree", "tensorflow.keras.backend.clear_session" ]
[((479, 512), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (502, 512), False, 'import warnings\n'), ((515, 541), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.model')"], {}), "(logBase + '.model')\n", (521, 541), True, 'from logs import logDecorator as lD\n'), ((2539, 2577), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.outputTensorBoard')"], {}), "(logBase + '.outputTensorBoard')\n", (2545, 2577), True, 'from logs import logDecorator as lD\n'), ((3149, 3185), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.visualise_graph')"], {}), "(logBase + '.visualise_graph')\n", (3155, 3185), True, 'from logs import logDecorator as lD\n'), ((4000, 4037), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.visualise_layers')"], {}), "(logBase + '.visualise_layers')\n", (4006, 4037), True, 'from logs import logDecorator as lD\n'), ((4668, 4705), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.getModelFileDict')"], {}), "(logBase + '.getModelFileDict')\n", (4674, 4705), True, 'from logs import logDecorator as lD\n'), ((5867, 5898), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.checkReady')"], {}), "(logBase + '.checkReady')\n", (5873, 5898), True, 'from logs import logDecorator as lD\n'), ((6702, 6727), 'logs.logDecorator.log', 'lD.log', (["(logBase + '.main')"], {}), "(logBase + '.main')\n", (6708, 6727), True, 'from logs import logDecorator as lD\n'), ((2800, 2829), 'os.path.exists', 'os.path.exists', (['tfboardFolder'], {}), '(tfboardFolder)\n', (2814, 2829), False, 'import os\n'), ((2881, 2907), 'os.makedirs', 'os.makedirs', (['tfboardFolder'], {}), '(tfboardFolder)\n', (2892, 2907), False, 'import os\n'), ((3260, 3292), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (3290, 3292), True, 'import tensorflow as tf\n'), ((3458, 3487), 'os.path.exists', 'os.path.exists', (['tfboardFolder'], {}), '(tfboardFolder)\n', (3472, 3487), False, 'import os\n'), ((3539, 3565), 'os.makedirs', 'os.makedirs', (['tfboardFolder'], {}), '(tfboardFolder)\n', (3550, 3565), False, 'import os\n'), ((3591, 3632), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)', '(1, 224, 224, 3)'], {}), '(0, 5, (1, 224, 224, 3))\n', (3608, 3632), True, 'import numpy as np\n'), ((818, 920), 'tensorflow.keras.applications.xception.Xception', 'keras.applications.xception.Xception', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top=\n False, weights=weights)\n', (854, 920), False, 'from tensorflow import keras\n'), ((2749, 2787), 'os.path.join', 'os.path.join', (['tfboardFolder', 'subfolder'], {}), '(tfboardFolder, subfolder)\n', (2761, 2787), False, 'import os\n'), ((2843, 2871), 'shutil.rmtree', 'shutil.rmtree', (['tfboardFolder'], {}), '(tfboardFolder)\n', (2856, 2871), False, 'import shutil\n'), ((2922, 2934), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2932, 2934), True, 'import tensorflow as tf\n'), ((2967, 3015), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['tfboardFolder', 'sess.graph'], {}), '(tfboardFolder, sess.graph)\n', (2988, 3015), True, 'import tensorflow as tf\n'), ((3407, 3445), 'os.path.join', 'os.path.join', (['tfboardFolder', 'subfolder'], {}), '(tfboardFolder, subfolder)\n', (3419, 3445), False, 'import os\n'), ((3501, 3529), 'shutil.rmtree', 'shutil.rmtree', (['tfboardFolder'], {}), '(tfboardFolder)\n', (3514, 3529), False, 'import shutil\n'), ((3762, 3774), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3772, 3774), True, 'import tensorflow as tf\n'), ((3809, 3857), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['tfboardFolder', 'sess.graph'], {}), '(tfboardFolder, sess.graph)\n', (3830, 3857), True, 'import tensorflow as tf\n'), ((4517, 4565), 'modules.data.getData.visualiseStackedArray', 'getData.visualiseStackedArray', (['res[0]'], {'cmap': 'None'}), '(res[0], cmap=None)\n', (4546, 4565), False, 'from modules.data import getData\n'), ((977, 1072), 'tensorflow.keras.applications.vgg16.VGG16', 'keras.applications.vgg16.VGG16', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top=False,\n weights=weights)\n', (1007, 1072), False, 'from tensorflow import keras\n'), ((1141, 1235), 'tensorflow.keras.applications.vgg16.VGG16', 'keras.applications.vgg16.VGG16', ([], {'input_shape': 'input_shape', 'include_top': '(True)', 'weights': 'weights'}), '(input_shape=input_shape, include_top=True,\n weights=weights)\n', (1171, 1235), False, 'from tensorflow import keras\n'), ((1293, 1388), 'tensorflow.keras.applications.vgg19.VGG19', 'keras.applications.vgg19.VGG19', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top=False,\n weights=weights)\n', (1323, 1388), False, 'from tensorflow import keras\n'), ((1449, 1551), 'tensorflow.keras.applications.resnet50.ResNet50', 'keras.applications.resnet50.ResNet50', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top=\n False, weights=weights)\n', (1485, 1551), False, 'from tensorflow import keras\n'), ((1614, 1722), 'tensorflow.keras.applications.inception_v3.InceptionV3', 'keras.applications.inception_v3.InceptionV3', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape,\n include_top=False, weights=weights)\n', (1657, 1722), False, 'from tensorflow import keras\n'), ((1792, 1914), 'tensorflow.keras.applications.inception_resnet_v2.InceptionResNetV2', 'keras.applications.inception_resnet_v2.InceptionResNetV2', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=\n input_shape, include_top=False, weights=weights)\n', (1848, 1914), False, 'from tensorflow import keras\n'), ((1975, 2079), 'tensorflow.keras.applications.mobilenet.MobileNet', 'keras.applications.mobilenet.MobileNet', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top\n =False, weights=weights)\n', (2013, 2079), False, 'from tensorflow import keras\n'), ((2139, 2243), 'tensorflow.keras.applications.densenet.DenseNet121', 'keras.applications.densenet.DenseNet121', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape,\n include_top=False, weights=weights)\n', (2178, 2243), False, 'from tensorflow import keras\n'), ((2302, 2406), 'tensorflow.keras.applications.nasnet.NASNetMobile', 'keras.applications.nasnet.NASNetMobile', ([], {'input_shape': 'input_shape', 'include_top': '(False)', 'weights': 'weights'}), '(input_shape=input_shape, include_top\n =False, weights=weights)\n', (2340, 2406), False, 'from tensorflow import keras\n')]
import glob, os import numpy as np import tensorflow as tf import tensorflow.contrib.graph_editor as ge class Flownet2: def __init__(self, bilinear_warping_module): self.weights = dict() for key, shape in self.all_variables(): self.weights[key] = tf.get_variable(key, shape=shape) self.bilinear_warping_module = bilinear_warping_module def leaky_relu(self, x, s): assert s > 0 and s < 1, "Wrong s" return tf.maximum(x, s*x) def warp(self, x, flow): return self.bilinear_warping_module.bilinear_warping(x, tf.stack([flow[:,:,:,1], flow[:,:,:,0]], axis=3)) # flip true -> [:,:,:,0] y axis downwards # [:,:,:,1] x axis # as in matrix indexing # # false returns 0->x, 1->y def __call__(self, im0, im1, flip=True): f = self.get_blobs(im0, im1)['predict_flow_final'] if flip: f = tf.stack([f[:,:,:,1], f[:,:,:,0]], axis=3) return f def get_optimizer(self, flow, target, learning_rate=1e-4): #flow = self.__call__(im0, im1) loss = tf.reduce_sum(flow * target) # target holding the gradients! opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.95, beta2=0.99, epsilon=1e-8) opt = opt.minimize(loss, var_list= # [v for k,v in self.weights.iteritems() if (k.startswith('net3_') or k.startswith('netsd_') or k.startswith('fuse_'))]) [v for k,v in self.weights.iteritems() if ((k.startswith('net3_') or k.startswith('netsd_') or k.startswith('fuse_')) and not ('upsample' in k or 'deconv' in k))]) return opt, loss # If I run the network with large images (1024x2048) it crashes due to memory # constraints on a 12Gb titan X. # See https://github.com/tensorflow/tensorflow/issues/5816#issuecomment-268710077 # for a possible explanation. I fix it by adding run_after in the section with # the correlation layer so that 441 large tensors are not allocated at the same time def run_after(self, a_tensor, b_tensor): """Force a to run after b""" ge.reroute.add_control_inputs(a_tensor.op, [b_tensor.op]) # without epsilon I get nan-errors when I backpropagate def l2_norm(self, x): return tf.sqrt(tf.maximum(1e-5, tf.reduce_sum(x**2, axis=3, keep_dims=True))) def get_blobs(self, im0, im1): blobs = dict() batch_size = tf.to_int32(tf.shape(im0)[0]) width = tf.to_int32(tf.shape(im0)[2]) height = tf.to_int32(tf.shape(im0)[1]) TARGET_WIDTH = width TARGET_HEIGHT = height divisor = 64. ADAPTED_WIDTH = tf.to_int32(tf.ceil(tf.to_float(width)/divisor) * divisor) ADAPTED_HEIGHT = tf.to_int32(tf.ceil(tf.to_float(height)/divisor) * divisor) SCALE_WIDTH = tf.to_float(width) / tf.to_float(ADAPTED_WIDTH); SCALE_HEIGHT = tf.to_float(height) / tf.to_float(ADAPTED_HEIGHT); blobs['img0'] = im0 blobs['img1'] = im1 blobs['img0s'] = blobs['img0']*0.00392156862745098 blobs['img1s'] = blobs['img1']*0.00392156862745098 #mean = np.array([0.411451, 0.432060, 0.450141]) mean = np.array([0.37655231, 0.39534855, 0.40119368]) blobs['img0_nomean'] = blobs['img0s'] - mean blobs['img1_nomean'] = blobs['img1s'] - mean blobs['img0_nomean_resize'] = tf.image.resize_bilinear(blobs['img0_nomean'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=True) blobs['img1_nomean_resize'] = tf.image.resize_bilinear(blobs['img1_nomean'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=True) blobs['conv1a'] = tf.pad(blobs['img0_nomean_resize'], [[0,0], [3,3], [3,3], [0,0]]) blobs['conv1a'] = tf.nn.conv2d(blobs['conv1a'], self.weights['conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv1_b'] blobs['conv1a'] = self.leaky_relu(blobs['conv1a'], 0.1) blobs['conv1b'] = tf.pad(blobs['img1_nomean_resize'], [[0,0], [3,3], [3,3], [0,0]]) blobs['conv1b'] = tf.nn.conv2d(blobs['conv1b'], self.weights['conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv1_b'] blobs['conv1b'] = self.leaky_relu(blobs['conv1b'], 0.1) blobs['conv2a'] = tf.pad(blobs['conv1a'], [[0,0], [2,2], [2,2], [0,0]]) blobs['conv2a'] = tf.nn.conv2d(blobs['conv2a'], self.weights['conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv2_b'] blobs['conv2a'] = self.leaky_relu(blobs['conv2a'], 0.1) blobs['conv2b'] = tf.pad(blobs['conv1b'], [[0,0], [2,2], [2,2], [0,0]]) blobs['conv2b'] = tf.nn.conv2d(blobs['conv2b'], self.weights['conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv2_b'] blobs['conv2b'] = self.leaky_relu(blobs['conv2b'], 0.1) blobs['conv3a'] = tf.pad(blobs['conv2a'], [[0,0], [2,2], [2,2], [0,0]]) blobs['conv3a'] = tf.nn.conv2d(blobs['conv3a'], self.weights['conv3_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv3_b'] blobs['conv3a'] = self.leaky_relu(blobs['conv3a'], 0.1) blobs['conv3b'] = tf.pad(blobs['conv2b'], [[0,0], [2,2], [2,2], [0,0]]) blobs['conv3b'] = tf.nn.conv2d(blobs['conv3b'], self.weights['conv3_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv3_b'] blobs['conv3b'] = self.leaky_relu(blobs['conv3b'], 0.1) # this might be considered a bit hacky tmp = [] x1_l = [] x2_l = [] for di in range(-20, 21, 2): for dj in range(-20, 21, 2): x1 = tf.pad(blobs['conv3a'], [[0,0], [20,20], [20,20], [0,0]]) x2 = tf.pad(blobs['conv3b'], [[0,0], [20-di,20+di], [20-dj,20+dj], [0,0]]) x1_l.append(x1) x2_l.append(x2) c = tf.nn.conv2d(x1*x2, tf.ones([1, 1, 256, 1])/256., strides=[1,1,1,1], padding='VALID') tmp.append(c[:,20:-20,20:-20,:]) for i in range(len(tmp)-1): #self.run_after(tmp[i], tmp[i+1]) self.run_after(x1_l[i], tmp[i+1]) self.run_after(x2_l[i], tmp[i+1]) blobs['corr'] = tf.concat(tmp, axis=3) blobs['corr'] = self.leaky_relu(blobs['corr'], 0.1) blobs['conv_redir'] = tf.nn.conv2d(blobs['conv3a'], self.weights['conv_redir_w'], strides=[1,1,1,1], padding="VALID") + self.weights['conv_redir_b'] blobs['conv_redir'] = self.leaky_relu(blobs['conv_redir'], 0.1) blobs['blob16'] = tf.concat([blobs['conv_redir'], blobs['corr']], axis=3) blobs['conv3_1'] = tf.nn.conv2d(blobs['blob16'], self.weights['conv3_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['conv3_1_b'] blobs['conv3_1'] = self.leaky_relu(blobs['conv3_1'], 0.1) blobs['conv4'] = tf.pad(blobs['conv3_1'], [[0,0], [1,1], [1,1], [0,0]]) blobs['conv4'] = tf.nn.conv2d(blobs['conv4'], self.weights['conv4_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv4_b'] blobs['conv4'] = self.leaky_relu(blobs['conv4'], 0.1) blobs['conv4_1'] = tf.nn.conv2d(blobs['conv4'], self.weights['conv4_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['conv4_1_b'] blobs['conv4_1'] = self.leaky_relu(blobs['conv4_1'], 0.1) blobs['conv5'] = tf.pad(blobs['conv4_1'], [[0,0], [1,1], [1,1], [0,0]]) blobs['conv5'] = tf.nn.conv2d(blobs['conv5'], self.weights['conv5_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv5_b'] blobs['conv5'] = self.leaky_relu(blobs['conv5'], 0.1) blobs['conv5_1'] = tf.nn.conv2d(blobs['conv5'], self.weights['conv5_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['conv5_1_b'] blobs['conv5_1'] = self.leaky_relu(blobs['conv5_1'], 0.1) blobs['conv6'] = tf.pad(blobs['conv5_1'], [[0,0], [1,1], [1,1], [0,0]]) blobs['conv6'] = tf.nn.conv2d(blobs['conv6'], self.weights['conv6_w'], strides=[1,2,2,1], padding="VALID") + self.weights['conv6_b'] blobs['conv6'] = self.leaky_relu(blobs['conv6'], 0.1) blobs['conv6_1'] = tf.nn.conv2d(blobs['conv6'], self.weights['conv6_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['conv6_1_b'] blobs['conv6_1'] = self.leaky_relu(blobs['conv6_1'], 0.1) blobs['predict_flow6'] = tf.nn.conv2d(blobs['conv6_1'], self.weights['Convolution1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['Convolution1_b'] blobs['deconv5'] = tf.nn.conv2d_transpose(blobs['conv6_1'], self.weights['deconv5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 512], strides=[1,2,2,1]) + self.weights['deconv5_b'] blobs['deconv5'] = self.leaky_relu(blobs['deconv5'], 0.1) blobs['upsampled_flow6_to_5'] = tf.nn.conv2d_transpose(blobs['predict_flow6'], self.weights['upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 2], strides=[1,2,2,1]) + self.weights['upsample_flow6to5_b'] blobs['concat5'] = tf.concat([blobs['conv5_1'], blobs['deconv5'], blobs['upsampled_flow6_to_5']], axis=3) blobs['predict_flow5'] = tf.pad(blobs['concat5'], [[0,0], [1,1], [1,1], [0,0]]) blobs['predict_flow5'] = tf.nn.conv2d(blobs['predict_flow5'], self.weights['Convolution2_w'], strides=[1,1,1,1], padding="VALID") + self.weights['Convolution2_b'] blobs['deconv4'] = tf.nn.conv2d_transpose(blobs['concat5'], self.weights['deconv4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 256], strides=[1,2,2,1]) + self.weights['deconv4_b'] blobs['deconv4'] = self.leaky_relu(blobs['deconv4'], 0.1) blobs['upsampled_flow5_to_4'] = tf.nn.conv2d_transpose(blobs['predict_flow5'], self.weights['upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 2], strides=[1,2,2,1]) + self.weights['upsample_flow5to4_b'] blobs['concat4'] = tf.concat([blobs['conv4_1'], blobs['deconv4'], blobs['upsampled_flow5_to_4']], axis=3) blobs['predict_flow4'] = tf.nn.conv2d(blobs['concat4'], self.weights['Convolution3_w'], strides=[1,1,1,1], padding="SAME") + self.weights['Convolution3_b'] blobs['deconv3'] = tf.nn.conv2d_transpose(blobs['concat4'], self.weights['deconv3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 128], strides=[1,2,2,1]) + self.weights['deconv3_b'] blobs['deconv3'] = self.leaky_relu(blobs['deconv3'], 0.1) blobs['upsampled_flow4_to_3'] = tf.nn.conv2d_transpose(blobs['predict_flow4'], self.weights['upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 2], strides=[1,2,2,1]) + self.weights['upsample_flow4to3_b'] blobs['concat3'] = tf.concat([blobs['conv3_1'], blobs['deconv3'], blobs['upsampled_flow4_to_3']], axis=3) blobs['predict_flow3'] = tf.nn.conv2d(blobs['concat3'], self.weights['Convolution4_w'], strides=[1,1,1,1], padding="SAME") + self.weights['Convolution4_b'] blobs['deconv2'] = tf.nn.conv2d_transpose(blobs['concat3'], self.weights['deconv2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 64], strides=[1,2,2,1]) + self.weights['deconv2_b'] blobs['deconv2'] = self.leaky_relu(blobs['deconv2'], 0.1) blobs['upsampled_flow3_to_2'] = tf.nn.conv2d_transpose(blobs['predict_flow3'], self.weights['upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 2], strides=[1,2,2,1]) + self.weights['upsample_flow3to2_b'] blobs['concat2'] = tf.concat([blobs['conv2a'], blobs['deconv2'], blobs['upsampled_flow3_to_2']], axis=3) blobs['predict_flow2'] = tf.nn.conv2d(blobs['concat2'], self.weights['Convolution5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['Convolution5_b'] blobs['blob41'] = blobs['predict_flow2'] * 20. blobs['blob42'] = tf.image.resize_bilinear(blobs['blob41'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=True) blobs['blob43'] = self.warp(blobs['img1_nomean_resize'], blobs['blob42']) blobs['blob44'] = blobs['img0_nomean_resize'] - blobs['blob43'] #blobs['blob45'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob44']**2, axis=3, keep_dims=True)) blobs['blob45'] = self.l2_norm(blobs['blob44']) blobs['blob46'] = 0.05*blobs['blob42'] blobs['blob47'] = tf.concat([blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs['blob43'], blobs['blob46'], blobs['blob45']], axis=3) #################################################################################### #################################################################################### #################################################################################### ###################### END OF THE FIRST BRANCH ##################################### #################################################################################### #################################################################################### #################################################################################### blobs['blob48'] = tf.pad(blobs['blob47'], [[0,0], [3,3], [3,3], [0,0]]) blobs['blob48'] = tf.nn.conv2d(blobs['blob48'], self.weights['net2_conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv1_b'] blobs['blob48'] = self.leaky_relu(blobs['blob48'], 0.1) blobs['blob49'] = tf.pad(blobs['blob48'], [[0,0], [2,2], [2, 2], [0,0]]) blobs['blob49'] = tf.nn.conv2d(blobs['blob49'], self.weights['net2_conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv2_b'] blobs['blob49'] = self.leaky_relu(blobs['blob49'], 0.1) blobs['blob50'] = tf.pad(blobs['blob49'], [[0,0], [2,2], [2,2], [0,0]]) blobs['blob50'] = tf.nn.conv2d(blobs['blob50'], self.weights['net2_conv3_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv3_b'] blobs['blob50'] = self.leaky_relu(blobs['blob50'], 0.1) blobs['blob51'] = tf.nn.conv2d(blobs['blob50'], self.weights['net2_conv3_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_conv3_1_b'] blobs['blob51'] = self.leaky_relu(blobs['blob51'], 0.1) blobs['blob52'] = tf.pad(blobs['blob51'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob52'] = tf.nn.conv2d(blobs['blob52'], self.weights['net2_conv4_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv4_b'] blobs['blob52'] = self.leaky_relu(blobs['blob52'], 0.1) blobs['blob53'] = tf.nn.conv2d(blobs['blob52'], self.weights['net2_conv4_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_conv4_1_b'] blobs['blob53'] = self.leaky_relu(blobs['blob53'], 0.1) blobs['blob54'] = tf.pad(blobs['blob53'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob54'] = tf.nn.conv2d(blobs['blob54'], self.weights['net2_conv5_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv5_b'] blobs['blob54'] = self.leaky_relu(blobs['blob54'], 0.1) blobs['blob55'] = tf.nn.conv2d(blobs['blob54'], self.weights['net2_conv5_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_conv5_1_b'] blobs['blob55'] = self.leaky_relu(blobs['blob55'], 0.1) blobs['blob56'] = tf.pad(blobs['blob55'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob56'] = tf.nn.conv2d(blobs['blob56'], self.weights['net2_conv6_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net2_conv6_b'] blobs['blob56'] = self.leaky_relu(blobs['blob56'], 0.1) blobs['blob57'] = tf.nn.conv2d(blobs['blob56'], self.weights['net2_conv6_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_conv6_1_b'] blobs['blob57'] = self.leaky_relu(blobs['blob57'], 0.1) blobs['blob58'] = tf.nn.conv2d(blobs['blob57'], self.weights['net2_predict_conv6_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_predict_conv6_b'] blobs['blob59'] = tf.nn.conv2d_transpose(blobs['blob57'], self.weights['net2_deconv5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 512], strides=[1,2,2,1]) + self.weights['net2_deconv5_b'] blobs['blob59'] = self.leaky_relu(blobs['blob59'], 0.1) blobs['blob60'] = tf.nn.conv2d_transpose(blobs['predict_flow6'], self.weights['net2_net2_upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 2], strides=[1,2,2,1]) + self.weights['net2_net2_upsample_flow6to5_b'] blobs['blob61'] = tf.concat([blobs['blob55'], blobs['blob59'], blobs['blob60']], axis=3) blobs['blob62'] = tf.nn.conv2d(blobs['blob61'], self.weights['net2_predict_conv5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_predict_conv5_b'] blobs['blob63'] = tf.nn.conv2d_transpose(blobs['blob61'], self.weights['net2_deconv4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 256], strides=[1,2,2,1]) + self.weights['net2_deconv4_b'] blobs['blob63'] = self.leaky_relu(blobs['blob63'], 0.1) blobs['blob64'] = tf.nn.conv2d_transpose(blobs['blob62'], self.weights['net2_net2_upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 2], strides=[1,2,2,1]) + self.weights['net2_net2_upsample_flow5to4_b'] blobs['blob65'] = tf.concat([blobs['blob53'], blobs['blob63'], blobs['blob64']], axis=3) blobs['blob66'] = tf.nn.conv2d(blobs['blob65'], self.weights['net2_predict_conv4_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_predict_conv4_b'] blobs['blob67'] = tf.nn.conv2d_transpose(blobs['blob65'], self.weights['net2_deconv3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 128], strides=[1,2,2,1]) + self.weights['net2_deconv3_b'] blobs['blob67'] = self.leaky_relu(blobs['blob67'], 0.1) blobs['blob68'] = tf.nn.conv2d_transpose(blobs['blob66'], self.weights['net2_net2_upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 2], strides=[1,2,2,1]) + self.weights['net2_net2_upsample_flow4to3_b'] blobs['blob69'] = tf.concat([blobs['blob51'], blobs['blob67'], blobs['blob68']], axis=3) blobs['blob70'] = tf.nn.conv2d(blobs['blob69'], self.weights['net2_predict_conv3_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_predict_conv3_b'] blobs['blob71'] = tf.nn.conv2d_transpose(blobs['blob69'], self.weights['net2_deconv2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 64], strides=[1,2,2,1]) + self.weights['net2_deconv2_b'] blobs['blob71'] = self.leaky_relu(blobs['blob71'], 0.1) blobs['blob72'] = tf.nn.conv2d_transpose(blobs['blob70'], self.weights['net2_net2_upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 2], strides=[1,2,2,1]) + self.weights['net2_net2_upsample_flow3to2_b'] blobs['blob73'] = tf.concat([blobs['blob49'], blobs['blob71'], blobs['blob72']], axis=3) blobs['blob74'] = tf.nn.conv2d(blobs['blob73'], self.weights['net2_predict_conv2_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net2_predict_conv2_b'] blobs['blob75'] = blobs['blob74'] * 20. blobs['blob76'] = tf.image.resize_bilinear(blobs['blob75'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=True) blobs['blob77'] = self.warp(blobs['img1_nomean_resize'], blobs['blob76']) blobs['blob78'] = blobs['img0_nomean_resize'] - blobs['blob77'] #blobs['blob79'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob78']**2, axis=3, keep_dims=True)) blobs['blob79'] = self.l2_norm(blobs['blob78']) blobs['blob80'] = 0.05*blobs['blob76'] blobs['blob81'] = tf.concat([blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs['blob77'], blobs['blob80'], blobs['blob79']], axis=3) #################################################################################### #################################################################################### #################################################################################### ###################### END OF THE SECOND BRANCH #################################### #################################################################################### #################################################################################### #################################################################################### blobs['blob82'] = tf.pad(blobs['blob81'], [[0,0], [3,3], [3,3], [0,0]]) blobs['blob82'] = tf.nn.conv2d(blobs['blob82'], self.weights['net3_conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv1_b'] blobs['blob82'] = self.leaky_relu(blobs['blob82'], 0.1) blobs['blob83'] = tf.pad(blobs['blob82'], [[0,0], [2,2], [2, 2], [0,0]]) blobs['blob83'] = tf.nn.conv2d(blobs['blob83'], self.weights['net3_conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv2_b'] blobs['blob83'] = self.leaky_relu(blobs['blob83'], 0.1) blobs['blob84'] = tf.pad(blobs['blob83'], [[0,0], [2,2], [2,2], [0,0]]) blobs['blob84'] = tf.nn.conv2d(blobs['blob84'], self.weights['net3_conv3_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv3_b'] blobs['blob84'] = self.leaky_relu(blobs['blob84'], 0.1) blobs['blob85'] = tf.nn.conv2d(blobs['blob84'], self.weights['net3_conv3_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_conv3_1_b'] blobs['blob85'] = self.leaky_relu(blobs['blob85'], 0.1) blobs['blob86'] = tf.pad(blobs['blob85'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob86'] = tf.nn.conv2d(blobs['blob86'], self.weights['net3_conv4_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv4_b'] blobs['blob86'] = self.leaky_relu(blobs['blob86'], 0.1) blobs['blob87'] = tf.nn.conv2d(blobs['blob86'], self.weights['net3_conv4_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_conv4_1_b'] blobs['blob87'] = self.leaky_relu(blobs['blob87'], 0.1) blobs['blob88'] = tf.pad(blobs['blob87'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob88'] = tf.nn.conv2d(blobs['blob88'], self.weights['net3_conv5_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv5_b'] blobs['blob88'] = self.leaky_relu(blobs['blob88'], 0.1) blobs['blob89'] = tf.nn.conv2d(blobs['blob88'], self.weights['net3_conv5_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_conv5_1_b'] blobs['blob89'] = self.leaky_relu(blobs['blob89'], 0.1) blobs['blob90'] = tf.pad(blobs['blob89'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob90'] = tf.nn.conv2d(blobs['blob90'], self.weights['net3_conv6_w'], strides=[1,2,2,1], padding="VALID") + self.weights['net3_conv6_b'] blobs['blob90'] = self.leaky_relu(blobs['blob90'], 0.1) blobs['blob91'] = tf.nn.conv2d(blobs['blob90'], self.weights['net3_conv6_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_conv6_1_b'] blobs['blob91'] = self.leaky_relu(blobs['blob91'], 0.1) blobs['blob92'] = tf.nn.conv2d(blobs['blob91'], self.weights['net3_predict_conv6_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_predict_conv6_b'] blobs['blob93'] = tf.nn.conv2d_transpose(blobs['blob91'], self.weights['net3_deconv5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 512], strides=[1,2,2,1]) + self.weights['net3_deconv5_b'] blobs['blob93'] = self.leaky_relu(blobs['blob93'], 0.1) blobs['blob94'] = tf.nn.conv2d_transpose(blobs['blob92'], self.weights['net3_net3_upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 2], strides=[1,2,2,1]) + self.weights['net3_net3_upsample_flow6to5_b'] blobs['blob95'] = tf.concat([blobs['blob89'], blobs['blob93'], blobs['blob94']], axis=3) blobs['blob96'] = tf.nn.conv2d(blobs['blob95'], self.weights['net3_predict_conv5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_predict_conv5_b'] blobs['blob97'] = tf.nn.conv2d_transpose(blobs['blob95'], self.weights['net3_deconv4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 256], strides=[1,2,2,1]) + self.weights['net3_deconv4_b'] blobs['blob97'] = self.leaky_relu(blobs['blob97'], 0.1) blobs['blob98'] = tf.nn.conv2d_transpose(blobs['blob96'], self.weights['net3_net3_upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 2], strides=[1,2,2,1]) + self.weights['net3_net3_upsample_flow5to4_b'] blobs['blob99'] = tf.concat([blobs['blob87'], blobs['blob97'], blobs['blob98']], axis=3) blobs['blob100'] = tf.nn.conv2d(blobs['blob99'], self.weights['net3_predict_conv4_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_predict_conv4_b'] blobs['blob101'] = tf.nn.conv2d_transpose(blobs['blob99'], self.weights['net3_deconv3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 128], strides=[1,2,2,1]) + self.weights['net3_deconv3_b'] blobs['blob101'] = self.leaky_relu(blobs['blob101'], 0.1) blobs['blob102'] = tf.nn.conv2d_transpose(blobs['blob100'], self.weights['net3_net3_upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 2], strides=[1,2,2,1]) + self.weights['net3_net3_upsample_flow4to3_b'] blobs['blob103'] = tf.concat([blobs['blob85'], blobs['blob101'], blobs['blob102']], axis=3) blobs['blob104'] = tf.nn.conv2d(blobs['blob103'], self.weights['net3_predict_conv3_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_predict_conv3_b'] blobs['blob105'] = tf.nn.conv2d_transpose(blobs['blob103'], self.weights['net3_deconv2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 64], strides=[1,2,2,1]) + self.weights['net3_deconv2_b'] blobs['blob105'] = self.leaky_relu(blobs['blob105'], 0.1) blobs['blob106'] = tf.nn.conv2d_transpose(blobs['blob104'], self.weights['net3_net3_upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 2], strides=[1,2,2,1]) + self.weights['net3_net3_upsample_flow3to2_b'] blobs['blob107'] = tf.concat([blobs['blob83'], blobs['blob105'], blobs['blob106']], axis=3) blobs['blob108'] = tf.nn.conv2d(blobs['blob107'], self.weights['net3_predict_conv2_w'], strides=[1,1,1,1], padding="SAME") + self.weights['net3_predict_conv2_b'] blobs['blob109'] = blobs['blob108'] * 20. #################################################################################### #################################################################################### #################################################################################### ###################### END OF THE THIRD BRANCH #################################### #################################################################################### #################################################################################### #################################################################################### blobs['blob110'] = tf.concat([blobs['img0_nomean_resize'], blobs['img1_nomean_resize']], axis=3) #self.run_after(blobs['blob110'], blobs['blob109']) blobs['blob111'] = tf.nn.conv2d(blobs['blob110'], self.weights['netsd_conv0_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv0_b'] blobs['blob111'] = self.leaky_relu(blobs['blob111'], 0.1) blobs['blob112'] = tf.pad(blobs['blob111'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob112'] = tf.nn.conv2d(blobs['blob112'], self.weights['netsd_conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv1_b'] blobs['blob112'] = self.leaky_relu(blobs['blob112'], 0.1) blobs['blob113'] = tf.nn.conv2d(blobs['blob112'], self.weights['netsd_conv1_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv1_1_b'] blobs['blob113'] = self.leaky_relu(blobs['blob113'], 0.1) blobs['blob114'] = tf.pad(blobs['blob113'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob114'] = tf.nn.conv2d(blobs['blob114'], self.weights['netsd_conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv2_b'] blobs['blob114'] = self.leaky_relu(blobs['blob114'], 0.1) blobs['blob115'] = tf.nn.conv2d(blobs['blob114'], self.weights['netsd_conv2_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv2_1_b'] blobs['blob115'] = self.leaky_relu(blobs['blob115'], 0.1) blobs['blob116'] = tf.pad(blobs['blob115'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob116'] = tf.nn.conv2d(blobs['blob116'], self.weights['netsd_conv3_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv3_b'] blobs['blob116'] = self.leaky_relu(blobs['blob116'], 0.1) blobs['blob117'] = tf.nn.conv2d(blobs['blob116'], self.weights['netsd_conv3_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv3_1_b'] blobs['blob117'] = self.leaky_relu(blobs['blob117'], 0.1) blobs['blob118'] = tf.pad(blobs['blob117'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob118'] = tf.nn.conv2d(blobs['blob118'], self.weights['netsd_conv4_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv4_b'] blobs['blob118'] = self.leaky_relu(blobs['blob118'], 0.1) blobs['blob119'] = tf.nn.conv2d(blobs['blob118'], self.weights['netsd_conv4_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv4_1_b'] blobs['blob119'] = self.leaky_relu(blobs['blob119'], 0.1) blobs['blob120'] = tf.pad(blobs['blob119'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob120'] = tf.nn.conv2d(blobs['blob120'], self.weights['netsd_conv5_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv5_b'] blobs['blob120'] = self.leaky_relu(blobs['blob120'], 0.1) blobs['blob121'] = tf.nn.conv2d(blobs['blob120'], self.weights['netsd_conv5_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv5_1_b'] blobs['blob121'] = self.leaky_relu(blobs['blob121'], 0.1) blobs['blob122'] = tf.pad(blobs['blob121'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob122'] = tf.nn.conv2d(blobs['blob122'], self.weights['netsd_conv6_w'], strides=[1,2,2,1], padding="VALID") + self.weights['netsd_conv6_b'] blobs['blob122'] = self.leaky_relu(blobs['blob122'], 0.1) blobs['blob123'] = tf.nn.conv2d(blobs['blob122'], self.weights['netsd_conv6_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_conv6_1_b'] blobs['blob123'] = self.leaky_relu(blobs['blob123'], 0.1) blobs['blob124'] = tf.nn.conv2d(blobs['blob123'], self.weights['netsd_Convolution1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_Convolution1_b'] blobs['blob125'] = tf.nn.conv2d_transpose(blobs['blob123'], self.weights['netsd_deconv5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 512], strides=[1,2,2,1]) + self.weights['netsd_deconv5_b'] blobs['blob125'] = self.leaky_relu(blobs['blob125'], 0.1) blobs['blob126'] = tf.nn.conv2d_transpose(blobs['blob124'], self.weights['netsd_upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT/32, ADAPTED_WIDTH/32, 2], strides=[1,2,2,1]) + self.weights['netsd_upsample_flow6to5_b'] blobs['blob127'] = tf.concat([blobs['blob121'], blobs['blob125'], blobs['blob126']], axis=3) blobs['blob128'] = tf.nn.conv2d(blobs['blob127'], self.weights['netsd_interconv5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_interconv5_b'] blobs['blob129'] = tf.nn.conv2d(blobs['blob128'], self.weights['netsd_Convolution2_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_Convolution2_b'] blobs['blob130'] = tf.nn.conv2d_transpose(blobs['blob127'], self.weights['netsd_deconv4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 256], strides=[1,2,2,1]) + self.weights['netsd_deconv4_b'] blobs['blob130'] = self.leaky_relu(blobs['blob130'], 0.1) blobs['blob131'] = tf.nn.conv2d_transpose(blobs['blob129'], self.weights['netsd_upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT/16, ADAPTED_WIDTH/16, 2], strides=[1,2,2,1]) + self.weights['netsd_upsample_flow5to4_b'] blobs['blob132'] = tf.concat([blobs['blob119'], blobs['blob130'], blobs['blob131']], axis=3) blobs['blob133'] = tf.nn.conv2d(blobs['blob132'], self.weights['netsd_interconv4_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_interconv4_b'] blobs['blob134'] = tf.nn.conv2d(blobs['blob133'], self.weights['netsd_Convolution3_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_Convolution3_b'] blobs['blob135'] = tf.nn.conv2d_transpose(blobs['blob132'], self.weights['netsd_deconv3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 128], strides=[1,2,2,1]) + self.weights['netsd_deconv3_b'] blobs['blob135'] = self.leaky_relu(blobs['blob135'], 0.1) blobs['blob136'] = tf.nn.conv2d_transpose(blobs['blob134'], self.weights['netsd_upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT/8, ADAPTED_WIDTH/8, 2], strides=[1,2,2,1]) + self.weights['netsd_upsample_flow4to3_b'] blobs['blob137'] = tf.concat([blobs['blob117'], blobs['blob135'], blobs['blob136']], axis=3) blobs['blob138'] = tf.nn.conv2d(blobs['blob137'], self.weights['netsd_interconv3_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_interconv3_b'] blobs['blob139'] = tf.nn.conv2d(blobs['blob138'], self.weights['netsd_Convolution4_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_Convolution4_b'] blobs['blob140'] = tf.nn.conv2d_transpose(blobs['blob137'], self.weights['netsd_deconv2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 64], strides=[1,2,2,1]) + self.weights['netsd_deconv2_b'] blobs['blob140'] = self.leaky_relu(blobs['blob140'], 0.1) blobs['blob141'] = tf.nn.conv2d_transpose(blobs['blob139'], self.weights['netsd_upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT/4, ADAPTED_WIDTH/4, 2], strides=[1,2,2,1]) + self.weights['netsd_upsample_flow3to2_b'] blobs['blob142'] = tf.concat([blobs['blob115'], blobs['blob140'], blobs['blob141']], axis=3) blobs['blob143'] = tf.nn.conv2d(blobs['blob142'], self.weights['netsd_interconv2_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_interconv2_b'] blobs['blob144'] = tf.nn.conv2d(blobs['blob143'], self.weights['netsd_Convolution5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['netsd_Convolution5_b'] blobs['blob145'] = 0.05*blobs['blob144'] blobs['blob146'] = tf.image.resize_nearest_neighbor(blobs['blob145'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=False) blobs['blob147'] = tf.image.resize_nearest_neighbor(blobs['blob109'], size=[ADAPTED_HEIGHT, ADAPTED_WIDTH], align_corners=False) #blobs['blob148'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob146']**2, axis=3, keep_dims=True)) blobs['blob148'] = self.l2_norm(blobs['blob146']) #blobs['blob149'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob147']**2, axis=3, keep_dims=True)) blobs['blob149'] = self.l2_norm(blobs['blob147']) blobs['blob150'] = self.warp(blobs['img1_nomean_resize'], blobs['blob146']) blobs['blob151'] = blobs['img0_nomean_resize'] - blobs['blob150'] #blobs['blob152'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob151']**2, axis=3, keep_dims=True)) blobs['blob152'] = self.l2_norm(blobs['blob151']) blobs['blob153'] = self.warp(blobs['img1_nomean_resize'], blobs['blob147']) blobs['blob154'] = blobs['img0_nomean_resize'] - blobs['blob153'] #blobs['blob155'] = tf.sqrt(1e-8+tf.reduce_sum(blobs['blob154']**2, axis=3, keep_dims=True)) blobs['blob155'] = self.l2_norm(blobs['blob154']) blobs['blob156'] = tf.concat([blobs['img0_nomean_resize'], blobs['blob146'], blobs['blob147'], blobs['blob148'], blobs['blob149'], blobs['blob152'], blobs['blob155']], axis=3) blobs['blob157'] = tf.nn.conv2d(blobs['blob156'], self.weights['fuse_conv0_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse_conv0_b'] blobs['blob157'] = self.leaky_relu(blobs['blob157'], 0.1) blobs['blob158'] = tf.pad(blobs['blob157'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob158'] = tf.nn.conv2d(blobs['blob158'], self.weights['fuse_conv1_w'], strides=[1,2,2,1], padding="VALID") + self.weights['fuse_conv1_b'] blobs['blob158'] = self.leaky_relu(blobs['blob158'], 0.1) blobs['blob159'] = tf.nn.conv2d(blobs['blob158'], self.weights['fuse_conv1_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse_conv1_1_b'] blobs['blob159'] = self.leaky_relu(blobs['blob159'], 0.1) blobs['blob160'] = tf.pad(blobs['blob159'], [[0,0], [1,1], [1,1], [0,0]]) blobs['blob160'] = tf.nn.conv2d(blobs['blob160'], self.weights['fuse_conv2_w'], strides=[1,2,2,1], padding="VALID") + self.weights['fuse_conv2_b'] blobs['blob160'] = self.leaky_relu(blobs['blob160'], 0.1) blobs['blob161'] = tf.nn.conv2d(blobs['blob160'], self.weights['fuse_conv2_1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse_conv2_1_b'] blobs['blob161'] = self.leaky_relu(blobs['blob161'], 0.1) blobs['blob162'] = tf.nn.conv2d(blobs['blob161'], self.weights['fuse__Convolution5_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse__Convolution5_b'] blobs['blob163'] = tf.nn.conv2d_transpose(blobs['blob161'], self.weights['fuse_deconv1_w'], output_shape=[batch_size, ADAPTED_HEIGHT/2, ADAPTED_WIDTH/2, 32], strides=[1,2,2,1]) + self.weights['fuse_deconv1_b'] blobs['blob163'] = self.leaky_relu(blobs['blob163'], 0.1) blobs['blob164'] = tf.nn.conv2d_transpose(blobs['blob162'], self.weights['fuse_upsample_flow2to1_w'], output_shape=[batch_size, ADAPTED_HEIGHT/2, ADAPTED_WIDTH/2, 2], strides=[1,2,2,1]) + self.weights['fuse_upsample_flow2to1_b'] blobs['blob165'] = tf.concat([blobs['blob159'], blobs['blob163'], blobs['blob164']], axis=3) blobs['blob166'] = tf.nn.conv2d(blobs['blob165'], self.weights['fuse_interconv1_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse_interconv1_b'] blobs['blob167'] = tf.nn.conv2d(blobs['blob166'], self.weights['fuse__Convolution6_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse__Convolution6_b'] blobs['blob168'] = tf.nn.conv2d_transpose(blobs['blob165'], self.weights['fuse_deconv0_w'], output_shape=[batch_size, ADAPTED_HEIGHT/1, ADAPTED_WIDTH/1, 16], strides=[1,2,2,1]) + self.weights['fuse_deconv0_b'] blobs['blob168'] = self.leaky_relu(blobs['blob168'], 0.1) blobs['blob169'] = tf.nn.conv2d_transpose(blobs['blob167'], self.weights['fuse_upsample_flow1to0_w'], output_shape=[batch_size, ADAPTED_HEIGHT, ADAPTED_WIDTH, 2], strides=[1,2,2,1]) + self.weights['fuse_upsample_flow1to0_b'] blobs['blob170'] = tf.concat([blobs['blob157'], blobs['blob168'], blobs['blob169']], axis=3) blobs['blob171'] = tf.nn.conv2d(blobs['blob170'], self.weights['fuse_interconv0_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse_interconv0_b'] blobs['blob172'] = tf.nn.conv2d(blobs['blob171'], self.weights['fuse__Convolution7_w'], strides=[1,1,1,1], padding="SAME") + self.weights['fuse__Convolution7_b'] blobs['predict_flow_resize'] = tf.image.resize_bilinear(blobs['blob172'], size=[TARGET_HEIGHT, TARGET_WIDTH], align_corners=True) scale = tf.stack([SCALE_WIDTH, SCALE_HEIGHT]) scale = tf.reshape(scale, [1,1,1,2]) blobs['predict_flow_final'] = scale*blobs['predict_flow_resize'] self.blobs = blobs return blobs def all_variables(self): return [('netsd_deconv5_w', (4, 4, 512, 1024)), ('netsd_conv1_b', (64,)), ('netsd_upsample_flow5to4_w', (4, 4, 2, 2)), ('conv2_b', (128,)), ('fuse__Convolution5_w', (3, 3, 128, 2)), ('netsd_conv4_1_w', (3, 3, 512, 512)), ('netsd_interconv3_w', (3, 3, 386, 128)), ('netsd_deconv4_w', (4, 4, 256, 1026)), ('deconv4_b', (256,)), ('fuse_interconv0_w', (3, 3, 82, 16)), ('netsd_Convolution2_b', (2,)), ('net3_conv4_b', (512,)), ('net3_conv3_b', (256,)), ('net3_predict_conv2_w', (3, 3, 194, 2)), ('net3_predict_conv3_b', (2,)), ('conv6_1_w', (3, 3, 1024, 1024)), ('fuse_upsample_flow2to1_b', (2,)), ('Convolution1_w', (3, 3, 1024, 2)), ('net3_deconv3_w', (4, 4, 128, 770)), ('net2_deconv3_b', (128,)), ('fuse_conv1_w', (3, 3, 64, 64)), ('conv5_w', (3, 3, 512, 512)), ('Convolution4_w', (3, 3, 386, 2)), ('fuse_conv0_b', (64,)), ('net2_conv3_w', (5, 5, 128, 256)), ('upsample_flow4to3_b', (2,)), ('netsd_conv4_1_b', (512,)), ('fuse_upsample_flow2to1_w', (4, 4, 2, 2)), ('netsd_conv4_b', (512,)), ('net2_net2_upsample_flow3to2_b', (2,)), ('net3_predict_conv4_b', (2,)), ('fuse_upsample_flow1to0_b', (2,)), ('conv4_1_w', (3, 3, 512, 512)), ('deconv2_b', (64,)), ('net2_conv4_1_w', (3, 3, 512, 512)), ('net3_deconv4_w', (4, 4, 256, 1026)), ('net2_deconv5_b', (512,)), ('netsd_deconv5_b', (512,)), ('net2_deconv2_b', (64,)), ('net3_conv2_b', (128,)), ('conv_redir_w', (1, 1, 256, 32)), ('fuse_conv1_1_b', (128,)), ('net2_deconv5_w', (4, 4, 512, 1024)), ('net2_conv5_b', (512,)), ('net2_conv4_w', (3, 3, 256, 512)), ('net2_predict_conv6_w', (3, 3, 1024, 2)), ('netsd_conv5_b', (512,)), ('deconv4_w', (4, 4, 256, 1026)), ('net2_net2_upsample_flow4to3_b', (2,)), ('fuse__Convolution6_w', (3, 3, 32, 2)), ('net3_deconv2_w', (4, 4, 64, 386)), ('net2_conv6_1_w', (3, 3, 1024, 1024)), ('netsd_conv0_b', (64,)), ('netsd_conv5_1_w', (3, 3, 512, 512)), ('net2_conv6_1_b', (1024,)), ('net3_conv2_w', (5, 5, 64, 128)), ('net3_predict_conv6_w', (3, 3, 1024, 2)), ('net3_conv4_1_b', (512,)), ('net3_net3_upsample_flow4to3_w', (4, 4, 2, 2)), ('net2_deconv2_w', (4, 4, 64, 386)), ('deconv3_b', (128,)), ('netsd_interconv5_b', (512,)), ('net2_conv3_1_w', (3, 3, 256, 256)), ('netsd_interconv4_w', (3, 3, 770, 256)), ('net3_deconv3_b', (128,)), ('fuse_conv0_w', (3, 3, 11, 64)), ('net3_predict_conv6_b', (2,)), ('fuse_upsample_flow1to0_w', (4, 4, 2, 2)), ('netsd_deconv3_b', (128,)), ('net3_predict_conv5_w', (3, 3, 1026, 2)), ('netsd_conv5_w', (3, 3, 512, 512)), ('netsd_interconv5_w', (3, 3, 1026, 512)), ('netsd_Convolution3_w', (3, 3, 256, 2)), ('net2_predict_conv4_w', (3, 3, 770, 2)), ('deconv2_w', (4, 4, 64, 386)), ('net3_predict_conv5_b', (2,)), ('fuse__Convolution5_b', (2,)), ('fuse__Convolution7_w', (3, 3, 16, 2)), ('net2_net2_upsample_flow6to5_w', (4, 4, 2, 2)), ('netsd_conv3_b', (256,)), ('net3_conv6_w', (3, 3, 512, 1024)), ('net3_conv1_b', (64,)), ('netsd_Convolution4_b', (2,)), ('net3_conv3_w', (5, 5, 128, 256)), ('netsd_conv0_w', (3, 3, 6, 64)), ('net2_conv4_b', (512,)), ('net2_predict_conv3_w', (3, 3, 386, 2)), ('net3_net3_upsample_flow3to2_w', (4, 4, 2, 2)), ('fuse_conv1_1_w', (3, 3, 64, 128)), ('deconv5_b', (512,)), ('fuse__Convolution7_b', (2,)), ('net3_conv6_1_w', (3, 3, 1024, 1024)), ('net3_net3_upsample_flow5to4_w', (4, 4, 2, 2)), ('net3_conv4_w', (3, 3, 256, 512)), ('upsample_flow5to4_w', (4, 4, 2, 2)), ('conv4_1_b', (512,)), ('img0s_aug_b', (320, 448, 3, 1)), ('conv5_1_b', (512,)), ('net3_conv4_1_w', (3, 3, 512, 512)), ('upsample_flow5to4_b', (2,)), ('net3_conv3_1_b', (256,)), ('Convolution1_b', (2,)), ('upsample_flow4to3_w', (4, 4, 2, 2)), ('conv5_1_w', (3, 3, 512, 512)), ('conv3_1_b', (256,)), ('conv3_w', (5, 5, 128, 256)), ('net2_conv2_b', (128,)), ('net3_net3_upsample_flow6to5_w', (4, 4, 2, 2)), ('upsample_flow3to2_b', (2,)), ('netsd_Convolution5_w', (3, 3, 64, 2)), ('netsd_interconv2_w', (3, 3, 194, 64)), ('net2_predict_conv6_b', (2,)), ('net2_deconv4_w', (4, 4, 256, 1026)), ('scale_conv1_b', (2,)), ('net2_net2_upsample_flow5to4_w', (4, 4, 2, 2)), ('netsd_conv2_b', (128,)), ('netsd_conv2_1_b', (128,)), ('netsd_upsample_flow6to5_w', (4, 4, 2, 2)), ('net2_predict_conv5_b', (2,)), ('net3_conv6_1_b', (1024,)), ('netsd_conv6_w', (3, 3, 512, 1024)), ('Convolution4_b', (2,)), ('net2_predict_conv4_b', (2,)), ('fuse_deconv1_b', (32,)), ('conv3_1_w', (3, 3, 473, 256)), ('net3_deconv2_b', (64,)), ('netsd_conv6_b', (1024,)), ('net2_conv5_1_w', (3, 3, 512, 512)), ('net3_conv5_1_w', (3, 3, 512, 512)), ('deconv5_w', (4, 4, 512, 1024)), ('fuse_conv2_b', (128,)), ('netsd_conv1_1_b', (128,)), ('netsd_upsample_flow6to5_b', (2,)), ('Convolution5_w', (3, 3, 194, 2)), ('scale_conv1_w', (1, 1, 2, 2)), ('net2_net2_upsample_flow5to4_b', (2,)), ('conv6_1_b', (1024,)), ('fuse_conv2_1_b', (128,)), ('netsd_Convolution5_b', (2,)), ('netsd_conv3_1_b', (256,)), ('conv2_w', (5, 5, 64, 128)), ('fuse_conv2_w', (3, 3, 128, 128)), ('net2_conv2_w', (5, 5, 64, 128)), ('conv3_b', (256,)), ('net3_deconv5_w', (4, 4, 512, 1024)), ('img1s_aug_w', (1, 1, 1, 1)), ('netsd_conv2_w', (3, 3, 128, 128)), ('conv6_w', (3, 3, 512, 1024)), ('netsd_conv4_w', (3, 3, 256, 512)), ('net2_conv1_w', (7, 7, 12, 64)), ('netsd_Convolution1_w', (3, 3, 1024, 2)), ('netsd_conv1_w', (3, 3, 64, 64)), ('netsd_deconv4_b', (256,)), ('conv4_w', (3, 3, 256, 512)), ('conv5_b', (512,)), ('net3_deconv5_b', (512,)), ('netsd_interconv3_b', (128,)), ('net3_conv3_1_w', (3, 3, 256, 256)), ('net2_predict_conv5_w', (3, 3, 1026, 2)), ('Convolution3_b', (2,)), ('netsd_conv5_1_b', (512,)), ('netsd_interconv4_b', (256,)), ('conv4_b', (512,)), ('net3_net3_upsample_flow6to5_b', (2,)), ('Convolution5_b', (2,)), ('fuse_conv2_1_w', (3, 3, 128, 128)), ('net3_net3_upsample_flow4to3_b', (2,)), ('conv1_w', (7, 7, 3, 64)), ('upsample_flow6to5_b', (2,)), ('conv6_b', (1024,)), ('netsd_upsample_flow3to2_w', (4, 4, 2, 2)), ('net2_deconv3_w', (4, 4, 128, 770)), ('netsd_conv2_1_w', (3, 3, 128, 128)), ('netsd_Convolution3_b', (2,)), ('netsd_upsample_flow4to3_w', (4, 4, 2, 2)), ('fuse_interconv1_w', (3, 3, 162, 32)), ('netsd_upsample_flow4to3_b', (2,)), ('netsd_conv3_1_w', (3, 3, 256, 256)), ('netsd_deconv3_w', (4, 4, 128, 770)), ('net3_conv5_b', (512,)), ('net3_conv5_1_b', (512,)), ('net2_net2_upsample_flow4to3_w', (4, 4, 2, 2)), ('net2_net2_upsample_flow3to2_w', (4, 4, 2, 2)), ('net2_conv3_b', (256,)), ('netsd_conv6_1_w', (3, 3, 1024, 1024)), ('fuse_deconv0_b', (16,)), ('net2_predict_conv2_w', (3, 3, 194, 2)), ('net2_conv1_b', (64,)), ('net2_conv6_b', (1024,)), ('net3_predict_conv2_b', (2,)), ('net2_conv4_1_b', (512,)), ('netsd_Convolution4_w', (3, 3, 128, 2)), ('deconv3_w', (4, 4, 128, 770)), ('fuse_deconv1_w', (4, 4, 32, 128)), ('netsd_Convolution2_w', (3, 3, 512, 2)), ('netsd_Convolution1_b', (2,)), ('net2_conv3_1_b', (256,)), ('fuse_conv1_b', (64,)), ('net2_deconv4_b', (256,)), ('net3_predict_conv4_w', (3, 3, 770, 2)), ('Convolution3_w', (3, 3, 770, 2)), ('netsd_upsample_flow3to2_b', (2,)), ('net3_net3_upsample_flow3to2_b', (2,)), ('fuse_interconv0_b', (16,)), ('Convolution2_w', (3, 3, 1026, 2)), ('net2_conv6_w', (3, 3, 512, 1024)), ('netsd_conv3_w', (3, 3, 128, 256)), ('netsd_upsample_flow5to4_b', (2,)), ('net3_predict_conv3_w', (3, 3, 386, 2)), ('conv_redir_b', (32,)), ('net2_conv5_1_b', (512,)), ('upsample_flow6to5_w', (4, 4, 2, 2)), ('net2_net2_upsample_flow6to5_b', (2,)), ('net3_conv6_b', (1024,)), ('fuse__Convolution6_b', (2,)), ('Convolution2_b', (2,)), ('upsample_flow3to2_w', (4, 4, 2, 2)), ('net3_conv1_w', (7, 7, 12, 64)), ('fuse_deconv0_w', (4, 4, 16, 162)), ('img0s_aug_w', (1, 1, 1, 1)), ('netsd_conv1_1_w', (3, 3, 64, 128)), ('netsd_deconv2_b', (64,)), ('net2_conv5_w', (3, 3, 512, 512)), ('fuse_interconv1_b', (32,)), ('netsd_conv6_1_b', (1024,)), ('netsd_interconv2_b', (64,)), ('img1s_aug_b', (320, 448, 3, 1)), ('netsd_deconv2_w', (4, 4, 64, 386)), ('net2_predict_conv3_b', (2,)), ('net2_predict_conv2_b', (2,)), ('net3_deconv4_b', (256,)), ('net3_net3_upsample_flow5to4_b', (2,)), ('conv1_b', (64,)), ('net3_conv5_w', (3, 3, 512, 512))]
[ "tensorflow.nn.conv2d", "tensorflow.contrib.graph_editor.reroute.add_control_inputs", "tensorflow.image.resize_nearest_neighbor", "tensorflow.shape", "tensorflow.pad", "tensorflow.reshape", "tensorflow.get_variable", "tensorflow.to_float", "tensorflow.reduce_sum", "tensorflow.ones", "tensorflow.image.resize_bilinear", "numpy.array", "tensorflow.concat", "tensorflow.nn.conv2d_transpose", "tensorflow.maximum", "tensorflow.train.AdamOptimizer", "tensorflow.stack" ]
[((469, 489), 'tensorflow.maximum', 'tf.maximum', (['x', '(s * x)'], {}), '(x, s * x)\n', (479, 489), True, 'import tensorflow as tf\n'), ((1098, 1126), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(flow * target)'], {}), '(flow * target)\n', (1111, 1126), True, 'import tensorflow as tf\n'), ((1173, 1267), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': '(0.95)', 'beta2': '(0.99)', 'epsilon': '(1e-08)'}), '(learning_rate=learning_rate, beta1=0.95, beta2=0.99,\n epsilon=1e-08)\n', (1195, 1267), True, 'import tensorflow as tf\n'), ((2109, 2166), 'tensorflow.contrib.graph_editor.reroute.add_control_inputs', 'ge.reroute.add_control_inputs', (['a_tensor.op', '[b_tensor.op]'], {}), '(a_tensor.op, [b_tensor.op])\n', (2138, 2166), True, 'import tensorflow.contrib.graph_editor as ge\n'), ((3190, 3236), 'numpy.array', 'np.array', (['[0.37655231, 0.39534855, 0.40119368]'], {}), '([0.37655231, 0.39534855, 0.40119368])\n', (3198, 3236), True, 'import numpy as np\n'), ((3382, 3490), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (["blobs['img0_nomean']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(True)'}), "(blobs['img0_nomean'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=True)\n", (3406, 3490), True, 'import tensorflow as tf\n'), ((3525, 3633), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (["blobs['img1_nomean']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(True)'}), "(blobs['img1_nomean'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=True)\n", (3549, 3633), True, 'import tensorflow as tf\n'), ((3665, 3734), 'tensorflow.pad', 'tf.pad', (["blobs['img0_nomean_resize']", '[[0, 0], [3, 3], [3, 3], [0, 0]]'], {}), "(blobs['img0_nomean_resize'], [[0, 0], [3, 3], [3, 3], [0, 0]])\n", (3671, 3734), True, 'import tensorflow as tf\n'), ((3965, 4034), 'tensorflow.pad', 'tf.pad', (["blobs['img1_nomean_resize']", '[[0, 0], [3, 3], [3, 3], [0, 0]]'], {}), "(blobs['img1_nomean_resize'], [[0, 0], [3, 3], [3, 3], [0, 0]])\n", (3971, 4034), True, 'import tensorflow as tf\n'), ((4265, 4322), 'tensorflow.pad', 'tf.pad', (["blobs['conv1a']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['conv1a'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (4271, 4322), True, 'import tensorflow as tf\n'), ((4553, 4610), 'tensorflow.pad', 'tf.pad', (["blobs['conv1b']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['conv1b'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (4559, 4610), True, 'import tensorflow as tf\n'), ((4841, 4898), 'tensorflow.pad', 'tf.pad', (["blobs['conv2a']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['conv2a'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (4847, 4898), True, 'import tensorflow as tf\n'), ((5129, 5186), 'tensorflow.pad', 'tf.pad', (["blobs['conv2b']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['conv2b'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (5135, 5186), True, 'import tensorflow as tf\n'), ((6156, 6178), 'tensorflow.concat', 'tf.concat', (['tmp'], {'axis': '(3)'}), '(tmp, axis=3)\n', (6165, 6178), True, 'import tensorflow as tf\n'), ((6497, 6552), 'tensorflow.concat', 'tf.concat', (["[blobs['conv_redir'], blobs['corr']]"], {'axis': '(3)'}), "([blobs['conv_redir'], blobs['corr']], axis=3)\n", (6506, 6552), True, 'import tensorflow as tf\n'), ((6793, 6851), 'tensorflow.pad', 'tf.pad', (["blobs['conv3_1']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['conv3_1'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (6799, 6851), True, 'import tensorflow as tf\n'), ((7290, 7348), 'tensorflow.pad', 'tf.pad', (["blobs['conv4_1']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['conv4_1'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (7296, 7348), True, 'import tensorflow as tf\n'), ((7787, 7845), 'tensorflow.pad', 'tf.pad', (["blobs['conv5_1']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['conv5_1'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (7793, 7845), True, 'import tensorflow as tf\n'), ((8994, 9085), 'tensorflow.concat', 'tf.concat', (["[blobs['conv5_1'], blobs['deconv5'], blobs['upsampled_flow6_to_5']]"], {'axis': '(3)'}), "([blobs['conv5_1'], blobs['deconv5'], blobs['upsampled_flow6_to_5'\n ]], axis=3)\n", (9003, 9085), True, 'import tensorflow as tf\n'), ((9115, 9173), 'tensorflow.pad', 'tf.pad', (["blobs['concat5']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['concat5'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (9121, 9173), True, 'import tensorflow as tf\n'), ((9920, 10011), 'tensorflow.concat', 'tf.concat', (["[blobs['conv4_1'], blobs['deconv4'], blobs['upsampled_flow5_to_4']]"], {'axis': '(3)'}), "([blobs['conv4_1'], blobs['deconv4'], blobs['upsampled_flow5_to_4'\n ]], axis=3)\n", (9929, 10011), True, 'import tensorflow as tf\n'), ((10747, 10838), 'tensorflow.concat', 'tf.concat', (["[blobs['conv3_1'], blobs['deconv3'], blobs['upsampled_flow4_to_3']]"], {'axis': '(3)'}), "([blobs['conv3_1'], blobs['deconv3'], blobs['upsampled_flow4_to_3'\n ]], axis=3)\n", (10756, 10838), True, 'import tensorflow as tf\n'), ((11557, 11647), 'tensorflow.concat', 'tf.concat', (["[blobs['conv2a'], blobs['deconv2'], blobs['upsampled_flow3_to_2']]"], {'axis': '(3)'}), "([blobs['conv2a'], blobs['deconv2'], blobs['upsampled_flow3_to_2']\n ], axis=3)\n", (11566, 11647), True, 'import tensorflow as tf\n'), ((11899, 12002), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (["blobs['blob41']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(True)'}), "(blobs['blob41'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=True)\n", (11923, 12002), True, 'import tensorflow as tf\n'), ((12394, 12527), 'tensorflow.concat', 'tf.concat', (["[blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs['blob43'],\n blobs['blob46'], blobs['blob45']]"], {'axis': '(3)'}), "([blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs[\n 'blob43'], blobs['blob46'], blobs['blob45']], axis=3)\n", (12403, 12527), True, 'import tensorflow as tf\n'), ((13203, 13260), 'tensorflow.pad', 'tf.pad', (["blobs['blob47']", '[[0, 0], [3, 3], [3, 3], [0, 0]]'], {}), "(blobs['blob47'], [[0, 0], [3, 3], [3, 3], [0, 0]])\n", (13209, 13260), True, 'import tensorflow as tf\n'), ((13501, 13558), 'tensorflow.pad', 'tf.pad', (["blobs['blob48']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['blob48'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (13507, 13558), True, 'import tensorflow as tf\n'), ((13800, 13857), 'tensorflow.pad', 'tf.pad', (["blobs['blob49']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['blob49'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (13806, 13857), True, 'import tensorflow as tf\n'), ((14319, 14376), 'tensorflow.pad', 'tf.pad', (["blobs['blob51']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob51'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (14325, 14376), True, 'import tensorflow as tf\n'), ((14838, 14895), 'tensorflow.pad', 'tf.pad', (["blobs['blob53']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob53'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (14844, 14895), True, 'import tensorflow as tf\n'), ((15357, 15414), 'tensorflow.pad', 'tf.pad', (["blobs['blob55']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob55'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (15363, 15414), True, 'import tensorflow as tf\n'), ((16616, 16686), 'tensorflow.concat', 'tf.concat', (["[blobs['blob55'], blobs['blob59'], blobs['blob60']]"], {'axis': '(3)'}), "([blobs['blob55'], blobs['blob59'], blobs['blob60']], axis=3)\n", (16625, 16686), True, 'import tensorflow as tf\n'), ((17439, 17509), 'tensorflow.concat', 'tf.concat', (["[blobs['blob53'], blobs['blob63'], blobs['blob64']]"], {'axis': '(3)'}), "([blobs['blob53'], blobs['blob63'], blobs['blob64']], axis=3)\n", (17448, 17509), True, 'import tensorflow as tf\n'), ((18266, 18336), 'tensorflow.concat', 'tf.concat', (["[blobs['blob51'], blobs['blob67'], blobs['blob68']]"], {'axis': '(3)'}), "([blobs['blob51'], blobs['blob67'], blobs['blob68']], axis=3)\n", (18275, 18336), True, 'import tensorflow as tf\n'), ((19068, 19138), 'tensorflow.concat', 'tf.concat', (["[blobs['blob49'], blobs['blob71'], blobs['blob72']]"], {'axis': '(3)'}), "([blobs['blob49'], blobs['blob71'], blobs['blob72']], axis=3)\n", (19077, 19138), True, 'import tensorflow as tf\n'), ((19392, 19495), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (["blobs['blob75']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(True)'}), "(blobs['blob75'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=True)\n", (19416, 19495), True, 'import tensorflow as tf\n'), ((19887, 20020), 'tensorflow.concat', 'tf.concat', (["[blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs['blob77'],\n blobs['blob80'], blobs['blob79']]"], {'axis': '(3)'}), "([blobs['img0_nomean_resize'], blobs['img1_nomean_resize'], blobs[\n 'blob77'], blobs['blob80'], blobs['blob79']], axis=3)\n", (19896, 20020), True, 'import tensorflow as tf\n'), ((20696, 20753), 'tensorflow.pad', 'tf.pad', (["blobs['blob81']", '[[0, 0], [3, 3], [3, 3], [0, 0]]'], {}), "(blobs['blob81'], [[0, 0], [3, 3], [3, 3], [0, 0]])\n", (20702, 20753), True, 'import tensorflow as tf\n'), ((20994, 21051), 'tensorflow.pad', 'tf.pad', (["blobs['blob82']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['blob82'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (21000, 21051), True, 'import tensorflow as tf\n'), ((21293, 21350), 'tensorflow.pad', 'tf.pad', (["blobs['blob83']", '[[0, 0], [2, 2], [2, 2], [0, 0]]'], {}), "(blobs['blob83'], [[0, 0], [2, 2], [2, 2], [0, 0]])\n", (21299, 21350), True, 'import tensorflow as tf\n'), ((21812, 21869), 'tensorflow.pad', 'tf.pad', (["blobs['blob85']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob85'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (21818, 21869), True, 'import tensorflow as tf\n'), ((22331, 22388), 'tensorflow.pad', 'tf.pad', (["blobs['blob87']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob87'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (22337, 22388), True, 'import tensorflow as tf\n'), ((22850, 22907), 'tensorflow.pad', 'tf.pad', (["blobs['blob89']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob89'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (22856, 22907), True, 'import tensorflow as tf\n'), ((24102, 24172), 'tensorflow.concat', 'tf.concat', (["[blobs['blob89'], blobs['blob93'], blobs['blob94']]"], {'axis': '(3)'}), "([blobs['blob89'], blobs['blob93'], blobs['blob94']], axis=3)\n", (24111, 24172), True, 'import tensorflow as tf\n'), ((24925, 24995), 'tensorflow.concat', 'tf.concat', (["[blobs['blob87'], blobs['blob97'], blobs['blob98']]"], {'axis': '(3)'}), "([blobs['blob87'], blobs['blob97'], blobs['blob98']], axis=3)\n", (24934, 24995), True, 'import tensorflow as tf\n'), ((25759, 25831), 'tensorflow.concat', 'tf.concat', (["[blobs['blob85'], blobs['blob101'], blobs['blob102']]"], {'axis': '(3)'}), "([blobs['blob85'], blobs['blob101'], blobs['blob102']], axis=3)\n", (25768, 25831), True, 'import tensorflow as tf\n'), ((26572, 26644), 'tensorflow.concat', 'tf.concat', (["[blobs['blob83'], blobs['blob105'], blobs['blob106']]"], {'axis': '(3)'}), "([blobs['blob83'], blobs['blob105'], blobs['blob106']], axis=3)\n", (26581, 26644), True, 'import tensorflow as tf\n'), ((27555, 27632), 'tensorflow.concat', 'tf.concat', (["[blobs['img0_nomean_resize'], blobs['img1_nomean_resize']]"], {'axis': '(3)'}), "([blobs['img0_nomean_resize'], blobs['img1_nomean_resize']], axis=3)\n", (27564, 27632), True, 'import tensorflow as tf\n'), ((27952, 28010), 'tensorflow.pad', 'tf.pad', (["blobs['blob111']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob111'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (27958, 28010), True, 'import tensorflow as tf\n'), ((28493, 28551), 'tensorflow.pad', 'tf.pad', (["blobs['blob113']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob113'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (28499, 28551), True, 'import tensorflow as tf\n'), ((29034, 29092), 'tensorflow.pad', 'tf.pad', (["blobs['blob115']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob115'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (29040, 29092), True, 'import tensorflow as tf\n'), ((29575, 29633), 'tensorflow.pad', 'tf.pad', (["blobs['blob117']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob117'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (29581, 29633), True, 'import tensorflow as tf\n'), ((30116, 30174), 'tensorflow.pad', 'tf.pad', (["blobs['blob119']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob119'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (30122, 30174), True, 'import tensorflow as tf\n'), ((30657, 30715), 'tensorflow.pad', 'tf.pad', (["blobs['blob121']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob121'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (30663, 30715), True, 'import tensorflow as tf\n'), ((31917, 31990), 'tensorflow.concat', 'tf.concat', (["[blobs['blob121'], blobs['blob125'], blobs['blob126']]"], {'axis': '(3)'}), "([blobs['blob121'], blobs['blob125'], blobs['blob126']], axis=3)\n", (31926, 31990), True, 'import tensorflow as tf\n'), ((32913, 32986), 'tensorflow.concat', 'tf.concat', (["[blobs['blob119'], blobs['blob130'], blobs['blob131']]"], {'axis': '(3)'}), "([blobs['blob119'], blobs['blob130'], blobs['blob131']], axis=3)\n", (32922, 32986), True, 'import tensorflow as tf\n'), ((33913, 33986), 'tensorflow.concat', 'tf.concat', (["[blobs['blob117'], blobs['blob135'], blobs['blob136']]"], {'axis': '(3)'}), "([blobs['blob117'], blobs['blob135'], blobs['blob136']], axis=3)\n", (33922, 33986), True, 'import tensorflow as tf\n'), ((34888, 34961), 'tensorflow.concat', 'tf.concat', (["[blobs['blob115'], blobs['blob140'], blobs['blob141']]"], {'axis': '(3)'}), "([blobs['blob115'], blobs['blob140'], blobs['blob141']], axis=3)\n", (34897, 34961), True, 'import tensorflow as tf\n'), ((35386, 35499), 'tensorflow.image.resize_nearest_neighbor', 'tf.image.resize_nearest_neighbor', (["blobs['blob145']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(False)'}), "(blobs['blob145'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=False)\n", (35418, 35499), True, 'import tensorflow as tf\n'), ((35532, 35645), 'tensorflow.image.resize_nearest_neighbor', 'tf.image.resize_nearest_neighbor', (["blobs['blob109']"], {'size': '[ADAPTED_HEIGHT, ADAPTED_WIDTH]', 'align_corners': '(False)'}), "(blobs['blob109'], size=[ADAPTED_HEIGHT,\n ADAPTED_WIDTH], align_corners=False)\n", (35564, 35645), True, 'import tensorflow as tf\n'), ((36630, 36794), 'tensorflow.concat', 'tf.concat', (["[blobs['img0_nomean_resize'], blobs['blob146'], blobs['blob147'], blobs[\n 'blob148'], blobs['blob149'], blobs['blob152'], blobs['blob155']]"], {'axis': '(3)'}), "([blobs['img0_nomean_resize'], blobs['blob146'], blobs['blob147'],\n blobs['blob148'], blobs['blob149'], blobs['blob152'], blobs['blob155']],\n axis=3)\n", (36639, 36794), True, 'import tensorflow as tf\n'), ((37036, 37094), 'tensorflow.pad', 'tf.pad', (["blobs['blob157']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob157'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (37042, 37094), True, 'import tensorflow as tf\n'), ((37573, 37631), 'tensorflow.pad', 'tf.pad', (["blobs['blob159']", '[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), "(blobs['blob159'], [[0, 0], [1, 1], [1, 1], [0, 0]])\n", (37579, 37631), True, 'import tensorflow as tf\n'), ((38812, 38885), 'tensorflow.concat', 'tf.concat', (["[blobs['blob159'], blobs['blob163'], blobs['blob164']]"], {'axis': '(3)'}), "([blobs['blob159'], blobs['blob163'], blobs['blob164']], axis=3)\n", (38821, 38885), True, 'import tensorflow as tf\n'), ((39777, 39850), 'tensorflow.concat', 'tf.concat', (["[blobs['blob157'], blobs['blob168'], blobs['blob169']]"], {'axis': '(3)'}), "([blobs['blob157'], blobs['blob168'], blobs['blob169']], axis=3)\n", (39786, 39850), True, 'import tensorflow as tf\n'), ((40235, 40337), 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (["blobs['blob172']"], {'size': '[TARGET_HEIGHT, TARGET_WIDTH]', 'align_corners': '(True)'}), "(blobs['blob172'], size=[TARGET_HEIGHT,\n TARGET_WIDTH], align_corners=True)\n", (40259, 40337), True, 'import tensorflow as tf\n'), ((40351, 40388), 'tensorflow.stack', 'tf.stack', (['[SCALE_WIDTH, SCALE_HEIGHT]'], {}), '([SCALE_WIDTH, SCALE_HEIGHT])\n', (40359, 40388), True, 'import tensorflow as tf\n'), ((40405, 40436), 'tensorflow.reshape', 'tf.reshape', (['scale', '[1, 1, 1, 2]'], {}), '(scale, [1, 1, 1, 2])\n', (40415, 40436), True, 'import tensorflow as tf\n'), ((281, 314), 'tensorflow.get_variable', 'tf.get_variable', (['key'], {'shape': 'shape'}), '(key, shape=shape)\n', (296, 314), True, 'import tensorflow as tf\n'), ((582, 636), 'tensorflow.stack', 'tf.stack', (['[flow[:, :, :, 1], flow[:, :, :, 0]]'], {'axis': '(3)'}), '([flow[:, :, :, 1], flow[:, :, :, 0]], axis=3)\n', (590, 636), True, 'import tensorflow as tf\n'), ((919, 967), 'tensorflow.stack', 'tf.stack', (['[f[:, :, :, 1], f[:, :, :, 0]]'], {'axis': '(3)'}), '([f[:, :, :, 1], f[:, :, :, 0]], axis=3)\n', (927, 967), True, 'import tensorflow as tf\n'), ((2818, 2836), 'tensorflow.to_float', 'tf.to_float', (['width'], {}), '(width)\n', (2829, 2836), True, 'import tensorflow as tf\n'), ((2839, 2865), 'tensorflow.to_float', 'tf.to_float', (['ADAPTED_WIDTH'], {}), '(ADAPTED_WIDTH)\n', (2850, 2865), True, 'import tensorflow as tf\n'), ((2890, 2909), 'tensorflow.to_float', 'tf.to_float', (['height'], {}), '(height)\n', (2901, 2909), True, 'import tensorflow as tf\n'), ((2912, 2939), 'tensorflow.to_float', 'tf.to_float', (['ADAPTED_HEIGHT'], {}), '(ADAPTED_HEIGHT)\n', (2923, 2939), True, 'import tensorflow as tf\n'), ((3757, 3854), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv1a']", "self.weights['conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv1a'], self.weights['conv1_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (3769, 3854), True, 'import tensorflow as tf\n'), ((4057, 4154), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv1b']", "self.weights['conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv1b'], self.weights['conv1_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (4069, 4154), True, 'import tensorflow as tf\n'), ((4345, 4442), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv2a']", "self.weights['conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv2a'], self.weights['conv2_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (4357, 4442), True, 'import tensorflow as tf\n'), ((4633, 4730), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv2b']", "self.weights['conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv2b'], self.weights['conv2_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (4645, 4730), True, 'import tensorflow as tf\n'), ((4921, 5018), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv3a']", "self.weights['conv3_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv3a'], self.weights['conv3_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (4933, 5018), True, 'import tensorflow as tf\n'), ((5209, 5306), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv3b']", "self.weights['conv3_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv3b'], self.weights['conv3_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (5221, 5306), True, 'import tensorflow as tf\n'), ((6271, 6374), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv3a']", "self.weights['conv_redir_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(blobs['conv3a'], self.weights['conv_redir_w'], strides=[1, 1, \n 1, 1], padding='VALID')\n", (6283, 6374), True, 'import tensorflow as tf\n'), ((6581, 6680), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob16']", "self.weights['conv3_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob16'], self.weights['conv3_1_w'], strides=[1, 1, 1, \n 1], padding='SAME')\n", (6593, 6680), True, 'import tensorflow as tf\n'), ((6873, 6969), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv4']", "self.weights['conv4_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv4'], self.weights['conv4_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (6885, 6969), True, 'import tensorflow as tf\n'), ((7079, 7177), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv4']", "self.weights['conv4_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['conv4'], self.weights['conv4_1_w'], strides=[1, 1, 1, 1\n ], padding='SAME')\n", (7091, 7177), True, 'import tensorflow as tf\n'), ((7370, 7466), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv5']", "self.weights['conv5_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv5'], self.weights['conv5_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (7382, 7466), True, 'import tensorflow as tf\n'), ((7576, 7674), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv5']", "self.weights['conv5_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['conv5'], self.weights['conv5_1_w'], strides=[1, 1, 1, 1\n ], padding='SAME')\n", (7588, 7674), True, 'import tensorflow as tf\n'), ((7867, 7963), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv6']", "self.weights['conv6_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['conv6'], self.weights['conv6_w'], strides=[1, 2, 2, 1],\n padding='VALID')\n", (7879, 7963), True, 'import tensorflow as tf\n'), ((8073, 8171), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv6']", "self.weights['conv6_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['conv6'], self.weights['conv6_1_w'], strides=[1, 1, 1, 1\n ], padding='SAME')\n", (8085, 8171), True, 'import tensorflow as tf\n'), ((8292, 8397), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['conv6_1']", "self.weights['Convolution1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['conv6_1'], self.weights['Convolution1_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (8304, 8397), True, 'import tensorflow as tf\n'), ((8451, 8621), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['conv6_1']", "self.weights['deconv5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512]', 'strides': '[1, 2, 2, 1]'}), "(blobs['conv6_1'], self.weights['deconv5_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512],\n strides=[1, 2, 2, 1])\n", (8473, 8621), True, 'import tensorflow as tf\n'), ((8750, 8936), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['predict_flow6']", "self.weights['upsample_flow6to5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['predict_flow6'], self.weights[\n 'upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT / 32, \n ADAPTED_WIDTH / 32, 2], strides=[1, 2, 2, 1])\n", (8772, 8936), True, 'import tensorflow as tf\n'), ((9203, 9314), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['predict_flow5']", "self.weights['Convolution2_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(blobs['predict_flow5'], self.weights['Convolution2_w'],\n strides=[1, 1, 1, 1], padding='VALID')\n", (9215, 9314), True, 'import tensorflow as tf\n'), ((9377, 9547), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['concat5']", "self.weights['deconv4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256]', 'strides': '[1, 2, 2, 1]'}), "(blobs['concat5'], self.weights['deconv4_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256],\n strides=[1, 2, 2, 1])\n", (9399, 9547), True, 'import tensorflow as tf\n'), ((9676, 9862), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['predict_flow5']", "self.weights['upsample_flow5to4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['predict_flow5'], self.weights[\n 'upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT / 16, \n ADAPTED_WIDTH / 16, 2], strides=[1, 2, 2, 1])\n", (9698, 9862), True, 'import tensorflow as tf\n'), ((10041, 10146), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['concat4']", "self.weights['Convolution3_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['concat4'], self.weights['Convolution3_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (10053, 10146), True, 'import tensorflow as tf\n'), ((10208, 10376), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['concat4']", "self.weights['deconv3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128]', 'strides': '[1, 2, 2, 1]'}), "(blobs['concat4'], self.weights['deconv3_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128],\n strides=[1, 2, 2, 1])\n", (10230, 10376), True, 'import tensorflow as tf\n'), ((10505, 10689), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['predict_flow4']", "self.weights['upsample_flow4to3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['predict_flow4'], self.weights[\n 'upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT / 8, \n ADAPTED_WIDTH / 8, 2], strides=[1, 2, 2, 1])\n", (10527, 10689), True, 'import tensorflow as tf\n'), ((10868, 10973), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['concat3']", "self.weights['Convolution4_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['concat3'], self.weights['Convolution4_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (10880, 10973), True, 'import tensorflow as tf\n'), ((11035, 11202), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['concat3']", "self.weights['deconv2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64]', 'strides': '[1, 2, 2, 1]'}), "(blobs['concat3'], self.weights['deconv2_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64],\n strides=[1, 2, 2, 1])\n", (11057, 11202), True, 'import tensorflow as tf\n'), ((11323, 11507), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['predict_flow3']", "self.weights['upsample_flow3to2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['predict_flow3'], self.weights[\n 'upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT / 4, \n ADAPTED_WIDTH / 4, 2], strides=[1, 2, 2, 1])\n", (11345, 11507), True, 'import tensorflow as tf\n'), ((11677, 11782), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['concat2']", "self.weights['Convolution5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['concat2'], self.weights['Convolution5_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (11689, 11782), True, 'import tensorflow as tf\n'), ((13283, 13386), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob48']", "self.weights['net2_conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob48'], self.weights['net2_conv1_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (13295, 13386), True, 'import tensorflow as tf\n'), ((13582, 13685), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob49']", "self.weights['net2_conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob49'], self.weights['net2_conv2_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (13594, 13685), True, 'import tensorflow as tf\n'), ((13880, 13983), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob50']", "self.weights['net2_conv3_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob50'], self.weights['net2_conv3_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (13892, 13983), True, 'import tensorflow as tf\n'), ((14098, 14201), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob50']", "self.weights['net2_conv3_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob50'], self.weights['net2_conv3_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (14110, 14201), True, 'import tensorflow as tf\n'), ((14399, 14502), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob52']", "self.weights['net2_conv4_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob52'], self.weights['net2_conv4_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (14411, 14502), True, 'import tensorflow as tf\n'), ((14617, 14720), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob52']", "self.weights['net2_conv4_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob52'], self.weights['net2_conv4_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (14629, 14720), True, 'import tensorflow as tf\n'), ((14918, 15021), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob54']", "self.weights['net2_conv5_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob54'], self.weights['net2_conv5_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (14930, 15021), True, 'import tensorflow as tf\n'), ((15136, 15239), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob54']", "self.weights['net2_conv5_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob54'], self.weights['net2_conv5_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (15148, 15239), True, 'import tensorflow as tf\n'), ((15437, 15540), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob56']", "self.weights['net2_conv6_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob56'], self.weights['net2_conv6_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (15449, 15540), True, 'import tensorflow as tf\n'), ((15655, 15758), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob56']", "self.weights['net2_conv6_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob56'], self.weights['net2_conv6_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (15667, 15758), True, 'import tensorflow as tf\n'), ((15884, 15994), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob57']", "self.weights['net2_predict_conv6_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob57'], self.weights['net2_predict_conv6_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (15896, 15994), True, 'import tensorflow as tf\n'), ((16061, 16235), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob57']", "self.weights['net2_deconv5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob57'], self.weights['net2_deconv5_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512],\n strides=[1, 2, 2, 1])\n", (16083, 16235), True, 'import tensorflow as tf\n'), ((16353, 16549), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['predict_flow6']", "self.weights['net2_net2_upsample_flow6to5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['predict_flow6'], self.weights[\n 'net2_net2_upsample_flow6to5_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2], strides=[1, 2, 2, 1])\n", (16375, 16549), True, 'import tensorflow as tf\n'), ((16714, 16824), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob61']", "self.weights['net2_predict_conv5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob61'], self.weights['net2_predict_conv5_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (16726, 16824), True, 'import tensorflow as tf\n'), ((16891, 17065), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob61']", "self.weights['net2_deconv4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob61'], self.weights['net2_deconv4_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256],\n strides=[1, 2, 2, 1])\n", (16913, 17065), True, 'import tensorflow as tf\n'), ((17183, 17372), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob62']", "self.weights['net2_net2_upsample_flow5to4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob62'], self.weights[\n 'net2_net2_upsample_flow5to4_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2], strides=[1, 2, 2, 1])\n", (17205, 17372), True, 'import tensorflow as tf\n'), ((17545, 17655), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob65']", "self.weights['net2_predict_conv4_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob65'], self.weights['net2_predict_conv4_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (17557, 17655), True, 'import tensorflow as tf\n'), ((17722, 17894), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob65']", "self.weights['net2_deconv3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob65'], self.weights['net2_deconv3_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128],\n strides=[1, 2, 2, 1])\n", (17744, 17894), True, 'import tensorflow as tf\n'), ((18012, 18199), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob66']", "self.weights['net2_net2_upsample_flow4to3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob66'], self.weights[\n 'net2_net2_upsample_flow4to3_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2], strides=[1, 2, 2, 1])\n", (18034, 18199), True, 'import tensorflow as tf\n'), ((18364, 18474), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob69']", "self.weights['net2_predict_conv3_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob69'], self.weights['net2_predict_conv3_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (18376, 18474), True, 'import tensorflow as tf\n'), ((18541, 18712), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob69']", "self.weights['net2_deconv2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob69'], self.weights['net2_deconv2_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64],\n strides=[1, 2, 2, 1])\n", (18563, 18712), True, 'import tensorflow as tf\n'), ((18822, 19009), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob70']", "self.weights['net2_net2_upsample_flow3to2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob70'], self.weights[\n 'net2_net2_upsample_flow3to2_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2], strides=[1, 2, 2, 1])\n", (18844, 19009), True, 'import tensorflow as tf\n'), ((19166, 19276), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob73']", "self.weights['net2_predict_conv2_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob73'], self.weights['net2_predict_conv2_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (19178, 19276), True, 'import tensorflow as tf\n'), ((20776, 20879), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob82']", "self.weights['net3_conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob82'], self.weights['net3_conv1_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (20788, 20879), True, 'import tensorflow as tf\n'), ((21075, 21178), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob83']", "self.weights['net3_conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob83'], self.weights['net3_conv2_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (21087, 21178), True, 'import tensorflow as tf\n'), ((21373, 21476), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob84']", "self.weights['net3_conv3_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob84'], self.weights['net3_conv3_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (21385, 21476), True, 'import tensorflow as tf\n'), ((21591, 21694), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob84']", "self.weights['net3_conv3_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob84'], self.weights['net3_conv3_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (21603, 21694), True, 'import tensorflow as tf\n'), ((21892, 21995), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob86']", "self.weights['net3_conv4_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob86'], self.weights['net3_conv4_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (21904, 21995), True, 'import tensorflow as tf\n'), ((22110, 22213), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob86']", "self.weights['net3_conv4_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob86'], self.weights['net3_conv4_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (22122, 22213), True, 'import tensorflow as tf\n'), ((22411, 22514), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob88']", "self.weights['net3_conv5_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob88'], self.weights['net3_conv5_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (22423, 22514), True, 'import tensorflow as tf\n'), ((22629, 22732), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob88']", "self.weights['net3_conv5_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob88'], self.weights['net3_conv5_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (22641, 22732), True, 'import tensorflow as tf\n'), ((22930, 23033), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob90']", "self.weights['net3_conv6_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob90'], self.weights['net3_conv6_w'], strides=[1, 2, \n 2, 1], padding='VALID')\n", (22942, 23033), True, 'import tensorflow as tf\n'), ((23148, 23251), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob90']", "self.weights['net3_conv6_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob90'], self.weights['net3_conv6_1_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (23160, 23251), True, 'import tensorflow as tf\n'), ((23377, 23487), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob91']", "self.weights['net3_predict_conv6_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob91'], self.weights['net3_predict_conv6_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (23389, 23487), True, 'import tensorflow as tf\n'), ((23554, 23728), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob91']", "self.weights['net3_deconv5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob91'], self.weights['net3_deconv5_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512],\n strides=[1, 2, 2, 1])\n", (23576, 23728), True, 'import tensorflow as tf\n'), ((23846, 24035), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob92']", "self.weights['net3_net3_upsample_flow6to5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob92'], self.weights[\n 'net3_net3_upsample_flow6to5_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2], strides=[1, 2, 2, 1])\n", (23868, 24035), True, 'import tensorflow as tf\n'), ((24200, 24310), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob95']", "self.weights['net3_predict_conv5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob95'], self.weights['net3_predict_conv5_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (24212, 24310), True, 'import tensorflow as tf\n'), ((24377, 24551), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob95']", "self.weights['net3_deconv4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob95'], self.weights['net3_deconv4_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256],\n strides=[1, 2, 2, 1])\n", (24399, 24551), True, 'import tensorflow as tf\n'), ((24669, 24858), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob96']", "self.weights['net3_net3_upsample_flow5to4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob96'], self.weights[\n 'net3_net3_upsample_flow5to4_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2], strides=[1, 2, 2, 1])\n", (24691, 24858), True, 'import tensorflow as tf\n'), ((25032, 25142), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob99']", "self.weights['net3_predict_conv4_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob99'], self.weights['net3_predict_conv4_w'], strides\n =[1, 1, 1, 1], padding='SAME')\n", (25044, 25142), True, 'import tensorflow as tf\n'), ((25210, 25382), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob99']", "self.weights['net3_deconv3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob99'], self.weights['net3_deconv3_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128],\n strides=[1, 2, 2, 1])\n", (25232, 25382), True, 'import tensorflow as tf\n'), ((25503, 25691), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob100']", "self.weights['net3_net3_upsample_flow4to3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob100'], self.weights[\n 'net3_net3_upsample_flow4to3_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2], strides=[1, 2, 2, 1])\n", (25525, 25691), True, 'import tensorflow as tf\n'), ((25860, 25970), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob103']", "self.weights['net3_predict_conv3_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob103'], self.weights['net3_predict_conv3_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (25872, 25970), True, 'import tensorflow as tf\n'), ((26039, 26211), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob103']", "self.weights['net3_deconv2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob103'], self.weights['net3_deconv2_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64],\n strides=[1, 2, 2, 1])\n", (26061, 26211), True, 'import tensorflow as tf\n'), ((26324, 26512), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob104']", "self.weights['net3_net3_upsample_flow3to2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob104'], self.weights[\n 'net3_net3_upsample_flow3to2_w'], output_shape=[batch_size, \n ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2], strides=[1, 2, 2, 1])\n", (26346, 26512), True, 'import tensorflow as tf\n'), ((26673, 26783), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob107']", "self.weights['net3_predict_conv2_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob107'], self.weights['net3_predict_conv2_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (26685, 26783), True, 'import tensorflow as tf\n'), ((27729, 27832), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob110']", "self.weights['netsd_conv0_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob110'], self.weights['netsd_conv0_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (27741, 27832), True, 'import tensorflow as tf\n'), ((28034, 28138), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob112']", "self.weights['netsd_conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob112'], self.weights['netsd_conv1_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (28046, 28138), True, 'import tensorflow as tf\n'), ((28258, 28363), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob112']", "self.weights['netsd_conv1_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob112'], self.weights['netsd_conv1_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (28270, 28363), True, 'import tensorflow as tf\n'), ((28575, 28679), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob114']", "self.weights['netsd_conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob114'], self.weights['netsd_conv2_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (28587, 28679), True, 'import tensorflow as tf\n'), ((28799, 28904), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob114']", "self.weights['netsd_conv2_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob114'], self.weights['netsd_conv2_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (28811, 28904), True, 'import tensorflow as tf\n'), ((29116, 29220), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob116']", "self.weights['netsd_conv3_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob116'], self.weights['netsd_conv3_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (29128, 29220), True, 'import tensorflow as tf\n'), ((29340, 29445), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob116']", "self.weights['netsd_conv3_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob116'], self.weights['netsd_conv3_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (29352, 29445), True, 'import tensorflow as tf\n'), ((29657, 29761), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob118']", "self.weights['netsd_conv4_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob118'], self.weights['netsd_conv4_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (29669, 29761), True, 'import tensorflow as tf\n'), ((29881, 29986), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob118']", "self.weights['netsd_conv4_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob118'], self.weights['netsd_conv4_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (29893, 29986), True, 'import tensorflow as tf\n'), ((30198, 30302), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob120']", "self.weights['netsd_conv5_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob120'], self.weights['netsd_conv5_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (30210, 30302), True, 'import tensorflow as tf\n'), ((30422, 30527), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob120']", "self.weights['netsd_conv5_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob120'], self.weights['netsd_conv5_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (30434, 30527), True, 'import tensorflow as tf\n'), ((30739, 30843), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob122']", "self.weights['netsd_conv6_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob122'], self.weights['netsd_conv6_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (30751, 30843), True, 'import tensorflow as tf\n'), ((30963, 31068), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob122']", "self.weights['netsd_conv6_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob122'], self.weights['netsd_conv6_1_w'], strides=[1,\n 1, 1, 1], padding='SAME')\n", (30975, 31068), True, 'import tensorflow as tf\n'), ((31190, 31300), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob123']", "self.weights['netsd_Convolution1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob123'], self.weights['netsd_Convolution1_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (31202, 31300), True, 'import tensorflow as tf\n'), ((31369, 31545), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob123']", "self.weights['netsd_deconv5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob123'], self.weights['netsd_deconv5_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 512],\n strides=[1, 2, 2, 1])\n", (31391, 31545), True, 'import tensorflow as tf\n'), ((31667, 31852), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob124']", "self.weights['netsd_upsample_flow6to5_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 32, ADAPTED_WIDTH / 32, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob124'], self.weights[\n 'netsd_upsample_flow6to5_w'], output_shape=[batch_size, ADAPTED_HEIGHT /\n 32, ADAPTED_WIDTH / 32, 2], strides=[1, 2, 2, 1])\n", (31689, 31852), True, 'import tensorflow as tf\n'), ((32019, 32128), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob127']", "self.weights['netsd_interconv5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob127'], self.weights['netsd_interconv5_w'], strides=\n [1, 1, 1, 1], padding='SAME')\n", (32031, 32128), True, 'import tensorflow as tf\n'), ((32194, 32304), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob128']", "self.weights['netsd_Convolution2_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob128'], self.weights['netsd_Convolution2_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (32206, 32304), True, 'import tensorflow as tf\n'), ((32365, 32541), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob127']", "self.weights['netsd_deconv4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob127'], self.weights['netsd_deconv4_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 256],\n strides=[1, 2, 2, 1])\n", (32387, 32541), True, 'import tensorflow as tf\n'), ((32663, 32848), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob129']", "self.weights['netsd_upsample_flow5to4_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 16, ADAPTED_WIDTH / 16, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob129'], self.weights[\n 'netsd_upsample_flow5to4_w'], output_shape=[batch_size, ADAPTED_HEIGHT /\n 16, ADAPTED_WIDTH / 16, 2], strides=[1, 2, 2, 1])\n", (32685, 32848), True, 'import tensorflow as tf\n'), ((33023, 33132), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob132']", "self.weights['netsd_interconv4_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob132'], self.weights['netsd_interconv4_w'], strides=\n [1, 1, 1, 1], padding='SAME')\n", (33035, 33132), True, 'import tensorflow as tf\n'), ((33198, 33308), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob133']", "self.weights['netsd_Convolution3_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob133'], self.weights['netsd_Convolution3_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (33210, 33308), True, 'import tensorflow as tf\n'), ((33369, 33543), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob132']", "self.weights['netsd_deconv3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob132'], self.weights['netsd_deconv3_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 128],\n strides=[1, 2, 2, 1])\n", (33391, 33543), True, 'import tensorflow as tf\n'), ((33665, 33848), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob134']", "self.weights['netsd_upsample_flow4to3_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 8, ADAPTED_WIDTH / 8, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob134'], self.weights[\n 'netsd_upsample_flow4to3_w'], output_shape=[batch_size, ADAPTED_HEIGHT /\n 8, ADAPTED_WIDTH / 8, 2], strides=[1, 2, 2, 1])\n", (33687, 33848), True, 'import tensorflow as tf\n'), ((34015, 34124), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob137']", "self.weights['netsd_interconv3_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob137'], self.weights['netsd_interconv3_w'], strides=\n [1, 1, 1, 1], padding='SAME')\n", (34027, 34124), True, 'import tensorflow as tf\n'), ((34190, 34300), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob138']", "self.weights['netsd_Convolution4_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob138'], self.weights['netsd_Convolution4_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (34202, 34300), True, 'import tensorflow as tf\n'), ((34361, 34534), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob137']", "self.weights['netsd_deconv2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob137'], self.weights['netsd_deconv2_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 64],\n strides=[1, 2, 2, 1])\n", (34383, 34534), True, 'import tensorflow as tf\n'), ((34648, 34831), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob139']", "self.weights['netsd_upsample_flow3to2_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 4, ADAPTED_WIDTH / 4, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob139'], self.weights[\n 'netsd_upsample_flow3to2_w'], output_shape=[batch_size, ADAPTED_HEIGHT /\n 4, ADAPTED_WIDTH / 4, 2], strides=[1, 2, 2, 1])\n", (34670, 34831), True, 'import tensorflow as tf\n'), ((34990, 35099), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob142']", "self.weights['netsd_interconv2_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob142'], self.weights['netsd_interconv2_w'], strides=\n [1, 1, 1, 1], padding='SAME')\n", (35002, 35099), True, 'import tensorflow as tf\n'), ((35165, 35275), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob143']", "self.weights['netsd_Convolution5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob143'], self.weights['netsd_Convolution5_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (35177, 35275), True, 'import tensorflow as tf\n'), ((36815, 36917), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob156']", "self.weights['fuse_conv0_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob156'], self.weights['fuse_conv0_w'], strides=[1, 1,\n 1, 1], padding='SAME')\n", (36827, 36917), True, 'import tensorflow as tf\n'), ((37118, 37221), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob158']", "self.weights['fuse_conv1_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob158'], self.weights['fuse_conv1_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (37130, 37221), True, 'import tensorflow as tf\n'), ((37340, 37445), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob158']", "self.weights['fuse_conv1_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob158'], self.weights['fuse_conv1_1_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (37352, 37445), True, 'import tensorflow as tf\n'), ((37655, 37758), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob160']", "self.weights['fuse_conv2_w']"], {'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(blobs['blob160'], self.weights['fuse_conv2_w'], strides=[1, 2,\n 2, 1], padding='VALID')\n", (37667, 37758), True, 'import tensorflow as tf\n'), ((37877, 37982), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob160']", "self.weights['fuse_conv2_1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob160'], self.weights['fuse_conv2_1_w'], strides=[1, \n 1, 1, 1], padding='SAME')\n", (37889, 37982), True, 'import tensorflow as tf\n'), ((38110, 38220), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob161']", "self.weights['fuse__Convolution5_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob161'], self.weights['fuse__Convolution5_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (38122, 38220), True, 'import tensorflow as tf\n'), ((38289, 38461), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob161']", "self.weights['fuse_deconv1_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 2, ADAPTED_WIDTH / 2, 32]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob161'], self.weights['fuse_deconv1_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 2, ADAPTED_WIDTH / 2, 32],\n strides=[1, 2, 2, 1])\n", (38311, 38461), True, 'import tensorflow as tf\n'), ((38574, 38756), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob162']", "self.weights['fuse_upsample_flow2to1_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 2, ADAPTED_WIDTH / 2, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob162'], self.weights[\n 'fuse_upsample_flow2to1_w'], output_shape=[batch_size, ADAPTED_HEIGHT /\n 2, ADAPTED_WIDTH / 2, 2], strides=[1, 2, 2, 1])\n", (38596, 38756), True, 'import tensorflow as tf\n'), ((38914, 39022), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob165']", "self.weights['fuse_interconv1_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob165'], self.weights['fuse_interconv1_w'], strides=[\n 1, 1, 1, 1], padding='SAME')\n", (38926, 39022), True, 'import tensorflow as tf\n'), ((39087, 39197), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob166']", "self.weights['fuse__Convolution6_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob166'], self.weights['fuse__Convolution6_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (39099, 39197), True, 'import tensorflow as tf\n'), ((39258, 39430), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob165']", "self.weights['fuse_deconv0_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT / 1, ADAPTED_WIDTH / 1, 16]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob165'], self.weights['fuse_deconv0_w'],\n output_shape=[batch_size, ADAPTED_HEIGHT / 1, ADAPTED_WIDTH / 1, 16],\n strides=[1, 2, 2, 1])\n", (39280, 39430), True, 'import tensorflow as tf\n'), ((39543, 39717), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (["blobs['blob167']", "self.weights['fuse_upsample_flow1to0_w']"], {'output_shape': '[batch_size, ADAPTED_HEIGHT, ADAPTED_WIDTH, 2]', 'strides': '[1, 2, 2, 1]'}), "(blobs['blob167'], self.weights[\n 'fuse_upsample_flow1to0_w'], output_shape=[batch_size, ADAPTED_HEIGHT,\n ADAPTED_WIDTH, 2], strides=[1, 2, 2, 1])\n", (39565, 39717), True, 'import tensorflow as tf\n'), ((39879, 39987), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob170']", "self.weights['fuse_interconv0_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob170'], self.weights['fuse_interconv0_w'], strides=[\n 1, 1, 1, 1], padding='SAME')\n", (39891, 39987), True, 'import tensorflow as tf\n'), ((40052, 40162), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (["blobs['blob171']", "self.weights['fuse__Convolution7_w']"], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(blobs['blob171'], self.weights['fuse__Convolution7_w'],\n strides=[1, 1, 1, 1], padding='SAME')\n", (40064, 40162), True, 'import tensorflow as tf\n'), ((2294, 2339), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(x ** 2)'], {'axis': '(3)', 'keep_dims': '(True)'}), '(x ** 2, axis=3, keep_dims=True)\n', (2307, 2339), True, 'import tensorflow as tf\n'), ((2433, 2446), 'tensorflow.shape', 'tf.shape', (['im0'], {}), '(im0)\n', (2441, 2446), True, 'import tensorflow as tf\n'), ((2479, 2492), 'tensorflow.shape', 'tf.shape', (['im0'], {}), '(im0)\n', (2487, 2492), True, 'import tensorflow as tf\n'), ((2526, 2539), 'tensorflow.shape', 'tf.shape', (['im0'], {}), '(im0)\n', (2534, 2539), True, 'import tensorflow as tf\n'), ((5590, 5651), 'tensorflow.pad', 'tf.pad', (["blobs['conv3a']", '[[0, 0], [20, 20], [20, 20], [0, 0]]'], {}), "(blobs['conv3a'], [[0, 0], [20, 20], [20, 20], [0, 0]])\n", (5596, 5651), True, 'import tensorflow as tf\n'), ((5669, 5754), 'tensorflow.pad', 'tf.pad', (["blobs['conv3b']", '[[0, 0], [20 - di, 20 + di], [20 - dj, 20 + dj], [0, 0]]'], {}), "(blobs['conv3b'], [[0, 0], [20 - di, 20 + di], [20 - dj, 20 + dj], [0,\n 0]])\n", (5675, 5754), True, 'import tensorflow as tf\n'), ((2671, 2689), 'tensorflow.to_float', 'tf.to_float', (['width'], {}), '(width)\n', (2682, 2689), True, 'import tensorflow as tf\n'), ((2755, 2774), 'tensorflow.to_float', 'tf.to_float', (['height'], {}), '(height)\n', (2766, 2774), True, 'import tensorflow as tf\n'), ((5843, 5866), 'tensorflow.ones', 'tf.ones', (['[1, 1, 256, 1]'], {}), '([1, 1, 256, 1])\n', (5850, 5866), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 7 14:40:40 2021 @author: victorsellemi """ import numpy as np def filter_MA(Y,q = 2): """ DESCRIPTION: Decompose a time series into a trend and stationary component using the moving average (MA) filter (i.e., low pass filter) INPUT: Y = (T x 1) vector of time series data q = scalar value of moving average (half) window: default = 2 OUTPUT: trend = (T x 1) vector of trend component of the time series, i.e., low frequency component error = (T x 1) vector of stationary part of the time series """ # length of time series T = Y.shape[0] # window width Q = 2*q # border of the series is preserved p1 = np.concatenate((np.eye(q), np.zeros((q,T-q))), axis = 1) p2 = np.zeros((T-Q,T)) p3 = np.concatenate((np.zeros((q,T-q)), np.eye(q)), axis = 1) P = np.concatenate((p1,p2,p3), axis = 0) # part of the series to be averaged X = np.eye(T-Q) Z = np.zeros((T-Q,1)) for i in range(Q): # update X X = np.concatenate((X, np.zeros((T-Q,1))), axis = 1) + np.concatenate((Z, np.eye(T-Q)), axis = 1) # update Z Z = np.concatenate((Z, np.zeros((T-Q,1))), axis = 1) X = np.concatenate((np.zeros((q,T)), X, np.zeros((q,T))), axis = 0) # construct linear filter L = P + (1/(Q+1)) * X # construct the trend trend = L.dot(Y) # construct stationary component signal = Y - trend return trend,signal
[ "numpy.eye", "numpy.zeros", "numpy.concatenate" ]
[((877, 897), 'numpy.zeros', 'np.zeros', (['(T - Q, T)'], {}), '((T - Q, T))\n', (885, 897), True, 'import numpy as np\n'), ((970, 1006), 'numpy.concatenate', 'np.concatenate', (['(p1, p2, p3)'], {'axis': '(0)'}), '((p1, p2, p3), axis=0)\n', (984, 1006), True, 'import numpy as np\n'), ((1060, 1073), 'numpy.eye', 'np.eye', (['(T - Q)'], {}), '(T - Q)\n', (1066, 1073), True, 'import numpy as np\n'), ((1080, 1100), 'numpy.zeros', 'np.zeros', (['(T - Q, 1)'], {}), '((T - Q, 1))\n', (1088, 1100), True, 'import numpy as np\n'), ((827, 836), 'numpy.eye', 'np.eye', (['q'], {}), '(q)\n', (833, 836), True, 'import numpy as np\n'), ((838, 858), 'numpy.zeros', 'np.zeros', (['(q, T - q)'], {}), '((q, T - q))\n', (846, 858), True, 'import numpy as np\n'), ((920, 940), 'numpy.zeros', 'np.zeros', (['(q, T - q)'], {}), '((q, T - q))\n', (928, 940), True, 'import numpy as np\n'), ((939, 948), 'numpy.eye', 'np.eye', (['q'], {}), '(q)\n', (945, 948), True, 'import numpy as np\n'), ((1387, 1403), 'numpy.zeros', 'np.zeros', (['(q, T)'], {}), '((q, T))\n', (1395, 1403), True, 'import numpy as np\n'), ((1407, 1423), 'numpy.zeros', 'np.zeros', (['(q, T)'], {}), '((q, T))\n', (1415, 1423), True, 'import numpy as np\n'), ((1319, 1339), 'numpy.zeros', 'np.zeros', (['(T - Q, 1)'], {}), '((T - Q, 1))\n', (1327, 1339), True, 'import numpy as np\n'), ((1185, 1205), 'numpy.zeros', 'np.zeros', (['(T - Q, 1)'], {}), '((T - Q, 1))\n', (1193, 1205), True, 'import numpy as np\n'), ((1236, 1249), 'numpy.eye', 'np.eye', (['(T - Q)'], {}), '(T - Q)\n', (1242, 1249), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 19 18:08:01 2020 @author: <NAME> Implementação do ajuste do modelo SEIIHURD com separação de grupos. Necessita de mais verificações e funções para simplificar o input. Baseado nas classes disponíveis no modelos.py """ import numpy as np from functools import reduce import scipy.integrate as spi from scipy.optimize import least_squares from platypus import NSGAII, Problem, Real from pyswarms.single.global_best import GlobalBestPSO import pyswarms as ps from pyswarms.backend.topology import Star from pyswarms.utils.plotters import plot_cost_history from itertools import repeat import multiprocessing as mp import copy import joblib ''' Social contact matrices from PREM, Kiesha; COOK, <NAME>.; <NAME>. Projecting social contact matrices in 152 countries using contact surveys and demographic data. PLoS computational biology, v. 13, n. 9, p. e1005697, 2017. ''' ages_Mu_min = 5 * np.arange(16) Mu_house = np.array([[0.47868515, 0.50507561, 0.29848922, 0.15763748, 0.26276959, 0.40185462, 0.46855027, 0.42581354, 0.2150961 , 0.0856771 , 0.08705463, 0.07551931, 0.05129175, 0.02344832, 0.00793644, 0.01072846], [0.35580205, 0.77874482, 0.51392686, 0.21151069, 0.08597966, 0.28306027, 0.49982218, 0.52854893, 0.41220947, 0.15848728, 0.07491245, 0.07658339, 0.04772343, 0.02588962, 0.01125956, 0.01073152], [0.25903114, 0.63488713, 1.36175618, 0.50016515, 0.11748191, 0.10264613, 0.24113458, 0.47274372, 0.54026417, 0.26708819, 0.11007723, 0.04406045, 0.02746409, 0.02825033, 0.02044872, 0.01214665], [0.14223192, 0.24383932, 0.53761638, 1.05325205, 0.28778496, 0.10925453, 0.0651564 , 0.2432454 , 0.39011334, 0.41381277, 0.23194909, 0.07541471, 0.03428398, 0.02122257, 0.01033573, 0.00864859], [0.27381886, 0.15430529, 0.16053062, 0.5104134 , 0.95175366, 0.3586594 , 0.09248672, 0.04774269, 0.15814197, 0.36581739, 0.25544811, 0.13338965, 0.03461345, 0.01062458, 0.00844199, 0.00868782], [0.59409802, 0.26971847, 0.10669146, 0.18330524, 0.39561893, 0.81955947, 0.26376865, 0.06604084, 0.03824556, 0.11560004, 0.23218163, 0.15331788, 0.07336147, 0.02312255, 0.00412646, 0.01025778], [0.63860889, 0.75760606, 0.43109156, 0.09913293, 0.13935789, 0.32056062, 0.65710277, 0.25488454, 0.1062129 , 0.0430932 , 0.06880784, 0.09938458, 0.09010691, 0.02233902, 0.01155556, 0.00695246], [0.56209348, 0.87334544, 0.75598244, 0.33199136, 0.07233271, 0.08674171, 0.20243583, 0.60062714, 0.17793601, 0.06307045, 0.04445926, 0.04082447, 0.06275133, 0.04051762, 0.01712777, 0.00598721], [0.35751289, 0.66234582, 0.77180208, 0.54993616, 0.17368099, 0.07361914, 0.13016852, 0.19937327, 0.46551558, 0.15412263, 0.06123041, 0.0182514 , 0.04234381, 0.04312892, 0.01656267, 0.01175358], [0.208131 , 0.41591452, 0.56510014, 0.67760241, 0.38146504, 0.14185001, 0.06160354, 0.12945701, 0.16470166, 0.41150841, 0.14596804, 0.04404807, 0.02395316, 0.01731295, 0.01469059, 0.02275339], [0.30472548, 0.26744442, 0.41631962, 0.46516888, 0.41751365, 0.28520772, 0.13931619, 0.07682945, 0.11404965, 0.16122096, 0.33813266, 0.1349378 , 0.03755396, 0.01429426, 0.01356763, 0.02551792], [0.52762004, 0.52787011, 0.33622117, 0.43037934, 0.36416323, 0.42655672, 0.33780201, 0.13492044, 0.0798784 , 0.15795568, 0.20367727, 0.33176385, 0.12256126, 0.05573807, 0.0124446 , 0.02190564], [0.53741472, 0.50750067, 0.3229994 , 0.30706704, 0.21340314, 0.27424513, 0.32838657, 0.26023515, 0.13222548, 0.07284901, 0.11950584, 0.16376401, 0.25560123, 0.09269703, 0.02451284, 0.00631762], [0.37949376, 0.55324102, 0.47449156, 0.24796638, 0.19276924, 0.20675484, 0.3267867 , 0.39525729, 0.3070043 , 0.10088992, 0.10256839, 0.13016641, 0.1231421 , 0.24067708, 0.05475668, 0.01401368], [0.16359554, 0.48536065, 0.40533723, 0.31542539, 0.06890518, 0.15670328, 0.12884062, 0.27912381, 0.25685832, 0.20143856, 0.12497647, 0.07565566, 0.10331686, 0.08830789, 0.15657321, 0.05744065], [0.29555039, 0.39898035, 0.60257982, 0.5009724 , 0.13799378, 0.11716593, 0.14366306, 0.31602298, 0.34691652, 0.30960511, 0.31253708, 0.14557295, 0.06065554, 0.10654772, 0.06390924, 0.09827735]]) Mu_school = np.array([[3.21885854e-001, 4.31659966e-002, 7.88269419e-003, 8.09548363e-003, 5.35038146e-003, 2.18201974e-002, 4.01633514e-002, 2.99376002e-002, 1.40680283e-002, 1.66587853e-002, 9.47774696e-003, 7.41041622e-003, 1.28200661e-003, 7.79120405e-004, 8.23608272e-066, 6.37926405e-120], [5.40133328e-002, 4.84870697e+000, 2.70046494e-001, 3.14778450e-002, 3.11206331e-002, 8.56826951e-002, 1.08251879e-001, 9.46101139e-002, 8.63528188e-002, 5.51141159e-002, 4.19385198e-002, 1.20958942e-002, 4.77242219e-003, 1.39787217e-003, 3.47452943e-004, 8.08973738e-039], [4.56461982e-004, 1.04840235e+000, 6.09152459e+000, 1.98915822e-001, 1.99709921e-002, 6.68319525e-002, 6.58949586e-002, 9.70851505e-002, 9.54147078e-002, 6.70538232e-002, 4.24864096e-002, 1.98701346e-002, 5.11869429e-003, 7.27320438e-004, 4.93746124e-025, 1.82153965e-004], [2.59613205e-003, 4.73315233e-002, 1.99337834e+000, 7.20040500e+000, 8.57326037e-002, 7.90668822e-002, 8.54208542e-002, 1.10816964e-001, 8.76955236e-002, 9.22975521e-002, 4.58035025e-002, 2.51130956e-002, 5.71391798e-003, 1.07818752e-003, 6.21174558e-033, 1.70710246e-070], [7.19158720e-003, 2.48833195e-002, 9.89727235e-003, 8.76815025e-001, 4.33963352e-001, 5.05185217e-002, 3.30594492e-002, 3.81384107e-002, 2.34709676e-002, 2.67235372e-002, 1.32913985e-002, 9.00655556e-003, 6.94913059e-004, 1.25675951e-003, 1.77164197e-004, 1.21957619e-047], [7.04119204e-003, 1.19412206e-001, 3.75016980e-002, 2.02193056e-001, 2.79822908e-001, 1.68610223e-001, 2.86939363e-002, 3.56961469e-002, 4.09234494e-002, 3.32290896e-002, 8.12074348e-003, 1.26152144e-002, 4.27869081e-003, 2.41737477e-003, 4.63116893e-004, 1.28597237e-003], [1.41486320e-002, 3.86561429e-001, 2.55902236e-001, 1.69973534e-001, 4.98104010e-002, 8.98122446e-002, 7.95333394e-002, 5.19274611e-002, 5.46612930e-002, 2.64567137e-002, 2.03241595e-002, 2.96263220e-003, 5.42888613e-003, 4.47585970e-004, 1.65440335e-048, 3.11189454e-055], [2.40945305e-002, 2.11030046e-001, 1.54767246e-001, 8.17929897e-002, 1.84061608e-002, 5.43009779e-002, 7.39351186e-002, 5.21677009e-002, 5.63267084e-002, 2.51807147e-002, 3.53972554e-003, 7.96646343e-003, 5.56929776e-004, 2.08530461e-003, 1.84428290e-123, 9.69555083e-067], [7.81313905e-003, 1.14371898e-001, 9.09011945e-002, 3.80212104e-001, 8.54533192e-003, 2.62430162e-002, 2.51880009e-002, 3.22563508e-002, 6.73506045e-002, 2.24997143e-002, 2.39241043e-002, 6.50627191e-003, 5.50892674e-003, 4.78308850e-004, 4.81213215e-068, 2.40231425e-092], [6.55265016e-002, 2.31163536e-001, 1.49970765e-001, 5.53563093e-001, 5.74032526e-003, 3.02865481e-002, 5.72506883e-002, 4.70559232e-002, 4.28736553e-002, 2.42614518e-002, 2.86665377e-002, 1.29570473e-002, 3.24362518e-003, 1.67930318e-003, 6.20916950e-134, 3.27297624e-072], [1.72765646e-002, 3.43744913e-001, 4.30902785e-001, 4.74293073e-001, 5.39328187e-003, 1.44128740e-002, 3.95545363e-002, 3.73781860e-002, 4.56834488e-002, 5.92135906e-002, 2.91473801e-002, 1.54857502e-002, 4.53105390e-003, 8.87272668e-024, 1.23797452e-117, 5.64262349e-078], [6.14363036e-002, 2.98367348e-001, 2.59092700e-001, 3.00800812e-001, 5.92454596e-003, 5.26458862e-002, 2.02188672e-002, 3.27897605e-002, 4.07753741e-002, 2.83422407e-002, 2.43657809e-002, 2.73993226e-002, 8.87990718e-003, 1.13279180e-031, 7.81960493e-004, 7.62467510e-004], [3.63695643e-002, 5.96870355e-002, 3.05072624e-002, 1.45523978e-001, 1.26062984e-002, 1.69458169e-003, 1.55127292e-002, 4.22097670e-002, 9.21792425e-003, 1.42200652e-002, 1.10967529e-002, 5.77020348e-003, 2.04474044e-002, 1.11075734e-002, 4.42271199e-067, 2.12068625e-037], [1.67937029e-003, 2.72971001e-002, 1.05886266e-002, 7.61087735e-032, 1.97191559e-003, 1.92885006e-003, 1.24343737e-002, 5.39297787e-003, 5.41684968e-003, 8.63502071e-003, 1.94554498e-003, 1.49082274e-002, 8.11781100e-003, 1.74395489e-002, 1.11239023e-002, 3.45693088e-126], [1.28088348e-028, 5.11065200e-026, 1.93019797e-040, 7.60476035e-003, 2.63586947e-022, 1.69749024e-024, 1.25875005e-026, 7.62109877e-003, 7.84979948e-003, 2.11516023e-002, 3.52117832e-002, 2.14360383e-002, 7.73902109e-003, 8.01328325e-003, 7.91285055e-003, 2.13825814e-002], [2.81655586e-094, 2.11305187e-002, 8.46562506e-042, 2.12592841e-002, 4.89802057e-036, 7.59232387e-003, 9.77247001e-069, 2.23108239e-060, 1.43715978e-048, 8.56015694e-060, 4.69469043e-042, 1.59822047e-046, 2.20978550e-083, 8.85861277e-107, 1.02042815e-080, 6.61413913e-113]]) Mu_work = np.array([[0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 8.20604524e-092, 1.20585150e-005, 3.16436834e-125], [0.00000000e+000, 1.16840561e-003, 9.90713236e-072, 4.42646396e-059, 2.91874286e-006, 9.98773031e-003, 2.58779981e-002, 5.66104376e-003, 2.12699812e-002, 5.72117462e-003, 1.48212306e-003, 1.23926126e-003, 1.28212945e-056, 1.34955578e-005, 7.64591325e-079, 2.38392073e-065], [0.00000000e+000, 2.56552144e-003, 1.12756182e-001, 2.40351143e-002, 2.62981485e-002, 7.56512432e-003, 6.19587609e-002, 1.73269871e-002, 5.87405128e-002, 3.26749742e-002, 1.24709193e-002, 2.93054408e-008, 3.71596993e-017, 2.79780317e-053, 4.95800770e-006, 3.77718083e-102], [0.00000000e+000, 1.07213881e-002, 4.28390448e-002, 7.22769090e-001, 5.93479736e-001, 3.39341952e-001, 3.17013715e-001, 2.89168861e-001, 3.11143180e-001, 2.34889238e-001, 1.32953769e-001, 6.01944097e-002, 1.47306181e-002, 8.34699602e-006, 2.85972822e-006, 1.88926122e-031], [0.00000000e+000, 9.14252587e-003, 5.74508682e-002, 4.00000235e-001, 7.93386618e-001, 7.55975146e-001, 6.32277283e-001, 6.83601459e-001, 4.98506972e-001, 3.82309992e-001, 2.81363576e-001, 1.23338103e-001, 4.15708021e-002, 9.86113407e-006, 1.32609387e-005, 3.74318048e-006], [0.00000000e+000, 1.04243481e-002, 7.34587492e-002, 3.49556755e-001, 7.50680101e-001, 1.25683393e+000, 9.01245714e-001, 8.63446835e-001, 7.70443641e-001, 5.17237071e-001, 4.09810981e-001, 1.80645400e-001, 5.51284783e-002, 1.60674627e-005, 1.01182608e-005, 3.01442534e-006], [0.00000000e+000, 1.65842404e-002, 8.34076781e-002, 1.89301935e-001, 5.21246906e-001, 8.54460001e-001, 1.12054931e+000, 9.64310078e-001, 8.34675180e-001, 6.52534012e-001, 3.79383514e-001, 2.11198205e-001, 5.17285688e-002, 1.63795563e-005, 4.10100851e-006, 3.49478980e-006], [0.00000000e+000, 1.11666639e-002, 5.03319748e-002, 3.70510313e-001, 4.24294782e-001, 7.87535547e-001, 8.45085693e-001, 1.14590365e+000, 1.07673077e+000, 7.13492115e-001, 5.00740004e-001, 1.90102207e-001, 3.59740115e-002, 1.22988530e-005, 9.13512833e-006, 6.02097416e-006], [0.00000000e+000, 6.07792440e-003, 5.49337607e-002, 2.23499535e-001, 4.82353827e-001, 7.52291991e-001, 8.89187601e-001, 9.33765370e-001, 1.10492283e+000, 8.50124391e-001, 5.88941528e-001, 1.94947085e-001, 5.09477228e-002, 1.43626161e-005, 1.02721567e-005, 1.29503893e-005], [0.00000000e+000, 3.31622551e-003, 7.01829848e-002, 2.67512972e-001, 3.14796392e-001, 5.41516885e-001, 6.95769048e-001, 7.50620518e-001, 7.50038547e-001, 7.00954088e-001, 4.35197983e-001, 2.11283335e-001, 3.88576200e-002, 1.62810370e-005, 1.08243610e-005, 6.09172339e-006], [0.00000000e+000, 4.39576425e-004, 7.17737968e-002, 1.89254612e-001, 2.47832532e-001, 5.16027731e-001, 6.02783971e-001, 6.15949277e-001, 8.05581107e-001, 7.44063535e-001, 5.44855374e-001, 2.52198706e-001, 4.39235685e-002, 1.18079721e-005, 1.18226645e-005, 1.01613165e-005], [0.00000000e+000, 4.91737561e-003, 1.08686672e-001, 1.24987806e-001, 1.64110983e-001, 3.00118829e-001, 4.18159745e-001, 3.86897613e-001, 4.77718241e-001, 3.60854250e-001, 3.22466456e-001, 1.92516925e-001, 4.07209694e-002, 1.34978304e-005, 6.58739925e-006, 6.65716756e-006], [0.00000000e+000, 6.35447018e-004, 3.96329620e-002, 1.83072502e-002, 7.04596701e-002, 1.24861117e-001, 1.37834574e-001, 1.59845720e-001, 1.66933479e-001, 1.56084857e-001, 1.14949158e-001, 8.46570798e-002, 1.50879843e-002, 2.03019580e-005, 8.26102156e-006, 1.48398182e-005], [7.60299521e-006, 3.36326754e-006, 7.64855296e-006, 2.27621532e-005, 3.14933351e-005, 7.89308410e-005, 7.24212842e-005, 2.91748203e-005, 6.61873732e-005, 5.95693238e-005, 7.70713500e-005, 5.30687748e-005, 4.66030117e-005, 1.41633235e-005, 2.49066205e-005, 1.19109038e-005], [5.78863840e-055, 7.88785149e-042, 2.54830412e-006, 2.60648191e-005, 1.68036205e-005, 2.12446739e-005, 3.57267603e-005, 4.02377033e-005, 3.56401935e-005, 3.09769252e-005, 2.13053382e-005, 4.49709414e-005, 2.61368373e-005, 1.68266203e-005, 1.66514322e-005, 2.60822813e-005], [2.35721271e-141, 9.06871674e-097, 1.18637122e-089, 9.39934076e-022, 4.66000452e-005, 4.69664011e-005, 4.69316082e-005, 8.42184044e-005, 2.77788168e-005, 1.03294378e-005, 1.06803618e-005, 7.26341826e-075, 1.10073971e-065, 1.02831671e-005, 5.16902994e-049, 8.28040509e-043]]) Mu_other = np.array([[0.95537734, 0.46860132, 0.27110607, 0.19447667, 0.32135073, 0.48782072, 0.54963024, 0.42195593, 0.27152038, 0.17864251, 0.20155642, 0.16358271, 0.1040159 , 0.0874149 , 0.05129938, 0.02153823], [0.51023519, 2.17757364, 0.9022516 , 0.24304235, 0.20119518, 0.39689588, 0.47242431, 0.46949918, 0.37741651, 0.16843746, 0.12590504, 0.12682331, 0.11282247, 0.08222718, 0.03648526, 0.02404257], [0.18585796, 1.11958124, 4.47729443, 0.67959759, 0.43936317, 0.36934142, 0.41566744, 0.44467286, 0.48797422, 0.28795385, 0.17659191, 0.10674831, 0.07175567, 0.07249261, 0.04815305, 0.03697862], [0.09854482, 0.3514869 , 1.84902386, 5.38491613, 1.27425161, 0.59242579, 0.36578735, 0.39181798, 0.38131832, 0.31501028, 0.13275648, 0.06408612, 0.04499218, 0.04000664, 0.02232326, 0.01322698], [0.13674436, 0.1973461 , 0.33264088, 2.08016394, 3.28810184, 1.29198125, 0.74642201, 0.44357051, 0.32781391, 0.35511243, 0.20132011, 0.12961 , 0.04994553, 0.03748657, 0.03841073, 0.02700581], [0.23495203, 0.13839031, 0.14085679, 0.5347385 , 1.46021275, 1.85222022, 1.02681162, 0.61513602, 0.39086271, 0.32871844, 0.25938947, 0.13520412, 0.05101963, 0.03714278, 0.02177751, 0.00979745], [0.23139098, 0.18634831, 0.32002214, 0.2477269 , 0.64111274, 0.93691022, 1.14560725, 0.73176025, 0.43760432, 0.31057135, 0.29406937, 0.20632155, 0.09044896, 0.06448983, 0.03041877, 0.02522842], [0.18786196, 0.25090485, 0.21366969, 0.15358412, 0.35761286, 0.62390736, 0.76125666, 0.82975354, 0.54980593, 0.32778339, 0.20858991, 0.1607099 , 0.13218526, 0.09042909, 0.04990491, 0.01762718], [0.12220241, 0.17968132, 0.31826246, 0.19846971, 0.34823183, 0.41563737, 0.55930999, 0.54070187, 0.5573184 , 0.31526474, 0.20194048, 0.09234293, 0.08377534, 0.05819374, 0.0414762 , 0.01563101], [0.03429527, 0.06388018, 0.09407867, 0.17418896, 0.23404519, 0.28879108, 0.34528852, 0.34507961, 0.31461973, 0.29954426, 0.21759668, 0.09684718, 0.06596679, 0.04274337, 0.0356891 , 0.02459849], [0.05092152, 0.10829561, 0.13898902, 0.2005828 , 0.35807132, 0.45181815, 0.32281821, 0.28014803, 0.30125545, 0.31260137, 0.22923948, 0.17657382, 0.10276889, 0.05555467, 0.03430327, 0.02064256], [0.06739051, 0.06795035, 0.0826437 , 0.09522087, 0.23309189, 0.39055444, 0.39458465, 0.29290532, 0.27204846, 0.17810118, 0.24399007, 0.22146653, 0.13732849, 0.07585801, 0.03938794, 0.0190908 ], [0.04337917, 0.05375367, 0.05230119, 0.08066901, 0.16619572, 0.25423056, 0.25580913, 0.27430323, 0.22478799, 0.16909017, 0.14284879, 0.17211604, 0.14336033, 0.10344522, 0.06797049, 0.02546014], [0.04080687, 0.06113728, 0.04392062, 0.04488748, 0.12808591, 0.19886058, 0.24542711, 0.19678011, 0.17800136, 0.13147441, 0.13564091, 0.14280335, 0.12969805, 0.11181631, 0.05550193, 0.02956066], [0.01432324, 0.03441212, 0.05604694, 0.10154456, 0.09204 , 0.13341443, 0.13396901, 0.16682638, 0.18562675, 0.1299677 , 0.09922375, 0.09634331, 0.15184583, 0.13541738, 0.1169359 , 0.03805293], [0.01972631, 0.02274412, 0.03797545, 0.02036785, 0.04357298, 0.05783639, 0.10706321, 0.07688271, 0.06969759, 0.08029393, 0.05466604, 0.05129046, 0.04648653, 0.06132882, 0.05004289, 0.03030569]]) def generate_reduced_matrices(age_sep, Ni): ''' Receives the age_separation and populations to generate the average contact matrices, returns a (4, len(age_sep)+1, len(age_sep)+1) with the 4 partial contact matrices: house, school, work and other Ni is the population for each population component (16 5-years age groups) ''' nMat = len(age_sep) + 1 Ms = np.empty((4, nMat, nMat)) age_indexes = list() age_indexes.append(np.flatnonzero(ages_Mu_min <= age_sep[0])) for i in range(1, len(age_sep)): age_indexes.append(np.flatnonzero((ages_Mu_min > age_sep[i-1]) * (ages_Mu_min <= age_sep[i]))) age_indexes.append(np.flatnonzero(ages_Mu_min > age_sep[-1])) for i in range(nMat): Nia = Ni[age_indexes[i]] Na = Nia.sum() for j in range(nMat): Ms[0,i,j] = (Nia * ((Mu_house[age_indexes[i]][:,age_indexes[j]]).sum(axis=1))).sum()/Na Ms[1,i,j] = (Nia * ((Mu_school[age_indexes[i]][:,age_indexes[j]]).sum(axis=1))).sum()/Na Ms[2,i,j] = (Nia * ((Mu_work[age_indexes[i]][:,age_indexes[j]]).sum(axis=1))).sum()/Na Ms[3,i,j] = (Nia * ((Mu_other[age_indexes[i]][:,age_indexes[j]]).sum(axis=1))).sum()/Na return Ms class SEIIHURD_age: ''' SEIIHURD Model''' def __init__(self,tamanhoPop,numeroProcessadores=None): self.N = tamanhoPop self.numeroProcessadores = numeroProcessadores self.pos = None #pars dict betas, delta, kappa, p, gammaA, gammaS, h, epsilon, gammaH, gammaU, muU, muH, wU, wH # seguindo a notação beta_12 é 2 infectando 1, onde 1 é a linha e 2 a coluna. def _SEIIHURD_age_eq(self, X, t, pars): S, E, Ia, Is, H, U, R, D, Nw = np.split(X, 9) StE = S * (pars['beta'] @ ((Ia * pars['delta'] + Is).reshape((-1,1)))).flatten() dS = - StE dE = StE - pars['kappa'] * E dIa = (1. - pars['p']) * pars['kappa'] * E - pars['gammaA'] * Ia dIs = pars['p'] * pars['kappa'] * E - pars['gammaS'] * Is dH = pars['h'] * pars['xi'] * pars['gammaS'] * Is + (1 - pars['muU'] +\ pars['wU'] * pars['muU']) * pars['gammaU'] * U - pars['gammaH'] * H dU = pars['h'] * (1 - pars['xi']) * pars['gammaS'] * Is + pars['wH'] *\ pars['gammaH'] * H - pars['gammaU'] * U dR = pars['gammaA'] * Ia + (1. - pars['h']) * pars['gammaS'] * Is + \ (1 - pars['muH']) * (1 - pars['wH']) * pars['gammaH'] * H dD = (1 - pars['wH']) * pars['muH'] * pars['gammaH'] * H + \ (1 - pars['wU']) * pars['muU'] * pars['gammaU'] * U dNw = pars['p'] * pars['kappa'] * E return np.r_[dS, dE, dIa, dIs, dH, dU, dR, dD, dNw] def _call_ODE(self, ts, ppars): betas = ppars['beta'].copy() pars = copy.deepcopy(ppars) if 'tcut' not in ppars.keys(): tcorte = None else: tcorte = pars['tcut'] if type(ts) in [int, float]: ts = np.arange(ts) if tcorte == None: tcorte = [ts[-1]] if type(betas) != list: betas = [betas] if tcorte[-1] < ts[-1]: tcorte.append(ts[-1]) tcorte = [ts[0]] + tcorte tcorte.sort() Is0 = pars['x0'].reshape((3,-1)).sum(axis=0) x0 = np.r_[1. - Is0, pars['x0'], np.zeros(4*len(Is0)), pars['x0'][2*len(Is0):]] saida = x0.reshape((1,-1)) Y = saida.copy() for i in range(1, len(tcorte)): cut_last = False pars['beta'] = betas[i-1] t = ts[(ts >= tcorte[i-1]) * (ts<= tcorte[i])] if len(t) > 0: if t[0] > tcorte[i-1]: t = np.r_[tcorte[i-1], t] if t[-1] < tcorte[i]: t = np.r_[t, tcorte[i]] cut_last = True Y = spi.odeint(self._SEIIHURD_age_eq, Y[-1], t, args=(pars,)) if cut_last: saida = np.r_[saida, Y[1:-1]] else: saida = np.r_[saida, Y[1:]] else: Y = spi.odeint(self._SEIIHURD_age_eq, Y[-1], tcorte[i-1:i+1], args=(pars,)) return ts, saida def _fill_paramPSO(self, paramPSO): if 'options' not in paramPSO.keys(): paramPSO['options'] = {'c1': 0.1, 'c2': 0.3, 'w': 0.9,'k':5,'p':2} if 'n_particles' not in paramPSO.keys(): paramPSO['n_particles'] = 300 if 'iter' not in paramPSO.keys(): paramPSO['iter'] = 1000 return paramPSO def _prepare_input(self, data): list_states = ['S', 'E', 'Ia', 'Is', 'H', 'U', 'R', 'D', 'Nw'] i_integ = list() Y = list() for ke in data.keys(): if ke == 't': t = data[ke] else: Y.append(data[ke]) simb, num = ke.split("_") n0 = self.nages * list_states.index(simb) if '_ALL' in ke: i_integ.append(list(range(n0,n0 + self.nages))) else: i_integ.append(int(num) + n0) return i_integ, Y, t def _prepare_conversor(self, p2f, pothers, bound): padjus = list() if bound != None: bound_new = [[], []] for i, par in enumerate(p2f): if 'beta' in par: if '_ALL' in par: for l in range(len(pothers['beta'])): for j in range(pothers['beta'][i].shape[0]): for k in range(pothers['beta'][i].shape[1]): padjus.append('beta_{}_{}_{}'.format(l,j,k)) if bound != None: bound_new[0].append(bound[0][i]) bound_new[1].append(bound[1][i]) else: padjus.append(par) if bound != None: bound_new[0].append(bound[0][i]) bound_new[1].append(bound[1][i]) elif '_ALL' in par: name = par.split('_')[0] for j in range(len(pothers[name])): padjus.append('{}_{}'.format(name, j)) if bound != None: bound_new[0].append(bound[0][i]) bound_new[1].append(bound[1][i]) else: padjus.append(par) if bound != None: bound_new[0].append(bound[0][i]) bound_new[1].append(bound[1][i]) if bound != None: bound_new[0] = np.array(bound_new[0]) bound_new[1] = np.array(bound_new[1]) return bound_new, padjus def _conversor(self, coefs, pars0, padjus): pars = copy.deepcopy(pars0) for i, coef in enumerate(coefs): if 'beta' in padjus[i]: if '_M_' in padjus[i]: indx = int(padjus[i].split('_')[-1]) pars['beta'][indx] = coef * pars['beta'][indx] else: indx = padjus[i].split('_') pars['beta'][int(indx[1])][int(indx[2]), int(indx[3])] = coef elif '_' in padjus[i]: name, indx = padjus[i].split('_') pars[name][int(indx)] = coef else: pars[padjus[i]] = coef return pars def objectiveFunction(self, coefs_list, stand_error=False, weights=None): errsq = np.zeros(coefs_list.shape[0]) for i, coefs in enumerate(coefs_list): errs = self._residuals(coefs, stand_error, weights) errsq[i] = (errs*errs).mean() return errsq def _residuals(self, coefs, stand_error=False, weights=None): if type(weights) == type(None): weights = np.ones(len(self.Y)) error_func = (lambda x: np.sqrt(x+1)) if stand_error else (lambda x:np.ones_like(x)) errs = np.empty((0,)) ts, mY = self._call_ODE(self.t, self._conversor(coefs, self.pars_init, self.padjus)) for indY, indODE in enumerate(self.i_integ): if type(indODE) == list: temp = (self.N.reshape((1,-1)) * mY[:,indODE]).sum(axis=1) errs = np.r_[errs, weights[indY] * ((self.Y[indY] - temp) / error_func(temp)) ] else: try: errs = np.r_[errs, weights[indY] * ((self.Y[indY] - self.N[indODE%self.nages] * mY[:,indODE]) / error_func(mY[:,indODE])) ] except: print(self.t, self._conversor(coefs, self.pars_init, self.padjus)) raise errs = errs[~np.isnan(errs)] return errs def prepare_to_fit(self, data, pars, pars_to_fit, bound=None, nages=1, stand_error=False): self.pars_init = copy.deepcopy(pars) self.nages = nages self.i_integ, self.Y, self.t = self._prepare_input(data) self.bound, self.padjus = self._prepare_conversor(pars_to_fit, pars, bound) self.n_to_fit = len(self.padjus) def fit(self, data, pars, pars_to_fit, bound=None, nages=2, paramPSO=dict(), stand_error=False): ''' data: dictionary: t -> times X_N -> variable: X is the simbol of the parameter: S, E, Ia, Is, H, U, R, D, Nw N is the index of the age-group, starting on 0 pars: dictionary, with the variable names as keys. pars_to_fit: the name of the parameters to fits, if the parameter is a list, add _N with the index you want to if or _ALL to fit all the 'beta' parameter has 3 indexes: beta_I_J_K, with I indicating the which tcut it belongs and J_K indicating the position in the matrix. the beta also has a option 'beta_M_I' that fits a multiplicative constant of the infection matrix, without changing the relative weights (the _M_ and _ALL_ options are incompatible by now, and _M_ requires testing) bound = intervalo de limite para procura de cada parametro, onde None = sem limite bound => (lista_min_bound, lista_max_bound) ''' paramPSO = self._fill_paramPSO(paramPSO) self.prepare_to_fit(data, pars, pars_to_fit, bound=bound, nages=nages, stand_error=stand_error) optimizer = ps.single.LocalBestPSO(n_particles=paramPSO['n_particles'], dimensions=self.n_to_fit, options=paramPSO['options'],bounds=self.bound) cost = pos = None cost, pos = optimizer.optimize(self.objectiveFunction,paramPSO['iter'], stand_error=stand_error, n_processes=self.numeroProcessadores) self.pos = pos self.pars_opt = self._conversor(pos, self.pars_init, self.padjus ) self.rmse = cost self.optimize = optimizer def fit_lsquares(self, data, pars, pars_to_fit, bound=None, nages=2, stand_error=False, init=None, nrand=10): self.prepare_to_fit(data, pars, pars_to_fit, bound=bound, nages=nages, stand_error=stand_error) if init == None: cost_best = np.inf res_best = None #BUG: the parallel code does not work if PSO code had run previously if type(self.pos) != type(None) or self.numeroProcessadores == None or self.numeroProcessadores <= 1: for i in range(nrand): print("{} / {}".format(i, nrand)) par0 = np.random.rand(self.n_to_fit) par0 = self.bound[0] + par0 * (self.bound[1] - self.bound[0]) res = least_squares(self._residuals, par0, bounds=self.bound) if res.cost < cost_best: cost_best = res.cost res_best = res else: par0 = np.random.rand(nrand, self.n_to_fit) par0 = self.bound[0].reshape((1,-1)) + par0 * (self.bound[1] - self.bound[0]).reshape((1,-1)) f = lambda p0: least_squares(self._residuals, p0, bounds=self.bound) all_res = joblib.Parallel(n_jobs=self.numeroProcessadores)(joblib.delayed(f)(p0,) for p0 in par0) costs = np.array([res.cost for res in all_res]) cost_best = all_res[costs.argmin()].cost res_best = all_res[costs.argmin()] else: res_best = least_squares(self._residuals, init, bounds=bound ) self.pos_ls = res_best.x self.pars_opt_ls = self._conversor(res_best.x, self.pars_init, self.padjus ) self.rmse_ls = (res_best.fun**2).mean() self.result_ls = res_best def predict(self, t=None, coefs=None, model_output=False): if type(t) == type(None): t = self.t if type(coefs) == type(None): coefs = self.pos elif type(coefs) == str and coefs == 'LS': coefs = self.pos_ls ts, mY = self._call_ODE(t, self._conversor(coefs, self.pars_init, self.padjus)) saida = np.zeros((len(ts), 0)) for i in self.i_integ: if type(i) == list: ytemp = (mY[:,i] *self.N.reshape((1,-1))).sum(axis=1) else: ytemp = mY[:,i] * self.N[i%self.nages] saida = np.c_[saida, ytemp.reshape((-1,1))] if model_output: return ts, saida, mY else: return ts, saida #ts, X = call_ODE(X0, tmax, betas, param, tcorte=tcorte) #plt.plot(ts, X[:,:2], '.-')
[ "numpy.ones_like", "scipy.optimize.least_squares", "numpy.sqrt", "numpy.random.rand", "scipy.integrate.odeint", "numpy.flatnonzero", "pyswarms.single.LocalBestPSO", "joblib.Parallel", "numpy.array", "numpy.split", "numpy.zeros", "numpy.empty", "numpy.isnan", "copy.deepcopy", "joblib.delayed", "numpy.arange" ]
[((987, 4278), 'numpy.array', 'np.array', (['[[0.47868515, 0.50507561, 0.29848922, 0.15763748, 0.26276959, 0.40185462, \n 0.46855027, 0.42581354, 0.2150961, 0.0856771, 0.08705463, 0.07551931, \n 0.05129175, 0.02344832, 0.00793644, 0.01072846], [0.35580205, \n 0.77874482, 0.51392686, 0.21151069, 0.08597966, 0.28306027, 0.49982218,\n 0.52854893, 0.41220947, 0.15848728, 0.07491245, 0.07658339, 0.04772343,\n 0.02588962, 0.01125956, 0.01073152], [0.25903114, 0.63488713, \n 1.36175618, 0.50016515, 0.11748191, 0.10264613, 0.24113458, 0.47274372,\n 0.54026417, 0.26708819, 0.11007723, 0.04406045, 0.02746409, 0.02825033,\n 0.02044872, 0.01214665], [0.14223192, 0.24383932, 0.53761638, \n 1.05325205, 0.28778496, 0.10925453, 0.0651564, 0.2432454, 0.39011334, \n 0.41381277, 0.23194909, 0.07541471, 0.03428398, 0.02122257, 0.01033573,\n 0.00864859], [0.27381886, 0.15430529, 0.16053062, 0.5104134, 0.95175366,\n 0.3586594, 0.09248672, 0.04774269, 0.15814197, 0.36581739, 0.25544811, \n 0.13338965, 0.03461345, 0.01062458, 0.00844199, 0.00868782], [\n 0.59409802, 0.26971847, 0.10669146, 0.18330524, 0.39561893, 0.81955947,\n 0.26376865, 0.06604084, 0.03824556, 0.11560004, 0.23218163, 0.15331788,\n 0.07336147, 0.02312255, 0.00412646, 0.01025778], [0.63860889, \n 0.75760606, 0.43109156, 0.09913293, 0.13935789, 0.32056062, 0.65710277,\n 0.25488454, 0.1062129, 0.0430932, 0.06880784, 0.09938458, 0.09010691, \n 0.02233902, 0.01155556, 0.00695246], [0.56209348, 0.87334544, \n 0.75598244, 0.33199136, 0.07233271, 0.08674171, 0.20243583, 0.60062714,\n 0.17793601, 0.06307045, 0.04445926, 0.04082447, 0.06275133, 0.04051762,\n 0.01712777, 0.00598721], [0.35751289, 0.66234582, 0.77180208, \n 0.54993616, 0.17368099, 0.07361914, 0.13016852, 0.19937327, 0.46551558,\n 0.15412263, 0.06123041, 0.0182514, 0.04234381, 0.04312892, 0.01656267, \n 0.01175358], [0.208131, 0.41591452, 0.56510014, 0.67760241, 0.38146504,\n 0.14185001, 0.06160354, 0.12945701, 0.16470166, 0.41150841, 0.14596804,\n 0.04404807, 0.02395316, 0.01731295, 0.01469059, 0.02275339], [\n 0.30472548, 0.26744442, 0.41631962, 0.46516888, 0.41751365, 0.28520772,\n 0.13931619, 0.07682945, 0.11404965, 0.16122096, 0.33813266, 0.1349378, \n 0.03755396, 0.01429426, 0.01356763, 0.02551792], [0.52762004, \n 0.52787011, 0.33622117, 0.43037934, 0.36416323, 0.42655672, 0.33780201,\n 0.13492044, 0.0798784, 0.15795568, 0.20367727, 0.33176385, 0.12256126, \n 0.05573807, 0.0124446, 0.02190564], [0.53741472, 0.50750067, 0.3229994,\n 0.30706704, 0.21340314, 0.27424513, 0.32838657, 0.26023515, 0.13222548,\n 0.07284901, 0.11950584, 0.16376401, 0.25560123, 0.09269703, 0.02451284,\n 0.00631762], [0.37949376, 0.55324102, 0.47449156, 0.24796638, \n 0.19276924, 0.20675484, 0.3267867, 0.39525729, 0.3070043, 0.10088992, \n 0.10256839, 0.13016641, 0.1231421, 0.24067708, 0.05475668, 0.01401368],\n [0.16359554, 0.48536065, 0.40533723, 0.31542539, 0.06890518, 0.15670328,\n 0.12884062, 0.27912381, 0.25685832, 0.20143856, 0.12497647, 0.07565566,\n 0.10331686, 0.08830789, 0.15657321, 0.05744065], [0.29555039, \n 0.39898035, 0.60257982, 0.5009724, 0.13799378, 0.11716593, 0.14366306, \n 0.31602298, 0.34691652, 0.30960511, 0.31253708, 0.14557295, 0.06065554,\n 0.10654772, 0.06390924, 0.09827735]]'], {}), '([[0.47868515, 0.50507561, 0.29848922, 0.15763748, 0.26276959, \n 0.40185462, 0.46855027, 0.42581354, 0.2150961, 0.0856771, 0.08705463, \n 0.07551931, 0.05129175, 0.02344832, 0.00793644, 0.01072846], [\n 0.35580205, 0.77874482, 0.51392686, 0.21151069, 0.08597966, 0.28306027,\n 0.49982218, 0.52854893, 0.41220947, 0.15848728, 0.07491245, 0.07658339,\n 0.04772343, 0.02588962, 0.01125956, 0.01073152], [0.25903114, \n 0.63488713, 1.36175618, 0.50016515, 0.11748191, 0.10264613, 0.24113458,\n 0.47274372, 0.54026417, 0.26708819, 0.11007723, 0.04406045, 0.02746409,\n 0.02825033, 0.02044872, 0.01214665], [0.14223192, 0.24383932, \n 0.53761638, 1.05325205, 0.28778496, 0.10925453, 0.0651564, 0.2432454, \n 0.39011334, 0.41381277, 0.23194909, 0.07541471, 0.03428398, 0.02122257,\n 0.01033573, 0.00864859], [0.27381886, 0.15430529, 0.16053062, 0.5104134,\n 0.95175366, 0.3586594, 0.09248672, 0.04774269, 0.15814197, 0.36581739, \n 0.25544811, 0.13338965, 0.03461345, 0.01062458, 0.00844199, 0.00868782],\n [0.59409802, 0.26971847, 0.10669146, 0.18330524, 0.39561893, 0.81955947,\n 0.26376865, 0.06604084, 0.03824556, 0.11560004, 0.23218163, 0.15331788,\n 0.07336147, 0.02312255, 0.00412646, 0.01025778], [0.63860889, \n 0.75760606, 0.43109156, 0.09913293, 0.13935789, 0.32056062, 0.65710277,\n 0.25488454, 0.1062129, 0.0430932, 0.06880784, 0.09938458, 0.09010691, \n 0.02233902, 0.01155556, 0.00695246], [0.56209348, 0.87334544, \n 0.75598244, 0.33199136, 0.07233271, 0.08674171, 0.20243583, 0.60062714,\n 0.17793601, 0.06307045, 0.04445926, 0.04082447, 0.06275133, 0.04051762,\n 0.01712777, 0.00598721], [0.35751289, 0.66234582, 0.77180208, \n 0.54993616, 0.17368099, 0.07361914, 0.13016852, 0.19937327, 0.46551558,\n 0.15412263, 0.06123041, 0.0182514, 0.04234381, 0.04312892, 0.01656267, \n 0.01175358], [0.208131, 0.41591452, 0.56510014, 0.67760241, 0.38146504,\n 0.14185001, 0.06160354, 0.12945701, 0.16470166, 0.41150841, 0.14596804,\n 0.04404807, 0.02395316, 0.01731295, 0.01469059, 0.02275339], [\n 0.30472548, 0.26744442, 0.41631962, 0.46516888, 0.41751365, 0.28520772,\n 0.13931619, 0.07682945, 0.11404965, 0.16122096, 0.33813266, 0.1349378, \n 0.03755396, 0.01429426, 0.01356763, 0.02551792], [0.52762004, \n 0.52787011, 0.33622117, 0.43037934, 0.36416323, 0.42655672, 0.33780201,\n 0.13492044, 0.0798784, 0.15795568, 0.20367727, 0.33176385, 0.12256126, \n 0.05573807, 0.0124446, 0.02190564], [0.53741472, 0.50750067, 0.3229994,\n 0.30706704, 0.21340314, 0.27424513, 0.32838657, 0.26023515, 0.13222548,\n 0.07284901, 0.11950584, 0.16376401, 0.25560123, 0.09269703, 0.02451284,\n 0.00631762], [0.37949376, 0.55324102, 0.47449156, 0.24796638, \n 0.19276924, 0.20675484, 0.3267867, 0.39525729, 0.3070043, 0.10088992, \n 0.10256839, 0.13016641, 0.1231421, 0.24067708, 0.05475668, 0.01401368],\n [0.16359554, 0.48536065, 0.40533723, 0.31542539, 0.06890518, 0.15670328,\n 0.12884062, 0.27912381, 0.25685832, 0.20143856, 0.12497647, 0.07565566,\n 0.10331686, 0.08830789, 0.15657321, 0.05744065], [0.29555039, \n 0.39898035, 0.60257982, 0.5009724, 0.13799378, 0.11716593, 0.14366306, \n 0.31602298, 0.34691652, 0.30960511, 0.31253708, 0.14557295, 0.06065554,\n 0.10654772, 0.06390924, 0.09827735]])\n', (995, 4278), True, 'import numpy as np\n'), ((4604, 8613), 'numpy.array', 'np.array', (['[[0.321885854, 0.0431659966, 0.00788269419, 0.00809548363, 0.00535038146, \n 0.0218201974, 0.0401633514, 0.0299376002, 0.0140680283, 0.0166587853, \n 0.00947774696, 0.00741041622, 0.00128200661, 0.000779120405, \n 8.23608272e-66, 6.37926405e-120], [0.0540133328, 4.84870697, \n 0.270046494, 0.031477845, 0.0311206331, 0.0856826951, 0.108251879, \n 0.0946101139, 0.0863528188, 0.0551141159, 0.0419385198, 0.0120958942, \n 0.00477242219, 0.00139787217, 0.000347452943, 8.08973738e-39], [\n 0.000456461982, 1.04840235, 6.09152459, 0.198915822, 0.0199709921, \n 0.0668319525, 0.0658949586, 0.0970851505, 0.0954147078, 0.0670538232, \n 0.0424864096, 0.0198701346, 0.00511869429, 0.000727320438, \n 4.93746124e-25, 0.000182153965], [0.00259613205, 0.0473315233, \n 1.99337834, 7.200405, 0.0857326037, 0.0790668822, 0.0854208542, \n 0.110816964, 0.0876955236, 0.0922975521, 0.0458035025, 0.0251130956, \n 0.00571391798, 0.00107818752, 6.21174558e-33, 1.70710246e-70], [\n 0.0071915872, 0.0248833195, 0.00989727235, 0.876815025, 0.433963352, \n 0.0505185217, 0.0330594492, 0.0381384107, 0.0234709676, 0.0267235372, \n 0.0132913985, 0.00900655556, 0.000694913059, 0.00125675951, \n 0.000177164197, 1.21957619e-47], [0.00704119204, 0.119412206, \n 0.037501698, 0.202193056, 0.279822908, 0.168610223, 0.0286939363, \n 0.0356961469, 0.0409234494, 0.0332290896, 0.00812074348, 0.0126152144, \n 0.00427869081, 0.00241737477, 0.000463116893, 0.00128597237], [\n 0.014148632, 0.386561429, 0.255902236, 0.169973534, 0.049810401, \n 0.0898122446, 0.0795333394, 0.0519274611, 0.054661293, 0.0264567137, \n 0.0203241595, 0.0029626322, 0.00542888613, 0.00044758597, \n 1.65440335e-48, 3.11189454e-55], [0.0240945305, 0.211030046, \n 0.154767246, 0.0817929897, 0.0184061608, 0.0543009779, 0.0739351186, \n 0.0521677009, 0.0563267084, 0.0251807147, 0.00353972554, 0.00796646343,\n 0.000556929776, 0.00208530461, 1.8442829e-123, 9.69555083e-67], [\n 0.00781313905, 0.114371898, 0.0909011945, 0.380212104, 0.00854533192, \n 0.0262430162, 0.0251880009, 0.0322563508, 0.0673506045, 0.0224997143, \n 0.0239241043, 0.00650627191, 0.00550892674, 0.00047830885, \n 4.81213215e-68, 2.40231425e-92], [0.0655265016, 0.231163536, \n 0.149970765, 0.553563093, 0.00574032526, 0.0302865481, 0.0572506883, \n 0.0470559232, 0.0428736553, 0.0242614518, 0.0286665377, 0.0129570473, \n 0.00324362518, 0.00167930318, 6.2091695e-134, 3.27297624e-72], [\n 0.0172765646, 0.343744913, 0.430902785, 0.474293073, 0.00539328187, \n 0.014412874, 0.0395545363, 0.037378186, 0.0456834488, 0.0592135906, \n 0.0291473801, 0.0154857502, 0.0045310539, 8.87272668e-24, \n 1.23797452e-117, 5.64262349e-78], [0.0614363036, 0.298367348, 0.2590927,\n 0.300800812, 0.00592454596, 0.0526458862, 0.0202188672, 0.0327897605, \n 0.0407753741, 0.0283422407, 0.0243657809, 0.0273993226, 0.00887990718, \n 1.1327918e-31, 0.000781960493, 0.00076246751], [0.0363695643, \n 0.0596870355, 0.0305072624, 0.145523978, 0.0126062984, 0.00169458169, \n 0.0155127292, 0.042209767, 0.00921792425, 0.0142200652, 0.0110967529, \n 0.00577020348, 0.0204474044, 0.0111075734, 4.42271199e-67, \n 2.12068625e-37], [0.00167937029, 0.0272971001, 0.0105886266, \n 7.61087735e-32, 0.00197191559, 0.00192885006, 0.0124343737, \n 0.00539297787, 0.00541684968, 0.00863502071, 0.00194554498, \n 0.0149082274, 0.008117811, 0.0174395489, 0.0111239023, 3.45693088e-126],\n [1.28088348e-28, 5.110652e-26, 1.93019797e-40, 0.00760476035, \n 2.63586947e-22, 1.69749024e-24, 1.25875005e-26, 0.00762109877, \n 0.00784979948, 0.0211516023, 0.0352117832, 0.0214360383, 0.00773902109,\n 0.00801328325, 0.00791285055, 0.0213825814], [2.81655586e-94, \n 0.0211305187, 8.46562506e-42, 0.0212592841, 4.89802057e-36, \n 0.00759232387, 9.77247001e-69, 2.23108239e-60, 1.43715978e-48, \n 8.56015694e-60, 4.69469043e-42, 1.59822047e-46, 2.2097855e-83, \n 8.85861277e-107, 1.02042815e-80, 6.61413913e-113]]'], {}), '([[0.321885854, 0.0431659966, 0.00788269419, 0.00809548363, \n 0.00535038146, 0.0218201974, 0.0401633514, 0.0299376002, 0.0140680283, \n 0.0166587853, 0.00947774696, 0.00741041622, 0.00128200661, \n 0.000779120405, 8.23608272e-66, 6.37926405e-120], [0.0540133328, \n 4.84870697, 0.270046494, 0.031477845, 0.0311206331, 0.0856826951, \n 0.108251879, 0.0946101139, 0.0863528188, 0.0551141159, 0.0419385198, \n 0.0120958942, 0.00477242219, 0.00139787217, 0.000347452943, \n 8.08973738e-39], [0.000456461982, 1.04840235, 6.09152459, 0.198915822, \n 0.0199709921, 0.0668319525, 0.0658949586, 0.0970851505, 0.0954147078, \n 0.0670538232, 0.0424864096, 0.0198701346, 0.00511869429, 0.000727320438,\n 4.93746124e-25, 0.000182153965], [0.00259613205, 0.0473315233, \n 1.99337834, 7.200405, 0.0857326037, 0.0790668822, 0.0854208542, \n 0.110816964, 0.0876955236, 0.0922975521, 0.0458035025, 0.0251130956, \n 0.00571391798, 0.00107818752, 6.21174558e-33, 1.70710246e-70], [\n 0.0071915872, 0.0248833195, 0.00989727235, 0.876815025, 0.433963352, \n 0.0505185217, 0.0330594492, 0.0381384107, 0.0234709676, 0.0267235372, \n 0.0132913985, 0.00900655556, 0.000694913059, 0.00125675951, \n 0.000177164197, 1.21957619e-47], [0.00704119204, 0.119412206, \n 0.037501698, 0.202193056, 0.279822908, 0.168610223, 0.0286939363, \n 0.0356961469, 0.0409234494, 0.0332290896, 0.00812074348, 0.0126152144, \n 0.00427869081, 0.00241737477, 0.000463116893, 0.00128597237], [\n 0.014148632, 0.386561429, 0.255902236, 0.169973534, 0.049810401, \n 0.0898122446, 0.0795333394, 0.0519274611, 0.054661293, 0.0264567137, \n 0.0203241595, 0.0029626322, 0.00542888613, 0.00044758597, \n 1.65440335e-48, 3.11189454e-55], [0.0240945305, 0.211030046, \n 0.154767246, 0.0817929897, 0.0184061608, 0.0543009779, 0.0739351186, \n 0.0521677009, 0.0563267084, 0.0251807147, 0.00353972554, 0.00796646343,\n 0.000556929776, 0.00208530461, 1.8442829e-123, 9.69555083e-67], [\n 0.00781313905, 0.114371898, 0.0909011945, 0.380212104, 0.00854533192, \n 0.0262430162, 0.0251880009, 0.0322563508, 0.0673506045, 0.0224997143, \n 0.0239241043, 0.00650627191, 0.00550892674, 0.00047830885, \n 4.81213215e-68, 2.40231425e-92], [0.0655265016, 0.231163536, \n 0.149970765, 0.553563093, 0.00574032526, 0.0302865481, 0.0572506883, \n 0.0470559232, 0.0428736553, 0.0242614518, 0.0286665377, 0.0129570473, \n 0.00324362518, 0.00167930318, 6.2091695e-134, 3.27297624e-72], [\n 0.0172765646, 0.343744913, 0.430902785, 0.474293073, 0.00539328187, \n 0.014412874, 0.0395545363, 0.037378186, 0.0456834488, 0.0592135906, \n 0.0291473801, 0.0154857502, 0.0045310539, 8.87272668e-24, \n 1.23797452e-117, 5.64262349e-78], [0.0614363036, 0.298367348, 0.2590927,\n 0.300800812, 0.00592454596, 0.0526458862, 0.0202188672, 0.0327897605, \n 0.0407753741, 0.0283422407, 0.0243657809, 0.0273993226, 0.00887990718, \n 1.1327918e-31, 0.000781960493, 0.00076246751], [0.0363695643, \n 0.0596870355, 0.0305072624, 0.145523978, 0.0126062984, 0.00169458169, \n 0.0155127292, 0.042209767, 0.00921792425, 0.0142200652, 0.0110967529, \n 0.00577020348, 0.0204474044, 0.0111075734, 4.42271199e-67, \n 2.12068625e-37], [0.00167937029, 0.0272971001, 0.0105886266, \n 7.61087735e-32, 0.00197191559, 0.00192885006, 0.0124343737, \n 0.00539297787, 0.00541684968, 0.00863502071, 0.00194554498, \n 0.0149082274, 0.008117811, 0.0174395489, 0.0111239023, 3.45693088e-126],\n [1.28088348e-28, 5.110652e-26, 1.93019797e-40, 0.00760476035, \n 2.63586947e-22, 1.69749024e-24, 1.25875005e-26, 0.00762109877, \n 0.00784979948, 0.0211516023, 0.0352117832, 0.0214360383, 0.00773902109,\n 0.00801328325, 0.00791285055, 0.0213825814], [2.81655586e-94, \n 0.0211305187, 8.46562506e-42, 0.0212592841, 4.89802057e-36, \n 0.00759232387, 9.77247001e-69, 2.23108239e-60, 1.43715978e-48, \n 8.56015694e-60, 4.69469043e-42, 1.59822047e-46, 2.2097855e-83, \n 8.85861277e-107, 1.02042815e-80, 6.61413913e-113]])\n', (4612, 8613), True, 'import numpy as np\n'), ((9755, 13508), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n 8.20604524e-92, 1.2058515e-05, 3.16436834e-125], [0.0, 0.00116840561, \n 9.90713236e-72, 4.42646396e-59, 2.91874286e-06, 0.00998773031, \n 0.0258779981, 0.00566104376, 0.0212699812, 0.00572117462, 0.00148212306,\n 0.00123926126, 1.28212945e-56, 1.34955578e-05, 7.64591325e-79, \n 2.38392073e-65], [0.0, 0.00256552144, 0.112756182, 0.0240351143, \n 0.0262981485, 0.00756512432, 0.0619587609, 0.0173269871, 0.0587405128, \n 0.0326749742, 0.0124709193, 2.93054408e-08, 3.71596993e-17, \n 2.79780317e-53, 4.9580077e-06, 3.77718083e-102], [0.0, 0.0107213881, \n 0.0428390448, 0.72276909, 0.593479736, 0.339341952, 0.317013715, \n 0.289168861, 0.31114318, 0.234889238, 0.132953769, 0.0601944097, \n 0.0147306181, 8.34699602e-06, 2.85972822e-06, 1.88926122e-31], [0.0, \n 0.00914252587, 0.0574508682, 0.400000235, 0.793386618, 0.755975146, \n 0.632277283, 0.683601459, 0.498506972, 0.382309992, 0.281363576, \n 0.123338103, 0.0415708021, 9.86113407e-06, 1.32609387e-05, \n 3.74318048e-06], [0.0, 0.0104243481, 0.0734587492, 0.349556755, \n 0.750680101, 1.25683393, 0.901245714, 0.863446835, 0.770443641, \n 0.517237071, 0.409810981, 0.1806454, 0.0551284783, 1.60674627e-05, \n 1.01182608e-05, 3.01442534e-06], [0.0, 0.0165842404, 0.0834076781, \n 0.189301935, 0.521246906, 0.854460001, 1.12054931, 0.964310078, \n 0.83467518, 0.652534012, 0.379383514, 0.211198205, 0.0517285688, \n 1.63795563e-05, 4.10100851e-06, 3.4947898e-06], [0.0, 0.0111666639, \n 0.0503319748, 0.370510313, 0.424294782, 0.787535547, 0.845085693, \n 1.14590365, 1.07673077, 0.713492115, 0.500740004, 0.190102207, \n 0.0359740115, 1.2298853e-05, 9.13512833e-06, 6.02097416e-06], [0.0, \n 0.0060779244, 0.0549337607, 0.223499535, 0.482353827, 0.752291991, \n 0.889187601, 0.93376537, 1.10492283, 0.850124391, 0.588941528, \n 0.194947085, 0.0509477228, 1.43626161e-05, 1.02721567e-05, \n 1.29503893e-05], [0.0, 0.00331622551, 0.0701829848, 0.267512972, \n 0.314796392, 0.541516885, 0.695769048, 0.750620518, 0.750038547, \n 0.700954088, 0.435197983, 0.211283335, 0.03885762, 1.6281037e-05, \n 1.0824361e-05, 6.09172339e-06], [0.0, 0.000439576425, 0.0717737968, \n 0.189254612, 0.247832532, 0.516027731, 0.602783971, 0.615949277, \n 0.805581107, 0.744063535, 0.544855374, 0.252198706, 0.0439235685, \n 1.18079721e-05, 1.18226645e-05, 1.01613165e-05], [0.0, 0.00491737561, \n 0.108686672, 0.124987806, 0.164110983, 0.300118829, 0.418159745, \n 0.386897613, 0.477718241, 0.36085425, 0.322466456, 0.192516925, \n 0.0407209694, 1.34978304e-05, 6.58739925e-06, 6.65716756e-06], [0.0, \n 0.000635447018, 0.039632962, 0.0183072502, 0.0704596701, 0.124861117, \n 0.137834574, 0.15984572, 0.166933479, 0.156084857, 0.114949158, \n 0.0846570798, 0.0150879843, 2.0301958e-05, 8.26102156e-06, \n 1.48398182e-05], [7.60299521e-06, 3.36326754e-06, 7.64855296e-06, \n 2.27621532e-05, 3.14933351e-05, 7.8930841e-05, 7.24212842e-05, \n 2.91748203e-05, 6.61873732e-05, 5.95693238e-05, 7.707135e-05, \n 5.30687748e-05, 4.66030117e-05, 1.41633235e-05, 2.49066205e-05, \n 1.19109038e-05], [5.7886384e-55, 7.88785149e-42, 2.54830412e-06, \n 2.60648191e-05, 1.68036205e-05, 2.12446739e-05, 3.57267603e-05, \n 4.02377033e-05, 3.56401935e-05, 3.09769252e-05, 2.13053382e-05, \n 4.49709414e-05, 2.61368373e-05, 1.68266203e-05, 1.66514322e-05, \n 2.60822813e-05], [2.35721271e-141, 9.06871674e-97, 1.18637122e-89, \n 9.39934076e-22, 4.66000452e-05, 4.69664011e-05, 4.69316082e-05, \n 8.42184044e-05, 2.77788168e-05, 1.03294378e-05, 1.06803618e-05, \n 7.26341826e-75, 1.10073971e-65, 1.02831671e-05, 5.16902994e-49, \n 8.28040509e-43]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 8.20604524e-92, 1.2058515e-05, 3.16436834e-125], [0.0, 0.00116840561, \n 9.90713236e-72, 4.42646396e-59, 2.91874286e-06, 0.00998773031, \n 0.0258779981, 0.00566104376, 0.0212699812, 0.00572117462, 0.00148212306,\n 0.00123926126, 1.28212945e-56, 1.34955578e-05, 7.64591325e-79, \n 2.38392073e-65], [0.0, 0.00256552144, 0.112756182, 0.0240351143, \n 0.0262981485, 0.00756512432, 0.0619587609, 0.0173269871, 0.0587405128, \n 0.0326749742, 0.0124709193, 2.93054408e-08, 3.71596993e-17, \n 2.79780317e-53, 4.9580077e-06, 3.77718083e-102], [0.0, 0.0107213881, \n 0.0428390448, 0.72276909, 0.593479736, 0.339341952, 0.317013715, \n 0.289168861, 0.31114318, 0.234889238, 0.132953769, 0.0601944097, \n 0.0147306181, 8.34699602e-06, 2.85972822e-06, 1.88926122e-31], [0.0, \n 0.00914252587, 0.0574508682, 0.400000235, 0.793386618, 0.755975146, \n 0.632277283, 0.683601459, 0.498506972, 0.382309992, 0.281363576, \n 0.123338103, 0.0415708021, 9.86113407e-06, 1.32609387e-05, \n 3.74318048e-06], [0.0, 0.0104243481, 0.0734587492, 0.349556755, \n 0.750680101, 1.25683393, 0.901245714, 0.863446835, 0.770443641, \n 0.517237071, 0.409810981, 0.1806454, 0.0551284783, 1.60674627e-05, \n 1.01182608e-05, 3.01442534e-06], [0.0, 0.0165842404, 0.0834076781, \n 0.189301935, 0.521246906, 0.854460001, 1.12054931, 0.964310078, \n 0.83467518, 0.652534012, 0.379383514, 0.211198205, 0.0517285688, \n 1.63795563e-05, 4.10100851e-06, 3.4947898e-06], [0.0, 0.0111666639, \n 0.0503319748, 0.370510313, 0.424294782, 0.787535547, 0.845085693, \n 1.14590365, 1.07673077, 0.713492115, 0.500740004, 0.190102207, \n 0.0359740115, 1.2298853e-05, 9.13512833e-06, 6.02097416e-06], [0.0, \n 0.0060779244, 0.0549337607, 0.223499535, 0.482353827, 0.752291991, \n 0.889187601, 0.93376537, 1.10492283, 0.850124391, 0.588941528, \n 0.194947085, 0.0509477228, 1.43626161e-05, 1.02721567e-05, \n 1.29503893e-05], [0.0, 0.00331622551, 0.0701829848, 0.267512972, \n 0.314796392, 0.541516885, 0.695769048, 0.750620518, 0.750038547, \n 0.700954088, 0.435197983, 0.211283335, 0.03885762, 1.6281037e-05, \n 1.0824361e-05, 6.09172339e-06], [0.0, 0.000439576425, 0.0717737968, \n 0.189254612, 0.247832532, 0.516027731, 0.602783971, 0.615949277, \n 0.805581107, 0.744063535, 0.544855374, 0.252198706, 0.0439235685, \n 1.18079721e-05, 1.18226645e-05, 1.01613165e-05], [0.0, 0.00491737561, \n 0.108686672, 0.124987806, 0.164110983, 0.300118829, 0.418159745, \n 0.386897613, 0.477718241, 0.36085425, 0.322466456, 0.192516925, \n 0.0407209694, 1.34978304e-05, 6.58739925e-06, 6.65716756e-06], [0.0, \n 0.000635447018, 0.039632962, 0.0183072502, 0.0704596701, 0.124861117, \n 0.137834574, 0.15984572, 0.166933479, 0.156084857, 0.114949158, \n 0.0846570798, 0.0150879843, 2.0301958e-05, 8.26102156e-06, \n 1.48398182e-05], [7.60299521e-06, 3.36326754e-06, 7.64855296e-06, \n 2.27621532e-05, 3.14933351e-05, 7.8930841e-05, 7.24212842e-05, \n 2.91748203e-05, 6.61873732e-05, 5.95693238e-05, 7.707135e-05, \n 5.30687748e-05, 4.66030117e-05, 1.41633235e-05, 2.49066205e-05, \n 1.19109038e-05], [5.7886384e-55, 7.88785149e-42, 2.54830412e-06, \n 2.60648191e-05, 1.68036205e-05, 2.12446739e-05, 3.57267603e-05, \n 4.02377033e-05, 3.56401935e-05, 3.09769252e-05, 2.13053382e-05, \n 4.49709414e-05, 2.61368373e-05, 1.68266203e-05, 1.66514322e-05, \n 2.60822813e-05], [2.35721271e-141, 9.06871674e-97, 1.18637122e-89, \n 9.39934076e-22, 4.66000452e-05, 4.69664011e-05, 4.69316082e-05, \n 8.42184044e-05, 2.77788168e-05, 1.03294378e-05, 1.06803618e-05, \n 7.26341826e-75, 1.10073971e-65, 1.02831671e-05, 5.16902994e-49, \n 8.28040509e-43]])\n', (9763, 13508), True, 'import numpy as np\n'), ((14907, 18188), 'numpy.array', 'np.array', (['[[0.95537734, 0.46860132, 0.27110607, 0.19447667, 0.32135073, 0.48782072, \n 0.54963024, 0.42195593, 0.27152038, 0.17864251, 0.20155642, 0.16358271,\n 0.1040159, 0.0874149, 0.05129938, 0.02153823], [0.51023519, 2.17757364,\n 0.9022516, 0.24304235, 0.20119518, 0.39689588, 0.47242431, 0.46949918, \n 0.37741651, 0.16843746, 0.12590504, 0.12682331, 0.11282247, 0.08222718,\n 0.03648526, 0.02404257], [0.18585796, 1.11958124, 4.47729443, \n 0.67959759, 0.43936317, 0.36934142, 0.41566744, 0.44467286, 0.48797422,\n 0.28795385, 0.17659191, 0.10674831, 0.07175567, 0.07249261, 0.04815305,\n 0.03697862], [0.09854482, 0.3514869, 1.84902386, 5.38491613, 1.27425161,\n 0.59242579, 0.36578735, 0.39181798, 0.38131832, 0.31501028, 0.13275648,\n 0.06408612, 0.04499218, 0.04000664, 0.02232326, 0.01322698], [\n 0.13674436, 0.1973461, 0.33264088, 2.08016394, 3.28810184, 1.29198125, \n 0.74642201, 0.44357051, 0.32781391, 0.35511243, 0.20132011, 0.12961, \n 0.04994553, 0.03748657, 0.03841073, 0.02700581], [0.23495203, \n 0.13839031, 0.14085679, 0.5347385, 1.46021275, 1.85222022, 1.02681162, \n 0.61513602, 0.39086271, 0.32871844, 0.25938947, 0.13520412, 0.05101963,\n 0.03714278, 0.02177751, 0.00979745], [0.23139098, 0.18634831, \n 0.32002214, 0.2477269, 0.64111274, 0.93691022, 1.14560725, 0.73176025, \n 0.43760432, 0.31057135, 0.29406937, 0.20632155, 0.09044896, 0.06448983,\n 0.03041877, 0.02522842], [0.18786196, 0.25090485, 0.21366969, \n 0.15358412, 0.35761286, 0.62390736, 0.76125666, 0.82975354, 0.54980593,\n 0.32778339, 0.20858991, 0.1607099, 0.13218526, 0.09042909, 0.04990491, \n 0.01762718], [0.12220241, 0.17968132, 0.31826246, 0.19846971, \n 0.34823183, 0.41563737, 0.55930999, 0.54070187, 0.5573184, 0.31526474, \n 0.20194048, 0.09234293, 0.08377534, 0.05819374, 0.0414762, 0.01563101],\n [0.03429527, 0.06388018, 0.09407867, 0.17418896, 0.23404519, 0.28879108,\n 0.34528852, 0.34507961, 0.31461973, 0.29954426, 0.21759668, 0.09684718,\n 0.06596679, 0.04274337, 0.0356891, 0.02459849], [0.05092152, 0.10829561,\n 0.13898902, 0.2005828, 0.35807132, 0.45181815, 0.32281821, 0.28014803, \n 0.30125545, 0.31260137, 0.22923948, 0.17657382, 0.10276889, 0.05555467,\n 0.03430327, 0.02064256], [0.06739051, 0.06795035, 0.0826437, 0.09522087,\n 0.23309189, 0.39055444, 0.39458465, 0.29290532, 0.27204846, 0.17810118,\n 0.24399007, 0.22146653, 0.13732849, 0.07585801, 0.03938794, 0.0190908],\n [0.04337917, 0.05375367, 0.05230119, 0.08066901, 0.16619572, 0.25423056,\n 0.25580913, 0.27430323, 0.22478799, 0.16909017, 0.14284879, 0.17211604,\n 0.14336033, 0.10344522, 0.06797049, 0.02546014], [0.04080687, \n 0.06113728, 0.04392062, 0.04488748, 0.12808591, 0.19886058, 0.24542711,\n 0.19678011, 0.17800136, 0.13147441, 0.13564091, 0.14280335, 0.12969805,\n 0.11181631, 0.05550193, 0.02956066], [0.01432324, 0.03441212, \n 0.05604694, 0.10154456, 0.09204, 0.13341443, 0.13396901, 0.16682638, \n 0.18562675, 0.1299677, 0.09922375, 0.09634331, 0.15184583, 0.13541738, \n 0.1169359, 0.03805293], [0.01972631, 0.02274412, 0.03797545, 0.02036785,\n 0.04357298, 0.05783639, 0.10706321, 0.07688271, 0.06969759, 0.08029393,\n 0.05466604, 0.05129046, 0.04648653, 0.06132882, 0.05004289, 0.03030569]]'], {}), '([[0.95537734, 0.46860132, 0.27110607, 0.19447667, 0.32135073, \n 0.48782072, 0.54963024, 0.42195593, 0.27152038, 0.17864251, 0.20155642,\n 0.16358271, 0.1040159, 0.0874149, 0.05129938, 0.02153823], [0.51023519,\n 2.17757364, 0.9022516, 0.24304235, 0.20119518, 0.39689588, 0.47242431, \n 0.46949918, 0.37741651, 0.16843746, 0.12590504, 0.12682331, 0.11282247,\n 0.08222718, 0.03648526, 0.02404257], [0.18585796, 1.11958124, \n 4.47729443, 0.67959759, 0.43936317, 0.36934142, 0.41566744, 0.44467286,\n 0.48797422, 0.28795385, 0.17659191, 0.10674831, 0.07175567, 0.07249261,\n 0.04815305, 0.03697862], [0.09854482, 0.3514869, 1.84902386, 5.38491613,\n 1.27425161, 0.59242579, 0.36578735, 0.39181798, 0.38131832, 0.31501028,\n 0.13275648, 0.06408612, 0.04499218, 0.04000664, 0.02232326, 0.01322698],\n [0.13674436, 0.1973461, 0.33264088, 2.08016394, 3.28810184, 1.29198125,\n 0.74642201, 0.44357051, 0.32781391, 0.35511243, 0.20132011, 0.12961, \n 0.04994553, 0.03748657, 0.03841073, 0.02700581], [0.23495203, \n 0.13839031, 0.14085679, 0.5347385, 1.46021275, 1.85222022, 1.02681162, \n 0.61513602, 0.39086271, 0.32871844, 0.25938947, 0.13520412, 0.05101963,\n 0.03714278, 0.02177751, 0.00979745], [0.23139098, 0.18634831, \n 0.32002214, 0.2477269, 0.64111274, 0.93691022, 1.14560725, 0.73176025, \n 0.43760432, 0.31057135, 0.29406937, 0.20632155, 0.09044896, 0.06448983,\n 0.03041877, 0.02522842], [0.18786196, 0.25090485, 0.21366969, \n 0.15358412, 0.35761286, 0.62390736, 0.76125666, 0.82975354, 0.54980593,\n 0.32778339, 0.20858991, 0.1607099, 0.13218526, 0.09042909, 0.04990491, \n 0.01762718], [0.12220241, 0.17968132, 0.31826246, 0.19846971, \n 0.34823183, 0.41563737, 0.55930999, 0.54070187, 0.5573184, 0.31526474, \n 0.20194048, 0.09234293, 0.08377534, 0.05819374, 0.0414762, 0.01563101],\n [0.03429527, 0.06388018, 0.09407867, 0.17418896, 0.23404519, 0.28879108,\n 0.34528852, 0.34507961, 0.31461973, 0.29954426, 0.21759668, 0.09684718,\n 0.06596679, 0.04274337, 0.0356891, 0.02459849], [0.05092152, 0.10829561,\n 0.13898902, 0.2005828, 0.35807132, 0.45181815, 0.32281821, 0.28014803, \n 0.30125545, 0.31260137, 0.22923948, 0.17657382, 0.10276889, 0.05555467,\n 0.03430327, 0.02064256], [0.06739051, 0.06795035, 0.0826437, 0.09522087,\n 0.23309189, 0.39055444, 0.39458465, 0.29290532, 0.27204846, 0.17810118,\n 0.24399007, 0.22146653, 0.13732849, 0.07585801, 0.03938794, 0.0190908],\n [0.04337917, 0.05375367, 0.05230119, 0.08066901, 0.16619572, 0.25423056,\n 0.25580913, 0.27430323, 0.22478799, 0.16909017, 0.14284879, 0.17211604,\n 0.14336033, 0.10344522, 0.06797049, 0.02546014], [0.04080687, \n 0.06113728, 0.04392062, 0.04488748, 0.12808591, 0.19886058, 0.24542711,\n 0.19678011, 0.17800136, 0.13147441, 0.13564091, 0.14280335, 0.12969805,\n 0.11181631, 0.05550193, 0.02956066], [0.01432324, 0.03441212, \n 0.05604694, 0.10154456, 0.09204, 0.13341443, 0.13396901, 0.16682638, \n 0.18562675, 0.1299677, 0.09922375, 0.09634331, 0.15184583, 0.13541738, \n 0.1169359, 0.03805293], [0.01972631, 0.02274412, 0.03797545, 0.02036785,\n 0.04357298, 0.05783639, 0.10706321, 0.07688271, 0.06969759, 0.08029393,\n 0.05466604, 0.05129046, 0.04648653, 0.06132882, 0.05004289, 0.03030569]])\n', (14915, 18188), True, 'import numpy as np\n'), ((961, 974), 'numpy.arange', 'np.arange', (['(16)'], {}), '(16)\n', (970, 974), True, 'import numpy as np\n'), ((18899, 18924), 'numpy.empty', 'np.empty', (['(4, nMat, nMat)'], {}), '((4, nMat, nMat))\n', (18907, 18924), True, 'import numpy as np\n'), ((18973, 19014), 'numpy.flatnonzero', 'np.flatnonzero', (['(ages_Mu_min <= age_sep[0])'], {}), '(ages_Mu_min <= age_sep[0])\n', (18987, 19014), True, 'import numpy as np\n'), ((19222, 19263), 'numpy.flatnonzero', 'np.flatnonzero', (['(ages_Mu_min > age_sep[-1])'], {}), '(ages_Mu_min > age_sep[-1])\n', (19236, 19263), True, 'import numpy as np\n'), ((20264, 20278), 'numpy.split', 'np.split', (['X', '(9)'], {}), '(X, 9)\n', (20272, 20278), True, 'import numpy as np\n'), ((21344, 21364), 'copy.deepcopy', 'copy.deepcopy', (['ppars'], {}), '(ppars)\n', (21357, 21364), False, 'import copy\n'), ((25461, 25481), 'copy.deepcopy', 'copy.deepcopy', (['pars0'], {}), '(pars0)\n', (25474, 25481), False, 'import copy\n'), ((26209, 26238), 'numpy.zeros', 'np.zeros', (['coefs_list.shape[0]'], {}), '(coefs_list.shape[0])\n', (26217, 26238), True, 'import numpy as np\n'), ((26671, 26685), 'numpy.empty', 'np.empty', (['(0,)'], {}), '((0,))\n', (26679, 26685), True, 'import numpy as np\n'), ((27548, 27567), 'copy.deepcopy', 'copy.deepcopy', (['pars'], {}), '(pars)\n', (27561, 27567), False, 'import copy\n'), ((29108, 29246), 'pyswarms.single.LocalBestPSO', 'ps.single.LocalBestPSO', ([], {'n_particles': "paramPSO['n_particles']", 'dimensions': 'self.n_to_fit', 'options': "paramPSO['options']", 'bounds': 'self.bound'}), "(n_particles=paramPSO['n_particles'], dimensions=self\n .n_to_fit, options=paramPSO['options'], bounds=self.bound)\n", (29130, 29246), True, 'import pyswarms as ps\n'), ((19080, 19156), 'numpy.flatnonzero', 'np.flatnonzero', (['((ages_Mu_min > age_sep[i - 1]) * (ages_Mu_min <= age_sep[i]))'], {}), '((ages_Mu_min > age_sep[i - 1]) * (ages_Mu_min <= age_sep[i]))\n', (19094, 19156), True, 'import numpy as np\n'), ((21532, 21545), 'numpy.arange', 'np.arange', (['ts'], {}), '(ts)\n', (21541, 21545), True, 'import numpy as np\n'), ((25287, 25309), 'numpy.array', 'np.array', (['bound_new[0]'], {}), '(bound_new[0])\n', (25295, 25309), True, 'import numpy as np\n'), ((25337, 25359), 'numpy.array', 'np.array', (['bound_new[1]'], {}), '(bound_new[1])\n', (25345, 25359), True, 'import numpy as np\n'), ((31106, 31156), 'scipy.optimize.least_squares', 'least_squares', (['self._residuals', 'init'], {'bounds': 'bound'}), '(self._residuals, init, bounds=bound)\n', (31119, 31156), False, 'from scipy.optimize import least_squares\n'), ((22410, 22467), 'scipy.integrate.odeint', 'spi.odeint', (['self._SEIIHURD_age_eq', 'Y[-1]', 't'], {'args': '(pars,)'}), '(self._SEIIHURD_age_eq, Y[-1], t, args=(pars,))\n', (22420, 22467), True, 'import scipy.integrate as spi\n'), ((22655, 22730), 'scipy.integrate.odeint', 'spi.odeint', (['self._SEIIHURD_age_eq', 'Y[-1]', 'tcorte[i - 1:i + 1]'], {'args': '(pars,)'}), '(self._SEIIHURD_age_eq, Y[-1], tcorte[i - 1:i + 1], args=(pars,))\n', (22665, 22730), True, 'import scipy.integrate as spi\n'), ((26595, 26609), 'numpy.sqrt', 'np.sqrt', (['(x + 1)'], {}), '(x + 1)\n', (26602, 26609), True, 'import numpy as np\n'), ((26639, 26654), 'numpy.ones_like', 'np.ones_like', (['x'], {}), '(x)\n', (26651, 26654), True, 'import numpy as np\n'), ((27383, 27397), 'numpy.isnan', 'np.isnan', (['errs'], {}), '(errs)\n', (27391, 27397), True, 'import numpy as np\n'), ((30551, 30587), 'numpy.random.rand', 'np.random.rand', (['nrand', 'self.n_to_fit'], {}), '(nrand, self.n_to_fit)\n', (30565, 30587), True, 'import numpy as np\n'), ((30921, 30960), 'numpy.array', 'np.array', (['[res.cost for res in all_res]'], {}), '([res.cost for res in all_res])\n', (30929, 30960), True, 'import numpy as np\n'), ((30187, 30216), 'numpy.random.rand', 'np.random.rand', (['self.n_to_fit'], {}), '(self.n_to_fit)\n', (30201, 30216), True, 'import numpy as np\n'), ((30325, 30380), 'scipy.optimize.least_squares', 'least_squares', (['self._residuals', 'par0'], {'bounds': 'self.bound'}), '(self._residuals, par0, bounds=self.bound)\n', (30338, 30380), False, 'from scipy.optimize import least_squares\n'), ((30729, 30782), 'scipy.optimize.least_squares', 'least_squares', (['self._residuals', 'p0'], {'bounds': 'self.bound'}), '(self._residuals, p0, bounds=self.bound)\n', (30742, 30782), False, 'from scipy.optimize import least_squares\n'), ((30809, 30857), 'joblib.Parallel', 'joblib.Parallel', ([], {'n_jobs': 'self.numeroProcessadores'}), '(n_jobs=self.numeroProcessadores)\n', (30824, 30857), False, 'import joblib\n'), ((30858, 30875), 'joblib.delayed', 'joblib.delayed', (['f'], {}), '(f)\n', (30872, 30875), False, 'import joblib\n')]
import random import numpy as np import tensorflow as tf from collections import deque class PrioritizedReplayBuffer(): """ Class implements Prioritized Experience Replay (PER) """ def __init__(self, maxlen): """ PER constructor Args: maxlen (int): buffer length """ self.maxlen = None if maxlen == "none" else maxlen self.buffer = deque(maxlen=self.maxlen) self.priorities = deque(maxlen=self.maxlen) def add(self, experience): """ Add experiences to buffer Args: experience (list): state, action, reward, next_state, done Returns: full_buffer (done): True if buffer is full """ full_buffer = len(self.buffer) == self.maxlen self.buffer.append(experience) self.priorities.append(max(self.priorities, default=1)) return full_buffer def get_probabilities(self, priority_scale): """ Get probabilities for experiences Args: priority_scale (float64): range [0, 1] Returns: sample_probabilities (numpy array): probabilities assigned to experiences based on weighting factor (scale) """ scaled_priorities = np.array(self.priorities) ** priority_scale sample_probabilities = scaled_priorities / sum(scaled_priorities) return sample_probabilities def get_importance(self, probabilities): """ Compute importance Args: probabilities (numpy array): experience probabilities Returns: importance_normalized (numpy array): normalized importance """ importance = 1 / len(self.buffer) * 1 / probabilities importance_normalized = importance / max(importance) return importance_normalized def sample(self, batch_size, priority_scale=1.0): """ Sample experiences Args: batch_size (int): size of batch priority_scale (float, optional): range = [0, 1]. Defaults to 1.0. Returns: samples (list): sampled based on probabilities importance (numpy array): Importance of samples sample_indices (array): Indices of samples """ sample_size = min(len(self.buffer), batch_size) sample_probs = self.get_probabilities(priority_scale) sample_indices = random.choices(range(len(self.buffer)), k=sample_size, weights=sample_probs) samples = np.array(self.buffer, dtype=object)[sample_indices] importance = self.get_importance(sample_probs[sample_indices]) return samples, importance, sample_indices def set_priorities(self, indices, errors, offset=0.1): """ Set priorities to experiences Args: indices (array): sample indices errors (array): corresponding losses offset (float, optional): Small offset. Defaults to 0.1. """ for i, e in zip(indices, errors): self.priorities[int(i)] = abs(e) + offset def get_buffer_length(self): """ Get buffer length Returns: (int): buffer length """ return len(self.buffer)
[ "numpy.array", "collections.deque" ]
[((400, 425), 'collections.deque', 'deque', ([], {'maxlen': 'self.maxlen'}), '(maxlen=self.maxlen)\n', (405, 425), False, 'from collections import deque\n'), ((452, 477), 'collections.deque', 'deque', ([], {'maxlen': 'self.maxlen'}), '(maxlen=self.maxlen)\n', (457, 477), False, 'from collections import deque\n'), ((1243, 1268), 'numpy.array', 'np.array', (['self.priorities'], {}), '(self.priorities)\n', (1251, 1268), True, 'import numpy as np\n'), ((2482, 2517), 'numpy.array', 'np.array', (['self.buffer'], {'dtype': 'object'}), '(self.buffer, dtype=object)\n', (2490, 2517), True, 'import numpy as np\n')]
#!/usr/bin/python3 # coding=utf-8 # 环境准备:pip install opencv_contrib_python # 输入话题:tianbot_mini/image_raw/compressed # 输出话题:roi import sys import os import rospy import sensor_msgs.msg from cv_bridge import CvBridge import cv2 import numpy as np from sensor_msgs.msg import RegionOfInterest as ROI from sensor_msgs.msg import CompressedImage br = CvBridge() class MessageItem(object): # 用于封装信息的类,包含图片和其他信息 def __init__(self,frame,message): self._frame = frame self._message = message def getFrame(self): # 图片信息 return self._frame def getMessage(self): #文字信息,json格式 return self._message class Tracker(object): ''' 追踪者模块,用于追踪指定目标 ''' def __init__(self, tracker_type="TLD", draw_coord=True): ''' 初始化追踪器种类 ''' # 获得opencv版本 (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') self.tracker_types = ['BOOSTING', 'MIL', 'KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', "CSRT"] self.tracker_type = tracker_type self.isWorking = False self.draw_coord = draw_coord # 构造追踪器 if int(major_ver) < 3: self.tracker = cv2.Tracker_create(tracker_type) else: if tracker_type == 'BOOSTING': self.tracker = cv2.TrackerBoosting_create() if tracker_type == 'MIL': self.tracker = cv2.TrackerMIL_create() if tracker_type == 'KCF': self.tracker = cv2.TrackerKCF_create() if tracker_type == 'TLD': self.tracker = cv2.TrackerTLD_create() if tracker_type == 'MEDIANFLOW': self.tracker = cv2.TrackerMedianFlow_create() if tracker_type == 'GOTURN': self.tracker = cv2.TrackerGOTURN_create() if tracker_type == "CSRT": self.tracker = cv2.TrackerCSRT_create() def initWorking(self, frame, box): ''' 追踪器工作初始化 frame:初始化追踪画面 box:追踪的区域 ''' if not self.tracker: raise Exception("追踪器未初始化") status = self.tracker.init(frame, box) if not status: raise Exception("追踪器工作初始化失败") self.coord = box self.isWorking = True def track(self, frame): ''' 开启追踪 ''' message = None if self.isWorking: status, self.coord = self.tracker.update(frame) if status: message = {"coord": [((int(self.coord[0]), int(self.coord[1])), (int(self.coord[0] + self.coord[2]), int(self.coord[1] + self.coord[3])))]} if self.draw_coord: p1 = (int(self.coord[0]), int(self.coord[1])) p2 = (int(self.coord[0] + self.coord[2]), int(self.coord[1] + self.coord[3])) cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1) message['msg'] = self.tracker_type + " is tracking" # 更新ROI if (int(self.coord[0]) <0 or int(self.coord[1]) <0): tld_roi.x_offset = 0 tld_roi.y_offset = 0 tld_roi.width = 0 tld_roi.height = 0 else: tld_roi.x_offset = int(self.coord[0]) tld_roi.y_offset = int(self.coord[1]) tld_roi.width = int(self.coord[2]) tld_roi.height = int(self.coord[3]) # 发布ROI pub.publish(tld_roi) return MessageItem(frame, message) def compressed_detect_and_draw(compressed_imgmsg): global br,gFrame,gCapStatus,getFrame,loopGetFrame if ((getFrame == True) or (loopGetFrame == True)): gFrame = br.compressed_imgmsg_to_cv2(compressed_imgmsg, "bgr8") gCapStatus = True getFrame = True gFrame = np.zeros((640,640,3), np.uint8) gCapStatus = False getFrame = True loopGetFrame = False if __name__ == '__main__': rospy.init_node('tbm_tld_tracker_node') rospy.Subscriber("/image_raw", sensor_msgs.msg.CompressedImage, compressed_detect_and_draw) pub = rospy.Publisher("roi",ROI,queue_size=10) tld_roi = ROI() # rate = rospy.Rate(10) # rate.sleep() # 选择 框选帧 print("按 n 渲染下一帧,按 y 设定当前帧作为ROI区域选择帧") while True: _key = cv2.waitKey(0) & 0xFF if(_key == ord('n')): # gCapStatus,gFrame = gVideoDevice.read() getFrame = True if(_key == ord('y')): break cv2.imshow("Pick frame",gFrame) # 框选感兴趣区域region of interest cv2.destroyWindow("Pick frame") gROI = cv2.selectROI("ROI frame",gFrame,False) if (not gROI): print("空框选,退出") quit() # 初始化追踪器 gTracker = Tracker(tracker_type="TLD") gTracker.initWorking(gFrame,gROI) # 循环帧读取,开始跟踪 while not rospy.is_shutdown(): # gCapStatus, gFrame = gVideoDevice.read() loopGetFrame = True if(gCapStatus): # 展示跟踪图片 _item = gTracker.track(gFrame) cv2.imshow("Track result",_item.getFrame()) if _item.getMessage(): # 打印跟踪数据 print(_item.getMessage()) _key = cv2.waitKey(1) & 0xFF if (_key == ord('q')) | (_key == 27): break if (_key == ord('r')) : # 用户请求用初始ROI print("用户请求用初始ROI") gTracker = Tracker(tracker_type="TLD") gTracker.initWorking(gFrame, gROI) else: print("捕获帧失败") quit()
[ "cv2.rectangle", "cv2.TrackerGOTURN_create", "rospy.init_node", "cv2.TrackerKCF_create", "cv2.imshow", "cv2.TrackerMedianFlow_create", "cv2.__version__.split", "cv2.TrackerMIL_create", "cv2.Tracker_create", "cv_bridge.CvBridge", "rospy.Subscriber", "cv2.waitKey", "sensor_msgs.msg.RegionOfInterest", "cv2.TrackerTLD_create", "rospy.Publisher", "cv2.selectROI", "rospy.is_shutdown", "cv2.destroyWindow", "numpy.zeros", "cv2.TrackerBoosting_create", "cv2.TrackerCSRT_create" ]
[((350, 360), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (358, 360), False, 'from cv_bridge import CvBridge\n'), ((4002, 4035), 'numpy.zeros', 'np.zeros', (['(640, 640, 3)', 'np.uint8'], {}), '((640, 640, 3), np.uint8)\n', (4010, 4035), True, 'import numpy as np\n'), ((4124, 4163), 'rospy.init_node', 'rospy.init_node', (['"""tbm_tld_tracker_node"""'], {}), "('tbm_tld_tracker_node')\n", (4139, 4163), False, 'import rospy\n'), ((4168, 4263), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/image_raw"""', 'sensor_msgs.msg.CompressedImage', 'compressed_detect_and_draw'], {}), "('/image_raw', sensor_msgs.msg.CompressedImage,\n compressed_detect_and_draw)\n", (4184, 4263), False, 'import rospy\n'), ((4270, 4312), 'rospy.Publisher', 'rospy.Publisher', (['"""roi"""', 'ROI'], {'queue_size': '(10)'}), "('roi', ROI, queue_size=10)\n", (4285, 4312), False, 'import rospy\n'), ((4325, 4330), 'sensor_msgs.msg.RegionOfInterest', 'ROI', ([], {}), '()\n', (4328, 4330), True, 'from sensor_msgs.msg import RegionOfInterest as ROI\n'), ((4725, 4756), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""Pick frame"""'], {}), "('Pick frame')\n", (4742, 4756), False, 'import cv2\n'), ((4768, 4809), 'cv2.selectROI', 'cv2.selectROI', (['"""ROI frame"""', 'gFrame', '(False)'], {}), "('ROI frame', gFrame, False)\n", (4781, 4809), False, 'import cv2\n'), ((892, 918), 'cv2.__version__.split', 'cv2.__version__.split', (['"""."""'], {}), "('.')\n", (913, 918), False, 'import cv2\n'), ((4656, 4688), 'cv2.imshow', 'cv2.imshow', (['"""Pick frame"""', 'gFrame'], {}), "('Pick frame', gFrame)\n", (4666, 4688), False, 'import cv2\n'), ((4993, 5012), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (5010, 5012), False, 'import rospy\n'), ((1199, 1231), 'cv2.Tracker_create', 'cv2.Tracker_create', (['tracker_type'], {}), '(tracker_type)\n', (1217, 1231), False, 'import cv2\n'), ((4465, 4479), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4476, 4479), False, 'import cv2\n'), ((1320, 1348), 'cv2.TrackerBoosting_create', 'cv2.TrackerBoosting_create', ([], {}), '()\n', (1346, 1348), False, 'import cv2\n'), ((1418, 1441), 'cv2.TrackerMIL_create', 'cv2.TrackerMIL_create', ([], {}), '()\n', (1439, 1441), False, 'import cv2\n'), ((1511, 1534), 'cv2.TrackerKCF_create', 'cv2.TrackerKCF_create', ([], {}), '()\n', (1532, 1534), False, 'import cv2\n'), ((1604, 1627), 'cv2.TrackerTLD_create', 'cv2.TrackerTLD_create', ([], {}), '()\n', (1625, 1627), False, 'import cv2\n'), ((1704, 1734), 'cv2.TrackerMedianFlow_create', 'cv2.TrackerMedianFlow_create', ([], {}), '()\n', (1732, 1734), False, 'import cv2\n'), ((1807, 1833), 'cv2.TrackerGOTURN_create', 'cv2.TrackerGOTURN_create', ([], {}), '()\n', (1831, 1833), False, 'import cv2\n'), ((1904, 1928), 'cv2.TrackerCSRT_create', 'cv2.TrackerCSRT_create', ([], {}), '()\n', (1926, 1928), False, 'import cv2\n'), ((5360, 5374), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5371, 5374), False, 'import cv2\n'), ((2900, 2947), 'cv2.rectangle', 'cv2.rectangle', (['frame', 'p1', 'p2', '(255, 0, 0)', '(2)', '(1)'], {}), '(frame, p1, p2, (255, 0, 0), 2, 1)\n', (2913, 2947), False, 'import cv2\n')]
from __future__ import print_function import warnings import numpy as np C4 = 261.6 # Hz piano_max = 4186.01 # Hz piano_min = 27.5000 # Hz - not audible __all__ = ['cent_per_value','get_f_min','get_f_max','FrequencyScale'] def cent_per_value(f_min, f_max, v_min, v_max): """ This function takes in a frequency max and min, and y value max and min and returns a y scale parameter in units of cents/y value. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/wiki/Cent_(music)). Parameters ---------- f_min : float Minimum frequency. f_max : float Maximum frequency. v_min : float Minimum y value. v_max : float Maximum y value. Returns ------- float A y-scale parameter in units of cents/y value. """ step = 1200 * np.log2(f_max / f_min) / (v_max - v_min) return step def get_f_min(f_max, cents_per_value, v_min, v_max): """ This function takes in a y value max and min, a maximum frequency and a y scale parameter in units of cents/y value, and returns the minimum frequency that fits to such a scale. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/wiki/Cent_(music)). Parameters ---------- f_max : float Maximum frequency. cents_per_value : float A y scale parameter in units of cents/y value. v_min : float Minimum y value. v_max : float Maximum y value. Returns ------- float Minimum frequency. """ f_min = f_max / (2 ** ((v_max - v_min) * cents_per_value / 1200)) return f_min def get_f_max(f_min, cents_per_value, v_min, v_max): """ This function takes in a y value max and min, a minimum frequency and a y scale parameter in units of cents/y value, and returns the maximum frequency that fits to such a scale. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/wiki/Cent_(music)). Parameters ---------- f_min : float Minimum frequency. cents_per_value : float A y scale parameter in units of cents/y value. v_min : float Minimum y value. v_max : float Maximum y value. Returns ------- float Maximum frequency. """ f_max = f_min * (2 ** ((v_max - v_min) * cents_per_value / 1200)) return f_max class FrequencyScale(object): """ This class builds a frequency scale and populates the namespace of frequency objects based on the given inputs from the following combos: - frequency_min, frequency_max, y value min and y value max - frequency_max, cents_per_value, y value min and y value max - frequency_min, cents_per_value, y value min and y value max Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/wiki/Cent_(music)). Parameters ---------- frequency_min : float Minimum frequency. frequency_max : float Maximum frequency. cents_per_value : float A y scale parameter in units of cents/y value. value_min : float Description of parameter `value_min`. value_max : float Description of parameter `value_max`. verbose : bool Flag to toggle printing functions. """ def __init__(self, value_min, value_max, frequency_min=None, frequency_max=None, cents_per_value=None, verbose=False): if verbose: print('initial vals (fmin, fmax, vmin, vmax):', frequency_min, frequency_max, value_min, value_max) # checking for which inputs were given self.y_inputs = [] if frequency_min != None: self.y_inputs.append('frequency_min') if frequency_max != None: self.y_inputs.append('frequency_max') if cents_per_value != None: self.y_inputs.append('cents_per_value') self.y_n_inputs = len(self.y_inputs) # raising exception if anything other than two inputs were given if self.y_n_inputs != 2: raise Exception('Frequency takes 2 of the frequency_min, frequency_max, and cents_per_value inputs. You inputted {} inputs, which were {}.'.format( self.y_n_inputs, self.y_inputs)) # frequency_min and frequency_max input case if (cents_per_value == None): cents_per_value = cent_per_value(frequency_min, frequency_max, value_min, value_max) # cents_per_value and frequency_max input case if (frequency_min == None): frequency_min = get_f_min(frequency_max, cents_per_value, value_min, value_max) # cents_per_value and frequency_min input case if (frequency_max == None): frequency_max = get_f_max(frequency_min, cents_per_value, value_min, value_max) self.y_value_min = value_min self.y_value_max = value_max self.y_frequency_max = frequency_max self.y_frequency_min = frequency_min self.y_cents_per_value = cents_per_value if self.y_frequency_max > piano_max: warnings.warn('Your maximum frequency of {} Hz is above a pianos maximum of {} Hz.'.format( np.round(self.y_frequency_max, 2), piano_max)) if self.y_frequency_min < piano_min: warnings.warn('Your minimum frequency of {} Hz is below a pianos minimum of {} Hz.'.format( np.round(self.y_frequency_min, 2), piano_min)) if self.y_value_min > self.y_value_max: warnings.warn('Min y value is greater than max y value.') if verbose: print('initial vals (f_min, f_max, y_min, y_max):', self.y_frequency_min, self.y_frequency_max, self.y_value_min, self.y_value_max) def freq(v): return self.y_frequency_min * \ 2 ** ((v - self.y_value_min) * self.y_cents_per_value / 1200) self.y_freq_translate_to_range = lambda array: list(map(freq, array)) if verbose: print('Frequency Scale Built')
[ "warnings.warn", "numpy.log2", "numpy.round" ]
[((841, 863), 'numpy.log2', 'np.log2', (['(f_max / f_min)'], {}), '(f_max / f_min)\n', (848, 863), True, 'import numpy as np\n'), ((5680, 5737), 'warnings.warn', 'warnings.warn', (['"""Min y value is greater than max y value."""'], {}), "('Min y value is greater than max y value.')\n", (5693, 5737), False, 'import warnings\n'), ((5361, 5394), 'numpy.round', 'np.round', (['self.y_frequency_max', '(2)'], {}), '(self.y_frequency_max, 2)\n', (5369, 5394), True, 'import numpy as np\n'), ((5573, 5606), 'numpy.round', 'np.round', (['self.y_frequency_min', '(2)'], {}), '(self.y_frequency_min, 2)\n', (5581, 5606), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue May 30 16:43:10 2017 ☜☜☜☜☜☜★☆★☆★☆★☆ provided code ★☆★☆★☆★☆☞☞☞☞☞☞ @author: Minsooyeo """ import os import matplotlib.image as mpimg import matplotlib.pyplot as plt from PIL import Image as im import numpy as np import utills as ut import tensorflow as tf sess = tf.InteractiveSession() train_epoch = 5000 # FLAG_FINGER = 0 FLAG_FACE = 1 FLAG_ANGLE = 2 flag = FLAG_ANGLE # if flag is FLAG_FINGER: class_num = 5 additional_path = '\\finger\\' elif flag is FLAG_FACE: class_num = 6 additional_path = '\\face\\' elif flag is FLAG_ANGLE: class_num = 4 additional_path = '\\angle\\' else: raise Exception("Unknown flag %d" %flag) # define parameter data_length = [] dir_image = [] data = [] label = [] data_shape = [298, 298] current_pwd = os.getcwd() for i in range(class_num): dir_image.append(ut.search(current_pwd + additional_path + str(i + 1))) data_length.append(len(dir_image[i])) data.append(np.zeros([data_length[i], data_shape[1], data_shape[0]])) label.append(np.zeros([data_length[i], class_num])) label[i][:, i] = 1 # load data for q in range(class_num): for i in range(data_length[q]): if i % 100 == 0: print("%dth data is opening" %i) data[q][i, :, :] = np.mean(im.open(current_pwd + additional_path + str(q + 1) + '\\' + dir_image[q][i]), -1) if flag is FLAG_FINGER: rawdata = np.concatenate((data[0], data[1], data[2], data[3], data[4]), axis=0) raw_label = np.concatenate((label[0], label[1], label[2], label[3], label[4]), axis=0) elif flag is FLAG_FACE: rawdata = np.concatenate((data[0], data[1], data[2], data[3], data[4], data[5]), axis=0) raw_label = np.concatenate((label[0], label[1], label[2], label[3], label[4], label[5]), axis=0) elif flag is FLAG_ANGLE: rawdata = np.concatenate((data[0], data[1], data[2], data[3]), axis=0) raw_label = np.concatenate((label[0], label[1], label[2], label[3]), axis=0) else: raise Exception("Unknown class number %d" %class_num) del data del label total_data_poin = rawdata.shape[0] permutation = np.random.permutation(total_data_poin) rawdata = rawdata[permutation, :, :] raw_label = raw_label[permutation, :] rawdata = np.reshape(rawdata, [rawdata.shape[0], data_shape[0] * data_shape[1]]) ######################################################################################################## # img_width = data_shape[0] img_height = data_shape[1] if flag is FLAG_FINGER: train_count = 5000 # 손가락 인식을 테스트하려는 경우 이 부분을 수정하십시오. (2000 또는 5000으로 테스트함) test_count = 490 elif flag is FLAG_FACE: train_count = 2000 # train data 수가 5000개가 안 돼서 또는 overfitting에 의해 NaN 문제가 발생합니다. 값을 바꾸지 마십시오! test_count = 490 elif flag is FLAG_ANGLE: train_count = 6000 # train data 수가 5000개가 안 돼서 또는 overfitting에 의해 NaN 문제가 발생합니다. 값을 바꾸지 마십시오! test_count = 1000 else: raise Exception("unknown flag %d" %flag) # train_epoch = train_count # TrainX = rawdata[:train_count] # mnist.train.images TrainY = raw_label[:train_count] # mnist.train.labels testX = rawdata[train_count:train_count+test_count] # mnist.test.images testY = raw_label[train_count:train_count+test_count] # mnist.test.labels # 손가락 구분을 테스트하기 위해 층의 수를 바꾸는 경우 else 부분을 수정하십시오. if flag is FLAG_FINGER: # 손가락 구분의 경우 층에 따라 경우를 테스트하려면 이 부분을 수정하십시오. CNNModel, x = ut._CNNModel(img_width=img_width, img_height=img_height, kernel_info=[ [3, 2, 32, True], [3, 2, 64, True], [3, 2, 128, True], [3, 2, 64, True], [3, 2, 128, True], # [3, 2, 128, True], ]) elif flag is FLAG_FACE: # 얼굴 인식의 경우 2개의 층만으로도 구분이 완전히 잘 됩니다. 층의 수를 수정하지 마십시오. CNNModel, x = ut._CNNModel(img_width=img_width, img_height=img_height, kernel_info=[ [3, 2, 32, True], [3, 2, 64, True], # [3, 2, 128, True], # [3, 2, 64, True], # [3, 2, 128, True], # [3, 2, 128, True], ]) elif flag is FLAG_ANGLE: # CNNModel, x = ut._CNNModel(img_width=img_width, img_height=img_height, kernel_info=[ [1, 1, 32, True], # [1, 1, 64, True], # [1, 1, 128, True], # [1, 1, 64, True], # [1, 1, 128, True], # [3, 2, 128, True], ]) else: raise Exception("Unknown flag %d" %flag) FlatModel = ut._FlatModel(CNNModel, fc_outlayer_count=128) DropOut, keep_prob = ut._DropOut(FlatModel) SoftMaxModel = ut._SoftMax(DropOut, label_count=class_num, fc_outlayer_count=128) TrainStep, Accuracy, y_, correct_prediction = ut._SetAccuracy(SoftMaxModel, label_count=class_num) sess.run(tf.global_variables_initializer()) for i in range(train_epoch): tmp_trainX, tmp_trainY = ut.Nextbatch(TrainX, TrainY, 50) if i%100 == 0: train_accuracy = Accuracy.eval(feed_dict={x: tmp_trainX, y_: tmp_trainY, keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) TrainStep.run(feed_dict={x: tmp_trainX, y_: tmp_trainY, keep_prob: 0.7}) print("test accuracy %g" %Accuracy.eval(feed_dict={x: testX[1:1000, :], y_: testY[1:1000], keep_prob: 1.0}))
[ "tensorflow.InteractiveSession", "numpy.reshape", "utills._FlatModel", "utills._DropOut", "utills._SoftMax", "os.getcwd", "tensorflow.global_variables_initializer", "utills._CNNModel", "numpy.zeros", "numpy.concatenate", "utills.Nextbatch", "utills._SetAccuracy", "numpy.random.permutation" ]
[((305, 328), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (326, 328), True, 'import tensorflow as tf\n'), ((809, 820), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (818, 820), False, 'import os\n'), ((2117, 2155), 'numpy.random.permutation', 'np.random.permutation', (['total_data_poin'], {}), '(total_data_poin)\n', (2138, 2155), True, 'import numpy as np\n'), ((2242, 2312), 'numpy.reshape', 'np.reshape', (['rawdata', '[rawdata.shape[0], data_shape[0] * data_shape[1]]'], {}), '(rawdata, [rawdata.shape[0], data_shape[0] * data_shape[1]])\n', (2252, 2312), True, 'import numpy as np\n'), ((4957, 5003), 'utills._FlatModel', 'ut._FlatModel', (['CNNModel'], {'fc_outlayer_count': '(128)'}), '(CNNModel, fc_outlayer_count=128)\n', (4970, 5003), True, 'import utills as ut\n'), ((5025, 5047), 'utills._DropOut', 'ut._DropOut', (['FlatModel'], {}), '(FlatModel)\n', (5036, 5047), True, 'import utills as ut\n'), ((5063, 5129), 'utills._SoftMax', 'ut._SoftMax', (['DropOut'], {'label_count': 'class_num', 'fc_outlayer_count': '(128)'}), '(DropOut, label_count=class_num, fc_outlayer_count=128)\n', (5074, 5129), True, 'import utills as ut\n'), ((5176, 5228), 'utills._SetAccuracy', 'ut._SetAccuracy', (['SoftMaxModel'], {'label_count': 'class_num'}), '(SoftMaxModel, label_count=class_num)\n', (5191, 5228), True, 'import utills as ut\n'), ((1423, 1492), 'numpy.concatenate', 'np.concatenate', (['(data[0], data[1], data[2], data[3], data[4])'], {'axis': '(0)'}), '((data[0], data[1], data[2], data[3], data[4]), axis=0)\n', (1437, 1492), True, 'import numpy as np\n'), ((1509, 1583), 'numpy.concatenate', 'np.concatenate', (['(label[0], label[1], label[2], label[3], label[4])'], {'axis': '(0)'}), '((label[0], label[1], label[2], label[3], label[4]), axis=0)\n', (1523, 1583), True, 'import numpy as np\n'), ((3361, 3531), 'utills._CNNModel', 'ut._CNNModel', ([], {'img_width': 'img_width', 'img_height': 'img_height', 'kernel_info': '[[3, 2, 32, True], [3, 2, 64, True], [3, 2, 128, True], [3, 2, 64, True], [\n 3, 2, 128, True]]'}), '(img_width=img_width, img_height=img_height, kernel_info=[[3, 2,\n 32, True], [3, 2, 64, True], [3, 2, 128, True], [3, 2, 64, True], [3, 2,\n 128, True]])\n', (3373, 3531), True, 'import utills as ut\n'), ((5239, 5272), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (5270, 5272), True, 'import tensorflow as tf\n'), ((5333, 5365), 'utills.Nextbatch', 'ut.Nextbatch', (['TrainX', 'TrainY', '(50)'], {}), '(TrainX, TrainY, 50)\n', (5345, 5365), True, 'import utills as ut\n'), ((982, 1038), 'numpy.zeros', 'np.zeros', (['[data_length[i], data_shape[1], data_shape[0]]'], {}), '([data_length[i], data_shape[1], data_shape[0]])\n', (990, 1038), True, 'import numpy as np\n'), ((1057, 1094), 'numpy.zeros', 'np.zeros', (['[data_length[i], class_num]'], {}), '([data_length[i], class_num])\n', (1065, 1094), True, 'import numpy as np\n'), ((1622, 1700), 'numpy.concatenate', 'np.concatenate', (['(data[0], data[1], data[2], data[3], data[4], data[5])'], {'axis': '(0)'}), '((data[0], data[1], data[2], data[3], data[4], data[5]), axis=0)\n', (1636, 1700), True, 'import numpy as np\n'), ((1717, 1805), 'numpy.concatenate', 'np.concatenate', (['(label[0], label[1], label[2], label[3], label[4], label[5])'], {'axis': '(0)'}), '((label[0], label[1], label[2], label[3], label[4], label[5]),\n axis=0)\n', (1731, 1805), True, 'import numpy as np\n'), ((3916, 4026), 'utills._CNNModel', 'ut._CNNModel', ([], {'img_width': 'img_width', 'img_height': 'img_height', 'kernel_info': '[[3, 2, 32, True], [3, 2, 64, True]]'}), '(img_width=img_width, img_height=img_height, kernel_info=[[3, 2,\n 32, True], [3, 2, 64, True]])\n', (3928, 4026), True, 'import utills as ut\n'), ((1841, 1901), 'numpy.concatenate', 'np.concatenate', (['(data[0], data[1], data[2], data[3])'], {'axis': '(0)'}), '((data[0], data[1], data[2], data[3]), axis=0)\n', (1855, 1901), True, 'import numpy as np\n'), ((1918, 1982), 'numpy.concatenate', 'np.concatenate', (['(label[0], label[1], label[2], label[3])'], {'axis': '(0)'}), '((label[0], label[1], label[2], label[3]), axis=0)\n', (1932, 1982), True, 'import numpy as np\n'), ((4426, 4518), 'utills._CNNModel', 'ut._CNNModel', ([], {'img_width': 'img_width', 'img_height': 'img_height', 'kernel_info': '[[1, 1, 32, True]]'}), '(img_width=img_width, img_height=img_height, kernel_info=[[1, 1,\n 32, True]])\n', (4438, 4518), True, 'import utills as ut\n')]
import numpy as np from common import projection_back EPS = 1e-9 def ilrma(mix, n_iter, n_basis=2, proj_back=True): """Implementation of ILRMA (Independent Low-Rank Matrix Analysis). This algorithm is called ILRMA1 in http://d-kitamura.net/pdf/misc/AlgorithmsForIndependentLowRankMatrixAnalysis.pdf It only works in determined case (n_sources == n_channels). Args: mix (numpy.ndarray): (n_frequencies, n_channels, n_frames) STFT representation of the observed signal. n_iter (int): Number of iterations. n_basis (int): Number of basis in the NMF model. proj_back (bool): If use back-projection technique. Returns: tuple[numpy.ndarray, numpy.ndarray]: Tuple of separated signal and separation matrix. The shapes of separated signal and separation matrix are (n_frequencies, n_sources, n_frames) and (n_sources, n_channels), respectively. """ n_freq, n_src, n_frame = mix.shape sep_mat = np.stack([np.eye(n_src, dtype=mix.dtype) for _ in range(n_freq)]) basis = np.abs(np.random.randn(n_src, n_freq, n_basis)) act = np.abs(np.random.randn(n_src, n_basis, n_frame)) sep = sep_mat @ mix sep_pow = np.power(np.abs(sep), 2) # (n_freq, n_src, n_frame) model = basis @ act # (n_src, n_freq, n_frame) m_reci = 1 / model eye = np.tile(np.eye(n_src), (n_freq, 1, 1)) for _ in range(n_iter): for src in range(n_src): h = (sep_pow[:, src, :] * m_reci[src]**2) @ act[src].T h /= m_reci[src] @ act[src].T h = np.sqrt(h, out=h) basis[src] *= h np.clip(basis[src], a_min=EPS, a_max=None, out=basis[src]) model[src] = basis[src] @ act[src] m_reci[src] = 1 / model[src] h = basis[src].T @ (sep_pow[:, src, :] * m_reci[src]**2) h /= basis[src].T @ m_reci[src] h = np.sqrt(h, out=h) act[src] *= h np.clip(act[src], a_min=EPS, a_max=None, out=act[src]) model[src] = basis[src] @ act[src] m_reci[src] = 1 / model[src] h = m_reci[src, :, :, None] @ np.ones((1, n_src)) h = mix.conj() @ (mix.swapaxes(1, 2) * h) u_mat = h.swapaxes(1, 2) / n_frame h = sep_mat @ u_mat + EPS * eye sep_mat[:, src, :] = np.linalg.solve(h, eye[:, :, src]).conj() h = sep_mat[:, src, None, :] @ u_mat h = (h @ sep_mat[:, src, :, None].conj()).squeeze(2) sep_mat[:, src, :] = (sep_mat[:, src, :] / np.sqrt(h).conj()) np.matmul(sep_mat, mix, out=sep) np.power(np.abs(sep), 2, out=sep_pow) np.clip(sep_pow, a_min=EPS, a_max=None, out=sep_pow) for src in range(n_src): lbd = np.sqrt(np.sum(sep_pow[:, src, :]) / n_freq / n_frame) sep_mat[:, src, :] /= lbd sep_pow[:, src, :] /= lbd ** 2 model[src] /= lbd ** 2 basis[src] /= lbd ** 2 # Back-projection technique if proj_back: z = projection_back(sep, mix[:, 0, :]) sep *= np.conj(z[:, :, None]) return sep, sep_mat
[ "numpy.clip", "numpy.abs", "numpy.eye", "numpy.linalg.solve", "numpy.sqrt", "numpy.ones", "numpy.conj", "numpy.sum", "numpy.matmul", "common.projection_back", "numpy.random.randn" ]
[((1098, 1137), 'numpy.random.randn', 'np.random.randn', (['n_src', 'n_freq', 'n_basis'], {}), '(n_src, n_freq, n_basis)\n', (1113, 1137), True, 'import numpy as np\n'), ((1156, 1196), 'numpy.random.randn', 'np.random.randn', (['n_src', 'n_basis', 'n_frame'], {}), '(n_src, n_basis, n_frame)\n', (1171, 1196), True, 'import numpy as np\n'), ((1245, 1256), 'numpy.abs', 'np.abs', (['sep'], {}), '(sep)\n', (1251, 1256), True, 'import numpy as np\n'), ((1383, 1396), 'numpy.eye', 'np.eye', (['n_src'], {}), '(n_src)\n', (1389, 1396), True, 'import numpy as np\n'), ((2617, 2649), 'numpy.matmul', 'np.matmul', (['sep_mat', 'mix'], {'out': 'sep'}), '(sep_mat, mix, out=sep)\n', (2626, 2649), True, 'import numpy as np\n'), ((2704, 2756), 'numpy.clip', 'np.clip', (['sep_pow'], {'a_min': 'EPS', 'a_max': 'None', 'out': 'sep_pow'}), '(sep_pow, a_min=EPS, a_max=None, out=sep_pow)\n', (2711, 2756), True, 'import numpy as np\n'), ((3078, 3112), 'common.projection_back', 'projection_back', (['sep', 'mix[:, 0, :]'], {}), '(sep, mix[:, 0, :])\n', (3093, 3112), False, 'from common import projection_back\n'), ((3128, 3150), 'numpy.conj', 'np.conj', (['z[:, :, None]'], {}), '(z[:, :, None])\n', (3135, 3150), True, 'import numpy as np\n'), ((1023, 1053), 'numpy.eye', 'np.eye', (['n_src'], {'dtype': 'mix.dtype'}), '(n_src, dtype=mix.dtype)\n', (1029, 1053), True, 'import numpy as np\n'), ((1601, 1618), 'numpy.sqrt', 'np.sqrt', (['h'], {'out': 'h'}), '(h, out=h)\n', (1608, 1618), True, 'import numpy as np\n'), ((1659, 1717), 'numpy.clip', 'np.clip', (['basis[src]'], {'a_min': 'EPS', 'a_max': 'None', 'out': 'basis[src]'}), '(basis[src], a_min=EPS, a_max=None, out=basis[src])\n', (1666, 1717), True, 'import numpy as np\n'), ((1937, 1954), 'numpy.sqrt', 'np.sqrt', (['h'], {'out': 'h'}), '(h, out=h)\n', (1944, 1954), True, 'import numpy as np\n'), ((1993, 2047), 'numpy.clip', 'np.clip', (['act[src]'], {'a_min': 'EPS', 'a_max': 'None', 'out': 'act[src]'}), '(act[src], a_min=EPS, a_max=None, out=act[src])\n', (2000, 2047), True, 'import numpy as np\n'), ((2667, 2678), 'numpy.abs', 'np.abs', (['sep'], {}), '(sep)\n', (2673, 2678), True, 'import numpy as np\n'), ((2180, 2199), 'numpy.ones', 'np.ones', (['(1, n_src)'], {}), '((1, n_src))\n', (2187, 2199), True, 'import numpy as np\n'), ((2378, 2412), 'numpy.linalg.solve', 'np.linalg.solve', (['h', 'eye[:, :, src]'], {}), '(h, eye[:, :, src])\n', (2393, 2412), True, 'import numpy as np\n'), ((2589, 2599), 'numpy.sqrt', 'np.sqrt', (['h'], {}), '(h)\n', (2596, 2599), True, 'import numpy as np\n'), ((2817, 2843), 'numpy.sum', 'np.sum', (['sep_pow[:, src, :]'], {}), '(sep_pow[:, src, :])\n', (2823, 2843), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # [0,0] = TN # [1,1] = TP # [0,1] = FP # [1,0] = FN # cm is a confusion matrix # Accuracy: (TP + TN) / Total def accuracy(cm: pd.DataFrame) -> float: return (cm[0,0] + cm[1,1]) / cm.sum() # Precision: TP / (TP + FP) def precision(cm: pd.DataFrame) -> float: return cm[1,1] / (cm[1,1] + cm[0,1]) # False positive rate: FP / N = FP / (FP + TN) def false_positive(cm: pd.DataFrame) -> float: return cm[0,1] / (cm[0,0] + cm[0,1]) # True positive rate: TP / P = TP / (TP + FN) # Equivalent to sensitivity/recall def true_positive(cm: pd.DataFrame) -> float: return cm[1,1] / (cm[1,0] + cm[1,1]) # F1 score: 2 * precision * recall / (precision + recall) def f_score(cm: pd.DataFrame) -> float: return 2 * precision(cm) * true_positive(cm) / (precision(cm) + true_positive(cm)) # Returns a confusion matrix for labels and predictions # [[TN, FP], # [FN, TP]] def confusion_matrix(y, y_hat): cm = np.zeros((2, 2)) np.add.at(cm, [y.astype(int), y_hat.astype(int)], 1) return cm def visualize_cm(cm): df_cm = pd.DataFrame(cm, columns=['0', '1'], index=['0', '1']) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' plt.figure(figsize=(5, 3)) sns.heatmap(df_cm, cmap='Blues', annot=True, annot_kws={'size': 16}, fmt='g') # Function to return two shuffled arrays, is a deep copy def shuffle(x, y): x_copy = x.copy() y_copy = y.copy() rand = np.random.randint(0, 10000) np.random.seed(rand) np.random.shuffle(x_copy) np.random.seed(rand) np.random.shuffle(y_copy) return x_copy, y_copy # Shuffles and splits data into two sets # test split will be 1/size of the data def split(x, y, size): x1, y1, = shuffle(x, y) x1_test = x1[0:int(x1.shape[0] / size)] x1_train = x1[int(x1.shape[0] / size):] y1_test = y1[0:int(y1.shape[0] / size)] y1_train = y1[int(y1.shape[0] / size):] return x1_train, x1_test, y1_train, y1_test def cross_validation(k, X, Y, model, lr=0.5, regularization=0, eps=1e-2, verbose=True): # randomize X and Y by shuffling x, y = shuffle(X, Y) # split into k folds x_folds = np.array_split(x, k) y_folds = np.array_split(y, k) acc = 0 f1 = 0 prec = 0 rec = 0 cms = [] for i in range(k): validation_features = x_folds[i] validation_labels = np.squeeze(y_folds[i]) train_features = np.delete(x_folds, i, axis=0) train_features = np.concatenate(train_features) train_labels = np.delete(y_folds, i, axis=0) train_labels = np.concatenate(train_labels) m = model(train_features, train_labels) m.fit(lr, verbose=False, regularization=regularization, eps=eps) predicted_labels = m.predict(validation_features) cm = confusion_matrix(validation_labels, predicted_labels) acc += accuracy(cm) f1 += f_score(cm) prec += precision(cm) rec += true_positive(cm) cms.append(cm) if verbose: print("Accuracy:", acc/k, "Precision:", prec/k, "Recall:", rec/k, "F1:", f1/k) # Return the accuracy and array of confusion matrices return acc/k, np.array(cms) # assume 5 fold for now def cross_validation_naive(k, df, model, label, cont=[], cat=[], bin=[]): df = df.copy(deep=True) np.random.shuffle(df.values) df = df.reset_index(drop=True) indices = np.arange(df.shape[0]) indices = np.array_split(indices, k) acc = 0 f1 = 0 prec = 0 rec = 0 cms = [] for i in range(k): val = df.loc[indices[i]] train = df.loc[np.concatenate(np.delete(indices, i, axis=0))] m = model(train, label, cont, cat, bin) pred = val.apply(m.predict, axis=1) cm = confusion_matrix(val[label], pred) acc += accuracy(cm) f1 += f_score(cm) prec += precision(cm) rec += true_positive(cm) cms.append(cm) print("Accuracy:", acc / k, "Precision:", prec / k, "Recall:", rec / k, "F1:", f1 / k) # Return the accuracy and array of confusion matrices return acc / k, np.array(cms) def cv_task_2(k, X, Y, model, lr = 0.5, regularization=0, eps = 1e-2, iterations=200): # randomize X and Y by shuffling x, y = shuffle(X, Y) # split into k folds x_folds = np.array_split(x, k) y_folds = np.array_split(y, k) train_acc_history = np.empty([k, iterations]) val_acc_history = np.empty([k, iterations]) for i in range(k): val_features = x_folds[i] val_labels = np.squeeze(y_folds[i]) train_features = np.delete(x_folds, i) train_features = np.concatenate(train_features) train_labels = np.delete(y_folds, i, axis=0) train_labels = np.concatenate(train_labels) m = model(train_features, train_labels) costs = [] train_accuracies = [] val_accuracies = [] # Keep on training until difference reached threshold for j in range(iterations): # fit model for 1 iteration cost = m.fit(lr=lr, verbose=False, regularization=regularization, eps=None, epochs=1) costs.append(cost) # predict the labels and eval accuracy for train and val split val_pred_labels = m.predict(val_features) train_pred_labels = m.predict(train_features) cm_val = confusion_matrix(val_labels, val_pred_labels) cm_train = confusion_matrix(train_labels, train_pred_labels) val_accuracies.append(accuracy(cm_val)) train_accuracies.append(accuracy(cm_train)) # store the costs and accuracies train_acc_history[i] = np.array(train_accuracies) val_acc_history[i] = np.array(val_accuracies) return train_acc_history, val_acc_history def grid_search(learning_rates, epsilons, lambdas, x, y, model): max_acc = 0 arg_max = [0,0,0] for lr in learning_rates: for eps in epsilons: for regularization in lambdas: #print(lr, eps, regularization) acc, cm = cross_validation(5, x, y, lr=lr, eps=eps, regularization=regularization, model=model, verbose=False) if acc > max_acc: max_acc = acc arg_max = [lr, eps, regularization] max_cm = cm f1 = [] prec = [] rec = [] for cm in max_cm: f1.append(f_score(cm)) prec.append(precision(cm)) rec.append(true_positive(cm)) f1 = np.mean(f1) prec = np.mean(prec) rec = np.mean(rec) print(arg_max) print("Accuracy:", max_acc, "Precision:", prec, "Recall:", rec, "F1:", f1) return max_acc, arg_max
[ "numpy.mean", "numpy.delete", "seaborn.heatmap", "numpy.squeeze", "numpy.array_split", "numpy.array", "numpy.random.randint", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.random.seed", "numpy.empty", "numpy.concatenate", "pandas.DataFrame", "numpy.arange", "numpy.random.shuffle" ]
[((1018, 1034), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (1026, 1034), True, 'import numpy as np\n'), ((1142, 1196), 'pandas.DataFrame', 'pd.DataFrame', (['cm'], {'columns': "['0', '1']", 'index': "['0', '1']"}), "(cm, columns=['0', '1'], index=['0', '1'])\n", (1154, 1196), True, 'import pandas as pd\n'), ((1270, 1296), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)'}), '(figsize=(5, 3))\n', (1280, 1296), True, 'import matplotlib.pyplot as plt\n'), ((1301, 1378), 'seaborn.heatmap', 'sns.heatmap', (['df_cm'], {'cmap': '"""Blues"""', 'annot': '(True)', 'annot_kws': "{'size': 16}", 'fmt': '"""g"""'}), "(df_cm, cmap='Blues', annot=True, annot_kws={'size': 16}, fmt='g')\n", (1312, 1378), True, 'import seaborn as sns\n'), ((1512, 1539), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (1529, 1539), True, 'import numpy as np\n'), ((1544, 1564), 'numpy.random.seed', 'np.random.seed', (['rand'], {}), '(rand)\n', (1558, 1564), True, 'import numpy as np\n'), ((1569, 1594), 'numpy.random.shuffle', 'np.random.shuffle', (['x_copy'], {}), '(x_copy)\n', (1586, 1594), True, 'import numpy as np\n'), ((1599, 1619), 'numpy.random.seed', 'np.random.seed', (['rand'], {}), '(rand)\n', (1613, 1619), True, 'import numpy as np\n'), ((1624, 1649), 'numpy.random.shuffle', 'np.random.shuffle', (['y_copy'], {}), '(y_copy)\n', (1641, 1649), True, 'import numpy as np\n'), ((2225, 2245), 'numpy.array_split', 'np.array_split', (['x', 'k'], {}), '(x, k)\n', (2239, 2245), True, 'import numpy as np\n'), ((2260, 2280), 'numpy.array_split', 'np.array_split', (['y', 'k'], {}), '(y, k)\n', (2274, 2280), True, 'import numpy as np\n'), ((3390, 3418), 'numpy.random.shuffle', 'np.random.shuffle', (['df.values'], {}), '(df.values)\n', (3407, 3418), True, 'import numpy as np\n'), ((3469, 3491), 'numpy.arange', 'np.arange', (['df.shape[0]'], {}), '(df.shape[0])\n', (3478, 3491), True, 'import numpy as np\n'), ((3506, 3532), 'numpy.array_split', 'np.array_split', (['indices', 'k'], {}), '(indices, k)\n', (3520, 3532), True, 'import numpy as np\n'), ((4387, 4407), 'numpy.array_split', 'np.array_split', (['x', 'k'], {}), '(x, k)\n', (4401, 4407), True, 'import numpy as np\n'), ((4422, 4442), 'numpy.array_split', 'np.array_split', (['y', 'k'], {}), '(y, k)\n', (4436, 4442), True, 'import numpy as np\n'), ((4468, 4493), 'numpy.empty', 'np.empty', (['[k, iterations]'], {}), '([k, iterations])\n', (4476, 4493), True, 'import numpy as np\n'), ((4516, 4541), 'numpy.empty', 'np.empty', (['[k, iterations]'], {}), '([k, iterations])\n', (4524, 4541), True, 'import numpy as np\n'), ((6602, 6613), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (6609, 6613), True, 'import numpy as np\n'), ((6625, 6638), 'numpy.mean', 'np.mean', (['prec'], {}), '(prec)\n', (6632, 6638), True, 'import numpy as np\n'), ((6649, 6661), 'numpy.mean', 'np.mean', (['rec'], {}), '(rec)\n', (6656, 6661), True, 'import numpy as np\n'), ((2436, 2458), 'numpy.squeeze', 'np.squeeze', (['y_folds[i]'], {}), '(y_folds[i])\n', (2446, 2458), True, 'import numpy as np\n'), ((2485, 2514), 'numpy.delete', 'np.delete', (['x_folds', 'i'], {'axis': '(0)'}), '(x_folds, i, axis=0)\n', (2494, 2514), True, 'import numpy as np\n'), ((2540, 2570), 'numpy.concatenate', 'np.concatenate', (['train_features'], {}), '(train_features)\n', (2554, 2570), True, 'import numpy as np\n'), ((2594, 2623), 'numpy.delete', 'np.delete', (['y_folds', 'i'], {'axis': '(0)'}), '(y_folds, i, axis=0)\n', (2603, 2623), True, 'import numpy as np\n'), ((2647, 2675), 'numpy.concatenate', 'np.concatenate', (['train_labels'], {}), '(train_labels)\n', (2661, 2675), True, 'import numpy as np\n'), ((3245, 3258), 'numpy.array', 'np.array', (['cms'], {}), '(cms)\n', (3253, 3258), True, 'import numpy as np\n'), ((4181, 4194), 'numpy.array', 'np.array', (['cms'], {}), '(cms)\n', (4189, 4194), True, 'import numpy as np\n'), ((4622, 4644), 'numpy.squeeze', 'np.squeeze', (['y_folds[i]'], {}), '(y_folds[i])\n', (4632, 4644), True, 'import numpy as np\n'), ((4671, 4692), 'numpy.delete', 'np.delete', (['x_folds', 'i'], {}), '(x_folds, i)\n', (4680, 4692), True, 'import numpy as np\n'), ((4718, 4748), 'numpy.concatenate', 'np.concatenate', (['train_features'], {}), '(train_features)\n', (4732, 4748), True, 'import numpy as np\n'), ((4772, 4801), 'numpy.delete', 'np.delete', (['y_folds', 'i'], {'axis': '(0)'}), '(y_folds, i, axis=0)\n', (4781, 4801), True, 'import numpy as np\n'), ((4825, 4853), 'numpy.concatenate', 'np.concatenate', (['train_labels'], {}), '(train_labels)\n', (4839, 4853), True, 'import numpy as np\n'), ((5760, 5786), 'numpy.array', 'np.array', (['train_accuracies'], {}), '(train_accuracies)\n', (5768, 5786), True, 'import numpy as np\n'), ((5816, 5840), 'numpy.array', 'np.array', (['val_accuracies'], {}), '(val_accuracies)\n', (5824, 5840), True, 'import numpy as np\n'), ((3691, 3720), 'numpy.delete', 'np.delete', (['indices', 'i'], {'axis': '(0)'}), '(indices, i, axis=0)\n', (3700, 3720), True, 'import numpy as np\n')]
import math import random import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory from fmt.pythonfmt.world import World def dist2(p, q): return math.sqrt((p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2) # FMTree class class FMTree: # s_init::Vec4f # s_goal::Vec4f # N #number of samples # Pset::Vector{Vec4f} # Point set # cost::Vector{Float64} #cost # time::Vector{Float64} #optimal time to connect one node to its parent node # parent::Vector{Int64} #parent node # bool_unvisit::BitVector #logical value for Vunvisit # bool_open::BitVector #logical value for Open # bool_closed::BitVector #logical value for Closed # world::World # simulation world config # itr::Int64 # iteration num def __init__(self, s_init, s_goal, N, world): # constructer: sampling valid point from the configurationspace print("initializing fmt ...") self.s_init = s_init self.s_goal = s_goal self.N = N self.world = world self.Pset = np.zeros((N, 4)) self.Pset[0, :] = np.array(s_init) def myrn(min, max): return min + (max - min) * random.random() # 采样N个点 n = 1 while True: num_ran = 2*N rp = np.empty((4, num_ran)) rp[0, :] = np.random.default_rng().uniform(self.world.x_min[0], self.world.x_max[0], num_ran) rp[1, :] = np.random.default_rng().uniform(self.world.x_min[1], self.world.x_max[1], num_ran) rp[2, :] = np.random.default_rng().uniform(self.world.v_min[0], self.world.v_max[0], num_ran) rp[3, :] = np.random.default_rng().uniform(self.world.v_min[1], self.world.v_max[1], num_ran) # p = np.array([myrn(world.x_min[0], world.x_max[0]), # myrn(world.x_min[1], world.x_max[1]), # myrn(world.v_min[0], world.v_max[0]), # myrn(world.v_min[1], world.v_max[1])]) for i_rp in range(0, num_ran): if self.world.isValid(rp[:, i_rp]): self.Pset[n, :] = rp[:, i_rp] n = n + 1 if n == N-1: break if n == N-1: break self.Pset[-1, :] = np.array(s_goal) # inply idx_goal = N [last] ? 修改為最後一個是終點 self.cost = np.zeros(N) self.time = np.zeros(N) self.parent = np.zeros(N, dtype=int) self.bool_unvisit = np.ones(N, dtype=np.bool_) self.bool_unvisit[0] = False self.bool_closed = np.zeros(N, dtype=np.bool_) self.bool_open = np.zeros(N, dtype=np.bool_) self.bool_open[0] = True self.itr = 0 print("finish initializing") # new(s_init, s_goal, # N, Pset, cost, time, parent, bool_unvisit, bool_open, bool_closed, world, 0) def show(self, ax): print("drawing...") # 先画障碍物 N = len(self.Pset) mat = np.zeros((2, N)) for idx in range(0, N): mat[:, idx] = self.Pset[idx, 0:2] idxset_open = np.nonzero(self.bool_open)[0] idxset_closed = np.nonzero(self.bool_closed)[0] idxset_unvisit = np.nonzero(self.bool_unvisit)[0] # idxset_tree = setdiff(union(idxset_open, idxset_closed), [1]) idxset_tree = np.concatenate((idxset_closed, idxset_open)) # 没有和原来一样去除 id 1 # 起点,重点,open, close ax.scatter(mat[0, 0], mat[1, 0], c='blue', s=20, zorder=100) ax.scatter(mat[0, -1], mat[1, -1], c='blue', s=20, zorder=101) ax.scatter(mat[0, idxset_open], mat[1, idxset_open], c='orange', s=5) ax.scatter(mat[0, idxset_closed], mat[1, idxset_closed], c='red', s=5) # ax.scatter(mat[0, idxset_unvisit], mat[1, idxset_unvisit], c='khaki', s=2) for idx in idxset_tree: s0 = self.Pset[self.parent[idx]] s1 = self.Pset[idx] tau = self.time[idx] show_trajectory(s0, s1, tau, N_split=5, ax=ax) # 起点重点画了第二次? # ax.scatter(mat[0, 1], mat[1, 1], c='blue', s=20, zorder=100) # ax.scatter(mat[0, -1], mat[1, -1], c='blue', s=20, zorder=101) # plt.xlim(this.world.x_min[1]-0.05, this.world.x_max[1]+0.05) # plt.ylim(this.world.x_min[2]-0.05, this.world.x_max[2]+0.05) print("finish drawing") def solve(self, ax=None, show=False, save=False): # keep extending the node until the tree reaches the goal print("please set with_savefig=false if you want to measure the computation time") print("start solving") while True: if not self.extend(): # 擴展失敗 break # if ((self.itr < 100) and (self.itr % 20 == 1)) or (self.itr % 200 == 1): if self.itr % 40 == 1: print("itr: ", self.itr) if ax and show: # close() self.show(ax) plt.pause(1) if ax and save: plt.savefig("./fig/" + str(self.itr) + ".png") # 这里需要通过传递fig解决 if not self.bool_unvisit[-1]: break # 無法連接到終點的情況處理待定 idx = -1 idx_solution = [idx] while True: idx = self.parent[idx] idx_solution.append(idx) if idx == 0: break print("finish solving") return np.array(idx_solution) def extend(self): # extend node self.itr += 1 r = 1.0 # 这是什么参数? # 此處數據結構可以優化, idxset_open和idxset_unvisit不用每次檢索 idxset_open = np.nonzero(self.bool_open)[0] #這裡莫名返回一個tuple,需要取第一個 if idxset_open.size == 0: #無法再繼續擴展 return False idxset_unvisit = np.nonzero(self.bool_unvisit)[0] idx_lowest = idxset_open[np.argmin(self.cost[idxset_open])] # idx_lowest = idxset_open[findmin(this.cost[idxset_open])[2]] s_c = self.Pset[idx_lowest, :] idxset_near, _, _ = filter_reachable(self.Pset, idxset_unvisit, self.Pset[idx_lowest], r, "F") for idx_near in idxset_near: idxset_cand, distset_cand, timeset_cand = filter_reachable(self.Pset, idxset_open, self.Pset[idx_near], r, "B") if len(idxset_cand) == 0: return idx_costmin = np.argmin(self.cost[idxset_cand] + distset_cand) cost_new = self.cost[idxset_cand[idx_costmin]] + distset_cand[idx_costmin] # cost_new, idx_costmin = findmin(this.cost[idxset_cand] + distset_cand) # optimal time for new connection time_new = timeset_cand[idx_costmin] idx_parent = idxset_cand[idx_costmin] waypoints = gen_trajectory(self.Pset[idx_parent], self.Pset[idx_near], time_new, 10) if self.world.isValid(waypoints): self.bool_unvisit[idx_near] = False self.bool_open[idx_near] = True self.cost[idx_near] = cost_new self.time[idx_near] = time_new self.parent[idx_near] = idx_parent # print("nonzero cost idx: ", np.nonzero(self.cost)) self.bool_open[idx_lowest] = False self.bool_closed[idx_lowest] = True return True
[ "numpy.ones", "numpy.random.default_rng", "fmt.pythonfmt.doubleintegrator.gen_trajectory", "fmt.pythonfmt.doubleintegrator.show_trajectory", "math.sqrt", "numpy.array", "numpy.zeros", "numpy.empty", "numpy.concatenate", "numpy.nonzero", "numpy.argmin", "random.random", "matplotlib.pyplot.pause", "fmt.pythonfmt.doubleintegrator.filter_reachable" ]
[((263, 313), 'math.sqrt', 'math.sqrt', (['((p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2)'], {}), '((p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2)\n', (272, 313), False, 'import math\n'), ((1135, 1151), 'numpy.zeros', 'np.zeros', (['(N, 4)'], {}), '((N, 4))\n', (1143, 1151), True, 'import numpy as np\n'), ((1178, 1194), 'numpy.array', 'np.array', (['s_init'], {}), '(s_init)\n', (1186, 1194), True, 'import numpy as np\n'), ((2399, 2415), 'numpy.array', 'np.array', (['s_goal'], {}), '(s_goal)\n', (2407, 2415), True, 'import numpy as np\n'), ((2478, 2489), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2486, 2489), True, 'import numpy as np\n'), ((2510, 2521), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2518, 2521), True, 'import numpy as np\n'), ((2544, 2566), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'int'}), '(N, dtype=int)\n', (2552, 2566), True, 'import numpy as np\n'), ((2595, 2621), 'numpy.ones', 'np.ones', (['N'], {'dtype': 'np.bool_'}), '(N, dtype=np.bool_)\n', (2602, 2621), True, 'import numpy as np\n'), ((2686, 2713), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'np.bool_'}), '(N, dtype=np.bool_)\n', (2694, 2713), True, 'import numpy as np\n'), ((2739, 2766), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'np.bool_'}), '(N, dtype=np.bool_)\n', (2747, 2766), True, 'import numpy as np\n'), ((3089, 3105), 'numpy.zeros', 'np.zeros', (['(2, N)'], {}), '((2, N))\n', (3097, 3105), True, 'import numpy as np\n'), ((3445, 3489), 'numpy.concatenate', 'np.concatenate', (['(idxset_closed, idxset_open)'], {}), '((idxset_closed, idxset_open))\n', (3459, 3489), True, 'import numpy as np\n'), ((5546, 5568), 'numpy.array', 'np.array', (['idx_solution'], {}), '(idx_solution)\n', (5554, 5568), True, 'import numpy as np\n'), ((6125, 6199), 'fmt.pythonfmt.doubleintegrator.filter_reachable', 'filter_reachable', (['self.Pset', 'idxset_unvisit', 'self.Pset[idx_lowest]', 'r', '"""F"""'], {}), "(self.Pset, idxset_unvisit, self.Pset[idx_lowest], r, 'F')\n", (6141, 6199), False, 'from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory\n'), ((1373, 1395), 'numpy.empty', 'np.empty', (['(4, num_ran)'], {}), '((4, num_ran))\n', (1381, 1395), True, 'import numpy as np\n'), ((3207, 3233), 'numpy.nonzero', 'np.nonzero', (['self.bool_open'], {}), '(self.bool_open)\n', (3217, 3233), True, 'import numpy as np\n'), ((3261, 3289), 'numpy.nonzero', 'np.nonzero', (['self.bool_closed'], {}), '(self.bool_closed)\n', (3271, 3289), True, 'import numpy as np\n'), ((3318, 3347), 'numpy.nonzero', 'np.nonzero', (['self.bool_unvisit'], {}), '(self.bool_unvisit)\n', (3328, 3347), True, 'import numpy as np\n'), ((4072, 4118), 'fmt.pythonfmt.doubleintegrator.show_trajectory', 'show_trajectory', (['s0', 's1', 'tau'], {'N_split': '(5)', 'ax': 'ax'}), '(s0, s1, tau, N_split=5, ax=ax)\n', (4087, 4118), False, 'from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory\n'), ((5741, 5767), 'numpy.nonzero', 'np.nonzero', (['self.bool_open'], {}), '(self.bool_open)\n', (5751, 5767), True, 'import numpy as np\n'), ((5886, 5915), 'numpy.nonzero', 'np.nonzero', (['self.bool_unvisit'], {}), '(self.bool_unvisit)\n', (5896, 5915), True, 'import numpy as np\n'), ((5952, 5985), 'numpy.argmin', 'np.argmin', (['self.cost[idxset_open]'], {}), '(self.cost[idxset_open])\n', (5961, 5985), True, 'import numpy as np\n'), ((6337, 6406), 'fmt.pythonfmt.doubleintegrator.filter_reachable', 'filter_reachable', (['self.Pset', 'idxset_open', 'self.Pset[idx_near]', 'r', '"""B"""'], {}), "(self.Pset, idxset_open, self.Pset[idx_near], r, 'B')\n", (6353, 6406), False, 'from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory\n'), ((6565, 6613), 'numpy.argmin', 'np.argmin', (['(self.cost[idxset_cand] + distset_cand)'], {}), '(self.cost[idxset_cand] + distset_cand)\n', (6574, 6613), True, 'import numpy as np\n'), ((6955, 7027), 'fmt.pythonfmt.doubleintegrator.gen_trajectory', 'gen_trajectory', (['self.Pset[idx_parent]', 'self.Pset[idx_near]', 'time_new', '(10)'], {}), '(self.Pset[idx_parent], self.Pset[idx_near], time_new, 10)\n', (6969, 7027), False, 'from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory\n'), ((1263, 1278), 'random.random', 'random.random', ([], {}), '()\n', (1276, 1278), False, 'import random\n'), ((1419, 1442), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1440, 1442), True, 'import numpy as np\n'), ((1525, 1548), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1546, 1548), True, 'import numpy as np\n'), ((1631, 1654), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1652, 1654), True, 'import numpy as np\n'), ((1737, 1760), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1758, 1760), True, 'import numpy as np\n'), ((5077, 5089), 'matplotlib.pyplot.pause', 'plt.pause', (['(1)'], {}), '(1)\n', (5086, 5089), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 27 23:58:37 2020 @author: manal """ import numpy as np import GPy from GPy.kern.src.stationary import Stationary class Cosine_prod(Stationary): """ Cosine kernel: Product of 1D Cosine kernels .. math:: &k(x,x')_i = \sigma^2 \prod_{j=1}^{dimension} \cos(x_{i,j}-x_{i,j}') &x,x' \in \mathcal{M}_{n,dimension} &k \in \mathcal{M}_{n,n} """ def __init__(self, input_dim, variance=1., lengthscale=None, ARD=False, active_dims=None, name='Cosine_prod'): super(Cosine_prod, self).__init__(input_dim, variance, lengthscale, ARD, active_dims, name) def K_of_r(self, dist): n = dist.shape[2] p = 1 # l = self.lengthscale for k in range(n): p*= np.cos(dist[:,:,k])#/l) return self.variance * p def K(self, X, X2): dist = X[:,None,:]-X2[None,:,:] return self.K_of_r(dist) def dK_dr(self,dist,dimX): n = dist.shape[2] m = dist.shape[0] # l = self.lengthscale dK = np.zeros((m,m,n)) for i in range(n): dK[:,:,i]= np.cos(dist[:,:,i])#/l) dK[:,:,dimX] = -np.sin(dist[:,:,dimX])#/l) return self.variance * np.prod(dK,2)#/l def dK_dX(self, X, X2, dimX): dist = X[:,None,:]-X2[None,:,:] dK_dr = self.dK_dr(dist,dimX) return dK_dr def dK_dX2(self,X,X2,dimX2): return -self.dK_dX(X,X2, dimX2) def dK2_dXdX2(self, X, X2, dimX, dimX2): dist = X[:,None,:]-X2[None,:,:] K = self.K_of_r(dist) n = dist.shape[2] m = dist.shape[0] # l = self.lengthscale dK = np.zeros((m,m,n)) for i in range(n): dK[:,:,i]= np.cos(dist[:,:,i])#/l) dK[:,:,dimX] = np.sin(dist[:,:,dimX])#/l) dK[:,:,dimX2] = np.sin(dist[:,:,dimX2])#/l) return ((dimX==dimX2)*K - (dimX!=dimX2)*np.prod(dK,2))#/(l**2)
[ "numpy.sin", "numpy.prod", "numpy.zeros", "numpy.cos" ]
[((1126, 1145), 'numpy.zeros', 'np.zeros', (['(m, m, n)'], {}), '((m, m, n))\n', (1134, 1145), True, 'import numpy as np\n'), ((1749, 1768), 'numpy.zeros', 'np.zeros', (['(m, m, n)'], {}), '((m, m, n))\n', (1757, 1768), True, 'import numpy as np\n'), ((1864, 1888), 'numpy.sin', 'np.sin', (['dist[:, :, dimX]'], {}), '(dist[:, :, dimX])\n', (1870, 1888), True, 'import numpy as np\n'), ((1915, 1940), 'numpy.sin', 'np.sin', (['dist[:, :, dimX2]'], {}), '(dist[:, :, dimX2])\n', (1921, 1940), True, 'import numpy as np\n'), ((839, 860), 'numpy.cos', 'np.cos', (['dist[:, :, k]'], {}), '(dist[:, :, k])\n', (845, 860), True, 'import numpy as np\n'), ((1194, 1215), 'numpy.cos', 'np.cos', (['dist[:, :, i]'], {}), '(dist[:, :, i])\n', (1200, 1215), True, 'import numpy as np\n'), ((1242, 1266), 'numpy.sin', 'np.sin', (['dist[:, :, dimX]'], {}), '(dist[:, :, dimX])\n', (1248, 1266), True, 'import numpy as np\n'), ((1300, 1314), 'numpy.prod', 'np.prod', (['dK', '(2)'], {}), '(dK, 2)\n', (1307, 1314), True, 'import numpy as np\n'), ((1817, 1838), 'numpy.cos', 'np.cos', (['dist[:, :, i]'], {}), '(dist[:, :, i])\n', (1823, 1838), True, 'import numpy as np\n'), ((1991, 2005), 'numpy.prod', 'np.prod', (['dK', '(2)'], {}), '(dK, 2)\n', (1998, 2005), True, 'import numpy as np\n')]
import numpy as np import sys import cv2 sys.path.append("../") from utils.config import config class TestLoader: def __init__(self, imdb, batch_size=1, shuffle=False): self.imdb = imdb self.batch_size = batch_size self.shuffle = shuffle self.size = len(imdb)#num of data self.cur = 0 self.data = None self.label = None self.reset() self.get_batch() def reset(self): self.cur = 0 if self.shuffle: np.random.shuffle(self.imdb) def iter_next(self): return self.cur + self.batch_size <= self.size def __iter__(self): return self def __next__(self): return self.next() def next(self): if self.iter_next(): self.get_batch() self.cur += self.batch_size return self.data else: raise StopIteration def getindex(self): return self.cur / self.batch_size def getpad(self): if self.cur + self.batch_size > self.size: return self.cur + self.batch_size - self.size else: return 0 def get_batch(self): imdb = self.imdb[self.cur] im = cv2.imread(imdb) self.data = im
[ "numpy.random.shuffle", "sys.path.append", "cv2.imread" ]
[((41, 63), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (56, 63), False, 'import sys\n'), ((1226, 1242), 'cv2.imread', 'cv2.imread', (['imdb'], {}), '(imdb)\n', (1236, 1242), False, 'import cv2\n'), ((516, 544), 'numpy.random.shuffle', 'np.random.shuffle', (['self.imdb'], {}), '(self.imdb)\n', (533, 544), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """Nowruz at SemEval 2022: Tackling Cloze Tests with Transformers and Ordinal Regression Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1RXkjBpzNJtc0WhhrKMjU-50rd5uSviX3 """ import torch import torch.nn as nn from torch.functional import F from datasets import Dataset import transformers as ts from transformers import AutoTokenizer , AutoModelForSequenceClassification from transformers import TrainingArguments, Trainer from transformers import DataCollatorWithPadding from transformers import create_optimizer from transformers.file_utils import ModelOutput from transformers.modeling_outputs import SequenceClassifierOutput from coral_pytorch.layers import CoralLayer from coral_pytorch.losses import coral_loss from coral_pytorch.dataset import levels_from_labelbatch from coral_pytorch.dataset import proba_to_label from dataclasses import dataclass from typing import Optional, Tuple import numpy as np import pandas as pd from scipy import stats import sys from data_loader import ( retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file, ) """#Preparing Data""" def loadDataset(dataPath , labelPath=None , scoresPath=None): dataset = pd.read_csv(dataPath, sep="\t", quoting=3) ids , sentences , fillers = retrieve_instances_from_dataset(dataset) #Creating dictionaries to convert datas to Huggingface Dataset datasetDict = { "id": ids, "sentence": sentences, "filler": fillers, } labels = None if labelPath != None: labels = pd.read_csv(labelPath, sep="\t", header=None, names=["Id", "Label"]) labels = retrieve_labels_from_dataset_for_classification(labels) datasetDict["labels"] = labels scores = None if scoresPath != None: scores = pd.read_csv(scoresPath, sep="\t", header=None, names=["Id", "Label"]) scores = retrieve_labels_from_dataset_for_ranking(scores) datasetDict["scores"] = scores #Removing Periods if fillers appear at the end of the sentence (because if we don't period will be considered last word piece of the filler) for index , _ in enumerate(fillers): fillers[index].replace("." , "") #Creating Huggingface Datasets from Dictionaries dataset = Dataset.from_dict(datasetDict) return dataset """#Preprocessing""" def preprocessDataset(dataset , tokenizer): def addToDict(dict_1 , dict_2 , columns_1=[] , columns_2=["input_ids" , "attention_mask"]): for item_1 , item_2 in zip(columns_1 , columns_2): dict_1[item_1] = dict_2.pop(item_2) def mappingFunction(dataset): outputDict = {} cleanedSentence = dataset["sentence"].replace("\n" , " ").replace("(...)" , "").strip() sentenceWithFiller = cleanedSentence.replace("[MASK]" , dataset["filler"].strip()).strip() tokenized_sentence = tokenizer(sentenceWithFiller) addToDict(outputDict , tokenized_sentence , ["input_ids" , "attention_mask"]) #Getting the index of the last word piece of the filler if "cls_token" in tokenizer.special_tokens_map.keys(): filler_indecies = len(tokenizer(tokenizer.special_tokens_map["cls_token"] + " " + cleanedSentence.split("[MASK]")[0].strip() + " " + dataset["filler"].strip() , add_special_tokens=False)["input_ids"]) - 1 elif "bos_token" in tokenizer.special_tokens_map.keys(): filler_indecies = len(tokenizer(tokenizer.special_tokens_map["bos_token"] + " " + cleanedSentence.split("[MASK]")[0].strip() + " " + dataset["filler"].strip() , add_special_tokens=False)["input_ids"]) - 1 else: filler_indecies = len(tokenizer(cleanedSentence.split("[MASK]")[0].strip() + " " + dataset["filler"].strip() , add_special_tokens=False)["input_ids"]) - 1 outputDict["filler_indecies"] = filler_indecies return outputDict return dataset.map(mappingFunction , batched=False) """#Model Definition""" @dataclass class CustomOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None classificationOutput: torch.FloatTensor = None regressionOutput: torch.FloatTensor = None class SequenceClassificationModel(nn.Module): def __init__(self, encoder, dim, use_coral=False, use_cls=True, supportPooledRepresentation=False, mode="both", num_labels=3, num_ranks=5, lambda_c=0.5, lambda_r=0.5, dropout_rate=0.2): super().__init__() #mode can be one of these: ["both" , "classification" , "regression"] self.encoder = encoder self.dim = dim self.use_coral = use_coral self.use_cls = use_cls self.supportPooledRepresentation = supportPooledRepresentation self.mode = mode self.num_labels = num_labels self.num_ranks = num_ranks self.lambda_c = lambda_c self.lambda_r = lambda_r self.dropout_rate = dropout_rate if self.use_cls: self.pre_classifier = nn.Linear(self.dim*2 , self.dim , bias=True) else: self.pre_classifier = nn.Linear(self.dim , self.dim , bias=True) self.dropout = nn.Dropout(p=self.dropout_rate , inplace=False) self.regressionHead = CoralLayer(self.dim , self.num_ranks) if use_coral: self.classificationHead = CoralLayer(self.dim , self.num_labels) else: self.classificationHead = nn.Linear(self.dim , self.num_labels , bias=True) def forward( self, input_ids, attention_mask, filler_indecies, labels=None, scores=None, **args): device = self.encoder.device # Getting fillers representation from pre-trained transformer (encoder) sentence_embedding = self.encoder( input_ids=input_ids, attention_mask=attention_mask, ) #Getting Fillers Representation filler_tokens = sentence_embedding[0][filler_indecies[0] , filler_indecies[1]] fillers = filler_tokens[: , 0 , :] #Concatenating [CLS] output with Filler output if the model supports [CLS] pooled_output = None if self.use_cls: if self.supportPooledRepresentation: pooled_output = torch.concat((sentence_embedding[1] , fillers) , dim=-1) else: pooled_output = torch.concat((sentence_embedding[0][: , 0 , :] , fillers) , dim=-1) else: pooled_output = fillers #Passing Pooled Output to another dense layer followed by activation function and dropout pooled_output = self.pre_classifier(pooled_output) pooled_output = nn.GELU()(pooled_output) pooled_output = self.dropout(pooled_output) #Passing the final output to the classificationHead and RegressionHead classificationOutput = self.classificationHead(pooled_output) regressionOutput = self.regressionHead(pooled_output) totalLoss = None classification_loss = None regression_loss = None #Computing classification loss if labels != None and (self.mode.lower() == "both" or self.mode.lower() == "classification"): if self.use_coral: levels = levels_from_labelbatch(labels.view(-1) , self.num_labels).to(device) classification_loss = coral_loss(classificationOutput.view(-1 , self.num_labels - 1) , levels.view(-1 , self.num_labels - 1)) else: loss_fct = nn.CrossEntropyLoss() classification_loss = loss_fct(classificationOutput.view(-1 , self.num_labels) , labels.view(-1)) #Computing regression loss if scores != None and (self.mode.lower() == "both" or self.mode.lower() == "regression"): levels = levels_from_labelbatch(scores.view(-1) , self.num_ranks).to(device) regression_loss = coral_loss(regressionOutput.view(-1 , self.num_ranks - 1) , levels.view(-1 , self.num_ranks - 1)) if self.mode.lower() == "both" and (labels != None and scores != None): totalLoss = (self.lambda_c * classification_loss) + (self.lambda_r * regression_loss) elif self.mode.lower() == "classification" and labels != None: totalLoss = classification_loss elif self.mode.lower() == "regression" and scores != None: totalLoss = regression_loss outputs = torch.concat((classificationOutput , regressionOutput) , dim=-1) finalClassificationOutput = torch.sigmoid(classificationOutput) finalRegressionOutput = torch.sigmoid(regressionOutput) finalClassificationOutput = proba_to_label(finalClassificationOutput.cpu().detach()).numpy() finalRegressionOutput = torch.sum(finalRegressionOutput.cpu().detach() , dim=-1).numpy() + 1 return CustomOutput( loss=totalLoss, logits=outputs, classificationOutput=finalClassificationOutput, regressionOutput=finalRegressionOutput, ) def model_init(encoderPath=None, dimKey=None, customEncoder=None, customDim=None, mode="both", use_coral=True, use_cls=True, supportPooledRepresentation=False, freezeEmbedding=True, num_labels=3, num_ranks=5, lambda_c=0.5, lambda_r=0.5, dropout_rate=0.2,): encoder = ts.AutoModel.from_pretrained(encoderPath) if encoderPath != None else customEncoder dim = encoder.config.to_dict()[dimKey] if dimKey != None else customDim model = SequenceClassificationModel( encoder, dim, use_coral=use_coral, use_cls=use_cls, supportPooledRepresentation=supportPooledRepresentation, mode=mode, num_labels=num_labels, num_ranks=num_ranks, lambda_c=lambda_c, lambda_r=lambda_r, dropout_rate=dropout_rate, ) try: if freezeEmbedding: for param in model.encoder.embeddings.parameters(): param.requires_grad = False except: print("The embedding layer name is different in this model, try to find the name of the emebdding layer and freeze it manually") return model def makeTrainer(model, trainDataset, data_collator, tokenizer, outputsPath, learning_rate=1.90323e-05, scheduler="cosine", save_steps=5000, batch_size=8, num_epochs=5, weight_decay=0.00123974, roundingType="F"): def data_collator_fn(items , columns=[]): data_collator_input = { "input_ids": items[columns[0]], "attention_mask": items[columns[1]] } result = data_collator(data_collator_input) items[columns[0]] = result["input_ids"] items[columns[1]] = result["attention_mask"] def collate_function(items): outputDict = { key: [] for key in items[0].keys() } for item in items: for key in item.keys(): outputDict[key].append(item[key]) data_collator_fn(outputDict , ["input_ids" , "attention_mask"]) #Removing unnecessary Items from outputDict columns = ["sentence" , "filler" , "id"] for item in columns: try: outputDict.pop(item) except: pass #Adding New Columns if "labels" in outputDict.keys(): outputDict["labels"] = torch.tensor(outputDict.pop("labels")) if "scores" in outputDict.keys(): if roundingType == "F": outputDict["scores"] = torch.tensor(outputDict.pop("scores") , dtype=torch.int32) - 1 elif roundingType == "R": outputDict["scores"] = torch.tensor([round(score) for score in outputDict.pop("scores")] , dtype=torch.int32) - 1 filler_indecies = torch.tensor(outputDict.pop("filler_indecies")).view(-1 , 1) outputDict["filler_indecies"] = (torch.arange(filler_indecies.shape[0]).view(-1 , 1) , filler_indecies) return outputDict training_args = TrainingArguments( outputsPath, learning_rate= learning_rate, lr_scheduler_type=scheduler, save_steps=save_steps, per_device_train_batch_size=batch_size, num_train_epochs=num_epochs, weight_decay=weight_decay, remove_unused_columns=False, ) trainer = Trainer( model=model, args=training_args, train_dataset=trainDataset, tokenizer=tokenizer, data_collator=collate_function, ) return trainer , collate_function """#Evaluating on Val Dataset""" def evaluateModel( model, dataset, collate_function, ): model.eval() #Passing the inputs through model labels = [] scores = [] for item in dataset: sample_input = collate_function([item]) outputs = model(input_ids=sample_input["input_ids"].to(model.encoder.device), attention_mask=sample_input["attention_mask"].to(model.encoder.device), filler_indecies=sample_input["filler_indecies"], scores=None) labels.append(outputs["classificationOutput"][0]) scores.append(outputs["regressionOutput"][0]) #Computing Accuracy count = 0 correctCount = 0 for prediction , target in zip(labels , dataset["labels"]): count += 1 correctCount += 1 if prediction == target else 0 accuracy = (correctCount / count) #Computing Spearman scores = np.array(scores , dtype=np.float32) valScores = np.array(dataset["scores"] , dtype=np.float32) spearman = stats.spearmanr(scores.reshape(-1 , 1) , valScores.reshape(-1 , 1)) return (labels , scores) , accuracy , spearman """#Making Predictions on Test Dataset""" def predictOnTestDataset( model, dataset, collate_function, labelsPath=None, scoresPath=None, ): model.eval() ids = [] classification_predictions = [] ranking_predictions = [] for item in dataset: sample_input = collate_function([item]) outputs = model(input_ids=sample_input["input_ids"].to(model.encoder.device), attention_mask=sample_input["attention_mask"].to(model.encoder.device), filler_indecies=sample_input["filler_indecies"], scores=None, labels=None) ids.append(item["id"]) classification_predictions.append(outputs["classificationOutput"][0]) ranking_predictions.append(outputs["regressionOutput"][0]) if labelsPath != None: open(labelsPath , mode="wb") write_predictions_to_file(labelsPath , ids , classification_predictions , "classification") if scoresPath != None: open(scoresPath , mode="wb") write_predictions_to_file(scoresPath , ids , ranking_predictions , "ranking") return ids , classification_predictions , ranking_predictions """#Inference""" def inference( model, sentences, fillers, tokenizer, collate_function ): model.eval() datasetDict = { "sentence": sentences, "filler": fillers, } dataset = Dataset.from_dict(datasetDict) tokenizedDataset = preprocessDataset(dataset , tokenizer) finalInput = collate_function(tokenizedDataset) outputs = model( input_ids=finalInput["input_ids"].to(model.encoder.device), attention_mask=finalInput["attention_mask"].to(model.encoder.device), filler_indecies=finalInput["filler_indecies"], ) finalLabels = [] for item in outputs["classificationOutput"].reshape(-1): if item == 0: finalLabels.append("Implausible") elif item == 1: finalLabels.append("Neutral") elif item == 2: finalLabels.append("Plausible") finalLabels = np.array(finalLabels) return { "labels": finalLabels, "scores": outputs["regressionOutput"], }
[ "transformers.AutoModel.from_pretrained", "torch.nn.Dropout", "torch.nn.GELU", "transformers.TrainingArguments", "pandas.read_csv", "torch.nn.CrossEntropyLoss", "datasets.Dataset.from_dict", "torch.sigmoid", "data_loader.retrieve_labels_from_dataset_for_classification", "numpy.array", "data_loader.retrieve_instances_from_dataset", "coral_pytorch.layers.CoralLayer", "data_loader.retrieve_labels_from_dataset_for_ranking", "torch.concat", "torch.nn.Linear", "transformers.Trainer", "torch.arange", "data_loader.write_predictions_to_file" ]
[((1360, 1402), 'pandas.read_csv', 'pd.read_csv', (['dataPath'], {'sep': '"""\t"""', 'quoting': '(3)'}), "(dataPath, sep='\\t', quoting=3)\n", (1371, 1402), True, 'import pandas as pd\n'), ((1436, 1476), 'data_loader.retrieve_instances_from_dataset', 'retrieve_instances_from_dataset', (['dataset'], {}), '(dataset)\n', (1467, 1476), False, 'from data_loader import retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file\n'), ((2373, 2403), 'datasets.Dataset.from_dict', 'Dataset.from_dict', (['datasetDict'], {}), '(datasetDict)\n', (2390, 2403), False, 'from datasets import Dataset\n'), ((12310, 12558), 'transformers.TrainingArguments', 'TrainingArguments', (['outputsPath'], {'learning_rate': 'learning_rate', 'lr_scheduler_type': 'scheduler', 'save_steps': 'save_steps', 'per_device_train_batch_size': 'batch_size', 'num_train_epochs': 'num_epochs', 'weight_decay': 'weight_decay', 'remove_unused_columns': '(False)'}), '(outputsPath, learning_rate=learning_rate,\n lr_scheduler_type=scheduler, save_steps=save_steps,\n per_device_train_batch_size=batch_size, num_train_epochs=num_epochs,\n weight_decay=weight_decay, remove_unused_columns=False)\n', (12327, 12558), False, 'from transformers import TrainingArguments, Trainer\n'), ((12615, 12740), 'transformers.Trainer', 'Trainer', ([], {'model': 'model', 'args': 'training_args', 'train_dataset': 'trainDataset', 'tokenizer': 'tokenizer', 'data_collator': 'collate_function'}), '(model=model, args=training_args, train_dataset=trainDataset,\n tokenizer=tokenizer, data_collator=collate_function)\n', (12622, 12740), False, 'from transformers import TrainingArguments, Trainer\n'), ((13701, 13735), 'numpy.array', 'np.array', (['scores'], {'dtype': 'np.float32'}), '(scores, dtype=np.float32)\n', (13709, 13735), True, 'import numpy as np\n'), ((13751, 13796), 'numpy.array', 'np.array', (["dataset['scores']"], {'dtype': 'np.float32'}), "(dataset['scores'], dtype=np.float32)\n", (13759, 13796), True, 'import numpy as np\n'), ((15307, 15337), 'datasets.Dataset.from_dict', 'Dataset.from_dict', (['datasetDict'], {}), '(datasetDict)\n', (15324, 15337), False, 'from datasets import Dataset\n'), ((15936, 15957), 'numpy.array', 'np.array', (['finalLabels'], {}), '(finalLabels)\n', (15944, 15957), True, 'import numpy as np\n'), ((1693, 1761), 'pandas.read_csv', 'pd.read_csv', (['labelPath'], {'sep': '"""\t"""', 'header': 'None', 'names': "['Id', 'Label']"}), "(labelPath, sep='\\t', header=None, names=['Id', 'Label'])\n", (1704, 1761), True, 'import pandas as pd\n'), ((1775, 1830), 'data_loader.retrieve_labels_from_dataset_for_classification', 'retrieve_labels_from_dataset_for_classification', (['labels'], {}), '(labels)\n', (1822, 1830), False, 'from data_loader import retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file\n'), ((1922, 1991), 'pandas.read_csv', 'pd.read_csv', (['scoresPath'], {'sep': '"""\t"""', 'header': 'None', 'names': "['Id', 'Label']"}), "(scoresPath, sep='\\t', header=None, names=['Id', 'Label'])\n", (1933, 1991), True, 'import pandas as pd\n'), ((2005, 2053), 'data_loader.retrieve_labels_from_dataset_for_ranking', 'retrieve_labels_from_dataset_for_ranking', (['scores'], {}), '(scores)\n', (2045, 2053), False, 'from data_loader import retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file\n'), ((5273, 5319), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'self.dropout_rate', 'inplace': '(False)'}), '(p=self.dropout_rate, inplace=False)\n', (5283, 5319), True, 'import torch.nn as nn\n'), ((5348, 5384), 'coral_pytorch.layers.CoralLayer', 'CoralLayer', (['self.dim', 'self.num_ranks'], {}), '(self.dim, self.num_ranks)\n', (5358, 5384), False, 'from coral_pytorch.layers import CoralLayer\n'), ((8287, 8349), 'torch.concat', 'torch.concat', (['(classificationOutput, regressionOutput)'], {'dim': '(-1)'}), '((classificationOutput, regressionOutput), dim=-1)\n', (8299, 8349), False, 'import torch\n'), ((8385, 8420), 'torch.sigmoid', 'torch.sigmoid', (['classificationOutput'], {}), '(classificationOutput)\n', (8398, 8420), False, 'import torch\n'), ((8449, 8480), 'torch.sigmoid', 'torch.sigmoid', (['regressionOutput'], {}), '(regressionOutput)\n', (8462, 8480), False, 'import torch\n'), ((9335, 9376), 'transformers.AutoModel.from_pretrained', 'ts.AutoModel.from_pretrained', (['encoderPath'], {}), '(encoderPath)\n', (9363, 9376), True, 'import transformers as ts\n'), ((14787, 14879), 'data_loader.write_predictions_to_file', 'write_predictions_to_file', (['labelsPath', 'ids', 'classification_predictions', '"""classification"""'], {}), "(labelsPath, ids, classification_predictions,\n 'classification')\n", (14812, 14879), False, 'from data_loader import retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file\n'), ((14944, 15018), 'data_loader.write_predictions_to_file', 'write_predictions_to_file', (['scoresPath', 'ids', 'ranking_predictions', '"""ranking"""'], {}), "(scoresPath, ids, ranking_predictions, 'ranking')\n", (14969, 15018), False, 'from data_loader import retrieve_instances_from_dataset, retrieve_labels_from_dataset_for_classification, retrieve_labels_from_dataset_for_ranking, write_predictions_to_file\n'), ((5127, 5171), 'torch.nn.Linear', 'nn.Linear', (['(self.dim * 2)', 'self.dim'], {'bias': '(True)'}), '(self.dim * 2, self.dim, bias=True)\n', (5136, 5171), True, 'import torch.nn as nn\n'), ((5210, 5250), 'torch.nn.Linear', 'nn.Linear', (['self.dim', 'self.dim'], {'bias': '(True)'}), '(self.dim, self.dim, bias=True)\n', (5219, 5250), True, 'import torch.nn as nn\n'), ((5437, 5474), 'coral_pytorch.layers.CoralLayer', 'CoralLayer', (['self.dim', 'self.num_labels'], {}), '(self.dim, self.num_labels)\n', (5447, 5474), False, 'from coral_pytorch.layers import CoralLayer\n'), ((5518, 5565), 'torch.nn.Linear', 'nn.Linear', (['self.dim', 'self.num_labels'], {'bias': '(True)'}), '(self.dim, self.num_labels, bias=True)\n', (5527, 5565), True, 'import torch.nn as nn\n'), ((6673, 6682), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (6680, 6682), True, 'import torch.nn as nn\n'), ((6296, 6350), 'torch.concat', 'torch.concat', (['(sentence_embedding[1], fillers)'], {'dim': '(-1)'}), '((sentence_embedding[1], fillers), dim=-1)\n', (6308, 6350), False, 'import torch\n'), ((6389, 6452), 'torch.concat', 'torch.concat', (['(sentence_embedding[0][:, 0, :], fillers)'], {'dim': '(-1)'}), '((sentence_embedding[0][:, 0, :], fillers), dim=-1)\n', (6401, 6452), False, 'import torch\n'), ((7442, 7463), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (7461, 7463), True, 'import torch.nn as nn\n'), ((12196, 12234), 'torch.arange', 'torch.arange', (['filler_indecies.shape[0]'], {}), '(filler_indecies.shape[0])\n', (12208, 12234), False, 'import torch\n')]
"""Tests for the bradley_terry module""" # Copyright 2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import unittest from ..bradley_terry import get_bt_summation_terms, get_bt_derivatives, sum from .assertions import assert_close class TestBradleyTerryFunctions(unittest.TestCase): """Tests for functions in the bradley_terry module""" def setUp(self): np.seterr(all="raise") self.assert_close = assert_close.__get__(self, self.__class__) def test_get_bt_summation_terms(self): """Test get_bt_summation_terms()""" gamma = np.array([1.0, 2.0]) adversary_gamma = np.array([1.0, 2.0]) d1, d2 = get_bt_summation_terms(gamma, adversary_gamma) self.assert_close([0.5, 0.5], d1, "d1") self.assert_close([0.25, 0.25], d2, "d2") def test_sum(self): """Test sum()""" x = np.array([1.0, 2.0, 4.0, 8.0]) self.assertEqual(15.0, sum(x, 0, 4)) self.assertEqual(0.0, sum(x, 0, 0)) self.assertEqual(6.0, sum(x, 1, 3)) self.assertEqual(7.0, sum(x, 0, 3)) def test_sum(self): """Test sum() error compensation""" x = np.full([10], 0.1) self.assertEqual(1.0, sum(x, 0, 10)) x = np.array([1e100, -1.0, -1e100, 1.0]) self.assertEqual(0.0, sum(x, 0, 4)) x = np.array([1e100, 1.0, -1e100, 1.0]) self.assertEqual(2.0, sum(x, 0, 4)) def test_get_bt_derivatives_single_win(self): """Test get_bt_derivatives() with a single win""" slices = [(0, 1)] wins = np.array([1.0]) gamma = np.array([1.0]) adversary_gamma = np.array([1.0]) d1, d2 = get_bt_derivatives(slices, wins, gamma, adversary_gamma) self.assert_close([0.5], d1, "d1") self.assert_close([-0.25], d2, "d2") def test_get_bt_derivatives_single_loss(self): """Test get_bt_derivatives() with a single loss""" slices = [(0, 1)] wins = np.array([0.0]) gamma = np.array([1.0]) adversary_gamma = np.array([1.0]) d1, d2 = get_bt_derivatives(slices, wins, gamma, adversary_gamma) self.assert_close([-0.5], d1, "d1") self.assert_close([-0.25], d2, "d2") def test_get_bt_derivatives_four_losses(self): """Test get_bt_derivatives() with four losses""" slices = [(0, 4)] wins = np.array([0.0]) gamma = np.array([4.0, 4.0, 4.0, 4.0]) adversary_gamma = np.array([1.0, 1.0, 1.0, 1.0]) d1, d2 = get_bt_derivatives(slices, wins, gamma, adversary_gamma) self.assert_close([-3.2], d1, "d1") self.assert_close([-0.64], d2, "d2") def test_get_bt_derivatives_no_ascents(self): """Test get_bt_derivatives() with no ascents""" slices = [(0, 0)] wins = np.array([]) gamma = np.array([]) adversary_gamma = np.array([]) d1, d2 = get_bt_derivatives(slices, wins, gamma, adversary_gamma) self.assert_close([0.0], d1, "d1") self.assert_close([0.0], d2, "d2") def test_get_bt_derivatives(self): """Test get_bt_derivatives() with multiple slices""" slices = [(0, 1), (1, 4)] wins = np.array([1.0, 2.0]) gamma = np.array([6.0, 4.0, 4.0, 4.0]) adversary_gamma = np.array([6.0, 4.0, 12.0, 12.0]) d1, d2 = get_bt_derivatives(slices, wins, gamma, adversary_gamma) self.assert_close([0.5, 1.0], d1, "d1") self.assert_close([-0.25, -0.625], d2, "d2")
[ "numpy.array", "numpy.seterr", "numpy.full" ]
[((903, 925), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (912, 925), True, 'import numpy as np\n'), ((1101, 1121), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (1109, 1121), True, 'import numpy as np\n'), ((1148, 1168), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (1156, 1168), True, 'import numpy as np\n'), ((1393, 1423), 'numpy.array', 'np.array', (['[1.0, 2.0, 4.0, 8.0]'], {}), '([1.0, 2.0, 4.0, 8.0])\n', (1401, 1423), True, 'import numpy as np\n'), ((1682, 1700), 'numpy.full', 'np.full', (['[10]', '(0.1)'], {}), '([10], 0.1)\n', (1689, 1700), True, 'import numpy as np\n'), ((1758, 1796), 'numpy.array', 'np.array', (['[1e+100, -1.0, -1e+100, 1.0]'], {}), '([1e+100, -1.0, -1e+100, 1.0])\n', (1766, 1796), True, 'import numpy as np\n'), ((1851, 1888), 'numpy.array', 'np.array', (['[1e+100, 1.0, -1e+100, 1.0]'], {}), '([1e+100, 1.0, -1e+100, 1.0])\n', (1859, 1888), True, 'import numpy as np\n'), ((2081, 2096), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2089, 2096), True, 'import numpy as np\n'), ((2113, 2128), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2121, 2128), True, 'import numpy as np\n'), ((2155, 2170), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2163, 2170), True, 'import numpy as np\n'), ((2485, 2500), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (2493, 2500), True, 'import numpy as np\n'), ((2517, 2532), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2525, 2532), True, 'import numpy as np\n'), ((2559, 2574), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2567, 2574), True, 'import numpy as np\n'), ((2888, 2903), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (2896, 2903), True, 'import numpy as np\n'), ((2920, 2950), 'numpy.array', 'np.array', (['[4.0, 4.0, 4.0, 4.0]'], {}), '([4.0, 4.0, 4.0, 4.0])\n', (2928, 2950), True, 'import numpy as np\n'), ((2977, 3007), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (2985, 3007), True, 'import numpy as np\n'), ((3319, 3331), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3327, 3331), True, 'import numpy as np\n'), ((3348, 3360), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3356, 3360), True, 'import numpy as np\n'), ((3387, 3399), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3395, 3399), True, 'import numpy as np\n'), ((3710, 3730), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (3718, 3730), True, 'import numpy as np\n'), ((3747, 3777), 'numpy.array', 'np.array', (['[6.0, 4.0, 4.0, 4.0]'], {}), '([6.0, 4.0, 4.0, 4.0])\n', (3755, 3777), True, 'import numpy as np\n'), ((3804, 3836), 'numpy.array', 'np.array', (['[6.0, 4.0, 12.0, 12.0]'], {}), '([6.0, 4.0, 12.0, 12.0])\n', (3812, 3836), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import numpy as np from PyQt5 import QtWidgets as QtWid import pyqtgraph as pg from dvg_pyqtgraph_threadsafe import PlotCurve USE_OPENGL = True if USE_OPENGL: print("OpenGL acceleration: Enabled") pg.setConfigOptions(useOpenGL=True) pg.setConfigOptions(antialias=True) pg.setConfigOptions(enableExperimental=True) # ------------------------------------------------------------------------------ # MainWindow # ------------------------------------------------------------------------------ class MainWindow(QtWid.QWidget): def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) self.setGeometry(350, 50, 800, 660) self.setWindowTitle("Demo: dvg_pyqtgraph_threadsafe") # GraphicsLayoutWidget self.gw = pg.GraphicsLayoutWidget() self.plot_1 = self.gw.addPlot() self.plot_1.showGrid(x=1, y=1) self.plot_1.setRange( xRange=[0, 5], yRange=[0, 4], disableAutoRange=True, ) self.tscurve = PlotCurve( linked_curve=self.plot_1.plot( pen=pg.mkPen(color=[255, 255, 0], width=3) ), ) x = np.array([0, 1, 2, 3, 4]) y = np.array([0, 1, np.nan, 3, 3]) # x = np.array([np.nan] * 5) # y = np.array([np.nan] * 5) self.tscurve.setData(x, y) self.tscurve.update() # Round up full window hbox = QtWid.QHBoxLayout(self) hbox.addWidget(self.gw, 1) # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == "__main__": app = QtWid.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
[ "PyQt5.QtWidgets.QHBoxLayout", "pyqtgraph.setConfigOptions", "numpy.array", "PyQt5.QtWidgets.QApplication", "pyqtgraph.GraphicsLayoutWidget", "pyqtgraph.mkPen" ]
[((267, 302), 'pyqtgraph.setConfigOptions', 'pg.setConfigOptions', ([], {'useOpenGL': '(True)'}), '(useOpenGL=True)\n', (286, 302), True, 'import pyqtgraph as pg\n'), ((307, 342), 'pyqtgraph.setConfigOptions', 'pg.setConfigOptions', ([], {'antialias': '(True)'}), '(antialias=True)\n', (326, 342), True, 'import pyqtgraph as pg\n'), ((347, 391), 'pyqtgraph.setConfigOptions', 'pg.setConfigOptions', ([], {'enableExperimental': '(True)'}), '(enableExperimental=True)\n', (366, 391), True, 'import pyqtgraph as pg\n'), ((1764, 1792), 'PyQt5.QtWidgets.QApplication', 'QtWid.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (1782, 1792), True, 'from PyQt5 import QtWidgets as QtWid\n'), ((852, 877), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (875, 877), True, 'import pyqtgraph as pg\n'), ((1238, 1263), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4]'], {}), '([0, 1, 2, 3, 4])\n', (1246, 1263), True, 'import numpy as np\n'), ((1276, 1306), 'numpy.array', 'np.array', (['[0, 1, np.nan, 3, 3]'], {}), '([0, 1, np.nan, 3, 3])\n', (1284, 1306), True, 'import numpy as np\n'), ((1494, 1517), 'PyQt5.QtWidgets.QHBoxLayout', 'QtWid.QHBoxLayout', (['self'], {}), '(self)\n', (1511, 1517), True, 'from PyQt5 import QtWidgets as QtWid\n'), ((1161, 1199), 'pyqtgraph.mkPen', 'pg.mkPen', ([], {'color': '[255, 255, 0]', 'width': '(3)'}), '(color=[255, 255, 0], width=3)\n', (1169, 1199), True, 'import pyqtgraph as pg\n')]
import numpy as np import itertools from .contrib import compress_filter, smooth, residual_model from .contrib import reduce_interferences def expectation_maximization(y, x, iterations=2, verbose=0, eps=None): r"""Expectation maximization algorithm, for refining source separation estimates. This algorithm allows to make source separation results better by enforcing multichannel consistency for the estimates. This usually means a better perceptual quality in terms of spatial artifacts. The implementation follows the details presented in [1]_, taking inspiration from the original EM algorithm proposed in [2]_ and its weighted refinement proposed in [3]_, [4]_. It works by iteratively: * Re-estimate source parameters (power spectral densities and spatial covariance matrices) through :func:`get_local_gaussian_model`. * Separate again the mixture with the new parameters by first computing the new modelled mixture covariance matrices with :func:`get_mix_model`, prepare the Wiener filters through :func:`wiener_gain` and apply them with :func:`apply_filter``. References ---------- .. [1] <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>, "Improving music source separation based on deep neural networks through data augmentation and network blending." 2017 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2017. .. [2] <NAME> and <NAME> and R.Gribonval. "Under-determined reverberant audio source separation using a full-rank spatial covariance model." IEEE Transactions on Audio, Speech, and Language Processing 18.7 (2010): 1830-1840. .. [3] <NAME> and <NAME> and <NAME>. "Multichannel audio source separation with deep neural networks." IEEE/ACM Transactions on Audio, Speech, and Language Processing 24.9 (2016): 1652-1664. .. [4] <NAME> and <NAME> and <NAME>. "Multichannel music separation with deep neural networks." 2016 24th European Signal Processing Conference (EUSIPCO). IEEE, 2016. .. [5] <NAME> and <NAME> and <NAME> "Kernel additive models for source separation." IEEE Transactions on Signal Processing 62.16 (2014): 4298-4310. Parameters ---------- y: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_sources)] initial estimates for the sources x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] complex STFT of the mixture signal iterations: int [scalar] number of iterations for the EM algorithm. verbose: boolean display some information if True eps: float or None [scalar] The epsilon value to use for regularization and filters. If None, the default will use the epsilon of np.real(x) dtype. Returns ------- y: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_sources)] estimated sources after iterations v: np.ndarray [shape=(nb_frames, nb_bins, nb_sources)] estimated power spectral densities R: np.ndarray [shape=(nb_bins, nb_channels, nb_channels, nb_sources)] estimated spatial covariance matrices Note ----- * You need an initial estimate for the sources to apply this algorithm. This is precisely what the :func:`wiener` function does. * This algorithm *is not* an implementation of the "exact" EM proposed in [1]_. In particular, it does compute the posterior covariance matrices the same (exact) way. Instead, it uses the simplified approximate scheme initially proposed in [5]_ and further refined in [3]_, [4]_, that boils down to just take the empirical covariance of the recent source estimates, followed by a weighted average for the update of the spatial covariance matrix. It has been empirically demonstrated that this simplified algorithm is more robust for music separation. Warning ------- It is *very* important to make sure `x.dtype` is `np.complex` if you want double precision, because this function will **not** do such conversion for you from `np.complex64`, in case you want the smaller RAM usage on purpose. It is usually always better in terms of quality to have double precision, by e.g. calling :func:`expectation_maximization` with ``x.astype(np.complex)``. This is notably needed if you let common deep learning frameworks like PyTorch or TensorFlow do the STFT, because this usually happens in single precision. """ # to avoid dividing by zero if eps is None: eps = np.finfo(np.real(x[0]).dtype).eps # dimensions (nb_frames, nb_bins, nb_channels) = x.shape nb_sources = y.shape[-1] # allocate the spatial covariance matrices and PSD R = np.zeros((nb_bins, nb_channels, nb_channels, nb_sources), x.dtype) v = np.zeros((nb_frames, nb_bins, nb_sources)) if verbose: print('Number of iterations: ', iterations) regularization = np.sqrt(eps) * ( np.tile(np.eye(nb_channels, dtype=np.complex64), (1, nb_bins, 1, 1))) for it in range(iterations): # constructing the mixture covariance matrix. Doing it with a loop # to avoid storing anytime in RAM the whole 6D tensor if verbose: print('EM, iteration %d' % (it+1)) for j in range(nb_sources): # update the spectrogram model for source j v[..., j], R[..., j] = get_local_gaussian_model( y[..., j], eps) for t in range(nb_frames): Cxx = get_mix_model(v[None, t, ...], R) Cxx += regularization inv_Cxx = _invert(Cxx, eps) # separate the sources for j in range(nb_sources): W_j = wiener_gain(v[None, t, ..., j], R[..., j], inv_Cxx) y[t, ..., j] = apply_filter(x[None, t, ...], W_j)[0] return y, v, R def wiener(v, x, iterations=1, use_softmask=True, eps=None): """Wiener-based separation for multichannel audio. The method uses the (possibly multichannel) spectrograms `v` of the sources to separate the (complex) Short Term Fourier Transform `x` of the mix. Separation is done in a sequential way by: * Getting an initial estimate. This can be done in two ways: either by directly using the spectrograms with the mixture phase, or by using :func:`softmask`. * Refinining these initial estimates through a call to :func:`expectation_maximization`. This implementation also allows to specify the epsilon value used for regularization. It is based on [1]_, [2]_, [3]_, [4]_. References ---------- .. [1] <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>, "Improving music source separation based on deep neural networks through data augmentation and network blending." 2017 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2017. .. [2] <NAME> and <NAME> and <NAME>. "Multichannel audio source separation with deep neural networks." IEEE/ACM Transactions on Audio, Speech, and Language Processing 24.9 (2016): 1652-1664. .. [3] <NAME> and <NAME> and <NAME>. "Multichannel music separation with deep neural networks." 2016 24th European Signal Processing Conference (EUSIPCO). IEEE, 2016. .. [4] <NAME> and <NAME> and <NAME> "Kernel additive models for source separation." IEEE Transactions on Signal Processing 62.16 (2014): 4298-4310. Parameters ---------- v: np.ndarray [shape=(nb_frames, nb_bins, {1,nb_channels}, nb_sources)] spectrograms of the sources. This is a nonnegative tensor that is usually the output of the actual separation method of the user. The spectrograms may be mono, but they need to be 4-dimensional in all cases. x: np.ndarray [complex, shape=(nb_frames, nb_bins, nb_channels)] STFT of the mixture signal. iterations: int [scalar] number of iterations for the EM algorithm use_softmask: boolean * if `False`, then the mixture phase will directly be used with the spectrogram as initial estimates. * if `True`, a softmasking strategy will be used as described in :func:`softmask`. eps: {None, float} Epsilon value to use for computing the separations. This is used whenever division with a model energy is performed, i.e. when softmasking and when iterating the EM. It can be understood as the energy of the additional white noise that is taken out when separating. If `None`, the default value is taken as `np.finfo(np.real(x[0])).eps`. Returns ------- y: np.ndarray [complex, shape=(nb_frames, nb_bins, nb_channels, nb_sources)] STFT of estimated sources Note ---- * Be careful that you need *magnitude spectrogram estimates* for the case `softmask==False`. * We recommand to use `softmask=False` only if your spectrogram model is pretty good, e.g. when the output of a deep neural net. In the case it is not so great, opt for an initial softmasking strategy. * The epsilon value will have a huge impact on performance. If it's large, only the parts of the signal with a significant energy will be kept in the sources. This epsilon then directly controls the energy of the reconstruction error. Warning ------- As in :func:`expectation_maximization`, we recommend converting the mixture `x` to double precision `np.complex` *before* calling :func:`wiener`. """ if use_softmask: y = softmask(v, x, eps=eps) else: y = v * np.exp(1j*np.angle(x[..., None])) if not iterations: return y # we need to refine the estimates. Scales down the estimates for # numerical stability max_abs = max(1, np.abs(x).max()/10.) x /= max_abs y = expectation_maximization(y/max_abs, x, iterations, eps=eps)[0] return y*max_abs def softmask(v, x, logit=None, eps=None): """Separates a mixture with a ratio mask, using the provided sources spectrograms estimates. Additionally allows compressing the mask with a logit function for soft binarization. The filter does *not* take multichannel correlations into account. The masking strategy can be traced back to the work of <NAME> in the case of *power* spectrograms [1]_. In the case of *fractional* spectrograms like magnitude, this filter is often referred to a "ratio mask", and has been shown to be the optimal separation procedure under alpha-stable assumptions [2]_. References ---------- .. [1] <NAME>,"Extrapolation, Inerpolation, and Smoothing of Stationary Time Series." 1949. .. [2] <NAME> and <NAME>. "Generalized Wiener filtering with fractional power spectrograms." 2015 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2015. Parameters ---------- v: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_sources)] spectrograms of the sources x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] mixture signal logit: {None, float between 0 and 1} enable a compression of the filter. If not None, it is the threshold value for the logit function: a softmask above this threshold is brought closer to 1, and a softmask below is brought closer to 0. Returns ------- ndarray, shape=(nb_frames, nb_bins, nb_channels, nb_sources) estimated sources """ # to avoid dividing by zero if eps is None: eps = np.finfo(np.real(x[0]).dtype).eps total_energy = np.sum(v, axis=-1, keepdims=True) filter = v/(eps + total_energy.astype(x.dtype)) if logit is not None: filter = compress_filter(filter, eps, thresh=logit, multichannel=False) return filter * x[..., None] def _invert(M, eps): """ Invert matrices, with special fast handling of the 1x1 and 2x2 cases. Will generate errors if the matrices are singular: user must handle this through his own regularization schemes. Parameters ---------- M: np.ndarray [shape=(..., nb_channels, nb_channels)] matrices to invert: must be square along the last two dimensions eps: [scalar] regularization parameter to use _only in the case of matrices bigger than 2x2 Returns ------- invM: np.ndarray, [shape=M.shape] inverses of M """ nb_channels = M.shape[-1] if nb_channels == 1: # scalar case invM = 1.0/(M+eps) elif nb_channels == 2: # two channels case: analytical expression det = ( M[..., 0, 0]*M[..., 1, 1] - M[..., 0, 1]*M[..., 1, 0]) invDet = 1.0/(det) invM = np.empty_like(M) invM[..., 0, 0] = invDet*M[..., 1, 1] invM[..., 1, 0] = -invDet*M[..., 1, 0] invM[..., 0, 1] = -invDet*M[..., 0, 1] invM[..., 1, 1] = invDet*M[..., 0, 0] else: # general case : no use of analytical expression (slow!) invM = np.linalg.pinv(M, eps) return invM def wiener_gain(v_j, R_j, inv_Cxx): """ Compute the wiener gain for separating one source, given all parameters. It is the matrix applied to the mix to get the posterior mean of the source as in [1]_ References ---------- .. [1] <NAME> and <NAME> and R.Gribonval. "Under-determined reverberant audio source separation using a full-rank spatial covariance model." IEEE Transactions on Audio, Speech, and Language Processing 18.7 (2010): 1830-1840. Parameters ---------- v_j: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] power spectral density of the target source. R_j: np.ndarray [shape=(nb_bins, nb_channels, nb_channels)] spatial covariance matrix of the target source inv_Cxx: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_channels)] inverse of the mixture covariance matrices Returns ------- G: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_channels)] wiener filtering matrices, to apply to the mix, e.g. through :func:`apply_filter` to get the target source estimate. """ (_, nb_channels) = R_j.shape[:2] # computes multichannel Wiener gain as v_j R_j inv_Cxx G = np.zeros_like(inv_Cxx) for (i1, i2, i3) in itertools.product(*(range(nb_channels),)*3): G[..., i1, i2] += (R_j[None, :, i1, i3] * inv_Cxx[..., i3, i2]) G *= v_j[..., None, None] return G def apply_filter(x, W): """ Applies a filter on the mixture. Just corresponds to a matrix multiplication. Parameters ---------- x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] STFT of the signal on which to apply the filter. W: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_channels)] filtering matrices, as returned, e.g. by :func:`wiener_gain` Returns ------- y_hat: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] filtered signal """ nb_channels = W.shape[-1] # apply the filter y_hat = 0+0j for i in range(nb_channels): y_hat += W[..., i] * x[..., i, None] return y_hat def get_mix_model(v, R): """ Compute the model covariance of a mixture based on local Gaussian models. simply adds up all the v[..., j] * R[..., j] Parameters ---------- v: np.ndarray [shape=(nb_frames, nb_bins, nb_sources)] Power spectral densities for the sources R: np.ndarray [shape=(nb_bins, nb_channels, nb_channels, nb_sources)] Spatial covariance matrices of each sources Returns ------- Cxx: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_channels)] Covariance matrix for the mixture """ nb_channels = R.shape[1] (nb_frames, nb_bins, nb_sources) = v.shape Cxx = np.zeros((nb_frames, nb_bins, nb_channels, nb_channels), R.dtype) for j in range(nb_sources): Cxx += v[..., j, None, None] * R[None, ..., j] return Cxx def _covariance(y_j): """ Compute the empirical covariance for a source. Parameters ---------- y_j: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)]. complex stft of the source. Returns ------- Cj: np.ndarray [shape=(nb_frames, nb_bins, nb_channels, nb_channels)] just y_j * conj(y_j.T): empirical covariance for each TF bin. """ (nb_frames, nb_bins, nb_channels) = y_j.shape Cj = np.zeros((nb_frames, nb_bins, nb_channels, nb_channels), y_j.dtype) for (i1, i2) in itertools.product(*(range(nb_channels),)*2): Cj[..., i1, i2] += y_j[..., i1] * np.conj(y_j[..., i2]) return Cj def get_local_gaussian_model(y_j, eps=1.): r""" Compute the local Gaussian model [1]_ for a source given the complex STFT. First get the power spectral densities, and then the spatial covariance matrix, as done in [1]_, [2]_ References ---------- .. [1] <NAME> and <NAME> and R.Gribonval. "Under-determined reverberant audio source separation using a full-rank spatial covariance model." IEEE Transactions on Audio, Speech, and Language Processing 18.7 (2010): 1830-1840. .. [2] <NAME> and <NAME> and <NAME>. "Low bitrate informed source separation of realistic mixtures." 2013 IEEE International Conference on Acoustics, Speech and Signal Processing. IEEE, 2013. Parameters ---------- y_j: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)] complex stft of the source. eps: float [scalar] regularization term Returns ------- v_j: np.ndarray [shape=(nb_frames, nb_bins)] power spectral density of the source R_J: np.ndarray [shape=(nb_bins, nb_channels, nb_channels)] Spatial covariance matrix of the source """ v_j = np.mean(np.abs(y_j)**2, axis=2) # updates the spatial covariance matrix nb_frames = y_j.shape[0] R_j = 0 weight = eps for t in range(nb_frames): R_j += _covariance(y_j[None, t, ...]) weight += v_j[None, t, ...] R_j /= weight[..., None, None] return v_j, R_j
[ "numpy.abs", "numpy.eye", "numpy.sqrt", "numpy.linalg.pinv", "numpy.conj", "numpy.angle", "numpy.sum", "numpy.zeros", "numpy.real", "numpy.empty_like", "numpy.zeros_like" ]
[((4979, 5045), 'numpy.zeros', 'np.zeros', (['(nb_bins, nb_channels, nb_channels, nb_sources)', 'x.dtype'], {}), '((nb_bins, nb_channels, nb_channels, nb_sources), x.dtype)\n', (4987, 5045), True, 'import numpy as np\n'), ((5054, 5096), 'numpy.zeros', 'np.zeros', (['(nb_frames, nb_bins, nb_sources)'], {}), '((nb_frames, nb_bins, nb_sources))\n', (5062, 5096), True, 'import numpy as np\n'), ((12060, 12093), 'numpy.sum', 'np.sum', (['v'], {'axis': '(-1)', 'keepdims': '(True)'}), '(v, axis=-1, keepdims=True)\n', (12066, 12093), True, 'import numpy as np\n'), ((14777, 14799), 'numpy.zeros_like', 'np.zeros_like', (['inv_Cxx'], {}), '(inv_Cxx)\n', (14790, 14799), True, 'import numpy as np\n'), ((16346, 16411), 'numpy.zeros', 'np.zeros', (['(nb_frames, nb_bins, nb_channels, nb_channels)', 'R.dtype'], {}), '((nb_frames, nb_bins, nb_channels, nb_channels), R.dtype)\n', (16354, 16411), True, 'import numpy as np\n'), ((16965, 17032), 'numpy.zeros', 'np.zeros', (['(nb_frames, nb_bins, nb_channels, nb_channels)', 'y_j.dtype'], {}), '((nb_frames, nb_bins, nb_channels, nb_channels), y_j.dtype)\n', (16973, 17032), True, 'import numpy as np\n'), ((5187, 5199), 'numpy.sqrt', 'np.sqrt', (['eps'], {}), '(eps)\n', (5194, 5199), True, 'import numpy as np\n'), ((5224, 5263), 'numpy.eye', 'np.eye', (['nb_channels'], {'dtype': 'np.complex64'}), '(nb_channels, dtype=np.complex64)\n', (5230, 5263), True, 'import numpy as np\n'), ((13200, 13216), 'numpy.empty_like', 'np.empty_like', (['M'], {}), '(M)\n', (13213, 13216), True, 'import numpy as np\n'), ((13493, 13515), 'numpy.linalg.pinv', 'np.linalg.pinv', (['M', 'eps'], {}), '(M, eps)\n', (13507, 13515), True, 'import numpy as np\n'), ((17158, 17179), 'numpy.conj', 'np.conj', (['y_j[..., i2]'], {}), '(y_j[..., i2])\n', (17165, 17179), True, 'import numpy as np\n'), ((18377, 18388), 'numpy.abs', 'np.abs', (['y_j'], {}), '(y_j)\n', (18383, 18388), True, 'import numpy as np\n'), ((4795, 4808), 'numpy.real', 'np.real', (['x[0]'], {}), '(x[0])\n', (4802, 4808), True, 'import numpy as np\n'), ((10034, 10056), 'numpy.angle', 'np.angle', (['x[..., None]'], {}), '(x[..., None])\n', (10042, 10056), True, 'import numpy as np\n'), ((10216, 10225), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (10222, 10225), True, 'import numpy as np\n'), ((12016, 12029), 'numpy.real', 'np.real', (['x[0]'], {}), '(x[0])\n', (12023, 12029), True, 'import numpy as np\n')]
import unittest import numpy as np from op_test import OpTest def modified_huber_loss_forward(val): if val < -1: return -4 * val elif val < 1: return (1 - val) * (1 - val) else: return 0 class TestModifiedHuberLossOp(OpTest): def setUp(self): self.op_type = 'modified_huber_loss' samples_num = 32 self.inputs = { 'X': np.random.uniform(-1, 1., (samples_num, 1)).astype('float32'), 'Y': np.random.choice([0, 1], samples_num).reshape((samples_num, 1)) } product_res = self.inputs['X'] * (2 * self.inputs['Y'] - 1) loss = np.vectorize(modified_huber_loss_forward)(product_res) self.outputs = { 'IntermediateVal': product_res, 'Out': loss.reshape((samples_num, 1)) } def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(['X'], 'Out', max_relative_error=0.005) if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.random.choice", "numpy.vectorize", "numpy.random.uniform" ]
[((1011, 1026), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1024, 1026), False, 'import unittest\n'), ((635, 676), 'numpy.vectorize', 'np.vectorize', (['modified_huber_loss_forward'], {}), '(modified_huber_loss_forward)\n', (647, 676), True, 'import numpy as np\n'), ((398, 442), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1.0)', '(samples_num, 1)'], {}), '(-1, 1.0, (samples_num, 1))\n', (415, 442), True, 'import numpy as np\n'), ((478, 515), 'numpy.random.choice', 'np.random.choice', (['[0, 1]', 'samples_num'], {}), '([0, 1], samples_num)\n', (494, 515), True, 'import numpy as np\n')]
"""The WaveBlocks Project Plot some quadrature rules. @author: <NAME> @copyright: Copyright (C) 2010, 2011 <NAME> @license: Modified BSD License """ from numpy import squeeze from matplotlib.pyplot import * from WaveBlocks import GaussHermiteQR tests = (2, 3, 4, 7, 32, 64, 128) for I in tests: Q = GaussHermiteQR(I) print(Q) N = Q.get_nodes() N = squeeze(N) W = Q.get_weights() W = squeeze(W) fig = figure() ax = fig.gca() ax.stem(N, W) ax.set_xlabel(r"$\gamma_i$") ax.set_ylabel(r"$\omega_i$") ax.set_title(r"Gauss-Hermite quadrature with $"+str(Q.get_number_nodes())+r"$ nodes") fig.savefig("qr_order_"+str(Q.get_order())+".png")
[ "WaveBlocks.GaussHermiteQR", "numpy.squeeze" ]
[((315, 332), 'WaveBlocks.GaussHermiteQR', 'GaussHermiteQR', (['I'], {}), '(I)\n', (329, 332), False, 'from WaveBlocks import GaussHermiteQR\n'), ((382, 392), 'numpy.squeeze', 'squeeze', (['N'], {}), '(N)\n', (389, 392), False, 'from numpy import squeeze\n'), ((438, 448), 'numpy.squeeze', 'squeeze', (['W'], {}), '(W)\n', (445, 448), False, 'from numpy import squeeze\n')]
import os import cv2 import numpy as np import matplotlib.pyplot as plt import scipy ROWS = 64 COLS = 64 CHANNELS = 3 TRAIN_DIR = 'Train_data/' TEST_DIR = 'Test_data/' train_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] test_images = [TEST_DIR+i for i in os.listdir(TEST_DIR)] def read_image(file_path): img = cv2.imread(file_path, cv2.IMREAD_COLOR) return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC) def prepare_data(images): m = len(images) X = np.zeros((m, ROWS, COLS, CHANNELS), dtype=np.uint8) y = np.zeros((1, m)) for i, image_file in enumerate(images): X[i,:] = read_image(image_file) if 'dog' in image_file.lower(): y[0, i] = 1 elif 'cat' in image_file.lower(): y[0, i] = 0 return X, y def sigmoid(z): s = 1/(1+np.exp(-z)) return s train_set_x, train_set_y = prepare_data(train_images) test_set_x, test_set_y = prepare_data(test_images) train_set_x_flatten = train_set_x.reshape(train_set_x.shape[0], ROWS*COLS*CHANNELS).T test_set_x_flatten = test_set_x.reshape(test_set_x.shape[0], -1).T train_set_x = train_set_x_flatten/255 test_set_x = test_set_x_flatten/255 #train_set_x_flatten shape: (12288, 6002) #train_set_y shape: (1, 6002) def initialize_parameters(input_layer, hidden_layer, output_layer): # initialize 1st layer output and input with random values W1 = np.random.randn(hidden_layer, input_layer) * 0.01 # initialize 1st layer output bias b1 = np.zeros((hidden_layer, 1)) # initialize 2nd layer output and input with random values W2 = np.random.randn(output_layer, hidden_layer) * 0.01 # initialize 2nd layer output bias b2 = np.zeros((output_layer,1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters def forward_propagation(X, parameters): # Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Implementing Forward Propagation to calculate A2 probabilities Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) # Values needed in the backpropagation are stored in "cache" cache = {"Z1": Z1, "A1": A1, "Z2": Z2, "A2": A2} return A2, cache def compute_cost(A2, Y, parameters): # number of example m = Y.shape[1] # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2),Y) + np.multiply(np.log(1-A2), (1-Y)) cost = -1/m*np.sum(logprobs) # makes sure cost is in dimension we expect, E.g., turns [[51]] into 51 cost = np.squeeze(cost) return cost def backward_propagation(parameters, cache, X, Y): # number of example m = X.shape[1] # Retrieve W1 and W2 from the "parameters" dictionary W1 = parameters["W1"] W2 = parameters["W2"] # Retrieve A1 and A2 from "cache" dictionary A1 = cache["A1"] A2 = cache["A2"] # Backward propagation for dW1, db1, dW2, db2 dZ2 = A2-Y dW2 = 1./m*np.dot(dZ2, A1.T) db2 = 1./m*np.sum(dZ2, axis = 1, keepdims=True) dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2)) dW1 = 1./m*np.dot(dZ1, X.T) db1 = 1./m*np.sum(dZ1, axis = 1, keepdims=True) grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} return grads def update_parameters(parameters, grads, learning_rate = 0.1): # Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] W2 = parameters["W2"] b1 = parameters["b1"] b2 = parameters["b2"] # Retrieve each gradient from the "grads" dictionary dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"] # Update rule for each parameter W1 = W1 - dW1 * learning_rate b1 = b1 - db1 * learning_rate W2 = W2 - dW2 * learning_rate b2 = b2 - db2 * learning_rate parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters def predict(parameters, X): # Computes probabilities using forward propagation Y_prediction = np.zeros((1, X.shape[1])) A2, cache = forward_propagation(X, parameters) for i in range(A2.shape[1]): # Convert probabilities A[0,i] to actual predictions p[0,i] if A2[0,i] > 0.5: Y_prediction[[0],[i]] = 1 else: Y_prediction[[0],[i]] = 0 return Y_prediction def nn_model(X_train, Y_train, X_test, Y_test, n_h, num_iterations = 1000, learning_rate = 0.05, print_cost=False): n_x = X_train.shape[0] n_y = Y_train.shape[0] # Initialize parameters with nputs: "n_x, n_h, n_y" parameters = initialize_parameters(n_x, n_h, n_y) # Retrieve W1, b1, W2, b2 W1 = parameters["W1"] W2 = parameters["W2"] b1 = parameters["b1"] b2 = parameters["b2"] costs = [] for i in range(0, num_iterations): # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache". A2, cache = forward_propagation(X_train, parameters) # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost". cost = compute_cost(A2, Y_train, parameters) # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads". grads = backward_propagation(parameters, cache, X_train, Y_train) # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters". parameters = update_parameters(parameters, grads, learning_rate) # Print the cost every 200 iterations if print_cost and i % 200 == 0: print ("Cost after iteration %i: %f" %(i, cost)) # Record the cost if i % 100 == 0: costs.append(cost) # Predict test/train set examples Y_prediction_test = predict(parameters,X_test) Y_prediction_train = predict(parameters,X_train) # Print train/test Errors print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) parameters.update({"costs": costs, "n_h": n_h}) return parameters #nn_model(train_set_x, train_set_y, test_set_x, test_set_y, n_h = 10, num_iterations = 3000, learning_rate = 0.05, print_cost = True) hidden_layer = [10, 50, 100, 200, 400] models = {} for i in hidden_layer: print ("hidden layer is: ",i) models[i] = nn_model(train_set_x, train_set_y, test_set_x, test_set_y, n_h = i, num_iterations = 10000, learning_rate = 0.05, print_cost = True) print ("-------------------------------------------------------") for i in hidden_layer: plt.plot(np.squeeze(models[i]["costs"]), label= str(models[i]["n_h"])) plt.ylabel('cost') plt.xlabel('iterations (hundreds)') legend = plt.legend(loc='upper center', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') plt.show()
[ "numpy.abs", "os.listdir", "matplotlib.pyplot.ylabel", "numpy.power", "matplotlib.pyplot.xlabel", "numpy.log", "numpy.tanh", "numpy.squeeze", "numpy.exp", "numpy.sum", "numpy.zeros", "numpy.random.randn", "numpy.dot", "cv2.resize", "cv2.imread", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((6966, 6984), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""cost"""'], {}), "('cost')\n", (6976, 6984), True, 'import matplotlib.pyplot as plt\n'), ((6985, 7020), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iterations (hundreds)"""'], {}), "('iterations (hundreds)')\n", (6995, 7020), True, 'import matplotlib.pyplot as plt\n'), ((7031, 7074), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper center"""', 'shadow': '(True)'}), "(loc='upper center', shadow=True)\n", (7041, 7074), True, 'import matplotlib.pyplot as plt\n'), ((7130, 7140), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7138, 7140), True, 'import matplotlib.pyplot as plt\n'), ((327, 366), 'cv2.imread', 'cv2.imread', (['file_path', 'cv2.IMREAD_COLOR'], {}), '(file_path, cv2.IMREAD_COLOR)\n', (337, 366), False, 'import cv2\n'), ((378, 438), 'cv2.resize', 'cv2.resize', (['img', '(ROWS, COLS)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC)\n', (388, 438), False, 'import cv2\n'), ((494, 545), 'numpy.zeros', 'np.zeros', (['(m, ROWS, COLS, CHANNELS)'], {'dtype': 'np.uint8'}), '((m, ROWS, COLS, CHANNELS), dtype=np.uint8)\n', (502, 545), True, 'import numpy as np\n'), ((554, 570), 'numpy.zeros', 'np.zeros', (['(1, m)'], {}), '((1, m))\n', (562, 570), True, 'import numpy as np\n'), ((1503, 1530), 'numpy.zeros', 'np.zeros', (['(hidden_layer, 1)'], {}), '((hidden_layer, 1))\n', (1511, 1530), True, 'import numpy as np\n'), ((1702, 1729), 'numpy.zeros', 'np.zeros', (['(output_layer, 1)'], {}), '((output_layer, 1))\n', (1710, 1729), True, 'import numpy as np\n'), ((2189, 2200), 'numpy.tanh', 'np.tanh', (['Z1'], {}), '(Z1)\n', (2196, 2200), True, 'import numpy as np\n'), ((2753, 2769), 'numpy.squeeze', 'np.squeeze', (['cost'], {}), '(cost)\n', (2763, 2769), True, 'import numpy as np\n'), ((4309, 4334), 'numpy.zeros', 'np.zeros', (['(1, X.shape[1])'], {}), '((1, X.shape[1]))\n', (4317, 4334), True, 'import numpy as np\n'), ((208, 229), 'os.listdir', 'os.listdir', (['TRAIN_DIR'], {}), '(TRAIN_DIR)\n', (218, 229), False, 'import os\n'), ((267, 287), 'os.listdir', 'os.listdir', (['TEST_DIR'], {}), '(TEST_DIR)\n', (277, 287), False, 'import os\n'), ((1405, 1447), 'numpy.random.randn', 'np.random.randn', (['hidden_layer', 'input_layer'], {}), '(hidden_layer, input_layer)\n', (1420, 1447), True, 'import numpy as np\n'), ((1603, 1646), 'numpy.random.randn', 'np.random.randn', (['output_layer', 'hidden_layer'], {}), '(output_layer, hidden_layer)\n', (1618, 1646), True, 'import numpy as np\n'), ((2160, 2173), 'numpy.dot', 'np.dot', (['W1', 'X'], {}), '(W1, X)\n', (2166, 2173), True, 'import numpy as np\n'), ((2210, 2224), 'numpy.dot', 'np.dot', (['W2', 'A1'], {}), '(W2, A1)\n', (2216, 2224), True, 'import numpy as np\n'), ((2647, 2663), 'numpy.sum', 'np.sum', (['logprobs'], {}), '(logprobs)\n', (2653, 2663), True, 'import numpy as np\n'), ((3174, 3191), 'numpy.dot', 'np.dot', (['dZ2', 'A1.T'], {}), '(dZ2, A1.T)\n', (3180, 3191), True, 'import numpy as np\n'), ((3207, 3241), 'numpy.sum', 'np.sum', (['dZ2'], {'axis': '(1)', 'keepdims': '(True)'}), '(dZ2, axis=1, keepdims=True)\n', (3213, 3241), True, 'import numpy as np\n'), ((3254, 3271), 'numpy.dot', 'np.dot', (['W2.T', 'dZ2'], {}), '(W2.T, dZ2)\n', (3260, 3271), True, 'import numpy as np\n'), ((3311, 3327), 'numpy.dot', 'np.dot', (['dZ1', 'X.T'], {}), '(dZ1, X.T)\n', (3317, 3327), True, 'import numpy as np\n'), ((3343, 3377), 'numpy.sum', 'np.sum', (['dZ1'], {'axis': '(1)', 'keepdims': '(True)'}), '(dZ1, axis=1, keepdims=True)\n', (3349, 3377), True, 'import numpy as np\n'), ((6903, 6933), 'numpy.squeeze', 'np.squeeze', (["models[i]['costs']"], {}), "(models[i]['costs'])\n", (6913, 6933), True, 'import numpy as np\n'), ((831, 841), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (837, 841), True, 'import numpy as np\n'), ((2581, 2591), 'numpy.log', 'np.log', (['A2'], {}), '(A2)\n', (2587, 2591), True, 'import numpy as np\n'), ((2610, 2624), 'numpy.log', 'np.log', (['(1 - A2)'], {}), '(1 - A2)\n', (2616, 2624), True, 'import numpy as np\n'), ((3279, 3294), 'numpy.power', 'np.power', (['A1', '(2)'], {}), '(A1, 2)\n', (3287, 3294), True, 'import numpy as np\n'), ((6185, 6221), 'numpy.abs', 'np.abs', (['(Y_prediction_train - Y_train)'], {}), '(Y_prediction_train - Y_train)\n', (6191, 6221), True, 'import numpy as np\n'), ((6284, 6318), 'numpy.abs', 'np.abs', (['(Y_prediction_test - Y_test)'], {}), '(Y_prediction_test - Y_test)\n', (6290, 6318), True, 'import numpy as np\n')]
"""Test motif.features.bitteli """ import unittest import numpy as np from motif.feature_extractors import bitteli def array_equal(array1, array2): return np.all(np.isclose(array1, array2, atol=1e-7)) class TestBitteliFeatures(unittest.TestCase): def setUp(self): self.ftr = bitteli.BitteliFeatures() def test_ref_hz(self): expected = 55.0 actual = self.ftr.ref_hz self.assertEqual(expected, actual) def test_poly_degree(self): expected = 5 actual = self.ftr.poly_degree self.assertEqual(expected, actual) def test_min_freq(self): expected = 3 actual = self.ftr.min_freq self.assertEqual(expected, actual) def test_max_freq(self): expected = 30 actual = self.ftr.max_freq self.assertEqual(expected, actual) def test_freq_step(self): expected = 0.1 actual = self.ftr.freq_step self.assertEqual(expected, actual) def test_vibrato_threshold(self): expected = 0.25 actual = self.ftr.vibrato_threshold self.assertEqual(expected, actual) def test_get_feature_vector(self): times = np.linspace(0, 1, 2000) freqs_hz = 440.0 * np.ones((2000, )) salience = 0.5 * np.ones((2000, )) sample_rate = 2000 actual = self.ftr.get_feature_vector( times, freqs_hz, salience, sample_rate ) expected = np.array([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3600.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]) self.assertTrue(array_equal(expected, actual)) self.assertEqual(len(actual), len(self.ftr.feature_names)) def test_get_feature_names(self): expected = [ 'vibrato rate', 'vibrato extent', 'vibrato coverage', 'vibrato coverage - beginning', 'vibrato coverage - middle', 'vibrato coverage - end', '0th polynomial coeff - freq', '1st polynomial coeff - freq', '2nd polynomial coeff - freq', '3rd polynomial coeff - freq', '4th polynomial coeff - freq', '5th polynomial coeff - freq', 'polynomial fit residual - freq', 'overall model fit residual - freq', '0th polynomial coeff - salience', '1st polynomial coeff - salience', '2nd polynomial coeff - salience', '3rd polynomial coeff - salience', '4th polynomial coeff - salience', '5th polynomial coeff - salience', 'polynomial fit residual - salience', 'duration', 'pitch stddev (cents)', 'pitch range (cents)', 'pitch average variation', 'salience stdev', 'salience range', 'salience average variation' ] actual = self.ftr.feature_names self.assertEqual(expected, actual) def test_get_id(self): expected = 'bitteli' actual = self.ftr.get_id() self.assertEqual(expected, actual)
[ "numpy.isclose", "numpy.ones", "motif.feature_extractors.bitteli.BitteliFeatures", "numpy.array", "numpy.linspace" ]
[((169, 207), 'numpy.isclose', 'np.isclose', (['array1', 'array2'], {'atol': '(1e-07)'}), '(array1, array2, atol=1e-07)\n', (179, 207), True, 'import numpy as np\n'), ((297, 322), 'motif.feature_extractors.bitteli.BitteliFeatures', 'bitteli.BitteliFeatures', ([], {}), '()\n', (320, 322), False, 'from motif.feature_extractors import bitteli\n'), ((1184, 1207), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(2000)'], {}), '(0, 1, 2000)\n', (1195, 1207), True, 'import numpy as np\n'), ((1449, 1612), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3600.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3600.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, \n 0.0, 0.0])\n', (1457, 1612), True, 'import numpy as np\n'), ((1235, 1251), 'numpy.ones', 'np.ones', (['(2000,)'], {}), '((2000,))\n', (1242, 1251), True, 'import numpy as np\n'), ((1278, 1294), 'numpy.ones', 'np.ones', (['(2000,)'], {}), '((2000,))\n', (1285, 1294), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ # 3D Image Data Synthesis. # Copyright (C) 2021 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Liceense at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Please refer to the documentation for more information about the software # as well as for installation instructions. # """ import os import glob import csv import numpy as np def get_files(folders, data_root='', descriptor='', filetype='tif'): filelist = [] for folder in folders: files = glob.glob(os.path.join(data_root, folder, '*'+descriptor+'*.'+filetype)) filelist.extend([os.path.join(folder, os.path.split(f)[-1]) for f in files]) return filelist def read_csv(list_path, data_root=''): filelist = [] with open(list_path, 'r') as f: reader = csv.reader(f, delimiter=';') for row in reader: if len(row)==0 or np.sum([len(r) for r in row])==0: continue row = [os.path.join(data_root, r) for r in row] filelist.append(row) return filelist def create_csv(data_list, save_path='list_folder/experiment_name', test_split=0.2, val_split=0.1, shuffle=False): if shuffle: np.random.shuffle(data_list) # Get number of files for each split num_files = len(data_list) num_test_files = int(test_split*num_files) num_val_files = int((num_files-num_test_files)*val_split) num_train_files = num_files - num_test_files - num_val_files # Get file indices file_idx = np.arange(num_files) # Save csv files if num_test_files > 0: test_idx = sorted(np.random.choice(file_idx, size=num_test_files, replace=False)) with open(save_path+'_test.csv', 'w') as fh: writer = csv.writer(fh, delimiter=';') for idx in test_idx: writer.writerow(data_list[idx]) else: test_idx = [] if num_val_files > 0: val_idx = sorted(np.random.choice(list(set(file_idx)-set(test_idx)), size=num_val_files, replace=False)) with open(save_path+'_val.csv', 'w') as fh: writer = csv.writer(fh, delimiter=';') for idx in val_idx: writer.writerow(data_list[idx]) else: val_idx = [] if num_train_files > 0: train_idx = sorted(list(set(file_idx) - set(test_idx) - set(val_idx))) with open(save_path+'_train.csv', 'w') as fh: writer = csv.writer(fh, delimiter=';') for idx in train_idx: writer.writerow(data_list[idx])
[ "numpy.random.choice", "csv.writer", "os.path.join", "os.path.split", "csv.reader", "numpy.arange", "numpy.random.shuffle" ]
[((2046, 2066), 'numpy.arange', 'np.arange', (['num_files'], {}), '(num_files)\n', (2055, 2066), True, 'import numpy as np\n'), ((1316, 1344), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (1326, 1344), False, 'import csv\n'), ((1723, 1751), 'numpy.random.shuffle', 'np.random.shuffle', (['data_list'], {}), '(data_list)\n', (1740, 1751), True, 'import numpy as np\n'), ((997, 1064), 'os.path.join', 'os.path.join', (['data_root', 'folder', "('*' + descriptor + '*.' + filetype)"], {}), "(data_root, folder, '*' + descriptor + '*.' + filetype)\n", (1009, 1064), False, 'import os\n'), ((2146, 2208), 'numpy.random.choice', 'np.random.choice', (['file_idx'], {'size': 'num_test_files', 'replace': '(False)'}), '(file_idx, size=num_test_files, replace=False)\n', (2162, 2208), True, 'import numpy as np\n'), ((2284, 2313), 'csv.writer', 'csv.writer', (['fh'], {'delimiter': '""";"""'}), "(fh, delimiter=';')\n", (2294, 2313), False, 'import csv\n'), ((2648, 2677), 'csv.writer', 'csv.writer', (['fh'], {'delimiter': '""";"""'}), "(fh, delimiter=';')\n", (2658, 2677), False, 'import csv\n'), ((2976, 3005), 'csv.writer', 'csv.writer', (['fh'], {'delimiter': '""";"""'}), "(fh, delimiter=';')\n", (2986, 3005), False, 'import csv\n'), ((1464, 1490), 'os.path.join', 'os.path.join', (['data_root', 'r'], {}), '(data_root, r)\n', (1476, 1490), False, 'import os\n'), ((1106, 1122), 'os.path.split', 'os.path.split', (['f'], {}), '(f)\n', (1119, 1122), False, 'import os\n')]
import numpy as np import torch from modules.frustum import get_box_corners_3d from kitti_meters.util import get_box_iou_3d __all__ = ['MeterFrustumKitti'] class MeterFrustumKitti: def __init__(self, num_heading_angle_bins, num_size_templates, size_templates, class_name_to_class_id, metric='iou_3d'): super().__init__() assert metric in ['iou_2d', 'iou_3d', 'accuracy', 'iou_3d_accuracy', 'iou_3d_class_accuracy'] self.metric = metric self.num_heading_angle_bins = num_heading_angle_bins self.num_size_templates = num_size_templates self.size_templates = size_templates.view(self.num_size_templates, 3) self.heading_angle_bin_centers = torch.arange(0, 2 * np.pi, 2 * np.pi / self.num_heading_angle_bins) self.class_name_to_class_id = class_name_to_class_id self.reset() def reset(self): self.total_seen_num = 0 self.total_correct_num = 0 self.iou_3d_corrent_num = 0 self.iou_2d_sum = 0 self.iou_3d_sum = 0 self.iou_3d_corrent_num_per_class = {cls: 0 for cls in self.class_name_to_class_id.keys()} self.total_seen_num_per_class = {cls: 0 for cls in self.class_name_to_class_id.keys()} def update(self, outputs, targets): if self.metric == 'accuracy': mask_logits = outputs['mask_logits'] mask_logits_target = targets['mask_logits'] self.total_seen_num += mask_logits_target.numel() self.total_correct_num += torch.sum(mask_logits.argmax(dim=1) == mask_logits_target).item() else: center = outputs['center'] # (B, 3) heading_scores = outputs['heading_scores'] # (B, NH) heading_residuals = outputs['heading_residuals'] # (B, NH) size_scores = outputs['size_scores'] # (B, NS) size_residuals = outputs['size_residuals'] # (B, NS, 3) center_target = targets['center'] # (B, 3) heading_bin_id_target = targets['heading_bin_id'] # (B, ) heading_residual_target = targets['heading_residual'] # (B, ) size_template_id_target = targets['size_template_id'] # (B, ) size_residual_target = targets['size_residual'] # (B, 3) class_id_target = targets['class_id'].cpu().numpy() # (B, ) batch_size = center.size(0) batch_id = torch.arange(batch_size, device=center.device) self.size_templates = self.size_templates.to(center.device) self.heading_angle_bin_centers = self.heading_angle_bin_centers.to(center.device) heading_bin_id = torch.argmax(heading_scores, dim=1) heading = self.heading_angle_bin_centers[heading_bin_id] + heading_residuals[batch_id, heading_bin_id] size_template_id = torch.argmax(size_scores, dim=1) size = self.size_templates[size_template_id] + size_residuals[batch_id, size_template_id] # (B, 3) corners = get_box_corners_3d(centers=center, headings=heading, sizes=size, with_flip=False) # (B, 8, 3) heading_target = self.heading_angle_bin_centers[heading_bin_id_target] + heading_residual_target # (B, ) size_target = self.size_templates[size_template_id_target] + size_residual_target # (B, 3) corners_target = get_box_corners_3d(centers=center_target, headings=heading_target, sizes=size_target, with_flip=False) # (B, 8, 3) iou_3d, iou_2d = get_box_iou_3d(corners.cpu().detach().numpy(), corners_target.cpu().detach().numpy()) self.iou_2d_sum += iou_2d.sum() self.iou_3d_sum += iou_3d.sum() self.iou_3d_corrent_num += np.sum(iou_3d >= 0.7) self.total_seen_num += batch_size for cls, cls_id in self.class_name_to_class_id.items(): mask = (class_id_target == cls_id) self.iou_3d_corrent_num_per_class[cls] += np.sum(iou_3d[mask] >= (0.7 if cls == 'Car' else 0.5)) self.total_seen_num_per_class[cls] += np.sum(mask) def compute(self): if self.metric == 'iou_3d': return self.iou_3d_sum / self.total_seen_num elif self.metric == 'iou_2d': return self.iou_2d_sum / self.total_seen_num elif self.metric == 'accuracy': return self.total_correct_num / self.total_seen_num elif self.metric == 'iou_3d_accuracy': return self.iou_3d_corrent_num / self.total_seen_num elif self.metric == 'iou_3d_class_accuracy': return sum(self.iou_3d_corrent_num_per_class[cls] / max(self.total_seen_num_per_class[cls], 1) for cls in self.class_name_to_class_id.keys()) / len(self.class_name_to_class_id) else: raise KeyError
[ "modules.frustum.get_box_corners_3d", "numpy.sum", "torch.arange", "torch.argmax" ]
[((717, 784), 'torch.arange', 'torch.arange', (['(0)', '(2 * np.pi)', '(2 * np.pi / self.num_heading_angle_bins)'], {}), '(0, 2 * np.pi, 2 * np.pi / self.num_heading_angle_bins)\n', (729, 784), False, 'import torch\n'), ((2407, 2453), 'torch.arange', 'torch.arange', (['batch_size'], {'device': 'center.device'}), '(batch_size, device=center.device)\n', (2419, 2453), False, 'import torch\n'), ((2650, 2685), 'torch.argmax', 'torch.argmax', (['heading_scores'], {'dim': '(1)'}), '(heading_scores, dim=1)\n', (2662, 2685), False, 'import torch\n'), ((2832, 2864), 'torch.argmax', 'torch.argmax', (['size_scores'], {'dim': '(1)'}), '(size_scores, dim=1)\n', (2844, 2864), False, 'import torch\n'), ((2999, 3085), 'modules.frustum.get_box_corners_3d', 'get_box_corners_3d', ([], {'centers': 'center', 'headings': 'heading', 'sizes': 'size', 'with_flip': '(False)'}), '(centers=center, headings=heading, sizes=size, with_flip=\n False)\n', (3017, 3085), False, 'from modules.frustum import get_box_corners_3d\n'), ((3345, 3452), 'modules.frustum.get_box_corners_3d', 'get_box_corners_3d', ([], {'centers': 'center_target', 'headings': 'heading_target', 'sizes': 'size_target', 'with_flip': '(False)'}), '(centers=center_target, headings=heading_target, sizes=\n size_target, with_flip=False)\n', (3363, 3452), False, 'from modules.frustum import get_box_corners_3d\n'), ((3751, 3772), 'numpy.sum', 'np.sum', (['(iou_3d >= 0.7)'], {}), '(iou_3d >= 0.7)\n', (3757, 3772), True, 'import numpy as np\n'), ((3996, 4050), 'numpy.sum', 'np.sum', (["(iou_3d[mask] >= (0.7 if cls == 'Car' else 0.5))"], {}), "(iou_3d[mask] >= (0.7 if cls == 'Car' else 0.5))\n", (4002, 4050), True, 'import numpy as np\n'), ((4105, 4117), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (4111, 4117), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from Bio import AlignIO, Seq # parameter to determine the maximum missing proportion that we keep missing_thresh = 0.4 # load the alignments and turn them into a numpy array alignments = AlignIO.read(snakemake.input[0], 'fasta') align_arr = np.array([list(rec) for rec in alignments]) # get a list of missing values per base missing_bases = [] # iterate over the whole alignment counting missing bases for base in range(align_arr.shape[1]): missing = 0 for seq in range(align_arr.shape[0]): if alignments[seq, base] not in ['A', 'T', 'G', 'C']: missing += 1 missing_bases.append(missing) # calculate the proportion of missing bases for each column missing_prop = np.array([m / align_arr.shape[0] for m in missing_bases]) align_arr = align_arr[:, missing_prop < missing_thresh] for r, rec in enumerate(alignments): joined_seq = ''.join(align_arr[r]) print(joined_seq[:10]) rec.seq = Seq.Seq(joined_seq) with open(snakemake.output[0], 'w') as fout: AlignIO.write(alignments, fout, 'fasta')
[ "numpy.array", "Bio.Seq.Seq", "Bio.AlignIO.read", "Bio.AlignIO.write" ]
[((228, 269), 'Bio.AlignIO.read', 'AlignIO.read', (['snakemake.input[0]', '"""fasta"""'], {}), "(snakemake.input[0], 'fasta')\n", (240, 269), False, 'from Bio import AlignIO, Seq\n'), ((739, 798), 'numpy.array', 'np.array', (['[(m / align_arr.shape[0]) for m in missing_bases]'], {}), '([(m / align_arr.shape[0]) for m in missing_bases])\n', (747, 798), True, 'import numpy as np\n'), ((971, 990), 'Bio.Seq.Seq', 'Seq.Seq', (['joined_seq'], {}), '(joined_seq)\n', (978, 990), False, 'from Bio import AlignIO, Seq\n'), ((1041, 1081), 'Bio.AlignIO.write', 'AlignIO.write', (['alignments', 'fout', '"""fasta"""'], {}), "(alignments, fout, 'fasta')\n", (1054, 1081), False, 'from Bio import AlignIO, Seq\n')]
from __future__ import (division, print_function, absolute_import, unicode_literals) import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline as InterpUS from powderday.nebular_emission.cloudy_tools import sym_to_name """ ------------------------------------------------------------------------------------------ From cloudyfsps written by <NAME>. (Source https://github.com/nell-byler/cloudyfsps/blob/master/cloudyfsps/nebAbundTools.py retrieved in October 2019) ------------------------------------------------------------------------------------------ """ def getNebAbunds(set_name, logZ, dust=True, re_z=False, **kwargs): """ neb_abund.get_abunds(set_name, logZ, dust=True, re_z=False) set_name must be 'dopita', 'newdopita', 'cl01' or 'yeh' """ allowed_names = ['dopita', 'newdopita', 'cl01', 'yeh', 'varyNO', 'gutkin', 'UVbyler', 'varyCO'] if set_name in allowed_names: return eval('{}({}, dust={}, re_z={})'.format(set_name, logZ, dust, re_z)) else: raise IOError(allowed_names) class abundSet(object): def __init__(self, set_name, logZ): """ overarching class for abundance sets. abundSet('dopita', 0.0) """ self.logZ = logZ self.abund_0 = load_abund(set_name) self.depl = load_depl(set_name) self.calcSpecial() self.calcFinal() self.inputStrings() def calcSpecial(self): return def calcFinal(self): return def inputStrings(self): self.solarstr = 'abundances {} {}'.format(self.solar, self.grains) elem_strs = [] names = sym_to_name() for key in self.abund_0.keys(): elm = names[key] abund = self.__getattribute__(key) # if hasattr(self, 're_z'): # if key != 'He': # abund -= self.re_z outstr = 'element abundance {0} {1:.2f} log'.format(elm, abund) elem_strs.append(outstr) self.__setattr__('elem_strs', elem_strs) return class dopita(abundSet): solar = 'old solar 84' def __init__(self, logZ, dust=True, re_z=False): """ Dopita+2001: old solar abundances = 0.019 ISM grains """ if dust: self.grains = 'no grains\ngrains ISM' else: self.grains = 'no grains' if re_z: self.re_z = logZ else: self.re_z = 0.0 abundSet.__init__(self, 'dopita', logZ) def calcSpecial(self): """ piece-wise function for nitrogen abund (step-function) functional form for helium """ def calc_N(logZ): if logZ <= -0.63: return -4.57 + logZ else: return -3.94 + (2.0 * logZ) def calc_He(logZ): return np.log10(0.08096 + (0.02618 * (10.0 ** logZ))) self.__setattr__('He', calc_He(self.logZ)) self.__setattr__('N', calc_N(self.logZ) + self.depl['N']) return def calcFinal(self): """ apply depletions and scale with logZ """ [self.__setattr__(key, val + self.logZ + self.depl[key]) for key, val in self.abund_0.items() if not hasattr(self, key)] return class newdopita(abundSet): solar = 'GASS10' def __init__(self, logZ, dust=True, re_z=False): """ Abundances from Dopita (2013) Solar Abundances from Grevasse 2010 - z= 0.013 includes smooth polynomial for N/O, C/O relationship functional form for He(z) new depletion factors ISM grains """ if dust: self.grains = 'no grains\ngrains ISM' else: self.grains = 'no grains' self.re_z = re_z abundSet.__init__(self, 'newdopita', logZ) def calcSpecial(self): def calc_He(logZ): return np.log10(0.0737 + (0.024 * (10.0 ** logZ))) def calc_CNO(logZ): oxy = np.array([7.39, 7.50, 7.69, 7.99, 8.17, 8.39, 8.69, 8.80, 8.99, 9.17, 9.39]) nit = np.array([-6.61, -6.47, -6.23, -5.79, -5.51, -5.14, -4.60, -4.40, -4.04, -3.67, -3.17]) car = np.array([-5.58, -5.44, -5.20, -4.76, -4.48, -4.11, -3.57, -3.37, -3.01, -2.64, -2.14]) O = self.abund_0['O'] + logZ C = float(InterpUS(oxy, car, k=1)(O + 12.0)) N = float(InterpUS(oxy, nit, k=1)(O + 12.0)) return C, N, O self.__setattr__('He', calc_He(self.logZ)) C, N, O = calc_CNO(self.logZ) [self.__setattr__(key, val + self.depl[key]) for key, val in zip(['C', 'N', 'O'], [C, N, O])] return def calcFinal(self): [self.__setattr__(key, val + self.logZ + self.depl[key]) for key, val in self.abund_0.items() if not hasattr(self, key)] return class UVbyler(abundSet): solar = 'GASS10' def __init__(self, logZ, dust=True, re_z=False): """ Abundances from Dopita (2013) Solar Abundances from Grevasse 2010 - z= 0.013 New fit for N/O, C/O relationship functional form for He(z) new depletion factors ISM grains """ if dust: self.grains = 'no grains\ngrains ISM' else: self.grains = 'no grains' self.re_z = re_z abundSet.__init__(self, 'UVbyler', logZ) def calcSpecial(self): def calc_He(logZ): return np.log10(0.0737 + (0.024 * (10.0 ** logZ))) def calc_CNO(logZ): O = self.abund_0['O'] + logZ # C = np.log10((1.0*10.**O)*(10.**-1.1 + 10.**(2.96 + O))) C = np.log10((10. ** O) * (10. ** -0.7 + 10. ** (4.8 + 1.45 * O))) # N = np.log10((1.0*10.**O)*(10.**-1.8 + 10.**(2.2 + O))) # N = np.log10((10.**O)*(10.**-1.5 + 10.**(2.5 + 1.2*O))) N = np.log10((1.0 * 10. ** O) * (10. ** -1.55 + 10. ** (2.3 + 1.1 * O))) # N = -4.81 + logZ if logZ <= -0.3 else -4.51 + 2.0*logZ return C, N, O self.__setattr__('He', calc_He(self.logZ)) C, N, O = calc_CNO(self.logZ) [self.__setattr__(key, val + self.depl[key]) for key, val in zip(['C', 'N', 'O'], [C, N, O])] return def calcFinal(self): [self.__setattr__(key, val + self.logZ + self.depl[key]) for key, val in self.abund_0.items() if not hasattr(self, key)] return class gutkin(abundSet): solar = 'GASS10' def __init__(self, logZ, dust=True, re_z=False): """ Gutkin+2016 PARSEC metallicity (Bressan+2012) based on Grevesse+Sauvel (1998) and Caffau+2011 """ if dust: self.grains = 'no grains\ngrains ISM' else: self.grains = 'no grains' self.re_z = re_z abundSet.__init__(self, 'gutkin', logZ) def calcSpecial(self): def calc_He(logZ): Z = (10. ** logZ) * 0.01524 Y = 0.2485 + 1.7756 * Z X = 1. - Y - Z return np.log10(Y / X / 4.) def calc_CNO(logZ): O = self.abund_0['O'] + logZ N = np.log10((0.41 * 10. ** O) * (10. ** -1.6 + 10. ** (2.33 + O))) C = self.abund_0['C'] + logZ return C, N, O self.__setattr__('He', calc_He(self.logZ)) C, N, O = calc_CNO(self.logZ) [self.__setattr__(key, val) for key, val in zip(['C', 'N', 'O'], [C, N, O])] return def calcFinal(self): [self.__setattr__(key, val) for key, val in self.abund_0.items() if not hasattr(self, key)] return def load_abund(set_name): if set_name == 'dopita': adict = dict(He=-1.01, C=-3.44, N=-3.95, O=-3.07, Ne=-3.91, Mg=-4.42, Si=-4.45, S=-4.79, Ar=-5.44, Ca=-5.64, Fe=-4.33, F=-7.52, Na=-5.69, Al=-5.53, P=-6.43, Cl=-6.73, K=-6.87, Ti=-6.96, Cr=-6.32, Mn=-6.47, Co=-7.08, Ni=-5.75, Cu=-7.73, Zn=-7.34) elif set_name == 'newdopita': adict = dict(He=-1.01, C=-3.57, N=-4.60, O=-3.31, Ne=-4.07, Na=-5.75, Mg=-4.40, Al=-5.55, Si=-4.49, S=-4.86, Cl=-6.63, Ar=-5.60, Ca=-5.66, Fe=-4.50, Ni=-5.78, F=-7.44, P=-6.59, K=-6.97, Cr=-6.36, Ti=-7.05, Mn=-6.57, Co=-7.01, Cu=-7.81, Zn=-7.44) elif set_name == 'UVbyler': adict = dict(He=-1.01, C=-3.57, N=-4.17, O=-3.31, Ne=-4.07, Na=-5.75, Mg=-4.40, Al=-5.55, Si=-4.49, S=-4.86, Cl=-6.63, Ar=-5.60, Ca=-5.66, Fe=-4.50, Ni=-5.78, F=-7.44, P=-6.59, K=-6.97, Cr=-6.36, Ti=-7.05, Mn=-6.57, Co=-7.01, Cu=-7.81, Zn=-7.44) elif set_name == 'gutkin': adict = dict(He=-1.01, C=-3.53, N=-4.32, O=-3.17, F=-7.47, Ne=-4.01, Na=-5.70, Mg=-4.45, Al=-5.56, Si=-4.48, P=-6.57, S=-4.87, Cl=-6.53, Ar=-5.63, K=-6.92, Ca=-5.67, Sc=-8.86, Ti=-7.01, V=-8.03, Cr=-6.36, Mn=-6.64, Fe=-4.51, Co=-7.11, Ni=-5.78, Cu=-7.82, Zn=-7.43) return adict def load_depl(set_name): if set_name == 'dopita': ddict = dict(C=-0.30, N=-0.22, O=-0.22, Ne=0.0, Mg=-0.70, Si=-1.0, S=0.0, Ar=0.0, Ca=-2.52, Fe=-2.0, F=0.0, Na=0.0, Al=0.0, P=0.0, Cl=0.0, K=0.0, Ti=0.0, Cr=0.0, Mn=0.0, Co=0.0, Ni=0.0, Cu=0.0, Zn=0.0) elif set_name == 'newdopita': ddict = dict(He=0.00, C=-0.30, N=-0.05, O=-0.07, Ne=0.00, Na=-1.00, Mg=-1.08, Al=-1.39, Si=-0.81, S=0.00, Cl=-1.00, Ar=0.00, Ca=-2.52, Fe=-1.31, Ni=-2.00, F=0.0, P=0.0, K=0.0, Cr=0.0, Ti=0.0, Mn=0.0, Co=0.0, Cu=0.0, Zn=0.0) elif set_name == 'UVbyler': ddict = dict(He=0.00, C=-0.30, N=-0.05, O=-0.07, Ne=0.00, Na=-1.00, Mg=-1.08, Al=-1.39, Si=-0.81, S=0.00, Cl=-1.00, Ar=0.00, Ca=-2.52, Fe=-1.31, Ni=-2.00, F=0.0, P=0.0, K=0.0, Cr=0.0, Ti=0.0, Mn=0.0, Co=0.0, Cu=0.0, Zn=0.0) elif set_name == 'gutkin': ddict = dict(He=0.00, Li=-0.8, C=-0.30, O=-0.15, Na=-0.60, Mg=-0.70, Al=-1.70, Si=-1.00, Cl=-0.30, Ca=-2.52, Fe=-2.00, Ni=-1.40) return ddict
[ "numpy.array", "numpy.log10", "scipy.interpolate.InterpolatedUnivariateSpline", "powderday.nebular_emission.cloudy_tools.sym_to_name" ]
[((1685, 1698), 'powderday.nebular_emission.cloudy_tools.sym_to_name', 'sym_to_name', ([], {}), '()\n', (1696, 1698), False, 'from powderday.nebular_emission.cloudy_tools import sym_to_name\n'), ((2912, 2954), 'numpy.log10', 'np.log10', (['(0.08096 + 0.02618 * 10.0 ** logZ)'], {}), '(0.08096 + 0.02618 * 10.0 ** logZ)\n', (2920, 2954), True, 'import numpy as np\n'), ((3994, 4033), 'numpy.log10', 'np.log10', (['(0.0737 + 0.024 * 10.0 ** logZ)'], {}), '(0.0737 + 0.024 * 10.0 ** logZ)\n', (4002, 4033), True, 'import numpy as np\n'), ((4085, 4159), 'numpy.array', 'np.array', (['[7.39, 7.5, 7.69, 7.99, 8.17, 8.39, 8.69, 8.8, 8.99, 9.17, 9.39]'], {}), '([7.39, 7.5, 7.69, 7.99, 8.17, 8.39, 8.69, 8.8, 8.99, 9.17, 9.39])\n', (4093, 4159), True, 'import numpy as np\n'), ((4208, 4298), 'numpy.array', 'np.array', (['[-6.61, -6.47, -6.23, -5.79, -5.51, -5.14, -4.6, -4.4, -4.04, -3.67, -3.17]'], {}), '([-6.61, -6.47, -6.23, -5.79, -5.51, -5.14, -4.6, -4.4, -4.04, -\n 3.67, -3.17])\n', (4216, 4298), True, 'import numpy as np\n'), ((4342, 4433), 'numpy.array', 'np.array', (['[-5.58, -5.44, -5.2, -4.76, -4.48, -4.11, -3.57, -3.37, -3.01, -2.64, -2.14]'], {}), '([-5.58, -5.44, -5.2, -4.76, -4.48, -4.11, -3.57, -3.37, -3.01, -\n 2.64, -2.14])\n', (4350, 4433), True, 'import numpy as np\n'), ((5666, 5705), 'numpy.log10', 'np.log10', (['(0.0737 + 0.024 * 10.0 ** logZ)'], {}), '(0.0737 + 0.024 * 10.0 ** logZ)\n', (5674, 5705), True, 'import numpy as np\n'), ((5867, 5930), 'numpy.log10', 'np.log10', (['(10.0 ** O * (10.0 ** -0.7 + 10.0 ** (4.8 + 1.45 * O)))'], {}), '(10.0 ** O * (10.0 ** -0.7 + 10.0 ** (4.8 + 1.45 * O)))\n', (5875, 5930), True, 'import numpy as np\n'), ((6086, 6155), 'numpy.log10', 'np.log10', (['(1.0 * 10.0 ** O * (10.0 ** -1.55 + 10.0 ** (2.3 + 1.1 * O)))'], {}), '(1.0 * 10.0 ** O * (10.0 ** -1.55 + 10.0 ** (2.3 + 1.1 * O)))\n', (6094, 6155), True, 'import numpy as np\n'), ((7267, 7288), 'numpy.log10', 'np.log10', (['(Y / X / 4.0)'], {}), '(Y / X / 4.0)\n', (7275, 7288), True, 'import numpy as np\n'), ((7374, 7438), 'numpy.log10', 'np.log10', (['(0.41 * 10.0 ** O * (10.0 ** -1.6 + 10.0 ** (2.33 + O)))'], {}), '(0.41 * 10.0 ** O * (10.0 ** -1.6 + 10.0 ** (2.33 + O)))\n', (7382, 7438), True, 'import numpy as np\n'), ((4521, 4544), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpUS', (['oxy', 'car'], {'k': '(1)'}), '(oxy, car, k=1)\n', (4529, 4544), True, 'from scipy.interpolate import InterpolatedUnivariateSpline as InterpUS\n'), ((4578, 4601), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpUS', (['oxy', 'nit'], {'k': '(1)'}), '(oxy, nit, k=1)\n', (4586, 4601), True, 'from scipy.interpolate import InterpolatedUnivariateSpline as InterpUS\n')]
from sklearn.preprocessing import StandardScaler, LabelEncoder, MinMaxScaler, OneHotEncoder import numpy as np import pandas as pd import tqdm """ Class for Preprocessing CICIDS2017 Data represented as rows """ class CICIDSPreprocessor: def __init__(self): self.to_delete_columns = ['Flow ID', ' Timestamp'] self.label_column = ' Label' def preprocess_train_data(self, df: pd.DataFrame, label="BENIGN"): df = df.drop(self.to_delete_columns, axis=1) df = df[df[self.label_column] == label] df.reset_index(drop=True, inplace=True) df.drop(self.label_column, axis=1, inplace=True) return df.fillna(0) def preprocess_test_data(self, df: pd.DataFrame, label="BENIGN"): df = df.drop(self.to_delete_columns, axis=1) df = df[df[self.label_column] == label] df.reset_index(drop=True, inplace=True) df.drop(self.label_column, axis=1, inplace=True) return df.fillna(0) def __get_windows(self, df, window_size=20, stride=10): windows_arr = [] for i in tqdm.tqdm(range(0, len(df)-window_size+1, stride)): windows_arr.append(df.iloc[i:i+window_size, :].to_numpy()) return np.array(windows_arr)
[ "numpy.array" ]
[((1214, 1235), 'numpy.array', 'np.array', (['windows_arr'], {}), '(windows_arr)\n', (1222, 1235), True, 'import numpy as np\n')]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 dlilien <<EMAIL>> # # Distributed under terms of the MIT license. """ """ import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt from .cartopy_overrides import SPS # import shapely.geometry as sgeom USP_EXTENT = (31000, 35000, -37750, -33750) # USP_EXTENT = (-100000, 100000, -100000, 100000) USP_ASP = (USP_EXTENT[1] - USP_EXTENT[0]) / (USP_EXTENT[3] - USP_EXTENT[2]) def upstream(ax=None, fig_kwargs=None): if fig_kwargs is None: fig_kwargs = {} if ax is None: _, ax = plt.subplots(**fig_kwargs, subplot_kw={'projection': SPS()}) ax.set_extent(USP_EXTENT, ccrs.epsg(3031)) ax._xlocs = np.arange(0, 180) ax._ylocs = np.arange(-90, -80, 0.1) ax._y_inline = False ax._x_inline = False return ax
[ "cartopy.crs.epsg", "numpy.arange" ]
[((733, 750), 'numpy.arange', 'np.arange', (['(0)', '(180)'], {}), '(0, 180)\n', (742, 750), True, 'import numpy as np\n'), ((767, 791), 'numpy.arange', 'np.arange', (['(-90)', '(-80)', '(0.1)'], {}), '(-90, -80, 0.1)\n', (776, 791), True, 'import numpy as np\n'), ((700, 715), 'cartopy.crs.epsg', 'ccrs.epsg', (['(3031)'], {}), '(3031)\n', (709, 715), True, 'import cartopy.crs as ccrs\n')]
import gym from gym import spaces, error, utils from gym.utils import seeding import numpy as np import configparser from os import path import matplotlib.pyplot as plt from matplotlib.pyplot import gca font = {'family': 'sans-serif', 'weight': 'bold', 'size': 14} class FlockingEnv(gym.Env): def __init__(self): config_file = path.join(path.dirname(__file__), "params_flock.cfg") config = configparser.ConfigParser() config.read(config_file) config = config['flock'] self.dynamic = False # if the agents are moving or not self.mean_pooling = True # normalize the adjacency matrix by the number of neighbors or not # number states per agent self.nx_system = 4 # numer of observations per agent self.n_features = 6 # number of actions per agent self.nu = 2 # problem parameters from file self.n_agents = int(config['network_size']) self.comm_radius = float(config['comm_radius']) self.comm_radius2 = self.comm_radius * self.comm_radius self.dt = float(config['system_dt']) self.v_max = float(config['max_vel_init']) self.v_bias = self.v_max self.r_max = float(config['max_rad_init']) self.std_dev = float(config['std_dev']) * self.dt # intitialize state matrices self.x = np.zeros((self.n_agents, self.nx_system)) self.u = np.zeros((self.n_agents, self.nu)) self.mean_vel = np.zeros((self.n_agents, self.nu)) self.init_vel = np.zeros((self.n_agents, self.nu)) self.a_net = np.zeros((self.n_agents, self.n_agents)) # TODO : what should the action space be? is [-1,1] OK? self.max_accel = 1 self.gain = 10.0 # TODO - adjust if necessary - may help the NN performance self.action_space = spaces.Box(low=-self.max_accel, high=self.max_accel, shape=(2 * self.n_agents,), dtype=np.float32) self.observation_space = spaces.Box(low=-np.Inf, high=np.Inf, shape=(self.n_agents, self.n_features), dtype=np.float32) self.fig = None self.line1 = None self.seed() def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, u): #u = np.reshape(u, (-1, 2)) assert u.shape == (self.n_agents, self.nu) self.u = u if self.dynamic: # x position self.x[:, 0] = self.x[:, 0] + self.x[:, 2] * self.dt # y position self.x[:, 1] = self.x[:, 1] + self.x[:, 3] * self.dt # x velocity self.x[:, 2] = self.x[:, 2] + self.gain * self.u[:, 0] * self.dt #+ np.random.normal(0, self.std_dev, (self.n_agents,)) # y velocity self.x[:, 3] = self.x[:, 3] + self.gain * self.u[:, 1] * self.dt #+ np.random.normal(0, self.std_dev, (self.n_agents,)) return self._get_obs(), self.instant_cost(), False, {} def instant_cost(self): # sum of differences in velocities # TODO adjust to desired reward # action_cost = -1.0 * np.sum(np.square(self.u)) #curr_variance = -1.0 * np.sum((np.var(self.x[:, 2:4], axis=0))) versus_initial_vel = -1.0 * np.sum(np.sum(np.square(self.x[:, 2:4] - self.mean_vel), axis=1)) #return curr_variance + versus_initial_vel return versus_initial_vel def reset(self): x = np.zeros((self.n_agents, self.nx_system)) degree = 0 min_dist = 0 min_dist_thresh = 0.1 # 0.25 # generate an initial configuration with all agents connected, # and minimum distance between agents > min_dist_thresh while degree < 2 or min_dist < min_dist_thresh: # randomly initialize the location and velocity of all agents length = np.sqrt(np.random.uniform(0, self.r_max, size=(self.n_agents,))) angle = np.pi * np.random.uniform(0, 2, size=(self.n_agents,)) x[:, 0] = length * np.cos(angle) x[:, 1] = length * np.sin(angle) bias = np.random.uniform(low=-self.v_bias, high=self.v_bias, size=(2,)) x[:, 2] = np.random.uniform(low=-self.v_max, high=self.v_max, size=(self.n_agents,)) + bias[0] x[:, 3] = np.random.uniform(low=-self.v_max, high=self.v_max, size=(self.n_agents,)) + bias[1] # compute distances between agents a_net = self.dist2_mat(x) # compute minimum distance between agents and degree of network to check if good initial configuration min_dist = np.sqrt(np.min(np.min(a_net))) a_net = a_net < self.comm_radius2 degree = np.min(np.sum(a_net.astype(int), axis=1)) # keep good initialization self.mean_vel = np.mean(x[:, 2:4], axis=0) self.init_vel = x[:, 2:4] self.x = x self.a_net = self.get_connectivity(self.x) return self._get_obs() def _get_obs(self): # state_values = self.x state_values = np.hstack((self.x, self.init_vel)) # initial velocities are part of state to make system observable if self.dynamic: state_network = self.get_connectivity(self.x) else: state_network = self.a_net return (state_values, state_network) def dist2_mat(self, x): """ Compute squared euclidean distances between agents. Diagonal elements are infinity Args: x (): current state of all agents Returns: symmetric matrix of size (n_agents, n_agents) with A_ij the distance between agents i and j """ x_loc = np.reshape(x[:, 0:2], (self.n_agents,2,1)) a_net = np.sum(np.square(np.transpose(x_loc, (0,2,1)) - np.transpose(x_loc, (2,0,1))), axis=2) np.fill_diagonal(a_net, np.Inf) return a_net def get_connectivity(self, x): """ Get the adjacency matrix of the network based on agent locations by computing pairwise distances using pdist Args: x (): current state of all agents Returns: adjacency matrix of network """ a_net = self.dist2_mat(x) a_net = (a_net < self.comm_radius2).astype(float) if self.mean_pooling: # Normalize the adjacency matrix by the number of neighbors - results in mean pooling, instead of sum pooling n_neighbors = np.reshape(np.sum(a_net, axis=1), (self.n_agents,1)) # TODO or axis=0? Is the mean in the correct direction? n_neighbors[n_neighbors == 0] = 1 a_net = a_net / n_neighbors return a_net def controller(self): """ Consensus-based centralized flocking with no obstacle avoidance Returns: the optimal action """ # TODO implement Tanner 2003? u = np.mean(self.x[:,2:4], axis=0) - self.x[:,2:4] u = np.clip(u, a_min=-self.max_accel, a_max=self.max_accel) return u def render(self, mode='human'): """ Render the environment with agents as points in 2D space """ if self.fig is None: plt.ion() fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(self.x[:, 0], self.x[:, 1], 'bo') # Returns a tuple of line objects, thus the comma ax.plot([0], [0], 'kx') plt.ylim(-1.0 * self.r_max, 1.0 * self.r_max) plt.xlim(-1.0 * self.r_max, 1.0 * self.r_max) a = gca() a.set_xticklabels(a.get_xticks(), font) a.set_yticklabels(a.get_yticks(), font) plt.title('GNN Controller') self.fig = fig self.line1 = line1 self.line1.set_xdata(self.x[:, 0]) self.line1.set_ydata(self.x[:, 1]) self.fig.canvas.draw() self.fig.canvas.flush_events() def close(self): pass
[ "numpy.clip", "configparser.ConfigParser", "numpy.hstack", "numpy.sin", "gym.utils.seeding.np_random", "numpy.mean", "numpy.reshape", "numpy.min", "matplotlib.pyplot.ylim", "matplotlib.pyplot.gca", "numpy.fill_diagonal", "numpy.square", "os.path.dirname", "numpy.cos", "matplotlib.pyplot.ion", "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "numpy.transpose", "gym.spaces.Box", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.random.uniform" ]
[((431, 458), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (456, 458), False, 'import configparser\n'), ((1387, 1428), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.nx_system)'], {}), '((self.n_agents, self.nx_system))\n', (1395, 1428), True, 'import numpy as np\n'), ((1446, 1480), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.nu)'], {}), '((self.n_agents, self.nu))\n', (1454, 1480), True, 'import numpy as np\n'), ((1505, 1539), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.nu)'], {}), '((self.n_agents, self.nu))\n', (1513, 1539), True, 'import numpy as np\n'), ((1564, 1598), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.nu)'], {}), '((self.n_agents, self.nu))\n', (1572, 1598), True, 'import numpy as np\n'), ((1620, 1660), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.n_agents)'], {}), '((self.n_agents, self.n_agents))\n', (1628, 1660), True, 'import numpy as np\n'), ((1866, 1969), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-self.max_accel)', 'high': 'self.max_accel', 'shape': '(2 * self.n_agents,)', 'dtype': 'np.float32'}), '(low=-self.max_accel, high=self.max_accel, shape=(2 * self.\n n_agents,), dtype=np.float32)\n', (1876, 1969), False, 'from gym import spaces, error, utils\n'), ((2039, 2137), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-np.Inf)', 'high': 'np.Inf', 'shape': '(self.n_agents, self.n_features)', 'dtype': 'np.float32'}), '(low=-np.Inf, high=np.Inf, shape=(self.n_agents, self.n_features),\n dtype=np.float32)\n', (2049, 2137), False, 'from gym import spaces, error, utils\n'), ((2313, 2336), 'gym.utils.seeding.np_random', 'seeding.np_random', (['seed'], {}), '(seed)\n', (2330, 2336), False, 'from gym.utils import seeding\n'), ((3519, 3560), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.nx_system)'], {}), '((self.n_agents, self.nx_system))\n', (3527, 3560), True, 'import numpy as np\n'), ((4882, 4908), 'numpy.mean', 'np.mean', (['x[:, 2:4]'], {'axis': '(0)'}), '(x[:, 2:4], axis=0)\n', (4889, 4908), True, 'import numpy as np\n'), ((5124, 5158), 'numpy.hstack', 'np.hstack', (['(self.x, self.init_vel)'], {}), '((self.x, self.init_vel))\n', (5133, 5158), True, 'import numpy as np\n'), ((5738, 5782), 'numpy.reshape', 'np.reshape', (['x[:, 0:2]', '(self.n_agents, 2, 1)'], {}), '(x[:, 0:2], (self.n_agents, 2, 1))\n', (5748, 5782), True, 'import numpy as np\n'), ((5892, 5923), 'numpy.fill_diagonal', 'np.fill_diagonal', (['a_net', 'np.Inf'], {}), '(a_net, np.Inf)\n', (5908, 5923), True, 'import numpy as np\n'), ((6988, 7043), 'numpy.clip', 'np.clip', (['u'], {'a_min': '(-self.max_accel)', 'a_max': 'self.max_accel'}), '(u, a_min=-self.max_accel, a_max=self.max_accel)\n', (6995, 7043), True, 'import numpy as np\n'), ((370, 392), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (382, 392), False, 'from os import path\n'), ((4178, 4242), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-self.v_bias)', 'high': 'self.v_bias', 'size': '(2,)'}), '(low=-self.v_bias, high=self.v_bias, size=(2,))\n', (4195, 4242), True, 'import numpy as np\n'), ((6929, 6960), 'numpy.mean', 'np.mean', (['self.x[:, 2:4]'], {'axis': '(0)'}), '(self.x[:, 2:4], axis=0)\n', (6936, 6960), True, 'import numpy as np\n'), ((7229, 7238), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (7236, 7238), True, 'import matplotlib.pyplot as plt\n'), ((7257, 7269), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7267, 7269), True, 'import matplotlib.pyplot as plt\n'), ((7470, 7515), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-1.0 * self.r_max)', '(1.0 * self.r_max)'], {}), '(-1.0 * self.r_max, 1.0 * self.r_max)\n', (7478, 7515), True, 'import matplotlib.pyplot as plt\n'), ((7528, 7573), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-1.0 * self.r_max)', '(1.0 * self.r_max)'], {}), '(-1.0 * self.r_max, 1.0 * self.r_max)\n', (7536, 7573), True, 'import matplotlib.pyplot as plt\n'), ((7590, 7595), 'matplotlib.pyplot.gca', 'gca', ([], {}), '()\n', (7593, 7595), False, 'from matplotlib.pyplot import gca\n'), ((7712, 7739), 'matplotlib.pyplot.title', 'plt.title', (['"""GNN Controller"""'], {}), "('GNN Controller')\n", (7721, 7739), True, 'import matplotlib.pyplot as plt\n'), ((3936, 3991), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self.r_max'], {'size': '(self.n_agents,)'}), '(0, self.r_max, size=(self.n_agents,))\n', (3953, 3991), True, 'import numpy as np\n'), ((4021, 4067), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2)'], {'size': '(self.n_agents,)'}), '(0, 2, size=(self.n_agents,))\n', (4038, 4067), True, 'import numpy as np\n'), ((4099, 4112), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (4105, 4112), True, 'import numpy as np\n'), ((4144, 4157), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (4150, 4157), True, 'import numpy as np\n'), ((4265, 4339), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-self.v_max)', 'high': 'self.v_max', 'size': '(self.n_agents,)'}), '(low=-self.v_max, high=self.v_max, size=(self.n_agents,))\n', (4282, 4339), True, 'import numpy as np\n'), ((4372, 4446), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-self.v_max)', 'high': 'self.v_max', 'size': '(self.n_agents,)'}), '(low=-self.v_max, high=self.v_max, size=(self.n_agents,))\n', (4389, 4446), True, 'import numpy as np\n'), ((6512, 6533), 'numpy.sum', 'np.sum', (['a_net'], {'axis': '(1)'}), '(a_net, axis=1)\n', (6518, 6533), True, 'import numpy as np\n'), ((3345, 3386), 'numpy.square', 'np.square', (['(self.x[:, 2:4] - self.mean_vel)'], {}), '(self.x[:, 2:4] - self.mean_vel)\n', (3354, 3386), True, 'import numpy as np\n'), ((4697, 4710), 'numpy.min', 'np.min', (['a_net'], {}), '(a_net)\n', (4703, 4710), True, 'import numpy as np\n'), ((5814, 5844), 'numpy.transpose', 'np.transpose', (['x_loc', '(0, 2, 1)'], {}), '(x_loc, (0, 2, 1))\n', (5826, 5844), True, 'import numpy as np\n'), ((5845, 5875), 'numpy.transpose', 'np.transpose', (['x_loc', '(2, 0, 1)'], {}), '(x_loc, (2, 0, 1))\n', (5857, 5875), True, 'import numpy as np\n')]
import logging from datetime import datetime import numpy as np from logging.config import dictConfig from kafkawrapper.producer import Producer from utils.mongo_utils import BenchMarkingProcessRepo from configs.configs import ulca_notifier_input_topic, ulca_notifier_benchmark_completed_event, ulca_notifier_benchmark_failed_event from models.metric_manager import MetricManager log = logging.getLogger('file') prod = Producer() repo = BenchMarkingProcessRepo() class OcrMetricEvalHandler: def __init__(self): pass def execute_ocr_metric_eval(self, request): try: log.info("Executing Ocr Metric Evaluation.... {}".format(datetime.now())) metric_mgr = MetricManager.getInstance() if 'benchmarkDatasets' in request.keys(): for benchmark in request["benchmarkDatasets"]: metric_inst = metric_mgr.get_metric_execute(benchmark["metric"], request["modelTaskType"]) if not metric_inst: log.info("Metric definition not found") doc = {'benchmarkingProcessId':request['benchmarkingProcessId'],'benchmarkDatasetId': benchmark['datasetId'],'eval_score': None} repo.insert(doc) repo.insert_pt({'benchmarkingProcessId': request['benchmarkingProcessId'], 'status': 'Failed'}) mail_notif_event = {"event": ulca_notifier_benchmark_failed_event, "entityID": request['modelId'], "userID": request['userId'], "details":{"modelName":request['modelName']}} prod.produce(mail_notif_event, ulca_notifier_input_topic, None) return ground_truth = [corpus_sentence["tgt"] for corpus_sentence in benchmark["corpus"]] machine_translation = [corpus_sentence["mtgt"] for corpus_sentence in benchmark["corpus"]] eval_score = metric_inst.ocr_metric_eval(ground_truth, machine_translation) if eval_score: doc = {'benchmarkingProcessId':request['benchmarkingProcessId'],'benchmarkDatasetId': benchmark['datasetId'],'eval_score': float(np.round(eval_score, 3))} repo.insert(doc) repo.insert_pt({'benchmarkingProcessId': request['benchmarkingProcessId'], 'status': 'Completed'}) mail_notif_event = {"event": ulca_notifier_benchmark_completed_event, "entityID": request['modelId'], "userID": request['userId'], "details":{"modelName":request['modelName']}} prod.produce(mail_notif_event, ulca_notifier_input_topic, None) else: log.exception("Exception while metric evaluation of model") doc = {'benchmarkingProcessId':request['benchmarkingProcessId'],'benchmarkDatasetId': benchmark['datasetId'],'eval_score': None} repo.insert(doc) repo.insert_pt({'benchmarkingProcessId': request['benchmarkingProcessId'], 'status': 'Failed'}) mail_notif_event = {"event": ulca_notifier_benchmark_failed_event, "entityID": request['modelId'], "userID": request['userId'], "details":{"modelName":request['modelName']}} prod.produce(mail_notif_event, ulca_notifier_input_topic, None) else: log.exception("Missing parameter: benchmark details") repo.insert_pt({'benchmarkingProcessId': request['benchmarkingProcessId'], 'status': 'Failed'}) mail_notif_event = {"event": ulca_notifier_benchmark_failed_event, "entityID": request['modelId'], "userID": request['userId'], "details":{"modelName":request['modelName']}} prod.produce(mail_notif_event, ulca_notifier_input_topic, None) return except Exception as e: log.exception(f"Exception while metric evaluation of model: {str(e)}") repo.insert_pt({'benchmarkingProcessId': request['benchmarkingProcessId'], 'status': 'Failed'}) mail_notif_event = {"event": ulca_notifier_benchmark_failed_event, "entityID": request['modelId'], "userID": request['userId'], "details":{"modelName":request['modelName']}} prod.produce(mail_notif_event, ulca_notifier_input_topic, None) # Log config dictConfig({ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] {%(filename)s:%(lineno)d} %(threadName)s %(levelname)s in %(module)s: %(message)s', }}, 'handlers': { 'info': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'formatter': 'default', 'filename': 'info.log' }, 'console': { 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'default', 'stream': 'ext://sys.stdout', } }, 'loggers': { 'file': { 'level': 'DEBUG', 'handlers': ['info', 'console'], 'propagate': '' } }, 'root': { 'level': 'DEBUG', 'handlers': ['info', 'console'] } })
[ "logging.getLogger", "kafkawrapper.producer.Producer", "utils.mongo_utils.BenchMarkingProcessRepo", "models.metric_manager.MetricManager.getInstance", "logging.config.dictConfig", "datetime.datetime.now", "numpy.round" ]
[((387, 412), 'logging.getLogger', 'logging.getLogger', (['"""file"""'], {}), "('file')\n", (404, 412), False, 'import logging\n'), ((421, 431), 'kafkawrapper.producer.Producer', 'Producer', ([], {}), '()\n', (429, 431), False, 'from kafkawrapper.producer import Producer\n'), ((439, 464), 'utils.mongo_utils.BenchMarkingProcessRepo', 'BenchMarkingProcessRepo', ([], {}), '()\n', (462, 464), False, 'from utils.mongo_utils import BenchMarkingProcessRepo\n'), ((4418, 5006), 'logging.config.dictConfig', 'dictConfig', (["{'version': 1, 'formatters': {'default': {'format':\n '[%(asctime)s] {%(filename)s:%(lineno)d} %(threadName)s %(levelname)s in %(module)s: %(message)s'\n }}, 'handlers': {'info': {'class': 'logging.FileHandler', 'level':\n 'DEBUG', 'formatter': 'default', 'filename': 'info.log'}, 'console': {\n 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter':\n 'default', 'stream': 'ext://sys.stdout'}}, 'loggers': {'file': {'level':\n 'DEBUG', 'handlers': ['info', 'console'], 'propagate': ''}}, 'root': {\n 'level': 'DEBUG', 'handlers': ['info', 'console']}}"], {}), "({'version': 1, 'formatters': {'default': {'format':\n '[%(asctime)s] {%(filename)s:%(lineno)d} %(threadName)s %(levelname)s in %(module)s: %(message)s'\n }}, 'handlers': {'info': {'class': 'logging.FileHandler', 'level':\n 'DEBUG', 'formatter': 'default', 'filename': 'info.log'}, 'console': {\n 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter':\n 'default', 'stream': 'ext://sys.stdout'}}, 'loggers': {'file': {'level':\n 'DEBUG', 'handlers': ['info', 'console'], 'propagate': ''}}, 'root': {\n 'level': 'DEBUG', 'handlers': ['info', 'console']}})\n", (4428, 5006), False, 'from logging.config import dictConfig\n'), ((705, 732), 'models.metric_manager.MetricManager.getInstance', 'MetricManager.getInstance', ([], {}), '()\n', (730, 732), False, 'from models.metric_manager import MetricManager\n'), ((663, 677), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (675, 677), False, 'from datetime import datetime\n'), ((2195, 2218), 'numpy.round', 'np.round', (['eval_score', '(3)'], {}), '(eval_score, 3)\n', (2203, 2218), True, 'import numpy as np\n')]
""" Module containing helper routines for routes """ from typing import Dict, Any, Set, List, Tuple import numpy as np from route_distances.utils.type_utils import StrDict def calc_depth(tree_dict: StrDict, depth: int = 0) -> int: """ Calculate the depth of a route, recursively :param tree_dict: the route :param depth: the current depth, don't specify for route """ children = tree_dict.get("children", []) if children: return max(calc_depth(child, depth + 1) for child in children) return depth def calc_llr(tree_dict: StrDict) -> int: """ Calculate the longest linear route for a synthetic route :param tree_dict: the route """ return calc_depth(tree_dict) // 2 def extract_leaves( tree_dict: StrDict, ) -> Set[str]: """ Extract a set with the SMILES of all the leaf nodes, i.e. starting material :param tree_dict: the route :return: a set of SMILE strings """ def traverse(tree_dict: StrDict, leaves: Set[str]) -> None: children = tree_dict.get("children", []) if children: for child in children: traverse(child, leaves) else: leaves.add(tree_dict["smiles"]) leaves = set() traverse(tree_dict, leaves) return leaves def is_solved(route: StrDict) -> bool: """ Find if a route is solved, i.e. if all starting material is in stock. To be accurate, each molecule node need to have an extra boolean property called `in_stock`. :param route: the route to analyze """ def find_leaves_not_in_stock(tree_dict: StrDict) -> None: children = tree_dict.get("children", []) if not children and not tree_dict.get("in_stock", True): raise ValueError(f"child not in stock {tree_dict}") elif children: for child in children: find_leaves_not_in_stock(child) try: find_leaves_not_in_stock(route) except ValueError: return False return True def route_score( tree_dict: StrDict, mol_costs: Dict[bool, float] = None, average_yield=0.8, reaction_cost=1.0, ) -> float: """ Calculate the score of route using the method from (Badowski et al. Chem Sci. 2019, 10, 4640). The reaction cost is constant and the yield is an average yield. The starting materials are assigned a cost based on whether they are in stock or not. By default starting material in stock is assigned a cost of 1 and starting material not in stock is assigned a cost of 10. To be accurate, each molecule node need to have an extra boolean property called `in_stock`. :param tree_dict: the route to analyze :param mol_costs: the starting material cost :param average_yield: the average yield, defaults to 0.8 :param reaction_cost: the reaction cost, defaults to 1.0 :return: the computed cost """ mol_cost = mol_costs or {True: 1, False: 10} reactions = tree_dict.get("children", []) if not reactions: return mol_cost[tree_dict.get("in_stock", True)] child_sum = sum( 1 / average_yield * route_score(child) for child in reactions[0]["children"] ) return reaction_cost + child_sum def route_scorer(routes: List[StrDict]) -> Tuple[List[StrDict], List[float]]: """ Scores and sort a list of routes. Returns a tuple of the sorted routes and their costs. :param routes: the routes to score :return: the sorted routes and their costs """ scores = np.asarray([route_score(route) for route in routes]) sorted_idx = np.argsort(scores) routes = [routes[idx] for idx in sorted_idx] return routes, scores[sorted_idx].tolist() def route_ranks(scores: List[float]) -> List[int]: """ Compute the rank of route scores. Rank starts at 1 :param scores: the route scores :return: a list of ranks for each route """ ranks = [1] for idx in range(1, len(scores)): if abs(scores[idx] - scores[idx - 1]) < 1e-8: ranks.append(ranks[idx - 1]) else: ranks.append(ranks[idx - 1] + 1) return ranks
[ "numpy.argsort" ]
[((3623, 3641), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (3633, 3641), True, 'import numpy as np\n')]
import os import dgl import time import argparse import numpy as np import torch as th import distutils.util import torch.nn.functional as F import utils import models import data_loader os.environ["CUDA_VISIBLE_DEVICES"] = '0' dev = th.device('cuda' if th.cuda.is_available() else 'cpu') if __name__ == '__main__': argparser = argparse.ArgumentParser("training") argparser.add_argument('--adj-path', type=str, default='../data/adj_matrix_formal_stage.pkl') argparser.add_argument('--feat-path', type=str, default='../data/feature_formal_stage.npy') argparser.add_argument('--label-path', type=str, default='../data/train_labels_formal_stage.npy') argparser.add_argument('--output-dir', type=str, default='./saved_models/') argparser.add_argument('--output-name', type=str, default='tagcn_128_3.pkl') argparser.add_argument('--if-load-model', type=lambda x: bool(distutils.util.strtobool(x)), default=False) argparser.add_argument('--model-dir', type=str, default='./saved_models/') argparser.add_argument('--model-name', type=str, default='tagcn_128_3.pkl') argparser.add_argument('--num-epochs', type=int, default=5000) argparser.add_argument('--num-hidden', type=int, default=128) argparser.add_argument('--num-layers', type=int, default=3) argparser.add_argument('--lr', type=float, default=0.001) argparser.add_argument('--dropout', type=float, default=0.1) argparser.add_argument('--adj-norm', type=lambda x: bool(distutils.util.strtobool(x)), default=True) argparser.add_argument('--feat-norm', type=str, default=None) args = argparser.parse_args() print(vars(args)) dataset = data_loader.KddDataset(args.adj_path, args.feat_path, args.label_path, indices) adj = dataset.adj features = dataset.features labels = dataset.labels train_mask = dataset.train_mask val_mask = dataset.val_mask test_mask = dataset.test_mask size_raw = features.shape[0] size_reduced = size_raw - 50000 graph = dgl.DGLGraph() if args.adj_norm: adj = utils.adj_preprocess(adj) feat_norm_func = utils.feat_norm(args.feat_norm) graph.from_scipy_sparse_matrix(adj) features = th.FloatTensor(features).to(dev) features[th.where(features < -1.0)[0]] = 0 features[th.where(features > 1.0)[0]] = 0 features = feat_norm_func(features) labels = th.LongTensor(labels).to(dev) graph.ndata['features'] = features model = models.TAGCN(100, args.num_hidden, 20, args.num_layers, activation=F.leaky_relu, dropout=args.dropout) if args.if_load_model: model_states = th.load(os.path.join(args.model_dir, args.model_name), map_location=dev) model.load_state_dict(model_states) model = model.to(dev) optimizer = th.optim.Adam(model.parameters(), lr=args.lr) dur = [] for epoch in range(args.num_epochs): t0 = time.time() logits = model(graph, features).to(dev) logp = F.log_softmax(logits, 1)[:size_reduced] loss = F.nll_loss(logp[train_mask], labels[train_mask]).to(dev) optimizer.zero_grad() loss.backward() optimizer.step() dur.append(time.time() - t0) if epoch % 10 == 0: train_acc = utils.compute_acc(logp, labels, train_mask) val_acc = utils.compute_acc(logp, labels, val_mask) print('Epoch {:05d} | Loss {:.4f} | Train Acc {:.4f} | Val Acc {:.4f} ' '| Time(s) {:.4f} | GPU {:.1f} MiB'.format( epoch, loss, train_acc, val_acc, np.mean(dur), th.cuda.max_memory_allocated() / 1000000)) th.save(model.state_dict(), os.path.join(args.output_dir, args.output_name))
[ "utils.feat_norm", "numpy.mean", "utils.compute_acc", "argparse.ArgumentParser", "torch.nn.functional.nll_loss", "torch.LongTensor", "os.path.join", "torch.FloatTensor", "data_loader.KddDataset", "utils.adj_preprocess", "torch.cuda.is_available", "dgl.DGLGraph", "torch.nn.functional.log_softmax", "torch.cuda.max_memory_allocated", "time.time", "models.TAGCN", "torch.where" ]
[((336, 371), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""training"""'], {}), "('training')\n", (359, 371), False, 'import argparse\n'), ((1666, 1745), 'data_loader.KddDataset', 'data_loader.KddDataset', (['args.adj_path', 'args.feat_path', 'args.label_path', 'indices'], {}), '(args.adj_path, args.feat_path, args.label_path, indices)\n', (1688, 1745), False, 'import data_loader\n'), ((2012, 2026), 'dgl.DGLGraph', 'dgl.DGLGraph', ([], {}), '()\n', (2024, 2026), False, 'import dgl\n'), ((2110, 2141), 'utils.feat_norm', 'utils.feat_norm', (['args.feat_norm'], {}), '(args.feat_norm)\n', (2125, 2141), False, 'import utils\n'), ((2458, 2565), 'models.TAGCN', 'models.TAGCN', (['(100)', 'args.num_hidden', '(20)', 'args.num_layers'], {'activation': 'F.leaky_relu', 'dropout': 'args.dropout'}), '(100, args.num_hidden, 20, args.num_layers, activation=F.\n leaky_relu, dropout=args.dropout)\n', (2470, 2565), False, 'import models\n'), ((256, 278), 'torch.cuda.is_available', 'th.cuda.is_available', ([], {}), '()\n', (276, 278), True, 'import torch as th\n'), ((2063, 2088), 'utils.adj_preprocess', 'utils.adj_preprocess', (['adj'], {}), '(adj)\n', (2083, 2088), False, 'import utils\n'), ((2885, 2896), 'time.time', 'time.time', ([], {}), '()\n', (2894, 2896), False, 'import time\n'), ((3635, 3682), 'os.path.join', 'os.path.join', (['args.output_dir', 'args.output_name'], {}), '(args.output_dir, args.output_name)\n', (3647, 3682), False, 'import os\n'), ((2197, 2221), 'torch.FloatTensor', 'th.FloatTensor', (['features'], {}), '(features)\n', (2211, 2221), True, 'import torch as th\n'), ((2243, 2268), 'torch.where', 'th.where', (['(features < -1.0)'], {}), '(features < -1.0)\n', (2251, 2268), True, 'import torch as th\n'), ((2290, 2314), 'torch.where', 'th.where', (['(features > 1.0)'], {}), '(features > 1.0)\n', (2298, 2314), True, 'import torch as th\n'), ((2376, 2397), 'torch.LongTensor', 'th.LongTensor', (['labels'], {}), '(labels)\n', (2389, 2397), True, 'import torch as th\n'), ((2620, 2665), 'os.path.join', 'os.path.join', (['args.model_dir', 'args.model_name'], {}), '(args.model_dir, args.model_name)\n', (2632, 2665), False, 'import os\n'), ((2960, 2984), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['logits', '(1)'], {}), '(logits, 1)\n', (2973, 2984), True, 'import torch.nn.functional as F\n'), ((3242, 3285), 'utils.compute_acc', 'utils.compute_acc', (['logp', 'labels', 'train_mask'], {}), '(logp, labels, train_mask)\n', (3259, 3285), False, 'import utils\n'), ((3308, 3349), 'utils.compute_acc', 'utils.compute_acc', (['logp', 'labels', 'val_mask'], {}), '(logp, labels, val_mask)\n', (3325, 3349), False, 'import utils\n'), ((3015, 3063), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['logp[train_mask]', 'labels[train_mask]'], {}), '(logp[train_mask], labels[train_mask])\n', (3025, 3063), True, 'import torch.nn.functional as F\n'), ((3171, 3182), 'time.time', 'time.time', ([], {}), '()\n', (3180, 3182), False, 'import time\n'), ((3545, 3557), 'numpy.mean', 'np.mean', (['dur'], {}), '(dur)\n', (3552, 3557), True, 'import numpy as np\n'), ((3559, 3589), 'torch.cuda.max_memory_allocated', 'th.cuda.max_memory_allocated', ([], {}), '()\n', (3587, 3589), True, 'import torch as th\n')]
from bluepy import btle import concurrent from concurrent import futures import threading import multiprocessing import time from time_sync import * import eval_client import dashBoardClient from joblib import dump, load import numpy # to count labels and store in dict import operator # to get most predicted label import json import random # RNG in worst case from sklearn.preprocessing import StandardScaler # to normalise data class UUIDS: SERIAL_COMMS = btle.UUID("0000dfb1-0000-1000-8000-00805f9b34fb") class Delegate(btle.DefaultDelegate): def __init__(self, params): btle.DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data): ultra96_receiving_timestamp = time.time() * 1000 for idx in range(len(beetle_addresses)): if global_delegate_obj[idx] == self: #print("receiving data from %s" % (beetle_addresses[idx])) #print("data: " + data.decode('ISO-8859-1')) if beetle_addresses[idx] == "50:F1:4A:CC:01:C4": # emg beetle data emg_buffer[beetle_addresses[idx] ] += data.decode('ISO-8859-1') if '>' in data.decode('ISO-8859-1'): print("sending emg dataset to dashboard") packet_count_dict[beetle_addresses[idx]] += 1 try: arr = emg_buffer[beetle_addresses[idx]].split(">")[ 0] final_arr = arr.split(",") board_client.send_data_to_DB( beetle_addresses[idx], str(final_arr)) emg_buffer[beetle_addresses[idx]] = "" except Exception as e: print(e) board_client.send_data_to_DB( beetle_addresses[idx], str(["1", "1", "1", "1"])) emg_buffer[beetle_addresses[idx]] = "" else: if incoming_data_flag[beetle_addresses[idx]] is True: if handshake_flag_dict[beetle_addresses[idx]] is True: buffer_dict[beetle_addresses[idx] ] += data.decode('ISO-8859-1') if '>' not in data.decode('ISO-8859-1'): pass else: if 'T' in buffer_dict[beetle_addresses[idx]]: for char in buffer_dict[beetle_addresses[idx]]: if char == 'T': ultra96_receiving_timestamp = time.time() * 1000 continue if char == '>': # end of packet try: timestamp_dict[beetle_addresses[idx]].append( int(datastring_dict[beetle_addresses[idx]])) except Exception: timestamp_dict[beetle_addresses[idx]].append( 0) timestamp_dict[beetle_addresses[idx]].append( ultra96_receiving_timestamp) handshake_flag_dict[beetle_addresses[idx]] = False clocksync_flag_dict[beetle_addresses[idx]] = True # clear serial input buffer to get ready for data packets datastring_dict[beetle_addresses[idx]] = "" buffer_dict[beetle_addresses[idx]] = "" return elif char != '>': if char == '|': # signify start of next timestamp try: timestamp_dict[beetle_addresses[idx]].append( int(datastring_dict[beetle_addresses[idx]])) except Exception: timestamp_dict[beetle_addresses[idx]].append( 0) datastring_dict[beetle_addresses[idx]] = "" else: datastring_dict[beetle_addresses[idx]] += char else: pass else: if '>' in data.decode('ISO-8859-1'): buffer_dict[beetle_addresses[idx] ] += data.decode('ISO-8859-1') #print("storing dance dataset") packet_count_dict[beetle_addresses[idx]] += 1 else: buffer_dict[beetle_addresses[idx] ] += data.decode('ISO-8859-1') # send data to dashboard once every 10 datasets try: if packet_count_dict[beetle_addresses[idx]] % 10 == 0 and '>' in data.decode('ISO-8859-1'): print("sending data to dashboard") first_string = buffer_dict[beetle_addresses[idx]].split("|")[ 0] final_arr = [first_string.split(",")[0], str(int(first_string.split(",")[1])/divide_get_float), str(int(first_string.split(",")[2])/divide_get_float), str(int(first_string.split(",")[ 3])/divide_get_float), str(int(first_string.split(",")[4])/divide_get_float), str(int(first_string.split(",")[5])/divide_get_float), str(int(first_string.split(",")[6])/divide_get_float)] board_client.send_data_to_DB( beetle_addresses[idx], str(final_arr)) except Exception as e: print(e) """ class EMGThread(object): def __init__(self): thread = threading.Thread(target=self.getEMGData, args=(beetle, )) thread.daemon = True # Daemonize thread thread.start() # Start the execution def getEMGData(self, beetle): while True: try: if beetle.waitForNotifications(2): continue except Exception as e: reestablish_connection(beetle) """ def initHandshake(beetle): retries = 0 if beetle.addr != "50:F1:4A:CC:01:C4": ultra96_sending_timestamp = time.time() * 1000 incoming_data_flag[beetle.addr] = True handshake_flag_dict[beetle.addr] = True for characteristic in beetle.getCharacteristics(): if characteristic.uuid == UUIDS.SERIAL_COMMS: ultra96_sending_timestamp = time.time() * 1000 timestamp_dict[beetle.addr].append( ultra96_sending_timestamp) print("Sending 'T' and 'H' and 'Z' packets to %s" % (beetle.addr)) characteristic.write( bytes('T', 'UTF-8'), withResponse=False) characteristic.write( bytes('H', 'UTF-8'), withResponse=False) characteristic.write( bytes('Z', 'UTF-8'), withResponse=False) while True: try: if beetle.waitForNotifications(2): if clocksync_flag_dict[beetle.addr] is True: # function for time calibration try: clock_offset_tmp = calculate_clock_offset(timestamp_dict[beetle.addr]) tmp_value_list = [] if clock_offset_tmp is not None: tmp_value_list.append(clock_offset_tmp) clock_offset_dict[beetle.addr] = tmp_value_list except Exception as e: print(e) timestamp_dict[beetle.addr].clear() print("beetle %s clock offset: %i" % (beetle.addr, clock_offset_dict[beetle.addr][-1])) clocksync_flag_dict[beetle.addr] = False incoming_data_flag[beetle.addr] = False return else: continue else: while True: if retries >= 5: retries = 0 break print( "Failed to receive timestamp, sending 'Z', 'T', 'H', and 'R' packet to %s" % (beetle.addr)) characteristic.write( bytes('R', 'UTF-8'), withResponse=False) characteristic.write( bytes('T', 'UTF-8'), withResponse=False) characteristic.write( bytes('H', 'UTF-8'), withResponse=False) characteristic.write( bytes('Z', 'UTF-8'), withResponse=False) retries += 1 except Exception as e: reestablish_connection(beetle) def establish_connection(address): while True: try: for idx in range(len(beetle_addresses)): # for initial connections or when any beetle is disconnected if beetle_addresses[idx] == address: if global_beetle[idx] != 0: # do not reconnect if already connected return else: print("connecting with %s" % (address)) beetle = btle.Peripheral(address) global_beetle[idx] = beetle beetle_delegate = Delegate(address) global_delegate_obj[idx] = beetle_delegate beetle.withDelegate(beetle_delegate) if address != "50:F1:4A:CC:01:C4": initHandshake(beetle) print("Connected to %s" % (address)) return except Exception as e: print(e) for idx in range(len(beetle_addresses)): # for initial connections or when any beetle is disconnected if beetle_addresses[idx] == address: if global_beetle[idx] != 0: # do not reconnect if already connected return time.sleep(3) def reestablish_connection(beetle): while True: try: print("reconnecting to %s" % (beetle.addr)) beetle.connect(beetle.addr) print("re-connected to %s" % (beetle.addr)) return except: time.sleep(1) continue def getDanceData(beetle): if beetle.addr != "50:F1:4A:CC:01:C4": timeout_count = 0 retries = 0 incoming_data_flag[beetle.addr] = True for characteristic in beetle.getCharacteristics(): if characteristic.uuid == UUIDS.SERIAL_COMMS: while True: if retries >= 10: retries = 0 break print( "sending 'A' to beetle %s to collect dancing data", (beetle.addr)) characteristic.write( bytes('A', 'UTF-8'), withResponse=False) retries += 1 while True: try: if beetle.waitForNotifications(2): #print("getting data...") # print(packet_count_dict[beetle.addr]) # if number of datasets received from all beetles exceed expectation if packet_count_dict[beetle.addr] >= num_datasets: print("sufficient datasets received from %s. Processing data now" % ( beetle.addr)) # reset for next dance move packet_count_dict[beetle.addr] = 0 incoming_data_flag[beetle.addr] = False while True: if retries >= 10: break characteristic.write( bytes('Z', 'UTF-8'), withResponse=False) retries += 1 return continue # beetle finish transmitting, but got packet losses elif (packet_count_dict[beetle.addr] < num_datasets) and (packet_count_dict[beetle.addr] >= 1): print(packet_count_dict[beetle.addr]) print("sufficient datasets received from %s with packet losses. Processing data now" % ( beetle.addr)) # reset for next dance move packet_count_dict[beetle.addr] = 0 incoming_data_flag[beetle.addr] = False while True: if retries >= 10: break characteristic.write( bytes('Z', 'UTF-8'), withResponse=False) retries += 1 return elif timeout_count >= 3: incoming_data_flag[beetle.addr] = False packet_count_dict[beetle.addr] = 0 timeout_count = 0 return else: # beetle did not start transmitting despite ultra96 sending 'A' previously timeout_count += 1 packet_count_dict[beetle.addr] = 0 retries = 0 while True: if retries >= 10: retries = 0 break print( "Failed to receive data, resending 'A' and 'B' packet to %s" % (beetle.addr)) characteristic.write( bytes('A', 'UTF-8'), withResponse=False) characteristic.write( bytes('B', 'UTF-8'), withResponse=False) retries += 1 except Exception as e: reestablish_connection(beetle) def getEMGData(beetle): retries = 0 for characteristic in beetle.getCharacteristics(): if characteristic.uuid == UUIDS.SERIAL_COMMS: while True: if retries >= 5: retries = 0 break print( "sending 'E' to beetle %s to collect emg data", (beetle.addr)) characteristic.write( bytes('E', 'UTF-8'), withResponse=False) retries += 1 while True: try: if beetle.waitForNotifications(2): if packet_count_dict[beetle.addr] >= 1: packet_count_dict[beetle.addr] = 0 retries = 0 while True: if retries >= 8: break characteristic.write( bytes('X', 'UTF-8'), withResponse=False) retries += 1 return continue else: print("failed to collect emg data, resending 'E'") characteristic.write( bytes('E', 'UTF-8'), withResponse=False) except Exception as e: reestablish_connection(beetle) def processData(address): if address != "50:F1:4A:CC:01:C4": data_dict = {address: {}} def deserialize(buffer_dict, result_dict, address): for char in buffer_dict[address]: # start of new dataset if char == 'D' or end_flag[address] is True: # 2nd part of dataset lost or '>' lost in transmission if start_flag[address] is True: try: # if only '>' lost in transmission, can keep dataset. Else delete if checksum_dict[address] != int(datastring_dict[address]): del result_dict[address][dataset_count_dict[address]] except Exception: # 2nd part of dataset lost try: del result_dict[address][dataset_count_dict[address]] except Exception: pass # reset datastring to prepare for next dataset datastring_dict[address] = "" # reset checksum to prepare for next dataset checksum_dict[address] = 0 comma_count_dict[address] = 0 dataset_count_dict[address] += 1 timestamp_flag_dict[address] = True checksum_dict[address] ^= ord(char) start_flag[address] = True end_flag[address] = False if char != 'D' and char != ',' and char != '|' and char != '>' and (char == '-' or char == '.' or float_flag_dict[address] is True or timestamp_flag_dict[address] is True): datastring_dict[address] += char checksum_dict[address] ^= ord(char) elif char == ' ': datastring_dict[address] += char checksum_dict[address] ^= ord(char) elif char == ',': # next value comma_count_dict[address] += 1 checksum_dict[address] ^= ord(char) # already past timestamp value if comma_count_dict[address] == 1: timestamp_flag_dict[address] = False try: result_dict[address].setdefault( dataset_count_dict[address], []).append(int(datastring_dict[address])) except Exception: try: del result_dict[address][dataset_count_dict[address]] except Exception: pass float_flag_dict[address] = True elif comma_count_dict[address] < 5: # yaw, pitch, roll floats try: result_dict[address][dataset_count_dict[address]].append( float("{0:.2f}".format((int(datastring_dict[address]) / divide_get_float)))) except Exception: try: del result_dict[address][dataset_count_dict[address]] except Exception: pass else: # accelerometer integers try: result_dict[address][dataset_count_dict[address]].append( int(int(datastring_dict[address]) / divide_get_float)) except Exception: try: del result_dict[address][dataset_count_dict[address]] except Exception: pass datastring_dict[address] = "" elif char == '>': # end of current dataset # print("ultra96 checksum: %i" % (checksum_dict[address])) # print("beetle checksum: %i" % (int(datastring_dict[address]))) # received dataset is invalid; drop the dataset from data dictionary try: if checksum_dict[address] != int(datastring_dict[address]): del result_dict[address][dataset_count_dict[address]] except Exception: try: del result_dict[address][dataset_count_dict[address]] except Exception: pass # reset datastring to prepare for next dataset datastring_dict[address] = "" # reset checksum to prepare for next dataset checksum_dict[address] = 0 comma_count_dict[address] = 0 start_flag[address] = False end_flag[address] = True # missing data in previous dataset try: if len(result_dict[address][list(result_dict[address].keys())[-1]]) < 7: del result_dict[address][list( result_dict[address].keys())[-1]] except Exception as e: print(e) print("error in processData in line 379") elif char == '|' or (float_flag_dict[address] is False and timestamp_flag_dict[address] is False): if float_flag_dict[address] is True: try: result_dict[address][dataset_count_dict[address]].append( int(int(datastring_dict[address]) / divide_get_float)) except Exception: try: del result_dict[address][dataset_count_dict[address]] except Exception: pass # clear datastring to prepare take in checksum from beetle datastring_dict[address] = "" float_flag_dict[address] = False elif char != '|' and char != '>': datastring_dict[address] += char try: if len(result_dict[address][list(result_dict[address].keys())[-1]]) < 7: del result_dict[address][list( result_dict[address].keys())[-1]] except Exception as e: print(e) print("error in processData in line 478") for character in "\r\n": buffer_dict[address] = buffer_dict[address].replace(character, "") deserialize(buffer_dict, data_dict, address) dataset_count_dict[address] = 0 return data_dict def parse_data(dic_data, beetle): # collect hand data data = [] for v in dic_data[beetle].values(): ypr = [] # yaw, pitch, roll for i in range(1, 7): ypr.append(v[i]) data.append(ypr) return (data) def predict_beetle(beetle_data, model): pred_arr = model.predict(beetle_data) unique, counts = numpy.unique(pred_arr, return_counts=True) pred_count = dict(zip(unique, counts)) prediction = max(pred_count.items(), key=operator.itemgetter(1))[0] return prediction # Program to find most frequent element in a list def most_frequent_prediction(pred_list): return max(set(pred_list), key=pred_list.count) def find_new_position(ground_truth, b1_move, b2_move, b3_move): # ground_truth = [3, 2, 1] # p1_movement = 'R' # p2_movement = 'S' # p3_movement = 'L' dic = {1: b1_move, 2: b2_move, 3: b3_move} p1_movement = dic[ground_truth[0]] p2_movement = dic[ground_truth[1]] p3_movement = dic[ground_truth[2]] if p1_movement == "R" and p2_movement == "S" and p3_movement == "L": # output = [3, 2, 1] output = [ground_truth[2], ground_truth[1], ground_truth[0]] elif p1_movement == "R" and p2_movement == "L" and p3_movement == "S": # output = [2, 1, 3] output = [ground_truth[1], ground_truth[0], ground_truth[2]] elif p1_movement == "R" and p2_movement == "L" and p3_movement == "L": # output = [2, 3, 1] output = [ground_truth[1], ground_truth[2], ground_truth[0]] elif p1_movement == "S" and p2_movement == "R" and p3_movement == "L": # output = [1, 3, 2] output = [ground_truth[0], ground_truth[2], ground_truth[1]] elif p1_movement == "S" and p2_movement == "L" and p3_movement == "S": # output = [2, 1, 3] output = [ground_truth[1], ground_truth[0], ground_truth[2]] else: # output = [1, 2, 3] output = ground_truth position = str(output[0]) + " " + str(output[1]) + " " + str(output[2]) return position def eval_1beetle(beetle_dict_1, beetle_1): # Get beetle data from dictionaries beetle1_data = parse_data(beetle_dict_1, beetle_1) # Predict dance move of each beetle #beetle1_dance = predict_beetle(beetle1_data, mlp_dance) pred_arr = mlp_dance.predict(beetle1_data) unique, counts = numpy.unique(pred_arr, return_counts=True) pred_count = dict(zip(unique, counts)) beetle1_dance = max(pred_count.items(), key=operator.itemgetter(1))[0] return beetle1_dance def normalise_data(data): try: scaler = StandardScaler() scaler.fit(data) data = scaler.transform(data) return data except Exception as e: return data if __name__ == '__main__': # 50:F1:4A:CB:FE:EE: position 1, 1C:BA:8C:1D:30:22: position 2, 78:DB:2F:BF:2C:E2: position 3 start_time = time.time() # global variables """ beetle_addresses = ["50:F1:4A:CC:01:C4", "50:F1:4A:CB:FE:EE", "78:DB:2F:BF:2C:E2", "1C:BA:8C:1D:30:22"] """ beetle_addresses = ["50:F1:4A:CC:01:C4", "50:F1:4A:CB:FE:EE", "78:DB:2F:BF:2C:E2", "1C:BA:8C:1D:30:22"] divide_get_float = 100.0 global_delegate_obj = [] global_beetle = [] handshake_flag_dict = {"50:F1:4A:CB:FE:EE": True, "78:DB:2F:BF:2C:E2": True, "1C:BA:8C:1D:30:22": True} emg_buffer = {"50:F1:4A:CC:01:C4": ""} buffer_dict = {"50:F1:4A:CB:FE:EE": "", "78:DB:2F:BF:2C:E2": "", "1C:BA:8C:1D:30:22": ""} incoming_data_flag = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} ground_truth = [1, 2, 3] ACTIONS = ['muscle', 'weightlifting', 'shoutout'] POSITIONS = ['1 2 3', '3 2 1', '2 3 1', '3 1 2', '1 3 2', '2 1 3'] beetle1 = "50:F1:4A:CB:FE:EE" beetle2 = "78:DB:2F:BF:2C:E2" beetle3 = "1C:BA:8C:1D:30:22" dance = "shoutout" new_pos = "1 2 3" # data global variables num_datasets = 200 beetle1_data_dict = {"50:F1:4A:CB:FE:EE": {}} beetle2_data_dict = {"78:DB:2F:BF:2C:E2": {}} beetle3_data_dict = {"1C:BA:8C:1D:30:22": {}} beetle1_moving_dict = {"50:F1:4A:CB:FE:EE": {}} beetle2_moving_dict = {"78:DB:2F:BF:2C:E2": {}} beetle3_moving_dict = {"1C:BA:8C:1D:30:22": {}} beetle1_dancing_dict = {"50:F1:4A:CB:FE:EE": {}} beetle2_dancing_dict = {"78:DB:2F:BF:2C:E2": {}} beetle3_dancing_dict = {"1C:BA:8C:1D:30:22": {}} datastring_dict = {"50:F1:4A:CB:FE:EE": "", "78:DB:2F:BF:2C:E2": "", "1C:BA:8C:1D:30:22": ""} packet_count_dict = {"50:F1:4A:CC:01:C4": 0, "50:F1:4A:CB:FE:EE": 0, "78:DB:2F:BF:2C:E2": 0, "1C:BA:8C:1D:30:22": 0} dataset_count_dict = {"50:F1:4A:CB:FE:EE": 0, "78:DB:2F:BF:2C:E2": 0, "1C:BA:8C:1D:30:22": 0} float_flag_dict = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} timestamp_flag_dict = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} comma_count_dict = {"50:F1:4A:CB:FE:EE": 0, "78:DB:2F:BF:2C:E2": 0, "1C:BA:8C:1D:30:22": 0} checksum_dict = {"50:F1:4A:CB:FE:EE": 0, "78:DB:2F:BF:2C:E2": 0, "1C:BA:8C:1D:30:22": 0} start_flag = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} end_flag = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} # clock synchronization global variables dance_count = 0 clocksync_flag_dict = {"50:F1:4A:CB:FE:EE": False, "78:DB:2F:BF:2C:E2": False, "1C:BA:8C:1D:30:22": False} timestamp_dict = {"50:F1:4A:CB:FE:EE": [], "78:DB:2F:BF:2C:E2": [], "1C:BA:8C:1D:30:22": []} clock_offset_dict = {"50:F1:4A:CB:FE:EE": [], "78:DB:2F:BF:2C:E2": [], "1C:BA:8C:1D:30:22": []} [global_delegate_obj.append(0) for idx in range(len(beetle_addresses))] [global_beetle.append(0) for idx in range(len(beetle_addresses))] try: eval_client = eval_client.Client("192.168.43.6", 8080, 6, "cg40024002group6") except Exception as e: print(e) try: board_client = dashBoardClient.Client("192.168.43.248", 8080, 6, "cg40024002group6") except Exception as e: print(e) establish_connection("50:F1:4A:CC:01:C4") time.sleep(2) establish_connection("78:DB:2F:BF:2C:E2") time.sleep(3) # Load MLP NN model mlp_dance = load('mlp_dance_LATEST.joblib') establish_connection("50:F1:4A:CB:FE:EE") time.sleep(3) # Load Movement ML mlp_move = load('mlp_movement_LATEST.joblib') establish_connection("1C:BA:8C:1D:30:22") with concurrent.futures.ThreadPoolExecutor(max_workers=7) as data_executor: for beetle in global_beetle: if beetle.addr == "50:F1:4A:CC:01:C4": data_executor.submit(getEMGData, beetle) data_executor.shutdown(wait=True) # start collecting data only after 1 min passed while True: elapsed_time = time.time() - start_time if int(elapsed_time) >= 60: break else: print(elapsed_time) time.sleep(1) """ for beetle in global_beetle: print(beetle.addr) emg_thread = EMGThread(global_beetle[3]) """ while True: with concurrent.futures.ThreadPoolExecutor(max_workers=7) as data_executor: {data_executor.submit(getDanceData, beetle): beetle for beetle in global_beetle} data_executor.shutdown(wait=True) """ with concurrent.futures.ThreadPoolExecutor(max_workers=7) as data_executor: data_executor.submit(getEMGData, global_beetle[0]) data_executor.shutdown(wait=True) """ # do calibration once every 4 moves; change 4 to other values according to time calibration needs if dance_count == 1: print("Proceed to do time calibration...") # clear clock_offset_dict for next time calibration for beetle in global_beetle: if beetle.addr != "50:F1:4A:CC:01:C4": initHandshake(beetle) if dance_count == 1: dance_count = 0 dance_count += 1 pool = multiprocessing.Pool() workers = [pool.apply_async(processData, args=(address, )) for address in beetle_addresses] result = [worker.get() for worker in workers] pool.close() try: # change to 1 if using emg beetle, 0 if not using for idx in range(1, len(result)): for address in result[idx].keys(): if address == "50:F1:4A:CB:FE:EE": beetle1_data_dict[address] = result[idx][address] elif address == "78:DB:2F:BF:2C:E2": beetle2_data_dict[address] = result[idx][address] elif address == "1C:BA:8C:1D:30:22": beetle3_data_dict[address] = result[idx][address] except Exception as e: pass try: for dataset_num, dataset_list in beetle1_data_dict["50:F1:4A:CB:FE:EE"].items(): if dataset_list[0] == 0: # moving data beetle1_moving_dict["50:F1:4A:CB:FE:EE"].update( {dataset_num: dataset_list}) else: # dancing data beetle1_dancing_dict["50:F1:4A:CB:FE:EE"].update( {dataset_num: dataset_list}) except Exception as e: pass try: for dataset_num, dataset_list in beetle2_data_dict["78:DB:2F:BF:2C:E2"].items(): if dataset_list[0] == 0: # moving data beetle2_moving_dict["78:DB:2F:BF:2C:E2"].update( {dataset_num: dataset_list}) else: # dancing data beetle2_dancing_dict["78:DB:2F:BF:2C:E2"].update( {dataset_num: dataset_list}) except Exception as e: pass try: for dataset_num, dataset_list in beetle3_data_dict["1C:BA:8C:1D:30:22"].items(): if dataset_list[0] == 0: # moving data beetle3_moving_dict["1C:BA:8C:1D:30:22"].update( {dataset_num: dataset_list}) else: # dancing data beetle3_dancing_dict["1C:BA:8C:1D:30:22"].update( {dataset_num: dataset_list}) except Exception as e: pass # clear buffer for next move for address in buffer_dict.keys(): buffer_dict[address] = "" # print(beetle1_data_dict) # print(beetle2_data_dict) # print(beetle3_data_dict) with open(r'position.txt', 'a') as file: file.write(json.dumps(beetle1_moving_dict) + "\n") file.write(json.dumps(beetle2_moving_dict) + "\n") file.write(json.dumps(beetle3_moving_dict) + "\n") file.close() with open(r'dance.txt', 'a') as file: file.write(json.dumps(beetle1_dancing_dict) + "\n") file.write(json.dumps(beetle2_dancing_dict) + "\n") file.write(json.dumps(beetle3_dancing_dict) + "\n") file.close() # synchronization delay try: beetle1_time_ultra96 = calculate_ultra96_time( beetle1_dancing_dict, clock_offset_dict["50:F1:4A:CB:FE:EE"][0]) beetle2_time_ultra96 = calculate_ultra96_time( beetle2_dancing_dict, clock_offset_dict["78:DB:2F:BF:2C:E2"][0]) beetle3_time_ultra96 = calculate_ultra96_time( beetle3_dancing_dict, clock_offset_dict["1C:BA:8C:1D:30:22"][0]) sync_delay = calculate_sync_delay(beetle1_time_ultra96, beetle2_time_ultra96, beetle3_time_ultra96) except Exception as e: print(e) print("use default sync delay") sync_delay = 950 # print("Beetle 1 ultra 96 time: ", beetle1_time_ultra96) # print("Beetle 2 ultra 96 time: ", beetle2_time_ultra96) # print("Beetle 3 ultra 96 time: ", beetle3_time_ultra96) print("Synchronization delay is: ", sync_delay) # machine learning # ml_result = get_prediction(beetle1_data_dict) """ """ beetle1_moving_dict = parse_data(beetle1_moving_dict, beetle1) beetle2_moving_dict = parse_data(beetle2_moving_dict, beetle2) beetle3_moving_dict = parse_data(beetle3_moving_dict, beetle3) beetle1_moving_dict = normalise_data(beetle1_moving_dict) beetle2_moving_dict = normalise_data(beetle2_moving_dict) beetle3_moving_dict = normalise_data(beetle3_moving_dict) # Predict movement direction of each beetle try: beetle1_move = predict_beetle(beetle1_moving_dict, mlp_move) except Exception as e: beetle1_move = 'S' try: beetle2_move = predict_beetle(beetle2_moving_dict, mlp_move) except Exception as e: beetle2_move = 'S' try: beetle3_move = predict_beetle(beetle3_moving_dict, mlp_move) except Exception as e: beetle3_move = 'S' # Find new position new_pos = find_new_position( ground_truth, beetle1_move, beetle2_move, beetle3_move) # PREDICT DANCE if beetle1_dancing_dict[beetle1] and beetle2_dancing_dict[beetle2] and beetle3_dancing_dict[beetle3]: # Get DANCE data from dictionaries in arguments beetle1_dance_data = parse_data(beetle1_dancing_dict, beetle1) beetle2_dance_data = parse_data(beetle2_dancing_dict, beetle2) beetle3_dance_data = parse_data(beetle3_dancing_dict, beetle3) # print(beetle1_data) # Normalise DANCE data beetle1_dance_data_norm = normalise_data(beetle1_dance_data) beetle2_dance_data_norm = normalise_data(beetle2_dance_data) beetle3_dance_data_norm = normalise_data(beetle3_dance_data) # print(beetle1_data_norm) # Predict DANCE of each beetle beetle1_dance = predict_beetle(beetle1_dance_data_norm, mlp_dance) beetle2_dance = predict_beetle(beetle2_dance_data_norm, mlp_dance) beetle3_dance = predict_beetle(beetle3_dance_data_norm, mlp_dance) # print(beetle1_dance) dance_predictions = [beetle1_dance, beetle2_dance, beetle3_dance] dance = most_frequent_prediction(dance_predictions) elif beetle2_dancing_dict[beetle2] and beetle3_dancing_dict[beetle3]: dance = eval_1beetle(beetle2_dancing_dict, beetle2) elif beetle1_dancing_dict[beetle1] and beetle3_dancing_dict[beetle3]: dance = eval_1beetle(beetle1_dancing_dict, beetle1) elif beetle1_dancing_dict[beetle1] and beetle2_dancing_dict[beetle2]: dance = eval_1beetle(beetle1_dancing_dict, beetle1) elif beetle1_dancing_dict[beetle1]: dance = eval_1beetle(beetle1_dancing_dict, beetle1) elif beetle2_dancing_dict[beetle2]: dance = eval_1beetle(beetle2_dancing_dict, beetle2) elif beetle3_dancing_dict[beetle3]: dance = eval_1beetle(beetle3_dancing_dict, beetle3) else: # RNG dance = random.choice(ACTIONS) print(dance) print(new_pos) # send data to eval and dashboard server eval_client.send_data(new_pos, dance, str(sync_delay)) ground_truth = eval_client.receive_dancer_position().split(' ') ground_truth = [int(ground_truth[0]), int( ground_truth[1]), int(ground_truth[2])] final_string = dance + " " + new_pos board_client.send_data_to_DB("MLDancer1", final_string) beetle1_moving_dict = {"50:F1:4A:CB:FE:EE": {}} beetle2_moving_dict = {"78:DB:2F:BF:2C:E2": {}} beetle3_moving_dict = {"1C:BA:8C:1D:30:22": {}} beetle1_dancing_dict = {"50:F1:4A:CB:FE:EE": {}} beetle2_dancing_dict = {"78:DB:2F:BF:2C:E2": {}} beetle3_dancing_dict = {"1C:BA:8C:1D:30:22": {}}
[ "random.choice", "numpy.unique", "bluepy.btle.DefaultDelegate.__init__", "concurrent.futures.ThreadPoolExecutor", "bluepy.btle.Peripheral", "dashBoardClient.Client", "json.dumps", "time.sleep", "sklearn.preprocessing.StandardScaler", "multiprocessing.Pool", "joblib.load", "operator.itemgetter", "eval_client.receive_dancer_position", "time.time", "bluepy.btle.UUID", "eval_client.Client" ]
[((469, 518), 'bluepy.btle.UUID', 'btle.UUID', (['"""0000dfb1-0000-1000-8000-00805f9b34fb"""'], {}), "('0000dfb1-0000-1000-8000-00805f9b34fb')\n", (478, 518), False, 'from bluepy import btle\n'), ((25115, 25157), 'numpy.unique', 'numpy.unique', (['pred_arr'], {'return_counts': '(True)'}), '(pred_arr, return_counts=True)\n', (25127, 25157), False, 'import numpy\n'), ((27115, 27157), 'numpy.unique', 'numpy.unique', (['pred_arr'], {'return_counts': '(True)'}), '(pred_arr, return_counts=True)\n', (27127, 27157), False, 'import numpy\n'), ((27648, 27659), 'time.time', 'time.time', ([], {}), '()\n', (27657, 27659), False, 'import time\n'), ((31358, 31371), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (31368, 31371), False, 'import time\n'), ((31423, 31436), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (31433, 31436), False, 'import time\n'), ((31477, 31508), 'joblib.load', 'load', (['"""mlp_dance_LATEST.joblib"""'], {}), "('mlp_dance_LATEST.joblib')\n", (31481, 31508), False, 'from joblib import dump, load\n'), ((31560, 31573), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (31570, 31573), False, 'import time\n'), ((31613, 31647), 'joblib.load', 'load', (['"""mlp_movement_LATEST.joblib"""'], {}), "('mlp_movement_LATEST.joblib')\n", (31617, 31647), False, 'from joblib import dump, load\n'), ((600, 635), 'bluepy.btle.DefaultDelegate.__init__', 'btle.DefaultDelegate.__init__', (['self'], {}), '(self)\n', (629, 635), False, 'from bluepy import btle\n'), ((27356, 27372), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (27370, 27372), False, 'from sklearn.preprocessing import StandardScaler\n'), ((31043, 31106), 'eval_client.Client', 'eval_client.Client', (['"""192.168.43.6"""', '(8080)', '(6)', '"""cg40024002group6"""'], {}), "('192.168.43.6', 8080, 6, 'cg40024002group6')\n", (31061, 31106), False, 'import eval_client\n'), ((31189, 31258), 'dashBoardClient.Client', 'dashBoardClient.Client', (['"""192.168.43.248"""', '(8080)', '(6)', '"""cg40024002group6"""'], {}), "('192.168.43.248', 8080, 6, 'cg40024002group6')\n", (31211, 31258), False, 'import dashBoardClient\n'), ((31709, 31761), 'concurrent.futures.ThreadPoolExecutor', 'concurrent.futures.ThreadPoolExecutor', ([], {'max_workers': '(7)'}), '(max_workers=7)\n', (31746, 31761), False, 'import concurrent\n'), ((33307, 33329), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (33327, 33329), False, 'import multiprocessing\n'), ((724, 735), 'time.time', 'time.time', ([], {}), '()\n', (733, 735), False, 'import time\n'), ((7564, 7575), 'time.time', 'time.time', ([], {}), '()\n', (7573, 7575), False, 'import time\n'), ((32071, 32082), 'time.time', 'time.time', ([], {}), '()\n', (32080, 32082), False, 'import time\n'), ((32208, 32221), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (32218, 32221), False, 'import time\n'), ((32373, 32425), 'concurrent.futures.ThreadPoolExecutor', 'concurrent.futures.ThreadPoolExecutor', ([], {'max_workers': '(7)'}), '(max_workers=7)\n', (32410, 32425), False, 'import concurrent\n'), ((11998, 12011), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (12008, 12011), False, 'import time\n'), ((12278, 12291), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (12288, 12291), False, 'import time\n'), ((25246, 25268), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (25265, 25268), False, 'import operator\n'), ((27249, 27271), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (27268, 27271), False, 'import operator\n'), ((40711, 40748), 'eval_client.receive_dancer_position', 'eval_client.receive_dancer_position', ([], {}), '()\n', (40746, 40748), False, 'import eval_client\n'), ((7839, 7850), 'time.time', 'time.time', ([], {}), '()\n', (7848, 7850), False, 'import time\n'), ((35911, 35942), 'json.dumps', 'json.dumps', (['beetle1_moving_dict'], {}), '(beetle1_moving_dict)\n', (35921, 35942), False, 'import json\n'), ((35974, 36005), 'json.dumps', 'json.dumps', (['beetle2_moving_dict'], {}), '(beetle2_moving_dict)\n', (35984, 36005), False, 'import json\n'), ((36037, 36068), 'json.dumps', 'json.dumps', (['beetle3_moving_dict'], {}), '(beetle3_moving_dict)\n', (36047, 36068), False, 'import json\n'), ((36171, 36203), 'json.dumps', 'json.dumps', (['beetle1_dancing_dict'], {}), '(beetle1_dancing_dict)\n', (36181, 36203), False, 'import json\n'), ((36235, 36267), 'json.dumps', 'json.dumps', (['beetle2_dancing_dict'], {}), '(beetle2_dancing_dict)\n', (36245, 36267), False, 'import json\n'), ((36299, 36331), 'json.dumps', 'json.dumps', (['beetle3_dancing_dict'], {}), '(beetle3_dancing_dict)\n', (36309, 36331), False, 'import json\n'), ((11165, 11189), 'bluepy.btle.Peripheral', 'btle.Peripheral', (['address'], {}), '(address)\n', (11180, 11189), False, 'from bluepy import btle\n'), ((40508, 40530), 'random.choice', 'random.choice', (['ACTIONS'], {}), '(ACTIONS)\n', (40521, 40530), False, 'import random\n'), ((2846, 2857), 'time.time', 'time.time', ([], {}), '()\n', (2855, 2857), False, 'import time\n')]
from .modules.common import * import numpy as np import os from .modules.rs_structs import getRSformat class RockstarFile(object): def __init__(self,binfile,data,galaxies,debug): self.galaxies = galaxies self.binfile = binfile self.debug = debug self.header() self.halos() if data == 'particles': self.particles() self.f.close() def header(self): f = open(self.binfile,'rb') f.seek(8*3 + 4*10,1) self.num_halos = np.fromfile(f,dtype=np.int64,count=1)[0] self.num_particles = np.fromfile(f,dtype=np.int64,count=1)[0] #print self.num_halos f.seek(4 + 4 + 8,1) self.format_revision = np.fromfile(f,dtype=np.int32,count=1)[0] if self.debug: print('found HALO_FORMAT_REVISION %d (header)' % self.format_revision) bytes_left = 256 - f.tell() f.seek(bytes_left,1) self.f = f self.halostruct = getRSformat(self) def halos(self): #print 'reading %d halos (%d)' % (self.num_halos,self.galaxies) self.halodata = np.fromfile(self.f,dtype=self.halostruct,count=self.num_halos) def particles(self): self.particle_IDs = np.zeros(self.num_particles,dtype=np.int64) self.particle_IDs.fill(-1) self.particle_haloIDs = np.zeros(self.num_particles,dtype=np.int64) self.particle_haloIDs.fill(-1) nparts = 0 for i in range(0,self.num_halos): hid = self.halodata[i]['id'] num_p = self.halodata[i]['num_p'] #print '%d %d' % (i,num_p) pids = np.fromfile(self.f,dtype=np.int64,count=num_p) self.particle_IDs[nparts:nparts+num_p] = pids self.particle_haloIDs[nparts:nparts+num_p] = hid nparts += num_p #print 'complete' def compileReturnArray(RS,data): """compile data from RS binary and return requested value""" arr = [] singleval = False ## return particle ID data if data == 'particles': npart = 0 for i in range(0,len(RS)): npart += len(RS[i].particle_IDs) arr = np.zeros((npart,2),dtype=np.int64) npart = 0 for i in range(0,len(RS)): n = len(RS[i].particle_IDs) arr[npart:npart+n,0] = RS[i].particle_IDs arr[npart:npart+n,1] = RS[i].particle_haloIDs npart += n return arr ## return halo struct data if data in RS[0].halostruct.names: singleval = True if RS[0].debug: print('%s found in halodata' % data) nhalos = 0 for i in range(0,len(RS)): nhalos += RS[i].num_halos if singleval: arr.extend(RS[i].halodata[data]) else: arr.extend(RS[i].halodata) #print nhalos,len(arr) return np.asarray(arr) def readrockstargalaxies(binfile,data,**kwargs): if 'galaxies' in kwargs: del kwargs['galaxies'] arr = readrockstar(binfile,data,galaxies=1,**kwargs) return arr def readrockstar(binfile,data,**kwargs): """read rockstar binary file Parameters ---------- binfile : string path to rockstar binary file. Do NOT include file extention or leading number data : string requested data, see readme for details Examples -------- >>> halo_mass = readrockstar('/Users/bob/halos_020','m') >>> halo_mass array([ 7.25643648e+08, 5.70148608e+08, 3.97376288e+08, 3.66277274e+09, 1.99379231e+10, 5.01039648e+08, ..., 1.58950515e+09, 2.10782208e+09, 8.41401088e+09, 4.14653504e+08], dtype=float32) """ galaxies = 0 if 'galaxies' in kwargs and kwargs['galaxies']==1: galaxies = 1 debug = 0 if 'debug' in kwargs and kwargs['debug']==1: debug = 1 RS_DATA = [] for j in range(0,5000): b = '%s.%d.bin' % (binfile,j) if os.path.isfile(b): if debug: print('reading %s' % b) RS_DATA.append(RockstarFile(b,data,galaxies,debug)) else: break arr = compileReturnArray(RS_DATA,data) return arr
[ "os.path.isfile", "numpy.fromfile", "numpy.asarray", "numpy.zeros" ]
[((2883, 2898), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (2893, 2898), True, 'import numpy as np\n'), ((1123, 1187), 'numpy.fromfile', 'np.fromfile', (['self.f'], {'dtype': 'self.halostruct', 'count': 'self.num_halos'}), '(self.f, dtype=self.halostruct, count=self.num_halos)\n', (1134, 1187), True, 'import numpy as np\n'), ((1252, 1296), 'numpy.zeros', 'np.zeros', (['self.num_particles'], {'dtype': 'np.int64'}), '(self.num_particles, dtype=np.int64)\n', (1260, 1296), True, 'import numpy as np\n'), ((1364, 1408), 'numpy.zeros', 'np.zeros', (['self.num_particles'], {'dtype': 'np.int64'}), '(self.num_particles, dtype=np.int64)\n', (1372, 1408), True, 'import numpy as np\n'), ((2203, 2239), 'numpy.zeros', 'np.zeros', (['(npart, 2)'], {'dtype': 'np.int64'}), '((npart, 2), dtype=np.int64)\n', (2211, 2239), True, 'import numpy as np\n'), ((3983, 4000), 'os.path.isfile', 'os.path.isfile', (['b'], {}), '(b)\n', (3997, 4000), False, 'import os\n'), ((537, 576), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.int64', 'count': '(1)'}), '(f, dtype=np.int64, count=1)\n', (548, 576), True, 'import numpy as np\n'), ((607, 646), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.int64', 'count': '(1)'}), '(f, dtype=np.int64, count=1)\n', (618, 646), True, 'import numpy as np\n'), ((737, 776), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.int32', 'count': '(1)'}), '(f, dtype=np.int32, count=1)\n', (748, 776), True, 'import numpy as np\n'), ((1657, 1705), 'numpy.fromfile', 'np.fromfile', (['self.f'], {'dtype': 'np.int64', 'count': 'num_p'}), '(self.f, dtype=np.int64, count=num_p)\n', (1668, 1705), True, 'import numpy as np\n')]
#! -*- coding:utf-8 from typing import Callable, List, Optional import numpy as np import torch import torchvision __all__ = ["CIFAR10", "FashionMNIST"] class CIFAR10(torch.utils.data.Dataset): def __init__(self, root: str, train: bool = True, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, download: bool = False, indices: List[int] = None, data_length: int = None, shuffle: bool = False): super(CIFAR10, self).__init__() self.__datas__ = [] self.__labels__ = [] dataset = torchvision.datasets.CIFAR10(root, train=train, transform=transform, target_transform=target_transform, download=download) self.__classes__ = dataset.classes if indices is None: indices = list(range(len(dataset))) for i in indices: # load data and catching... d, l = dataset[i] self.__datas__.append(d) self.__labels__.append(l) self.__length__ = (len(self.data) if data_length is None else data_length) self.__indices__ = np.arange(len(self.data)) self.__shuffle__ = shuffle if self.shuffle: np.random.shuffle(self.__indices__) self.__call_count__ = 0 @property def data(self): return self.__datas__ @property def label(self): return self.__labels__ @property def classes(self): return self.__classes__ @property def indices(self): return self.__indices__ @property def shuffle(self): return self.__shuffle__ def __len__(self): return self.__length__ def __getitem__(self, idx): idx = self.indices[idx % len(self.data)] d = self.data[idx] l = self.label[idx] self.__call_count__ += 1 if self.shuffle and self.__call_count__ >= len(self): np.random.shuffle(self.__indices__) self.__call_count__ = 0 return d, l class FashionMNIST(torch.utils.data.Dataset): def __init__(self, root: str, train: bool = True, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, download: bool = False, indices: List[int] = None, data_length: int = None, shuffle: bool = False): super(FashionMNIST, self).__init__() self.__datas__ = [] self.__labels__ = [] dataset = torchvision.datasets.FashionMNIST(root, train=train, transform=transform, target_transform=target_transform, download=download) self.__classes__ = dataset.classes if indices is None: indices = list(range(len(dataset))) for i in indices: # load data and catching... d, l = dataset[i] self.__datas__.append(d) self.__labels__.append(l) self.__length__ = (len(self.data) if data_length is None else data_length) self.__indices__ = np.arange(len(self.data)) self.__shuffle__ = shuffle if self.shuffle: np.random.shuffle(self.__indices__) self.__call_count__ = 0 @property def data(self): return self.__datas__ @property def label(self): return self.__labels__ @property def classes(self): return self.__classes__ @property def indices(self): return self.__indices__ @property def shuffle(self): return self.__shuffle__ def __len__(self): return self.__length__ def __getitem__(self, idx): idx = self.indices[idx % len(self.data)] d = self.data[idx] l = self.label[idx] self.__call_count__ += 1 if self.shuffle and self.__call_count__ >= len(self): np.random.shuffle(self.__indices__) self.__call_count__ = 0 return d, l
[ "numpy.random.shuffle", "torchvision.datasets.FashionMNIST", "torchvision.datasets.CIFAR10" ]
[((709, 835), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', (['root'], {'train': 'train', 'transform': 'transform', 'target_transform': 'target_transform', 'download': 'download'}), '(root, train=train, transform=transform,\n target_transform=target_transform, download=download)\n', (737, 835), False, 'import torchvision\n'), ((2883, 3014), 'torchvision.datasets.FashionMNIST', 'torchvision.datasets.FashionMNIST', (['root'], {'train': 'train', 'transform': 'transform', 'target_transform': 'target_transform', 'download': 'download'}), '(root, train=train, transform=transform,\n target_transform=target_transform, download=download)\n', (2916, 3014), False, 'import torchvision\n'), ((1553, 1588), 'numpy.random.shuffle', 'np.random.shuffle', (['self.__indices__'], {}), '(self.__indices__)\n', (1570, 1588), True, 'import numpy as np\n'), ((2230, 2265), 'numpy.random.shuffle', 'np.random.shuffle', (['self.__indices__'], {}), '(self.__indices__)\n', (2247, 2265), True, 'import numpy as np\n'), ((3752, 3787), 'numpy.random.shuffle', 'np.random.shuffle', (['self.__indices__'], {}), '(self.__indices__)\n', (3769, 3787), True, 'import numpy as np\n'), ((4429, 4464), 'numpy.random.shuffle', 'np.random.shuffle', (['self.__indices__'], {}), '(self.__indices__)\n', (4446, 4464), True, 'import numpy as np\n')]
from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog import torch import numpy as np import cv2 class Model: def __init__(self,confidence_thresh=0.6): cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")) cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confidence_thresh # set threshold for this model cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml") self.model = DefaultPredictor(cfg) def get_seg_output(self,image:np.array): out = self.model(image)['instances'] outputs = [(out.pred_masks[i],out.pred_classes[i]) for i in range(len(out.pred_classes)) if out.pred_classes[i]==0] return outputs class Preprocessing: def __init__(self,kernel,dilate_iter=5,erode_iter=1): self.kernel = kernel self.dilate_iter = dilate_iter self.erode_iter = erode_iter def get_target_mask(self,masks): out = np.zeros(masks[0].shape) for mask in masks: out += mask out = np.clip(out,0,1) return out def get_trimap(self,masks): target_mask = self.get_target_mask(masks) erode = cv2.erode(target_mask.astype('uint8'),self.kernel,iterations=self.erode_iter) dilate = cv2.dilate(target_mask.astype('uint8'),self.kernel,iterations=self.dilate_iter) h, w = target_mask.shape trimap = np.zeros((h, w, 2)) trimap[erode == 1, 1] = 1 trimap[dilate == 0, 0] = 1 return trimap
[ "numpy.clip", "detectron2.config.get_cfg", "detectron2.model_zoo.get_checkpoint_url", "numpy.zeros", "detectron2.model_zoo.get_config_file", "detectron2.engine.DefaultPredictor" ]
[((333, 342), 'detectron2.config.get_cfg', 'get_cfg', ([], {}), '()\n', (340, 342), False, 'from detectron2.config import get_cfg\n'), ((580, 669), 'detectron2.model_zoo.get_checkpoint_url', 'model_zoo.get_checkpoint_url', (['"""COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"""'], {}), "(\n 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml')\n", (608, 669), False, 'from detectron2 import model_zoo\n'), ((686, 707), 'detectron2.engine.DefaultPredictor', 'DefaultPredictor', (['cfg'], {}), '(cfg)\n', (702, 707), False, 'from detectron2.engine import DefaultPredictor\n'), ((1221, 1245), 'numpy.zeros', 'np.zeros', (['masks[0].shape'], {}), '(masks[0].shape)\n', (1229, 1245), True, 'import numpy as np\n'), ((1311, 1329), 'numpy.clip', 'np.clip', (['out', '(0)', '(1)'], {}), '(out, 0, 1)\n', (1318, 1329), True, 'import numpy as np\n'), ((1681, 1700), 'numpy.zeros', 'np.zeros', (['(h, w, 2)'], {}), '((h, w, 2))\n', (1689, 1700), True, 'import numpy as np\n'), ((371, 457), 'detectron2.model_zoo.get_config_file', 'model_zoo.get_config_file', (['"""COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"""'], {}), "(\n 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml')\n", (396, 457), False, 'from detectron2 import model_zoo\n')]
import numpy as np from example_functions import target_function_dict from line_search_methods import line_search_dict from main_methods import main_method_dict from config import best_params from helpers import generate_x0 def run_one(_theta, _main_method, _ls_method, params, ls_params): theta = _theta() x0 = generate_x0(theta.n, *theta.bounds) ls_method = _ls_method(ls_params) main_method = _main_method(params, ls_method) # print('Correct solution: ', theta.min_values) result = main_method(theta, np.array(x0)) # print('Found solution: ', result['min_value']) # print(result_to_string(result)) return result def result_to_string(result): perf = result['performance'] ls_perf = perf['line_search'] return ', '.join([str(s) for s in [ result['status'], perf['iterations'], f"{perf['duration']} ms", ls_perf['iterations'], f"{round(ls_perf['duration'], 2)} ms", ]]) np.warnings.filterwarnings('ignore', category=RuntimeWarning) for theta in best_params: for main_method in best_params[theta]: for line_search in best_params[theta][main_method]: result = run_one( target_function_dict[theta], main_method_dict[main_method], line_search_dict[line_search], best_params[theta][main_method][line_search]['params'], best_params[theta][main_method][line_search]['ls_params'], ) status = result['status'] print(f"{status}: {theta},{main_method},{line_search}")
[ "numpy.array", "helpers.generate_x0", "numpy.warnings.filterwarnings" ]
[((946, 1007), 'numpy.warnings.filterwarnings', 'np.warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (972, 1007), True, 'import numpy as np\n'), ((323, 358), 'helpers.generate_x0', 'generate_x0', (['theta.n', '*theta.bounds'], {}), '(theta.n, *theta.bounds)\n', (334, 358), False, 'from helpers import generate_x0\n'), ((532, 544), 'numpy.array', 'np.array', (['x0'], {}), '(x0)\n', (540, 544), True, 'import numpy as np\n')]
import skimage.color import matplotlib.pyplot as plt import numpy as np import cv2 import os import imghdr import time """ Duplicate Image Finder (DIF): function that searches a given directory for images and finds duplicate/similar images among them. Outputs the number of found duplicate/similar image pairs with a list of the filenames having lower resolution. """ class dif: def compare_images(directory, show_imgs=False, similarity="normal", px_size=50, delete=False): """ directory (str)......folder path to search for duplicate/similar images show_imgs (bool).....False = omits the output and doesn't show found images True = shows duplicate/similar images found in output similarity (str)....."normal" = searches for duplicates, recommended setting, MSE < 200 "high" = serached for exact duplicates, extremly sensitive to details, MSE < 0.1 "low" = searches for similar images, MSE < 1000 px_size (int)........recommended not to change default value resize images to px_size height x width (in pixels) before being compared the higher the pixel size, the more computational ressources and time required delete (bool)........! please use with care, as this cannot be undone lower resolution duplicate images that were found are automatically deleted OUTPUT (set).........a set of the filenames of the lower resolution duplicate images """ # list where the found duplicate/similar images are stored duplicates = [] lower_res = [] imgs_matrix = dif.create_imgs_matrix(directory, px_size) # search for similar images, MSE < 1000 if similarity == "low": ref = 1000 # search for exact duplicate images, extremly sensitive, MSE < 0.1 elif similarity == "high": ref = 0.1 # normal, search for duplicates, recommended, MSE < 200 else: ref = 200 main_img = 0 compared_img = 1 nrows, ncols = px_size, px_size srow_A = 0 erow_A = nrows srow_B = erow_A erow_B = srow_B + nrows while erow_B <= imgs_matrix.shape[0]: while compared_img < (len(image_files)): # select two images from imgs_matrix imgA = imgs_matrix[srow_A: erow_A, # rows 0: ncols] # columns imgB = imgs_matrix[srow_B: erow_B, # rows 0: ncols] # columns # compare the images rotations = 0 while image_files[main_img] not in duplicates and rotations <= 3: if rotations != 0: imgB = dif.rotate_img(imgB) err = dif.mse(imgA, imgB) if err < ref: if show_imgs: dif.show_img_figs(imgA, imgB, err) dif.show_file_info(compared_img, main_img) dif.add_to_list(image_files[main_img], duplicates) dif.check_img_quality(directory, image_files[main_img], image_files[compared_img], lower_res) rotations += 1 srow_B += nrows erow_B += nrows compared_img += 1 srow_A += nrows erow_A += nrows srow_B = erow_A erow_B = srow_B + nrows main_img += 1 compared_img = main_img + 1 msg = "\n***\nFound " + str(len(duplicates)) + " duplicate image pairs in " + str( len(image_files)) + " total images.\n\nThe following files have lower resolution:" print(msg) print(lower_res, "\n") time.sleep(0.5) if delete: usr = input("Are you sure you want to delete all lower resolution duplicate images? (y/n)") if str(usr) == "y": dif.delete_imgs(directory, set(lower_res)) else: print("Image deletion canceled.") return set(lower_res) else: return set(lower_res) def _process_directory(directory): directory += os.sep if not os.path.isdir(directory): raise FileNotFoundError(f"Directory: " + directory + " does not exist") return directory # Function that searches the folder for image files, converts them to a matrix def create_imgs_matrix(directory, px_size): directory = dif._process_directory(directory) global image_files image_files = [] # create list of all files in directory folder_files = [filename for filename in os.listdir(directory)] # create images matrix counter = 0 for filename in folder_files: if not os.path.isdir(directory + filename) and imghdr.what(directory + filename): img = cv2.imdecode(np.fromfile(directory + filename, dtype=np.uint8), cv2.IMREAD_UNCHANGED) if type(img) == np.ndarray: img = img[..., 0:3] img = cv2.resize(img, dsize=(px_size, px_size), interpolation=cv2.INTER_CUBIC) if len(img.shape) == 2: img = skimage.color.gray2rgb(img) if counter == 0: imgs_matrix = img image_files.append(filename) counter += 1 else: imgs_matrix = np.concatenate((imgs_matrix, img)) image_files.append(filename) return imgs_matrix # Function that calulates the mean squared error (mse) between two image matrices def mse(imageA, imageB): err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2) err /= float(imageA.shape[0] * imageA.shape[1]) return err # Function that plots two compared image files and their mse def show_img_figs(imageA, imageB, err): fig = plt.figure() plt.suptitle("MSE: %.2f" % (err)) # plot first image ax = fig.add_subplot(1, 2, 1) plt.imshow(imageA, cmap=plt.cm.gray) plt.axis("off") # plot second image ax = fig.add_subplot(1, 2, 2) plt.imshow(imageB, cmap=plt.cm.gray) plt.axis("off") # show the images plt.show() # Function for rotating an image matrix by a 90 degree angle def rotate_img(image): image = np.rot90(image, k=1, axes=(0, 1)) return image # Function for printing filename info of plotted image files def show_file_info(compared_img, main_img): print("Duplicate file: " + image_files[main_img] + " and " + image_files[compared_img]) # Function for appending items to a list def add_to_list(filename, list): list.append(filename) # Function for checking the quality of compared images, appends the lower quality image to the list def check_img_quality(directory, imageA, imageB, list): directory = dif._process_directory(directory) size_imgA = os.stat(directory + imageA).st_size size_imgB = os.stat(directory + imageB).st_size if size_imgA > size_imgB: dif.add_to_list(imageB, list) else: dif.add_to_list(imageA, list) def delete_imgs(directory, filenames_set): directory = dif._process_directory(directory) print("\nDeletion in progress...") deleted = 0 for filename in filenames_set: try: os.remove(directory + filename) print("Deleted file:", filename) deleted += 1 except: print("Could not delete file:", filename) print("\n***\nDeleted", deleted, "duplicates.")
[ "matplotlib.pyplot.imshow", "numpy.fromfile", "os.listdir", "os.stat", "time.sleep", "os.remove", "matplotlib.pyplot.figure", "os.path.isdir", "imghdr.what", "numpy.rot90", "numpy.concatenate", "matplotlib.pyplot.axis", "cv2.resize", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.show" ]
[((3912, 3927), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (3922, 3927), False, 'import time\n'), ((6198, 6210), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6208, 6210), True, 'import matplotlib.pyplot as plt\n'), ((6219, 6250), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (["('MSE: %.2f' % err)"], {}), "('MSE: %.2f' % err)\n", (6231, 6250), True, 'import matplotlib.pyplot as plt\n'), ((6326, 6362), 'matplotlib.pyplot.imshow', 'plt.imshow', (['imageA'], {'cmap': 'plt.cm.gray'}), '(imageA, cmap=plt.cm.gray)\n', (6336, 6362), True, 'import matplotlib.pyplot as plt\n'), ((6371, 6386), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6379, 6386), True, 'import matplotlib.pyplot as plt\n'), ((6461, 6497), 'matplotlib.pyplot.imshow', 'plt.imshow', (['imageB'], {'cmap': 'plt.cm.gray'}), '(imageB, cmap=plt.cm.gray)\n', (6471, 6497), True, 'import matplotlib.pyplot as plt\n'), ((6506, 6521), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6514, 6521), True, 'import matplotlib.pyplot as plt\n'), ((6556, 6566), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6564, 6566), True, 'import matplotlib.pyplot as plt\n'), ((6676, 6709), 'numpy.rot90', 'np.rot90', (['image'], {'k': '(1)', 'axes': '(0, 1)'}), '(image, k=1, axes=(0, 1))\n', (6684, 6709), True, 'import numpy as np\n'), ((4380, 4404), 'os.path.isdir', 'os.path.isdir', (['directory'], {}), '(directory)\n', (4393, 4404), False, 'import os\n'), ((7293, 7320), 'os.stat', 'os.stat', (['(directory + imageA)'], {}), '(directory + imageA)\n', (7300, 7320), False, 'import os\n'), ((7349, 7376), 'os.stat', 'os.stat', (['(directory + imageB)'], {}), '(directory + imageB)\n', (7356, 7376), False, 'import os\n'), ((4855, 4876), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (4865, 4876), False, 'import os\n'), ((5030, 5063), 'imghdr.what', 'imghdr.what', (['(directory + filename)'], {}), '(directory + filename)\n', (5041, 5063), False, 'import imghdr\n'), ((7754, 7785), 'os.remove', 'os.remove', (['(directory + filename)'], {}), '(directory + filename)\n', (7763, 7785), False, 'import os\n'), ((4990, 5025), 'os.path.isdir', 'os.path.isdir', (['(directory + filename)'], {}), '(directory + filename)\n', (5003, 5025), False, 'import os\n'), ((5100, 5149), 'numpy.fromfile', 'np.fromfile', (['(directory + filename)'], {'dtype': 'np.uint8'}), '(directory + filename, dtype=np.uint8)\n', (5111, 5149), True, 'import numpy as np\n'), ((5283, 5355), 'cv2.resize', 'cv2.resize', (['img'], {'dsize': '(px_size, px_size)', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, dsize=(px_size, px_size), interpolation=cv2.INTER_CUBIC)\n', (5293, 5355), False, 'import cv2\n'), ((5691, 5725), 'numpy.concatenate', 'np.concatenate', (['(imgs_matrix, img)'], {}), '((imgs_matrix, img))\n', (5705, 5725), True, 'import numpy as np\n')]
import torch import numpy as np PAD_TOKEN_INDEX = 0 def pad_masking(x, target_len): # x: (batch_size, seq_len) batch_size, seq_len = x.size() padded_positions = x == PAD_TOKEN_INDEX # (batch_size, seq_len) pad_mask = padded_positions.unsqueeze(1).expand(batch_size, target_len, seq_len) return pad_mask def subsequent_masking(x): # x: (batch_size, seq_len - 1) batch_size, seq_len = x.size() subsequent_mask = np.triu(np.ones(shape=(seq_len, seq_len)), k=1).astype('uint8') subsequent_mask = torch.tensor(subsequent_mask).to(x.device) subsequent_mask = subsequent_mask.unsqueeze(0).expand(batch_size, seq_len, seq_len) return subsequent_mask
[ "torch.tensor", "numpy.ones" ]
[((534, 563), 'torch.tensor', 'torch.tensor', (['subsequent_mask'], {}), '(subsequent_mask)\n', (546, 563), False, 'import torch\n'), ((456, 489), 'numpy.ones', 'np.ones', ([], {'shape': '(seq_len, seq_len)'}), '(shape=(seq_len, seq_len))\n', (463, 489), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import matplotlib.pyplot as plt #%matplotlib inline import codecs import lightgbm as lgb from sklearn.model_selection import StratifiedShuffleSplit from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score # Read data image_file_path = './simulated_dpc_data.csv' with codecs.open(image_file_path, "r", "Shift-JIS", "ignore") as file: dpc = pd.read_table(file, delimiter=",") # dpc_r, g_dpc_r_1, g_r: restricted data from dpc dpc_r=dpc.loc[:, ['ID','code']] # g_dpc_r_1: made to check the details (: name of the code, ‘name’) g_dpc_r_1=dpc.loc[:, ['ID','code','name']] # Dummy Encoding with ‘name’ g_r = pd.get_dummies(dpc_r['code']) # Reconstruct simulated data for AI learning df_concat_dpc_get_dummies = pd.concat([dpc_r, g_r], axis=1) # Remove features that may be the cause of the data leak dpc_Remove_data_leak = df_concat_dpc_get_dummies.drop(["code",160094710,160094810,160094910,150285010,2113008,8842965,8843014,622224401,810000000,160060010], axis=1) # Sum up the number of occurrences of each feature for each patient. total_patient_features= dpc_Remove_data_leak.groupby("ID").sum() total_patient_features.reset_index() # Load a new file with ID and treatment availability # Prepare training data image_file_path_ID_and_polyp_pn = './simulated_patient_data.csv' with codecs.open(image_file_path_ID_and_polyp_pn, "r", "Shift-JIS", "ignore") as file: ID_and_polyp_pn = pd.read_table(file, delimiter=",") ID_and_polyp_pn_data= ID_and_polyp_pn[['ID', 'target']] #Combine the new file containing ID and treatment status with the file after dummy encoding by the ‘name’ ID_treatment_medical_statement=pd.merge(ID_and_polyp_pn_data,total_patient_features,on=["ID"],how='outer') ID_treatment_medical_statement_o= ID_treatment_medical_statement.fillna(0) ID_treatment_medical_statement_p=ID_treatment_medical_statement_o.drop("ID", axis=1) ID_treatment_medical_statement_rename= ID_treatment_medical_statement_p.rename(columns={'code':"Receipt type code"}) merge_data= ID_treatment_medical_statement_rename # Split the training/validation set into 80% and the test set into 20%, with a constant proportion of cases with lesions X = merge_data.drop("target",axis=1).values y = merge_data["target"].values columns_name = merge_data.drop("target",axis=1).columns sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2,random_state=1) # Create a function to divide data def data_split(X,y): for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] X_train = pd.DataFrame(X_train, columns=columns_name) X_test = pd.DataFrame(X_test, columns=columns_name) return X_train, y_train, X_test, y_test # Separate into training, validation, and test set X_train, y_train, X_test, y_test = data_split(X, y) X_train, y_train, X_val, y_val = data_split(X_train.values, y_train) # Make test set into pandas X_test_df = pd.DataFrame(X_test) y_test_df = pd.DataFrame(y_test) # Make test set into test_df to keep away for the final process test_dfp = pd.concat([y_test_df,X_test_df], axis=1) test_df=test_dfp.rename(columns={0:"target"}) # Make training/validation sets into pandas y_trainp = pd.DataFrame(y_train) X_trainp = pd.DataFrame(X_train) train=pd.concat([y_trainp, X_trainp], axis=1) y_valp = pd.DataFrame(y_val) X_valp = pd.DataFrame(X_val) val=pd.concat([y_valp, X_valp], axis=1) test_vol=pd.concat([train, val]) training_validation_sets=test_vol.rename(columns={0:"target"}) # Create a function to save the results and feature importance after analysis with lightGBM def reg_top10_lightGBM(merge_data,outname,no,random_state_number): # Define the objective variable X = merge_data.drop("target",axis=1).values y = merge_data["target"].values columns_name = merge_data.drop("target",axis=1).columns # Define a function sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=random_state_number) def data_split(X,y): for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] X_train = pd.DataFrame(X_train, columns=columns_name) X_test = pd.DataFrame(X_test, columns=columns_name) return X_train, y_train, X_test, y_test X_train, y_train, X_test, y_test = data_split(X, y) X_train, y_train, X_val, y_val = data_split(X_train.values, y_train) y_test_df = pd.DataFrame(y_test) # Prepare dataset: training data: X_train, label: y_train train = lgb.Dataset(X_train, label=y_train) valid = lgb.Dataset(X_val, label=y_val) # Set the parameters params = {'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': 'rmse', 'learning_rate': 0.1 } # Train the model model = lgb.train(params, train, valid_sets=valid, num_boost_round=3000, early_stopping_rounds=100) # Prediction y_pred = model.predict(X_test, num_iteration=model.best_iteration) # Display actual values and predicted values df_pred = pd.DataFrame({'regression_y_test':y_test,'regression_y_pred':y_pred}) # Calculate MSE (Mean Square Error) mse = mean_squared_error(y_test, y_pred) # Calculate RSME = √MSE rmse = np.sqrt(mse) # r2 : Calculate the coefficient of determination r2 = r2_score(y_test,y_pred) df_Df = pd.DataFrame({'regression_y_test_'+no:y_test,'regression_y_pred_'+no:y_pred,'RMSE_'+no:rmse,'R2_'+no:r2}) df_Df.to_csv(r""+"./"+outname+no+'.csv', encoding = 'shift-jis') importance = pd.DataFrame(model.feature_importance(), columns=['importance']) column_list=merge_data.drop(["target"], axis=1) importance["columns"] =list(column_list.columns) return importance # Find out Top 50 features procedure / Run the model once importance = reg_top10_lightGBM(training_validation_sets,"check_data","_1",1) # Create a function that sorts and stores the values of feature importance. def after_imp_save_sort(importance,outname,no): importance.sort_values(by='importance',ascending=False) i_df=importance.sort_values(by='importance',ascending=False) top50=i_df.iloc[0:51,:] g_dpc_pre= g_dpc_r_1.drop(["ID"], axis=1) g_dpc_Remove_duplicates=g_dpc_pre.drop_duplicates() g_dpc_r_columns=g_dpc_Remove_duplicates.rename(columns={'code':"columns"}) importance_name=pd.merge(top50,g_dpc_r_columns) importance_all=pd.merge(i_df,g_dpc_r_columns) importance_all.to_csv(r""+"./"+outname+no+'importance_name_all'+'.csv', encoding = 'shift-jis') return importance_all # Run a function to sort and save the values of feature importance. top50_importance_all = after_imp_save_sort(importance,"check_data","_1") # 10 runs of this procedure dict = {} for num in range(10): print(num+1) importance = reg_top10_lightGBM(training_validation_sets,"check_data","_"+str(num+1),num+1) top50_importance_all = after_imp_save_sort(importance,"check_data","_"+str(num+1)) dict[str(num)] = top50_importance_all # Recall and merge the saved CSV files def concat_importance(First_pd,Next_pd): importance_1=pd.DataFrame(dict[First_pd]) importance_1d=importance_1.drop_duplicates(subset='columns') importance_2=pd.DataFrame(dict[Next_pd]) importance_2d=importance_2.drop_duplicates(subset='columns') importance_1_2=pd.concat([importance_1d, importance_2d]) return importance_1_2 importance_1_2 = concat_importance("0","1") importance_3_4 = concat_importance("2","3") importance_5_6 = concat_importance("4","5") importance_7_8 = concat_importance("6","7") importance_9_10 = concat_importance("8","9") importance_1_4=pd.concat([importance_1_2, importance_3_4]) importance_1_6=pd.concat([importance_1_4, importance_5_6]) importance_1_8=pd.concat([importance_1_6, importance_7_8]) importance_1_10=pd.concat([importance_1_8, importance_9_10]) # Calculate the total value of the feature importance for each code group_sum=importance_1_10.groupby(["columns"]).sum() group_sum_s = group_sum.sort_values('importance', ascending=False) importance_group_sum=group_sum_s.reset_index() # Create train/validation test data with all features merge_data_test=pd.concat([training_validation_sets, test_df]) # Make features in the order of highest total feature impotance value importance_top50_previous_data=importance_group_sum["columns"] importance_top50_previous_data # refine the data to top 50 features dict_top50 = {} pycaret_dict_top50 = {} X = range(1, 51) for i,v in enumerate(X): dict_top50[str(i)] = importance_top50_previous_data.iloc[v] pycaret_dict_top50[importance_top50_previous_data[i]] = merge_data_test[dict_top50[str(i)]] pycaret_df_dict_top50=pd.DataFrame(pycaret_dict_top50) # Add the value of target (: objective variable) target_data=merge_data_test["target"] target_top50_dataframe=pd.concat([target_data, pycaret_df_dict_top50], axis=1) # adjust pandas (pycaret needs to set “str” to “int”) target_top50_dataframe_int=target_top50_dataframe.astype('int') target_top50_dataframe_columns=target_top50_dataframe_int.columns.astype(str) numpy_target_top50=target_top50_dataframe_int.to_numpy() target_top50_dataframe_pycaret=pd.DataFrame(numpy_target_top50,columns=target_top50_dataframe_columns) # compare the models from pycaret.classification import * clf1 = setup(target_top50_dataframe_pycaret, target ='target',train_size = 0.8,data_split_shuffle=False,fold=10,session_id=0) best_model = compare_models()
[ "sklearn.model_selection.StratifiedShuffleSplit", "numpy.sqrt", "pandas.DataFrame", "pandas.merge", "lightgbm.train", "sklearn.metrics.mean_squared_error", "lightgbm.Dataset", "pandas.read_table", "pandas.get_dummies", "codecs.open", "sklearn.metrics.r2_score", "pandas.concat" ]
[((674, 703), 'pandas.get_dummies', 'pd.get_dummies', (["dpc_r['code']"], {}), "(dpc_r['code'])\n", (688, 703), True, 'import pandas as pd\n'), ((778, 809), 'pandas.concat', 'pd.concat', (['[dpc_r, g_r]'], {'axis': '(1)'}), '([dpc_r, g_r], axis=1)\n', (787, 809), True, 'import pandas as pd\n'), ((1684, 1762), 'pandas.merge', 'pd.merge', (['ID_and_polyp_pn_data', 'total_patient_features'], {'on': "['ID']", 'how': '"""outer"""'}), "(ID_and_polyp_pn_data, total_patient_features, on=['ID'], how='outer')\n", (1692, 1762), True, 'import pandas as pd\n'), ((2348, 2413), 'sklearn.model_selection.StratifiedShuffleSplit', 'StratifiedShuffleSplit', ([], {'n_splits': '(1)', 'test_size': '(0.2)', 'random_state': '(1)'}), '(n_splits=1, test_size=0.2, random_state=1)\n', (2370, 2413), False, 'from sklearn.model_selection import StratifiedShuffleSplit\n'), ((3027, 3047), 'pandas.DataFrame', 'pd.DataFrame', (['X_test'], {}), '(X_test)\n', (3039, 3047), True, 'import pandas as pd\n'), ((3060, 3080), 'pandas.DataFrame', 'pd.DataFrame', (['y_test'], {}), '(y_test)\n', (3072, 3080), True, 'import pandas as pd\n'), ((3156, 3197), 'pandas.concat', 'pd.concat', (['[y_test_df, X_test_df]'], {'axis': '(1)'}), '([y_test_df, X_test_df], axis=1)\n', (3165, 3197), True, 'import pandas as pd\n'), ((3298, 3319), 'pandas.DataFrame', 'pd.DataFrame', (['y_train'], {}), '(y_train)\n', (3310, 3319), True, 'import pandas as pd\n'), ((3331, 3352), 'pandas.DataFrame', 'pd.DataFrame', (['X_train'], {}), '(X_train)\n', (3343, 3352), True, 'import pandas as pd\n'), ((3359, 3398), 'pandas.concat', 'pd.concat', (['[y_trainp, X_trainp]'], {'axis': '(1)'}), '([y_trainp, X_trainp], axis=1)\n', (3368, 3398), True, 'import pandas as pd\n'), ((3408, 3427), 'pandas.DataFrame', 'pd.DataFrame', (['y_val'], {}), '(y_val)\n', (3420, 3427), True, 'import pandas as pd\n'), ((3437, 3456), 'pandas.DataFrame', 'pd.DataFrame', (['X_val'], {}), '(X_val)\n', (3449, 3456), True, 'import pandas as pd\n'), ((3461, 3496), 'pandas.concat', 'pd.concat', (['[y_valp, X_valp]'], {'axis': '(1)'}), '([y_valp, X_valp], axis=1)\n', (3470, 3496), True, 'import pandas as pd\n'), ((3506, 3529), 'pandas.concat', 'pd.concat', (['[train, val]'], {}), '([train, val])\n', (3515, 3529), True, 'import pandas as pd\n'), ((7893, 7936), 'pandas.concat', 'pd.concat', (['[importance_1_2, importance_3_4]'], {}), '([importance_1_2, importance_3_4])\n', (7902, 7936), True, 'import pandas as pd\n'), ((7952, 7995), 'pandas.concat', 'pd.concat', (['[importance_1_4, importance_5_6]'], {}), '([importance_1_4, importance_5_6])\n', (7961, 7995), True, 'import pandas as pd\n'), ((8011, 8054), 'pandas.concat', 'pd.concat', (['[importance_1_6, importance_7_8]'], {}), '([importance_1_6, importance_7_8])\n', (8020, 8054), True, 'import pandas as pd\n'), ((8071, 8115), 'pandas.concat', 'pd.concat', (['[importance_1_8, importance_9_10]'], {}), '([importance_1_8, importance_9_10])\n', (8080, 8115), True, 'import pandas as pd\n'), ((8421, 8467), 'pandas.concat', 'pd.concat', (['[training_validation_sets, test_df]'], {}), '([training_validation_sets, test_df])\n', (8430, 8467), True, 'import pandas as pd\n'), ((8935, 8967), 'pandas.DataFrame', 'pd.DataFrame', (['pycaret_dict_top50'], {}), '(pycaret_dict_top50)\n', (8947, 8967), True, 'import pandas as pd\n'), ((9078, 9133), 'pandas.concat', 'pd.concat', (['[target_data, pycaret_df_dict_top50]'], {'axis': '(1)'}), '([target_data, pycaret_df_dict_top50], axis=1)\n', (9087, 9133), True, 'import pandas as pd\n'), ((9418, 9490), 'pandas.DataFrame', 'pd.DataFrame', (['numpy_target_top50'], {'columns': 'target_top50_dataframe_columns'}), '(numpy_target_top50, columns=target_top50_dataframe_columns)\n', (9430, 9490), True, 'import pandas as pd\n'), ((334, 390), 'codecs.open', 'codecs.open', (['image_file_path', '"""r"""', '"""Shift-JIS"""', '"""ignore"""'], {}), "(image_file_path, 'r', 'Shift-JIS', 'ignore')\n", (345, 390), False, 'import codecs\n'), ((410, 444), 'pandas.read_table', 'pd.read_table', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (423, 444), True, 'import pandas as pd\n'), ((1352, 1424), 'codecs.open', 'codecs.open', (['image_file_path_ID_and_polyp_pn', '"""r"""', '"""Shift-JIS"""', '"""ignore"""'], {}), "(image_file_path_ID_and_polyp_pn, 'r', 'Shift-JIS', 'ignore')\n", (1363, 1424), False, 'import codecs\n'), ((1456, 1490), 'pandas.read_table', 'pd.read_table', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (1469, 1490), True, 'import pandas as pd\n'), ((2663, 2706), 'pandas.DataFrame', 'pd.DataFrame', (['X_train'], {'columns': 'columns_name'}), '(X_train, columns=columns_name)\n', (2675, 2706), True, 'import pandas as pd\n'), ((2724, 2766), 'pandas.DataFrame', 'pd.DataFrame', (['X_test'], {'columns': 'columns_name'}), '(X_test, columns=columns_name)\n', (2736, 2766), True, 'import pandas as pd\n'), ((3967, 4055), 'sklearn.model_selection.StratifiedShuffleSplit', 'StratifiedShuffleSplit', ([], {'n_splits': '(1)', 'test_size': '(0.2)', 'random_state': 'random_state_number'}), '(n_splits=1, test_size=0.2, random_state=\n random_state_number)\n', (3989, 4055), False, 'from sklearn.model_selection import StratifiedShuffleSplit\n'), ((4567, 4587), 'pandas.DataFrame', 'pd.DataFrame', (['y_test'], {}), '(y_test)\n', (4579, 4587), True, 'import pandas as pd\n'), ((4662, 4697), 'lightgbm.Dataset', 'lgb.Dataset', (['X_train'], {'label': 'y_train'}), '(X_train, label=y_train)\n', (4673, 4697), True, 'import lightgbm as lgb\n'), ((4710, 4741), 'lightgbm.Dataset', 'lgb.Dataset', (['X_val'], {'label': 'y_val'}), '(X_val, label=y_val)\n', (4721, 4741), True, 'import lightgbm as lgb\n'), ((4981, 5076), 'lightgbm.train', 'lgb.train', (['params', 'train'], {'valid_sets': 'valid', 'num_boost_round': '(3000)', 'early_stopping_rounds': '(100)'}), '(params, train, valid_sets=valid, num_boost_round=3000,\n early_stopping_rounds=100)\n', (4990, 5076), True, 'import lightgbm as lgb\n'), ((5312, 5384), 'pandas.DataFrame', 'pd.DataFrame', (["{'regression_y_test': y_test, 'regression_y_pred': y_pred}"], {}), "({'regression_y_test': y_test, 'regression_y_pred': y_pred})\n", (5324, 5384), True, 'import pandas as pd\n'), ((5432, 5466), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (5450, 5466), False, 'from sklearn.metrics import mean_squared_error\n'), ((5506, 5518), 'numpy.sqrt', 'np.sqrt', (['mse'], {}), '(mse)\n', (5513, 5518), True, 'import numpy as np\n'), ((5582, 5606), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (5590, 5606), False, 'from sklearn.metrics import r2_score\n'), ((5618, 5750), 'pandas.DataFrame', 'pd.DataFrame', (["{('regression_y_test_' + no): y_test, ('regression_y_pred_' + no): y_pred,\n ('RMSE_' + no): rmse, ('R2_' + no): r2}"], {}), "({('regression_y_test_' + no): y_test, ('regression_y_pred_' +\n no): y_pred, ('RMSE_' + no): rmse, ('R2_' + no): r2})\n", (5630, 5750), True, 'import pandas as pd\n'), ((6617, 6649), 'pandas.merge', 'pd.merge', (['top50', 'g_dpc_r_columns'], {}), '(top50, g_dpc_r_columns)\n', (6625, 6649), True, 'import pandas as pd\n'), ((6668, 6699), 'pandas.merge', 'pd.merge', (['i_df', 'g_dpc_r_columns'], {}), '(i_df, g_dpc_r_columns)\n', (6676, 6699), True, 'import pandas as pd\n'), ((7366, 7394), 'pandas.DataFrame', 'pd.DataFrame', (['dict[First_pd]'], {}), '(dict[First_pd])\n', (7378, 7394), True, 'import pandas as pd\n'), ((7477, 7504), 'pandas.DataFrame', 'pd.DataFrame', (['dict[Next_pd]'], {}), '(dict[Next_pd])\n', (7489, 7504), True, 'import pandas as pd\n'), ((7589, 7630), 'pandas.concat', 'pd.concat', (['[importance_1d, importance_2d]'], {}), '([importance_1d, importance_2d])\n', (7598, 7630), True, 'import pandas as pd\n'), ((4270, 4313), 'pandas.DataFrame', 'pd.DataFrame', (['X_train'], {'columns': 'columns_name'}), '(X_train, columns=columns_name)\n', (4282, 4313), True, 'import pandas as pd\n'), ((4331, 4373), 'pandas.DataFrame', 'pd.DataFrame', (['X_test'], {'columns': 'columns_name'}), '(X_test, columns=columns_name)\n', (4343, 4373), True, 'import pandas as pd\n')]
from typing import Tuple import numpy as np import png from skimage.transform import resize def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array: """Load a preconstructred track to initialize world. Args: filename: Full path to the track file (png). size: Width and height of the map resolution: Resolution of the grid map (i.e. into how many cells) one meter is divided into. Returns: An initialized gridmap based on the preconstructed track as an n x m dimensional numpy array, where n is the width (num cells) and m the height (num cells) - (after applying resolution). """ width_in_cells, height_in_cells = np.multiply(size, resolution) world = np.array(png_to_ogm( filename, normalized=True, origin='lower')) # If the image is already in our desired shape, no need to rescale it if world.shape == (height_in_cells, width_in_cells): return world # Otherwise, scale the image to our desired size. resized_world = resize(world, (width_in_cells, height_in_cells)) return resized_world def png_to_ogm(filename, normalized=False, origin='lower'): """Convert a png image to occupancy grid map. Inspired by https://github.com/richardos/occupancy-grid-a-star Args: filename: Path to the png file. normalized: Whether to normalize the data, i.e. to be in value range [0, 1] origin: Point of origin (0,0) Returns: 2D Array """ r = png.Reader(filename) img = r.read() img_data = list(img[2]) out_img = [] bitdepth = img[3]['bitdepth'] for i in range(len(img_data)): out_img_row = [] for j in range(len(img_data[0])): if j % img[3]['planes'] == 0: if normalized: out_img_row.append(img_data[i][j]*1.0/(2**bitdepth)) else: out_img_row.append(img_data[i][j]) out_img.append(out_img_row) if origin == 'lower': out_img.reverse() return out_img
[ "numpy.multiply", "skimage.transform.resize", "png.Reader" ]
[((778, 807), 'numpy.multiply', 'np.multiply', (['size', 'resolution'], {}), '(size, resolution)\n', (789, 807), True, 'import numpy as np\n'), ((1122, 1170), 'skimage.transform.resize', 'resize', (['world', '(width_in_cells, height_in_cells)'], {}), '(world, (width_in_cells, height_in_cells))\n', (1128, 1170), False, 'from skimage.transform import resize\n'), ((1604, 1624), 'png.Reader', 'png.Reader', (['filename'], {}), '(filename)\n', (1614, 1624), False, 'import png\n')]
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import IncrementalPCA as _IncrementalPCA from ..count_matrix.zarr import dataset_to_array def _normalize_per_cell(matrix, cell_sum): print('normalize per cell to CPM') if cell_sum is None: norm_vec = (matrix.sum(axis=1) + 1) / 1000000 else: norm_vec = cell_sum / 1000000 norm_vec = norm_vec.values norm_vec = norm_vec.astype(np.float32) matrix /= norm_vec[:, None] return matrix class IncrementalPCA: def __init__(self, n_components=100, sparse=False, normalize_per_cell=True, log1p=True, scale=True, **kwargs): self.pca = _IncrementalPCA(n_components=n_components, **kwargs) self.sparse = sparse self.normalize_per_cell = normalize_per_cell self.log1p = log1p self.scale = scale self.scaler = None self.cell_sum = None self.use_features = None self.obs_dim = None self.var_dim = None self.load_chunk = None self._fit = False return def fit(self, ds, use_cells=None, use_features=None, chunk=500000, cell_sum=None, var_dim='gene', obs_dim='cell', load_chunk=None, random_shuffle=True): self.cell_sum = cell_sum self.use_features = use_features self.obs_dim = obs_dim self.var_dim = var_dim self.load_chunk = chunk if load_chunk is None else load_chunk # prepare index cell_index = ds.get_index(obs_dim) if use_cells is not None: cell_index = cell_index[cell_index.isin(use_cells)].copy() # random shuffle to make fitting more stable if random_shuffle: cell_order = cell_index.tolist() np.random.shuffle(cell_order) cell_order = pd.Index(cell_order) else: cell_order = cell_index # fit by chunks chunk_stds = [] chunk_means = [] for chunk_start in range(0, cell_order.size, chunk): print(f'Fitting {chunk_start}-{chunk_start + chunk}') _chunk_cells = cell_order[chunk_start:chunk_start + chunk] _chunk_matrix, _chunk_cells, _chunk_genes = dataset_to_array( ds, use_cells=_chunk_cells, use_genes=use_features, sparse=self.sparse, obs_dim=obs_dim, var_dim=var_dim, chunk=self.load_chunk) if cell_sum is not None: _chunk_cell_sum = cell_sum.loc[_chunk_cells] else: _chunk_cell_sum = None _chunk_matrix = _chunk_matrix.astype(np.float32) # normalize cell counts if self.normalize_per_cell: _chunk_matrix = _normalize_per_cell(matrix=_chunk_matrix, cell_sum=_chunk_cell_sum) # log transfer if self.log1p: print('log1p transform') _chunk_matrix = np.log1p(_chunk_matrix) # scale if self.scale: print('Scale') if self.scaler is None: # assume the chunk is large enough, so only use the first chunk to fit # e.g., 5,000,000 cells self.scaler = StandardScaler(with_mean=not self.sparse) _chunk_matrix = self.scaler.fit_transform(_chunk_matrix) else: # transform remaining cells _chunk_matrix = self.scaler.transform(_chunk_matrix) # save chunk stats for checking robustness chunk_stds.append(_chunk_matrix.std(axis=0)) chunk_means.append(_chunk_matrix.mean(axis=0)) # fit IncrementalPCA print('Fit PCA') self.pca.partial_fit(_chunk_matrix) self._fit = True return def transform(self, ds, use_cells=None, chunk=100000): if not self._fit: raise ValueError('fit first before transform') cell_index = ds.get_index(self.obs_dim) if use_cells is not None: cell_index = cell_index[cell_index.isin(use_cells)].copy() total_pcs = [] for chunk_start in range(0, cell_index.size, chunk): print(f'Transforming {chunk_start}-{chunk_start + chunk}') _chunk_cells = cell_index[chunk_start:chunk_start + chunk] _chunk_matrix, _chunk_cells, _chunk_genes = dataset_to_array( ds, use_cells=_chunk_cells, use_genes=self.use_features, sparse=self.sparse, obs_dim=self.obs_dim, var_dim=self.var_dim, chunk=self.load_chunk) if self.cell_sum is not None: _chunk_cell_sum = self.cell_sum.loc[_chunk_cells] else: _chunk_cell_sum = None _chunk_matrix = _chunk_matrix.astype(np.float32) # normalize cell counts if self.normalize_per_cell: _chunk_matrix = _normalize_per_cell(matrix=_chunk_matrix, cell_sum=_chunk_cell_sum) # log transfer if self.log1p: print('log1p transform') _chunk_matrix = np.log1p(_chunk_matrix) # scale if self.scale: print('Scale') if self.scaler is None: # this shouldn't happen in transform raise ValueError('scale is True, but scaler not exist') else: # transform remaining cells _chunk_matrix = self.scaler.transform(_chunk_matrix) # transform print('Transform PCA') pcs = self.pca.transform(_chunk_matrix) pcs = pd.DataFrame(pcs, index=_chunk_cells) total_pcs.append(pcs) total_pcs = pd.concat(total_pcs) return total_pcs def fit_transform(self, ds, use_cells=None, use_features=None, chunk=500000, cell_sum=None, var_dim='gene', obs_dim='cell', load_chunk=None, random_shuffle=True): self.fit(ds, use_cells=use_cells, use_features=use_features, chunk=chunk, cell_sum=cell_sum, var_dim=var_dim, obs_dim=obs_dim, load_chunk=load_chunk, random_shuffle=random_shuffle) total_pcs = self.transform(ds, use_cells=use_cells, chunk=self.load_chunk) return total_pcs
[ "pandas.Index", "sklearn.preprocessing.StandardScaler", "pandas.DataFrame", "sklearn.decomposition.IncrementalPCA", "numpy.log1p", "pandas.concat", "numpy.random.shuffle" ]
[((702, 754), 'sklearn.decomposition.IncrementalPCA', '_IncrementalPCA', ([], {'n_components': 'n_components'}), '(n_components=n_components, **kwargs)\n', (717, 754), True, 'from sklearn.decomposition import IncrementalPCA as _IncrementalPCA\n'), ((6155, 6175), 'pandas.concat', 'pd.concat', (['total_pcs'], {}), '(total_pcs)\n', (6164, 6175), True, 'import pandas as pd\n'), ((1891, 1920), 'numpy.random.shuffle', 'np.random.shuffle', (['cell_order'], {}), '(cell_order)\n', (1908, 1920), True, 'import numpy as np\n'), ((1946, 1966), 'pandas.Index', 'pd.Index', (['cell_order'], {}), '(cell_order)\n', (1954, 1966), True, 'import pandas as pd\n'), ((6063, 6100), 'pandas.DataFrame', 'pd.DataFrame', (['pcs'], {'index': '_chunk_cells'}), '(pcs, index=_chunk_cells)\n', (6075, 6100), True, 'import pandas as pd\n'), ((3177, 3200), 'numpy.log1p', 'np.log1p', (['_chunk_matrix'], {}), '(_chunk_matrix)\n', (3185, 3200), True, 'import numpy as np\n'), ((5514, 5537), 'numpy.log1p', 'np.log1p', (['_chunk_matrix'], {}), '(_chunk_matrix)\n', (5522, 5537), True, 'import numpy as np\n'), ((3489, 3530), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': '(not self.sparse)'}), '(with_mean=not self.sparse)\n', (3503, 3530), False, 'from sklearn.preprocessing import StandardScaler\n')]
# Predict time series w/o using OutputProjectWrapper import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # Create time series t_min, t_max = 0, 30 resolution = 0.1 def time_series(t): return t * np.sin(t) / 3 + 2 * np.sin(t * 5) def next_batch(batch_size, n_steps): t0 = np.random.rand(batch_size, 1) * (t_max - t_min - n_steps * resolution) Ts = t0 + np.arange(0., n_steps + 1) * resolution ys = time_series(Ts) return ys[:,:-1].reshape(-1, n_steps, 1), ys[:,1:].reshape(-1, n_steps, 1) t = np.linspace(t_min, t_max, (t_max - t_min) // resolution) n_steps = 20 t_instance = np.linspace(12.2, 12.2 + resolution * (n_steps + 1), n_steps + 1) n_inputs = 1 n_neurons = 100 n_outputs = 1 X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None, n_steps, n_outputs]) basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu) rnn_outputs, states = tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32) learning_rate = 0.001 stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons]) stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs) outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs]) loss = tf.reduce_sum(tf.square(outputs - y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) init = tf.global_variables_initializer() n_iterations = 1000 batch_size = 50 with tf.Session() as sess: init.run() for k in range(n_iterations): X_batch, y_batch = next_batch(batch_size, n_steps) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) if k % 100 == 0: mse = loss.eval(feed_dict={X: X_batch, y: y_batch}) print(k, "\tMSE: ", mse) X_new = time_series(np.array(t_instance[:-1].reshape(-1, n_steps, n_inputs))) y_pred = sess.run(outputs, feed_dict={X: X_new}) print(y_pred) # Generat a creative new seq n_iterations = 2000 batch_size = 50 with tf.Session() as sess: init.run() for k in range(n_iterations): X_batch, y_batch = next_batch(batch_size, n_steps) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) if k % 100 == 0: mse = loss.eval(feed_dict={X: X_batch, y: y_batch}) print(k, "\tMSE: ", mse) sequence1 = [0. for j in range(n_steps)] for k in range(len(t) - n_steps): X_batch = np.array(sequence1[-n_steps:]).reshape(1, n_steps, 1) y_pred = sess.run(outputs, feed_dict={X: X_batch}) sequence1.append(y_pred[0, -1, 0]) sequence2 = [time_series(i * resolution + t_min + (t_max-t_min/3)) for i in range(n_steps)] for j in range(len(t) - n_steps): X_batch = np.array(sequence2[-n_steps:]).reshape(1, n_steps, 1) y_pred = sess.run(outputs, feed_dict={X: X_batch}) sequence2.append(y_pred[0, -1, 0]) plt.figure(figsize=(11,4)) plt.subplot(121) plt.plot(t, sequence1, 'b-') plt.plot(t[:n_steps],sequence1[:n_steps], 'b-', linewidth=3) plt.xlabel('Time') plt.ylabel('Value') plt.subplot(122) plt.plot(t, sequence2, 'b-') plt.plot(t[:n_steps], sequence2[:n_steps], 'b-', linewidth=3) plt.xlabel('Time') plt.show()
[ "numpy.random.rand", "matplotlib.pyplot.ylabel", "numpy.array", "numpy.sin", "numpy.arange", "tensorflow.placeholder", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "tensorflow.Session", "tensorflow.nn.dynamic_rnn", "numpy.linspace", "tensorflow.square", "tensorflow.train.AdamOptimizer", "tensorflow.reshape", "tensorflow.layers.dense", "matplotlib.pyplot.show", "tensorflow.contrib.rnn.BasicRNNCell", "tensorflow.global_variables_initializer", "matplotlib.pyplot.figure", "matplotlib.pyplot.subplot" ]
[((540, 596), 'numpy.linspace', 'np.linspace', (['t_min', 't_max', '((t_max - t_min) // resolution)'], {}), '(t_min, t_max, (t_max - t_min) // resolution)\n', (551, 596), True, 'import numpy as np\n'), ((624, 689), 'numpy.linspace', 'np.linspace', (['(12.2)', '(12.2 + resolution * (n_steps + 1))', '(n_steps + 1)'], {}), '(12.2, 12.2 + resolution * (n_steps + 1), n_steps + 1)\n', (635, 689), True, 'import numpy as np\n'), ((739, 792), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, n_steps, n_inputs]'], {}), '(tf.float32, [None, n_steps, n_inputs])\n', (753, 792), True, 'import tensorflow as tf\n'), ((797, 851), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, n_steps, n_outputs]'], {}), '(tf.float32, [None, n_steps, n_outputs])\n', (811, 851), True, 'import tensorflow as tf\n'), ((866, 937), 'tensorflow.contrib.rnn.BasicRNNCell', 'tf.contrib.rnn.BasicRNNCell', ([], {'num_units': 'n_neurons', 'activation': 'tf.nn.relu'}), '(num_units=n_neurons, activation=tf.nn.relu)\n', (893, 937), True, 'import tensorflow as tf\n'), ((964, 1014), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['basic_cell', 'X'], {'dtype': 'tf.float32'}), '(basic_cell, X, dtype=tf.float32)\n', (981, 1014), True, 'import tensorflow as tf\n'), ((1065, 1105), 'tensorflow.reshape', 'tf.reshape', (['rnn_outputs', '[-1, n_neurons]'], {}), '(rnn_outputs, [-1, n_neurons])\n', (1075, 1105), True, 'import tensorflow as tf\n'), ((1124, 1171), 'tensorflow.layers.dense', 'tf.layers.dense', (['stacked_rnn_outputs', 'n_outputs'], {}), '(stacked_rnn_outputs, n_outputs)\n', (1139, 1171), True, 'import tensorflow as tf\n'), ((1182, 1235), 'tensorflow.reshape', 'tf.reshape', (['stacked_outputs', '[-1, n_steps, n_outputs]'], {}), '(stacked_outputs, [-1, n_steps, n_outputs])\n', (1192, 1235), True, 'import tensorflow as tf\n'), ((1294, 1345), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (1316, 1345), True, 'import tensorflow as tf\n'), ((1393, 1426), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1424, 1426), True, 'import tensorflow as tf\n'), ((2915, 2942), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(11, 4)'}), '(figsize=(11, 4))\n', (2925, 2942), True, 'import matplotlib.pyplot as plt\n'), ((2942, 2958), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (2953, 2958), True, 'import matplotlib.pyplot as plt\n'), ((2959, 2987), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'sequence1', '"""b-"""'], {}), "(t, sequence1, 'b-')\n", (2967, 2987), True, 'import matplotlib.pyplot as plt\n'), ((2988, 3049), 'matplotlib.pyplot.plot', 'plt.plot', (['t[:n_steps]', 'sequence1[:n_steps]', '"""b-"""'], {'linewidth': '(3)'}), "(t[:n_steps], sequence1[:n_steps], 'b-', linewidth=3)\n", (2996, 3049), True, 'import matplotlib.pyplot as plt\n'), ((3049, 3067), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (3059, 3067), True, 'import matplotlib.pyplot as plt\n'), ((3068, 3087), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Value"""'], {}), "('Value')\n", (3078, 3087), True, 'import matplotlib.pyplot as plt\n'), ((3089, 3105), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (3100, 3105), True, 'import matplotlib.pyplot as plt\n'), ((3106, 3134), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'sequence2', '"""b-"""'], {}), "(t, sequence2, 'b-')\n", (3114, 3134), True, 'import matplotlib.pyplot as plt\n'), ((3135, 3196), 'matplotlib.pyplot.plot', 'plt.plot', (['t[:n_steps]', 'sequence2[:n_steps]', '"""b-"""'], {'linewidth': '(3)'}), "(t[:n_steps], sequence2[:n_steps], 'b-', linewidth=3)\n", (3143, 3196), True, 'import matplotlib.pyplot as plt\n'), ((3197, 3215), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (3207, 3215), True, 'import matplotlib.pyplot as plt\n'), ((3216, 3226), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3224, 3226), True, 'import matplotlib.pyplot as plt\n'), ((1258, 1280), 'tensorflow.square', 'tf.square', (['(outputs - y)'], {}), '(outputs - y)\n', (1267, 1280), True, 'import tensorflow as tf\n'), ((1470, 1482), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1480, 1482), True, 'import tensorflow as tf\n'), ((2017, 2029), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2027, 2029), True, 'import tensorflow as tf\n'), ((306, 335), 'numpy.random.rand', 'np.random.rand', (['batch_size', '(1)'], {}), '(batch_size, 1)\n', (320, 335), True, 'import numpy as np\n'), ((245, 258), 'numpy.sin', 'np.sin', (['(t * 5)'], {}), '(t * 5)\n', (251, 258), True, 'import numpy as np\n'), ((391, 418), 'numpy.arange', 'np.arange', (['(0.0)', '(n_steps + 1)'], {}), '(0.0, n_steps + 1)\n', (400, 418), True, 'import numpy as np\n'), ((225, 234), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (231, 234), True, 'import numpy as np\n'), ((2445, 2475), 'numpy.array', 'np.array', (['sequence1[-n_steps:]'], {}), '(sequence1[-n_steps:])\n', (2453, 2475), True, 'import numpy as np\n'), ((2758, 2788), 'numpy.array', 'np.array', (['sequence2[-n_steps:]'], {}), '(sequence2[-n_steps:])\n', (2766, 2788), True, 'import numpy as np\n')]
import os from argparse import ArgumentParser from glob import glob import cv2 import numpy as np import torch import torchvision import matplotlib as mpl import matplotlib.pyplot as plt from PIL import Image from fiery.trainer import TrainingModule from fiery.utils.network import NormalizeInverse from fiery.utils.instance import predict_instance_segmentation_and_trajectories from fiery.utils.visualisation import plot_instance_map, generate_instance_colours, make_contour, convert_figure_numpy EXAMPLE_DATA_PATH = 'example_data' def plot_prediction(image, output, cfg): # Process predictions consistent_instance_seg, matched_centers = predict_instance_segmentation_and_trajectories( output, compute_matched_centers=True ) # Plot future trajectories unique_ids = torch.unique(consistent_instance_seg[0, 0]).cpu().long().numpy()[1:] instance_map = dict(zip(unique_ids, unique_ids)) instance_colours = generate_instance_colours(instance_map) vis_image = plot_instance_map(consistent_instance_seg[0, 0].cpu().numpy(), instance_map) trajectory_img = np.zeros(vis_image.shape, dtype=np.uint8) for instance_id in unique_ids: path = matched_centers[instance_id] for t in range(len(path) - 1): color = instance_colours[instance_id].tolist() cv2.line(trajectory_img, tuple(path[t]), tuple(path[t + 1]), color, 4) # Overlay arrows temp_img = cv2.addWeighted(vis_image, 0.7, trajectory_img, 0.3, 1.0) mask = ~ np.all(trajectory_img == 0, axis=2) vis_image[mask] = temp_img[mask] # Plot present RGB frames and predictions val_w = 2.99 cameras = cfg.IMAGE.NAMES image_ratio = cfg.IMAGE.FINAL_DIM[0] / cfg.IMAGE.FINAL_DIM[1] val_h = val_w * image_ratio fig = plt.figure(figsize=(4 * val_w, 2 * val_h)) width_ratios = (val_w, val_w, val_w, val_w) gs = mpl.gridspec.GridSpec(2, 4, width_ratios=width_ratios) gs.update(wspace=0.0, hspace=0.0, left=0.0, right=1.0, top=1.0, bottom=0.0) denormalise_img = torchvision.transforms.Compose( (NormalizeInverse(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), torchvision.transforms.ToPILImage(),) ) for imgi, img in enumerate(image[0, -1]): ax = plt.subplot(gs[imgi // 3, imgi % 3]) showimg = denormalise_img(img.cpu()) if imgi > 2: showimg = showimg.transpose(Image.FLIP_LEFT_RIGHT) plt.annotate(cameras[imgi].replace('_', ' ').replace('CAM ', ''), (0.01, 0.87), c='white', xycoords='axes fraction', fontsize=14) plt.imshow(showimg) plt.axis('off') ax = plt.subplot(gs[:, 3]) plt.imshow(make_contour(vis_image[::-1, ::-1])) plt.axis('off') plt.draw() figure_numpy = convert_figure_numpy(fig) plt.close() return figure_numpy def download_example_data(): from requests import get def download(url, file_name): # open in binary mode with open(file_name, "wb") as file: # get request response = get(url) # write to file file.write(response.content) if not os.path.exists(EXAMPLE_DATA_PATH): os.makedirs(EXAMPLE_DATA_PATH, exist_ok=True) url_list = ['https://github.com/wayveai/fiery/releases/download/v1.0/example_1.npz', 'https://github.com/wayveai/fiery/releases/download/v1.0/example_2.npz', 'https://github.com/wayveai/fiery/releases/download/v1.0/example_3.npz', 'https://github.com/wayveai/fiery/releases/download/v1.0/example_4.npz' ] for url in url_list: download(url, os.path.join(EXAMPLE_DATA_PATH, os.path.basename(url))) def visualise(checkpoint_path): trainer = TrainingModule.load_from_checkpoint(checkpoint_path, strict=True) device = torch.device('cuda:0') trainer = trainer.to(device) trainer.eval() # Download example data download_example_data() # Load data for data_path in sorted(glob(os.path.join(EXAMPLE_DATA_PATH, '*.npz'))): data = np.load(data_path) image = torch.from_numpy(data['image']).to(device) intrinsics = torch.from_numpy(data['intrinsics']).to(device) extrinsics = torch.from_numpy(data['extrinsics']).to(device) future_egomotions = torch.from_numpy(data['future_egomotion']).to(device) # Forward pass with torch.no_grad(): output = trainer.model(image, intrinsics, extrinsics, future_egomotions) figure_numpy = plot_prediction(image, output, trainer.cfg) os.makedirs('./output_vis', exist_ok=True) output_filename = os.path.join('./output_vis', os.path.basename(data_path).split('.')[0]) + '.png' Image.fromarray(figure_numpy).save(output_filename) print(f'Saved output in {output_filename}') if __name__ == '__main__': parser = ArgumentParser(description='Fiery visualisation') parser.add_argument('--checkpoint', default='./fiery.ckpt', type=str, help='path to checkpoint') args = parser.parse_args() visualise(args.checkpoint)
[ "fiery.trainer.TrainingModule.load_from_checkpoint", "fiery.utils.network.NormalizeInverse", "fiery.utils.instance.predict_instance_segmentation_and_trajectories", "torchvision.transforms.ToPILImage", "fiery.utils.visualisation.make_contour", "torch.from_numpy", "matplotlib.pyplot.imshow", "fiery.utils.visualisation.generate_instance_colours", "os.path.exists", "torch.unique", "argparse.ArgumentParser", "matplotlib.pyplot.close", "cv2.addWeighted", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.axis", "requests.get", "matplotlib.pyplot.draw", "torch.device", "PIL.Image.fromarray", "os.makedirs", "os.path.join", "numpy.zeros", "matplotlib.pyplot.figure", "fiery.utils.visualisation.convert_figure_numpy", "os.path.basename", "torch.no_grad", "numpy.all", "numpy.load", "matplotlib.pyplot.subplot" ]
[((652, 740), 'fiery.utils.instance.predict_instance_segmentation_and_trajectories', 'predict_instance_segmentation_and_trajectories', (['output'], {'compute_matched_centers': '(True)'}), '(output,\n compute_matched_centers=True)\n', (698, 740), False, 'from fiery.utils.instance import predict_instance_segmentation_and_trajectories\n'), ((945, 984), 'fiery.utils.visualisation.generate_instance_colours', 'generate_instance_colours', (['instance_map'], {}), '(instance_map)\n', (970, 984), False, 'from fiery.utils.visualisation import plot_instance_map, generate_instance_colours, make_contour, convert_figure_numpy\n'), ((1099, 1140), 'numpy.zeros', 'np.zeros', (['vis_image.shape'], {'dtype': 'np.uint8'}), '(vis_image.shape, dtype=np.uint8)\n', (1107, 1140), True, 'import numpy as np\n'), ((1459, 1516), 'cv2.addWeighted', 'cv2.addWeighted', (['vis_image', '(0.7)', 'trajectory_img', '(0.3)', '(1.0)'], {}), '(vis_image, 0.7, trajectory_img, 0.3, 1.0)\n', (1474, 1516), False, 'import cv2\n'), ((1805, 1847), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4 * val_w, 2 * val_h)'}), '(figsize=(4 * val_w, 2 * val_h))\n', (1815, 1847), True, 'import matplotlib.pyplot as plt\n'), ((1905, 1959), 'matplotlib.gridspec.GridSpec', 'mpl.gridspec.GridSpec', (['(2)', '(4)'], {'width_ratios': 'width_ratios'}), '(2, 4, width_ratios=width_ratios)\n', (1926, 1959), True, 'import matplotlib as mpl\n'), ((2677, 2698), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[:, 3]'], {}), '(gs[:, 3])\n', (2688, 2698), True, 'import matplotlib.pyplot as plt\n'), ((2755, 2770), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2763, 2770), True, 'import matplotlib.pyplot as plt\n'), ((2776, 2786), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (2784, 2786), True, 'import matplotlib.pyplot as plt\n'), ((2806, 2831), 'fiery.utils.visualisation.convert_figure_numpy', 'convert_figure_numpy', (['fig'], {}), '(fig)\n', (2826, 2831), False, 'from fiery.utils.visualisation import plot_instance_map, generate_instance_colours, make_contour, convert_figure_numpy\n'), ((2836, 2847), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2845, 2847), True, 'import matplotlib.pyplot as plt\n'), ((3820, 3885), 'fiery.trainer.TrainingModule.load_from_checkpoint', 'TrainingModule.load_from_checkpoint', (['checkpoint_path'], {'strict': '(True)'}), '(checkpoint_path, strict=True)\n', (3855, 3885), False, 'from fiery.trainer import TrainingModule\n'), ((3900, 3922), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (3912, 3922), False, 'import torch\n'), ((4957, 5006), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Fiery visualisation"""'}), "(description='Fiery visualisation')\n", (4971, 5006), False, 'from argparse import ArgumentParser\n'), ((1530, 1565), 'numpy.all', 'np.all', (['(trajectory_img == 0)'], {'axis': '(2)'}), '(trajectory_img == 0, axis=2)\n', (1536, 1565), True, 'import numpy as np\n'), ((2289, 2325), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[imgi // 3, imgi % 3]'], {}), '(gs[imgi // 3, imgi % 3])\n', (2300, 2325), True, 'import matplotlib.pyplot as plt\n'), ((2623, 2642), 'matplotlib.pyplot.imshow', 'plt.imshow', (['showimg'], {}), '(showimg)\n', (2633, 2642), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2666), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2659, 2666), True, 'import matplotlib.pyplot as plt\n'), ((2714, 2749), 'fiery.utils.visualisation.make_contour', 'make_contour', (['vis_image[::-1, ::-1]'], {}), '(vis_image[::-1, ::-1])\n', (2726, 2749), False, 'from fiery.utils.visualisation import plot_instance_map, generate_instance_colours, make_contour, convert_figure_numpy\n'), ((3179, 3212), 'os.path.exists', 'os.path.exists', (['EXAMPLE_DATA_PATH'], {}), '(EXAMPLE_DATA_PATH)\n', (3193, 3212), False, 'import os\n'), ((3222, 3267), 'os.makedirs', 'os.makedirs', (['EXAMPLE_DATA_PATH'], {'exist_ok': '(True)'}), '(EXAMPLE_DATA_PATH, exist_ok=True)\n', (3233, 3267), False, 'import os\n'), ((4140, 4158), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (4147, 4158), True, 'import numpy as np\n'), ((4653, 4695), 'os.makedirs', 'os.makedirs', (['"""./output_vis"""'], {'exist_ok': '(True)'}), "('./output_vis', exist_ok=True)\n", (4664, 4695), False, 'import os\n'), ((2104, 2175), 'fiery.utils.network.NormalizeInverse', 'NormalizeInverse', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (2120, 2175), False, 'from fiery.utils.network import NormalizeInverse\n'), ((2186, 2221), 'torchvision.transforms.ToPILImage', 'torchvision.transforms.ToPILImage', ([], {}), '()\n', (2219, 2221), False, 'import torchvision\n'), ((3090, 3098), 'requests.get', 'get', (['url'], {}), '(url)\n', (3093, 3098), False, 'from requests import get\n'), ((4081, 4121), 'os.path.join', 'os.path.join', (['EXAMPLE_DATA_PATH', '"""*.npz"""'], {}), "(EXAMPLE_DATA_PATH, '*.npz')\n", (4093, 4121), False, 'import os\n'), ((4475, 4490), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4488, 4490), False, 'import torch\n'), ((4175, 4206), 'torch.from_numpy', 'torch.from_numpy', (["data['image']"], {}), "(data['image'])\n", (4191, 4206), False, 'import torch\n'), ((4239, 4275), 'torch.from_numpy', 'torch.from_numpy', (["data['intrinsics']"], {}), "(data['intrinsics'])\n", (4255, 4275), False, 'import torch\n'), ((4308, 4344), 'torch.from_numpy', 'torch.from_numpy', (["data['extrinsics']"], {}), "(data['extrinsics'])\n", (4324, 4344), False, 'import torch\n'), ((4384, 4426), 'torch.from_numpy', 'torch.from_numpy', (["data['future_egomotion']"], {}), "(data['future_egomotion'])\n", (4400, 4426), False, 'import torch\n'), ((4811, 4840), 'PIL.Image.fromarray', 'Image.fromarray', (['figure_numpy'], {}), '(figure_numpy)\n', (4826, 4840), False, 'from PIL import Image\n'), ((3748, 3769), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (3764, 3769), False, 'import os\n'), ((4751, 4778), 'os.path.basename', 'os.path.basename', (['data_path'], {}), '(data_path)\n', (4767, 4778), False, 'import os\n'), ((800, 843), 'torch.unique', 'torch.unique', (['consistent_instance_seg[0, 0]'], {}), '(consistent_instance_seg[0, 0])\n', (812, 843), False, 'import torch\n')]
import tensorflow as tf import numpy as np def euclidean_dist(x, y): return np.linalg.norm(x - y) def limit_gpu(): gpus = tf.config.list_physical_devices('GPU') if gpus: try: tf.config.set_logical_device_configuration( gpus[0], [tf.config.LogicalDeviceConfiguration(memory_limit=4000)]) logical_gpus = tf.config.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: print(e)
[ "tensorflow.config.list_logical_devices", "tensorflow.config.list_physical_devices", "tensorflow.config.LogicalDeviceConfiguration", "numpy.linalg.norm" ]
[((82, 103), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - y)'], {}), '(x - y)\n', (96, 103), True, 'import numpy as np\n'), ((134, 172), 'tensorflow.config.list_physical_devices', 'tf.config.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (165, 172), True, 'import tensorflow as tf\n'), ((390, 427), 'tensorflow.config.list_logical_devices', 'tf.config.list_logical_devices', (['"""GPU"""'], {}), "('GPU')\n", (420, 427), True, 'import tensorflow as tf\n'), ((305, 360), 'tensorflow.config.LogicalDeviceConfiguration', 'tf.config.LogicalDeviceConfiguration', ([], {'memory_limit': '(4000)'}), '(memory_limit=4000)\n', (341, 360), True, 'import tensorflow as tf\n')]
from PIL import Image, ImageDraw from numpy import array, random, vstack, ones, linalg from const import TOWERS from copy import deepcopy from os import path class MapDrawer: """ a class for drawing Dota2Maps with replay-parsed data """ def __init__(self, towers, received_tables): """ @param towers: table containing info about towers @param received_tables: the received_tables from the replay """ self.coordinates = [] libdir = path.abspath(path.dirname(__file__)) self.image = Image.open(libdir + "/assets/dota2map.png") self.draw = ImageDraw.Draw(self.image) self.map_w, self.map_h = self.image.size # init information tables and respective columns tower_info_table = received_tables.by_dt['DT_DOTA_BaseNPC_Tower'] position_x_index = tower_info_table.by_name['m_cellX'] position_y_index = tower_info_table.by_name['m_cellY'] position_vector_index = tower_info_table.by_name['m_vecOrigin'] name_index = tower_info_table.by_name['m_iName'] tower_list = deepcopy(TOWERS) # getting world coordinates for every tower in TOWERS for name, data in tower_list.iteritems(): for t in towers: state = t.state state_name = state.get(name_index) if state_name == name: data["worldX"] = state.get(position_x_index) + state.get(position_vector_index)[0] / 128. if "worldY" not in data: data["worldY"] = state.get(position_y_index) + state.get(position_vector_index)[1] / 128. # caching vals, so ordering stays the same throughout the comprehensions vals = tower_list.values() x = [v["worldX"] for v in vals if "worldX" in v] y = [v["worldY"] for v in vals if "worldY" in v] x_map = [v["x"] for v in vals if "worldX" in v] y_map = [v["y"] for v in vals if "worldY" in v] # calculating scale and offset to convert worldcoordinates to coordinates on the map Ax = vstack((x, ones(len(x)))).T Ay = vstack((y, ones(len(y)))).T self.scale_x, self.offset_x = linalg.lstsq(Ax, x_map)[0] self.scale_y, self.offset_y = linalg.lstsq(Ay, y_map)[0] # import matplotlib # matplotlib.use('Agg') # import matplotlib.pyplot as plt # x_tomap = [(a * self.scale_x) + self.offset_x for a in x] # y_tomap = [(a * self.scale_y) + self.offset_y for a in y] # plotting conversion output for debugging purposes # fig, axarr = plt.subplots(nrows = 2, ncols = 2) # axarr[0][0].scatter(x_tomap, y_tomap) # axarr[0][1].scatter(x_map, y_map) # axarr[1][0].scatter(x, y) # plt.savefig("output/towers.png", figsize=(12, 4), dpi=150) def draw_circle_world_coordinates(self, worldX, worldY, r=20, color="red"): """ draws a circle at the specified world coordinates (from bottom-left) with radius r (in px) and the color as required by PIL """ x, y = self.convert_coordinates(worldX, worldY) bounds = (x-r, self.map_h-(y+r), x+r, self.map_h-(y-r)) bounds = tuple(int(round(a)) for a in bounds) self.draw.ellipse(bounds, fill = color) def draw_circle_world_coordinates_list(self, coordinates, r=20, color="red"): """ same as draw_circle_world_coordinates, but for batch drawing """ for x, y in coordinates: self.draw_circle_world_coordinates(x, y, r, color) def draw_circle_map_coordinates(self, x, y, r=20, color="red"): """ draws a circle on the specified pixels (from bottom-left) with radius r (in px) and the color as required by PIL """ bounds = (x-r, self.map_h-(y+r), x+r, self.map_h-(y-r)) bounds = tuple(int(round(a)) for a in bounds) self.draw.ellipse(bounds, fill = color) def draw_circle_map_coordinates_list(self, coordinates, r=20, color="red"): """ same as draw_circle_map_coordinates, but for batch drawing """ for x, y in coordinates: self.draw_circle_map_coordinates(x, y, r, color) def save(self, filename, scale=4): """ saves the map """ scaled = self.image.resize((self.map_w / scale, self.map_h / scale), Image.ANTIALIAS) scaled.save(filename) def convert_coordinates(self, worldX, worldY): """ converts world coordinates to map coordinates by using the scale and offset defined in the __init__ method """ return (worldX * self.scale_x) + self.offset_x, (worldY * self.scale_y) + self.offset_y
[ "PIL.Image.open", "os.path.dirname", "PIL.ImageDraw.Draw", "numpy.linalg.lstsq", "copy.deepcopy" ]
[((585, 628), 'PIL.Image.open', 'Image.open', (["(libdir + '/assets/dota2map.png')"], {}), "(libdir + '/assets/dota2map.png')\n", (595, 628), False, 'from PIL import Image, ImageDraw\n'), ((650, 676), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['self.image'], {}), '(self.image)\n', (664, 676), False, 'from PIL import Image, ImageDraw\n'), ((1145, 1161), 'copy.deepcopy', 'deepcopy', (['TOWERS'], {}), '(TOWERS)\n', (1153, 1161), False, 'from copy import deepcopy\n'), ((539, 561), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (551, 561), False, 'from os import path\n'), ((2277, 2300), 'numpy.linalg.lstsq', 'linalg.lstsq', (['Ax', 'x_map'], {}), '(Ax, x_map)\n', (2289, 2300), False, 'from numpy import array, random, vstack, ones, linalg\n'), ((2343, 2366), 'numpy.linalg.lstsq', 'linalg.lstsq', (['Ay', 'y_map'], {}), '(Ay, y_map)\n', (2355, 2366), False, 'from numpy import array, random, vstack, ones, linalg\n')]
import torch import numpy as np import torch.nn as nn from torch.utils.data import Dataset, DataLoader def binary_reg(x: torch.Tensor): # forward: f(x) = (x>=0) # backward: f(x) = sigmoid a = torch.sigmoid(x) b = a.detach() c = (x.detach() >= 0).float() return a - b + c class HIN2vec(nn.Module): def __init__(self, node_size, path_size, embed_dim, sigmoid_reg=False, r=True): super().__init__() self.reg = torch.sigmoid if sigmoid_reg else binary_reg self.__initialize_model(node_size, path_size, embed_dim, r) def __initialize_model(self, node_size, path_size, embed_dim, r): self.start_embeds = nn.Embedding(node_size, embed_dim) self.end_embeds = self.start_embeds if r else nn.Embedding(node_size, embed_dim) self.path_embeds = nn.Embedding(path_size, embed_dim) # self.classifier = nn.Sequential( # nn.Linear(embed_dim, 1), # nn.Sigmoid(), # ) def forward(self, start_node: torch.LongTensor, end_node: torch.LongTensor, path: torch.LongTensor): # assert start_node.dim() == 1 # shape = (batch_size,) s = self.start_embeds(start_node) # (batch_size, embed_size) e = self.end_embeds(end_node) p = self.path_embeds(path) p = self.reg(p) agg = torch.mul(s, e) agg = torch.mul(agg, p) # agg = F.sigmoid(agg) # output = self.classifier(agg) output = torch.sigmoid(torch.sum(agg, axis=1)) return output def train(log_interval, model, device, train_loader: DataLoader, optimizer, loss_function, epoch): model.train() for idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data[:, 0], data[:, 1], data[:, 2]) loss = loss_function(output.view(-1), target) loss.backward() optimizer.step() if idx % log_interval == 0: print(f'\rTrain Epoch: {epoch} ' f'[{idx * len(data)}/{len(train_loader.dataset)} ({100. * idx / len(train_loader):.3f}%)]\t' f'Loss: {loss.item():.3f}\t\t', # f'data = {data}\t target = {target}', end='') print() class NSTrainSet(Dataset): """ 完全随机的负采样 todo 改进一下? """ def __init__(self, sample, node_size, neg=5): """ :param node_size: 节点数目 :param neg: 负采样数目 :param sample: HIN.sample()返回值,(start_node, end_node, path_id) """ print('init training dataset...') l = len(sample) x = np.tile(sample, (neg + 1, 1)) y = np.zeros(l * (1 + neg)) y[:l] = 1 # x[l:, 2] = np.random.randint(0, path_size - 1, (l * neg,)) x[l:, 1] = np.random.randint(0, node_size - 1, (l * neg,)) self.x = torch.LongTensor(x) self.y = torch.FloatTensor(y) self.length = len(x) print('finished') def __getitem__(self, index): return self.x[index], self.y[index] def __len__(self): return self.length if __name__ == '__main__': ## test binary_reg print('sigmoid') a = torch.tensor([-1.,0.,1.],requires_grad=True) b = torch.sigmoid(a) c = b.sum() print(a) print(b) print(c) c.backward() print(c.grad) print(b.grad) print(a.grad) print('binary') a = torch.tensor([-1., 0., 1.], requires_grad=True) b = binary_reg(a) c = b.sum() print(a) print(b) print(c) c.backward() print(c.grad) print(b.grad) print(a.grad)
[ "torch.mul", "numpy.tile", "torch.LongTensor", "torch.sigmoid", "torch.tensor", "numpy.zeros", "numpy.random.randint", "torch.sum", "torch.FloatTensor", "torch.nn.Embedding" ]
[((205, 221), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (218, 221), False, 'import torch\n'), ((3209, 3259), 'torch.tensor', 'torch.tensor', (['[-1.0, 0.0, 1.0]'], {'requires_grad': '(True)'}), '([-1.0, 0.0, 1.0], requires_grad=True)\n', (3221, 3259), False, 'import torch\n'), ((3262, 3278), 'torch.sigmoid', 'torch.sigmoid', (['a'], {}), '(a)\n', (3275, 3278), False, 'import torch\n'), ((3434, 3484), 'torch.tensor', 'torch.tensor', (['[-1.0, 0.0, 1.0]'], {'requires_grad': '(True)'}), '([-1.0, 0.0, 1.0], requires_grad=True)\n', (3446, 3484), False, 'import torch\n'), ((668, 702), 'torch.nn.Embedding', 'nn.Embedding', (['node_size', 'embed_dim'], {}), '(node_size, embed_dim)\n', (680, 702), True, 'import torch.nn as nn\n'), ((820, 854), 'torch.nn.Embedding', 'nn.Embedding', (['path_size', 'embed_dim'], {}), '(path_size, embed_dim)\n', (832, 854), True, 'import torch.nn as nn\n'), ((1330, 1345), 'torch.mul', 'torch.mul', (['s', 'e'], {}), '(s, e)\n', (1339, 1345), False, 'import torch\n'), ((1360, 1377), 'torch.mul', 'torch.mul', (['agg', 'p'], {}), '(agg, p)\n', (1369, 1377), False, 'import torch\n'), ((2645, 2674), 'numpy.tile', 'np.tile', (['sample', '(neg + 1, 1)'], {}), '(sample, (neg + 1, 1))\n', (2652, 2674), True, 'import numpy as np\n'), ((2687, 2710), 'numpy.zeros', 'np.zeros', (['(l * (1 + neg))'], {}), '(l * (1 + neg))\n', (2695, 2710), True, 'import numpy as np\n'), ((2818, 2865), 'numpy.random.randint', 'np.random.randint', (['(0)', '(node_size - 1)', '(l * neg,)'], {}), '(0, node_size - 1, (l * neg,))\n', (2835, 2865), True, 'import numpy as np\n'), ((2884, 2903), 'torch.LongTensor', 'torch.LongTensor', (['x'], {}), '(x)\n', (2900, 2903), False, 'import torch\n'), ((2921, 2941), 'torch.FloatTensor', 'torch.FloatTensor', (['y'], {}), '(y)\n', (2938, 2941), False, 'import torch\n'), ((757, 791), 'torch.nn.Embedding', 'nn.Embedding', (['node_size', 'embed_dim'], {}), '(node_size, embed_dim)\n', (769, 791), True, 'import torch.nn as nn\n'), ((1481, 1503), 'torch.sum', 'torch.sum', (['agg'], {'axis': '(1)'}), '(agg, axis=1)\n', (1490, 1503), False, 'import torch\n')]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json import uuid from typing import Callable, Mapping, Optional import numpy as np from caffe2.python import workspace from caffe2.python.predictor import predictor_exporter from .builtin_task import register_builtin_tasks from .config import PyTextConfig, pytext_config_from_json from .config.component import create_featurizer from .data.featurizer import InputRecord from .utils.onnx_utils import CAFFE2_DB_TYPE, convert_caffe2_blob_name register_builtin_tasks() Predictor = Callable[[Mapping[str, str]], Mapping[str, np.array]] def _predict(workspace_id, feature_config, predict_net, featurizer, input): workspace.SwitchWorkspace(workspace_id) features = featurizer.featurize(InputRecord(**input)) if feature_config.word_feat: for blob_name in feature_config.word_feat.export_input_names: converted_blob_name = convert_caffe2_blob_name(blob_name) workspace.blobs[converted_blob_name] = np.array( [features.tokens], dtype=str ) workspace.blobs["tokens_lens"] = np.array([len(features.tokens)], dtype=np.int_) if feature_config.dict_feat: dict_feats, weights, lens = feature_config.dict_feat.export_input_names converted_dict_blob_name = convert_caffe2_blob_name(dict_feats) workspace.blobs[converted_dict_blob_name] = np.array( [features.gazetteer_feats], dtype=str ) workspace.blobs[weights] = np.array( [features.gazetteer_feat_weights], dtype=np.float32 ) workspace.blobs[lens] = np.array(features.gazetteer_feat_lengths, dtype=np.int_) if feature_config.char_feat: for blob_name in feature_config.char_feat.export_input_names: converted_blob_name = convert_caffe2_blob_name(blob_name) workspace.blobs[converted_blob_name] = np.array( [features.characters], dtype=str ) workspace.RunNet(predict_net) return { str(blob): workspace.blobs[blob][0] for blob in predict_net.external_outputs } def load_config(filename: str) -> PyTextConfig: """ Load a PyText configuration file from a file path. See pytext.config.pytext_config for more info on configs. """ with open(filename) as file: config_json = json.loads(file.read()) if "config" not in config_json: return pytext_config_from_json(config_json) return pytext_config_from_json(config_json["config"]) def create_predictor( config: PyTextConfig, model_file: Optional[str] = None ) -> Predictor: """ Create a simple prediction API from a training config and an exported caffe2 model file. This model file should be created by calling export on a trained model snapshot. """ workspace_id = str(uuid.uuid4()) workspace.SwitchWorkspace(workspace_id, True) predict_net = predictor_exporter.prepare_prediction_net( filename=model_file or config.export_caffe2_path, db_type=CAFFE2_DB_TYPE ) task = config.task feature_config = task.features featurizer = create_featurizer(task.featurizer, feature_config) return lambda input: _predict( workspace_id, feature_config, predict_net, featurizer, input )
[ "caffe2.python.workspace.RunNet", "caffe2.python.workspace.SwitchWorkspace", "caffe2.python.predictor.predictor_exporter.prepare_prediction_net", "uuid.uuid4", "numpy.array" ]
[((721, 760), 'caffe2.python.workspace.SwitchWorkspace', 'workspace.SwitchWorkspace', (['workspace_id'], {}), '(workspace_id)\n', (746, 760), False, 'from caffe2.python import workspace\n'), ((2019, 2048), 'caffe2.python.workspace.RunNet', 'workspace.RunNet', (['predict_net'], {}), '(predict_net)\n', (2035, 2048), False, 'from caffe2.python import workspace\n'), ((2899, 2944), 'caffe2.python.workspace.SwitchWorkspace', 'workspace.SwitchWorkspace', (['workspace_id', '(True)'], {}), '(workspace_id, True)\n', (2924, 2944), False, 'from caffe2.python import workspace\n'), ((2963, 3083), 'caffe2.python.predictor.predictor_exporter.prepare_prediction_net', 'predictor_exporter.prepare_prediction_net', ([], {'filename': '(model_file or config.export_caffe2_path)', 'db_type': 'CAFFE2_DB_TYPE'}), '(filename=model_file or config.\n export_caffe2_path, db_type=CAFFE2_DB_TYPE)\n', (3004, 3083), False, 'from caffe2.python.predictor import predictor_exporter\n'), ((1438, 1485), 'numpy.array', 'np.array', (['[features.gazetteer_feats]'], {'dtype': 'str'}), '([features.gazetteer_feats], dtype=str)\n', (1446, 1485), True, 'import numpy as np\n'), ((1543, 1604), 'numpy.array', 'np.array', (['[features.gazetteer_feat_weights]'], {'dtype': 'np.float32'}), '([features.gazetteer_feat_weights], dtype=np.float32)\n', (1551, 1604), True, 'import numpy as np\n'), ((1659, 1715), 'numpy.array', 'np.array', (['features.gazetteer_feat_lengths'], {'dtype': 'np.int_'}), '(features.gazetteer_feat_lengths, dtype=np.int_)\n', (1667, 1715), True, 'import numpy as np\n'), ((2881, 2893), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2891, 2893), False, 'import uuid\n'), ((1043, 1081), 'numpy.array', 'np.array', (['[features.tokens]'], {'dtype': 'str'}), '([features.tokens], dtype=str)\n', (1051, 1081), True, 'import numpy as np\n'), ((1941, 1983), 'numpy.array', 'np.array', (['[features.characters]'], {'dtype': 'str'}), '([features.characters], dtype=str)\n', (1949, 1983), True, 'import numpy as np\n')]
import os import re import hyperparams as hp from data_load import DataLoad from tqdm import tqdm import numpy as np import pandas as pd import tensorflow as tf def load_ckpt_paths(model_name='cdmf'): # get ckpt ckpt_path = '../model_ckpt/compare/{}/'.format(model_name) fpaths = [] with open(ckpt_path+'checkpoint', 'r', encoding='utf-8') as f_ckpt : for line in f_ckpt.readlines()[1:]: fname = re.sub(r'\"', '', line.split(':')[-1]).strip() fpath = os.path.join(ckpt_path, fname) fpaths.append(fpath) return fpaths if __name__ == '__main__': data = DataLoad(data_path=hp.DATA_PATH, fnames=hp.FNAMES, forced_seq_len=hp.FORCED_SEQ_LEN, vocab_size=hp.VOCAB_SIZE, paly_times=hp.PLAY_TIMES, num_main_actors=hp.NUM_MAIN_ACTORS, batch_size=hp.BATCH_SIZE, num_epochs=hp.NUM_EPOCHS, noise_rate=hp.NOISE_RATE) # CDMF graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): for fpath in load_ckpt_paths('cdmf'): saver = tf.train.import_meta_graph(fpath+'.meta') saver.restore(sess, fpath) # Get the placeholders from the graph by name m_oids = graph.get_tensor_by_name('movie_order_ids:0') info = graph.get_tensor_by_name('info:0') actors = graph.get_tensor_by_name('actors:0') descriptions = graph.get_tensor_by_name('descriptions:0') u_oids = graph.get_tensor_by_name('user_order_ids:0') r_seq = graph.get_tensor_by_name('rating_sequence:0') dropout_keep_prob = graph.get_tensor_by_name("dropout_keep_prob:0") # Tensors we want to evaluate mse_op = graph.get_tensor_by_name('mse/mse_op:0') # load evalset eval_iter = data.load_data('eval') mse, count = 0.0, 0 for (sub_X_user, sub_X_movie), sub_Y in tqdm(eval_iter): # unpack sub_u_oids, sub_bu_seq = sub_X_user sub_m_oids, sub_info, sub_actors, sub_des, sub_bm_seq = sub_X_movie sub_r_seq = sub_Y dev_feed_dict = { m_oids: sub_m_oids, info: sub_info, actors: sub_actors, descriptions: sub_des, u_oids: sub_u_oids, r_seq: sub_r_seq, dropout_keep_prob: hp.DROPOUT_KEEP_PROB} sub_mse = sess.run(mse_op, feed_dict=dev_feed_dict) mse += sub_mse count += 1 rmse = np.sqrt(mse / count) print('cdmf | rmse:{}'.format(rmse)) # ConvMF tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): for fpath in load_ckpt_paths('convmf'): saver = tf.train.import_meta_graph(fpath+'.meta') saver.restore(sess, fpath) # Get the placeholders from the graph by name m_oids = graph.get_tensor_by_name('movie_order_ids:0') descriptions = graph.get_tensor_by_name('descriptions:0') u_oids = graph.get_tensor_by_name('user_order_ids:0') r_seq = graph.get_tensor_by_name('rating_sequence:0') dropout_keep_prob = graph.get_tensor_by_name("dropout_keep_prob:0") # Tensors we want to evaluate mse_op = graph.get_tensor_by_name('mse/mse_op:0') # load evalset eval_iter = data.load_data('eval') mse, count = 0.0, 0 for (sub_X_user, sub_X_movie), sub_Y in tqdm(eval_iter): # unpack sub_u_oids, sub_bu_seq = sub_X_user sub_m_oids, sub_info, sub_actors, sub_des, sub_bm_seq = sub_X_movie sub_r_seq = sub_Y dev_feed_dict = { m_oids: sub_m_oids, descriptions: sub_des, u_oids: sub_u_oids, r_seq: sub_r_seq, dropout_keep_prob: hp.DROPOUT_KEEP_PROB} sub_mse = sess.run(mse_op, feed_dict=dev_feed_dict) mse += sub_mse count += 1 rmse = np.sqrt(mse / count) print('convmf | rmse:{}'.format(rmse))
[ "tensorflow.Graph", "tensorflow.reset_default_graph", "numpy.sqrt", "tensorflow.Session", "tqdm.tqdm", "os.path.join", "tensorflow.train.import_meta_graph", "data_load.DataLoad", "tensorflow.ConfigProto" ]
[((623, 886), 'data_load.DataLoad', 'DataLoad', ([], {'data_path': 'hp.DATA_PATH', 'fnames': 'hp.FNAMES', 'forced_seq_len': 'hp.FORCED_SEQ_LEN', 'vocab_size': 'hp.VOCAB_SIZE', 'paly_times': 'hp.PLAY_TIMES', 'num_main_actors': 'hp.NUM_MAIN_ACTORS', 'batch_size': 'hp.BATCH_SIZE', 'num_epochs': 'hp.NUM_EPOCHS', 'noise_rate': 'hp.NOISE_RATE'}), '(data_path=hp.DATA_PATH, fnames=hp.FNAMES, forced_seq_len=hp.\n FORCED_SEQ_LEN, vocab_size=hp.VOCAB_SIZE, paly_times=hp.PLAY_TIMES,\n num_main_actors=hp.NUM_MAIN_ACTORS, batch_size=hp.BATCH_SIZE,\n num_epochs=hp.NUM_EPOCHS, noise_rate=hp.NOISE_RATE)\n', (631, 886), False, 'from data_load import DataLoad\n'), ((1058, 1068), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1066, 1068), True, 'import tensorflow as tf\n'), ((3153, 3177), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (3175, 3177), True, 'import tensorflow as tf\n'), ((3198, 3208), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (3206, 3208), True, 'import tensorflow as tf\n'), ((1121, 1190), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': '(False)'}), '(allow_soft_placement=True, log_device_placement=False)\n', (1135, 1190), True, 'import tensorflow as tf\n'), ((1231, 1262), 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), '(config=session_conf)\n', (1241, 1262), True, 'import tensorflow as tf\n'), ((3261, 3330), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': '(False)'}), '(allow_soft_placement=True, log_device_placement=False)\n', (3275, 3330), True, 'import tensorflow as tf\n'), ((3371, 3402), 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), '(config=session_conf)\n', (3381, 3402), True, 'import tensorflow as tf\n'), ((502, 532), 'os.path.join', 'os.path.join', (['ckpt_path', 'fname'], {}), '(ckpt_path, fname)\n', (514, 532), False, 'import os\n'), ((1382, 1425), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (["(fpath + '.meta')"], {}), "(fpath + '.meta')\n", (1408, 1425), True, 'import tensorflow as tf\n'), ((2307, 2322), 'tqdm.tqdm', 'tqdm', (['eval_iter'], {}), '(eval_iter)\n', (2311, 2322), False, 'from tqdm import tqdm\n'), ((3061, 3081), 'numpy.sqrt', 'np.sqrt', (['(mse / count)'], {}), '(mse / count)\n', (3068, 3081), True, 'import numpy as np\n'), ((3511, 3554), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (["(fpath + '.meta')"], {}), "(fpath + '.meta')\n", (3537, 3554), True, 'import tensorflow as tf\n'), ((4316, 4331), 'tqdm.tqdm', 'tqdm', (['eval_iter'], {}), '(eval_iter)\n', (4320, 4331), False, 'from tqdm import tqdm\n'), ((4986, 5006), 'numpy.sqrt', 'np.sqrt', (['(mse / count)'], {}), '(mse / count)\n', (4993, 5006), True, 'import numpy as np\n')]
# coding=utf-8 # Author: <NAME> <<EMAIL>> import numpy as np import re class KeelAttribute: """ A class that represent an attribute of keel dataset format. """ TYPE_REAL, TYPE_INTEGER, TYPE_NOMINAL = ("real", "integer", "nominal") def __init__(self, attribute_name, attribute_type, attribute_range, attribute_builder): self.name = attribute_name self.type = attribute_type self.range = attribute_range self.builder = attribute_builder class KeelDataSet: """ A class that represent the keel dataset format. """ UNKNOWN = '?' def __init__(self, relation_name, attributes, data, inputs=None, outputs=None): self.name = relation_name self.attributes = attributes self.data = data self.inputs = inputs self.outputs = outputs self.shape = len(data[0]), len(data) self.ir = self.__imbalance_ratio() def __get_data(self, attributes): return [self.data[self.attributes.index(a)] for a in attributes] def __imbalance_ratio(self): """Compute the imbalance ratio of the dataset """ labels = self.__get_data(self.outputs) labels = np.concatenate(labels) _, count_classes = np.unique(labels, return_counts=True) max_count = np.max(count_classes) min_count = np.min(count_classes) return round((max_count / min_count), 2) def get_data(self): """Returns (data, target) of the dataset. """ inputs = self.__get_data(self.inputs) outputs = self.__get_data(self.outputs) return np.transpose(inputs), np.concatenate(outputs) def __str__(self): row_format = "{:<31}" * 5 labels = self.__get_data(self.outputs) labels = np.concatenate(labels) classes = np.unique(labels) # metadata = f"{self.name}:\tAttributes: {self.shape[1]}\tSamples: {self.shape[0]}\tClasses: {classes.shape[0]}\tImbalance Ratio: {self.ir}" return row_format.format(f"{self.name} ", *[f"Attributes: {self.shape[1]}", f"Samples: {self.shape[0]}", f"Classes: {classes.shape[0]}", f"IR: {self.ir}"]) def __get_header(self): """Get the header of a keel dataset format. """ header = f"@relation {self.name}\n" attributes = [] for attr in self.attributes: attr_type = "real" if attr.type == KeelAttribute.TYPE_REAL else "integer" if attr.type == KeelAttribute.TYPE_INTEGER else '' if len(attr_type) > 0: attributes.append(f"@attribute {attr.name} {attr_type} [{attr.range[0]}, {attr.range[1]}]") else: attributes.append("@attribute " + attr.name + " {" + (", ").join(list(attr.range)) + "}") header += "\n".join(attributes) header += "\n" header += f"@inputs {(', ').join([attr.name for attr in self.inputs])}\n" header += f"@outputs {(', ').join([attr.name for attr in self.outputs])}\n" header += "@data\n" return header def save(self, path): """Export the data on keel dataset format. Parameters ---------- path : str The filepath to save the dataset. """ with open(path, 'w') as f: # Write header of database f.write(self.__get_header()) # Write data of database data = list(map(list, zip(*self.data))) data = '\n'.join(map(', '.join, map(lambda x: map(str, x), data))) f.write(data) def load_keel_file(path): """Load a keel dataset format. Parameters ---------- path : str The filepath of the keel dataset format. Returns ------- keel_dataset: KeelDataset The keel dataset format loaded. """ handle = open(path) try: line = handle.readline().strip() header_parts = line.split() if header_parts[0] != "@relation" or len(header_parts) != 2: raise SyntaxError("This is not a valid keel database.") # Get database name relation_name = header_parts[1] # Get attributes line = handle.readline().strip() attrs = [] lkp = {} while line.startswith("@attribute"): # Get attribute name attr_name = line.split(" ")[1] # Get attribute type match = re.findall(r"\s([a-z]+)\s{0,1}\[", line) if len(match) > 0: attr_type = match[0] else: attr_type = "nominal" # Get values range if attr_type != "nominal": match = re.findall(r"\[(.*?)\]", line) attr_builder = float if attr_type == "real" else int attr_range = tuple(map(attr_builder, match[0].split(","))) else: match = re.findall(r"\{(.*?)\}", line) attr_builder = str attr_range = tuple(match[0].replace(" ", "").split(",")) keel_attribute = KeelAttribute(attr_name, attr_type, attr_range, attr_builder) attrs.append(keel_attribute) lkp[attr_name] = keel_attribute line = handle.readline().strip() # Get inputs if not line.startswith("@input"): raise SyntaxError("Expected @input or @inputs. " + line) inputs_parts = line.split(maxsplit=1) inputs_name = inputs_parts[1].replace(" ", "").split(",") inputs = [lkp[name] for name in inputs_name] # Get output line = handle.readline().strip() if not line.startswith("@output"): raise SyntaxError("Expected @outputs or @outputs. " + line) output_parts = line.split(maxsplit=1) output_name = output_parts[1].replace(" ", "").split(",") outputs = [lkp[name] for name in output_name] # Get data line = handle.readline().strip() if line != "@data": raise SyntaxError("Expected @data.") data = [[] for _ in range(len(attrs))] for data_line in handle: if data_line: data_values = data_line.strip().replace(" ", "").split(',') for lst, value, attr in zip(data, data_values, attrs): v = value v = v if v == KeelDataSet.UNKNOWN else attr.builder(v) lst.append(v) return KeelDataSet(relation_name, attrs, data, inputs, outputs) finally: if path: handle.close()
[ "numpy.unique", "numpy.max", "numpy.concatenate", "numpy.min", "re.findall", "numpy.transpose" ]
[((1202, 1224), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (1216, 1224), True, 'import numpy as np\n'), ((1253, 1290), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (1262, 1290), True, 'import numpy as np\n'), ((1320, 1341), 'numpy.max', 'np.max', (['count_classes'], {}), '(count_classes)\n', (1326, 1341), True, 'import numpy as np\n'), ((1362, 1383), 'numpy.min', 'np.min', (['count_classes'], {}), '(count_classes)\n', (1368, 1383), True, 'import numpy as np\n'), ((1800, 1822), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (1814, 1822), True, 'import numpy as np\n'), ((1842, 1859), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (1851, 1859), True, 'import numpy as np\n'), ((1631, 1651), 'numpy.transpose', 'np.transpose', (['inputs'], {}), '(inputs)\n', (1643, 1651), True, 'import numpy as np\n'), ((1653, 1676), 'numpy.concatenate', 'np.concatenate', (['outputs'], {}), '(outputs)\n', (1667, 1676), True, 'import numpy as np\n'), ((4458, 4500), 're.findall', 're.findall', (['"""\\\\s([a-z]+)\\\\s{0,1}\\\\["""', 'line'], {}), "('\\\\s([a-z]+)\\\\s{0,1}\\\\[', line)\n", (4468, 4500), False, 'import re\n'), ((4718, 4749), 're.findall', 're.findall', (['"""\\\\[(.*?)\\\\]"""', 'line'], {}), "('\\\\[(.*?)\\\\]', line)\n", (4728, 4749), False, 'import re\n'), ((4935, 4966), 're.findall', 're.findall', (['"""\\\\{(.*?)\\\\}"""', 'line'], {}), "('\\\\{(.*?)\\\\}', line)\n", (4945, 4966), False, 'import re\n')]
""" This test module has tests relating to kelvin model validations. All functions in /calculations/models_kelvin.py are tested here. The purposes are: - testing the meniscus shape determination function - testing the output of the kelvin equations - testing that the "function getter" is performing as expected. The kelvin functions are tested against pre-calculated values at several points. """ import numpy import pytest import pygaps.characterisation.models_kelvin as km import pygaps.utilities.exceptions as pgEx @pytest.mark.characterisation class TestKelvinModels(): """Test the kelvin models.""" @pytest.mark.parametrize( 'branch, pore, geometry', [ ('ads', 'slit', 'hemicylindrical'), ('ads', 'cylinder', 'cylindrical'), ('ads', 'sphere', 'hemispherical'), ('des', 'slit', 'hemicylindrical'), ('des', 'cylinder', 'hemispherical'), ('des', 'sphere', 'hemispherical'), ] ) def test_meniscus_geometry(self, branch, pore, geometry): """Test the meniscus geometry function.""" assert km.get_meniscus_geometry(branch, pore) == geometry @pytest.mark.parametrize( 'model, pressure', [ (km._KELVIN_MODELS['Kelvin'], [0.1, 0.4, 0.9]), ] ) @pytest.mark.parametrize( 'geometry, c_radius', [ ('cylindrical', [0.208, 0.522, 4.539]), ('hemispherical', [0.415, 1.044, 9.078]), ('hemicylindrical', [0.831, 2.090, 18.180]), ] ) def test_kelvin_model( self, model, geometry, pressure, c_radius, basic_adsorbate ): """Test each model against pre-calculated values for N2 at 77K.""" temperature = 77.355 pressure = [0.1, 0.4, 0.9] for index, value in enumerate(pressure): radius = model( value, geometry, temperature, basic_adsorbate.liquid_density(temperature), basic_adsorbate.molar_mass(), basic_adsorbate.surface_tension(temperature) ) assert numpy.isclose(radius, c_radius[index], 0.01, 0.01) def test_kelvin_kjs_model(self, basic_adsorbate): """Test Kelvin KJS model against pre-calculated values for N2 at 77K.""" temperature = 77.355 pressure = [0.1, 0.4, 0.9] c_radius = [0.715, 1.344, 9.378] model = km._KELVIN_MODELS['Kelvin-KJS'] geometry = 'cylindrical' for index, value in enumerate(pressure): radius = model( value, geometry, temperature, basic_adsorbate.liquid_density(temperature), basic_adsorbate.molar_mass(), basic_adsorbate.surface_tension(temperature) ) assert numpy.isclose(radius, c_radius[index], 0.01, 0.01) # Now check for excluding other models geometry = 'hemispherical' with pytest.raises(pgEx.ParameterError): radius = model( value, geometry, temperature, basic_adsorbate.liquid_density(temperature), basic_adsorbate.molar_mass(), basic_adsorbate.surface_tension(temperature) ) def test_get_kelvin_error(self): """When the model requested is not found we raise.""" with pytest.raises(pgEx.ParameterError): km.get_kelvin_model('bad_model') def test_get_kelvin_callable(self): """When we pass a function and dict, we receive a partial back.""" def call_this(addendum): return 'called' + addendum ret = km.get_kelvin_model(call_this, addendum='add') assert ret() == 'calledadd'
[ "pygaps.characterisation.models_kelvin.get_meniscus_geometry", "numpy.isclose", "pytest.mark.parametrize", "pytest.raises", "pygaps.characterisation.models_kelvin.get_kelvin_model" ]
[((633, 914), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""branch, pore, geometry"""', "[('ads', 'slit', 'hemicylindrical'), ('ads', 'cylinder', 'cylindrical'), (\n 'ads', 'sphere', 'hemispherical'), ('des', 'slit', 'hemicylindrical'),\n ('des', 'cylinder', 'hemispherical'), ('des', 'sphere', 'hemispherical')]"], {}), "('branch, pore, geometry', [('ads', 'slit',\n 'hemicylindrical'), ('ads', 'cylinder', 'cylindrical'), ('ads',\n 'sphere', 'hemispherical'), ('des', 'slit', 'hemicylindrical'), ('des',\n 'cylinder', 'hemispherical'), ('des', 'sphere', 'hemispherical')])\n", (656, 914), False, 'import pytest\n'), ((1185, 1282), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""model, pressure"""', "[(km._KELVIN_MODELS['Kelvin'], [0.1, 0.4, 0.9])]"], {}), "('model, pressure', [(km._KELVIN_MODELS['Kelvin'], [\n 0.1, 0.4, 0.9])])\n", (1208, 1282), False, 'import pytest\n'), ((1320, 1502), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""geometry, c_radius"""', "[('cylindrical', [0.208, 0.522, 4.539]), ('hemispherical', [0.415, 1.044, \n 9.078]), ('hemicylindrical', [0.831, 2.09, 18.18])]"], {}), "('geometry, c_radius', [('cylindrical', [0.208, \n 0.522, 4.539]), ('hemispherical', [0.415, 1.044, 9.078]), (\n 'hemicylindrical', [0.831, 2.09, 18.18])])\n", (1343, 1502), False, 'import pytest\n'), ((3655, 3701), 'pygaps.characterisation.models_kelvin.get_kelvin_model', 'km.get_kelvin_model', (['call_this'], {'addendum': '"""add"""'}), "(call_this, addendum='add')\n", (3674, 3701), True, 'import pygaps.characterisation.models_kelvin as km\n'), ((1128, 1166), 'pygaps.characterisation.models_kelvin.get_meniscus_geometry', 'km.get_meniscus_geometry', (['branch', 'pore'], {}), '(branch, pore)\n', (1152, 1166), True, 'import pygaps.characterisation.models_kelvin as km\n'), ((2121, 2171), 'numpy.isclose', 'numpy.isclose', (['radius', 'c_radius[index]', '(0.01)', '(0.01)'], {}), '(radius, c_radius[index], 0.01, 0.01)\n', (2134, 2171), False, 'import numpy\n'), ((2819, 2869), 'numpy.isclose', 'numpy.isclose', (['radius', 'c_radius[index]', '(0.01)', '(0.01)'], {}), '(radius, c_radius[index], 0.01, 0.01)\n', (2832, 2869), False, 'import numpy\n'), ((2966, 3000), 'pytest.raises', 'pytest.raises', (['pgEx.ParameterError'], {}), '(pgEx.ParameterError)\n', (2979, 3000), False, 'import pytest\n'), ((3371, 3405), 'pytest.raises', 'pytest.raises', (['pgEx.ParameterError'], {}), '(pgEx.ParameterError)\n', (3384, 3405), False, 'import pytest\n'), ((3419, 3451), 'pygaps.characterisation.models_kelvin.get_kelvin_model', 'km.get_kelvin_model', (['"""bad_model"""'], {}), "('bad_model')\n", (3438, 3451), True, 'import pygaps.characterisation.models_kelvin as km\n')]
import os import sys import pytest import numpy as np import pandas as pd from scipy.stats import ks_2samp sys.path.append("zarnitsa/") from zarnitsa.stats import DataAugmenterExternally N_TO_CHECK = 500 SIG = 0.5 @pytest.fixture def dae(): return DataAugmenterExternally() @pytest.fixture def normal_data(): return pd.Series(np.random.normal(0, SIG * 3, size=N_TO_CHECK), dtype="float64") def test_augment_column_permute(dae, normal_data): """ Augment column with normal distribution """ normal_data_aug = dae.augment_distrib_random( aug_type="normal", size=N_TO_CHECK, loc=0, scale=SIG * 3 ) assert ks_2samp(normal_data, normal_data_aug).pvalue > 0.01, "KS criteria"
[ "numpy.random.normal", "zarnitsa.stats.DataAugmenterExternally", "sys.path.append", "scipy.stats.ks_2samp" ]
[((109, 137), 'sys.path.append', 'sys.path.append', (['"""zarnitsa/"""'], {}), "('zarnitsa/')\n", (124, 137), False, 'import sys\n'), ((259, 284), 'zarnitsa.stats.DataAugmenterExternally', 'DataAugmenterExternally', ([], {}), '()\n', (282, 284), False, 'from zarnitsa.stats import DataAugmenterExternally\n'), ((343, 388), 'numpy.random.normal', 'np.random.normal', (['(0)', '(SIG * 3)'], {'size': 'N_TO_CHECK'}), '(0, SIG * 3, size=N_TO_CHECK)\n', (359, 388), True, 'import numpy as np\n'), ((652, 690), 'scipy.stats.ks_2samp', 'ks_2samp', (['normal_data', 'normal_data_aug'], {}), '(normal_data, normal_data_aug)\n', (660, 690), False, 'from scipy.stats import ks_2samp\n')]
from .Wavefunction import Wavefunction import numpy as np from scipy.fft import ifft2, fft2 import numba CACHE_OPTIMIZATIONS = True class Collision(): targetWavefunction = None # Implements wilson line incidentWavefunction = None # Doesn't (have to) implement wilson line _omega = None _omegaFFT = None _particlesProduced = None _particlesProducedDeriv = None _momentaMagSquared = None _momentaComponents = None _thetaInFourierSpace = None _momentaBins = None _fourierHarmonics = None # This will be initialized as an empty dict to store harmonics (see __init__) _omegaExists = False _omegaFFTExists = False _momentaComponentsExist = False _particlesProducedExists = False _particlesProducedDerivExists = False _momentaBinsExists = False def __init__(self, wavefunction1: Wavefunction, wavefunction2: Wavefunction): r""" Initialize a collision with two wavefunctions, presumably a nucleus and a proton. One must implement the wilson line, though the order of the arguments does not matter. In the case that both wavefunctions implement the wilson line, the first (wavefunction1) will be used as such. In the case that neither implement the wilson line, an exception will be raised. Parameters ---------- wavefunction1 : Wavefunction (or child) The first wavefunction wavefunction2 : Wavefunction (or child) The second wavefunction """ # Make sure that at least one has a wilson line wilsonLineExists1 = callable(getattr(wavefunction1, "wilsonLine", None)) wilsonLineExists2 = callable(getattr(wavefunction2, "wilsonLine", None)) if not wilsonLineExists1 and not wilsonLineExists2: raise Exception("Neither of the wavefunctions passed to Collision(Wavefunction, Wavefunction) implement the wilsonLine() method; at least one is required to.") if wilsonLineExists1 and not wilsonLineExists2: self.targetWavefunction = wavefunction1 self.incidentWavefunction = wavefunction2 elif wilsonLineExists2 and not wilsonLineExists1: self.targetWavefunction = wavefunction2 self.incidentWavefunction = wavefunction1 else: self.targetWavefunction = wavefunction1 self.incidentWavefunction = wavefunction2 # Make sure that both use the same number of colors if self.targetWavefunction.gluonDOF != self.incidentWavefunction.gluonDOF: raise Exception(f"Wavefunctions implement different gluon degrees of freedom (number of color charges): {self.incidentWavefunction.gluonDOF} vs. {self.targetWavefunction.gluonDOF}") # Probably some other checks that need to be done to make sure the two wavefunctions are compatable, but this is fine for now # Carry over some variables so we don't have to call through the wavefunctions so much self.N = self.targetWavefunction.N self.length = self.targetWavefunction.length self.gluonDOF = self.targetWavefunction.gluonDOF self.delta = self.targetWavefunction.delta self.delta2 = self.targetWavefunction.delta2 #print(self.targetWavefunction) #print(self.incidentWavefunction) # Variables to do with binning the momenta later on self.binSize = 4*np.pi/self.length self.kMax = 2/self.delta self.numBins = int(self.kMax/self.binSize) # This has to be initialized as an empty dict within the constructor # because otherwise it can retain information across separate objects # (no idea how, but this fixes it) self._fourierHarmonics = {} def omega(self, forceCalculate=False, verbose=0): r""" Calculate the field omega at each point on the lattice. If the field already exists, it is simply returned and no calculation is done. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- omega : array(N, N, 2, 2, `colorCharges`**2 - 1) """ if self._omegaExists and not forceCalculate: return self._omega self.incidentWavefunction.gaugeField(verbose=verbose) self.targetWavefunction.adjointWilsonLine(verbose=verbose) if verbose > 0: print(f'Calculating {type(self).__name__} omega' + '.'*10, end='') self._omega = _calculateOmegaOpt(self.N, self.gluonDOF, self.delta, self.incidentWavefunction.gaugeField(), self.targetWavefunction.adjointWilsonLine()) self._omegaExists = True if verbose > 0: print('finished!') return self._omega def omegaFFT(self, forceCalculate=False, verbose=0): r""" Compute the fourier transform of the field omega on the lattice. If the fft of the field already exists, it is simply returned and no calculation is done. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- omegaFFT : array(N, N, 2, 2, `colorCharges`**2 - 1) """ if self._omegaFFTExists and not forceCalculate: return self._omegaFFT # Make sure omega exists self.omega(verbose=verbose) if verbose > 0: print(f'Calculating {type(self).__name__} omega fourier transform' + '.'*10, end='') # We want to do the normalization explicitly, but scipy doesn't offer no # normalization as an option, so we just set it to be the opposite of whatever # we are doing (forward for ifft, backward for fft) # (we had some issues with scipy changing its default mode) self._omegaFFT = self.delta2 * fft2(self._omega, axes=(0,1), norm='backward') self._omegaFFTExists = True if verbose > 0: print('finished!') return self._omegaFFT def momentaBins(self, forceCalculate=False, verbose=0): r""" Compute the range of momenta at which particles will be created based on the dimensions of the lattice. The exact values are: - \( k_{max} = 2 / \Delta\) - \( w_k = 4 \pi / L \) If the bins already exist, they are simply returned and no calculation is done. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- momentaBins : array(numBins = L / (delta 2 pi)) """ if self._momentaBinsExists and not forceCalculate: return self._momentaBins if verbose > 0: print(f'Calculating {type(self).__name__} momentum bins' + '.'*10, end='') self._momentaBins = [i*self.binSize for i in range(self.numBins)] self._momentaBinsExists = True if verbose > 0: print('finished!') return self._momentaBins def momentaComponents(self, forceCalculate=False, verbose=0): r""" Compute the components of the momentum at each point on the lattice, according to: $$ (k_x, k_y) = \frac{2}{\Delta} \left( \sin\left( \frac{\pi i}{N} \right), \sin\left( \frac{\pi j}{N} \right) \right) $$ where \(i\) and \(j\) index the \(x\) and \(y\) directions in real space, respectively. If the calculation has already been done, the result is simply returned and is not repeated. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- momentaComponents : array(N, N, 2) """ if self._momentaComponentsExist and not forceCalculate: return self._momentaComponents if verbose > 0: print(f'Calculating {type(self).__name__} momentum components' + '.'*10, end='') self._momentaComponents, self._thetaInFourierSpace = _calculateMomentaOpt(self.N, self.delta) self._momentaMagSquared = np.linalg.norm(self._momentaComponents, axis=2)**2 self._momentaComponentsExist = True if verbose > 0: print('finished!') return self._momentaComponents def momentaMagnitudeSquared(self, forceCalculate=False, verbose=0): r""" Compute the magnitude of the momentum at each point on the lattice, according to: $$ |k| = \sqrt{k_x^2 + k_y^2} $$ $$ (k_x, k_y) = \frac{2}{\Delta} \left( \sin\left( \frac{\pi i}{N} \right), \sin\left( \frac{\pi j}{N} \right) \right) $$ where \(i\) and \(j\) index the \(x\) and \(y\) directions in real space, respectively. If the calculation has already been done, the result is simply returned and is not repeated. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- momentaComponents : array(N, N) """ if self._momentaComponentsExist and not forceCalculate: return self._momentaMagSquared if verbose > 0: print(f'Calculating {type(self).__name__} momenta magnitude squared' + '.'*10, end='') self._momentaComponents, self._thetaInFourierSpace = _calculateMomentaOpt(self.N, self.delta) self._momentaMagSquared = np.linalg.norm(self._momentaComponents, axis=2)**2 self._momentaComponentsExist = True if verbose > 0: print('finished!') return self._momentaMagSquared def particlesProducedDeriv(self, forceCalculate=False, verbose=0): r""" Compute the derivative of particles produced (\( \frac{d^2 N}{d^2 k} \)) at each point on the lattice If the calculation has already been done, the result is simply returned and is not repeated. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- particlesProducedDeriv : array(N, N) """ if self._particlesProducedDerivExists and not forceCalculate: return self._particlesProducedDeriv # Make sure these quantities exist self.omegaFFT(verbose=verbose) self.momentaMagnitudeSquared(verbose=verbose) # This also calculates thetaInFourierSpace and momentaComponents if verbose > 0: print(f'Calculating {type(self).__name__} derivative of particles produced' + '.'*10, end='') self._particlesProducedDeriv = _calculateParticlesProducedDerivOpt(self.N, self.gluonDOF, self._momentaMagSquared, self._omegaFFT) if verbose > 0: print('finished!') self._particlesProducedDerivExists = True return self._particlesProducedDeriv def particlesProduced(self, forceCalculate=False, verbose=0): r""" Compute the number of particles produced \(N(|k|)\) as a function of momentum. Note that this is technically the zeroth fourier harmonic, so this actually just calls the cgc.Collision.fourierHarmonic() function. The particles are binned according to cgc.Collision.momentaBins(). Most likely will be plotted against cgc.Collision.momentaBins(). If the calculation has already been done, the result is simply returned and is not repeated. Parameters ---------- forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- particlesProduced : array(numBins = L / (delta 2 pi)) """ # This one is strictly real, so we should make sure that is updated self._fourierHarmonics[0] = np.real(self.fourierHarmonic(0, forceCalculate, verbose)) return self._fourierHarmonics[0] def fourierHarmonic(self, harmonic: int, forceCalculate=False, verbose=0): r""" Calculate the fourier harmonic of the particle production as: $$ v_n = \frac{ \sum_{(i,j)\in [k, k+ \Delta k]} |k| \frac{d^2 N}{d^2 k} e^{i n \theta }} { \sum_{(i,j)\in [k, k+ \Delta k]} |k| } $$ If the calculation has already been done, the result is simply returned and is not repeated. Parameters ---------- harmonic : int The fourier harmonic to calculate. All odd harmonics should be zero, and the zeroth harmonic will be equal to cgc.Collision.particlesProduced() forceCalculate : bool (default=False) If the quantity has previously been calculated, the calculation will not be done again unless this argument is set to True. verbose : int (default=0) How much output should be printed as calculations are done. Options are 0, 1, or 2. Returns ------- particlesProduced : array(numBins = L / (delta 2 pi)) """ # First, see if we have already calculated this harmonic if harmonic in self._fourierHarmonics.keys() and not forceCalculate: return self._fourierHarmonics[harmonic] # For actually calculating the harmonic, we first have to make sure we've calculated # the derivative, dN/d^2k # This makes sure that _momentaMagSquared, _thetaInFourierSpace and _particlesProducedDeriv # all exist self.particlesProducedDeriv(verbose=verbose) if verbose > 0: print(f'Calculating {type(self).__name__} fourier harmonic: {harmonic}' + '.'*10, end='') # Drop all of our arrays into long 1D structure, since we will want to bin them vectorizedParticleDerivs = np.reshape(self._particlesProducedDeriv, [self.N*self.N]) vectorizedTheta = np.reshape(self._thetaInFourierSpace, [self.N*self.N]) vectorizedMomentaMag = np.reshape(np.sqrt(self._momentaMagSquared), [self.N*self.N]) # The number of particles that are produced in each bin # These bins are actually just thin rings in momentum space self._fourierHarmonics[harmonic] = np.zeros(self.numBins, dtype='complex') # The bin sizes/bounds are calculated for elsewhere self.momentaBins() # Ideally, these rings should be only have a thickness dk (infinitesimal) # but since we have a discrete lattice, we weight the particles by their momentum # (which may slightly vary) and then properly normalize # Go through each bin and calculate (for all points in that bin): # 1. Sum over |k| * dN/d^2k * exp(i * harmonic * theta) # 2. Sum over |k| # 3. Divide 1./2. for i in range(self.numBins): # Find which places on the lattice fall into this particular momentum bin # Note the use of element-wise (or bitwise) and, "&" particleDerivsInRing = vectorizedParticleDerivs[(vectorizedMomentaMag < self.binSize*(i+1)) & (vectorizedMomentaMag > self.binSize*i)] momentaMagInRing = vectorizedMomentaMag[(vectorizedMomentaMag < self.binSize*(i+1)) & (vectorizedMomentaMag > self.binSize*i)] thetaInRing = vectorizedTheta[(vectorizedMomentaMag < self.binSize*(i+1)) & (vectorizedMomentaMag > self.binSize*i)] # Note that multiplication is done element-wise by default numeratorSum = np.sum(particleDerivsInRing * momentaMagInRing * np.exp(1.j * harmonic * thetaInRing)) denominatorSum = np.sum(momentaMagInRing) self._fourierHarmonics[harmonic][i] = numeratorSum / denominatorSum if verbose > 0: print('finished!') return self._fourierHarmonics[harmonic] # Using custom functions within other jitted functions can cause some issues, # so we define the signatures explicitly for these two functions. @numba.jit((numba.float64[:,:], numba.int64, numba.int64, numba.int64, numba.float64), nopython=True, cache=CACHE_OPTIMIZATIONS) def _x_deriv(matrix, i, j, N, delta): return (matrix[i,(j+1)%N] - matrix[i,j-1]) / (2 * delta) @numba.jit((numba.float64[:,:], numba.int64, numba.int64, numba.int64, numba.float64), nopython=True, cache=CACHE_OPTIMIZATIONS) def _y_deriv(matrix, i, j, N, delta): return (matrix[(i+1)%N,j] - matrix[i-1,j]) / (2 * delta) # Because of the same issue described above, we can't cache this function # This function gives a warning because numba only experimentally supports # treating functions as objects (the list derivs). @numba.jit(nopython=True) def _calculateOmegaOpt(N, gluonDOF, delta, incidentGaugeField, targetAdjointWilsonLine): """ Calculate the field omega at each point on the lattice. If the field already exists, it is simply returned and no calculation is done. Returns ------- numpy.array : shape=(N, N, 2, 2, `colorCharges`**2 - 1) """ # 2,2 is for the 2 dimensions, x and y omega = np.zeros((N, N, 2, 2, gluonDOF), dtype='complex') # 2 is for two dimensions, x and y derivs = [_x_deriv, _y_deriv] for i in range(N): for j in range(N): for k in range(gluonDOF): for l in range(2): # 2 is number of dimensions for n in range(2): # 2 is number of dimensions omega[i,j,l,n,k] = np.sum(np.array([derivs[l](incidentGaugeField[:,:,m], i, j, N, delta) * derivs[n](targetAdjointWilsonLine[:,:,k,m], i, j, N, delta) for m in range(gluonDOF)])) return omega @numba.jit(nopython=True, cache=CACHE_OPTIMIZATIONS) def _calculateMomentaOpt(N, delta): """ Optimized (via numba) function to calculated the position (momentum) in Fourier space of each point Parameters ---------- N : int Size of the lattice delta : double Spacing between each point Returns ------- (momentaComponents, theta) momentaComponents : array(N, N, 2) x and y components of the momentum at each point theta : array(N, N) Relationship between x and y components at each point, or atan2(k_y, k_x) """ momentaComponents = np.zeros((N, N, 2)) theta = np.zeros((N, N)) for i in range(N): for j in range(N): # Note that these components are of the form: # k_x = 2/a sin(k_x' a / 2) # Though the argument of the sin is simplified a bit momentaComponents[i,j] = [2/delta * np.sin(np.pi*i/N) * np.sign(np.sin(2*np.pi*i/N)), 2/delta * np.sin(np.pi*j/N) * np.sign(np.sin(2*np.pi*j/N))] theta[i,j] = np.arctan2(momentaComponents[i,j,1], momentaComponents[i,j,0]) return momentaComponents, theta @numba.jit(nopython=True, cache=CACHE_OPTIMIZATIONS) def _calculateParticlesProducedDerivOpt(N, gluonDOF, momentaMagSquared, omegaFFT): """ Optimized (via numba) function to calculate dN/d^2k Parameters ---------- N : int The system size gluonDOF : int The number of gluon degrees of freedom ((possible color charges)^2 - 1) momentaMagSquared : array(N, N) The magnitude of the momentum at each point, likely calculated (in part) with _calculateMomentaOpt() omegaFFT : array(2, 2, gluonDOF, N, N) Previously calculated omega array Returns ------- particleProduction : array(N, N) The number of particles produced at each point on the momentum lattice """ # Where we will calculate dN/d^2k particleProduction = np.zeros((N,N)) # # 2D Levi-Cevita symbol LCS = np.array([[0,1],[-1,0]]) # # 2D Delta function KDF = np.array([[1,0],[0,1]]) # Note that unlike in the rest of the code, i and j *do not* refer to the # spacial indices here: x and y do (too many indices... :/ ) for y in range(N): for x in range(N): # To prevent any divide by zero errors if momentaMagSquared[y,x] == 0: continue # All of these 2s are for our two dimensions, x and y for i in range(2): for j in range(2): for l in range(2): for m in range(2): for a in range(gluonDOF): particleProduction[y,x] += np.real(2/(2*np.pi)**3 / momentaMagSquared[y,x] * ( (KDF[i,j]*KDF[l,m] + LCS[i,j]*LCS[l,m])) * ( omegaFFT[y,x,i,j,a] * np.conj(omegaFFT[y,x,l,m,a]))) return particleProduction
[ "numpy.reshape", "scipy.fft.fft2", "numpy.sqrt", "numpy.conj", "numpy.exp", "numpy.array", "numpy.zeros", "numba.jit", "numpy.sum", "numpy.arctan2", "numpy.linalg.norm", "numpy.sin" ]
[((17641, 17773), 'numba.jit', 'numba.jit', (['(numba.float64[:, :], numba.int64, numba.int64, numba.int64, numba.float64)'], {'nopython': '(True)', 'cache': 'CACHE_OPTIMIZATIONS'}), '((numba.float64[:, :], numba.int64, numba.int64, numba.int64,\n numba.float64), nopython=True, cache=CACHE_OPTIMIZATIONS)\n', (17650, 17773), False, 'import numba\n'), ((17870, 18002), 'numba.jit', 'numba.jit', (['(numba.float64[:, :], numba.int64, numba.int64, numba.int64, numba.float64)'], {'nopython': '(True)', 'cache': 'CACHE_OPTIMIZATIONS'}), '((numba.float64[:, :], numba.int64, numba.int64, numba.int64,\n numba.float64), nopython=True, cache=CACHE_OPTIMIZATIONS)\n', (17879, 18002), False, 'import numba\n'), ((18299, 18323), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (18308, 18323), False, 'import numba\n'), ((19278, 19329), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'cache': 'CACHE_OPTIMIZATIONS'}), '(nopython=True, cache=CACHE_OPTIMIZATIONS)\n', (19287, 19329), False, 'import numba\n'), ((20446, 20497), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'cache': 'CACHE_OPTIMIZATIONS'}), '(nopython=True, cache=CACHE_OPTIMIZATIONS)\n', (20455, 20497), False, 'import numba\n'), ((18715, 18764), 'numpy.zeros', 'np.zeros', (['(N, N, 2, 2, gluonDOF)'], {'dtype': '"""complex"""'}), "((N, N, 2, 2, gluonDOF), dtype='complex')\n", (18723, 18764), True, 'import numpy as np\n'), ((19898, 19917), 'numpy.zeros', 'np.zeros', (['(N, N, 2)'], {}), '((N, N, 2))\n', (19906, 19917), True, 'import numpy as np\n'), ((19930, 19946), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (19938, 19946), True, 'import numpy as np\n'), ((21259, 21275), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (21267, 21275), True, 'import numpy as np\n'), ((21316, 21343), 'numpy.array', 'np.array', (['[[0, 1], [-1, 0]]'], {}), '([[0, 1], [-1, 0]])\n', (21324, 21343), True, 'import numpy as np\n'), ((21378, 21404), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (21386, 21404), True, 'import numpy as np\n'), ((15481, 15540), 'numpy.reshape', 'np.reshape', (['self._particlesProducedDeriv', '[self.N * self.N]'], {}), '(self._particlesProducedDeriv, [self.N * self.N])\n', (15491, 15540), True, 'import numpy as np\n'), ((15565, 15621), 'numpy.reshape', 'np.reshape', (['self._thetaInFourierSpace', '[self.N * self.N]'], {}), '(self._thetaInFourierSpace, [self.N * self.N])\n', (15575, 15621), True, 'import numpy as np\n'), ((15896, 15935), 'numpy.zeros', 'np.zeros', (['self.numBins'], {'dtype': '"""complex"""'}), "(self.numBins, dtype='complex')\n", (15904, 15935), True, 'import numpy as np\n'), ((6384, 6431), 'scipy.fft.fft2', 'fft2', (['self._omega'], {'axes': '(0, 1)', 'norm': '"""backward"""'}), "(self._omega, axes=(0, 1), norm='backward')\n", (6388, 6431), False, 'from scipy.fft import ifft2, fft2\n'), ((9129, 9176), 'numpy.linalg.norm', 'np.linalg.norm', (['self._momentaComponents'], {'axis': '(2)'}), '(self._momentaComponents, axis=2)\n', (9143, 9176), True, 'import numpy as np\n'), ((10691, 10738), 'numpy.linalg.norm', 'np.linalg.norm', (['self._momentaComponents'], {'axis': '(2)'}), '(self._momentaComponents, axis=2)\n', (10705, 10738), True, 'import numpy as np\n'), ((15662, 15694), 'numpy.sqrt', 'np.sqrt', (['self._momentaMagSquared'], {}), '(self._momentaMagSquared)\n', (15669, 15694), True, 'import numpy as np\n'), ((17282, 17306), 'numpy.sum', 'np.sum', (['momentaMagInRing'], {}), '(momentaMagInRing)\n', (17288, 17306), True, 'import numpy as np\n'), ((20344, 20410), 'numpy.arctan2', 'np.arctan2', (['momentaComponents[i, j, 1]', 'momentaComponents[i, j, 0]'], {}), '(momentaComponents[i, j, 1], momentaComponents[i, j, 0])\n', (20354, 20410), True, 'import numpy as np\n'), ((17203, 17240), 'numpy.exp', 'np.exp', (['(1.0j * harmonic * thetaInRing)'], {}), '(1.0j * harmonic * thetaInRing)\n', (17209, 17240), True, 'import numpy as np\n'), ((20209, 20230), 'numpy.sin', 'np.sin', (['(np.pi * i / N)'], {}), '(np.pi * i / N)\n', (20215, 20230), True, 'import numpy as np\n'), ((20237, 20262), 'numpy.sin', 'np.sin', (['(2 * np.pi * i / N)'], {}), '(2 * np.pi * i / N)\n', (20243, 20262), True, 'import numpy as np\n'), ((20269, 20290), 'numpy.sin', 'np.sin', (['(np.pi * j / N)'], {}), '(np.pi * j / N)\n', (20275, 20290), True, 'import numpy as np\n'), ((20297, 20322), 'numpy.sin', 'np.sin', (['(2 * np.pi * j / N)'], {}), '(2 * np.pi * j / N)\n', (20303, 20322), True, 'import numpy as np\n'), ((22252, 22284), 'numpy.conj', 'np.conj', (['omegaFFT[y, x, l, m, a]'], {}), '(omegaFFT[y, x, l, m, a])\n', (22259, 22284), True, 'import numpy as np\n')]
import sys sys.path.append("../../configs") #../../configs from path import EXP_PATH import numpy as np DECAY_PARAMS_DICT =\ { 'stair' : { 128 :{ 'a1': {'initial_lr' : 1e-5, 'decay_steps' : 50000, 'decay_rate' : 0.3}, 'a2' : {'initial_lr' : 3e-4, 'decay_steps' : 50000, 'decay_rate' : 0.3}, 'a3' : {'initial_lr' : 1e-3, 'decay_steps' : 50000, 'decay_rate' : 0.3}, 'a4' : {'initial_lr' : 3e-3, 'decay_steps' : 50000, 'decay_rate' : 0.3}, 'a5' : {'initial_lr' : 1e-2, 'decay_steps' : 50000, 'decay_rate' : 0.3} } }, 'piecewise' : { 128 : { 'a1' : {'boundaries' : [10000, 20000], 'values' : [1e-4, 3e-5, 1e-5]}, 'a2' : {'boundaries' : [10000, 20000], 'values' : [3e-4, 1e-4, 3e-5]}, 'a3' : {'boundaries' : [10000, 20000], 'values' : [1e-3, 3e-4, 1e-4]}, 'a4' : {'boundaries' : [10000, 20000], 'values' : [3e-3, 1e-3, 3e-4]}, 'a5' : {'boundaries' : [10000, 20000], 'values' : [1e-2, 3e-3, 1e-3]}, 'b1' : {'boundaries' : [20000, 35000], 'values' : [1e-4, 3e-5, 1e-5]}, 'b2' : {'boundaries' : [20000, 35000], 'values' : [3e-4, 1e-4, 3e-5]}, 'b3' : {'boundaries' : [20000, 35000], 'values' : [1e-3, 3e-4, 1e-4]}, 'b4' : {'boundaries' : [20000, 35000], 'values' : [3e-3, 1e-3, 3e-4]}, 'b5' : {'boundaries' : [20000, 35000], 'values' : [1e-2, 3e-3, 1e-3]} } } } ACTIVATE_K_SET = np.arange(1, 5) K_SET = [1,4,16] RESULT_DIR = EXP_PATH+"cifar_exps/" #========================PARAM============================# DATASET= 'cifar' GPU_ID = 0 BATCH_SIZE = 128 EPOCH = 300 NSCLASS = 16 # model EMBED_M= 64 CONV_NAME = 'conv1' # metric loss LOSS_TYPE = 'triplet' MARGIN_ALPHA = 0.3 LAMBDA = 0.003 # regularization for npair # learning DECAY_TYPE = 'stair' DECAY_PARAM_TYPE = 'a3'
[ "sys.path.append", "numpy.arange" ]
[((11, 43), 'sys.path.append', 'sys.path.append', (['"""../../configs"""'], {}), "('../../configs')\n", (26, 43), False, 'import sys\n'), ((1616, 1631), 'numpy.arange', 'np.arange', (['(1)', '(5)'], {}), '(1, 5)\n', (1625, 1631), True, 'import numpy as np\n')]
import dgl import torch as th import numpy as np import itertools import time from collections import * Graph = namedtuple('Graph', ['g', 'src', 'tgt', 'tgt_y', 'nids', 'eids', 'nid_arr', 'n_nodes', 'n_edges', 'n_tokens', 'layer_eids']) # We need to create new graph pools for relative position attention (ngram style) def dedupe_tuples(tups): try: return list(set([(a, b) if a < b else (b, a) for a, b in tups])) except ValueError: raise Exception(tups) def get_src_dst_deps(src_deps, order=1): if not isinstance(src_deps, list): src_deps = [src_deps] # If order is one, then we simply return src_deps if order == 1: return list(set(src_deps)) else: new_deps = list() for src, dst in src_deps: # Go up one order. i.e make dst the src, and find its parent for src_dup, dst_dup in src_deps: if dst_dup == dst and src != src_dup: new_deps.append((src, src_dup)) elif src_dup == src and dst != dst_dup: new_deps.append((dst, dst_dup)) elif dst == src_dup and src != dst_dup: new_deps.append((src, dst_dup)) return list(set(get_src_dst_deps(new_deps, order=order - 1)).difference(set(src_deps))) class GraphPool: "Create a graph pool in advance to accelerate graph building phase in Transformer." def __init__(self, n=50, m=50): ''' args: n: maximum length of input sequence. m: maximum length of output sequence. ''' print('start creating graph pool...') tic = time.time() self.n, self.m = n, m g_pool = [[dgl.DGLGraph() for _ in range(m)] for _ in range(n)] num_edges = { 'ee': np.zeros((n, n)).astype(int), 'ed': np.zeros((n, m)).astype(int), 'dd': np.zeros((m, m)).astype(int) } for i, j in itertools.product(range(n), range(m)): src_length = i + 1 tgt_length = j + 1 g_pool[i][j].add_nodes(src_length + tgt_length) enc_nodes = th.arange(src_length, dtype=th.long) dec_nodes = th.arange(tgt_length, dtype=th.long) + src_length # enc -> enc us = enc_nodes.unsqueeze(-1).repeat(1, src_length).view(-1) vs = enc_nodes.repeat(src_length) g_pool[i][j].add_edges(us, vs) num_edges['ee'][i][j] = len(us) # enc -> dec us = enc_nodes.unsqueeze(-1).repeat(1, tgt_length).view(-1) vs = dec_nodes.repeat(src_length) g_pool[i][j].add_edges(us, vs) num_edges['ed'][i][j] = len(us) # dec -> dec indices = th.triu(th.ones(tgt_length, tgt_length)) == 1 us = dec_nodes.unsqueeze(-1).repeat(1, tgt_length)[indices] vs = dec_nodes.unsqueeze(0).repeat(tgt_length, 1)[indices] g_pool[i][j].add_edges(us, vs) num_edges['dd'][i][j] = len(us) print('successfully created graph pool, time: {0:0.3f}s'.format(time.time() - tic)) self.g_pool = g_pool self.num_edges = num_edges def beam(self, src_buf, start_sym, max_len, k, device='cpu', src_deps=None): ''' Return a batched graph for beam search during inference of Transformer. args: src_buf: a list of input sequence start_sym: the index of start-of-sequence symbol max_len: maximum length for decoding k: beam size device: 'cpu' or 'cuda:*' ''' if src_deps is None: src_deps = list() g_list = [] src_lens = [len(_) for _ in src_buf] tgt_lens = [max_len] * len(src_buf) num_edges = {'ee': [], 'ed': [], 'dd': []} for src_len, tgt_len in zip(src_lens, tgt_lens): i, j = src_len - 1, tgt_len - 1 for _ in range(k): g_list.append(self.g_pool[i][j]) for key in ['ee', 'ed', 'dd']: num_edges[key].append(int(self.num_edges[key][i][j])) g = dgl.batch(g_list) src, tgt = [], [] src_pos, tgt_pos = [], [] enc_ids, dec_ids = [], [] layer_eids = { 'dep': [[], []] } e2e_eids, e2d_eids, d2d_eids = [], [], [] n_nodes, n_edges, n_tokens = 0, 0, 0 for src_sample, src_dep, n, n_ee, n_ed, n_dd in zip(src_buf, src_deps, src_lens, num_edges['ee'], num_edges['ed'], num_edges['dd']): for _ in range(k): src.append(th.tensor(src_sample, dtype=th.long, device=device)) src_pos.append(th.arange(n, dtype=th.long, device=device)) enc_ids.append(th.arange(n_nodes, n_nodes + n, dtype=th.long, device=device)) n_nodes += n e2e_eids.append(th.arange(n_edges, n_edges + n_ee, dtype=th.long, device=device)) # Copy the ids of edges that correspond to a given node and its previous N nodes # We are using arange here. This will not work. Instead we need to select edges that # correspond to previous positions. This information is present in graph pool # For each edge, we need to figure out source_node_id and target_node_id. if src_dep: for i in range(0, 2): for src_node_id, dst_node_id in dedupe_tuples(get_src_dst_deps(src_dep, i + 1)): layer_eids['dep'][i].append(n_edges + src_node_id * n + dst_node_id) layer_eids['dep'][i].append(n_edges + dst_node_id * n + src_node_id) n_edges += n_ee tgt_seq = th.zeros(max_len, dtype=th.long, device=device) tgt_seq[0] = start_sym tgt.append(tgt_seq) tgt_pos.append(th.arange(max_len, dtype=th.long, device=device)) dec_ids.append(th.arange(n_nodes, n_nodes + max_len, dtype=th.long, device=device)) n_nodes += max_len e2d_eids.append(th.arange(n_edges, n_edges + n_ed, dtype=th.long, device=device)) n_edges += n_ed d2d_eids.append(th.arange(n_edges, n_edges + n_dd, dtype=th.long, device=device)) n_edges += n_dd g.set_n_initializer(dgl.init.zero_initializer) g.set_e_initializer(dgl.init.zero_initializer) return Graph(g=g, src=(th.cat(src), th.cat(src_pos)), tgt=(th.cat(tgt), th.cat(tgt_pos)), tgt_y=None, nids = {'enc': th.cat(enc_ids), 'dec': th.cat(dec_ids)}, eids = {'ee': th.cat(e2e_eids), 'ed': th.cat(e2d_eids), 'dd': th.cat(d2d_eids)}, nid_arr = {'enc': enc_ids, 'dec': dec_ids}, n_nodes=n_nodes, n_edges=n_edges, layer_eids={ 'dep': [ th.tensor(layer_eids['dep'][i]) for i in range(0, len(layer_eids['dep'])) ] }, n_tokens=n_tokens) def __call__(self, src_buf, tgt_buf, device='cpu', src_deps=None): ''' Return a batched graph for the training phase of Transformer. args: src_buf: a set of input sequence arrays. tgt_buf: a set of output sequence arrays. device: 'cpu' or 'cuda:*' src_deps: list, optional Dependency parses of the source in the form of src_node_id -> dst_node_id. where src is the child and dst is the parent. i.e a child node attends on its syntactic parent in a dependency parse ''' if src_deps is None: src_deps = list() g_list = [] src_lens = [len(_) for _ in src_buf] tgt_lens = [len(_) - 1 for _ in tgt_buf] num_edges = {'ee': [], 'ed': [], 'dd': []} # We are running over source and target pairs here for src_len, tgt_len in zip(src_lens, tgt_lens): i, j = src_len - 1, tgt_len - 1 g_list.append(self.g_pool[i][j]) for key in ['ee', 'ed', 'dd']: num_edges[key].append(int(self.num_edges[key][i][j])) g = dgl.batch(g_list) src, tgt, tgt_y = [], [], [] src_pos, tgt_pos = [], [] enc_ids, dec_ids = [], [] e2e_eids, d2d_eids, e2d_eids = [], [], [] layer_eids = { 'dep': [[], []] } n_nodes, n_edges, n_tokens = 0, 0, 0 for src_sample, tgt_sample, src_dep, n, m, n_ee, n_ed, n_dd in zip(src_buf, tgt_buf, src_deps, src_lens, tgt_lens, num_edges['ee'], num_edges['ed'], num_edges['dd']): src.append(th.tensor(src_sample, dtype=th.long, device=device)) tgt.append(th.tensor(tgt_sample[:-1], dtype=th.long, device=device)) tgt_y.append(th.tensor(tgt_sample[1:], dtype=th.long, device=device)) src_pos.append(th.arange(n, dtype=th.long, device=device)) tgt_pos.append(th.arange(m, dtype=th.long, device=device)) enc_ids.append(th.arange(n_nodes, n_nodes + n, dtype=th.long, device=device)) n_nodes += n dec_ids.append(th.arange(n_nodes, n_nodes + m, dtype=th.long, device=device)) n_nodes += m e2e_eids.append(th.arange(n_edges, n_edges + n_ee, dtype=th.long, device=device)) # Copy the ids of edges that correspond to a given node and its previous N nodes # We are using arange here. This will not work. Instead we need to select edges that # correspond to previous positions. This information is present in graph pool # For each edge, we need to figure out source_node_id and target_node_id. if src_dep: for i in range(0, 2): for src_node_id, dst_node_id in dedupe_tuples(get_src_dst_deps(src_dep, i + 1)): layer_eids['dep'][i].append(n_edges + src_node_id * n + dst_node_id) layer_eids['dep'][i].append(n_edges + dst_node_id * n + src_node_id) n_edges += n_ee e2d_eids.append(th.arange(n_edges, n_edges + n_ed, dtype=th.long, device=device)) n_edges += n_ed d2d_eids.append(th.arange(n_edges, n_edges + n_dd, dtype=th.long, device=device)) n_edges += n_dd n_tokens += m g.set_n_initializer(dgl.init.zero_initializer) g.set_e_initializer(dgl.init.zero_initializer) return Graph(g=g, src=(th.cat(src), th.cat(src_pos)), tgt=(th.cat(tgt), th.cat(tgt_pos)), tgt_y=th.cat(tgt_y), nids = {'enc': th.cat(enc_ids), 'dec': th.cat(dec_ids)}, eids = {'ee': th.cat(e2e_eids), 'ed': th.cat(e2d_eids), 'dd': th.cat(d2d_eids)}, nid_arr = {'enc': enc_ids, 'dec': dec_ids}, n_nodes=n_nodes, layer_eids={ 'dep': [ th.tensor(layer_eids['dep'][i]) for i in range(0, len(layer_eids['dep'])) ] }, n_edges=n_edges, n_tokens=n_tokens)
[ "dgl.batch", "torch.tensor", "torch.cat", "numpy.zeros", "dgl.DGLGraph", "time.time", "torch.zeros", "torch.arange", "torch.ones" ]
[((1669, 1680), 'time.time', 'time.time', ([], {}), '()\n', (1678, 1680), False, 'import time\n'), ((4163, 4180), 'dgl.batch', 'dgl.batch', (['g_list'], {}), '(g_list)\n', (4172, 4180), False, 'import dgl\n'), ((8419, 8436), 'dgl.batch', 'dgl.batch', (['g_list'], {}), '(g_list)\n', (8428, 8436), False, 'import dgl\n'), ((2164, 2200), 'torch.arange', 'th.arange', (['src_length'], {'dtype': 'th.long'}), '(src_length, dtype=th.long)\n', (2173, 2200), True, 'import torch as th\n'), ((1730, 1744), 'dgl.DGLGraph', 'dgl.DGLGraph', ([], {}), '()\n', (1742, 1744), False, 'import dgl\n'), ((2225, 2261), 'torch.arange', 'th.arange', (['tgt_length'], {'dtype': 'th.long'}), '(tgt_length, dtype=th.long)\n', (2234, 2261), True, 'import torch as th\n'), ((5790, 5837), 'torch.zeros', 'th.zeros', (['max_len'], {'dtype': 'th.long', 'device': 'device'}), '(max_len, dtype=th.long, device=device)\n', (5798, 5837), True, 'import torch as th\n'), ((8896, 8947), 'torch.tensor', 'th.tensor', (['src_sample'], {'dtype': 'th.long', 'device': 'device'}), '(src_sample, dtype=th.long, device=device)\n', (8905, 8947), True, 'import torch as th\n'), ((8972, 9028), 'torch.tensor', 'th.tensor', (['tgt_sample[:-1]'], {'dtype': 'th.long', 'device': 'device'}), '(tgt_sample[:-1], dtype=th.long, device=device)\n', (8981, 9028), True, 'import torch as th\n'), ((9055, 9110), 'torch.tensor', 'th.tensor', (['tgt_sample[1:]'], {'dtype': 'th.long', 'device': 'device'}), '(tgt_sample[1:], dtype=th.long, device=device)\n', (9064, 9110), True, 'import torch as th\n'), ((9139, 9181), 'torch.arange', 'th.arange', (['n'], {'dtype': 'th.long', 'device': 'device'}), '(n, dtype=th.long, device=device)\n', (9148, 9181), True, 'import torch as th\n'), ((9210, 9252), 'torch.arange', 'th.arange', (['m'], {'dtype': 'th.long', 'device': 'device'}), '(m, dtype=th.long, device=device)\n', (9219, 9252), True, 'import torch as th\n'), ((9281, 9342), 'torch.arange', 'th.arange', (['n_nodes', '(n_nodes + n)'], {'dtype': 'th.long', 'device': 'device'}), '(n_nodes, n_nodes + n, dtype=th.long, device=device)\n', (9290, 9342), True, 'import torch as th\n'), ((9396, 9457), 'torch.arange', 'th.arange', (['n_nodes', '(n_nodes + m)'], {'dtype': 'th.long', 'device': 'device'}), '(n_nodes, n_nodes + m, dtype=th.long, device=device)\n', (9405, 9457), True, 'import torch as th\n'), ((9513, 9577), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_ee)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_ee, dtype=th.long, device=device)\n', (9522, 9577), True, 'import torch as th\n'), ((10352, 10416), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_ed)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_ed, dtype=th.long, device=device)\n', (10361, 10416), True, 'import torch as th\n'), ((10474, 10538), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_dd)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_dd, dtype=th.long, device=device)\n', (10483, 10538), True, 'import torch as th\n'), ((10874, 10887), 'torch.cat', 'th.cat', (['tgt_y'], {}), '(tgt_y)\n', (10880, 10887), True, 'import torch as th\n'), ((1823, 1839), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (1831, 1839), True, 'import numpy as np\n'), ((1871, 1887), 'numpy.zeros', 'np.zeros', (['(n, m)'], {}), '((n, m))\n', (1879, 1887), True, 'import numpy as np\n'), ((1919, 1935), 'numpy.zeros', 'np.zeros', (['(m, m)'], {}), '((m, m))\n', (1927, 1935), True, 'import numpy as np\n'), ((2792, 2823), 'torch.ones', 'th.ones', (['tgt_length', 'tgt_length'], {}), '(tgt_length, tgt_length)\n', (2799, 2823), True, 'import torch as th\n'), ((3133, 3144), 'time.time', 'time.time', ([], {}), '()\n', (3142, 3144), False, 'import time\n'), ((4630, 4681), 'torch.tensor', 'th.tensor', (['src_sample'], {'dtype': 'th.long', 'device': 'device'}), '(src_sample, dtype=th.long, device=device)\n', (4639, 4681), True, 'import torch as th\n'), ((4714, 4756), 'torch.arange', 'th.arange', (['n'], {'dtype': 'th.long', 'device': 'device'}), '(n, dtype=th.long, device=device)\n', (4723, 4756), True, 'import torch as th\n'), ((4789, 4850), 'torch.arange', 'th.arange', (['n_nodes', '(n_nodes + n)'], {'dtype': 'th.long', 'device': 'device'}), '(n_nodes, n_nodes + n, dtype=th.long, device=device)\n', (4798, 4850), True, 'import torch as th\n'), ((4913, 4977), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_ee)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_ee, dtype=th.long, device=device)\n', (4922, 4977), True, 'import torch as th\n'), ((5944, 5992), 'torch.arange', 'th.arange', (['max_len'], {'dtype': 'th.long', 'device': 'device'}), '(max_len, dtype=th.long, device=device)\n', (5953, 5992), True, 'import torch as th\n'), ((6026, 6093), 'torch.arange', 'th.arange', (['n_nodes', '(n_nodes + max_len)'], {'dtype': 'th.long', 'device': 'device'}), '(n_nodes, n_nodes + max_len, dtype=th.long, device=device)\n', (6035, 6093), True, 'import torch as th\n'), ((6163, 6227), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_ed)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_ed, dtype=th.long, device=device)\n', (6172, 6227), True, 'import torch as th\n'), ((6293, 6357), 'torch.arange', 'th.arange', (['n_edges', '(n_edges + n_dd)'], {'dtype': 'th.long', 'device': 'device'}), '(n_edges, n_edges + n_dd, dtype=th.long, device=device)\n', (6302, 6357), True, 'import torch as th\n'), ((6555, 6566), 'torch.cat', 'th.cat', (['src'], {}), '(src)\n', (6561, 6566), True, 'import torch as th\n'), ((6568, 6583), 'torch.cat', 'th.cat', (['src_pos'], {}), '(src_pos)\n', (6574, 6583), True, 'import torch as th\n'), ((6612, 6623), 'torch.cat', 'th.cat', (['tgt'], {}), '(tgt)\n', (6618, 6623), True, 'import torch as th\n'), ((6625, 6640), 'torch.cat', 'th.cat', (['tgt_pos'], {}), '(tgt_pos)\n', (6631, 6640), True, 'import torch as th\n'), ((6712, 6727), 'torch.cat', 'th.cat', (['enc_ids'], {}), '(enc_ids)\n', (6718, 6727), True, 'import torch as th\n'), ((6736, 6751), 'torch.cat', 'th.cat', (['dec_ids'], {}), '(dec_ids)\n', (6742, 6751), True, 'import torch as th\n'), ((6789, 6805), 'torch.cat', 'th.cat', (['e2e_eids'], {}), '(e2e_eids)\n', (6795, 6805), True, 'import torch as th\n'), ((6813, 6829), 'torch.cat', 'th.cat', (['e2d_eids'], {}), '(e2d_eids)\n', (6819, 6829), True, 'import torch as th\n'), ((6837, 6853), 'torch.cat', 'th.cat', (['d2d_eids'], {}), '(d2d_eids)\n', (6843, 6853), True, 'import torch as th\n'), ((10759, 10770), 'torch.cat', 'th.cat', (['src'], {}), '(src)\n', (10765, 10770), True, 'import torch as th\n'), ((10772, 10787), 'torch.cat', 'th.cat', (['src_pos'], {}), '(src_pos)\n', (10778, 10787), True, 'import torch as th\n'), ((10816, 10827), 'torch.cat', 'th.cat', (['tgt'], {}), '(tgt)\n', (10822, 10827), True, 'import torch as th\n'), ((10829, 10844), 'torch.cat', 'th.cat', (['tgt_pos'], {}), '(tgt_pos)\n', (10835, 10844), True, 'import torch as th\n'), ((10925, 10940), 'torch.cat', 'th.cat', (['enc_ids'], {}), '(enc_ids)\n', (10931, 10940), True, 'import torch as th\n'), ((10949, 10964), 'torch.cat', 'th.cat', (['dec_ids'], {}), '(dec_ids)\n', (10955, 10964), True, 'import torch as th\n'), ((11002, 11018), 'torch.cat', 'th.cat', (['e2e_eids'], {}), '(e2e_eids)\n', (11008, 11018), True, 'import torch as th\n'), ((11026, 11042), 'torch.cat', 'th.cat', (['e2d_eids'], {}), '(e2d_eids)\n', (11032, 11042), True, 'import torch as th\n'), ((11050, 11066), 'torch.cat', 'th.cat', (['d2d_eids'], {}), '(d2d_eids)\n', (11056, 11066), True, 'import torch as th\n'), ((7094, 7125), 'torch.tensor', 'th.tensor', (["layer_eids['dep'][i]"], {}), "(layer_eids['dep'][i])\n", (7103, 7125), True, 'import torch as th\n'), ((11269, 11300), 'torch.tensor', 'th.tensor', (["layer_eids['dep'][i]"], {}), "(layer_eids['dep'][i])\n", (11278, 11300), True, 'import torch as th\n')]
import tensorflow as tf import prettytensor as pt import numpy as np import gym import math import random from collections import deque from agents import mixed_network, spaces, replay_buffer tensorType = tf.float32 """ Implements a Deep Deterministic Policy Gradient agent. Adjustable parameters: - Actor / Critic learning rates - Temporal Difference discount factor - Experience Replay buffer / batch sizes """ class DDPGAgent: """ Creates a new DDPG agent. Args: - actorGen and criticGen should be functions that create new neural networks with supplied Placeholder input Tensors. - state_shape will be the shape of the state input Placeholder. - action_shape should be the shape of the tensors output by the actor neural network. - buf_sz is the size of the agent's internal experience replay buffer. - batch_sz will be the size of each training batch (drawn from the replay buffer) """ def __init__(self, actorGen, criticGen, state_shape, action_shape, buf_sz=100000, batch_sz=64, critic_learning_rate=0.001, actor_learning_rate=0.0001, discount_factor=0.99, actor_mix_factor=0.001, critic_mix_factor=0.001, actor_gradient_clipping=None, critic_gradient_clipping=None): self.graph = tf.Graph() self.session = tf.Session(graph=self.graph) self.discount_factor = discount_factor self.replay_buf = deque(maxlen=buf_sz) self.batch_size = batch_sz self.state_shape = state_shape self.action_shape = action_shape self.__single_state_shape = self.state_shape[:] self.__single_state_shape[0] = 1 with self.graph.as_default(): self.state_in = tf.placeholder(tensorType, state_shape, name='state-in') self.action_in = tf.placeholder(tensorType, action_shape, name='action-in') with tf.variable_scope('critic'): self.critic = mixed_network.MixedNetwork(self.graph, self.session, tf.concat_v2([self.state_in, self.action_in], axis=1), criticGen, target_mix_factor=critic_mix_factor, prefix='critic/') self.critic_prediction = tf.placeholder(tensorType, [None]) self.critic_loss = tf.reduce_mean( tf.square( self.critic_prediction - tf.squeeze(self.critic.main_out) ) ) critic_optimizer = tf.train.AdamOptimizer(critic_learning_rate) if isinstance(critic_gradient_clipping, tuple): critic_gradients = critic_optimizer.compute_gradients(self.critic_loss, self.critic.main_parameters) clipped_grads = [ \ ( tf.clip_by_value(gv[0], critic_gradient_clipping[0], critic_gradient_clipping[1]), gv[1]) \ for gv in critic_gradients ] self.critic_optimize = critic_optimizer.apply_gradients(clipped_grads) else: self.critic_optimize = critic_optimizer.minimize(self.critic_loss, var_list=self.critic.main_parameters) # gradient of the critic network w.r.t. the actions, averaged over all (s,a) pairs in batch self.action_gradient = tf.div(tf.gradients(self.critic.main_out, self.action_in), tf.constant(self.batch_size, tensorType)) with tf.variable_scope('actor'): self.actor = mixed_network.MixedNetwork(self.graph, self.session, self.state_in, actorGen, prefix='actor/', target_mix_factor=actor_mix_factor) #self.aGrad_pl = tf.placeholder(tensorType, action_shape, name='action-gradient-placeholder') self.actor_gradients = tf.gradients(self.actor.main_out, self.actor.main_parameters, self.action_gradient) #self.actor_optimize = [p.assign(p + actor_learning_rate*g) \ #for p, g in zip(self.actor.main_parameters, self.actor_gradients)] #self.actor_optimize = tf.train.GradientDescentOptimizer(actor_learning_rate).apply_gradients( # zip(self.actor_gradients, self.actor.main_parameters) #) if isinstance(actor_gradient_clipping, tuple): self.actor_gradients = [tf.clip_by_value(g, actor_gradient_clipping[0], actor_gradient_clipping[1]) for g in self.actor_gradients] self.actor_gradients = [tf.negative(g) for g in self.actor_gradients] self.actor_optimize = tf.train.AdamOptimizer(actor_learning_rate).apply_gradients( zip(self.actor_gradients, self.actor.main_parameters) ) self.session.run(tf.global_variables_initializer()) def act(self, observation): return self.actor.get_main({ self.state_in: np.reshape(observation, self.__single_state_shape)}) def add_experience(self, state, action, reward, done, next_state): self.replay_buf.append( (state, action, reward, done, next_state) ) def train(self): sm = random.sample(self.replay_buf, min(len(self.replay_buf), self.batch_size)) state_shape = self.state_shape[:] action_shape = self.action_shape[:] state_shape[0] = action_shape[0] = len(sm) states = np.reshape([ ts[0] for ts in sm ], state_shape) actions = np.reshape([ ts[1] for ts in sm ], action_shape) rewards = np.reshape([ ts[2] for ts in sm ], [len(sm)]) term_state = np.reshape([ ts[3] for ts in sm ], [len(sm)]) next_states = np.reshape([ ts[4] for ts in sm ], state_shape) # Use target actor and critic networks to estimate TD targets target_a = np.reshape(self.actor.get_target({self.state_in:next_states}), action_shape) target_q = np.reshape(self.critic.get_target({ self.state_in:next_states, self.action_in:target_a }), [len(sm)]) td_targets = [] for i, t in enumerate(target_q): if term_state[i]: td_targets.append(rewards[i]) else: td_targets.append(rewards[i] + (self.discount_factor * t)) _, crit_loss, predicted_q = self.session.run([self.critic_optimize, self.critic_loss, self.critic.main_out], { self.state_in: states, self.action_in: actions, self.critic_prediction: np.squeeze(td_targets) }) net_actions = np.reshape(self.actor.get_main({self.state_in: states}), action_shape) self.session.run(self.actor_optimize, {self.state_in:states, self.action_in:net_actions}) #self.session.run(self.actor_optimize, {self.state_in:states, self.action_in:actions}) #actor_grad = self.session.run(self.actor_gradients, {self.state_in:states, self.action_in:net_actions})[0] #assert not np.isnan(np.sum(actor_grad)) return np.squeeze(predicted_q), crit_loss def update_targets(self): self.actor.update_target() self.critic.update_target()
[ "tensorflow.Graph", "agents.mixed_network.MixedNetwork", "collections.deque", "numpy.reshape", "tensorflow.variable_scope", "tensorflow.placeholder", "tensorflow.Session", "numpy.squeeze", "tensorflow.gradients", "tensorflow.global_variables_initializer", "tensorflow.negative", "tensorflow.constant", "tensorflow.clip_by_value", "tensorflow.train.AdamOptimizer", "tensorflow.concat_v2", "tensorflow.squeeze" ]
[((1300, 1310), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1308, 1310), True, 'import tensorflow as tf\n'), ((1334, 1362), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), '(graph=self.graph)\n', (1344, 1362), True, 'import tensorflow as tf\n'), ((1438, 1458), 'collections.deque', 'deque', ([], {'maxlen': 'buf_sz'}), '(maxlen=buf_sz)\n', (1443, 1458), False, 'from collections import deque\n'), ((5346, 5391), 'numpy.reshape', 'np.reshape', (['[ts[0] for ts in sm]', 'state_shape'], {}), '([ts[0] for ts in sm], state_shape)\n', (5356, 5391), True, 'import numpy as np\n'), ((5412, 5458), 'numpy.reshape', 'np.reshape', (['[ts[1] for ts in sm]', 'action_shape'], {}), '([ts[1] for ts in sm], action_shape)\n', (5422, 5458), True, 'import numpy as np\n'), ((5614, 5659), 'numpy.reshape', 'np.reshape', (['[ts[4] for ts in sm]', 'state_shape'], {}), '([ts[4] for ts in sm], state_shape)\n', (5624, 5659), True, 'import numpy as np\n'), ((1739, 1795), 'tensorflow.placeholder', 'tf.placeholder', (['tensorType', 'state_shape'], {'name': '"""state-in"""'}), "(tensorType, state_shape, name='state-in')\n", (1753, 1795), True, 'import tensorflow as tf\n'), ((1825, 1883), 'tensorflow.placeholder', 'tf.placeholder', (['tensorType', 'action_shape'], {'name': '"""action-in"""'}), "(tensorType, action_shape, name='action-in')\n", (1839, 1883), True, 'import tensorflow as tf\n'), ((6919, 6942), 'numpy.squeeze', 'np.squeeze', (['predicted_q'], {}), '(predicted_q)\n', (6929, 6942), True, 'import numpy as np\n'), ((1902, 1929), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""critic"""'], {}), "('critic')\n", (1919, 1929), True, 'import tensorflow as tf\n'), ((2273, 2307), 'tensorflow.placeholder', 'tf.placeholder', (['tensorType', '[None]'], {}), '(tensorType, [None])\n', (2287, 2307), True, 'import tensorflow as tf\n'), ((2467, 2511), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['critic_learning_rate'], {}), '(critic_learning_rate)\n', (2489, 2511), True, 'import tensorflow as tf\n'), ((3410, 3436), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""actor"""'], {}), "('actor')\n", (3427, 3436), True, 'import tensorflow as tf\n'), ((3467, 3601), 'agents.mixed_network.MixedNetwork', 'mixed_network.MixedNetwork', (['self.graph', 'self.session', 'self.state_in', 'actorGen'], {'prefix': '"""actor/"""', 'target_mix_factor': 'actor_mix_factor'}), "(self.graph, self.session, self.state_in,\n actorGen, prefix='actor/', target_mix_factor=actor_mix_factor)\n", (3493, 3601), False, 'from agents import mixed_network, spaces, replay_buffer\n'), ((3781, 3869), 'tensorflow.gradients', 'tf.gradients', (['self.actor.main_out', 'self.actor.main_parameters', 'self.action_gradient'], {}), '(self.actor.main_out, self.actor.main_parameters, self.\n action_gradient)\n', (3793, 3869), True, 'import tensorflow as tf\n'), ((4759, 4792), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4790, 4792), True, 'import tensorflow as tf\n'), ((4879, 4929), 'numpy.reshape', 'np.reshape', (['observation', 'self.__single_state_shape'], {}), '(observation, self.__single_state_shape)\n', (4889, 4929), True, 'import numpy as np\n'), ((6415, 6437), 'numpy.squeeze', 'np.squeeze', (['td_targets'], {}), '(td_targets)\n', (6425, 6437), True, 'import numpy as np\n'), ((2046, 2099), 'tensorflow.concat_v2', 'tf.concat_v2', (['[self.state_in, self.action_in]'], {'axis': '(1)'}), '([self.state_in, self.action_in], axis=1)\n', (2058, 2099), True, 'import tensorflow as tf\n'), ((3298, 3348), 'tensorflow.gradients', 'tf.gradients', (['self.critic.main_out', 'self.action_in'], {}), '(self.critic.main_out, self.action_in)\n', (3310, 3348), True, 'import tensorflow as tf\n'), ((3350, 3390), 'tensorflow.constant', 'tf.constant', (['self.batch_size', 'tensorType'], {}), '(self.batch_size, tensorType)\n', (3361, 3390), True, 'import tensorflow as tf\n'), ((4491, 4505), 'tensorflow.negative', 'tf.negative', (['g'], {}), '(g)\n', (4502, 4505), True, 'import tensorflow as tf\n'), ((4343, 4418), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['g', 'actor_gradient_clipping[0]', 'actor_gradient_clipping[1]'], {}), '(g, actor_gradient_clipping[0], actor_gradient_clipping[1])\n', (4359, 4418), True, 'import tensorflow as tf\n'), ((4576, 4619), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['actor_learning_rate'], {}), '(actor_learning_rate)\n', (4598, 4619), True, 'import tensorflow as tf\n'), ((2395, 2427), 'tensorflow.squeeze', 'tf.squeeze', (['self.critic.main_out'], {}), '(self.critic.main_out)\n', (2405, 2427), True, 'import tensorflow as tf\n'), ((2763, 2848), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['gv[0]', 'critic_gradient_clipping[0]', 'critic_gradient_clipping[1]'], {}), '(gv[0], critic_gradient_clipping[0],\n critic_gradient_clipping[1])\n', (2779, 2848), True, 'import tensorflow as tf\n')]
# -*- coding: utf-8 -*- from remi.gui import * from remi import start, App import cv2 import numpy import chdkptp import time import threading import rawpy class OpenCVVideoWidget(Image): def __init__(self, **kwargs): super(OpenCVVideoWidget, self).__init__("/%s/get_image_data" % id(self), **kwargs) self.frame_index = 0 self.frame = numpy.full((480, 720,3),155, dtype=numpy.uint8) def update(self, app_instance): self.frame_index = numpy.random.randint(1e8) app_instance.execute_javascript(""" var url = '/%(id)s/get_image_data?index=%(frame_index)s'; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob' xhr.onload = function(e){ urlCreator = window.URL || window.webkitURL; urlCreator.revokeObjectURL(document.getElementById('%(id)s').src); imageUrl = urlCreator.createObjectURL(this.response); document.getElementById('%(id)s').src = imageUrl; } xhr.send(); """ % {'id': id(self), 'frame_index':self.frame_index}) def get_image_data(self, index=0): ret, jpeg = cv2.imencode('.jpeg', self.frame) if ret: headers = {'Content-type': 'image/jpeg'} return [jpeg.tostring(), headers] return None, None class M10GUI(App): def __init__(self, *args, **kwargs): if not 'editing_mode' in kwargs.keys(): super(M10GUI, self).__init__(*args, static_file_path={'my_res':'./res/'}) self.stop_event = threading.Event() self.stop_event.clear() def log_message(self, *args, **kwargs): pass def idle(self): if self.live_view_check.get_value(): vp, bm = self.get_live_view() self.image.frame = numpy.clip(vp.astype(numpy.uint16)+ bm.astype(numpy.uint16),0,255).astype(numpy.uint8) self.image.update(self) if time.time()-self.timer > 10: try: self.temperature_label.set_text('Temp (\xb0C): '+str(self.camera.lua_execute('get_temperature(1)'))) self.battery_label.set_text('Batt (V): '+str(self.camera.lua_execute('get_vbatt()')/1000.)) except: None self.timer = time.time() pass def main(self): self.timer = time.time() return M10GUI.construct_ui(self) def on_close(self): self.stop_event.set() super(M10GUI, self).on_close() @staticmethod def construct_ui(self): container = GridBox(width='100%', height='100%', style={'margin':'0px auto', "background-color":"#d5d0c7"}) container.attributes.update({"class":"Widget","editor_constructor":"()","editor_varname":"container","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Widget"}) container.set_from_asciiart(""" | | | | iso_label | shutter_label | pics_label | time_label | live_view_label | zoom_label | | shoot_button | video_button | stop_button | iso_menu | shutter_value | pics_value | time_value | live_view_check | zoom_menu | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | image | image | image | image | image | image | image | image | image | | lua_label | lua_label | lua_value | lua_value | lua_value | lua_value | lua_value | lua_value | lua_value | | status_label | status_label | status_label | status_label | status_label | status_label | temperature_label | battery_label | connect_button | """, 1, 1) self.shoot_button = Button('Shoot') self.shoot_button.set_enabled(False) self.shoot_button.style.update({"width":"100%","height":"100%"}) self.shoot_button.attributes.update({"class":"Button","editor_constructor":"('Shoot')","editor_varname":"shoot_button","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Button"}) self.shoot_button.onclick.do(self.start_shoot) self.video_button = Button('Video') self.video_button.set_enabled(False) self.video_button.style.update({"width":"100%","height":"100%"}) self.video_button.attributes.update({"class":"Button","editor_constructor":"('Video')","editor_varname":"video_button","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Button"}) self.video_button.onclick.do(self.start_video) self.stop_button = Button('Stop') self.stop_button.set_enabled(False) self.stop_button.style.update({"width":"100%","height":"100%"}) self.stop_button.attributes.update({"class":"Button","editor_constructor":"('Stop')","editor_varname":"stop_button","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Button"}) self.stop_button.onclick.do(self.stop_action) self.iso_menu = DropDown.new_from_list(('Auto','100','125','160','200','250','320','400', '500','640','800','1000','1250','1600','2000','2500', '3200','4000','5000','6400','8000','10000','12800')) self.iso_menu.set_enabled(False) self.iso_menu.set_value('Auto') self.iso_menu.attributes.update({"class":"DropDown","editor_constructor":"()","editor_varname":"iso_menu","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"DropDown"}) self.iso_menu.onchange.do(self.set_iso) self.shutter_value = TextInput(True,'') self.shutter_value.set_enabled(False) self.shutter_value.attributes.update({"class":"TextInput","autocomplete":"off","editor_constructor":"(False,'')","editor_varname":"shutter_value","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"TextInput"}) self.shutter_value.onchange.do(self.change_shutter) iso_label = Label('ISO') iso_label.attributes.update({"class":"Label","editor_constructor":"('ISO')","editor_varname":"iso_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) shutter_label = Label('Shutter') shutter_label.attributes.update({"class":"Label","editor_constructor":"('Shutter')","editor_varname":"shutter_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.pics_value = TextInput(True,'') self.pics_value.set_enabled(False) self.pics_value.attributes.update({"class":"TextInput","autocomplete":"off","editor_constructor":"(False,'')","editor_varname":"pics_value","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"TextInput"}) pics_label = Label('Pics') pics_label.attributes.update({"class":"Label","editor_constructor":"('Pics')","editor_varname":"pics_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.time_value = TextInput(True,'') self.time_value.set_enabled(False) self.time_value.attributes.update({"class":"TextInput","autocomplete":"off","editor_constructor":"(False,'')","editor_varname":"time_value","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"TextInput"}) time_label = Label('Hold') time_label.attributes.update({"class":"Label","editor_constructor":"('Time')","editor_varname":"time_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.live_view_check = CheckBox(False,'') self.live_view_check.set_enabled(False) self.live_view_check.onchange.do(self.toggle_live) self.live_view_check.attributes.update({"class":"checkbox","value":"","type":"checkbox","autocomplete":"off","editor_constructor":"(False,'')","editor_varname":"live_view_check","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"CheckBox"}) live_view_label = Label('Live') live_view_label.attributes.update({"class":"Label","editor_constructor":"('Live')","editor_varname":"live_view_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.zoom_menu = DropDown.new_from_list(('1', '5', '10')) self.zoom_menu.set_enabled(False) self.zoom_menu.set_value('1') self.zoom_menu.attributes.update({"class":"DropDown","editor_constructor":"()","editor_varname":"zoom_menu","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"DropDown"}) self.zoom_menu.onchange.do(self.change_zoom) zoom_label = Label('Zoom') zoom_label.attributes.update({"class":"Label","editor_constructor":"('Zoom')","editor_varname":"zoom_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.image = OpenCVVideoWidget(width='100%', height='100%') self.image.attributes.update({"class":"Image","width":"720","height":"480","editor_constructor":"(720,480)","editor_varname":"image","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Image"}) infos_label = Label('Infos') infos_label.attributes.update({"class":"Label","editor_constructor":"('Infos')","editor_varname":"infos_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.temperature_label = Label('Temp (\xb0C):') self.temperature_label.attributes.update({"class":"Label","editor_constructor":"('Temp (ºC):')","editor_varname":"temperature_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.battery_label = Label('Batt (V):') self.battery_label.attributes.update({"class":"Label","editor_constructor":"('Batt (V):')","editor_varname":"battery_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.connect_button = Button('Connect') self.connect_button.style.update({"width":"100%","height":"100%"}) self.connect_button.attributes.update({"class":"Button","editor_constructor":"('Connect')","editor_varname":"connect_button","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Button"}) self.connect_button.onclick.do(self.init_camera) lua_label = Label('Lua Execute:') lua_label.attributes.update({"class":"Label","editor_constructor":"('Lua Execute:')","editor_varname":"lua_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) self.lua_value = TextInput(True,'') self.lua_value.set_enabled(False) self.lua_value.attributes.update({"class":"TextInput","autocomplete":"off","editor_constructor":"(False,'')","editor_varname":"lua_value","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"TextInput"}) self.lua_value.onchange.do(self.exec_lua) self.status_label = Label('Camera not connected') self.status_label.attributes.update({"class":"Label","editor_constructor":"('')","editor_varname":"status_label","editor_tag_type":"widget","editor_newclass":"False","editor_baseclass":"Label"}) container.append({'shoot_button':self.shoot_button, 'video_button':self.video_button, 'stop_button':self.stop_button, 'iso_menu':self.iso_menu, 'shutter_value':self.shutter_value, 'iso_label':iso_label, 'shutter_label':shutter_label, 'pics_value':self.pics_value, 'pics_label':pics_label, 'time_value':self.time_value, 'time_label':time_label, 'live_view_check':self.live_view_check, 'live_view_label':live_view_label, 'zoom_menu':self.zoom_menu, 'zoom_label':zoom_label, 'image':self.image, 'temperature_label':self.temperature_label, 'battery_label':self.battery_label, 'connect_button':self.connect_button, 'lua_label':lua_label, 'lua_value':self.lua_value, 'status_label':self.status_label}) self.container = container return self.container def set_status_label(self, text): with self.update_lock: self.status_label.set_text(text) ##### Here the GUI is over and starts the camera def init_camera(self, widget): def erase_ok(widget): try: device=chdkptp.list_devices() self.camera=chdkptp.ChdkDevice(device[0]) except: self.status_label.set_text('Error: camera not connected') return self.camera.switch_mode('record') self.camera.lua_execute('set_backlight(0)') self.camera.lua_execute('call_event_proc("UI.CreatePublic")') self.purge_files() self.status_label.set_text('Camera connected') self.connect_button.set_enabled(False) self.iso_menu.set_enabled(True) self.shutter_value.set_enabled(True) self.pics_value.set_enabled(True) self.shoot_button.set_enabled(True) self.video_button.set_enabled(True) self.live_view_check.set_enabled(True) self.lua_value.set_enabled(True) self.iso_menu.set_value(self.get_iso()) self.shutter_value.set_value(str(self.get_camera_shutter_time())) self.pics_value.set_value('1') if self.camera.lua_execute('get_drive_mode()') == 1: if float(self.shutter_value.get_value()) < 1: self.time_value.set_enabled(True) self.time_value.set_value('0') else: self.time_value.set_value('0') self.temperature_label.set_text('Temp (\xb0C): '+str(self.camera.lua_execute('get_temperature(1)'))) self.battery_label.set_text('Batt (V): '+str(self.camera.lua_execute('get_vbatt()')/1000.)) erase_dialog=GenericDialog(title='WARNING',message='All your data on the camera will be erased!') erase_dialog.style.update({"margin":"0px","width":"500px","height":"100px","top":"10px","left":"10px","position":"absolute","overflow":"auto"}) erase_dialog.show(self) erase_dialog.confirm_dialog.do(erase_ok) def toggle_live(self, widget, value): if self.live_view_check.get_value(): self.zoom_menu.set_enabled(True) else: self.zoom_menu.set_enabled(False) def get_iso(self): return self.camera.lua_execute('get_iso_mode()') def set_iso(self, widget, iso): iso = self.iso_menu.get_value() if iso == 'Auto': iso='0' self.camera.lua_execute('set_iso_mode('+iso+')') self.camera.lua_execute('press("shoot_half")') def get_camera_shutter_time(self): time = self.camera.lua_execute('tv96_to_usec(get_user_tv96())') if time < 1000000: return time/1000000. else: return time/1000000 def change_shutter(self, widget, value): try: time=int(float(self.shutter_value.get_text())*1000000) except: self.status_label.set_text('Error: shutter time must be a number') return if time > 32000000: time=32000000 if time < 250: time=250 self.camera.lua_execute('set_user_tv96(usec_to_tv96('+str(time)+'))\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.text_line_message='Done' def purge_files(self): for i in self.list_files(): self.camera.delete_files(i) def list_files(self): file_list=[] for i in self.camera.list_files(): if 'CANONMSC' not in i: file_list+=self.camera.list_files(i[:-1]) return file_list def change_zoom(self, widget, zoom): zoom = int(self.zoom_menu.get_value()) if zoom==1: self.camera.lua_execute('post_levent_to_ui(0x11ea,0)\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.iso_menu.set_enabled(True) self.shutter_value.set_enabled(True) if zoom==5: self.camera.lua_execute('post_levent_to_ui(0x11ea,0)\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.camera.lua_execute('post_levent_to_ui(0x11ea,1)\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.iso_menu.set_enabled(False) self.shutter_value.set_enabled(False) if zoom==10: self.camera.lua_execute('post_levent_to_ui(0x11ea,1)\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'call_event_proc("PTM_SetCurrentItem",0x80b8,2)\n' 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.iso_menu.set_enabled(False) self.shutter_value.set_enabled(False) def start_shoot(self, widget): try: float(self.shutter_value.get_value()) float(self.time_value.get_value()) int(self.pics_value.get_value()) except: return self.shoot_button.set_enabled(False) self.video_button.set_enabled(False) self.stop_button.set_enabled(True) self.live_view_check.set_value(False) self.live_view_check.set_enabled(False) tr = threading.Thread(target=self.shoot_pic, args=(self.stop_event,)) tr.start() def start_video(self, widget): try: float(self.shutter_value.get_value()) float(self.time_value.get_value()) int(self.pics_value.get_value()) except: return if float(self.shutter_value.get_value()) < 1: self.status_label.set_text('Video length must be at least 1 second') return self.shoot_button.set_enabled(False) self.video_button.set_enabled(False) self.stop_button.set_enabled(True) self.live_view_check.set_value(False) self.live_view_check.set_enabled(False) tr = threading.Thread(target=self.shoot_video, args=(self.stop_event,)) tr.start() def shoot_pic(self, stop_event): record_counter = 0 timer=int(time.time()) shutter_time=str(int(numpy.rint(float(self.shutter_value.get_value())*1000000))) while record_counter < int(self.pics_value.get_value()) and not stop_event.isSet(): if float(self.shutter_value.get_value()) >= 1 or float(self.time_value.get_value()) == 0: self.camera.lua_execute('set_tv96_direct(usec_to_tv96('+shutter_time+'))\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'press("shoot_full")\n' \ 'return') else: self.camera.lua_execute('set_tv96_direct(usec_to_tv96('+shutter_time+'))\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'press("shoot_full")\n' \ 'sleep('+str(int(numpy.rint(float(self.time_value.get_value())*1000)))+')\n' \ 'release("shoot_full")\n' \ 'return') if float(self.shutter_value.get_value()) <= 1: self.status_label.set_text('Photo '+str(record_counter+1)+' of '+str(self.pics_value.get_value())) time.sleep(float(self.shutter_value.get_value())) else: seconds=0 while seconds<float(self.shutter_value.get_value()): if stop_event.isSet(): self.set_status_label('Aborting, waiting '+str(int(float(self.shutter_value.get_value())-seconds))+' seconds for the last photo') else: self.set_status_label('Photo '+str(record_counter+1)+' of '+str(self.pics_value.get_value())+' due in '+str(int(float(self.shutter_value.get_value())-seconds))+' seconds') time.sleep(1) seconds+=1 self.set_status_label('Downloading photos from the camera') while len(self.list_files()) == 0: time.sleep(1) for i in self.list_files(): localfile=i.split('/')[3] self.camera.download_file(i,localfile) if 'JPG' in localfile: self.image.frame=cv2.resize(cv2.imread(localfile.split('.')[0]+'.JPG'), (720, 480)) else: raw=rawpy.imread(localfile.split('.')[0]+'.CR2') self.image.frame=cv2.resize(raw.postprocess(half_size=True, user_flip=False)[...,::-1], (720, 480)) raw.close() with self.update_lock: self.image.update(self) self.purge_files() record_counter += 1 stop_event.clear() self.set_status_label('Done') with self.update_lock: self.shoot_button.set_enabled(True) self.video_button.set_enabled(True) self.stop_button.set_enabled(False) self.live_view_check.set_enabled(True) def shoot_video(self, stop_event): record_counter = 0 while record_counter < int(self.pics_value.get_value()) and not stop_event.isSet(): seconds=0 self.camera.lua_execute('press("video")') while seconds<float(self.shutter_value.get_value()) and not stop_event.isSet(): self.set_status_label('Video '+str(record_counter+1)+' of '+str(self.pics_value.get_value())+' due in '+str(int(float(self.shutter_value.get_value())-seconds))+' seconds') time.sleep(1) seconds+=1 self.camera.lua_execute('press("video")') self.set_status_label('Downloading video from the camera') while self.camera.lua_execute('get_movie_status()') != 1: time.sleep(1) for i in self.list_files(): localfile=i.split('/')[3] self.camera.download_file(i,localfile) self.purge_files() record_counter += 1 stop_event.clear() self.set_status_label('Done') with self.update_lock: self.shoot_button.set_enabled(True) self.video_button.set_enabled(True) self.stop_button.set_enabled(False) self.live_view_check.set_enabled(True) def stop_action(self, widget): self.status_label.set_text('Abotring...') self.stop_event.set() def get_live_view(self): self.camera._lua.eval(""" function() status, err = con:live_dump_start('/tmp/live_view_frame') for i=1,1 do status, err = con:live_get_frame(29) status, err = con:live_dump_frame() end status, err = con:live_dump_end() return err end """)() lv_aspect_ratio = {0:'LV_ASPECT_4_3', 1:'LV_ASPECT_16_9', 2:'LV_ASPECT_3_2'} fb_type = {0:12, 1:8, 2:16, 3:16, 4:8 } file_header_dtype = numpy.dtype([('magic','int32'),('header_size', 'int32'),('version_major', 'int32'),('version_minor','int32')]) frame_length_dtype = numpy.dtype([('length','int32')]) frame_header_dtype = numpy.dtype([('version_major','int32'),('version_minor', 'int32'),('lv_aspect_ratio', 'int32'), ('palette_type','int32'), ('palette_data_start','int32'), ('vp_desc_start','int32'), ('bm_desc_start','int32'), ('bmo_desc_start','int32')]) block_description_dtype = numpy.dtype([('fb_type','int32'),('data_start','int32'),('buffer_width','int32'), ('visible_width','int32'),('visible_height','int32'),('margin_left','int32'), ('margin_top','int32'), ('margin_right','int32'),('margin_bottom','int32')]) myFile = open('/tmp/live_view_frame','r') file_header=numpy.fromfile(myFile, dtype=file_header_dtype, count=1) frame_length=numpy.fromfile(myFile, dtype=frame_length_dtype, count=1) frame_header=numpy.fromfile(myFile, dtype=frame_header_dtype, count=1) vp_description=numpy.fromfile(myFile, dtype=block_description_dtype, count=1) vp_bpp = fb_type[int(vp_description['fb_type'])] vp_frame_size=vp_description['buffer_width']*vp_description['visible_height']*vp_bpp/8 # in byte ! vp_frame_size = int(vp_frame_size[0]) bm_description=numpy.fromfile(myFile, dtype=block_description_dtype, count=1) bm_bpp = fb_type[int(bm_description['fb_type'])] bm_frame_size=bm_description['buffer_width']*bm_description['visible_height']*bm_bpp/8 bm_frame_size = int(bm_frame_size[0]) bmo_description=numpy.fromfile(myFile, dtype=block_description_dtype, count=1) bmo_bpp = fb_type[int(bmo_description['fb_type'])] bmo_frame_size=bmo_description['buffer_width']*bmo_description['visible_height']*bmo_bpp/8 bmo_frame_size = int(bmo_frame_size[0]) if vp_description['data_start'] > 0: vp_raw_img=numpy.fromfile(myFile, dtype=numpy.uint8, count=vp_frame_size) y=vp_raw_img[1::2].reshape(int(vp_description['visible_height']),int(vp_description['buffer_width'])) u=numpy.empty(vp_frame_size//2, dtype=numpy.uint8) u[0::2]=vp_raw_img[0::4] u[1::2]=vp_raw_img[0::4] u=u.reshape(int(vp_description['visible_height']),int(vp_description['buffer_width'])) v=numpy.empty(vp_frame_size//2, dtype=numpy.uint8) v[0::2]=vp_raw_img[2::4] v[1::2]=vp_raw_img[2::4] v=v.reshape(int(vp_description['visible_height']),int(vp_description['buffer_width'])) raw_yuv=numpy.dstack((y,u,v))[:,0:int(vp_description['visible_width']),:] vp_rgb=cv2.cvtColor(raw_yuv, cv2.COLOR_YUV2BGR) if bm_description['data_start'] > 0: bm_raw_img=numpy.fromfile(myFile, dtype=numpy.uint8, count=bm_frame_size) y=bm_raw_img[1::2].reshape(int(bm_description['visible_height']),int(bm_description['buffer_width'])) u=numpy.empty(bm_frame_size//2, dtype=numpy.uint8) u[0::2]=bm_raw_img[0::4] u[1::2]=bm_raw_img[0::4] u=u.reshape(int(bm_description['visible_height']),int(bm_description['buffer_width'])) v=numpy.empty(bm_frame_size//2, dtype=numpy.uint8) v[0::2]=bm_raw_img[2::4] v[1::2]=bm_raw_img[2::4] v=v.reshape(int(bm_description['visible_height']),int(bm_description['buffer_width'])) raw_yuv=numpy.dstack((y,u,v))[:,0:int(bm_description['visible_width']),:] bm_rgb=cv2.cvtColor(raw_yuv, cv2.COLOR_YUV2BGR) if bmo_description['data_start'] >0: bmo_raw_img=numpy.fromfile(myFile, dtype=numpy.int32, count=bmo_frame_size) myFile.close() if vp_rgb.shape[0]==408: # Workaround for video mode extension=numpy.zeros((480,720,3)) extension[36:444, :, :]=vp_rgb # (480-408)/2:480-(480-408)/2, :, : vp_rgb=extension return vp_rgb, bm_rgb def exec_lua(self, widget, value): try: self.camera.lua_execute(str(self.lua_value.get_value())+'\n' \ 'press("shoot_half")\n' \ 'repeat\n' \ ' sleep(10)\n' \ 'until get_shooting()\n' \ 'return') self.status_label.set_text('Done') except: self.status_label.set_text('Error executing LUA') if __name__ == "__main__": start(M10GUI, address='0.0.0.0', port=8081, multiple_instance=False, enable_file_cache=True, start_browser=False, debug=False, update_interval = 0.01)
[ "numpy.dstack", "numpy.fromfile", "remi.start", "cv2.imencode", "chdkptp.ChdkDevice", "time.sleep", "threading.Event", "numpy.random.randint", "numpy.zeros", "numpy.empty", "cv2.cvtColor", "numpy.full", "numpy.dtype", "time.time", "threading.Thread", "chdkptp.list_devices" ]
[((31139, 31295), 'remi.start', 'start', (['M10GUI'], {'address': '"""0.0.0.0"""', 'port': '(8081)', 'multiple_instance': '(False)', 'enable_file_cache': '(True)', 'start_browser': '(False)', 'debug': '(False)', 'update_interval': '(0.01)'}), "(M10GUI, address='0.0.0.0', port=8081, multiple_instance=False,\n enable_file_cache=True, start_browser=False, debug=False,\n update_interval=0.01)\n", (31144, 31295), False, 'from remi import start, App\n'), ((365, 414), 'numpy.full', 'numpy.full', (['(480, 720, 3)', '(155)'], {'dtype': 'numpy.uint8'}), '((480, 720, 3), 155, dtype=numpy.uint8)\n', (375, 414), False, 'import numpy\n'), ((477, 510), 'numpy.random.randint', 'numpy.random.randint', (['(100000000.0)'], {}), '(100000000.0)\n', (497, 510), False, 'import numpy\n'), ((1223, 1256), 'cv2.imencode', 'cv2.imencode', (['""".jpeg"""', 'self.frame'], {}), "('.jpeg', self.frame)\n", (1235, 1256), False, 'import cv2\n'), ((1619, 1636), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1634, 1636), False, 'import threading\n'), ((2409, 2420), 'time.time', 'time.time', ([], {}), '()\n', (2418, 2420), False, 'import time\n'), ((20296, 20360), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.shoot_pic', 'args': '(self.stop_event,)'}), '(target=self.shoot_pic, args=(self.stop_event,))\n', (20312, 20360), False, 'import threading\n'), ((21000, 21066), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.shoot_video', 'args': '(self.stop_event,)'}), '(target=self.shoot_video, args=(self.stop_event,))\n', (21016, 21066), False, 'import threading\n'), ((26509, 26628), 'numpy.dtype', 'numpy.dtype', (["[('magic', 'int32'), ('header_size', 'int32'), ('version_major', 'int32'),\n ('version_minor', 'int32')]"], {}), "([('magic', 'int32'), ('header_size', 'int32'), ('version_major',\n 'int32'), ('version_minor', 'int32')])\n", (26520, 26628), False, 'import numpy\n'), ((26649, 26683), 'numpy.dtype', 'numpy.dtype', (["[('length', 'int32')]"], {}), "([('length', 'int32')])\n", (26660, 26683), False, 'import numpy\n'), ((26712, 26971), 'numpy.dtype', 'numpy.dtype', (["[('version_major', 'int32'), ('version_minor', 'int32'), ('lv_aspect_ratio',\n 'int32'), ('palette_type', 'int32'), ('palette_data_start', 'int32'), (\n 'vp_desc_start', 'int32'), ('bm_desc_start', 'int32'), (\n 'bmo_desc_start', 'int32')]"], {}), "([('version_major', 'int32'), ('version_minor', 'int32'), (\n 'lv_aspect_ratio', 'int32'), ('palette_type', 'int32'), (\n 'palette_data_start', 'int32'), ('vp_desc_start', 'int32'), (\n 'bm_desc_start', 'int32'), ('bmo_desc_start', 'int32')])\n", (26723, 26971), False, 'import numpy\n'), ((27007, 27270), 'numpy.dtype', 'numpy.dtype', (["[('fb_type', 'int32'), ('data_start', 'int32'), ('buffer_width', 'int32'),\n ('visible_width', 'int32'), ('visible_height', 'int32'), ('margin_left',\n 'int32'), ('margin_top', 'int32'), ('margin_right', 'int32'), (\n 'margin_bottom', 'int32')]"], {}), "([('fb_type', 'int32'), ('data_start', 'int32'), ('buffer_width',\n 'int32'), ('visible_width', 'int32'), ('visible_height', 'int32'), (\n 'margin_left', 'int32'), ('margin_top', 'int32'), ('margin_right',\n 'int32'), ('margin_bottom', 'int32')])\n", (27018, 27270), False, 'import numpy\n'), ((27340, 27396), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'file_header_dtype', 'count': '(1)'}), '(myFile, dtype=file_header_dtype, count=1)\n', (27354, 27396), False, 'import numpy\n'), ((27418, 27475), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'frame_length_dtype', 'count': '(1)'}), '(myFile, dtype=frame_length_dtype, count=1)\n', (27432, 27475), False, 'import numpy\n'), ((27497, 27554), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'frame_header_dtype', 'count': '(1)'}), '(myFile, dtype=frame_header_dtype, count=1)\n', (27511, 27554), False, 'import numpy\n'), ((27578, 27640), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'block_description_dtype', 'count': '(1)'}), '(myFile, dtype=block_description_dtype, count=1)\n', (27592, 27640), False, 'import numpy\n'), ((27875, 27937), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'block_description_dtype', 'count': '(1)'}), '(myFile, dtype=block_description_dtype, count=1)\n', (27889, 27937), False, 'import numpy\n'), ((28161, 28223), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'block_description_dtype', 'count': '(1)'}), '(myFile, dtype=block_description_dtype, count=1)\n', (28175, 28223), False, 'import numpy\n'), ((2338, 2349), 'time.time', 'time.time', ([], {}), '()\n', (2347, 2349), False, 'import time\n'), ((21169, 21180), 'time.time', 'time.time', ([], {}), '()\n', (21178, 21180), False, 'import time\n'), ((28499, 28561), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'numpy.uint8', 'count': 'vp_frame_size'}), '(myFile, dtype=numpy.uint8, count=vp_frame_size)\n', (28513, 28561), False, 'import numpy\n'), ((28690, 28740), 'numpy.empty', 'numpy.empty', (['(vp_frame_size // 2)'], {'dtype': 'numpy.uint8'}), '(vp_frame_size // 2, dtype=numpy.uint8)\n', (28701, 28740), False, 'import numpy\n'), ((28926, 28976), 'numpy.empty', 'numpy.empty', (['(vp_frame_size // 2)'], {'dtype': 'numpy.uint8'}), '(vp_frame_size // 2, dtype=numpy.uint8)\n', (28937, 28976), False, 'import numpy\n'), ((29253, 29293), 'cv2.cvtColor', 'cv2.cvtColor', (['raw_yuv', 'cv2.COLOR_YUV2BGR'], {}), '(raw_yuv, cv2.COLOR_YUV2BGR)\n', (29265, 29293), False, 'import cv2\n'), ((29362, 29424), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'numpy.uint8', 'count': 'bm_frame_size'}), '(myFile, dtype=numpy.uint8, count=bm_frame_size)\n', (29376, 29424), False, 'import numpy\n'), ((29553, 29603), 'numpy.empty', 'numpy.empty', (['(bm_frame_size // 2)'], {'dtype': 'numpy.uint8'}), '(bm_frame_size // 2, dtype=numpy.uint8)\n', (29564, 29603), False, 'import numpy\n'), ((29789, 29839), 'numpy.empty', 'numpy.empty', (['(bm_frame_size // 2)'], {'dtype': 'numpy.uint8'}), '(bm_frame_size // 2, dtype=numpy.uint8)\n', (29800, 29839), False, 'import numpy\n'), ((30116, 30156), 'cv2.cvtColor', 'cv2.cvtColor', (['raw_yuv', 'cv2.COLOR_YUV2BGR'], {}), '(raw_yuv, cv2.COLOR_YUV2BGR)\n', (30128, 30156), False, 'import cv2\n'), ((30226, 30289), 'numpy.fromfile', 'numpy.fromfile', (['myFile'], {'dtype': 'numpy.int32', 'count': 'bmo_frame_size'}), '(myFile, dtype=numpy.int32, count=bmo_frame_size)\n', (30240, 30289), False, 'import numpy\n'), ((30396, 30422), 'numpy.zeros', 'numpy.zeros', (['(480, 720, 3)'], {}), '((480, 720, 3))\n', (30407, 30422), False, 'import numpy\n'), ((2001, 2012), 'time.time', 'time.time', ([], {}), '()\n', (2010, 2012), False, 'import time\n'), ((14060, 14082), 'chdkptp.list_devices', 'chdkptp.list_devices', ([], {}), '()\n', (14080, 14082), False, 'import chdkptp\n'), ((14111, 14140), 'chdkptp.ChdkDevice', 'chdkptp.ChdkDevice', (['device[0]'], {}), '(device[0])\n', (14129, 14140), False, 'import chdkptp\n'), ((23568, 23581), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (23578, 23581), False, 'import time\n'), ((25043, 25056), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (25053, 25056), False, 'import time\n'), ((25295, 25308), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (25305, 25308), False, 'import time\n'), ((29168, 29191), 'numpy.dstack', 'numpy.dstack', (['(y, u, v)'], {}), '((y, u, v))\n', (29180, 29191), False, 'import numpy\n'), ((30031, 30054), 'numpy.dstack', 'numpy.dstack', (['(y, u, v)'], {}), '((y, u, v))\n', (30043, 30054), False, 'import numpy\n'), ((23387, 23400), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (23397, 23400), False, 'import time\n')]
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import multiprocessing import numpy as np import os import torch import triton_python_backend_utils as pb_utils from torch.utils.dlpack import to_dlpack, from_dlpack from swig_decoders import ctc_beam_search_decoder_batch, Scorer, map_batch class WenetModel(object): def __init__(self, model_config, device): params = self.parse_model_parameters(model_config) self.device = device print("Using device", device) print("Successfully load model !") # load vocabulary ret = self.load_vocab(params["vocab_path"]) self.id2vocab, self.vocab, space_id, blank_id, sos_eos = ret self.space_id = space_id if space_id else -1 self.blank_id = blank_id if blank_id else 0 self.eos = self.sos = sos_eos if sos_eos else len(self.vocab) - 1 print("Successfully load vocabulary !") self.params = params # beam search setting self.beam_size = params.get("beam_size") self.cutoff_prob = params.get("cutoff_prob") # language model lm_path = params.get("lm_path", None) alpha, beta = params.get('alpha'), params.get('beta') self.scorer = None if os.path.exists(lm_path): self.scorer = Scorer(alpha, beta, lm_path, self.vocab) self.bidecoder = params.get('bidecoder') # rescore setting self.rescoring = params.get("rescoring", 0) print("Using rescoring:", bool(self.rescoring)) print("Successfully load all parameters!") self.dtype = torch.float16 def generate_init_cache(self): encoder_out = None return encoder_out def load_vocab(self, vocab_file): """ load lang_char.txt """ id2vocab = {} space_id, blank_id, sos_eos = None, None, None with open(vocab_file, "r", encoding="utf-8") as f: for line in f: line = line.strip() char, id = line.split() id2vocab[int(id)] = char if char == " ": space_id = int(id) elif char == "<blank>": blank_id = int(id) elif char == "<sos/eos>": sos_eos = int(id) vocab = [0] * len(id2vocab) for id, char in id2vocab.items(): vocab[id] = char return (id2vocab, vocab, space_id, blank_id, sos_eos) def parse_model_parameters(self, model_parameters): model_p = {"beam_size": 10, "cutoff_prob": 0.999, "vocab_path": None, "lm_path": None, "alpha": 2.0, "beta": 1.0, "rescoring": 0, "bidecoder": 1} # get parameter configurations for li in model_parameters.items(): key, value = li true_value = value["string_value"] if key not in model_p: continue key_type = type(model_p[key]) if key_type == type(None): model_p[key] = true_value else: model_p[key] = key_type(true_value) assert model_p["vocab_path"] is not None return model_p def infer(self, batch_log_probs, batch_log_probs_idx, seq_lens, rescore_index, batch_states): """ batch_states = [trieVector, batch_start, batch_encoder_hist, cur_encoder_out] """ trie_vector, batch_start, batch_encoder_hist, cur_encoder_out = batch_states num_processes = min(multiprocessing.cpu_count(), len(batch_log_probs)) score_hyps = self.batch_ctc_prefix_beam_search_cpu(batch_log_probs, batch_log_probs_idx, seq_lens, trie_vector, batch_start, self.beam_size, self.blank_id, self.space_id, self.cutoff_prob, num_processes, self.scorer) if self.rescoring and len(rescore_index) != 0: # find the end of sequence rescore_encoder_hist = [] rescore_encoder_lens = [] rescore_hyps = [] res_idx = list(rescore_index.keys()) max_length = -1 for idx in res_idx: hist_enc = batch_encoder_hist[idx] if hist_enc is None: cur_enc = cur_encoder_out[idx] else: cur_enc = torch.cat([hist_enc, cur_encoder_out[idx]], axis=0) rescore_encoder_hist.append(cur_enc) cur_mask_len = int(len(hist_enc) + seq_lens[idx]) rescore_encoder_lens.append(cur_mask_len) rescore_hyps.append(score_hyps[idx]) if cur_enc.shape[0] > max_length: max_length = cur_enc.shape[0] best_index = self.batch_rescoring(rescore_hyps, rescore_encoder_hist, rescore_encoder_lens, max_length) best_sent = [] j = 0 for idx, li in enumerate(score_hyps): if idx in rescore_index and self.rescoring: best_sent.append(li[best_index[j]][1]) j += 1 else: best_sent.append(li[0][1]) final_result = map_batch(best_sent, self.vocab, num_processes) return final_result, cur_encoder_out def batch_ctc_prefix_beam_search_cpu(self, batch_log_probs_seq, batch_log_probs_idx, batch_len, batch_root, batch_start, beam_size, blank_id, space_id, cutoff_prob, num_processes, scorer): """ Return: Batch x Beam_size elements, each element is a tuple (score, list of ids), """ batch_len_list = batch_len batch_log_probs_seq_list = [] batch_log_probs_idx_list = [] for i in range(len(batch_len_list)): cur_len = int(batch_len_list[i]) batch_log_probs_seq_list.append(batch_log_probs_seq[i][0:cur_len].tolist()) batch_log_probs_idx_list.append(batch_log_probs_idx[i][0:cur_len].tolist()) score_hyps = ctc_beam_search_decoder_batch(batch_log_probs_seq_list, batch_log_probs_idx_list, batch_root, batch_start, beam_size, num_processes, blank_id, space_id, cutoff_prob, scorer) return score_hyps def batch_rescoring(self, score_hyps, hist_enc, hist_mask_len, max_len): """ score_hyps: [((ctc_score, (id1, id2, id3, ....)), (), ...), ....] hist_enc: [len1xF, len2xF, .....] hist_mask: [1x1xlen1, 1x1xlen2] return bzx1 best_index """ bz = len(hist_enc) f = hist_enc[0].shape[-1] beam_size = self.beam_size encoder_lens = np.zeros((bz, 1), dtype=np.int32) encoder_out = torch.zeros((bz, max_len, f), dtype=self.dtype) hyps = [] ctc_score = torch.zeros((bz, beam_size), dtype=self.dtype) max_seq_len = 0 for i in range(bz): cur_len = hist_enc[i].shape[0] encoder_out[i, 0:cur_len] = hist_enc[i] encoder_lens[i, 0] = hist_mask_len[i] # process candidate if len(score_hyps[i]) < beam_size: to_append = (beam_size - len(score_hyps[i])) * [(-10000, ())] score_hyps[i] = list(score_hyps[i]) + to_append for idx, c in enumerate(score_hyps[i]): score, idlist = c if score < -10000: score = -10000 ctc_score[i][idx] = score hyps.append(list(idlist)) if len(hyps[-1]) > max_seq_len: max_seq_len = len(hyps[-1]) max_seq_len += 2 hyps_pad_sos_eos = np.ones((bz, beam_size, max_seq_len), dtype=np.int64) hyps_pad_sos_eos = hyps_pad_sos_eos * self.eos # fill eos if self.bidecoder: r_hyps_pad_sos_eos = np.ones((bz, beam_size, max_seq_len), dtype=np.int64) r_hyps_pad_sos_eos = r_hyps_pad_sos_eos * self.eos hyps_lens_sos = np.ones((bz, beam_size), dtype=np.int32) bz_id = 0 for idx, cand in enumerate(hyps): bz_id = idx // beam_size length = len(cand) + 2 bz_offset = idx % beam_size pad_cand = [self.sos] + cand + [self.eos] hyps_pad_sos_eos[bz_id][bz_offset][0 : length] = pad_cand if self.bidecoder: r_pad_cand = [self.sos] + cand[::-1] + [self.eos] r_hyps_pad_sos_eos[bz_id][bz_offset][0:length] = r_pad_cand hyps_lens_sos[bz_id][idx % beam_size] = len(cand) + 1 in0 = pb_utils.Tensor.from_dlpack("encoder_out", to_dlpack(encoder_out)) in1 = pb_utils.Tensor("encoder_out_lens", encoder_lens) in2 = pb_utils.Tensor("hyps_pad_sos_eos", hyps_pad_sos_eos) in3 = pb_utils.Tensor("hyps_lens_sos", hyps_lens_sos) input_tensors = [in0, in1, in2, in3] if self.bidecoder: in4 = pb_utils.Tensor("r_hyps_pad_sos_eos", r_hyps_pad_sos_eos) input_tensors.append(in4) in5 = pb_utils.Tensor.from_dlpack("ctc_score", to_dlpack(ctc_score)) input_tensors.append(in5) request = pb_utils.InferenceRequest(model_name='decoder', requested_output_names=['best_index'], inputs=input_tensors) response = request.exec() best_index = pb_utils.get_output_tensor_by_name(response, 'best_index') best_index = from_dlpack(best_index.to_dlpack()).clone() best_index = best_index.numpy()[:, 0] return best_index def __del__(self): print("remove wenet model")
[ "os.path.exists", "numpy.ones", "triton_python_backend_utils.InferenceRequest", "swig_decoders.map_batch", "torch.utils.dlpack.to_dlpack", "triton_python_backend_utils.Tensor", "swig_decoders.Scorer", "multiprocessing.cpu_count", "numpy.zeros", "triton_python_backend_utils.get_output_tensor_by_name", "swig_decoders.ctc_beam_search_decoder_batch", "torch.zeros", "torch.cat" ]
[((1805, 1828), 'os.path.exists', 'os.path.exists', (['lm_path'], {}), '(lm_path)\n', (1819, 1828), False, 'import os\n'), ((6428, 6475), 'swig_decoders.map_batch', 'map_batch', (['best_sent', 'self.vocab', 'num_processes'], {}), '(best_sent, self.vocab, num_processes)\n', (6437, 6475), False, 'from swig_decoders import ctc_beam_search_decoder_batch, Scorer, map_batch\n'), ((7491, 7672), 'swig_decoders.ctc_beam_search_decoder_batch', 'ctc_beam_search_decoder_batch', (['batch_log_probs_seq_list', 'batch_log_probs_idx_list', 'batch_root', 'batch_start', 'beam_size', 'num_processes', 'blank_id', 'space_id', 'cutoff_prob', 'scorer'], {}), '(batch_log_probs_seq_list,\n batch_log_probs_idx_list, batch_root, batch_start, beam_size,\n num_processes, blank_id, space_id, cutoff_prob, scorer)\n', (7520, 7672), False, 'from swig_decoders import ctc_beam_search_decoder_batch, Scorer, map_batch\n'), ((8559, 8592), 'numpy.zeros', 'np.zeros', (['(bz, 1)'], {'dtype': 'np.int32'}), '((bz, 1), dtype=np.int32)\n', (8567, 8592), True, 'import numpy as np\n'), ((8615, 8662), 'torch.zeros', 'torch.zeros', (['(bz, max_len, f)'], {'dtype': 'self.dtype'}), '((bz, max_len, f), dtype=self.dtype)\n', (8626, 8662), False, 'import torch\n'), ((8701, 8747), 'torch.zeros', 'torch.zeros', (['(bz, beam_size)'], {'dtype': 'self.dtype'}), '((bz, beam_size), dtype=self.dtype)\n', (8712, 8747), False, 'import torch\n'), ((9556, 9609), 'numpy.ones', 'np.ones', (['(bz, beam_size, max_seq_len)'], {'dtype': 'np.int64'}), '((bz, beam_size, max_seq_len), dtype=np.int64)\n', (9563, 9609), True, 'import numpy as np\n'), ((9879, 9919), 'numpy.ones', 'np.ones', (['(bz, beam_size)'], {'dtype': 'np.int32'}), '((bz, beam_size), dtype=np.int32)\n', (9886, 9919), True, 'import numpy as np\n'), ((10550, 10599), 'triton_python_backend_utils.Tensor', 'pb_utils.Tensor', (['"""encoder_out_lens"""', 'encoder_lens'], {}), "('encoder_out_lens', encoder_lens)\n", (10565, 10599), True, 'import triton_python_backend_utils as pb_utils\n'), ((10614, 10667), 'triton_python_backend_utils.Tensor', 'pb_utils.Tensor', (['"""hyps_pad_sos_eos"""', 'hyps_pad_sos_eos'], {}), "('hyps_pad_sos_eos', hyps_pad_sos_eos)\n", (10629, 10667), True, 'import triton_python_backend_utils as pb_utils\n'), ((10682, 10729), 'triton_python_backend_utils.Tensor', 'pb_utils.Tensor', (['"""hyps_lens_sos"""', 'hyps_lens_sos'], {}), "('hyps_lens_sos', hyps_lens_sos)\n", (10697, 10729), True, 'import triton_python_backend_utils as pb_utils\n'), ((11045, 11158), 'triton_python_backend_utils.InferenceRequest', 'pb_utils.InferenceRequest', ([], {'model_name': '"""decoder"""', 'requested_output_names': "['best_index']", 'inputs': 'input_tensors'}), "(model_name='decoder', requested_output_names=[\n 'best_index'], inputs=input_tensors)\n", (11070, 11158), True, 'import triton_python_backend_utils as pb_utils\n'), ((11297, 11355), 'triton_python_backend_utils.get_output_tensor_by_name', 'pb_utils.get_output_tensor_by_name', (['response', '"""best_index"""'], {}), "(response, 'best_index')\n", (11331, 11355), True, 'import triton_python_backend_utils as pb_utils\n'), ((1856, 1896), 'swig_decoders.Scorer', 'Scorer', (['alpha', 'beta', 'lm_path', 'self.vocab'], {}), '(alpha, beta, lm_path, self.vocab)\n', (1862, 1896), False, 'from swig_decoders import ctc_beam_search_decoder_batch, Scorer, map_batch\n'), ((4213, 4240), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (4238, 4240), False, 'import multiprocessing\n'), ((9737, 9790), 'numpy.ones', 'np.ones', (['(bz, beam_size, max_seq_len)'], {'dtype': 'np.int64'}), '((bz, beam_size, max_seq_len), dtype=np.int64)\n', (9744, 9790), True, 'import numpy as np\n'), ((10512, 10534), 'torch.utils.dlpack.to_dlpack', 'to_dlpack', (['encoder_out'], {}), '(encoder_out)\n', (10521, 10534), False, 'from torch.utils.dlpack import to_dlpack, from_dlpack\n'), ((10820, 10877), 'triton_python_backend_utils.Tensor', 'pb_utils.Tensor', (['"""r_hyps_pad_sos_eos"""', 'r_hyps_pad_sos_eos'], {}), "('r_hyps_pad_sos_eos', r_hyps_pad_sos_eos)\n", (10835, 10877), True, 'import triton_python_backend_utils as pb_utils\n'), ((10971, 10991), 'torch.utils.dlpack.to_dlpack', 'to_dlpack', (['ctc_score'], {}), '(ctc_score)\n', (10980, 10991), False, 'from torch.utils.dlpack import to_dlpack, from_dlpack\n'), ((5581, 5632), 'torch.cat', 'torch.cat', (['[hist_enc, cur_encoder_out[idx]]'], {'axis': '(0)'}), '([hist_enc, cur_encoder_out[idx]], axis=0)\n', (5590, 5632), False, 'import torch\n')]
"""Temporal VAE with gaussian margial and laplacian transition prior""" import torch import numpy as np import ipdb as pdb import torch.nn as nn import pytorch_lightning as pl import torch.distributions as D from torch.nn import functional as F from .components.beta import BetaVAE_MLP from .metrics.correlation import compute_mcc from .components.base import GroupLinearLayer from .components.transforms import ComponentWiseSpline def reconstruction_loss(x, x_recon, distribution): batch_size = x.size(0) assert batch_size != 0 if distribution == 'bernoulli': recon_loss = F.binary_cross_entropy_with_logits( x_recon, x, size_average=False).div(batch_size) elif distribution == 'gaussian': recon_loss = F.mse_loss(x_recon, x, size_average=False).div(batch_size) elif distribution == 'sigmoid': x_recon = F.sigmoid(x_recon) recon_loss = F.mse_loss(x_recon, x, size_average=False).div(batch_size) return recon_loss def compute_cross_ent_normal(mu, logvar): return 0.5 * (mu**2 + torch.exp(logvar)) + np.log(np.sqrt(2 * np.pi)) def compute_ent_normal(logvar): return 0.5 * (logvar + np.log(2 * np.pi * np.e)) def compute_sparsity(mu, normed=True): # assume couples, compute normalized sparsity diff = mu[::2] - mu[1::2] if normed: norm = torch.norm(diff, dim=1, keepdim=True) norm[norm == 0] = 1 # keep those that are same, dont divide by 0 diff = diff / norm return torch.mean(torch.abs(diff)) class AfflineVAESynthetic(pl.LightningModule): def __init__( self, input_dim, lag=1, beta=1, alpha=1, lr=1e-4, z_dim=10, gamma=10, rate_prior=1, hidden_dim=128, diagonal=False, decoder_dist='gaussian', nonlinear_type='gaussian' ): '''Import Beta-VAE as encoder/decoder''' super().__init__() self.net = BetaVAE_MLP(input_dim=input_dim, z_dim=z_dim, hidden_dim=hidden_dim) self.trans_func = GroupLinearLayer(din=z_dim, dout=z_dim, num_blocks=lag, diagonal=diagonal) self.spline = ComponentWiseSpline(input_dim=z_dim, bound=5, count_bins=8, order="linear") self.f1 = nn.Sequential(nn.Linear(z_dim, z_dim), nn.LeakyReLU(0.2)) self.f2 = nn.Sequential(nn.Linear(z_dim, z_dim), nn.LeakyReLU(0.2)) self.coff = nn.Linear(z_dim, z_dim) # self.spline.load_state_dict(torch.load("/home/yuewen/spline.pth")) self.lr = lr self.lag = lag self.beta = beta self.z_dim = z_dim self.alpha = alpha self.gamma = gamma self.input_dim = input_dim self.rate_prior = rate_prior self.decoder_dist = decoder_dist self.nonlinear_type = nonlinear_type self.b = nn.Parameter(0.01 * torch.randn(1, z_dim)) # base distribution for calculation of log prob under the model self.register_buffer('base_dist_var', torch.eye(self.z_dim)) self.register_buffer('base_dist_mean', torch.zeros(self.z_dim)) @property def base_dist(self): return D.MultivariateNormal(self.base_dist_mean, self.base_dist_var) def forward(self, batch): xt, xt_ = batch["xt"], batch["xt_"] batch_size, _, _ = xt.shape x = torch.cat((xt, xt_), dim=1) x = x.view(-1, self.input_dim) return self.net(x) def compute_cross_ent_laplace(self, mean, logvar, rate_prior): var = torch.exp(logvar) sigma = torch.sqrt(var) ce = - torch.log(rate_prior / 2) + rate_prior * sigma *\ np.sqrt(2 / np.pi) * torch.exp(- mean**2 / (2 * var)) -\ rate_prior * mean * ( 1 - 2 * self.normal_dist.cdf(mean / sigma)) return ce def training_step(self, batch, batch_idx): xt, xt_ = batch["xt"], batch["xt_"] batch_size, _, _ = xt.shape x = torch.cat((xt, xt_), dim=1) x = x.view(-1, self.input_dim) x_recon, mu, logvar, z = self.net(x) # Normal VAE loss: recon_loss + kld_loss recon_loss = reconstruction_loss(x, x_recon, self.decoder_dist) mu = mu.view(batch_size, -1, self.z_dim) logvar = logvar.view(batch_size, -1, self.z_dim) z = z.view(batch_size, -1, self.z_dim) mut, mut_ = mu[:,:-1,:], mu[:,-1:,:] logvart, logvart_ = logvar[:,:-1,:], logvar[:,-1:,:] zt, zt_ = z[:,:-1,:], z[:,-1:,:] # Past KLD divergenve p1 = D.Normal(torch.zeros_like(mut), torch.ones_like(logvart)) q1 = D.Normal(mut, torch.exp(logvart / 2)) log_qz_normal = q1.log_prob(zt) log_pz_normal = p1.log_prob(zt) kld_normal = log_qz_normal - log_pz_normal kld_normal = torch.sum(torch.sum(kld_normal,dim=-1),dim=-1).mean() ''' have question on this part... ''' # Current KLD divergence if self.nonlinear_type == "gaussian": zt_mid = self.f1(zt) noise_term = nn.Parameter(torch.randn(zt.shape).cuda()) zt_mid = zt_mid + self.coff(noise_term) zt_bar = self.f2(zt_mid) recon_zt_ = reconstruction_loss(zt_, zt_bar, self.decoder_dist) else: zt_mid = self.f1(zt) noise_term = nn.Parameter(torch.distributions.laplace.Laplace(0,1).rsample(zt.shape).cuda()) zt_mid = zt_mid + self.coff(noise_term) zt_bar = self.f2(zt_mid) recon_zt_ = reconstruction_loss(zt_, zt_bar, self.decoder_dist) coff = torch.abs(self.coff.weight).mean() # # Current KLD divergence # ut = self.trans_func(zt) # ut = torch.sum(ut, dim=1) + self.b # epst_ = zt_.squeeze() + ut # et_, logabsdet = self.spline(epst_) # log_pz_laplace = self.base_dist.log_prob(et_) + logabsdet # q_laplace = D.Normal(mut_, torch.exp(logvart_ / 2)) # log_qz_laplace = q_laplace.log_prob(zt_) # kld_laplace = torch.sum(torch.sum(log_qz_laplace,dim=-1),dim=-1) - log_pz_laplace # kld_laplace = kld_laplace.mean() loss = (self.lag+1) * recon_loss + self.beta * kld_normal + self.gamma * recon_zt_ + self.alpha * coff # loss = (self.lag+1) * recon_loss + self.beta * kld_normal zt_recon = mu[:,-1,:].T.detach().cpu().numpy() zt_true = batch["yt_"].squeeze().T.detach().cpu().numpy() mcc = compute_mcc(zt_recon, zt_true, "Pearson") self.log("train_mcc", mcc) self.log("train_coff", coff) self.log("train_elbo_loss", loss) self.log("train_recon_zt_", recon_zt_) self.log("train_recon_loss", recon_loss) self.log("train_kld_normal", kld_normal) return loss def validation_step(self, batch, batch_idx): xt, xt_ = batch["xt"], batch["xt_"] batch_size, _, _ = xt.shape x = torch.cat((xt, xt_), dim=1) x = x.view(-1, self.input_dim) x_recon, mu, logvar, z = self.net(x) # Normal VAE loss: recon_loss + kld_loss recon_loss = reconstruction_loss(x, x_recon, self.decoder_dist) mu = mu.view(batch_size, -1, self.z_dim) logvar = logvar.view(batch_size, -1, self.z_dim) z = z.view(batch_size, -1, self.z_dim) mut, mut_ = mu[:,:-1,:], mu[:,-1:,:] logvart, logvart_ = logvar[:,:-1,:], logvar[:,-1:,:] zt, zt_ = z[:,:-1,:], z[:,-1:,:] # Past KLD divergenve p1 = D.Normal(torch.zeros_like(mut), torch.ones_like(logvart)) q1 = D.Normal(mut, torch.exp(logvart / 2)) log_qz_normal = q1.log_prob(zt) log_pz_normal = p1.log_prob(zt) kld_normal = log_qz_normal - log_pz_normal kld_normal = torch.sum(torch.sum(kld_normal,dim=-1),dim=-1).mean() # Current KLD divergence if self.nonlinear_type == "gaussian": zt_mid = self.f1(zt) noise_term = nn.Parameter(torch.randn(zt.shape).cuda()) zt_mid = zt_mid + self.coff(noise_term) zt_bar = self.f2(zt_mid) recon_zt_ = reconstruction_loss(zt_, zt_bar, self.decoder_dist) else: zt_mid = self.f1(zt) noise_term = nn.Parameter(torch.distributions.laplace.Laplace(0,1).rsample(zt.shape).cuda()) zt_mid = zt_mid + self.coff(noise_term) zt_bar = self.f2(zt_mid) recon_zt_ = reconstruction_loss(zt_, zt_bar, self.decoder_dist) coff = torch.abs(self.coff.weight).mean() loss = (self.lag+1) * recon_loss + self.beta * kld_normal + self.gamma * recon_zt_ + self.alpha * coff # loss = (self.lag+1) * recon_loss + self.beta * kld_normal zt_recon = mu[:,-1,:].T.detach().cpu().numpy() zt_true = batch["yt_"].squeeze().T.detach().cpu().numpy() mcc = compute_mcc(zt_recon, zt_true, "Pearson") self.log("val_mcc", mcc) self.log("val_coff", coff) self.log("val_elbo_loss", loss) self.log("val_recon_zt_", recon_zt_) self.log("val_recon_loss", recon_loss) self.log("val_kld_normal", kld_normal) return loss def sample(self, xt): batch_size = xt.shape[0] e = torch.randn(batch_size, self.z_dim).to(xt.device) eps, _ = self.spline.inverse(e) return eps def reconstruct(self): return self.forward(batch)[0] def configure_optimizers(self): optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=self.lr) # An scheduler is optional, but can help in flows to get the last bpd improvement scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.99) return [optimizer], [scheduler]
[ "numpy.sqrt", "numpy.log", "torch.sqrt", "torch.exp", "torch.nn.functional.sigmoid", "torch.sum", "torch.eye", "torch.zeros_like", "torch.randn", "torch.ones_like", "torch.abs", "torch.nn.functional.mse_loss", "torch.nn.LeakyReLU", "torch.distributions.laplace.Laplace", "torch.norm", "torch.cat", "torch.log", "torch.optim.lr_scheduler.StepLR", "torch.nn.Linear", "torch.distributions.MultivariateNormal", "torch.zeros", "torch.nn.functional.binary_cross_entropy_with_logits" ]
[((1386, 1423), 'torch.norm', 'torch.norm', (['diff'], {'dim': '(1)', 'keepdim': '(True)'}), '(diff, dim=1, keepdim=True)\n', (1396, 1423), False, 'import torch\n'), ((1550, 1565), 'torch.abs', 'torch.abs', (['diff'], {}), '(diff)\n', (1559, 1565), False, 'import torch\n'), ((2875, 2898), 'torch.nn.Linear', 'nn.Linear', (['z_dim', 'z_dim'], {}), '(z_dim, z_dim)\n', (2884, 2898), True, 'import torch.nn as nn\n'), ((3631, 3692), 'torch.distributions.MultivariateNormal', 'D.MultivariateNormal', (['self.base_dist_mean', 'self.base_dist_var'], {}), '(self.base_dist_mean, self.base_dist_var)\n', (3651, 3692), True, 'import torch.distributions as D\n'), ((3822, 3849), 'torch.cat', 'torch.cat', (['(xt, xt_)'], {'dim': '(1)'}), '((xt, xt_), dim=1)\n', (3831, 3849), False, 'import torch\n'), ((4003, 4020), 'torch.exp', 'torch.exp', (['logvar'], {}), '(logvar)\n', (4012, 4020), False, 'import torch\n'), ((4038, 4053), 'torch.sqrt', 'torch.sqrt', (['var'], {}), '(var)\n', (4048, 4053), False, 'import torch\n'), ((4458, 4485), 'torch.cat', 'torch.cat', (['(xt, xt_)'], {'dim': '(1)'}), '((xt, xt_), dim=1)\n', (4467, 4485), False, 'import torch\n'), ((7517, 7544), 'torch.cat', 'torch.cat', (['(xt, xt_)'], {'dim': '(1)'}), '((xt, xt_), dim=1)\n', (7526, 7544), False, 'import torch\n'), ((10323, 10380), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer', '(1)'], {'gamma': '(0.99)'}), '(optimizer, 1, gamma=0.99)\n', (10354, 10380), False, 'import torch\n'), ((1121, 1139), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (1128, 1139), True, 'import numpy as np\n'), ((1204, 1228), 'numpy.log', 'np.log', (['(2 * np.pi * np.e)'], {}), '(2 * np.pi * np.e)\n', (1210, 1228), True, 'import numpy as np\n'), ((2667, 2690), 'torch.nn.Linear', 'nn.Linear', (['z_dim', 'z_dim'], {}), '(z_dim, z_dim)\n', (2676, 2690), True, 'import torch.nn as nn\n'), ((2725, 2742), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (2737, 2742), True, 'import torch.nn as nn\n'), ((2777, 2800), 'torch.nn.Linear', 'nn.Linear', (['z_dim', 'z_dim'], {}), '(z_dim, z_dim)\n', (2786, 2800), True, 'import torch.nn as nn\n'), ((2835, 2852), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (2847, 2852), True, 'import torch.nn as nn\n'), ((3476, 3497), 'torch.eye', 'torch.eye', (['self.z_dim'], {}), '(self.z_dim)\n', (3485, 3497), False, 'import torch\n'), ((3547, 3570), 'torch.zeros', 'torch.zeros', (['self.z_dim'], {}), '(self.z_dim)\n', (3558, 3570), False, 'import torch\n'), ((5059, 5080), 'torch.zeros_like', 'torch.zeros_like', (['mut'], {}), '(mut)\n', (5075, 5080), False, 'import torch\n'), ((5082, 5106), 'torch.ones_like', 'torch.ones_like', (['logvart'], {}), '(logvart)\n', (5097, 5106), False, 'import torch\n'), ((5136, 5158), 'torch.exp', 'torch.exp', (['(logvart / 2)'], {}), '(logvart / 2)\n', (5145, 5158), False, 'import torch\n'), ((8118, 8139), 'torch.zeros_like', 'torch.zeros_like', (['mut'], {}), '(mut)\n', (8134, 8139), False, 'import torch\n'), ((8141, 8165), 'torch.ones_like', 'torch.ones_like', (['logvart'], {}), '(logvart)\n', (8156, 8165), False, 'import torch\n'), ((8195, 8217), 'torch.exp', 'torch.exp', (['(logvart / 2)'], {}), '(logvart / 2)\n', (8204, 8217), False, 'import torch\n'), ((620, 686), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['x_recon', 'x'], {'size_average': '(False)'}), '(x_recon, x, size_average=False)\n', (654, 686), True, 'from torch.nn import functional as F\n'), ((896, 914), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['x_recon'], {}), '(x_recon)\n', (905, 914), True, 'from torch.nn import functional as F\n'), ((1093, 1110), 'torch.exp', 'torch.exp', (['logvar'], {}), '(logvar)\n', (1102, 1110), False, 'import torch\n'), ((3333, 3354), 'torch.randn', 'torch.randn', (['(1)', 'z_dim'], {}), '(1, z_dim)\n', (3344, 3354), False, 'import torch\n'), ((6132, 6159), 'torch.abs', 'torch.abs', (['self.coff.weight'], {}), '(self.coff.weight)\n', (6141, 6159), False, 'import torch\n'), ((9128, 9155), 'torch.abs', 'torch.abs', (['self.coff.weight'], {}), '(self.coff.weight)\n', (9137, 9155), False, 'import torch\n'), ((9888, 9923), 'torch.randn', 'torch.randn', (['batch_size', 'self.z_dim'], {}), '(batch_size, self.z_dim)\n', (9899, 9923), False, 'import torch\n'), ((779, 821), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['x_recon', 'x'], {'size_average': '(False)'}), '(x_recon, x, size_average=False)\n', (789, 821), True, 'from torch.nn import functional as F\n'), ((4070, 4095), 'torch.log', 'torch.log', (['(rate_prior / 2)'], {}), '(rate_prior / 2)\n', (4079, 4095), False, 'import torch\n'), ((4155, 4188), 'torch.exp', 'torch.exp', (['(-mean ** 2 / (2 * var))'], {}), '(-mean ** 2 / (2 * var))\n', (4164, 4188), False, 'import torch\n'), ((5326, 5355), 'torch.sum', 'torch.sum', (['kld_normal'], {'dim': '(-1)'}), '(kld_normal, dim=-1)\n', (5335, 5355), False, 'import torch\n'), ((8385, 8414), 'torch.sum', 'torch.sum', (['kld_normal'], {'dim': '(-1)'}), '(kld_normal, dim=-1)\n', (8394, 8414), False, 'import torch\n'), ((937, 979), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['x_recon', 'x'], {'size_average': '(False)'}), '(x_recon, x, size_average=False)\n', (947, 979), True, 'from torch.nn import functional as F\n'), ((4134, 4152), 'numpy.sqrt', 'np.sqrt', (['(2 / np.pi)'], {}), '(2 / np.pi)\n', (4141, 4152), True, 'import numpy as np\n'), ((5595, 5616), 'torch.randn', 'torch.randn', (['zt.shape'], {}), '(zt.shape)\n', (5606, 5616), False, 'import torch\n'), ((8591, 8612), 'torch.randn', 'torch.randn', (['zt.shape'], {}), '(zt.shape)\n', (8602, 8612), False, 'import torch\n'), ((5881, 5922), 'torch.distributions.laplace.Laplace', 'torch.distributions.laplace.Laplace', (['(0)', '(1)'], {}), '(0, 1)\n', (5916, 5922), False, 'import torch\n'), ((8877, 8918), 'torch.distributions.laplace.Laplace', 'torch.distributions.laplace.Laplace', (['(0)', '(1)'], {}), '(0, 1)\n', (8912, 8918), False, 'import torch\n')]
import openmoc import openmc.openmoc_compatible import openmc.mgxs import numpy as np import matplotlib # Enable Matplotib to work for headless nodes matplotlib.use('Agg') import matplotlib.pyplot as plt plt.ioff() opts = openmoc.options.Options() openmoc.log.set_log_level('NORMAL') ############################################################################### # Eigenvalue Calculation w/o SPH Factors ############################################################################### # Initialize 2-group OpenMC multi-group cross section library for a pin cell mgxs_lib = openmc.mgxs.Library.load_from_file(filename='mgxs', directory='.') # Create an OpenMOC Geometry from the OpenMOC Geometry openmoc_geometry = \ openmc.openmoc_compatible.get_openmoc_geometry(mgxs_lib.geometry) # Load cross section data openmoc_materials = \ openmoc.materialize.load_openmc_mgxs_lib(mgxs_lib, openmoc_geometry) # Initialize FSRs openmoc_geometry.initializeFlatSourceRegions() # Initialize an OpenMOC TrackGenerator track_generator = openmoc.TrackGenerator( openmoc_geometry, opts.num_azim, opts.azim_spacing) track_generator.generateTracks() # Initialize an OpenMOC Solver solver = openmoc.CPUSolver(track_generator) solver.setConvergenceThreshold(opts.tolerance) solver.setNumThreads(opts.num_omp_threads) # Run an eigenvalue calulation with the MGXS from OpenMC solver.computeEigenvalue(opts.max_iters) solver.printTimerReport() keff_no_sph = solver.getKeff() # Extract the OpenMOC scalar fluxes fluxes_no_sph = openmoc.process.get_scalar_fluxes(solver) ############################################################################### # Eigenvalue Calculation with SPH Factors ############################################################################### # Compute SPH factors sph, sph_mgxs_lib, sph_indices = \ openmoc.materialize.compute_sph_factors( mgxs_lib, azim_spacing=opts.azim_spacing, num_azim=opts.num_azim, num_threads=opts.num_omp_threads) # Load the SPH-corrected MGXS library data materials = \ openmoc.materialize.load_openmc_mgxs_lib(sph_mgxs_lib, openmoc_geometry) # Run an eigenvalue calculation with the SPH-corrected modified MGXS library solver.computeEigenvalue(opts.max_iters) solver.printTimerReport() keff_with_sph = solver.getKeff() # Report the OpenMC and OpenMOC eigenvalues openmoc.log.py_printf('RESULT', 'OpenMOC keff w/o SPH: \t%1.5f', keff_no_sph) openmoc.log.py_printf('RESULT', 'OpenMOC keff w/ SPH: \t%1.5f', keff_with_sph) openmoc.log.py_printf('RESULT', 'OpenMC keff: \t\t1.17574 +/- 0.00086') ############################################################################### # Extracting Scalar Fluxes ############################################################################### openmoc.log.py_printf('NORMAL', 'Plotting data...') # Plot the cells openmoc.plotter.plot_cells(openmoc_geometry) # Extract the OpenMOC scalar fluxes fluxes_sph = openmoc.process.get_scalar_fluxes(solver) fluxes_sph *= sph # Extract the OpenMC scalar fluxes num_fsrs = openmoc_geometry.getNumFSRs() num_groups = openmoc_geometry.getNumEnergyGroups() openmc_fluxes = np.zeros((num_fsrs, num_groups), dtype=np.float64) nufission_xs = np.zeros((num_fsrs, num_groups), dtype=np.float64) # Get the OpenMC flux in each FSR for fsr in range(num_fsrs): # Find the OpenMOC cell and volume for this FSR openmoc_cell = openmoc_geometry.findCellContainingFSR(fsr) cell_id = openmoc_cell.getId() fsr_volume = track_generator.getFSRVolume(fsr) # Store the volume-averaged flux mgxs = mgxs_lib.get_mgxs(cell_id, 'nu-fission') flux = mgxs.tallies['flux'].mean.flatten() flux = np.flipud(flux) / fsr_volume openmc_fluxes[fsr, :] = flux nufission_xs[fsr, :] = mgxs.get_xs(nuclide='all') # Extract energy group edges group_edges = mgxs_lib.energy_groups.group_edges group_edges += 1e-3 # Adjust lower bound to 1e-3 eV (for loglog scaling) # Compute difference in energy bounds for each group group_edges = np.flipud(group_edges) # Normalize fluxes with the fission source openmc_fluxes /= np.sum(openmc_fluxes * nufission_xs) fluxes_sph /= np.sum(fluxes_sph * nufission_xs) fluxes_no_sph /= np.sum(fluxes_no_sph * nufission_xs) ############################################################################### # Plot the OpenMC, OpenMOC Scalar Fluxes ############################################################################### # Extend the mgxs values array for matplotlib's step plot of fluxes openmc_fluxes = np.insert(openmc_fluxes, 0, openmc_fluxes[:,0], axis=1) fluxes_no_sph = np.insert(fluxes_no_sph, 0, fluxes_no_sph[:,0], axis=1) fluxes_sph = np.insert(fluxes_sph, 0, fluxes_sph[:,0], axis=1) # Plot OpenMOC and OpenMC fluxes in each FSR for fsr in range(num_fsrs): # Get the OpenMOC cell and material for this FSR cell = openmoc_geometry.findCellContainingFSR(fsr) material_name = cell.getFillMaterial().getName() # Create a step plot for the MGXS fig = plt.figure() plt.plot(group_edges, openmc_fluxes[fsr,:], drawstyle='steps', color='r', linewidth=2) plt.plot(group_edges, fluxes_no_sph[fsr,:], drawstyle='steps', color='b', linewidth=2) plt.plot(group_edges, fluxes_sph[fsr,:], drawstyle='steps', color='g', linewidth=2) plt.yscale('log') plt.xscale('log') plt.xlabel('Energy [eV]') plt.ylabel('Flux') plt.title('Normalized Flux ({0})'.format(material_name)) plt.xlim((min(group_edges), max(group_edges))) plt.legend(['openmc', 'openmoc w/o sph', 'openmoc w/ sph'], loc='best') plt.grid() filename = 'plots/flux-{0}.png'.format(material_name.replace(' ', '-')) plt.savefig(filename, bbox_inches='tight') plt.close() ############################################################################### # Plot OpenMC-to-OpenMOC Scalar Flux Errors ############################################################################### # Compute the percent relative error in the flux rel_err_no_sph = np.zeros(openmc_fluxes.shape) rel_err_sph = np.zeros(openmc_fluxes.shape) for fsr in range(num_fsrs): delta_flux_no_sph = fluxes_no_sph[fsr,:] - openmc_fluxes[fsr,:] delta_flux_sph = fluxes_sph[fsr,:] - openmc_fluxes[fsr,:] rel_err_no_sph[fsr,:] = delta_flux_no_sph / openmc_fluxes[fsr,:] * 100. rel_err_sph[fsr,:] = delta_flux_sph / openmc_fluxes[fsr,:] * 100. # Plot OpenMOC relative flux errors in each FSR for fsr in range(num_fsrs): # Get the OpenMOC cell and material for this FSR cell = openmoc_geometry.findCellContainingFSR(fsr) material_name = cell.getFillMaterial().getName() # Create a step plot for the MGXS fig = plt.figure() plt.plot(group_edges, rel_err_no_sph[fsr,:], drawstyle='steps', color='r', linewidth=2) plt.plot(group_edges, rel_err_sph[fsr,:], drawstyle='steps', color='b', linewidth=2) plt.xscale('log') plt.xlabel('Energy [eV]') plt.ylabel('Relative Error [%]') plt.title('OpenMOC-to-OpenMC Flux Rel. Err. ({0})'.format(material_name)) plt.xlim((min(group_edges), max(group_edges))) plt.legend(['openmoc w/o sph', 'openmoc w/ sph'], loc='best') plt.grid() filename = 'plots/rel-err-{0}.png'.format(material_name.replace(' ', '-')) plt.savefig(filename, bbox_inches='tight') plt.close()
[ "matplotlib.pyplot.grid", "openmoc.plotter.plot_cells", "matplotlib.pyplot.ylabel", "openmoc.materialize.compute_sph_factors", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "openmoc.log.set_log_level", "matplotlib.pyplot.yscale", "openmoc.options.Options", "matplotlib.pyplot.savefig", "numpy.flipud", "matplotlib.use", "matplotlib.pyplot.ioff", "openmoc.log.py_printf", "matplotlib.pyplot.legend", "numpy.insert", "openmoc.TrackGenerator", "openmoc.CPUSolver", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure", "openmoc.materialize.load_openmc_mgxs_lib", "matplotlib.pyplot.xscale", "openmoc.process.get_scalar_fluxes" ]
[((152, 173), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (166, 173), False, 'import matplotlib\n'), ((206, 216), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (214, 216), True, 'import matplotlib.pyplot as plt\n'), ((226, 251), 'openmoc.options.Options', 'openmoc.options.Options', ([], {}), '()\n', (249, 251), False, 'import openmoc\n'), ((252, 287), 'openmoc.log.set_log_level', 'openmoc.log.set_log_level', (['"""NORMAL"""'], {}), "('NORMAL')\n", (277, 287), False, 'import openmoc\n'), ((863, 931), 'openmoc.materialize.load_openmc_mgxs_lib', 'openmoc.materialize.load_openmc_mgxs_lib', (['mgxs_lib', 'openmoc_geometry'], {}), '(mgxs_lib, openmoc_geometry)\n', (903, 931), False, 'import openmoc\n'), ((1056, 1130), 'openmoc.TrackGenerator', 'openmoc.TrackGenerator', (['openmoc_geometry', 'opts.num_azim', 'opts.azim_spacing'], {}), '(openmoc_geometry, opts.num_azim, opts.azim_spacing)\n', (1078, 1130), False, 'import openmoc\n'), ((1210, 1244), 'openmoc.CPUSolver', 'openmoc.CPUSolver', (['track_generator'], {}), '(track_generator)\n', (1227, 1244), False, 'import openmoc\n'), ((1544, 1585), 'openmoc.process.get_scalar_fluxes', 'openmoc.process.get_scalar_fluxes', (['solver'], {}), '(solver)\n', (1577, 1585), False, 'import openmoc\n'), ((1867, 2011), 'openmoc.materialize.compute_sph_factors', 'openmoc.materialize.compute_sph_factors', (['mgxs_lib'], {'azim_spacing': 'opts.azim_spacing', 'num_azim': 'opts.num_azim', 'num_threads': 'opts.num_omp_threads'}), '(mgxs_lib, azim_spacing=opts.\n azim_spacing, num_azim=opts.num_azim, num_threads=opts.num_omp_threads)\n', (1906, 2011), False, 'import openmoc\n'), ((2086, 2158), 'openmoc.materialize.load_openmc_mgxs_lib', 'openmoc.materialize.load_openmc_mgxs_lib', (['sph_mgxs_lib', 'openmoc_geometry'], {}), '(sph_mgxs_lib, openmoc_geometry)\n', (2126, 2158), False, 'import openmoc\n'), ((2382, 2459), 'openmoc.log.py_printf', 'openmoc.log.py_printf', (['"""RESULT"""', '"""OpenMOC keff w/o SPH: \t%1.5f"""', 'keff_no_sph'], {}), "('RESULT', 'OpenMOC keff w/o SPH: \\t%1.5f', keff_no_sph)\n", (2403, 2459), False, 'import openmoc\n'), ((2460, 2538), 'openmoc.log.py_printf', 'openmoc.log.py_printf', (['"""RESULT"""', '"""OpenMOC keff w/ SPH: \t%1.5f"""', 'keff_with_sph'], {}), "('RESULT', 'OpenMOC keff w/ SPH: \\t%1.5f', keff_with_sph)\n", (2481, 2538), False, 'import openmoc\n'), ((2539, 2610), 'openmoc.log.py_printf', 'openmoc.log.py_printf', (['"""RESULT"""', '"""OpenMC keff: \t\t1.17574 +/- 0.00086"""'], {}), "('RESULT', 'OpenMC keff: \\t\\t1.17574 +/- 0.00086')\n", (2560, 2610), False, 'import openmoc\n'), ((2825, 2876), 'openmoc.log.py_printf', 'openmoc.log.py_printf', (['"""NORMAL"""', '"""Plotting data..."""'], {}), "('NORMAL', 'Plotting data...')\n", (2846, 2876), False, 'import openmoc\n'), ((2895, 2939), 'openmoc.plotter.plot_cells', 'openmoc.plotter.plot_cells', (['openmoc_geometry'], {}), '(openmoc_geometry)\n', (2921, 2939), False, 'import openmoc\n'), ((2990, 3031), 'openmoc.process.get_scalar_fluxes', 'openmoc.process.get_scalar_fluxes', (['solver'], {}), '(solver)\n', (3023, 3031), False, 'import openmoc\n'), ((3194, 3244), 'numpy.zeros', 'np.zeros', (['(num_fsrs, num_groups)'], {'dtype': 'np.float64'}), '((num_fsrs, num_groups), dtype=np.float64)\n', (3202, 3244), True, 'import numpy as np\n'), ((3260, 3310), 'numpy.zeros', 'np.zeros', (['(num_fsrs, num_groups)'], {'dtype': 'np.float64'}), '((num_fsrs, num_groups), dtype=np.float64)\n', (3268, 3310), True, 'import numpy as np\n'), ((4064, 4086), 'numpy.flipud', 'np.flipud', (['group_edges'], {}), '(group_edges)\n', (4073, 4086), True, 'import numpy as np\n'), ((4148, 4184), 'numpy.sum', 'np.sum', (['(openmc_fluxes * nufission_xs)'], {}), '(openmc_fluxes * nufission_xs)\n', (4154, 4184), True, 'import numpy as np\n'), ((4199, 4232), 'numpy.sum', 'np.sum', (['(fluxes_sph * nufission_xs)'], {}), '(fluxes_sph * nufission_xs)\n', (4205, 4232), True, 'import numpy as np\n'), ((4250, 4286), 'numpy.sum', 'np.sum', (['(fluxes_no_sph * nufission_xs)'], {}), '(fluxes_no_sph * nufission_xs)\n', (4256, 4286), True, 'import numpy as np\n'), ((4591, 4647), 'numpy.insert', 'np.insert', (['openmc_fluxes', '(0)', 'openmc_fluxes[:, 0]'], {'axis': '(1)'}), '(openmc_fluxes, 0, openmc_fluxes[:, 0], axis=1)\n', (4600, 4647), True, 'import numpy as np\n'), ((4663, 4719), 'numpy.insert', 'np.insert', (['fluxes_no_sph', '(0)', 'fluxes_no_sph[:, 0]'], {'axis': '(1)'}), '(fluxes_no_sph, 0, fluxes_no_sph[:, 0], axis=1)\n', (4672, 4719), True, 'import numpy as np\n'), ((4732, 4782), 'numpy.insert', 'np.insert', (['fluxes_sph', '(0)', 'fluxes_sph[:, 0]'], {'axis': '(1)'}), '(fluxes_sph, 0, fluxes_sph[:, 0], axis=1)\n', (4741, 4782), True, 'import numpy as np\n'), ((6118, 6147), 'numpy.zeros', 'np.zeros', (['openmc_fluxes.shape'], {}), '(openmc_fluxes.shape)\n', (6126, 6147), True, 'import numpy as np\n'), ((6162, 6191), 'numpy.zeros', 'np.zeros', (['openmc_fluxes.shape'], {}), '(openmc_fluxes.shape)\n', (6170, 6191), True, 'import numpy as np\n'), ((5067, 5079), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5077, 5079), True, 'import matplotlib.pyplot as plt\n'), ((5084, 5175), 'matplotlib.pyplot.plot', 'plt.plot', (['group_edges', 'openmc_fluxes[fsr, :]'], {'drawstyle': '"""steps"""', 'color': '"""r"""', 'linewidth': '(2)'}), "(group_edges, openmc_fluxes[fsr, :], drawstyle='steps', color='r',\n linewidth=2)\n", (5092, 5175), True, 'import matplotlib.pyplot as plt\n'), ((5188, 5279), 'matplotlib.pyplot.plot', 'plt.plot', (['group_edges', 'fluxes_no_sph[fsr, :]'], {'drawstyle': '"""steps"""', 'color': '"""b"""', 'linewidth': '(2)'}), "(group_edges, fluxes_no_sph[fsr, :], drawstyle='steps', color='b',\n linewidth=2)\n", (5196, 5279), True, 'import matplotlib.pyplot as plt\n'), ((5292, 5380), 'matplotlib.pyplot.plot', 'plt.plot', (['group_edges', 'fluxes_sph[fsr, :]'], {'drawstyle': '"""steps"""', 'color': '"""g"""', 'linewidth': '(2)'}), "(group_edges, fluxes_sph[fsr, :], drawstyle='steps', color='g',\n linewidth=2)\n", (5300, 5380), True, 'import matplotlib.pyplot as plt\n'), ((5394, 5411), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (5404, 5411), True, 'import matplotlib.pyplot as plt\n'), ((5416, 5433), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (5426, 5433), True, 'import matplotlib.pyplot as plt\n'), ((5438, 5463), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Energy [eV]"""'], {}), "('Energy [eV]')\n", (5448, 5463), True, 'import matplotlib.pyplot as plt\n'), ((5468, 5486), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flux"""'], {}), "('Flux')\n", (5478, 5486), True, 'import matplotlib.pyplot as plt\n'), ((5603, 5674), 'matplotlib.pyplot.legend', 'plt.legend', (["['openmc', 'openmoc w/o sph', 'openmoc w/ sph']"], {'loc': '"""best"""'}), "(['openmc', 'openmoc w/o sph', 'openmoc w/ sph'], loc='best')\n", (5613, 5674), True, 'import matplotlib.pyplot as plt\n'), ((5679, 5689), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (5687, 5689), True, 'import matplotlib.pyplot as plt\n'), ((5770, 5812), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""'}), "(filename, bbox_inches='tight')\n", (5781, 5812), True, 'import matplotlib.pyplot as plt\n'), ((5817, 5828), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5826, 5828), True, 'import matplotlib.pyplot as plt\n'), ((6786, 6798), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6796, 6798), True, 'import matplotlib.pyplot as plt\n'), ((6803, 6895), 'matplotlib.pyplot.plot', 'plt.plot', (['group_edges', 'rel_err_no_sph[fsr, :]'], {'drawstyle': '"""steps"""', 'color': '"""r"""', 'linewidth': '(2)'}), "(group_edges, rel_err_no_sph[fsr, :], drawstyle='steps', color='r',\n linewidth=2)\n", (6811, 6895), True, 'import matplotlib.pyplot as plt\n'), ((6908, 6997), 'matplotlib.pyplot.plot', 'plt.plot', (['group_edges', 'rel_err_sph[fsr, :]'], {'drawstyle': '"""steps"""', 'color': '"""b"""', 'linewidth': '(2)'}), "(group_edges, rel_err_sph[fsr, :], drawstyle='steps', color='b',\n linewidth=2)\n", (6916, 6997), True, 'import matplotlib.pyplot as plt\n'), ((7011, 7028), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (7021, 7028), True, 'import matplotlib.pyplot as plt\n'), ((7033, 7058), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Energy [eV]"""'], {}), "('Energy [eV]')\n", (7043, 7058), True, 'import matplotlib.pyplot as plt\n'), ((7063, 7095), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error [%]"""'], {}), "('Relative Error [%]')\n", (7073, 7095), True, 'import matplotlib.pyplot as plt\n'), ((7229, 7290), 'matplotlib.pyplot.legend', 'plt.legend', (["['openmoc w/o sph', 'openmoc w/ sph']"], {'loc': '"""best"""'}), "(['openmoc w/o sph', 'openmoc w/ sph'], loc='best')\n", (7239, 7290), True, 'import matplotlib.pyplot as plt\n'), ((7295, 7305), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (7303, 7305), True, 'import matplotlib.pyplot as plt\n'), ((7389, 7431), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""'}), "(filename, bbox_inches='tight')\n", (7400, 7431), True, 'import matplotlib.pyplot as plt\n'), ((7436, 7447), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7445, 7447), True, 'import matplotlib.pyplot as plt\n'), ((3724, 3739), 'numpy.flipud', 'np.flipud', (['flux'], {}), '(flux)\n', (3733, 3739), True, 'import numpy as np\n')]
from sklearn.cluster import KMeans import cv2 import PIL import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from matplotlib import image as img1 import pandas as pd from scipy.cluster.vq import whiten import os class DominantColors: CLUSTERS = None IMAGEPATH = None IMAGE = None COLORS = None LABELS = None BASEWIDTH = 256 def __init__(self, image, clusters=3): self.CLUSTERS = clusters self.IMAGEPATH = image def dominantColors(self): # read image img = cv2.imread(self.IMAGEPATH) # resize image imgh, imgw, _ = img.shape wpercent = (self.BASEWIDTH / float(imgw)) hsize = int((float(imgh) * float(wpercent))) img = cv2.resize(img, (self.BASEWIDTH, hsize), PIL.Image.ANTIALIAS) # convert to rgb from bgr img = cv2.cvtColor(img, cv2.COLOR_RGB2Luv) # reshaping to a list of pixels img = img.reshape((img.shape[0] * img.shape[1], 3)) # save image after operations self.IMAGE = img # using k-means to cluster pixels kmeans = KMeans(n_clusters=self.CLUSTERS) kmeans.fit(img) # the cluster centers are our dominant colors. self.COLORS = kmeans.cluster_centers_ # save labels self.LABELS = kmeans.labels_ # returning after converting to integer from float return self.COLORS.astype(int) def rgb_to_hex(self, rgb): return '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2])) def analyseRGB(self): r = [] g = [] b = [] image = img1.imread(self.IMAGEPATH) for line in image: for pixel in line: # print(pixel) temp_r, temp_g, temp_b = pixel r.append(temp_r) g.append(temp_g) b.append(temp_b) fig = plt.figure() ax = Axes3D(fig) ax.scatter(r, g, b) plt.show() df = pd.DataFrame({'red': r, 'blue': b, 'green': g}) df['scaled_red'] = whiten(df['red']) df['scaled_blue'] = whiten(df['blue']) df['scaled_green'] = whiten(df['green']) df.sample(n=10) from scipy.cluster.vq import kmeans cluster_centers, distortion = kmeans(df[['scaled_red', 'scaled_green', 'scaled_blue']], 2) print(cluster_centers) colors = [] r_std, g_std, b_std = df[['red', 'green', 'blue']].std() for cluster_center in cluster_centers: scaled_r, scaled_g, scaled_b = cluster_center colors.append((scaled_r * r_std / 255, scaled_g * g_std / 255, scaled_b * b_std / 255)) plt.imshow([colors]) plt.show() def plotClusters(self): # plotting fig = plt.figure() ax = Axes3D(fig) for label, pix in zip(self.LABELS, self.IMAGE): ax.scatter(pix[0], pix[1], pix[2], color=self.rgb_to_hex(self.COLORS[label])) plt.show() def plotHistogram(self): # labels form 0 to no. of clusters numLabels = np.arange(0, self.CLUSTERS + 1) # create frequency count tables (hist, _) = np.histogram(self.LABELS, bins=numLabels) hist = hist.astype("float") hist /= hist.sum() # appending frequencies to cluster centers colors = self.COLORS # descending order sorting as per frequency count colors = colors[(-hist).argsort()] hist = hist[(-hist).argsort()] # creating empty chart chart = np.zeros((50, 500, 3), np.uint8) start = 0 # creating color rectangles for i in range(self.CLUSTERS): end = start + hist[i] * 500 # getting rgb values r = colors[i][0] g = colors[i][1] b = colors[i][2] # using cv2.rectangle to plot colors cv2.rectangle(chart, (int(start), 0), (int(end), 50), (r, g, b), -1) start = end # display chart plt.figure() plt.axis("off") plt.imshow(chart) plt.show() def _main_(): clusters = 8 for img in sorted(os.listdir('output\\predicted\\')): print(img) dc = DominantColors('..\\..\\data\\output\\predicted\\{0}'.format(img), clusters) colors = dc.dominantColors() dc.analyseRGB() if __name__ == '__main__': _main_()
[ "sklearn.cluster.KMeans", "matplotlib.pyplot.imshow", "numpy.histogram", "scipy.cluster.vq.kmeans", "os.listdir", "cv2.resize", "numpy.arange", "matplotlib.image.imread", "scipy.cluster.vq.whiten", "matplotlib.pyplot.figure", "numpy.zeros", "cv2.cvtColor", "pandas.DataFrame", "matplotlib.pyplot.axis", "scipy.cluster.vq.kmeans.fit", "cv2.imread", "mpl_toolkits.mplot3d.Axes3D", "matplotlib.pyplot.show" ]
[((564, 590), 'cv2.imread', 'cv2.imread', (['self.IMAGEPATH'], {}), '(self.IMAGEPATH)\n', (574, 590), False, 'import cv2\n'), ((766, 827), 'cv2.resize', 'cv2.resize', (['img', '(self.BASEWIDTH, hsize)', 'PIL.Image.ANTIALIAS'], {}), '(img, (self.BASEWIDTH, hsize), PIL.Image.ANTIALIAS)\n', (776, 827), False, 'import cv2\n'), ((877, 913), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2Luv'], {}), '(img, cv2.COLOR_RGB2Luv)\n', (889, 913), False, 'import cv2\n'), ((1139, 1171), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'self.CLUSTERS'}), '(n_clusters=self.CLUSTERS)\n', (1145, 1171), False, 'from sklearn.cluster import KMeans\n'), ((1180, 1195), 'scipy.cluster.vq.kmeans.fit', 'kmeans.fit', (['img'], {}), '(img)\n', (1190, 1195), False, 'from scipy.cluster.vq import kmeans\n'), ((1652, 1679), 'matplotlib.image.imread', 'img1.imread', (['self.IMAGEPATH'], {}), '(self.IMAGEPATH)\n', (1663, 1679), True, 'from matplotlib import image as img1\n'), ((1929, 1941), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1939, 1941), True, 'import matplotlib.pyplot as plt\n'), ((1955, 1966), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (1961, 1966), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((2003, 2013), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2011, 2013), True, 'import matplotlib.pyplot as plt\n'), ((2027, 2074), 'pandas.DataFrame', 'pd.DataFrame', (["{'red': r, 'blue': b, 'green': g}"], {}), "({'red': r, 'blue': b, 'green': g})\n", (2039, 2074), True, 'import pandas as pd\n'), ((2102, 2119), 'scipy.cluster.vq.whiten', 'whiten', (["df['red']"], {}), "(df['red'])\n", (2108, 2119), False, 'from scipy.cluster.vq import whiten\n'), ((2148, 2166), 'scipy.cluster.vq.whiten', 'whiten', (["df['blue']"], {}), "(df['blue'])\n", (2154, 2166), False, 'from scipy.cluster.vq import whiten\n'), ((2196, 2215), 'scipy.cluster.vq.whiten', 'whiten', (["df['green']"], {}), "(df['green'])\n", (2202, 2215), False, 'from scipy.cluster.vq import whiten\n'), ((2322, 2382), 'scipy.cluster.vq.kmeans', 'kmeans', (["df[['scaled_red', 'scaled_green', 'scaled_blue']]", '(2)'], {}), "(df[['scaled_red', 'scaled_green', 'scaled_blue']], 2)\n", (2328, 2382), False, 'from scipy.cluster.vq import kmeans\n'), ((2712, 2732), 'matplotlib.pyplot.imshow', 'plt.imshow', (['[colors]'], {}), '([colors])\n', (2722, 2732), True, 'import matplotlib.pyplot as plt\n'), ((2741, 2751), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2749, 2751), True, 'import matplotlib.pyplot as plt\n'), ((2815, 2827), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2825, 2827), True, 'import matplotlib.pyplot as plt\n'), ((2841, 2852), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (2847, 2852), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((3007, 3017), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3015, 3017), True, 'import matplotlib.pyplot as plt\n'), ((3112, 3143), 'numpy.arange', 'np.arange', (['(0)', '(self.CLUSTERS + 1)'], {}), '(0, self.CLUSTERS + 1)\n', (3121, 3143), True, 'import numpy as np\n'), ((3205, 3246), 'numpy.histogram', 'np.histogram', (['self.LABELS'], {'bins': 'numLabels'}), '(self.LABELS, bins=numLabels)\n', (3217, 3246), True, 'import numpy as np\n'), ((3580, 3612), 'numpy.zeros', 'np.zeros', (['(50, 500, 3)', 'np.uint8'], {}), '((50, 500, 3), np.uint8)\n', (3588, 3612), True, 'import numpy as np\n'), ((4060, 4072), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4070, 4072), True, 'import matplotlib.pyplot as plt\n'), ((4081, 4096), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (4089, 4096), True, 'import matplotlib.pyplot as plt\n'), ((4105, 4122), 'matplotlib.pyplot.imshow', 'plt.imshow', (['chart'], {}), '(chart)\n', (4115, 4122), True, 'import matplotlib.pyplot as plt\n'), ((4131, 4141), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4139, 4141), True, 'import matplotlib.pyplot as plt\n'), ((4196, 4229), 'os.listdir', 'os.listdir', (['"""output\\\\predicted\\\\"""'], {}), "('output\\\\predicted\\\\')\n", (4206, 4229), False, 'import os\n')]
import torch from torch import nn import numpy as np from models.AttentionLayer import AttentionLayer from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch,\ BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP,\ BertMultiAttentionScoresP, BertAttentionClsQuery from pytorch_transformers.modeling_bert import BertAttention, BertSelfAttention from utils import visualize_attention __author__ = "<NAME>" class EmbracementLayer(nn.Module): def __init__(self, config, hidden_size, p, max_seq_length): super(EmbracementLayer, self).__init__() self.p = p self.hidden_size = hidden_size # 768 self.max_seq_length = max_seq_length # 128 if self.p == 'selfattention': self.self_attention = SelfAttention(self.hidden_size) #self.max_seq_length) # AttentionLayer(self.hidden_size) elif self.p == 'multihead_bertselfattention': self.self_attention = BertSelfAttention(config) elif self.p == 'multihead_bertselfattention_in_p': config.num_attention_heads = 1 self.self_attention = BertSelfAttentionScoresP(config) elif self.p == 'multihead_bertattention': self.self_attention = BertAttention(config) elif self.p == 'multihead_bertattention_clsquery': config.output_attentions = True self.self_attention = BertAttentionClsQuery(config, hidden_size) self.softmax = nn.Softmax() elif self.p == 'attention_clsquery': self.self_attention = AttentionLayer(self.hidden_size) elif self.p == 'attention_clsquery_weights': self.self_attention = AttentionLayer(self.hidden_size, return_att_weights=True) self.softmax = nn.Softmax(dim=-1) elif self.p == 'multiheadattention': config_att = config config_att.output_attentions = True self.self_attention = BertSelfAttentionScores(config_att) elif self.p == 'selfattention_pytorch': self.self_attention = SelfAttentionPytorch(self.max_seq_length) # 128 elif self.p == 'multiple_multihead_bertselfattention_in_p': config.num_attention_heads = 1 self.self_attention = BertMultiSelfAttentionScoresP(config) elif self.p == 'multiple_multihead_bertattention_in_p': config.num_attention_heads = 1 config.output_attentions = True self.self_attention = BertMultiAttentionScoresP(config, max_seq_length) self.softmax = nn.Softmax(dim=-1) def forward(self, output_tokens_from_bert, cls_token=None): # pooled_enc_output = bs x 768 # output_tokens_from_bert = bert_output[0] # cls_output = bert_output[1] # CLS # Note: Docking layer not needed given that all features have the same size # tokens_to_embrace = output_tokens_from_bert[:, 1:, :] # (8, 128, 768) = (bs, sequence_length (where the first index is CLS), embedding_size) tokens_to_embrace = output_tokens_from_bert[:, :, :] # (8, 128, 768) = (bs, sequence_length, embedding_size) [bs, seq_len, emb_size] = tokens_to_embrace.size() tokens_to_embrace = tokens_to_embrace.cpu().detach().numpy() # Note: Consider each token in the sequence of 128 as one modality. embraced_features_token = [] for i_bs in range(bs): # 1. Choose feature indexes to be considered in the Embrace vector if self.p == 'multinomial': # A. Multinomial distribution: randomly choose features from all 128 with same probability for each index feature probability = torch.tensor(np.ones(seq_len), dtype=torch.float) embraced_features_index = torch.multinomial(probability, emb_size, replacement=True) # shape = [768] embraced_features_index = embraced_features_index.cpu().detach().numpy() # shape = 768 elif self.p == 'multihead_bertselfattention' or self.p == 'multihead_bertattention': tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] head_mask = torch.ones([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() attention_mask = torch.zeros([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze(0).cuda() #selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, attention_mask, head_mask=None) selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, attention_mask, head_mask=head_mask) selfattention_scores = selfattention_scores[0] elif self.p == 'multihead_bertattention_clsquery': print("TODO. Use cls_token - Come back to this") tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] cls_token_bs = cls_token[i_bs, :] #cls_token_bs = torch.tensor(cls_token_bs, dtype=torch.float).unsqueeze(0).unsqueeze(0).cuda() attention_mask = torch.ones([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze(0).cuda() cls_token_bs = torch.tensor(cls_token_bs, dtype=torch.float).unsqueeze(0) cls_token_bs = cls_token_bs.repeat(self.max_seq_length, 1) cls_token_bs = cls_token_bs.unsqueeze(0).cuda() selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, head_mask=attention_mask, cls_query=cls_token_bs) selfattention_scores = self.softmax(selfattention_scores[1]) print("") elif self.p == 'attention_clsquery': tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] cls_token_bs = cls_token[i_bs, :] tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).cuda() cls_token_bs = torch.tensor(cls_token_bs, dtype=torch.float).unsqueeze(0).cuda() selfattention_scores = self.self_attention(cls_token_bs, tokens_to_embrace_bs_tensor, unsqueeze_idx=0) selfattention_scores = selfattention_scores[0] elif self.p == 'multiple_multihead_bertselfattention_in_p' or self.p == 'multiple_multihead_bertattention_in_p': tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] attention_mask = torch.ones([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze(0).cuda() selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, head_mask=attention_mask, is_visualize_attention=False) if self.p == 'multiple_multihead_bertattention_in_p': selfattention_scores = selfattention_scores.squeeze() selfattention_scores = self.softmax(selfattention_scores) # Choose features using information from self-attention multiple_embrace_vectors = [] for i in range(self.max_seq_length): # 128 score = selfattention_scores[i, :] #attention_probs_img = score.unsqueeze(0).cpu().detach().numpy() #visualize_attention(attention_probs_img) embraced_features_index = torch.multinomial(score, emb_size, replacement=True) # shape = [768] embraced_features_index = embraced_features_index.cpu().detach().numpy() # shape = 768 embraced_features_token_bs = [] for i_emb, e in enumerate(embraced_features_index): embraced_features_token_bs.append(tokens_to_embrace[i_bs, e, i_emb]) multiple_embrace_vectors.append(embraced_features_token_bs) multiple_embrace_vectors = torch.tensor(multiple_embrace_vectors, dtype=torch.float) else: # B. Self-attention used to choose most important indexes -> p = softmax(mean(self_att)) # 'selfattention_scores' shape -> (bs, 128) tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] # ADD THE NEXT 2 LINES TO CONDENSED # attention_mask_bs = attention_mask[i_bs, :] # _, selfattention_scores = self.self_attention(tokens_to_embrace_bs, attention_mask_bs) # Original attention_mask ranges from 0 to -1000 # If we want to mask the scores by multiplying between 0 and 1, we should give the attention_mask # as head_mask if self.p == 'selfattention': _, selfattention_scores = self.self_attention(tokens_to_embrace_bs) elif self.p == 'attention_clsquery_weights': tokens_to_embrace_bs = tokens_to_embrace[i_bs, :, :] cls_token_bs = cls_token[i_bs, :] tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).cuda() cls_token_bs = torch.tensor(cls_token_bs, dtype=torch.float).unsqueeze(0).cuda() selfattention_scores = self.self_attention(cls_token_bs, tokens_to_embrace_bs_tensor, unsqueeze_idx=0) selfattention_scores = selfattention_scores[1] selfattention_scores = self.softmax(selfattention_scores).squeeze() elif self.p == 'multiheadattention': # BertAttention attention_mask = torch.ones([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze(0).cuda() #selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, attention_mask, head_mask=None) selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, head_mask=attention_mask) elif self.p == 'multihead_bertselfattention_in_p': attention_mask = torch.ones([1, 1, 1, np.shape(tokens_to_embrace_bs)[0]]).cuda() tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze(0).cuda() #selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, attention_mask, head_mask=None) selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor, head_mask=attention_mask) else: # 'selfattention_pytorch' tokens_to_embrace_bs_tensor = torch.tensor(tokens_to_embrace_bs, dtype=torch.float).unsqueeze( 0).cuda() selfattention_scores = self.self_attention(tokens_to_embrace_bs_tensor) # Choose features using information from self-attention selfattention_scores = torch.tensor(selfattention_scores, dtype=torch.float) embraced_features_index = torch.multinomial(selfattention_scores, emb_size, replacement=True) # shape = [768] embraced_features_index = embraced_features_index.cpu().detach().numpy() # shape = 768 # 2. Add features into one of size (bs, embedding_size) embraced_features_token_bs = [] if self.p == 'multihead_bertselfattention' or self.p == 'multihead_bertattention': embraced_features_index = torch.sum(selfattention_scores, dim=1) embraced_features_token_bs = embraced_features_index.squeeze() embraced_features_token_bs = embraced_features_token_bs.cpu().detach().numpy() elif self.p == 'multiple_multihead_bertselfattention_in_p' or self.p == 'multiple_multihead_bertattention_in_p': embraced_features_token_bs = torch.sum(multiple_embrace_vectors, dim=0) embraced_features_token_bs = embraced_features_token_bs.squeeze() embraced_features_token_bs = embraced_features_token_bs.cpu().detach().numpy() elif self.p == 'attention_clsquery': embraced_features_token_bs = selfattention_scores.cpu().detach().numpy() else: for i_emb, e in enumerate(embraced_features_index): embraced_features_token_bs.append(tokens_to_embrace[i_bs, e, i_emb]) embraced_features_token.append(embraced_features_token_bs) # (768) embraced_features_token = torch.tensor(embraced_features_token, dtype=torch.float) # (bs, 768) return embraced_features_token
[ "models.SelfAttentionLayer.BertAttentionClsQuery", "models.SelfAttentionLayer.SelfAttentionPytorch", "torch.multinomial", "numpy.ones", "torch.nn.Softmax", "models.SelfAttentionLayer.BertMultiAttentionScoresP", "models.AttentionLayer.AttentionLayer", "models.SelfAttentionLayer.BertMultiSelfAttentionScoresP", "models.SelfAttentionLayer.BertSelfAttentionScores", "torch.tensor", "pytorch_transformers.modeling_bert.BertSelfAttention", "torch.sum", "pytorch_transformers.modeling_bert.BertAttention", "models.SelfAttentionLayer.BertSelfAttentionScoresP", "numpy.shape", "models.SelfAttentionLayer.SelfAttention" ]
[((12737, 12793), 'torch.tensor', 'torch.tensor', (['embraced_features_token'], {'dtype': 'torch.float'}), '(embraced_features_token, dtype=torch.float)\n', (12749, 12793), False, 'import torch\n'), ((800, 831), 'models.SelfAttentionLayer.SelfAttention', 'SelfAttention', (['self.hidden_size'], {}), '(self.hidden_size)\n', (813, 831), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((979, 1004), 'pytorch_transformers.modeling_bert.BertSelfAttention', 'BertSelfAttention', (['config'], {}), '(config)\n', (996, 1004), False, 'from pytorch_transformers.modeling_bert import BertAttention, BertSelfAttention\n'), ((3792, 3850), 'torch.multinomial', 'torch.multinomial', (['probability', 'emb_size'], {'replacement': '(True)'}), '(probability, emb_size, replacement=True)\n', (3809, 3850), False, 'import torch\n'), ((11707, 11745), 'torch.sum', 'torch.sum', (['selfattention_scores'], {'dim': '(1)'}), '(selfattention_scores, dim=1)\n', (11716, 11745), False, 'import torch\n'), ((1141, 1173), 'models.SelfAttentionLayer.BertSelfAttentionScoresP', 'BertSelfAttentionScoresP', (['config'], {}), '(config)\n', (1165, 1173), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((3713, 3729), 'numpy.ones', 'np.ones', (['seq_len'], {}), '(seq_len)\n', (3720, 3729), True, 'import numpy as np\n'), ((12090, 12132), 'torch.sum', 'torch.sum', (['multiple_embrace_vectors'], {'dim': '(0)'}), '(multiple_embrace_vectors, dim=0)\n', (12099, 12132), False, 'import torch\n'), ((1258, 1279), 'pytorch_transformers.modeling_bert.BertAttention', 'BertAttention', (['config'], {}), '(config)\n', (1271, 1279), False, 'from pytorch_transformers.modeling_bert import BertAttention, BertSelfAttention\n'), ((1417, 1459), 'models.SelfAttentionLayer.BertAttentionClsQuery', 'BertAttentionClsQuery', (['config', 'hidden_size'], {}), '(config, hidden_size)\n', (1438, 1459), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((1487, 1499), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (1497, 1499), False, 'from torch import nn\n'), ((1579, 1611), 'models.AttentionLayer.AttentionLayer', 'AttentionLayer', (['self.hidden_size'], {}), '(self.hidden_size)\n', (1593, 1611), False, 'from models.AttentionLayer import AttentionLayer\n'), ((5363, 5408), 'torch.tensor', 'torch.tensor', (['cls_token_bs'], {'dtype': 'torch.float'}), '(cls_token_bs, dtype=torch.float)\n', (5375, 5408), False, 'import torch\n'), ((8136, 8193), 'torch.tensor', 'torch.tensor', (['multiple_embrace_vectors'], {'dtype': 'torch.float'}), '(multiple_embrace_vectors, dtype=torch.float)\n', (8148, 8193), False, 'import torch\n'), ((11172, 11225), 'torch.tensor', 'torch.tensor', (['selfattention_scores'], {'dtype': 'torch.float'}), '(selfattention_scores, dtype=torch.float)\n', (11184, 11225), False, 'import torch\n'), ((11268, 11335), 'torch.multinomial', 'torch.multinomial', (['selfattention_scores', 'emb_size'], {'replacement': '(True)'}), '(selfattention_scores, emb_size, replacement=True)\n', (11285, 11335), False, 'import torch\n'), ((1699, 1756), 'models.AttentionLayer.AttentionLayer', 'AttentionLayer', (['self.hidden_size'], {'return_att_weights': '(True)'}), '(self.hidden_size, return_att_weights=True)\n', (1713, 1756), False, 'from models.AttentionLayer import AttentionLayer\n'), ((1784, 1802), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (1794, 1802), False, 'from torch import nn\n'), ((4374, 4427), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (4386, 4427), False, 'import torch\n'), ((6016, 6069), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (6028, 6069), False, 'import torch\n'), ((7618, 7670), 'torch.multinomial', 'torch.multinomial', (['score', 'emb_size'], {'replacement': '(True)'}), '(score, emb_size, replacement=True)\n', (7635, 7670), False, 'import torch\n'), ((1962, 1997), 'models.SelfAttentionLayer.BertSelfAttentionScores', 'BertSelfAttentionScores', (['config_att'], {}), '(config_att)\n', (1985, 1997), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((4187, 4217), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (4195, 4217), True, 'import numpy as np\n'), ((4285, 4315), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (4293, 4315), True, 'import numpy as np\n'), ((5258, 5311), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (5270, 5311), False, 'import torch\n'), ((2080, 2121), 'models.SelfAttentionLayer.SelfAttentionPytorch', 'SelfAttentionPytorch', (['self.max_seq_length'], {}), '(self.max_seq_length)\n', (2100, 2121), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((5169, 5199), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (5177, 5199), True, 'import numpy as np\n'), ((6108, 6153), 'torch.tensor', 'torch.tensor', (['cls_token_bs'], {'dtype': 'torch.float'}), '(cls_token_bs, dtype=torch.float)\n', (6120, 6153), False, 'import torch\n'), ((2274, 2311), 'models.SelfAttentionLayer.BertMultiSelfAttentionScoresP', 'BertMultiSelfAttentionScoresP', (['config'], {}), '(config)\n', (2303, 2311), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((6693, 6746), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (6705, 6746), False, 'import torch\n'), ((9258, 9311), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (9270, 9311), False, 'import torch\n'), ((2497, 2546), 'models.SelfAttentionLayer.BertMultiAttentionScoresP', 'BertMultiAttentionScoresP', (['config', 'max_seq_length'], {}), '(config, max_seq_length)\n', (2522, 2546), False, 'from models.SelfAttentionLayer import SelfAttention, SelfAttentionPytorch, BertSelfAttentionScores, BertSelfAttentionScoresP, BertMultiSelfAttentionScoresP, BertMultiAttentionScoresP, BertAttentionClsQuery\n'), ((2574, 2592), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (2584, 2592), False, 'from torch import nn\n'), ((6604, 6634), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (6612, 6634), True, 'import numpy as np\n'), ((9354, 9399), 'torch.tensor', 'torch.tensor', (['cls_token_bs'], {'dtype': 'torch.float'}), '(cls_token_bs, dtype=torch.float)\n', (9366, 9399), False, 'import torch\n'), ((9919, 9972), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (9931, 9972), False, 'import torch\n'), ((9826, 9856), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (9834, 9856), True, 'import numpy as np\n'), ((10454, 10507), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (10466, 10507), False, 'import torch\n'), ((10870, 10923), 'torch.tensor', 'torch.tensor', (['tokens_to_embrace_bs'], {'dtype': 'torch.float'}), '(tokens_to_embrace_bs, dtype=torch.float)\n', (10882, 10923), False, 'import torch\n'), ((10361, 10391), 'numpy.shape', 'np.shape', (['tokens_to_embrace_bs'], {}), '(tokens_to_embrace_bs)\n', (10369, 10391), True, 'import numpy as np\n')]
""" Functions for ionospheric modelling: see SDP memo 97 """ import astropy.units as u import numpy from astropy.coordinates import SkyCoord from data_models.memory_data_models import BlockVisibility from processing_components.calibration.operations import create_gaintable_from_blockvisibility, \ create_gaintable_from_rows from processing_components.calibration.iterators import gaintable_timeslice_iter from processing_components.image.operations import copy_image, create_empty_image_like from processing_components.visibility.base import create_visibility_from_rows from processing_components.visibility.iterators import vis_timeslice_iter from processing_library.util.coordinate_support import xyz_to_uvw, skycoord_to_lmn import logging log = logging.getLogger(__name__) def find_pierce_points(station_locations, ha, dec, phasecentre, height): """Find the pierce points for a flat screen at specified height :param station_locations: All station locations [:3] :param ha: Hour angle :param dec: Declination :param phasecentre: Phase centre :param height: Height of screen :return: """ source_direction = SkyCoord(ra=ha, dec=dec, frame='icrs', equinox='J2000') local_locations = xyz_to_uvw(station_locations, ha, dec) local_locations -= numpy.average(local_locations, axis=0) lmn = numpy.array(skycoord_to_lmn(source_direction, phasecentre)) lmn[2] += 1.0 pierce_points = local_locations + height * numpy.array(lmn) return pierce_points def create_gaintable_from_screen(vis, sc, screen, height=3e5, vis_slices=None, scale=1.0, **kwargs): """ Create gaintables from a screen calculated using ARatmospy :param vis: :param sc: Sky components for which pierce points are needed :param screen: :param height: Height (in m) of screen above telescope e.g. 3e5 :param scale: Multiply the screen by this factor :return: """ assert isinstance(vis, BlockVisibility) station_locations = vis.configuration.xyz nant = station_locations.shape[0] t2r = numpy.pi / 43200.0 gaintables = [create_gaintable_from_blockvisibility(vis, **kwargs) for i in sc] # The time in the Visibility is hour angle in seconds! for iha, rows in enumerate(vis_timeslice_iter(vis, vis_slices=vis_slices)): v = create_visibility_from_rows(vis, rows) ha = numpy.average(v.time) number_bad = 0 number_good = 0 for icomp, comp in enumerate(sc): pp = find_pierce_points(station_locations, (comp.direction.ra.rad + t2r * ha) * u.rad, comp.direction.dec, height=height, phasecentre=vis.phasecentre) scr = numpy.zeros([nant]) for ant in range(nant): pp0 = pp[ant][0:2] worldloc = [pp0[0], pp0[1], ha, 1e8] try: pixloc = screen.wcs.wcs_world2pix([worldloc], 0)[0].astype('int') scr[ant] = scale * screen.data[pixloc[3], pixloc[2], pixloc[1], pixloc[0]] number_good += 1 except: number_bad += 1 scr[ant] = 0.0 gaintables[icomp].gain[iha, :, :, :] = numpy.exp(1j * scr[:, numpy.newaxis, numpy.newaxis, numpy.newaxis]) gaintables[icomp].phasecentre = comp.direction if number_bad > 0: log.warning("create_gaintable_from_screen: %d pierce points are inside the screen image" % (number_good)) log.warning("create_gaintable_from_screen: %d pierce points are outside the screen image" % (number_bad)) return gaintables def grid_gaintable_to_screen(vis, gaintables, screen, height=3e5, gaintable_slices=None, scale=1.0, **kwargs): """ Grid a gaintable to a screen image The phases are just average per grid cell, no phase unwrapping is performed. :param vis: :param sc: Sky components for which pierce points are needed :param screen: :param height: Height (in m) of screen above telescope e.g. 3e5 :param scale: Multiply the screen by this factor :return: gridded screen image, weights image """ assert isinstance(vis, BlockVisibility) station_locations = vis.configuration.xyz nant = station_locations.shape[0] t2r = numpy.pi / 43200.0 newscreen = create_empty_image_like(screen) weights = create_empty_image_like(screen) nchan, ntimes, ny, nx = screen.shape # The time in the Visibility is hour angle in seconds! number_no_weight = 0 for gaintable in gaintables: for iha, rows in enumerate(gaintable_timeslice_iter(gaintable, gaintable_slices=gaintable_slices)): gt = create_gaintable_from_rows(gaintable, rows) ha = numpy.average(gt.time) pp = find_pierce_points(station_locations, (gt.phasecentre.ra.rad + t2r * ha) * u.rad, gt.phasecentre.dec, height=height, phasecentre=vis.phasecentre) scr = numpy.angle(gt.gain[0, :, 0, 0, 0]) wt = gt.weight[0, :, 0, 0, 0] for ant in range(nant): pp0 = pp[ant][0:2] worldloc = [pp0[0], pp0[1], ha, 1e8] pixloc = newscreen.wcs.wcs_world2pix([worldloc], 0)[0].astype('int') assert pixloc[0] >= 0 assert pixloc[0] < nx assert pixloc[1] >= 0 assert pixloc[1] < ny newscreen.data[pixloc[3], pixloc[2], pixloc[1], pixloc[0]] += wt[ant] * scr[ant] weights.data[pixloc[3], pixloc[2], pixloc[1], pixloc[0]] += wt[ant] if wt[ant] == 0.0: number_no_weight += 1 if number_no_weight > 0: print("grid_gaintable_to_screen: %d pierce points are have no weight" % (number_no_weight)) log.warning("grid_gaintable_to_screen: %d pierce points are have no weight" % (number_no_weight)) newscreen.data[weights.data > 0.0] = newscreen.data[weights.data > 0.0] / weights.data[weights.data > 0.0] return newscreen, weights def calculate_sf_from_screen(screen): """ Calculate structure function image from screen Screen axes are ['XX', 'YY', 'TIME', 'FREQ'] :param screen: :return: """ from scipy.signal import fftconvolve nchan, ntimes, ny, nx = screen.data.shape sf = numpy.zeros([nchan, 1, 2 * ny - 1, 2 * nx - 1]) for chan in range(nchan): sf[chan, 0, ...] = fftconvolve(screen.data[chan, 0, ...], screen.data[chan, 0, ::-1, ::-1]) for itime in range(ntimes): sf += fftconvolve(screen.data[chan, itime, ...], screen.data[chan, itime, ::-1, ::-1]) sf[chan, 0, ...] /= numpy.max(sf[chan, 0, ...]) sf[chan, 0, ...] = 1.0 - sf[chan, 0, ...] sf_image = copy_image(screen) sf_image.data = sf[:, :, (ny - ny // 4):(ny + ny // 4), (nx - nx // 4):(nx + nx // 4)] sf_image.wcs.wcs.crpix[0] = ny // 4 + 1 sf_image.wcs.wcs.crpix[1] = ny // 4 + 1 sf_image.wcs.wcs.crpix[2] = 1 return sf_image def plot_gaintable_on_screen(vis, gaintables, height=3e5, gaintable_slices=None, plotfile=None): """ Plot a gaintable on an ionospheric screen :param vis: :param sc: Sky components for which pierce points are needed :param height: Height (in m) of screen above telescope e.g. 3e5 :param scale: Multiply the screen by this factor :return: gridded screen image, weights image """ import matplotlib.pyplot as plt assert isinstance(vis, BlockVisibility) station_locations = vis.configuration.xyz t2r = numpy.pi / 43200.0 # The time in the Visibility is hour angle in seconds! plt.clf() for gaintable in gaintables: for iha, rows in enumerate(gaintable_timeslice_iter(gaintable, gaintable_slices=gaintable_slices)): gt = create_gaintable_from_rows(gaintable, rows) ha = numpy.average(gt.time) pp = find_pierce_points(station_locations, (gt.phasecentre.ra.rad + t2r * ha) * u.rad, gt.phasecentre.dec, height=height, phasecentre=vis.phasecentre) phases = numpy.angle(gt.gain[0, :, 0, 0, 0]) plt.scatter(pp[:,0],pp[:,1], c=phases, cmap='hsv', alpha=0.75, s=0.1) plt.title('Pierce point phases') plt.xlabel('X (m)') plt.ylabel('Y (m)') if plotfile is not None: plt.savefig(plotfile) plt.show()
[ "logging.getLogger", "matplotlib.pyplot.ylabel", "processing_components.calibration.operations.create_gaintable_from_blockvisibility", "numpy.array", "processing_components.calibration.operations.create_gaintable_from_rows", "processing_library.util.coordinate_support.skycoord_to_lmn", "matplotlib.pyplot.xlabel", "scipy.signal.fftconvolve", "numpy.max", "numpy.exp", "matplotlib.pyplot.scatter", "processing_components.image.operations.copy_image", "processing_components.visibility.base.create_visibility_from_rows", "matplotlib.pyplot.savefig", "numpy.average", "processing_components.calibration.iterators.gaintable_timeslice_iter", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "processing_components.image.operations.create_empty_image_like", "matplotlib.pyplot.clf", "astropy.coordinates.SkyCoord", "processing_components.visibility.iterators.vis_timeslice_iter", "numpy.angle", "numpy.zeros", "processing_library.util.coordinate_support.xyz_to_uvw" ]
[((757, 784), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (774, 784), False, 'import logging\n'), ((1160, 1215), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': 'ha', 'dec': 'dec', 'frame': '"""icrs"""', 'equinox': '"""J2000"""'}), "(ra=ha, dec=dec, frame='icrs', equinox='J2000')\n", (1168, 1215), False, 'from astropy.coordinates import SkyCoord\n'), ((1238, 1276), 'processing_library.util.coordinate_support.xyz_to_uvw', 'xyz_to_uvw', (['station_locations', 'ha', 'dec'], {}), '(station_locations, ha, dec)\n', (1248, 1276), False, 'from processing_library.util.coordinate_support import xyz_to_uvw, skycoord_to_lmn\n'), ((1300, 1338), 'numpy.average', 'numpy.average', (['local_locations'], {'axis': '(0)'}), '(local_locations, axis=0)\n', (1313, 1338), False, 'import numpy\n'), ((4395, 4426), 'processing_components.image.operations.create_empty_image_like', 'create_empty_image_like', (['screen'], {}), '(screen)\n', (4418, 4426), False, 'from processing_components.image.operations import copy_image, create_empty_image_like\n'), ((4441, 4472), 'processing_components.image.operations.create_empty_image_like', 'create_empty_image_like', (['screen'], {}), '(screen)\n', (4464, 4472), False, 'from processing_components.image.operations import copy_image, create_empty_image_like\n'), ((6536, 6583), 'numpy.zeros', 'numpy.zeros', (['[nchan, 1, 2 * ny - 1, 2 * nx - 1]'], {}), '([nchan, 1, 2 * ny - 1, 2 * nx - 1])\n', (6547, 6583), False, 'import numpy\n'), ((6975, 6993), 'processing_components.image.operations.copy_image', 'copy_image', (['screen'], {}), '(screen)\n', (6985, 6993), False, 'from processing_components.image.operations import copy_image, create_empty_image_like\n'), ((7884, 7893), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (7891, 7893), True, 'import matplotlib.pyplot as plt\n'), ((8612, 8644), 'matplotlib.pyplot.title', 'plt.title', (['"""Pierce point phases"""'], {}), "('Pierce point phases')\n", (8621, 8644), True, 'import matplotlib.pyplot as plt\n'), ((8649, 8668), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X (m)"""'], {}), "('X (m)')\n", (8659, 8668), True, 'import matplotlib.pyplot as plt\n'), ((8673, 8692), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y (m)"""'], {}), "('Y (m)')\n", (8683, 8692), True, 'import matplotlib.pyplot as plt\n'), ((8762, 8772), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8770, 8772), True, 'import matplotlib.pyplot as plt\n'), ((1366, 1412), 'processing_library.util.coordinate_support.skycoord_to_lmn', 'skycoord_to_lmn', (['source_direction', 'phasecentre'], {}), '(source_direction, phasecentre)\n', (1381, 1412), False, 'from processing_library.util.coordinate_support import xyz_to_uvw, skycoord_to_lmn\n'), ((2119, 2171), 'processing_components.calibration.operations.create_gaintable_from_blockvisibility', 'create_gaintable_from_blockvisibility', (['vis'], {}), '(vis, **kwargs)\n', (2156, 2171), False, 'from processing_components.calibration.operations import create_gaintable_from_blockvisibility, create_gaintable_from_rows\n'), ((2280, 2326), 'processing_components.visibility.iterators.vis_timeslice_iter', 'vis_timeslice_iter', (['vis'], {'vis_slices': 'vis_slices'}), '(vis, vis_slices=vis_slices)\n', (2298, 2326), False, 'from processing_components.visibility.iterators import vis_timeslice_iter\n'), ((2341, 2379), 'processing_components.visibility.base.create_visibility_from_rows', 'create_visibility_from_rows', (['vis', 'rows'], {}), '(vis, rows)\n', (2368, 2379), False, 'from processing_components.visibility.base import create_visibility_from_rows\n'), ((2393, 2414), 'numpy.average', 'numpy.average', (['v.time'], {}), '(v.time)\n', (2406, 2414), False, 'import numpy\n'), ((6641, 6713), 'scipy.signal.fftconvolve', 'fftconvolve', (['screen.data[chan, 0, ...]', 'screen.data[chan, 0, ::-1, ::-1]'], {}), '(screen.data[chan, 0, ...], screen.data[chan, 0, ::-1, ::-1])\n', (6652, 6713), False, 'from scipy.signal import fftconvolve\n'), ((6877, 6904), 'numpy.max', 'numpy.max', (['sf[chan, 0, ...]'], {}), '(sf[chan, 0, ...])\n', (6886, 6904), False, 'import numpy\n'), ((8735, 8756), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plotfile'], {}), '(plotfile)\n', (8746, 8756), True, 'import matplotlib.pyplot as plt\n'), ((1479, 1495), 'numpy.array', 'numpy.array', (['lmn'], {}), '(lmn)\n', (1490, 1495), False, 'import numpy\n'), ((2722, 2741), 'numpy.zeros', 'numpy.zeros', (['[nant]'], {}), '([nant])\n', (2733, 2741), False, 'import numpy\n'), ((3264, 3333), 'numpy.exp', 'numpy.exp', (['(1.0j * scr[:, numpy.newaxis, numpy.newaxis, numpy.newaxis])'], {}), '(1.0j * scr[:, numpy.newaxis, numpy.newaxis, numpy.newaxis])\n', (3273, 3333), False, 'import numpy\n'), ((4667, 4737), 'processing_components.calibration.iterators.gaintable_timeslice_iter', 'gaintable_timeslice_iter', (['gaintable'], {'gaintable_slices': 'gaintable_slices'}), '(gaintable, gaintable_slices=gaintable_slices)\n', (4691, 4737), False, 'from processing_components.calibration.iterators import gaintable_timeslice_iter\n'), ((4757, 4800), 'processing_components.calibration.operations.create_gaintable_from_rows', 'create_gaintable_from_rows', (['gaintable', 'rows'], {}), '(gaintable, rows)\n', (4783, 4800), False, 'from processing_components.calibration.operations import create_gaintable_from_blockvisibility, create_gaintable_from_rows\n'), ((4818, 4840), 'numpy.average', 'numpy.average', (['gt.time'], {}), '(gt.time)\n', (4831, 4840), False, 'import numpy\n'), ((5175, 5210), 'numpy.angle', 'numpy.angle', (['gt.gain[0, :, 0, 0, 0]'], {}), '(gt.gain[0, :, 0, 0, 0])\n', (5186, 5210), False, 'import numpy\n'), ((6768, 6853), 'scipy.signal.fftconvolve', 'fftconvolve', (['screen.data[chan, itime, ...]', 'screen.data[chan, itime, ::-1, ::-1]'], {}), '(screen.data[chan, itime, ...], screen.data[chan, itime, ::-1, ::-1]\n )\n', (6779, 6853), False, 'from scipy.signal import fftconvolve\n'), ((7962, 8032), 'processing_components.calibration.iterators.gaintable_timeslice_iter', 'gaintable_timeslice_iter', (['gaintable'], {'gaintable_slices': 'gaintable_slices'}), '(gaintable, gaintable_slices=gaintable_slices)\n', (7986, 8032), False, 'from processing_components.calibration.iterators import gaintable_timeslice_iter\n'), ((8052, 8095), 'processing_components.calibration.operations.create_gaintable_from_rows', 'create_gaintable_from_rows', (['gaintable', 'rows'], {}), '(gaintable, rows)\n', (8078, 8095), False, 'from processing_components.calibration.operations import create_gaintable_from_blockvisibility, create_gaintable_from_rows\n'), ((8113, 8135), 'numpy.average', 'numpy.average', (['gt.time'], {}), '(gt.time)\n', (8126, 8135), False, 'import numpy\n'), ((8477, 8512), 'numpy.angle', 'numpy.angle', (['gt.gain[0, :, 0, 0, 0]'], {}), '(gt.gain[0, :, 0, 0, 0])\n', (8488, 8512), False, 'import numpy\n'), ((8525, 8597), 'matplotlib.pyplot.scatter', 'plt.scatter', (['pp[:, 0]', 'pp[:, 1]'], {'c': 'phases', 'cmap': '"""hsv"""', 'alpha': '(0.75)', 's': '(0.1)'}), "(pp[:, 0], pp[:, 1], c=phases, cmap='hsv', alpha=0.75, s=0.1)\n", (8536, 8597), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np import matplotlib.pyplot as plt N = 4 ind = np.arange(N) # the x locations for the groups width = 0.4 # the width of the bars fig, ax = plt.subplots() ax.set_ylim(0,11) # outliers only #ax2.set_ylim(0,35) # most of the data #ax.spines['bottom'].set_visible(False) #ax2.spines['top'].set_visible(False) ax.xaxis.tick_top() #ax.tick_params(labeltop='off') # don't put tick labels at the top ax.xaxis.tick_bottom() fig.subplots_adjust(hspace=0.1) # call-site-specific noneV = (5.729, 6.966, 7.953, 8.524) rectsNone = ax.bar(ind, noneV, width, color='w', hatch=' ') #ax2.bar(ind, noneV, width, color='w') # call-target-specific uncached classCached = (2.560, 3.616, 5.357, 6.846) rectsClassCached = ax.bar(ind+width, classCached, width, color='w', hatch='o') #ax2.bar(ind+width, classCached, width, color='w', hatch='/') # call-target-specific cached #classUncached = (2.634, 3.358, 5.583, 6.838) #rectsClassUncached = ax.bar(ind+2*width, classUncached, width, color='w', hatch='o') #ax2.bar(ind+2*width, classUncached, width, color='w', hatch='o') # add some text for labels, title and axes ticks #ax2.set_ylabel('Runtime (ms)') #ax.set_title('Average rendering runtime per frame') ax.set_ylabel('Runtime (s) / 100.000 invocations') ax.set_xticks(ind+width+0.14) ax.set_xticklabels( ('(a) 1 target \n (10 kwargs)', '(b) 2 targets \n (10 kwargs; \n 10 kwargs)', '(c) 2 targets \n (10 kwargs; \n 5 kwargs + rest kwargs)', '(d) 1 target \n (5 kwargs + rest kwargs)') ) #ax2.set_yticks(ax2.get_yticks()[:-1]) ax.set_yticks(ax.get_yticks()[1:]) ax.legend( (rectsNone[0], rectsClassCached[0]), ('call-site-specific', 'call-target-specific') , loc=4) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() if height == 0: ax.text(rect.get_x()+rect.get_width()/2., height+2, 'n/a', ha='center', va='bottom', rotation='vertical') else: ax.text(rect.get_x()+rect.get_width()/2., height+0.2, '%.2f'%float(height), ha='center', va='bottom', rotation='vertical') autolabel(rectsNone) autolabel(rectsClassCached) plt.show()
[ "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.show" ]
[((66, 78), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (75, 78), True, 'import numpy as np\n'), ((165, 179), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (177, 179), True, 'import matplotlib.pyplot as plt\n'), ((2178, 2188), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2186, 2188), True, 'import matplotlib.pyplot as plt\n')]
#+ echo=False import numpy from biobakery_workflows import utilities, visualizations, files from anadama2 import PweaveDocument document=PweaveDocument() # get the variables for this document generation task vars = document.get_vars() # determine the document format pdf_format = True if vars["format"] == "pdf" else False # read in the DNA samples (dna_paired_columns, dna_orphan_columns), dna_samples, (dna_paired_data, dna_orphan_data) = visualizations.qc_read_counts(document, vars["dna_read_counts"]) # read in the RNA samples (rna_paired_columns, rna_orphan_columns), rna_samples, (rna_paired_data, rna_orphan_data) = visualizations.qc_read_counts(document, vars["rna_read_counts"]) #' # Quality Control #' <% visualizations.ShotGun.print_qc_intro_caption("{} DNA and {} RNA ".format(len(dna_samples),len(rna_samples)), rna_paired_columns[2:], paired=True) %> #+ echo=False #' ## DNA Samples Quality Control #' ### DNA Samples Tables of Filtered Reads #+ echo=False document.write_table(["# Sample"]+dna_paired_columns, dna_samples, dna_paired_data, files.ShotGunVis.path("qc_counts_paired",document.data_folder)) table_message=visualizations.show_table_max_rows(document, dna_paired_data, dna_samples, dna_paired_columns, "DNA Paired end reads", files.ShotGunVis.path("qc_counts_paired"), format_data_comma=True) #' <%= table_message %> #+ echo=False document.write_table(["# Sample"]+dna_orphan_columns, dna_samples, dna_orphan_data, files.ShotGunVis.path("qc_counts_orphan",document.data_folder)) table_message=visualizations.show_table_max_rows(document, dna_orphan_data, dna_samples, dna_orphan_columns, "DNA Orphan reads", files.ShotGunVis.path("qc_counts_orphan"), format_data_comma=True) #' <%= table_message %> #' <% if pdf_format: print("\clearpage") %> #+ echo=False # plot the microbial reads ratios dna_microbial_reads, dna_microbial_labels = utilities.microbial_read_proportion_multiple_databases( dna_paired_data, dna_paired_columns, dna_orphan_data) document.write_table(["# Sample"]+dna_microbial_labels, dna_samples, dna_microbial_reads, files.ShotGunVis.path("microbial_counts",document.data_folder)) table_message=visualizations.show_table_max_rows(document, dna_microbial_reads, dna_samples, dna_microbial_labels, "DNA microbial read proportion", files.ShotGunVis.path("microbial_counts")) #' <%= visualizations.ShotGun.captions["microbial_ratios"] %> #' <%= table_message %> #' ### DNA Samples Plots of Filtered Reads #+ echo=False document.plot_grouped_barchart(numpy.transpose(dna_paired_data), row_labels=dna_paired_columns, column_labels=dna_samples, title="DNA Paired end reads", ylabel="Read count (in millions)", legend_title="Filter", yaxis_in_millions=True) #+ echo=False document.plot_grouped_barchart(numpy.transpose(dna_orphan_data), row_labels=dna_orphan_columns, column_labels=dna_samples, title="DNA Orphan reads", ylabel="Read count (in millions)", legend_title="Filter", yaxis_in_millions=True) #' ## RNA Samples Quality Control #' ### RNA Samples Tables of Filtered Reads #+ echo=False document.write_table(["# Sample"]+rna_paired_columns, rna_samples, rna_paired_data, files.ShotGunVis.path("rna_qc_counts_paired",document.data_folder)) table_message=visualizations.show_table_max_rows(document, rna_paired_data, rna_samples, rna_paired_columns, "RNA Paired end reads", files.ShotGunVis.path("rna_qc_counts_paired"), format_data_comma=True) #' <%= table_message %> #+ echo=False document.write_table(["# Sample"]+rna_orphan_columns, rna_samples, rna_orphan_data, files.ShotGunVis.path("rna_qc_counts_orphan",document.data_folder)) table_message=visualizations.show_table_max_rows(document, rna_orphan_data, rna_samples, rna_orphan_columns, "RNA Orphan reads", files.ShotGunVis.path("rna_qc_counts_orphan"), format_data_comma=True) #' <%= table_message %> #' <% if pdf_format: print("\clearpage") %> #+ echo=False # write and plot the microbial reads ratios rna_microbial_reads, rna_microbial_labels = utilities.microbial_read_proportion_multiple_databases( rna_paired_data, rna_paired_columns, rna_orphan_data) document.write_table(["# Sample"]+rna_microbial_labels, rna_samples, rna_microbial_reads, files.ShotGunVis.path("rna_microbial_counts",document.data_folder)) table_message=visualizations.show_table_max_rows(document, rna_microbial_reads, rna_samples, rna_microbial_labels, "RNA microbial read proportion", files.ShotGunVis.path("rna_microbial_counts")) #' <%= visualizations.ShotGun.captions["microbial_ratios"] %> #' <%= table_message %> #' ### RNA Samples Plots of Filtered Reads #+ echo=False document.plot_grouped_barchart(numpy.transpose(rna_paired_data), row_labels=rna_paired_columns, column_labels=rna_samples, title="RNA Paired end reads", ylabel="Read count (in millions)", legend_title="Filter", yaxis_in_millions=True) #+ echo=False document.plot_grouped_barchart(numpy.transpose(rna_orphan_data), row_labels=rna_orphan_columns, column_labels=rna_samples, title="RNA Orphan reads", ylabel="Read count (in millions)", legend_title="Filter", yaxis_in_millions=True)
[ "biobakery_workflows.files.ShotGunVis.path", "numpy.transpose", "anadama2.PweaveDocument", "biobakery_workflows.utilities.microbial_read_proportion_multiple_databases", "biobakery_workflows.visualizations.qc_read_counts" ]
[((141, 157), 'anadama2.PweaveDocument', 'PweaveDocument', ([], {}), '()\n', (155, 157), False, 'from anadama2 import PweaveDocument\n'), ((450, 514), 'biobakery_workflows.visualizations.qc_read_counts', 'visualizations.qc_read_counts', (['document', "vars['dna_read_counts']"], {}), "(document, vars['dna_read_counts'])\n", (479, 514), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((634, 698), 'biobakery_workflows.visualizations.qc_read_counts', 'visualizations.qc_read_counts', (['document', "vars['rna_read_counts']"], {}), "(document, vars['rna_read_counts'])\n", (663, 698), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((1919, 2031), 'biobakery_workflows.utilities.microbial_read_proportion_multiple_databases', 'utilities.microbial_read_proportion_multiple_databases', (['dna_paired_data', 'dna_paired_columns', 'dna_orphan_data'], {}), '(dna_paired_data,\n dna_paired_columns, dna_orphan_data)\n', (1973, 2031), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((4082, 4194), 'biobakery_workflows.utilities.microbial_read_proportion_multiple_databases', 'utilities.microbial_read_proportion_multiple_databases', (['rna_paired_data', 'rna_paired_columns', 'rna_orphan_data'], {}), '(rna_paired_data,\n rna_paired_columns, rna_orphan_data)\n', (4136, 4194), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((1077, 1140), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""qc_counts_paired"""', 'document.data_folder'], {}), "('qc_counts_paired', document.data_folder)\n", (1098, 1140), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((1279, 1320), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""qc_counts_paired"""'], {}), "('qc_counts_paired')\n", (1300, 1320), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((1478, 1541), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""qc_counts_orphan"""', 'document.data_folder'], {}), "('qc_counts_orphan', document.data_folder)\n", (1499, 1541), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((1676, 1717), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""qc_counts_orphan"""'], {}), "('qc_counts_orphan')\n", (1697, 1717), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((2128, 2191), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""microbial_counts"""', 'document.data_folder'], {}), "('microbial_counts', document.data_folder)\n", (2149, 2191), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((2349, 2390), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""microbial_counts"""'], {}), "('microbial_counts')\n", (2370, 2390), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((2572, 2604), 'numpy.transpose', 'numpy.transpose', (['dna_paired_data'], {}), '(dna_paired_data)\n', (2587, 2604), False, 'import numpy\n'), ((2831, 2863), 'numpy.transpose', 'numpy.transpose', (['dna_orphan_data'], {}), '(dna_orphan_data)\n', (2846, 2863), False, 'import numpy\n'), ((3223, 3290), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_qc_counts_paired"""', 'document.data_folder'], {}), "('rna_qc_counts_paired', document.data_folder)\n", (3244, 3290), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((3429, 3474), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_qc_counts_paired"""'], {}), "('rna_qc_counts_paired')\n", (3450, 3474), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((3632, 3699), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_qc_counts_orphan"""', 'document.data_folder'], {}), "('rna_qc_counts_orphan', document.data_folder)\n", (3653, 3699), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((3834, 3879), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_qc_counts_orphan"""'], {}), "('rna_qc_counts_orphan')\n", (3855, 3879), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((4291, 4358), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_microbial_counts"""', 'document.data_folder'], {}), "('rna_microbial_counts', document.data_folder)\n", (4312, 4358), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((4516, 4561), 'biobakery_workflows.files.ShotGunVis.path', 'files.ShotGunVis.path', (['"""rna_microbial_counts"""'], {}), "('rna_microbial_counts')\n", (4537, 4561), False, 'from biobakery_workflows import utilities, visualizations, files\n'), ((4744, 4776), 'numpy.transpose', 'numpy.transpose', (['rna_paired_data'], {}), '(rna_paired_data)\n', (4759, 4776), False, 'import numpy\n'), ((5003, 5035), 'numpy.transpose', 'numpy.transpose', (['rna_orphan_data'], {}), '(rna_orphan_data)\n', (5018, 5035), False, 'import numpy\n')]
''' This example provides three examples of a simple plot of 1-D data. 1. a publication-ready single column figure, which is printed to png (600 dpi), pdf, and svg 2. a presentation-ready figure on a black background Four steps are involved in each figure: - load/generate the data - construct a 1d plot (figure, axis, line series) for the spectrum - size the figure and font - print the figure to a pdf ''' import jalapeno.colors.svgcolors as jc import jalapeno.plots.plots as jpp import jalapeno.plots.colorscheme as jpc import numpy as np # generate the data x = np.linspace(0, 2*np.pi, 600) y = np.abs(np.cos(2*x)) # make a 1d plot fig, ax, line = jpp.make_1d_plot(linecolor=jc.darkorange, maxx=max(x/np.pi), maxy=1.01, xname='x/pi', yname='cos(2x)') # plot the data on our 1d plot line.set_data(x/np.pi,y) # size the figure and print it to pdf jpp.SquareFigure().set_size(fig) jpp.print_fig(fig, 'xy-for-publication', ['pdf', 'png', 'svg'], dpi=600) # make another 1d plot fig, ax, line = jpp.make_1d_plot(colorscheme=jpc.FigColors.scheme('black'), linecolor=jc.coral, linewidth=4, showgrid='off', maxx=max(x/np.pi), maxy=1.01, xname='x/pi', yname='cos(2x)') # plot the data on our 1d plot line.set_data(x/np.pi, y) # size the figure and print it to pdf jpp.SquareFigure(width=4, fontsize=12).set_size(fig) jpp.print_fig(fig, 'xy-for-presentation', exts=['pdf']) # way 1, use print_fig and provide exts=['pdf'] jpp.print_fig_to_pdf(fig, 'xy-for-presentation') # way 2, use print_fig_to_pdf
[ "jalapeno.plots.plots.print_fig", "jalapeno.plots.colorscheme.FigColors.scheme", "jalapeno.plots.plots.SquareFigure", "numpy.linspace", "numpy.cos", "jalapeno.plots.plots.print_fig_to_pdf" ]
[((573, 603), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(600)'], {}), '(0, 2 * np.pi, 600)\n', (584, 603), True, 'import numpy as np\n'), ((1024, 1096), 'jalapeno.plots.plots.print_fig', 'jpp.print_fig', (['fig', '"""xy-for-publication"""', "['pdf', 'png', 'svg']"], {'dpi': '(600)'}), "(fig, 'xy-for-publication', ['pdf', 'png', 'svg'], dpi=600)\n", (1037, 1096), True, 'import jalapeno.plots.plots as jpp\n'), ((1688, 1743), 'jalapeno.plots.plots.print_fig', 'jpp.print_fig', (['fig', '"""xy-for-presentation"""'], {'exts': "['pdf']"}), "(fig, 'xy-for-presentation', exts=['pdf'])\n", (1701, 1743), True, 'import jalapeno.plots.plots as jpp\n'), ((1793, 1841), 'jalapeno.plots.plots.print_fig_to_pdf', 'jpp.print_fig_to_pdf', (['fig', '"""xy-for-presentation"""'], {}), "(fig, 'xy-for-presentation')\n", (1813, 1841), True, 'import jalapeno.plots.plots as jpp\n'), ((613, 626), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (619, 626), True, 'import numpy as np\n'), ((991, 1009), 'jalapeno.plots.plots.SquareFigure', 'jpp.SquareFigure', ([], {}), '()\n', (1007, 1009), True, 'import jalapeno.plots.plots as jpp\n'), ((1166, 1195), 'jalapeno.plots.colorscheme.FigColors.scheme', 'jpc.FigColors.scheme', (['"""black"""'], {}), "('black')\n", (1186, 1195), True, 'import jalapeno.plots.colorscheme as jpc\n'), ((1635, 1673), 'jalapeno.plots.plots.SquareFigure', 'jpp.SquareFigure', ([], {'width': '(4)', 'fontsize': '(12)'}), '(width=4, fontsize=12)\n', (1651, 1673), True, 'import jalapeno.plots.plots as jpp\n')]
from __future__ import division from __future__ import print_function from pathlib import Path import sys project_path = Path(__file__).resolve().parents[1] sys.path.append(str(project_path)) from keras.layers import Dense, Activation, Dropout from keras.models import Model, Sequential from keras.regularizers import l2 from keras.optimizers import Adam import keras.backend as K import numpy as np import time import tensorflow as tf import os from core.utils import * from core.layers.graph_cnn_layer import GraphCNN from sklearn.preprocessing import normalize # Set random seed seed = 123 np.random.seed(seed) tf.random.set_seed(seed) # Settings flags = tf.compat.v1.flags FLAGS = flags.FLAGS flags.DEFINE_string('dataset', 'brc_microarray_usa', 'Dataset string.') flags.DEFINE_string('embedding_method', 'ge', 'Name of the embedding method.') #Check dataset availability if not os.path.isdir("{}/data/parsed_input/{}".format(project_path, FLAGS.dataset)): sys.exit("{} dataset is not available under data/parsed_input/".format(FLAGS.dataset)) if not os.path.isdir("{}/data/output/{}/embedding/{}".format(project_path, FLAGS.dataset, FLAGS.embedding_method)): os.makedirs("{}/data/output/{}/embedding/{}".format(project_path, FLAGS.dataset, FLAGS.embedding_method)) print("--------------------------------------------") print("--------------------------------------------") print("Hyper-parameters:") print("Dataset: {}".format(FLAGS.dataset)) print("Embedding method: {}".format(FLAGS.embedding_method)) print("--------------------------------------------") print("--------------------------------------------") # Prepare Data X, A, Y = load_training_data(dataset=FLAGS.dataset) Y_train, Y_val, Y_test, train_idx, val_idx, test_idx, train_mask = get_splits_for_learning(Y, dataset=FLAGS.dataset) # Normalize gene expression X = normalize(X, norm='l1') #for positive non-zero entries, it's equivalent to: X /= X.sum(1).reshape(-1, 1) #Save the node emmbeddings np.savetxt("{}/data/output/{}/embedding/{}/embeddings.txt".format(project_path, FLAGS.dataset, FLAGS.embedding_method), X, delimiter="\t") print("Embeddings saved in /data/output/{}/embedding/{}/embeddings.txt".format(FLAGS.dataset, FLAGS.embedding_method))
[ "tensorflow.random.set_seed", "sklearn.preprocessing.normalize", "numpy.random.seed", "pathlib.Path" ]
[((623, 643), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (637, 643), True, 'import numpy as np\n'), ((645, 669), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (663, 669), True, 'import tensorflow as tf\n'), ((1912, 1935), 'sklearn.preprocessing.normalize', 'normalize', (['X'], {'norm': '"""l1"""'}), "(X, norm='l1')\n", (1921, 1935), False, 'from sklearn.preprocessing import normalize\n'), ((127, 141), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (131, 141), False, 'from pathlib import Path\n')]
import io import zlib import numpy as np def maybe_compress(str, compress): return zlib.compress(str) if compress else str def maybe_decompress(str, decompress): return zlib.decompress(str) if decompress else str def serialize_numpy(arr: np.ndarray, compress: bool = False) -> str: """Serializes numpy array to string with optional zlib compression. Args: arr (np.ndarray): Numpy array to serialize. compress (bool, optional): Whether to compress resulting string with zlib or not. Defaults to False. Returns: str: serialized string """ buf = io.BytesIO() assert isinstance(arr, np.ndarray) np.save(buf, arr) result = buf.getvalue() return maybe_compress(result, compress) def deserialize_numpy(serialized_string: str, decompress: bool = False) -> np.ndarray: """Deserializes numpy array from compressed string. Args: serialized_string (str): Serialized numpy array decompress (bool, optional): Whether to decompress string with zlib before laoding. Defaults to False. Returns: np.ndarray: deserialized numpy array """ str = maybe_decompress(serialized_string, decompress) buf = io.BytesIO(str) return np.load(buf)
[ "io.BytesIO", "zlib.compress", "numpy.save", "numpy.load", "zlib.decompress" ]
[((616, 628), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (626, 628), False, 'import io\n'), ((672, 689), 'numpy.save', 'np.save', (['buf', 'arr'], {}), '(buf, arr)\n', (679, 689), True, 'import numpy as np\n'), ((1232, 1247), 'io.BytesIO', 'io.BytesIO', (['str'], {}), '(str)\n', (1242, 1247), False, 'import io\n'), ((1259, 1271), 'numpy.load', 'np.load', (['buf'], {}), '(buf)\n', (1266, 1271), True, 'import numpy as np\n'), ((90, 108), 'zlib.compress', 'zlib.compress', (['str'], {}), '(str)\n', (103, 108), False, 'import zlib\n'), ((182, 202), 'zlib.decompress', 'zlib.decompress', (['str'], {}), '(str)\n', (197, 202), False, 'import zlib\n')]
from cv2 import fastNlMeansDenoisingColored from cv2 import cvtColor from cv2 import bitwise_not,threshold,getRotationMatrix2D from cv2 import warpAffine,filter2D,imread from cv2 import THRESH_BINARY,COLOR_BGR2GRAY,THRESH_OTSU from cv2 import INTER_CUBIC,BORDER_REPLICATE,minAreaRect from numpy import column_stack,array,where from matplotlib.pyplot import imshow,xticks,yticks from pytesseract import image_to_string,pytesseract from PIL import Image class ImageProcess: '''this function is removing noise from the image''' def remove_noise(image): image = fastNlMeansDenoisingColored(image,None,20,10,7,21) return image '''this function is removing skewness. first, it calculate the angle and accordingly rotate image''' def remove_skew(image): in_gray = cvtColor(image, COLOR_BGR2GRAY) in_gray = bitwise_not(in_gray) thresh_pic = threshold(in_gray, 0, 255,THRESH_BINARY | THRESH_OTSU)[1] coords_x_y = column_stack(where(thresh_pic > 0)) angle = minAreaRect(coords_x_y)[-1] if angle < -45: angle = -(90 + angle) else: angle = -angle (h, w) = image.shape[:2] center_of_pic = (w // 2, h // 2) M = getRotationMatrix2D(center_of_pic, angle, 1.0) image = warpAffine(image, M, (w, h),flags=INTER_CUBIC, borderMode=BORDER_REPLICATE) return image '''for removing blurness from the image, this function increase sharpness of the image.''' def shapness_blur(image): sharpen_kernel = array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) image = filter2D(image, -1, sharpen_kernel) return image '''using pytesseract, this function extracting text from the image.''' def to_text(image): try: pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" string_from_image = image_to_string(image,lang='eng') except Exception: pytesseract.tesseract_cmd = r"C:\Program Files(x86)\Tesseract-OCR\tesseract.exe" string_from_image = image_to_string(image,lang='eng') return string_from_image ##plot image in output def plot_image(image): imshow(image) xticks([]) yticks([])
[ "matplotlib.pyplot.imshow", "cv2.warpAffine", "cv2.getRotationMatrix2D", "matplotlib.pyplot.xticks", "cv2.fastNlMeansDenoisingColored", "cv2.threshold", "numpy.where", "cv2.filter2D", "cv2.minAreaRect", "numpy.array", "matplotlib.pyplot.yticks", "cv2.cvtColor", "pytesseract.image_to_string", "cv2.bitwise_not" ]
[((576, 631), 'cv2.fastNlMeansDenoisingColored', 'fastNlMeansDenoisingColored', (['image', 'None', '(20)', '(10)', '(7)', '(21)'], {}), '(image, None, 20, 10, 7, 21)\n', (603, 631), False, 'from cv2 import fastNlMeansDenoisingColored\n'), ((804, 835), 'cv2.cvtColor', 'cvtColor', (['image', 'COLOR_BGR2GRAY'], {}), '(image, COLOR_BGR2GRAY)\n', (812, 835), False, 'from cv2 import cvtColor\n'), ((854, 874), 'cv2.bitwise_not', 'bitwise_not', (['in_gray'], {}), '(in_gray)\n', (865, 874), False, 'from cv2 import bitwise_not, threshold, getRotationMatrix2D\n'), ((1240, 1286), 'cv2.getRotationMatrix2D', 'getRotationMatrix2D', (['center_of_pic', 'angle', '(1.0)'], {}), '(center_of_pic, angle, 1.0)\n', (1259, 1286), False, 'from cv2 import bitwise_not, threshold, getRotationMatrix2D\n'), ((1303, 1379), 'cv2.warpAffine', 'warpAffine', (['image', 'M', '(w, h)'], {'flags': 'INTER_CUBIC', 'borderMode': 'BORDER_REPLICATE'}), '(image, M, (w, h), flags=INTER_CUBIC, borderMode=BORDER_REPLICATE)\n', (1313, 1379), False, 'from cv2 import warpAffine, filter2D, imread\n'), ((1555, 1603), 'numpy.array', 'array', (['[[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]'], {}), '([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n', (1560, 1603), False, 'from numpy import column_stack, array, where\n'), ((1614, 1649), 'cv2.filter2D', 'filter2D', (['image', '(-1)', 'sharpen_kernel'], {}), '(image, -1, sharpen_kernel)\n', (1622, 1649), False, 'from cv2 import warpAffine, filter2D, imread\n'), ((2219, 2232), 'matplotlib.pyplot.imshow', 'imshow', (['image'], {}), '(image)\n', (2225, 2232), False, 'from matplotlib.pyplot import imshow, xticks, yticks\n'), ((2241, 2251), 'matplotlib.pyplot.xticks', 'xticks', (['[]'], {}), '([])\n', (2247, 2251), False, 'from matplotlib.pyplot import imshow, xticks, yticks\n'), ((2260, 2270), 'matplotlib.pyplot.yticks', 'yticks', (['[]'], {}), '([])\n', (2266, 2270), False, 'from matplotlib.pyplot import imshow, xticks, yticks\n'), ((896, 951), 'cv2.threshold', 'threshold', (['in_gray', '(0)', '(255)', '(THRESH_BINARY | THRESH_OTSU)'], {}), '(in_gray, 0, 255, THRESH_BINARY | THRESH_OTSU)\n', (905, 951), False, 'from cv2 import bitwise_not, threshold, getRotationMatrix2D\n'), ((988, 1009), 'numpy.where', 'where', (['(thresh_pic > 0)'], {}), '(thresh_pic > 0)\n', (993, 1009), False, 'from numpy import column_stack, array, where\n'), ((1027, 1050), 'cv2.minAreaRect', 'minAreaRect', (['coords_x_y'], {}), '(coords_x_y)\n', (1038, 1050), False, 'from cv2 import INTER_CUBIC, BORDER_REPLICATE, minAreaRect\n'), ((1904, 1938), 'pytesseract.image_to_string', 'image_to_string', (['image'], {'lang': '"""eng"""'}), "(image, lang='eng')\n", (1919, 1938), False, 'from pytesseract import image_to_string, pytesseract\n'), ((2089, 2123), 'pytesseract.image_to_string', 'image_to_string', (['image'], {'lang': '"""eng"""'}), "(image, lang='eng')\n", (2104, 2123), False, 'from pytesseract import image_to_string, pytesseract\n')]
import cv2 import numpy as np import matplotlib.pyplot as plt from findpoint import FindPoint class LineDetector: def __init__(self,img): self.frame = None self.leftx = None self.rightx = None # self.output = None self.frame = 0 self.frame_list = [] self.findpoint = FindPoint(img) def sliding_window(self,x_start_L,x_start_R,img): x_location = None out_img = np.dstack((img,img,img)) height = img.shape[0] width = img.shape[1] window_height = 5 nwindows = 30 nonzero = img.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) point_list_left = list() point_list_right = list() margin = 20 minpix = 10 left_lane_inds = [] right_lane_inds = [] good_left_inds = \ ((nonzerox >= x_start_L-20) & (nonzeroy >= 300)& (nonzeroy <= 400) & (nonzerox <= x_start_L+20)).nonzero()[ 0] good_right_inds = ((nonzerox >= x_start_R-40) & (nonzeroy >= 300)& (nonzeroy <= 400) & ( nonzerox <= x_start_R+20)).nonzero()[0] line_exist_flag = None y_current = None x_current = None good_center_inds = None p_cut = None # check the minpix before left start line # if minpix is enough on left, draw left, then draw right depends on left # else draw right, then draw left depends on right # lx_current = 120 # ly_current = 350 # rx_current = 550 # ry_current = 350 if len(good_left_inds) > minpix and len(good_right_inds) > minpix: line_flag = 3 lx_current = np.int(np.mean(nonzerox[good_left_inds])) ly_current = np.int(np.mean(nonzeroy[good_left_inds])) rx_current = np.int(np.mean(nonzerox[good_right_inds])) ry_current = np.int(np.mean(nonzeroy[good_right_inds])) elif len(good_left_inds) > minpix: line_flag = 1 lx_current = np.int(np.mean(nonzerox[good_left_inds])) ly_current = np.int(np.mean(nonzeroy[good_left_inds])) rx_current = None ry_current = None max_y = y_current elif len(good_right_inds) > minpix: line_flag = 2 rx_current = nonzerox[good_right_inds[np.argmax(nonzeroy[good_right_inds])]] ry_current = np.int(np.max(nonzeroy[good_right_inds])) lx_current = None ly_current = None else: line_flag = 4 # rx_current # ry_current # if line_flag ==3: # for i in range(len(good_left_inds)): # cv2.circle(out_img, (nonzerox[good_left_inds[i]], nonzeroy[good_left_inds[i]]), 1, (0, 255, 0), -1) # for i in range(len(good_right_inds)): # cv2.circle(out_img, (nonzerox[good_right_inds[i]], nonzeroy[good_right_inds[i]]), 1, (255,0, 0), -1) # for window in range(0, nwindows): # print('x',x_location) if line_flag != 4: # it's just for visualization of the valid inds in the region for i in range(len(good_left_inds)): cv2.circle(out_img, (nonzerox[good_left_inds[i]], nonzeroy[good_left_inds[i]]), 1, (0, 255, 0), -1) for i in range(len(good_right_inds)): cv2.circle(out_img, (nonzerox[good_right_inds[i]], nonzeroy[good_right_inds[i]]), 1, (255,0, 0), -1) # window sliding and draw # print(lx_current) # print(rx_current) for window in range(0, nwindows): # if lx_current and rx_current: # # print(line_flag) # cv2.circle(out_img,(lx_current,ly_current-window*window_height-3),3,(0,0,255),-1) # cv2.circle(out_img,(rx_current,ry_current-window*window_height-3),3,(0,0,255),-1) # mean_x = (lx_current + rx_current)/2 # cv2.circle(out_img,(mean_x,ry_current-window*window_height-3),3,(0,255,255),-1) # point_list_left.append((lx_current, ly_current-window*window_height-3)) # point_list_right.append((rx_current,ry_current-window*window_height-3)) if lx_current and rx_current: cv2.circle(out_img,(lx_current,ly_current-window*window_height-3),3,(0,0,255),-1) cv2.circle(out_img,(rx_current,ry_current-window*window_height-3),3,(0,0,255),-1) mean_x = (lx_current + rx_current)/2 cv2.circle(out_img,(mean_x,ry_current-window*window_height-3),3,(0,255,255),-1) point_list_left.append((lx_current, ly_current-window*window_height-3)) point_list_right.append((rx_current,ry_current-window*window_height-3)) elif lx_current: cv2.circle(out_img,(lx_current,ly_current-window*window_height-3),3,(0,0,255),-1) mean_x = (lx_current + width/2) cv2.circle(out_img,(mean_x,ly_current-window*window_height-3),3,(0,255,255),-1) point_list_left.append((lx_current, ly_current-window*window_height-3)) elif rx_current: # cv2.circle(out_img,(lx_current,ly_current-window*window_height-3),3,(0,0,255),-1) cv2.circle(out_img,(rx_current,ry_current-window*window_height-3),3,(0,0,255),-1) mean_x = (rx_current-width/2)/2 cv2.circle(out_img,(mean_x,ry_current-window*window_height-3),3,(0,255,255),-1) # point_list_left.append((lx_current, ly_current-window*window_height-3)) point_list_right.append((rx_current,ry_current-window*window_height-3)) if line_flag == 3: l_win_y_low = ly_current - (window + 1) * window_height l_win_y_high = ly_current - (window) * window_height l_win_x_low = lx_current - margin l_win_x_high = lx_current + margin r_win_y_low = ry_current - (window + 1) * window_height r_win_y_high = ry_current - (window) * window_height r_win_x_low = rx_current - margin r_win_x_high = rx_current + margin # draw rectangle # 0.33 is for width of the road cv2.rectangle(out_img, (l_win_x_low, l_win_y_low), (l_win_x_high, l_win_y_high), (0, 255, 0), 1) cv2.rectangle(out_img, (r_win_x_low, r_win_y_low), (r_win_x_high, r_win_y_high), (255,0, 0), 1) good_left_inds = ((nonzeroy >= l_win_y_low) & (nonzeroy < l_win_y_high) & (nonzerox >= l_win_x_low) & ( nonzerox < l_win_x_high)).nonzero()[0] good_right_inds = ((nonzeroy >= r_win_y_low) & (nonzeroy < r_win_y_high) & (nonzerox >= r_win_x_low) & ( nonzerox < r_win_x_high)).nonzero()[0] # check num of indicies in square and put next location to current if len(good_left_inds) > minpix: lx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rx_current = np.int(np.mean(nonzerox[good_right_inds])) # 338~344 is for recognize line which is yellow line in processed image(you can check in imshow) # if (l_win_y_low >= 338 and l_win_y_low < 344) and (r_win_y_low >= 338 and r_win_y_low < 344): # # 0.165 is the half of the road(0.33) x_location = rx_current - lx_current + 75 elif line_flag == 1: # rectangle x,y range init win_y_low = ly_current - (window + 1) * window_height win_y_high = ly_current - (window) * window_height win_x_low = lx_current - margin win_x_high = lx_current + margin # draw rectangle # 0.33 is for width of the road cv2.rectangle(out_img, (win_x_low, win_y_low), (win_x_high, win_y_high), (0, 255, 0), 1) # cv2.rectangle(out_img, (win_x_low + int(width * 0.33), win_y_low), # (win_x_high + int(width * 0.33), win_y_high), (255, 0, 0), 1) # indicies of dots in nonzerox in one square good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_x_low) & ( nonzerox < win_x_high)).nonzero()[0] # check num of indicies in square and put next location to current if len(good_left_inds) > minpix: # x_current = np.int(np.mean(nonzerox[good_left_inds])) lx_current = np.int(np.mean(nonzerox[good_left_inds])) # elif nonzeroy[left_lane_inds] != [] and nonzerox[left_lane_inds] != []: # p_left = np.polyfit(nonzeroy[left_lane_inds], nonzerox[left_lane_inds], 2) # x_current = np.int(np.polyval(p_left, win_y_high)) # # 338~344 is for recognize line which is yellow line in processed image(you can check in imshow) # if win_y_low >= 338 and win_y_low < 344: # # 0.165 is the half of the road(0.33) # x_location = x_current + 180 elif line_flag ==2: win_y_low = ry_current - (window + 1) * window_height win_y_high = ry_current - (window) * window_height win_x_low = rx_current - margin win_x_high = rx_current + margin # cv2.rectangle(out_img, (win_x_low , win_y_low), # (win_x_high, win_y_high), (0, 255, 0), 1) cv2.rectangle(out_img, (win_x_low, win_y_low), (win_x_high, win_y_high), (255, 0, 0), 1) good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_x_low) & ( nonzerox < win_x_high)).nonzero()[0] if len(good_right_inds) > minpix: # x_current = np.int(np.mean(nonzerox[good_right_inds])) rx_current = np.int(np.mean(nonzerox[good_right_inds])) # elif nonzeroy[right_lane_inds] != [] and nonzerox[right_lane_inds] != []: # p_right = np.polyfit(nonzeroy[right_lane_inds], nonzerox[right_lane_inds], 2) # x_current = np.int(np.polyval(p_right, win_y_high)) # if win_y_low >= 338 and win_y_low < 344: # # 0.165 is the half of the road(0.33) # x_location = x_current - 250 # left_lane_inds.extend(good_left_inds) # right_lane_inds.extend(good_right_inds) # left_lane_inds = np.concatenate(left_lane_inds) # right_lane_inds = np.concatenate(right_lane_inds) # else: return out_img, x_location, point_list_left, point_list_right def main(self,img): x_start_l,x_start_r = self.findpoint.findpoint(img) output , x_location, point_list_left, point_list_right = self.sliding_window(x_start_l,x_start_r,img) return output, x_location, point_list_left, point_list_right
[ "cv2.rectangle", "numpy.dstack", "numpy.mean", "findpoint.FindPoint", "numpy.argmax", "numpy.max", "numpy.array", "cv2.circle" ]
[((330, 344), 'findpoint.FindPoint', 'FindPoint', (['img'], {}), '(img)\n', (339, 344), False, 'from findpoint import FindPoint\n'), ((444, 470), 'numpy.dstack', 'np.dstack', (['(img, img, img)'], {}), '((img, img, img))\n', (453, 470), True, 'import numpy as np\n'), ((629, 649), 'numpy.array', 'np.array', (['nonzero[0]'], {}), '(nonzero[0])\n', (637, 649), True, 'import numpy as np\n'), ((669, 689), 'numpy.array', 'np.array', (['nonzero[1]'], {}), '(nonzero[1])\n', (677, 689), True, 'import numpy as np\n'), ((1739, 1772), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (1746, 1772), True, 'import numpy as np\n'), ((1806, 1839), 'numpy.mean', 'np.mean', (['nonzeroy[good_left_inds]'], {}), '(nonzeroy[good_left_inds])\n', (1813, 1839), True, 'import numpy as np\n'), ((1873, 1907), 'numpy.mean', 'np.mean', (['nonzerox[good_right_inds]'], {}), '(nonzerox[good_right_inds])\n', (1880, 1907), True, 'import numpy as np\n'), ((1941, 1975), 'numpy.mean', 'np.mean', (['nonzeroy[good_right_inds]'], {}), '(nonzeroy[good_right_inds])\n', (1948, 1975), True, 'import numpy as np\n'), ((3271, 3375), 'cv2.circle', 'cv2.circle', (['out_img', '(nonzerox[good_left_inds[i]], nonzeroy[good_left_inds[i]])', '(1)', '(0, 255, 0)', '(-1)'], {}), '(out_img, (nonzerox[good_left_inds[i]], nonzeroy[good_left_inds[i\n ]]), 1, (0, 255, 0), -1)\n', (3281, 3375), False, 'import cv2\n'), ((3437, 3543), 'cv2.circle', 'cv2.circle', (['out_img', '(nonzerox[good_right_inds[i]], nonzeroy[good_right_inds[i]])', '(1)', '(255, 0, 0)', '(-1)'], {}), '(out_img, (nonzerox[good_right_inds[i]], nonzeroy[good_right_inds\n [i]]), 1, (255, 0, 0), -1)\n', (3447, 3543), False, 'import cv2\n'), ((2079, 2112), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (2086, 2112), True, 'import numpy as np\n'), ((2146, 2179), 'numpy.mean', 'np.mean', (['nonzeroy[good_left_inds]'], {}), '(nonzeroy[good_left_inds])\n', (2153, 2179), True, 'import numpy as np\n'), ((4387, 4486), 'cv2.circle', 'cv2.circle', (['out_img', '(lx_current, ly_current - window * window_height - 3)', '(3)', '(0, 0, 255)', '(-1)'], {}), '(out_img, (lx_current, ly_current - window * window_height - 3), \n 3, (0, 0, 255), -1)\n', (4397, 4486), False, 'import cv2\n'), ((4489, 4588), 'cv2.circle', 'cv2.circle', (['out_img', '(rx_current, ry_current - window * window_height - 3)', '(3)', '(0, 0, 255)', '(-1)'], {}), '(out_img, (rx_current, ry_current - window * window_height - 3), \n 3, (0, 0, 255), -1)\n', (4499, 4588), False, 'import cv2\n'), ((4648, 4745), 'cv2.circle', 'cv2.circle', (['out_img', '(mean_x, ry_current - window * window_height - 3)', '(3)', '(0, 255, 255)', '(-1)'], {}), '(out_img, (mean_x, ry_current - window * window_height - 3), 3, (\n 0, 255, 255), -1)\n', (4658, 4745), False, 'import cv2\n'), ((6528, 6628), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(l_win_x_low, l_win_y_low)', '(l_win_x_high, l_win_y_high)', '(0, 255, 0)', '(1)'], {}), '(out_img, (l_win_x_low, l_win_y_low), (l_win_x_high,\n l_win_y_high), (0, 255, 0), 1)\n', (6541, 6628), False, 'import cv2\n'), ((6645, 6745), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(r_win_x_low, r_win_y_low)', '(r_win_x_high, r_win_y_high)', '(255, 0, 0)', '(1)'], {}), '(out_img, (r_win_x_low, r_win_y_low), (r_win_x_high,\n r_win_y_high), (255, 0, 0), 1)\n', (6658, 6745), False, 'import cv2\n'), ((2462, 2495), 'numpy.max', 'np.max', (['nonzeroy[good_right_inds]'], {}), '(nonzeroy[good_right_inds])\n', (2468, 2495), True, 'import numpy as np\n'), ((4965, 5064), 'cv2.circle', 'cv2.circle', (['out_img', '(lx_current, ly_current - window * window_height - 3)', '(3)', '(0, 0, 255)', '(-1)'], {}), '(out_img, (lx_current, ly_current - window * window_height - 3), \n 3, (0, 0, 255), -1)\n', (4975, 5064), False, 'import cv2\n'), ((5119, 5216), 'cv2.circle', 'cv2.circle', (['out_img', '(mean_x, ly_current - window * window_height - 3)', '(3)', '(0, 255, 255)', '(-1)'], {}), '(out_img, (mean_x, ly_current - window * window_height - 3), 3, (\n 0, 255, 255), -1)\n', (5129, 5216), False, 'import cv2\n'), ((8287, 8379), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_x_low, win_y_low)', '(win_x_high, win_y_high)', '(0, 255, 0)', '(1)'], {}), '(out_img, (win_x_low, win_y_low), (win_x_high, win_y_high), (0,\n 255, 0), 1)\n', (8300, 8379), False, 'import cv2\n'), ((2391, 2427), 'numpy.argmax', 'np.argmax', (['nonzeroy[good_right_inds]'], {}), '(nonzeroy[good_right_inds])\n', (2400, 2427), True, 'import numpy as np\n'), ((5448, 5547), 'cv2.circle', 'cv2.circle', (['out_img', '(rx_current, ry_current - window * window_height - 3)', '(3)', '(0, 0, 255)', '(-1)'], {}), '(out_img, (rx_current, ry_current - window * window_height - 3), \n 3, (0, 0, 255), -1)\n', (5458, 5547), False, 'import cv2\n'), ((5602, 5699), 'cv2.circle', 'cv2.circle', (['out_img', '(mean_x, ry_current - window * window_height - 3)', '(3)', '(0, 255, 255)', '(-1)'], {}), '(out_img, (mean_x, ry_current - window * window_height - 3), 3, (\n 0, 255, 255), -1)\n', (5612, 5699), False, 'import cv2\n'), ((7314, 7347), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (7321, 7347), True, 'import numpy as np\n'), ((7447, 7481), 'numpy.mean', 'np.mean', (['nonzerox[good_right_inds]'], {}), '(nonzerox[good_right_inds])\n', (7454, 7481), True, 'import numpy as np\n'), ((10145, 10238), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_x_low, win_y_low)', '(win_x_high, win_y_high)', '(255, 0, 0)', '(1)'], {}), '(out_img, (win_x_low, win_y_low), (win_x_high, win_y_high), (\n 255, 0, 0), 1)\n', (10158, 10238), False, 'import cv2\n'), ((9079, 9112), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (9086, 9112), True, 'import numpy as np\n'), ((10601, 10635), 'numpy.mean', 'np.mean', (['nonzerox[good_right_inds]'], {}), '(nonzerox[good_right_inds])\n', (10608, 10635), True, 'import numpy as np\n')]
import numpy as np from matplotlib import _api from .axes_divider import make_axes_locatable, Size from .mpl_axes import Axes @_api.delete_parameter("3.3", "add_all") def make_rgb_axes(ax, pad=0.01, axes_class=None, add_all=True, **kwargs): """ Parameters ---------- pad : float Fraction of the axes height. """ divider = make_axes_locatable(ax) pad_size = pad * Size.AxesY(ax) xsize = ((1-2*pad)/3) * Size.AxesX(ax) ysize = ((1-2*pad)/3) * Size.AxesY(ax) divider.set_horizontal([Size.AxesX(ax), pad_size, xsize]) divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize]) ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1)) ax_rgb = [] if axes_class is None: try: axes_class = ax._axes_class except AttributeError: axes_class = type(ax) for ny in [4, 2, 0]: ax1 = axes_class(ax.get_figure(), ax.get_position(original=True), sharex=ax, sharey=ax, **kwargs) locator = divider.new_locator(nx=2, ny=ny) ax1.set_axes_locator(locator) for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels(): t.set_visible(False) try: for axis in ax1.axis.values(): axis.major_ticklabels.set_visible(False) except AttributeError: pass ax_rgb.append(ax1) if add_all: fig = ax.get_figure() for ax1 in ax_rgb: fig.add_axes(ax1) return ax_rgb @_api.deprecated("3.3", alternative="ax.imshow(np.dstack([r, g, b]))") def imshow_rgb(ax, r, g, b, **kwargs): return ax.imshow(np.dstack([r, g, b]), **kwargs) class RGBAxes: """ 4-panel imshow (RGB, R, G, B). Layout: +---------------+-----+ | | R | + +-----+ | RGB | G | + +-----+ | | B | +---------------+-----+ Subclasses can override the ``_defaultAxesClass`` attribute. Attributes ---------- RGB : ``_defaultAxesClass`` The axes object for the three-channel imshow. R : ``_defaultAxesClass`` The axes object for the red channel imshow. G : ``_defaultAxesClass`` The axes object for the green channel imshow. B : ``_defaultAxesClass`` The axes object for the blue channel imshow. """ _defaultAxesClass = Axes @_api.delete_parameter("3.3", "add_all") def __init__(self, *args, pad=0, add_all=True, **kwargs): """ Parameters ---------- pad : float, default: 0 fraction of the axes height to put as padding. add_all : bool, default: True Whether to add the {rgb, r, g, b} axes to the figure. This parameter is deprecated. axes_class : matplotlib.axes.Axes *args Unpacked into axes_class() init for RGB **kwargs Unpacked into axes_class() init for RGB, R, G, B axes """ axes_class = kwargs.pop("axes_class", self._defaultAxesClass) self.RGB = ax = axes_class(*args, **kwargs) if add_all: ax.get_figure().add_axes(ax) else: kwargs["add_all"] = add_all # only show deprecation in that case self.R, self.G, self.B = make_rgb_axes( ax, pad=pad, axes_class=axes_class, **kwargs) # Set the line color and ticks for the axes. for ax1 in [self.RGB, self.R, self.G, self.B]: ax1.axis[:].line.set_color("w") ax1.axis[:].major_ticks.set_markeredgecolor("w") @_api.deprecated("3.3") def add_RGB_to_figure(self): """Add red, green and blue axes to the RGB composite's axes figure.""" self.RGB.get_figure().add_axes(self.R) self.RGB.get_figure().add_axes(self.G) self.RGB.get_figure().add_axes(self.B) def imshow_rgb(self, r, g, b, **kwargs): """ Create the four images {rgb, r, g, b}. Parameters ---------- r, g, b : array-like The red, green, and blue arrays. kwargs : imshow kwargs kwargs get unpacked into the imshow calls for the four images. Returns ------- rgb : matplotlib.image.AxesImage r : matplotlib.image.AxesImage g : matplotlib.image.AxesImage b : matplotlib.image.AxesImage """ if not (r.shape == g.shape == b.shape): raise ValueError( f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match') RGB = np.dstack([r, g, b]) R = np.zeros_like(RGB) R[:, :, 0] = r G = np.zeros_like(RGB) G[:, :, 1] = g B = np.zeros_like(RGB) B[:, :, 2] = b im_rgb = self.RGB.imshow(RGB, **kwargs) im_r = self.R.imshow(R, **kwargs) im_g = self.G.imshow(G, **kwargs) im_b = self.B.imshow(B, **kwargs) return im_rgb, im_r, im_g, im_b @_api.deprecated("3.3", alternative="RGBAxes") class RGBAxesBase(RGBAxes): pass
[ "numpy.dstack", "matplotlib._api.delete_parameter", "numpy.zeros_like", "matplotlib._api.deprecated" ]
[((130, 169), 'matplotlib._api.delete_parameter', '_api.delete_parameter', (['"""3.3"""', '"""add_all"""'], {}), "('3.3', 'add_all')\n", (151, 169), False, 'from matplotlib import _api\n'), ((1527, 1596), 'matplotlib._api.deprecated', '_api.deprecated', (['"""3.3"""'], {'alternative': '"""ax.imshow(np.dstack([r, g, b]))"""'}), "('3.3', alternative='ax.imshow(np.dstack([r, g, b]))')\n", (1542, 1596), False, 'from matplotlib import _api\n'), ((5031, 5076), 'matplotlib._api.deprecated', '_api.deprecated', (['"""3.3"""'], {'alternative': '"""RGBAxes"""'}), "('3.3', alternative='RGBAxes')\n", (5046, 5076), False, 'from matplotlib import _api\n'), ((2463, 2502), 'matplotlib._api.delete_parameter', '_api.delete_parameter', (['"""3.3"""', '"""add_all"""'], {}), "('3.3', 'add_all')\n", (2484, 2502), False, 'from matplotlib import _api\n'), ((3656, 3678), 'matplotlib._api.deprecated', '_api.deprecated', (['"""3.3"""'], {}), "('3.3')\n", (3671, 3678), False, 'from matplotlib import _api\n'), ((1657, 1677), 'numpy.dstack', 'np.dstack', (['[r, g, b]'], {}), '([r, g, b])\n', (1666, 1677), True, 'import numpy as np\n'), ((4631, 4651), 'numpy.dstack', 'np.dstack', (['[r, g, b]'], {}), '([r, g, b])\n', (4640, 4651), True, 'import numpy as np\n'), ((4664, 4682), 'numpy.zeros_like', 'np.zeros_like', (['RGB'], {}), '(RGB)\n', (4677, 4682), True, 'import numpy as np\n'), ((4718, 4736), 'numpy.zeros_like', 'np.zeros_like', (['RGB'], {}), '(RGB)\n', (4731, 4736), True, 'import numpy as np\n'), ((4772, 4790), 'numpy.zeros_like', 'np.zeros_like', (['RGB'], {}), '(RGB)\n', (4785, 4790), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the SCICO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. r""" Regularized Abel Inversion ========================== This example demonstrates a TV-regularized Abel inversion using an Abel projector based on PyAbel :cite:`pyabel-2022` """ import numpy as np import scico.numpy as snp from scico import functional, linop, loss, metric, plot from scico.examples import create_circular_phantom from scico.linop.abel import AbelProjector from scico.optimize.admm import ADMM, LinearSubproblemSolver from scico.util import device_info """ Create a ground truth image. """ N = 256 # phantom size x_gt = create_circular_phantom((N, N), [0.4 * N, 0.2 * N, 0.1 * N], [1, 0, 0.5]) """ Set up the forward operator and create a test measurement """ A = AbelProjector(x_gt.shape) y = A @ x_gt np.random.seed(12345) y = y + np.random.normal(size=y.shape).astype(np.float32) ATy = A.T @ y """ Set up ADMM solver object. """ λ = 1.9e1 # L1 norm regularization parameter ρ = 4.9e1 # ADMM penalty parameter maxiter = 100 # number of ADMM iterations cg_tol = 1e-4 # CG relative tolerance cg_maxiter = 25 # maximum CG iterations per ADMM iteration # Note the use of anisotropic TV. Isotropic TV would require use of L21Norm. g = λ * functional.L1Norm() C = linop.FiniteDifference(input_shape=x_gt.shape) f = loss.SquaredL2Loss(y=y, A=A) x_inv = A.inverse(y) x0 = snp.clip(x_inv, 0, 1.0) solver = ADMM( f=f, g_list=[g], C_list=[C], rho_list=[ρ], x0=x0, maxiter=maxiter, subproblem_solver=LinearSubproblemSolver(cg_kwargs={"tol": cg_tol, "maxiter": cg_maxiter}), itstat_options={"display": True, "period": 5}, ) """ Run the solver. """ print(f"Solving on {device_info()}\n") solver.solve() hist = solver.itstat_object.history(transpose=True) x_tv = snp.clip(solver.x, 0, 1.0) """ Show results. """ norm = plot.matplotlib.colors.Normalize(vmin=-0.1, vmax=1.2) fig, ax = plot.subplots(nrows=2, ncols=2, figsize=(12, 12)) plot.imview(x_gt, title="Ground Truth", cmap=plot.cm.Blues, fig=fig, ax=ax[0, 0], norm=norm) plot.imview(y, title="Measurement", cmap=plot.cm.Blues, fig=fig, ax=ax[0, 1]) plot.imview( x_inv, title="Inverse Abel: %.2f (dB)" % metric.psnr(x_gt, x_inv), cmap=plot.cm.Blues, fig=fig, ax=ax[1, 0], norm=norm, ) plot.imview( x_tv, title="TV Regularized Inversion: %.2f (dB)" % metric.psnr(x_gt, x_tv), cmap=plot.cm.Blues, fig=fig, ax=ax[1, 1], norm=norm, ) fig.show() input("\nWaiting for input to close figures and exit")
[ "scico.linop.abel.AbelProjector", "scico.functional.L1Norm", "scico.plot.subplots", "scico.plot.matplotlib.colors.Normalize", "numpy.random.normal", "scico.examples.create_circular_phantom", "scico.plot.imview", "scico.linop.FiniteDifference", "scico.optimize.admm.LinearSubproblemSolver", "numpy.random.seed", "scico.numpy.clip", "scico.loss.SquaredL2Loss", "scico.util.device_info", "scico.metric.psnr" ]
[((748, 821), 'scico.examples.create_circular_phantom', 'create_circular_phantom', (['(N, N)', '[0.4 * N, 0.2 * N, 0.1 * N]', '[1, 0, 0.5]'], {}), '((N, N), [0.4 * N, 0.2 * N, 0.1 * N], [1, 0, 0.5])\n', (771, 821), False, 'from scico.examples import create_circular_phantom\n'), ((894, 919), 'scico.linop.abel.AbelProjector', 'AbelProjector', (['x_gt.shape'], {}), '(x_gt.shape)\n', (907, 919), False, 'from scico.linop.abel import AbelProjector\n'), ((933, 954), 'numpy.random.seed', 'np.random.seed', (['(12345)'], {}), '(12345)\n', (947, 954), True, 'import numpy as np\n'), ((1398, 1444), 'scico.linop.FiniteDifference', 'linop.FiniteDifference', ([], {'input_shape': 'x_gt.shape'}), '(input_shape=x_gt.shape)\n', (1420, 1444), False, 'from scico import functional, linop, loss, metric, plot\n'), ((1450, 1478), 'scico.loss.SquaredL2Loss', 'loss.SquaredL2Loss', ([], {'y': 'y', 'A': 'A'}), '(y=y, A=A)\n', (1468, 1478), False, 'from scico import functional, linop, loss, metric, plot\n'), ((1506, 1529), 'scico.numpy.clip', 'snp.clip', (['x_inv', '(0)', '(1.0)'], {}), '(x_inv, 0, 1.0)\n', (1514, 1529), True, 'import scico.numpy as snp\n'), ((1925, 1951), 'scico.numpy.clip', 'snp.clip', (['solver.x', '(0)', '(1.0)'], {}), '(solver.x, 0, 1.0)\n', (1933, 1951), True, 'import scico.numpy as snp\n'), ((1983, 2036), 'scico.plot.matplotlib.colors.Normalize', 'plot.matplotlib.colors.Normalize', ([], {'vmin': '(-0.1)', 'vmax': '(1.2)'}), '(vmin=-0.1, vmax=1.2)\n', (2015, 2036), False, 'from scico import functional, linop, loss, metric, plot\n'), ((2047, 2096), 'scico.plot.subplots', 'plot.subplots', ([], {'nrows': '(2)', 'ncols': '(2)', 'figsize': '(12, 12)'}), '(nrows=2, ncols=2, figsize=(12, 12))\n', (2060, 2096), False, 'from scico import functional, linop, loss, metric, plot\n'), ((2097, 2194), 'scico.plot.imview', 'plot.imview', (['x_gt'], {'title': '"""Ground Truth"""', 'cmap': 'plot.cm.Blues', 'fig': 'fig', 'ax': 'ax[0, 0]', 'norm': 'norm'}), "(x_gt, title='Ground Truth', cmap=plot.cm.Blues, fig=fig, ax=ax[\n 0, 0], norm=norm)\n", (2108, 2194), False, 'from scico import functional, linop, loss, metric, plot\n'), ((2190, 2267), 'scico.plot.imview', 'plot.imview', (['y'], {'title': '"""Measurement"""', 'cmap': 'plot.cm.Blues', 'fig': 'fig', 'ax': 'ax[0, 1]'}), "(y, title='Measurement', cmap=plot.cm.Blues, fig=fig, ax=ax[0, 1])\n", (2201, 2267), False, 'from scico import functional, linop, loss, metric, plot\n'), ((1375, 1394), 'scico.functional.L1Norm', 'functional.L1Norm', ([], {}), '()\n', (1392, 1394), False, 'from scico import functional, linop, loss, metric, plot\n'), ((1659, 1731), 'scico.optimize.admm.LinearSubproblemSolver', 'LinearSubproblemSolver', ([], {'cg_kwargs': "{'tol': cg_tol, 'maxiter': cg_maxiter}"}), "(cg_kwargs={'tol': cg_tol, 'maxiter': cg_maxiter})\n", (1681, 1731), False, 'from scico.optimize.admm import ADMM, LinearSubproblemSolver\n'), ((963, 993), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'y.shape'}), '(size=y.shape)\n', (979, 993), True, 'import numpy as np\n'), ((1832, 1845), 'scico.util.device_info', 'device_info', ([], {}), '()\n', (1843, 1845), False, 'from scico.util import device_info\n'), ((2330, 2354), 'scico.metric.psnr', 'metric.psnr', (['x_gt', 'x_inv'], {}), '(x_gt, x_inv)\n', (2341, 2354), False, 'from scico import functional, linop, loss, metric, plot\n'), ((2500, 2523), 'scico.metric.psnr', 'metric.psnr', (['x_gt', 'x_tv'], {}), '(x_gt, x_tv)\n', (2511, 2523), False, 'from scico import functional, linop, loss, metric, plot\n')]
import numpy as np import scipy.stats as sp from concept import Concept def info_gain(prev_dist, new_dist): return sp.entropy(prev_dist) - sp.entropy(new_dist) def main(): attributes = range(10) num_concepts = 5 concept_size = 4 concept_space = Concept(attributes, num_concepts, concept_size) problem1 = [(1, 2, 3, 4), (3, 4, 5, 6), (2, 4, 5, 7), (2, 3, 5, 8), (2, 3, 4, 5)] init_belief = np.ones(num_concepts) / num_concepts for msg in [2, 3, 4, 5]: new_belief = concept_space.bayesian_update(init_belief, problem1, msg) print(info_gain(init_belief, new_belief)) init_belief = new_belief print(info_gain(np.ones(num_concepts) / num_concepts, new_belief)) print('%%%%%%%%%%%%%%%%%%%%%%') problem2 = [(0, 2, 3), (4, 7, 9), (4, 7), (0, 2, 4, 9)] init_belief = np.ones(4) / 4 for msg in [7] * 8: new_belief = concept_space.bayesian_update(init_belief, problem2, msg) print(info_gain(init_belief, new_belief)) init_belief = new_belief print(info_gain(np.ones(4) / 4, [0, 0, 1, 0])) if __name__ == '__main__': main()
[ "scipy.stats.entropy", "numpy.ones", "concept.Concept" ]
[((253, 300), 'concept.Concept', 'Concept', (['attributes', 'num_concepts', 'concept_size'], {}), '(attributes, num_concepts, concept_size)\n', (260, 300), False, 'from concept import Concept\n'), ((117, 138), 'scipy.stats.entropy', 'sp.entropy', (['prev_dist'], {}), '(prev_dist)\n', (127, 138), True, 'import scipy.stats as sp\n'), ((141, 161), 'scipy.stats.entropy', 'sp.entropy', (['new_dist'], {}), '(new_dist)\n', (151, 161), True, 'import scipy.stats as sp\n'), ((399, 420), 'numpy.ones', 'np.ones', (['num_concepts'], {}), '(num_concepts)\n', (406, 420), True, 'import numpy as np\n'), ((781, 791), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (788, 791), True, 'import numpy as np\n'), ((624, 645), 'numpy.ones', 'np.ones', (['num_concepts'], {}), '(num_concepts)\n', (631, 645), True, 'import numpy as np\n'), ((978, 988), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (985, 988), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # %reset -f """ @author: <NAME> """ # Demonstration of MAEcce in PLS modeling import matplotlib.figure as figure import matplotlib.pyplot as plt import numpy as np from dcekit.validation import mae_cce from sklearn import datasets from sklearn.cross_decomposition import PLSRegression from sklearn.model_selection import GridSearchCV, train_test_split # settings number_of_training_samples = 50 # 30, 50, 100, 300, 500, 1000, 3000, for example number_of_test_samples = 10000 number_of_x_variables = 30 # 10, 30, 50, 100, 300, 500, 1000, 3000, for example number_of_y_randomization = 50 max_pls_component_number = 20 fold_number = 5 # generate sample dataset x, y = datasets.make_regression(n_samples=number_of_training_samples + number_of_test_samples, n_features=number_of_x_variables, n_informative=10, noise=30, random_state=number_of_training_samples + number_of_x_variables) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=number_of_test_samples, random_state=0) # autoscaling autoscaled_x_train = (x_train - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1) autoscaled_y_train = (y_train - y_train.mean()) / y_train.std(ddof=1) autoscaled_x_test = (x_test - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1) # cross-validation pls_components = np.arange(1, max_pls_component_number + 1) cv_model = GridSearchCV(PLSRegression(), {'n_components': pls_components}, cv=fold_number) cv_model.fit(autoscaled_x_train, autoscaled_y_train) # modeling and prediction model = getattr(cv_model, 'estimator') hyperparameters = list(cv_model.best_params_.keys()) for hyperparameter in hyperparameters: setattr(model, hyperparameter, cv_model.best_params_[hyperparameter]) model.fit(autoscaled_x_train, autoscaled_y_train) estimated_y_train = np.ndarray.flatten(model.predict(autoscaled_x_train)) estimated_y_train = estimated_y_train * y_train.std(ddof=1) + y_train.mean() predicted_y_test = np.ndarray.flatten(model.predict(autoscaled_x_test)) predicted_y_test = predicted_y_test * y_train.std(ddof=1) + y_train.mean() # MAEcce mae_cce_train = mae_cce(cv_model, x_train, y_train, number_of_y_randomization=number_of_y_randomization, do_autoscaling=True, random_state=0) # yy-plot for test data plt.figure(figsize=figure.figaspect(1)) plt.scatter(y_test, predicted_y_test) y_max = np.max(np.array([np.array(y_test), predicted_y_test])) y_min = np.min(np.array([np.array(y_test), predicted_y_test])) plt.plot([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], [y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], 'k-') plt.ylim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)) plt.xlim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)) plt.xlabel('Actual Y') plt.ylabel('Estimated Y') plt.show() # r2p, RMSEp, MAEp for test data print('r2p: {0}'.format(float(1 - sum((y_test - predicted_y_test) ** 2) / sum((y_test - y_test.mean()) ** 2)))) print('RMSEp: {0}'.format(float((sum((y_test - predicted_y_test) ** 2) / len(y_test)) ** 0.5))) mae_test = float(sum(abs(y_test - predicted_y_test)) / len(y_test)) print('MAEp: {0}'.format(mae_test)) # histgram of MAEcce plt.rcParams["font.size"] = 18 plt.hist(mae_cce_train, bins=30) plt.plot(mae_test, 0.2, 'r.', markersize=30) plt.xlabel('MAEcce(histgram), MAEp(red point)') plt.ylabel('frequency') plt.show()
[ "sklearn.datasets.make_regression", "matplotlib.pyplot.hist", "sklearn.cross_decomposition.PLSRegression", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.figure.figaspect", "numpy.array", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "matplotlib.pyplot.xlim", "dcekit.validation.mae_cce", "numpy.arange", "matplotlib.pyplot.show" ]
[((719, 946), 'sklearn.datasets.make_regression', 'datasets.make_regression', ([], {'n_samples': '(number_of_training_samples + number_of_test_samples)', 'n_features': 'number_of_x_variables', 'n_informative': '(10)', 'noise': '(30)', 'random_state': '(number_of_training_samples + number_of_x_variables)'}), '(n_samples=number_of_training_samples +\n number_of_test_samples, n_features=number_of_x_variables, n_informative\n =10, noise=30, random_state=number_of_training_samples +\n number_of_x_variables)\n', (743, 946), False, 'from sklearn import datasets\n'), ((1036, 1108), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': 'number_of_test_samples', 'random_state': '(0)'}), '(x, y, test_size=number_of_test_samples, random_state=0)\n', (1052, 1108), False, 'from sklearn.model_selection import GridSearchCV, train_test_split\n'), ((1405, 1447), 'numpy.arange', 'np.arange', (['(1)', '(max_pls_component_number + 1)'], {}), '(1, max_pls_component_number + 1)\n', (1414, 1447), True, 'import numpy as np\n'), ((2214, 2344), 'dcekit.validation.mae_cce', 'mae_cce', (['cv_model', 'x_train', 'y_train'], {'number_of_y_randomization': 'number_of_y_randomization', 'do_autoscaling': '(True)', 'random_state': '(0)'}), '(cv_model, x_train, y_train, number_of_y_randomization=\n number_of_y_randomization, do_autoscaling=True, random_state=0)\n', (2221, 2344), False, 'from dcekit.validation import mae_cce\n'), ((2409, 2446), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y_test', 'predicted_y_test'], {}), '(y_test, predicted_y_test)\n', (2420, 2446), True, 'import matplotlib.pyplot as plt\n'), ((2576, 2726), 'matplotlib.pyplot.plot', 'plt.plot', (['[y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)]', '[y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)]', '"""k-"""'], {}), "([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)],\n [y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], 'k-')\n", (2584, 2726), True, 'import matplotlib.pyplot as plt\n'), ((2734, 2806), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(y_min - 0.05 * (y_max - y_min))', '(y_max + 0.05 * (y_max - y_min))'], {}), '(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\n', (2742, 2806), True, 'import matplotlib.pyplot as plt\n'), ((2808, 2880), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(y_min - 0.05 * (y_max - y_min))', '(y_max + 0.05 * (y_max - y_min))'], {}), '(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\n', (2816, 2880), True, 'import matplotlib.pyplot as plt\n'), ((2882, 2904), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Actual Y"""'], {}), "('Actual Y')\n", (2892, 2904), True, 'import matplotlib.pyplot as plt\n'), ((2906, 2931), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimated Y"""'], {}), "('Estimated Y')\n", (2916, 2931), True, 'import matplotlib.pyplot as plt\n'), ((2933, 2943), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2941, 2943), True, 'import matplotlib.pyplot as plt\n'), ((3351, 3383), 'matplotlib.pyplot.hist', 'plt.hist', (['mae_cce_train'], {'bins': '(30)'}), '(mae_cce_train, bins=30)\n', (3359, 3383), True, 'import matplotlib.pyplot as plt\n'), ((3385, 3429), 'matplotlib.pyplot.plot', 'plt.plot', (['mae_test', '(0.2)', '"""r."""'], {'markersize': '(30)'}), "(mae_test, 0.2, 'r.', markersize=30)\n", (3393, 3429), True, 'import matplotlib.pyplot as plt\n'), ((3431, 3478), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""MAEcce(histgram), MAEp(red point)"""'], {}), "('MAEcce(histgram), MAEp(red point)')\n", (3441, 3478), True, 'import matplotlib.pyplot as plt\n'), ((3480, 3503), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""frequency"""'], {}), "('frequency')\n", (3490, 3503), True, 'import matplotlib.pyplot as plt\n'), ((3505, 3515), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3513, 3515), True, 'import matplotlib.pyplot as plt\n'), ((1473, 1488), 'sklearn.cross_decomposition.PLSRegression', 'PLSRegression', ([], {}), '()\n', (1486, 1488), False, 'from sklearn.cross_decomposition import PLSRegression\n'), ((2387, 2406), 'matplotlib.figure.figaspect', 'figure.figaspect', (['(1)'], {}), '(1)\n', (2403, 2406), True, 'import matplotlib.figure as figure\n'), ((2473, 2489), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (2481, 2489), True, 'import numpy as np\n'), ((2537, 2553), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (2545, 2553), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- ''' @author: <NAME> May 2018 ''' # import code # code.interact(local=locals()) import os import pickle # from fordclassifier.classifier.classifier import Classifier import numpy as np import pandas as pd from sklearn.metrics import roc_curve, auc import json import matplotlib.pyplot as plt import operator import itertools from sklearn.metrics import confusion_matrix from collections import OrderedDict import pyemd # Local imports from fordclassifier.evaluator.predictorClass import Predictor from fordclassifier.evaluator.rbo import * import pdb class Evaluator(object): ''' Class to evaluate the performance of the classifiers ============================================================================ Methods: ============================================================================ _recover: if a variable is not in memory, tries to recover it from disk _get_folder: retuns full path to a subfolder _exists_file: check if the file exists in disk draw_rocs: draws the Xval ROCs and saves them as png files load_Xtfidf: Loads from disk Xtfidf and tags load_test_data: Loads from disk test Xtfidf and tags load_train_data: Loads from disk train Xtfidf and tags compute_average_xval_AUC: computes the average AUC on xval compute_average_test_AUC: computes the average AUC on test obtain_labels_from_Preds: Produces the multilabel tag prediction from individual predictions of every classifier compute_confussion_matrix: computes the confusion matrix on test (multiclass case) compute_confusion_matrix_multilabel: computes the confussion matrix for a multilabel set (multilabel case) draw_confussion_matrix: draws the CM and saves it as a png file draw_ROCS_tst: draws the ROC curves for the test data draw_anyROC: draws the ROC curves compute_thresholds: computes the thresholds compute_cardinality: computes the cardinality of the tags compute_label_density: Computes the label density JaccardIndex: Computes the Jaccard index compute_multilabel_threshold: Computes the multilabel threshold draw_costs_on_test: draws the multilabel cost for the test data load_multilabel_threshold: Loads the multilabel thresholds Jaccard_RBO_cost: Computes a convex combination of the Jaccard and RBO costs align_strings: Aligns strings into columns get_pred_weights: Returns the normalized predictions write_prediction_report: writes a simple prediction report in text format ============================================================================ ''' def __init__(self, project_path, subfolders, categories=None, verbose=True): ''' Initialization: Creates the initial object data Inputs: - project_path: path to the working project - subfolders: subfolder structure ''' self._project_path = project_path # working directory self._verbose = verbose # messages are printed on screen when True self.models2evaluate = None # models to evaluate (classif, params) self._subfolders = None # subfolders structure self.best_auc = None # Best AUC self.best_models = None # Best models self.Xtfidf_tr = None # Xtfidf for training self.tags_tr = None # Training tags self.tags = None # All tags self.ths_dict = None # dict with the thresholds for every classifier self.Preds = None # Prediction matrix, one column per category self.Preds_tr = None # Pred. matrix, one column per category, train self.Preds_tst = None # Pred. matrix, one column per category, test self.index_tst = None # Index for tags test self.categories = categories # List of categories self.Xtfidf_tst = None # Xtfidf for test self.tags_tst = None # Test tags self.CONF = None # Confusion matrix self.multilabel_th = None # Multilabel Threshold self._subfolders = subfolders def _get_folder(self, subfolder): ''' gets full path to a folder Inputs: - subfolder: target subfolder ''' return os.path.join(self._project_path, self._subfolders[subfolder]) def _exists_file(self, filename): ''' Checks if the file exists Inputs: - filename ''' try: f = open(filename, 'r') existe = True f.close() except: existe = False pass return existe def _recover(self, field): ''' Loads from disk a previously stored variable, to avoid recomputing it Inputs: - field: variable to restore from disk ''' if field == 'best_auc': input_file = os.path.join(self._get_folder('results'), 'best_auc.json') with open(input_file, 'r') as f: self.best_auc = json.load(f) if field == 'best_models': try: input_file = os.path.join(self._get_folder('results'), 'best_models.json') with open(input_file, 'r') as f: self.best_models = json.load(f) except: input_file = os.path.join(self._get_folder('export'), 'best_models.json') with open(input_file, 'r') as f: self.best_models = json.load(f) pass if field == 'Xtfidf_tr': filetoload_Xtfidf = os.path.join( self._project_path + self._subfolders['training_data'], 'train_data.pkl') with open(filetoload_Xtfidf, 'rb') as f: [self.Xtfidf_tr, tags_tr, self.tags_tr, refs_tr] = pickle.load(f) if field == 'Xtfidf_tst': filetoload_Xtfidf = os.path.join( self._project_path + self._subfolders['test_data'], 'test_data.pkl') with open(filetoload_Xtfidf, 'rb') as f: [self.Xtfidf_tst, tags_tst, self.tags_tst, refs_tst] = pickle.load(f) if field == 'tags': filetoload_tags = os.path.join( self._project_path + self._subfolders['training_data'], 'tags.pkl') with open(filetoload_tags, 'rb') as f: self.tags = pickle.load(f) if field == 'ths_dict': try: filename = os.path.join( self._project_path + self._subfolders['results'], 'ths_dict.pkl') with open(filename, 'rb') as f: self.ths_dict = pickle.load(f) except: filename = os.path.join( self._project_path + self._subfolders['export'], 'ths_dict.pkl') with open(filename, 'rb') as f: self.ths_dict = pickle.load(f) pass if field == 'Preds': filename = os.path.join( self._project_path + self._subfolders['results'], 'Preds.pkl') with open(filename, 'rb') as f: self.Preds = pickle.load(f) if field == 'Preds_tr': filename = os.path.join( self._project_path, self._subfolders['results'], 'Preds_tr.pkl') with open(filename, 'rb') as f: self.Preds_tr = pickle.load(f) if field == 'Preds_tst': filename = os.path.join( self._project_path, self._subfolders['results'], 'Preds_test.pkl') with open(filename, 'rb') as f: self.Preds_tst = pickle.load(f) if field == 'CONF': filename = os.path.join( self._project_path + self._subfolders['results'], 'CONF.pkl') with open(filename, 'rb') as f: self.CONF = pickle.load(f) if field == 'tags_index': filename = os.path.join( self._project_path + self._subfolders['test_data'], 'tags_index.pkl') with open(filename, 'rb') as f: [self.tags_tst, self.index_tst] = pickle.load(f) if field == 'categories': try: filename = os.path.join( self._project_path + self._subfolders['training_data'], 'categories.pkl') with open(filename, 'rb') as f: self.categories = pickle.load(f) except: filename = os.path.join( self._project_path + self._subfolders['export'], 'categories.pkl') with open(filename, 'rb') as f: self.categories = pickle.load(f) pass if field == 'models2evaluate': try: filename = os.path.join( self._project_path + self._subfolders['training_data'], 'models2evaluate.pkl') with open(filename, 'rb') as f: self.models2evaluate = pickle.load(f) except: filename = os.path.join( self._project_path + self._subfolders['export'], 'models2evaluate.pkl') with open(filename, 'rb') as f: self.models2evaluate = pickle.load(f) pass if field == 'multilabel_th': try: filename = os.path.join( self._project_path + self._subfolders['training_data'], 'multilabel_th.pkl') with open(filename, 'rb') as f: self.multilabel_th = pickle.load(f) except: filename = os.path.join( self._project_path + self._subfolders['export'], 'multilabel_th.pkl') with open(filename, 'rb') as f: self.multilabel_th = pickle.load(f) pass return def draw_rocs(self, verbose=True): ''' Draws the Xval ROCs and saves them as png files Inputs: - None, it operates on self values ''' if verbose: print("Saving ROC figures ...") if self.categories is None: self._recover('categories') if self.models2evaluate is None: self._recover('models2evaluate') # get the evaluated models models = list(self.models2evaluate.keys()) Nclass = len(models) Ncats = len(self.categories) for kcat in range(0, Ncats): plt.figure(figsize=(15, 12)) aucs = [] cat = self.categories[kcat] for kclass in range(0, Nclass): try: model_name = models[kclass] file_input_ROC = os.path.join( self._get_folder('eval_ROCs'), 'ROC_' + model_name + '_' + cat + '.pkl') with open(file_input_ROC, 'rb') as f: mdict = pickle.load(f) auc = mdict['roc_auc_loo'] aucs.append((model_name, auc)) except: pass # Sorting by AUC aucs.sort(key=operator.itemgetter(1), reverse=True) colors = ['k', 'r', 'g', 'b', 'm', 'c', 'r--', 'g--', 'b--', 'm--', 'c--', 'k--'] # drawing the best 10 models for k in range(0, 10): try: model_name = aucs[k][0] auc = aucs[k][1] file_input_ROC = os.path.join( self._get_folder('eval_ROCs'), 'ROC_' + model_name + '_' + cat + '.pkl') with open(file_input_ROC, 'rb') as f: mdict = pickle.load(f) fpr = mdict['fpr_loo'] tpr = mdict['tpr_loo'] text = model_name + ', AUC= ' + str(auc)[0:6] if auc > 0.6: if k == 0: # drawing the best model with thicker line plt.plot(fpr, tpr, colors[k], label=text, linewidth=6.0) else: plt.plot(fpr, tpr, colors[k], label=text, linewidth=2.0) except: pass plt.xlabel('FPR') plt.ylabel('TPR') plt.title('ROC curves for category ' + cat) plt.grid(True) plt.legend(loc="lower right") filename = os.path.join(self._get_folder('ROCS_tr'), cat + '_ROC_xval.png') plt.savefig(filename) plt.close() if verbose: print(cat, ) return def load_Xtfidf(self, verbose=True): ''' Loads from disk Xtfidf and tags Inputs: - None, it operates on self values ''' if self.Xtfidf is None: self._recover('Xtfidf') if self.tags is None: self._recover('tags') return self.Xtfidf, self.tags def load_test_data(self, verbose=True): ''' Loads from disk test Xtfidf and tags Inputs: - None, it operates on self values ''' filename = os.path.join( self._project_path + self._subfolders['test_data'], 'test_data.pkl') with open(filename, 'rb') as f: [self.Xtfidf_tst, self.tags_tst, refs_tst] = pickle.load(f) new_tags_tst = [] for tags in self.tags_tst: unique_tags = sorted(set(tags), key=tags.index) new_tags_tst.append(unique_tags) return self.Xtfidf_tst, new_tags_tst, refs_tst def load_train_data(self, verbose=True): ''' Loads from disk train Xtfidf and tags Inputs: - None, it operates on self values ''' filename = os.path.join( self._project_path + self._subfolders['training_data'], 'train_data.pkl') with open(filename, 'rb') as f: [self.Xtfidf_tr, self.tags_tr, refs_tr] = pickle.load(f) new_tags_tr = [] for tags in self.tags_tr: unique_tags = sorted(set(tags), key=tags.index) new_tags_tr.append(unique_tags) return self.Xtfidf_tr, new_tags_tr, refs_tr def compute_average_xval_AUC(self, verbose=True): ''' Computes the average AUC on xval Inputs: - None, it operates on self values ''' if self.best_auc is None: self._recover('best_auc') aucs = list(self.best_auc.values()) average_auc = np.mean(aucs) return average_auc def obtain_labels_from_Preds(self, Preds, threshold, categories=None, verbose=True): ''' Produces the multilabel tag prediction from individual predictions of every classifier Inputs: - Preds: predictions matrix, one column per category, as many rows as patterns - threshold: multilabel threshold ''' if self.categories is None: self._recover('categories') labels_preds = [] Ndocs = Preds.shape[0] for kdoc in range(0, Ndocs): l = [] p = Preds[kdoc, :] # Normalize individual predictions, the maximum becomes 1.0 in all # cases if max(p) > 0: p = p / max(p) orden = np.argsort(-p) for index in orden: if p[index] > threshold: l.append(self.categories[index]) labels_preds.append(l) return labels_preds def compute_confusion_matrix(self, orig_tags, best_pred_tags, filename, sorted_categories=[], verbose=True): ''' computes the confussion matrix on test (multiclass case) Inputs: - orig_tags: original labels - best_pred_tags: predicted labels - filename: file to save results - sorted_categories: categories to take into account, respecting the order ''' if self.categories is None: self._recover('categories') if len(sorted_categories) > 0: labels_categories = sorted_categories else: labels_categories = self.categories self.CONF = confusion_matrix(orig_tags, best_pred_tags, labels=labels_categories) pathfilename = os.path.join( self._project_path + self._subfolders['results'], filename) with open(pathfilename, 'wb') as f: pickle.dump(self.CONF, f) return self.CONF def compute_confusion_matrix_multilabel(self, orig_tags, best_pred_tags, filename, sorted_categories=[], verbose=True): ''' computes the confussion matrix for a multilabel set (multilabel case) Inputs: - orig_tags: original labels - best_pred_tags: predicted labels - filename: file to save results - sorted_categories: categories to take into account, respecting the order ''' if self.categories is None: self._recover('categories') if len(sorted_categories) > 0: labels_categories = sorted_categories else: labels_categories = self.categories Ncats = len(labels_categories) self.CONF = np.zeros((Ncats, Ncats)) NP = len(orig_tags) for k in range(0, NP): cats_orig = orig_tags[k] cats_pred = best_pred_tags[k] for m in range(0, Ncats): for n in range(0, Ncats): cat_orig = labels_categories[m] cat_pred = labels_categories[n] if cat_orig in cats_orig and cat_pred in cats_pred: self.CONF[m, n] += 1.0 # self.CONF = confusion_matrix(orig_tags, best_pred_tags, # labels=labels_categories) pathfilename = os.path.join( self._project_path + self._subfolders['results'], filename) with open(pathfilename, 'wb') as f: pickle.dump(self.CONF, f) return self.CONF def compute_confusion_matrix_multilabel_v2( self, orig_tags, best_pred_tags, filename, sorted_categories=[], order_sensitive=False, verbose=True): ''' computes the confusion matrix for a multilabel set Inputs: - orig_tags: original labels - best_pred_tags: predicted labels - filename: file to save results - sorted_categories: categories to take into account, respecting the order - order_sensitive: indicates if the computation is order sensitive or not ''' # Set dump factor if order_sensitive: dump_factor = 0.5 else: dump_factor = 1.0 # Take categories from the input arguments. If not, from the object. # If not, from a file using the recover method. if len(sorted_categories) > 0: categories = sorted_categories else: # Get list of categories if self.categories is None: self._recover('categories') categories = self.categories # Validate true labels n = len([x for x in orig_tags if len(x) == 0]) if n > 0: print('---- WARNING: {} samples without labels '.format(n) + 'will be ignored.') # Validate predicted labels n = len([x for x in best_pred_tags if len(x) == 0]) if n > 0: print('---- WARNING: {} samples without predictions '.format(n) + 'will be ignored.') # Loop over the true and predicted labels Ncats = len(categories) self.CONF = np.zeros((Ncats, Ncats)) for cats_orig, cats_pred in zip(orig_tags, best_pred_tags): if len(cats_orig) > 0 and len(cats_pred) > 0: # Compute numerical true label vector value_orig = 1.0 p = np.zeros(Ncats) for c in cats_orig: p[categories.index(c)] = value_orig value_orig *= dump_factor p = p / np.sum(p) # Compute numerical prediction label vector value_pred = 1.0 q = np.zeros(Ncats) for c in cats_pred: q[categories.index(c)] = value_pred value_pred *= dump_factor q = q / np.sum(q) # Compute diagonal elements min_pq = np.minimum(p, q) M = np.diag(min_pq) # Compute non-diagonal elements p_ = p - min_pq q_ = q - min_pq z = 1 - np.sum(min_pq) if z > 0: M += (p_[:, np.newaxis] * q_) / z self.CONF += M pathfilename = os.path.join( self._project_path, self._subfolders['results'], filename) with open(pathfilename, 'wb') as f: pickle.dump(self.CONF, f) return self.CONF def compute_EMD_error(self, orig_tags, best_pred_tags, fpath, order_sensitive=False): ''' computes the confusion matrix for a multilabel set Args: - orig_tags: original labels - best_pred_tags: predicted labels - fpath: path to the file with the similarity matrix - order_sensitive: indicates if the computation is order sensitive or not ''' # ###################### # Load similarity values if type(fpath) is str: df_S = pd.read_excel(fpath) # Compute cost matrix C = 1 - df_S[df_S.columns].values # WARNING: For later versions of pandas, you might need to use: # Note that df_S.columnst shooud be taken from 1, because # The first column is taken as the index column. # C = 1 - df_S[df_S.columns[1:]].to_numpy() else: # This is a combination of cost matrices that takes the # component-wise minimum of the costs C = 1 for fp in fpath: df_S = pd.read_excel(fp) # Compute cost matrix Cf = 1 - df_S[df_S.columns].values C = np.minimum(C, Cf) # This combination of cost matrices takes each cost matrix with a # different weights. Only for two Cost matrices. # df_S = pd.read_excel(fpath[0]) # C1 = 1 - df_S[df_S.columns].values # df_S = pd.read_excel(fpath[1]) # Cs = 1 - df_S[df_S.columns].values # ncat = Cs.shape[0] # C = np.minimum(1 - np.eye(ncat), # np.minimum(0.25 + 0.75 * Cs, 0.5 + 0.5 * C1)) # This is to make sure that C is "C-contitguos", a requirement of pyemd C = np.ascontiguousarray(C, dtype=np.float64) # Set dump factor if order_sensitive: dump_factor = 0.5 else: dump_factor = 1.0 # Take categories in the order of the cost matrix categories = df_S.columns.tolist() # Validate true labels n = len([x for x in orig_tags if len(x) == 0]) if n > 0: print(f'---- WARNING: {n} samples without labels will be ignored') # Validate predicted labels n = len([x for x in best_pred_tags if len(x) == 0]) if n > 0: print(f'---- WARNING: {n} samples without preds will be ignored') # ################## # Compute EMD errors # Loop over the true and predicted labels Ncats = len(categories) self.emd = 0 count = 0 for cats_orig, cats_pred in zip(orig_tags, best_pred_tags): if len(cats_orig) > 0 and len(cats_pred) > 0: # Compute numerical true label vector value_orig = 1.0 p = np.zeros(Ncats) for c in cats_orig: p[categories.index(c)] = value_orig value_orig *= dump_factor p = p / np.sum(p) # Compute numerical prediction label vector value_pred = 1.0 q = np.zeros(Ncats) for c in cats_pred: q[categories.index(c)] = value_pred value_pred *= dump_factor q = q / np.sum(q) # Compute EMD distance for the given sample emd_i = pyemd.emd(p, q, C) self.emd += emd_i count += 1 self.emd /= count return self.emd def compute_sorted_errors(self, CONF, categories): eps = 1e-20 # Sample size per category n_cat = len(categories) ns_cat = CONF.sum(axis=1, keepdims=True) # Total sample size ns_tot = CONF.sum() # Compute all-normalized confusion matrix CONF_a = CONF / ns_tot # Compute row-normalized confusion matrix CONF_r = ((CONF.astype('float') + eps) / (ns_cat + n_cat*eps)) # Sort errors by unsorted_values = [(categories[i], categories[j], 100*CONF_a[i, j], 100*CONF_r[i, j], 100*ns_cat[i][0]/ns_tot) for i in range(n_cat) for j in range(n_cat)] sorted_values_a = sorted(unsorted_values, key=lambda x: -x[2]) sorted_values_r = sorted(unsorted_values, key=lambda x: -x[3]) # Remove diagonal elements sorted_values_a = [x for x in sorted_values_a if x[0] != x[1]] sorted_values_r = [x for x in sorted_values_r if x[0] != x[1]] # Remove relative errors of categories with zero samples sorted_values_r = [x for x in sorted_values_r if ns_cat[categories.index(x[0])] > 0] cols = ['Cat. real', 'Clasif', 'Err/total (%)', 'Error/cat (%)', 'Peso muestral'] df_ranked_abs = pd.DataFrame(sorted_values_a, columns=cols) df_ranked_rel = pd.DataFrame(sorted_values_r, columns=cols) f_path = os.path.join(self._project_path, self._subfolders['results'], 'ranked_abs_errors.xlsx') df_ranked_abs.to_excel(f_path) f_path = os.path.join(self._project_path, self._subfolders['results'], 'ranked_rel_errors.xlsx') df_ranked_rel.to_excel(f_path) return df_ranked_abs, df_ranked_rel def compute_error_confusion_matrix(self, CONF, normalize=True, verbose=True): # Returns the ratio of elements outside the diagonal allsum = np.sum(CONF) diagsum = np.sum(np.diagonal(CONF)) offdiagsum = allsum - diagsum error = offdiagsum / allsum return error def draw_confusion_matrix(self, CONF, filename, sorted_categories=[], verbose=True, normalize=True): ''' draws the CM and saves it as a png file Inputs: - CONF: conf matrix to be stored - filename: filename - sorted_categories: list of sorted categories - normalize: indicates to normalize CONF ''' # An extemelly small value to avoid zero division eps = 1e-20 n_cat = len(sorted_categories) if len(sorted_categories) > 0: labels_categories = sorted_categories else: if self.categories is None: self._recover('categories') labels_categories = self.categories if normalize: # Normalize CONF = ((CONF.astype('float') + eps) / (CONF.sum(axis=1, keepdims=True) + n_cat*eps)) else: CONF = CONF.astype('float') plt.figure(figsize=(15, 12)) cmap = plt.cm.Blues plt.imshow(CONF, interpolation='nearest', cmap=cmap) plt.colorbar() tick_marks = np.arange(len(labels_categories)) plt.xticks(tick_marks, labels_categories, rotation=90) plt.yticks(tick_marks, labels_categories) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') pathfilename = os.path.join(self._get_folder('figures'), filename) print(f"SALVADO EN {pathfilename}") plt.savefig(pathfilename) plt.clf() return def draw_ROCS_tst(self, Preds_tst, tags_tst): ''' draws the ROC curves for the test data Inputs: - Preds_tst: predicted labels - tags_tst: true labels ''' if self.best_models is None: self._recover('best_models') if self.categories is None: self._recover('categories') colors = ['k', 'r', 'g', 'b', 'm', 'c', 'r--', 'g--', 'b--', 'm--', 'c--', 'k--'] # retain the first tag in the labels tags = [t[0] if len(t) > 0 else '' for t in tags_tst] for k in range(0, len(self.categories)): cat = self.categories[k] y_tst = [1.0 if p == cat else -1.0 for p in tags] preds_tst = list(Preds_tst[:, k]) fpr_tst, tpr_tst, thresholds = roc_curve(y_tst, preds_tst) roc_auc_tst = auc(fpr_tst, tpr_tst) model_name = self.best_models[cat] file_output_ROC = os.path.join( self._get_folder('ROCS_tst'), 'ROC_' + model_name + '_' + cat + '.pkl') mdict = {'fpr_tst': list(fpr_tst), 'tpr_tst': list(tpr_tst), 'roc_auc_tst': roc_auc_tst, 'y_tst': list(y_tst), 'preds_tst': list(preds_tst)} with open(file_output_ROC, 'wb') as f: pickle.dump(mdict, f) plt.figure(figsize=(15, 12)) plt.xlabel('FPR') plt.ylabel('TPR') plt.title('ROC test curve for category ' + cat) text = model_name + ', AUC= ' + str(roc_auc_tst)[0:6] plt.plot(fpr_tst, tpr_tst, colors[3], label=text, linewidth=6.0) plt.grid(True) plt.legend(loc="lower right") filename = os.path.join( self._get_folder('ROCS_tst'), cat + '_ROC_test.png') plt.savefig(filename) plt.close() return def draw_anyROC(self, Preds_tst, tags_tst, case): ''' draws the ROC curves Inputs: - Preds_tst: predicted labels - tags_tst: true labels ''' if self.categories is None: self._recover('categories') colors = ['k', 'r', 'g', 'b', 'm', 'c', 'r--', 'g--', 'b--', 'm--', 'c--', 'k--'] # retain the first tag in the labels tags = [t[0] if len(t) > 0 else '' for t in tags_tst] aucs = [] for k in range(0, len(self.categories)): cat = self.categories[k] y_tst = [1.0 if p == cat else -1.0 for p in tags] preds_tst = list(Preds_tst[:, k]) fpr_tst, tpr_tst, thresholds = roc_curve(y_tst, preds_tst) roc_auc_tst = auc(fpr_tst, tpr_tst) aucs.append(roc_auc_tst) file_output_ROC = os.path.join( self._get_folder('ROCS_tst'), cat + '_' + 'ROC_' + case + '.pkl') mdict = {'fpr_tst': list(fpr_tst), 'tpr_tst': list(tpr_tst), 'roc_auc_tst': roc_auc_tst, 'y_tst': list(y_tst), 'preds_tst': list(preds_tst)} with open(file_output_ROC, 'wb') as f: pickle.dump(mdict, f) plt.figure(figsize=(15, 12)) plt.xlabel('FPR') plt.ylabel('TPR') plt.title('ROC test curve for category ' + cat) text = case + ', AUC= ' + str(roc_auc_tst)[0:6] plt.plot(fpr_tst, tpr_tst, colors[3], label=text, linewidth=6.0) plt.grid(True) plt.legend(loc="lower right") filename = os.path.join(self._get_folder('ROCS_tst'), cat + '_' + 'ROC_' + case + '.png') plt.savefig(filename) plt.close() average_auc = np.nanmean(aucs) return average_auc def compute_average_test_AUC(self, verbose=True): ''' computes the average AUC on test Inputs: - None, it operates on self values ''' if self.best_models is None: self._recover('best_models') if self.categories is None: self._recover('categories') aucs = [] for k in range(0, len(self.categories)): cat = self.categories[k] model_name = self.best_models[cat] filename = os.path.join( self._get_folder('ROCS_tst'), 'ROC_' + model_name + '_' + cat + '.pkl') with open(filename, 'rb') as f: mdict = pickle.load(f) auc = mdict['roc_auc_tst'] aucs.append(auc) average_auc = np.nanmean(aucs) return average_auc def compute_thresholds(self, verbose=True): ''' computes the thresholds Inputs: - None, it operates on self values ''' if self.categories is None: self._recover('categories') if self.best_models is None: self._recover('best_models') Ncats = len(self.categories) ths_dict = {} for kcat in range(0, Ncats): try: cat = self.categories[kcat] model_name = self.best_models[cat] file_input_ROC = os.path.join( self._get_folder('eval_ROCs'), 'ROC_' + model_name + '_' + cat + '.pkl') with open(file_input_ROC, 'rb') as f: mdict = pickle.load(f) fpr = mdict['fpr_loo'] tpr = mdict['tpr_loo'] ths = mdict['thresholds'] mix = [] for k in range(0, len(fpr)): # We select the threshold maximizing this convex combinat mix.append(tpr[k] + (1 - fpr[k])) cual = np.argmax(mix) th = ths[cual] ths_dict.update({cat: th}) print(cat, th, cual, tpr[cual], fpr[cual]) except: print("Error in cat ", cat) pass filename = os.path.join( self._project_path + self._subfolders['results'], 'ths_dict.pkl') with open(filename, 'wb') as f: pickle.dump(ths_dict, f) return def compute_cardinality(self, tags): ''' computes the cardinality of the tags Inputs: - tags: labels ''' C = np.mean([len(set(l)) for l in tags]) return C def compute_label_density(self, tags): ''' Computes the label density Inputs: - tags: labels ''' # total number of possible labels NL = len(set(itertools.chain.from_iterable(tags))) D = np.mean([len(set(l)) / NL for l in tags]) return D def JaccardIndex(self, orig, pred): ''' Computes the Jaccard index Inputs: - orig: original labels - pred: predicted labels ''' accs = [] for k in range(0, len(orig)): l_orig = orig[k] l_pred = pred[k] num = len(set(l_orig).intersection(l_pred)) den = len(set(l_orig + l_pred)) acc = num / den accs.append(acc) JI = np.mean(accs) return JI def compute_multilabel_threshold(self, p, alpha, option, th_values, verbose=True): ''' Computes the multilabel threshold Inputs: - p: RBO parameter, ``p`` is the probability of looking for overlap at rank k + 1 after having examined rank k - alpha: convex Jaccard-RBO combination parameter - option: sorting option for multilabel prediction - th_values: range of threshold values to be evaluated ''' if self.Xtfidf_tr is None: self._recover('Xtfidf_tr') if self.Preds_tr is None: self._recover('Preds_tr') # Warning tags_tr may have duplicates... self.tags_tr = [list(OrderedDict.fromkeys(l)) for l in self.tags_tr] if verbose: print('-' * 50) COST = [] DENS_pred = [] DENS_true = [] COST_dens = [] density_true = self.compute_cardinality(self.tags_tr) # to normalize Jaccard_RBO_cost, depends on p baseline = [0] for k in range(2, 50): l = list(range(1, k)) baseline.append(rbo(l, l, p)['min']) P = Predictor(self._project_path, self._subfolders, verbose=False) for threshold in th_values: multilabel_pred_tr, labels_pred_tr = P.obtain_multilabel_preds( self.Preds_tr, option, threshold, verbose=True) density_pred = self.compute_cardinality(labels_pred_tr) DENS_pred.append(density_pred) DENS_true.append(density_true) dens_error = (density_pred - density_true) ** 2 COST_dens.append(dens_error) # Computing Jackard_RBO cost jrbos = [] for k in range(0, len(self.tags_tr)): values = [] for key in labels_pred_tr[k]: values.append((key, multilabel_pred_tr[k][key]['p'])) values.sort(key=lambda x: x[1], reverse=True) l_pred = [] for v in values: l_pred.append(v[0]) jrbo = self.Jaccard_RBO_cost( self.tags_tr[k], l_pred, baseline, p, alpha) jrbos.append(jrbo) cost_jrbo = np.mean(jrbos) print(threshold, cost_jrbo, density_true, density_pred, ) COST.append(cost_jrbo) max_cost = max(COST) max_dens = max(COST_dens) COST_dens = [x / max_dens * max_cost for x in COST_dens] plt.figure(figsize=(15, 12)) plt.xlabel('Th') plt.ylabel('Jackard-RBO cost') plt.title('Jackard-RBO and Label Density costs for p =' + str(p) + ' and alpha= ' + str(alpha)) plt.plot(th_values, COST, 'b', label='Jackard-RBO cost', linewidth=3.0) plt.plot(th_values, COST_dens, 'r', label='Labels Density cost', linewidth=3.0) cual_min = np.argmin(COST) th_JRBO = th_values[cual_min] plt.plot(th_values[cual_min], COST[cual_min], 'bo', label='Minimum Jackard-RBO cost', linewidth=3.0) cual_min = np.argmin(COST_dens) th_DENS = th_values[cual_min] plt.plot(th_values[cual_min], COST_dens[cual_min], 'ro', label='Minimum Labels Density cost', linewidth=3.0) plt.legend(loc="upper right") plt.grid(True) filename = os.path.join( self._project_path + self._subfolders['results'], 'JRBO_COST_tr_p_' + str(p) + '_alpha_' + str(alpha) + '.png') plt.savefig(filename) plt.close() self.multilabel_th = np.mean([th_JRBO, th_DENS]) filename = os.path.join( self._project_path + self._subfolders['training_data'], 'multilabel_th.pkl') with open(filename, 'wb') as f: pickle.dump(self.multilabel_th, f) filename = os.path.join( self._project_path + self._subfolders['export'], 'multilabel_th.pkl') with open(filename, 'wb') as f: pickle.dump(self.multilabel_th, f) return self.multilabel_th def draw_costs_on_test(self, p, alpha, option, th_values, verbose=True): ''' draws the multilabel cost for the test data Inputs: - p: RBO parameter, ``p`` is the probability of looking for overlap at rank k + 1 after having examined rank k - alpha: convex Jaccard-RBO combination parameter - option: sorting option for multilabel prediction - th_values: range of threshold values to be evaluated ''' if self.Xtfidf_tst is None: self._recover('Xtfidf_tst') if self.Preds_tst is None: self._recover('Preds_tst') if self.multilabel_th is None: self._recover('multilabel_th') # Warning tags_tst may have duplicates... self.tags_tst = [list(OrderedDict.fromkeys(l)) for l in self.tags_tst] if verbose: print('-' * 50) COST = [] DENS_pred = [] DENS_true = [] COST_dens = [] density_true = self.compute_cardinality(self.tags_tst) # to normalize Jaccard_RBO_cost, depends on p baseline = [0] for k in range(2, 50): l = list(range(1, k)) baseline.append(rbo(l, l, p)['min']) P = Predictor(self._project_path, self._subfolders, verbose=False) for threshold in th_values: multilabel_pred_tst, labels_pred_tst = P.obtain_multilabel_preds( self.Preds_tst, option, threshold, verbose=True) density_pred = self.compute_cardinality(labels_pred_tst) DENS_pred.append(density_pred) DENS_true.append(density_true) dens_error = (density_pred - density_true) ** 2 COST_dens.append(dens_error) # Computing Jackard_RBO cost jrbos = [] for k in range(0, len(self.tags_tst)): values = [] for key in labels_pred_tst[k]: values.append((key, multilabel_pred_tst[k][key]['p'])) values.sort(key=lambda x: x[1], reverse=True) l_pred = [] for v in values: l_pred.append(v[0]) jrbo = self.Jaccard_RBO_cost( self.tags_tst[k], l_pred, baseline, p, alpha) jrbos.append(jrbo) cost_jrbo = np.mean(jrbos) print(threshold, cost_jrbo, density_true, density_pred, ) COST.append(cost_jrbo) max_cost = max(COST) max_dens = max(COST_dens) COST_dens = [x / max_dens * max_cost for x in COST_dens] plt.figure(figsize=(15, 12)) plt.xlabel('Th') plt.ylabel('Jackard-RBO cost') plt.title('Jackard-RBO and Label Density costs for p =' + str(p) + ' and alpha= ' + str(alpha)) plt.plot(th_values, COST, 'b', label='Jackard-RBO cost', linewidth=3.0) plt.plot(th_values, COST_dens, 'r', label='Labels Density cost', linewidth=3.0) cual_min = np.argmin(abs(th_values - self.multilabel_th)) plt.plot(th_values[cual_min], COST[cual_min], 'bo', label='Jackard-RBO cost at threshold', linewidth=3.0) plt.plot(th_values[cual_min], COST_dens[cual_min], 'ro', label='Labels Density cost at threshold', linewidth=3.0) plt.legend(loc="upper right") plt.grid(True) filename = os.path.join( self._project_path + self._subfolders['results'], 'JRBO_COST_tst_p_' + str(p) + '_alpha_' + str(alpha) + '.png') plt.savefig(filename) plt.close() return def load_multilabel_threshold(self, path2export=''): ''' Loads the multilabel thresholds Inputs: - path2export: export path ''' if path2export != '': print('Loading multilabel_th from export') filename = os.path.join(path2export, 'multilabel_th.pkl') with open(filename, 'rb') as f: self.multilabel_th = pickle.load(f) else: if self.multilabel_th is None: self._recover('multilabel_th') return self.multilabel_th def Jaccard_RBO_cost(self, l_orig, l_pred, baseline, p, alpha): ''' Computes a convex combination of the Jaccard and RBO costs Inputs: - l_orig: original labels - l_pred: predicted labels - baseline: normalizing values - p: RBO parameter, ``p`` is the probability of looking for overlap at rank k + 1 after having examined rank k - alpha: convex Jaccard-RBO combination parameter ''' try: if len(l_orig) > 0: num = len(set(l_orig).intersection(l_pred)) den = len(set(l_orig + l_pred)) ji = 1.0 - num / den else: if len(l_pred) == 0: # empty labels and empty predict means cost = 0.0 ji = 0 else: # empty labels and non-empty predict means cost = 1.0 ji = 1.0 r = 0 L = min((len(l_orig), len(l_pred))) if L > 0: r = 1 - rbo(l_orig, l_pred, p)['min'] / baseline[L] else: r = 1.0 if len(l_orig) == 0 and len(l_pred) == 0: r = 0.0 except: print('Error in Jaccard_RBO_cost ' + '----------------------------------------------------') import code code.interact(local=locals()) pass jrbo = (alpha * ji + (1 - alpha) * r) / 2.0 return jrbo def align_strings(self, string0, string1, string2, string3, L, M, N, P): ''' Aligns strings into columns ''' empty = ' ' # if len(string1) > M or len(string2) > N or len(string3) > P: # import code # code.interact(local=locals()) if L - len(string0) > 0: string0 = string0 + empty[0: L - len(string0)] if M - len(string1) > 0: string1 = string1 + empty[0: M - len(string1)] if N - len(string2) > 0: string2 = string2 + empty[0: N - len(string2)] if P - len(string3) > 0: string3 = string3 + empty[0: P - len(string3)] aligned_string = string0 + '| ' + string1 + '| ' + string2 + '| ' + string3 + '\r\n' return aligned_string def get_pred_weights(self, refs, label_preds, multilabel_preds): ''' Returns the normalized predictions **Unused????**** Inputs: - refs: *unused* - label_preds: - multilabel_preds: ''' weights = [] for k, labels in enumerate(label_preds): w0 = [multilabel_preds[k][key]['p'] for key in labels] scale = np.sum(w0) weights.append([w / scale for w in w0]) return weights def write_prediction_report(self, refs_tst, tags_tst, labels_pred_tst, multilabel_pred_tst, filename_out): ''' writes a simple prediction report in text format Inputs: - refs_tst: references - tags_tst: original labels - labels_pred_tst: predicted labels - multilabel_pred_tst: multilabel predicted labels - filename_out: file to save results ''' # writing report for the best threshold value string0 = 'PROJECT REFERENCE' string1 = 'TARGET LABELS' string2 = 'PREDICTED LABELS' string3 = ' ' data = [self.align_strings(string0, string1, string2, string3, 20, 30, 50, 10)] data.append('=' * 80 + '\r\n') for k in range(0, len(tags_tst)): string0 = refs_tst[k] string1 = '' for t in tags_tst[k]: string1 += t + ', ' if len(tags_tst[k]) == 0: string1 += '--------------' values = labels_pred_tst[k] if len(values) == 0: string2 = '--------------' else: string2 = '' pesos = [] for key in values: pesos.append(multilabel_pred_tst[k][key]['p']) for key in values: weight = multilabel_pred_tst[k][key]['p'] / np.sum(pesos) str_weight = str(weight)[0:5] string2 += key + '(' + str_weight + '), ' string3 = ' ' cadena = self.align_strings(string0, string1, string2, string3, 20, 30, 50, 10) data.append(cadena) filename = os.path.join(self._project_path, self._subfolders['results'], filename_out) with open(filename, 'w') as f: f.writelines(data) print('Saved ', filename) return
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "numpy.ascontiguousarray", "numpy.argsort", "numpy.nanmean", "sklearn.metrics.roc_curve", "pandas.read_excel", "operator.itemgetter", "matplotlib.pyplot.imshow", "numpy.mean", "collections.OrderedDict.fromkeys", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "itertools.chain.from_iterable", "matplotlib.pyplot.yticks", "pandas.DataFrame", "numpy.argmin", "sklearn.metrics.confusion_matrix", "pyemd.emd", "numpy.diagonal", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xticks", "pickle.load", "numpy.argmax", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "pickle.dump", "numpy.minimum", "matplotlib.pyplot.colorbar", "os.path.join", "matplotlib.pyplot.clf", "fordclassifier.evaluator.predictorClass.Predictor", "numpy.diag", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "json.load" ]
[((4723, 4784), 'os.path.join', 'os.path.join', (['self._project_path', 'self._subfolders[subfolder]'], {}), '(self._project_path, self._subfolders[subfolder])\n', (4735, 4784), False, 'import os\n'), ((14515, 14600), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['test_data'])", '"""test_data.pkl"""'], {}), "(self._project_path + self._subfolders['test_data'],\n 'test_data.pkl')\n", (14527, 14600), False, 'import os\n'), ((15174, 15264), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""train_data.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'train_data.pkl')\n", (15186, 15264), False, 'import os\n'), ((15959, 15972), 'numpy.mean', 'np.mean', (['aucs'], {}), '(aucs)\n', (15966, 15972), True, 'import numpy as np\n'), ((17818, 17887), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['orig_tags', 'best_pred_tags'], {'labels': 'labels_categories'}), '(orig_tags, best_pred_tags, labels=labels_categories)\n', (17834, 17887), False, 'from sklearn.metrics import confusion_matrix\n'), ((17952, 18024), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", 'filename'], {}), "(self._project_path + self._subfolders['results'], filename)\n", (17964, 18024), False, 'import os\n'), ((19029, 19053), 'numpy.zeros', 'np.zeros', (['(Ncats, Ncats)'], {}), '((Ncats, Ncats))\n', (19037, 19053), True, 'import numpy as np\n'), ((19669, 19741), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", 'filename'], {}), "(self._project_path + self._subfolders['results'], filename)\n", (19681, 19741), False, 'import os\n'), ((21594, 21618), 'numpy.zeros', 'np.zeros', (['(Ncats, Ncats)'], {}), '((Ncats, Ncats))\n', (21602, 21618), True, 'import numpy as np\n'), ((22789, 22860), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", 'filename'], {}), "(self._project_path, self._subfolders['results'], filename)\n", (22801, 22860), False, 'import os\n'), ((24975, 25016), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['C'], {'dtype': 'np.float64'}), '(C, dtype=np.float64)\n', (24995, 25016), True, 'import numpy as np\n'), ((28191, 28234), 'pandas.DataFrame', 'pd.DataFrame', (['sorted_values_a'], {'columns': 'cols'}), '(sorted_values_a, columns=cols)\n', (28203, 28234), True, 'import pandas as pd\n'), ((28260, 28303), 'pandas.DataFrame', 'pd.DataFrame', (['sorted_values_r'], {'columns': 'cols'}), '(sorted_values_r, columns=cols)\n', (28272, 28303), True, 'import pandas as pd\n'), ((28324, 28415), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", '"""ranked_abs_errors.xlsx"""'], {}), "(self._project_path, self._subfolders['results'],\n 'ranked_abs_errors.xlsx')\n", (28336, 28415), False, 'import os\n'), ((28503, 28594), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", '"""ranked_rel_errors.xlsx"""'], {}), "(self._project_path, self._subfolders['results'],\n 'ranked_rel_errors.xlsx')\n", (28515, 28594), False, 'import os\n'), ((28916, 28928), 'numpy.sum', 'np.sum', (['CONF'], {}), '(CONF)\n', (28922, 28928), True, 'import numpy as np\n'), ((30099, 30127), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (30109, 30127), True, 'import matplotlib.pyplot as plt\n'), ((30166, 30218), 'matplotlib.pyplot.imshow', 'plt.imshow', (['CONF'], {'interpolation': '"""nearest"""', 'cmap': 'cmap'}), "(CONF, interpolation='nearest', cmap=cmap)\n", (30176, 30218), True, 'import matplotlib.pyplot as plt\n'), ((30228, 30242), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (30240, 30242), True, 'import matplotlib.pyplot as plt\n'), ((30308, 30362), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tick_marks', 'labels_categories'], {'rotation': '(90)'}), '(tick_marks, labels_categories, rotation=90)\n', (30318, 30362), True, 'import matplotlib.pyplot as plt\n'), ((30372, 30413), 'matplotlib.pyplot.yticks', 'plt.yticks', (['tick_marks', 'labels_categories'], {}), '(tick_marks, labels_categories)\n', (30382, 30413), True, 'import matplotlib.pyplot as plt\n'), ((30423, 30441), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (30439, 30441), True, 'import matplotlib.pyplot as plt\n'), ((30451, 30475), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True label"""'], {}), "('True label')\n", (30461, 30475), True, 'import matplotlib.pyplot as plt\n'), ((30485, 30514), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted label"""'], {}), "('Predicted label')\n", (30495, 30514), True, 'import matplotlib.pyplot as plt\n'), ((30645, 30670), 'matplotlib.pyplot.savefig', 'plt.savefig', (['pathfilename'], {}), '(pathfilename)\n', (30656, 30670), True, 'import matplotlib.pyplot as plt\n'), ((30680, 30689), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (30687, 30689), True, 'import matplotlib.pyplot as plt\n'), ((34624, 34640), 'numpy.nanmean', 'np.nanmean', (['aucs'], {}), '(aucs)\n', (34634, 34640), True, 'import numpy as np\n'), ((35498, 35514), 'numpy.nanmean', 'np.nanmean', (['aucs'], {}), '(aucs)\n', (35508, 35514), True, 'import numpy as np\n'), ((36978, 37056), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", '"""ths_dict.pkl"""'], {}), "(self._project_path + self._subfolders['results'], 'ths_dict.pkl')\n", (36990, 37056), False, 'import os\n'), ((38214, 38227), 'numpy.mean', 'np.mean', (['accs'], {}), '(accs)\n', (38221, 38227), True, 'import numpy as np\n'), ((39499, 39561), 'fordclassifier.evaluator.predictorClass.Predictor', 'Predictor', (['self._project_path', 'self._subfolders'], {'verbose': '(False)'}), '(self._project_path, self._subfolders, verbose=False)\n', (39508, 39561), False, 'from fordclassifier.evaluator.predictorClass import Predictor\n'), ((40882, 40910), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (40892, 40910), True, 'import matplotlib.pyplot as plt\n'), ((40920, 40936), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Th"""'], {}), "('Th')\n", (40930, 40936), True, 'import matplotlib.pyplot as plt\n'), ((40946, 40976), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Jackard-RBO cost"""'], {}), "('Jackard-RBO cost')\n", (40956, 40976), True, 'import matplotlib.pyplot as plt\n'), ((41110, 41181), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values', 'COST', '"""b"""'], {'label': '"""Jackard-RBO cost"""', 'linewidth': '(3.0)'}), "(th_values, COST, 'b', label='Jackard-RBO cost', linewidth=3.0)\n", (41118, 41181), True, 'import matplotlib.pyplot as plt\n'), ((41191, 41270), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values', 'COST_dens', '"""r"""'], {'label': '"""Labels Density cost"""', 'linewidth': '(3.0)'}), "(th_values, COST_dens, 'r', label='Labels Density cost', linewidth=3.0)\n", (41199, 41270), True, 'import matplotlib.pyplot as plt\n'), ((41309, 41324), 'numpy.argmin', 'np.argmin', (['COST'], {}), '(COST)\n', (41318, 41324), True, 'import numpy as np\n'), ((41373, 41478), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values[cual_min]', 'COST[cual_min]', '"""bo"""'], {'label': '"""Minimum Jackard-RBO cost"""', 'linewidth': '(3.0)'}), "(th_values[cual_min], COST[cual_min], 'bo', label=\n 'Minimum Jackard-RBO cost', linewidth=3.0)\n", (41381, 41478), True, 'import matplotlib.pyplot as plt\n'), ((41512, 41532), 'numpy.argmin', 'np.argmin', (['COST_dens'], {}), '(COST_dens)\n', (41521, 41532), True, 'import numpy as np\n'), ((41581, 41694), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values[cual_min]', 'COST_dens[cual_min]', '"""ro"""'], {'label': '"""Minimum Labels Density cost"""', 'linewidth': '(3.0)'}), "(th_values[cual_min], COST_dens[cual_min], 'ro', label=\n 'Minimum Labels Density cost', linewidth=3.0)\n", (41589, 41694), True, 'import matplotlib.pyplot as plt\n'), ((41717, 41746), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (41727, 41746), True, 'import matplotlib.pyplot as plt\n'), ((41756, 41770), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (41764, 41770), True, 'import matplotlib.pyplot as plt\n'), ((41952, 41973), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (41963, 41973), True, 'import matplotlib.pyplot as plt\n'), ((41983, 41994), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (41992, 41994), True, 'import matplotlib.pyplot as plt\n'), ((42027, 42054), 'numpy.mean', 'np.mean', (['[th_JRBO, th_DENS]'], {}), '([th_JRBO, th_DENS])\n', (42034, 42054), True, 'import numpy as np\n'), ((42077, 42170), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""multilabel_th.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'multilabel_th.pkl')\n", (42089, 42170), False, 'import os\n'), ((42305, 42391), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['export'])", '"""multilabel_th.pkl"""'], {}), "(self._project_path + self._subfolders['export'],\n 'multilabel_th.pkl')\n", (42317, 42391), False, 'import os\n'), ((43851, 43913), 'fordclassifier.evaluator.predictorClass.Predictor', 'Predictor', (['self._project_path', 'self._subfolders'], {'verbose': '(False)'}), '(self._project_path, self._subfolders, verbose=False)\n', (43860, 43913), False, 'from fordclassifier.evaluator.predictorClass import Predictor\n'), ((45242, 45270), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (45252, 45270), True, 'import matplotlib.pyplot as plt\n'), ((45280, 45296), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Th"""'], {}), "('Th')\n", (45290, 45296), True, 'import matplotlib.pyplot as plt\n'), ((45306, 45336), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Jackard-RBO cost"""'], {}), "('Jackard-RBO cost')\n", (45316, 45336), True, 'import matplotlib.pyplot as plt\n'), ((45470, 45541), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values', 'COST', '"""b"""'], {'label': '"""Jackard-RBO cost"""', 'linewidth': '(3.0)'}), "(th_values, COST, 'b', label='Jackard-RBO cost', linewidth=3.0)\n", (45478, 45541), True, 'import matplotlib.pyplot as plt\n'), ((45551, 45630), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values', 'COST_dens', '"""r"""'], {'label': '"""Labels Density cost"""', 'linewidth': '(3.0)'}), "(th_values, COST_dens, 'r', label='Labels Density cost', linewidth=3.0)\n", (45559, 45630), True, 'import matplotlib.pyplot as plt\n'), ((45725, 45835), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values[cual_min]', 'COST[cual_min]', '"""bo"""'], {'label': '"""Jackard-RBO cost at threshold"""', 'linewidth': '(3.0)'}), "(th_values[cual_min], COST[cual_min], 'bo', label=\n 'Jackard-RBO cost at threshold', linewidth=3.0)\n", (45733, 45835), True, 'import matplotlib.pyplot as plt\n'), ((45858, 45976), 'matplotlib.pyplot.plot', 'plt.plot', (['th_values[cual_min]', 'COST_dens[cual_min]', '"""ro"""'], {'label': '"""Labels Density cost at threshold"""', 'linewidth': '(3.0)'}), "(th_values[cual_min], COST_dens[cual_min], 'ro', label=\n 'Labels Density cost at threshold', linewidth=3.0)\n", (45866, 45976), True, 'import matplotlib.pyplot as plt\n'), ((45999, 46028), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (46009, 46028), True, 'import matplotlib.pyplot as plt\n'), ((46038, 46052), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (46046, 46052), True, 'import matplotlib.pyplot as plt\n'), ((46235, 46256), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (46246, 46256), True, 'import matplotlib.pyplot as plt\n'), ((46266, 46277), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (46275, 46277), True, 'import matplotlib.pyplot as plt\n'), ((51706, 51781), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", 'filename_out'], {}), "(self._project_path, self._subfolders['results'], filename_out)\n", (51718, 51781), False, 'import os\n'), ((6220, 6310), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""train_data.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'train_data.pkl')\n", (6232, 6310), False, 'import os\n'), ((6567, 6652), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['test_data'])", '"""test_data.pkl"""'], {}), "(self._project_path + self._subfolders['test_data'],\n 'test_data.pkl')\n", (6579, 6652), False, 'import os\n'), ((6905, 6990), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""tags.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'], 'tags.pkl'\n )\n", (6917, 6990), False, 'import os\n'), ((7770, 7845), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", '"""Preds.pkl"""'], {}), "(self._project_path + self._subfolders['results'], 'Preds.pkl')\n", (7782, 7845), False, 'import os\n'), ((8013, 8090), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", '"""Preds_tr.pkl"""'], {}), "(self._project_path, self._subfolders['results'], 'Preds_tr.pkl')\n", (8025, 8090), False, 'import os\n'), ((8279, 8358), 'os.path.join', 'os.path.join', (['self._project_path', "self._subfolders['results']", '"""Preds_test.pkl"""'], {}), "(self._project_path, self._subfolders['results'], 'Preds_test.pkl')\n", (8291, 8358), False, 'import os\n'), ((8543, 8617), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", '"""CONF.pkl"""'], {}), "(self._project_path + self._subfolders['results'], 'CONF.pkl')\n", (8555, 8617), False, 'import os\n'), ((8786, 8872), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['test_data'])", '"""tags_index.pkl"""'], {}), "(self._project_path + self._subfolders['test_data'],\n 'tags_index.pkl')\n", (8798, 8872), False, 'import os\n'), ((11549, 11577), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (11559, 11577), True, 'import matplotlib.pyplot as plt\n'), ((13518, 13535), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""FPR"""'], {}), "('FPR')\n", (13528, 13535), True, 'import matplotlib.pyplot as plt\n'), ((13549, 13566), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""TPR"""'], {}), "('TPR')\n", (13559, 13566), True, 'import matplotlib.pyplot as plt\n'), ((13580, 13623), 'matplotlib.pyplot.title', 'plt.title', (["('ROC curves for category ' + cat)"], {}), "('ROC curves for category ' + cat)\n", (13589, 13623), True, 'import matplotlib.pyplot as plt\n'), ((13637, 13651), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (13645, 13651), True, 'import matplotlib.pyplot as plt\n'), ((13665, 13694), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (13675, 13694), True, 'import matplotlib.pyplot as plt\n'), ((13834, 13855), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (13845, 13855), True, 'import matplotlib.pyplot as plt\n'), ((13869, 13880), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (13878, 13880), True, 'import matplotlib.pyplot as plt\n'), ((14723, 14737), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (14734, 14737), False, 'import pickle\n'), ((15384, 15398), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (15395, 15398), False, 'import pickle\n'), ((16851, 16865), 'numpy.argsort', 'np.argsort', (['(-p)'], {}), '(-p)\n', (16861, 16865), True, 'import numpy as np\n'), ((18097, 18122), 'pickle.dump', 'pickle.dump', (['self.CONF', 'f'], {}), '(self.CONF, f)\n', (18108, 18122), False, 'import pickle\n'), ((19814, 19839), 'pickle.dump', 'pickle.dump', (['self.CONF', 'f'], {}), '(self.CONF, f)\n', (19825, 19839), False, 'import pickle\n'), ((22933, 22958), 'pickle.dump', 'pickle.dump', (['self.CONF', 'f'], {}), '(self.CONF, f)\n', (22944, 22958), False, 'import pickle\n'), ((23618, 23638), 'pandas.read_excel', 'pd.read_excel', (['fpath'], {}), '(fpath)\n', (23631, 23638), True, 'import pandas as pd\n'), ((28955, 28972), 'numpy.diagonal', 'np.diagonal', (['CONF'], {}), '(CONF)\n', (28966, 28972), True, 'import numpy as np\n'), ((31565, 31592), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_tst', 'preds_tst'], {}), '(y_tst, preds_tst)\n', (31574, 31592), False, 'from sklearn.metrics import roc_curve, auc\n'), ((31620, 31641), 'sklearn.metrics.auc', 'auc', (['fpr_tst', 'tpr_tst'], {}), '(fpr_tst, tpr_tst)\n', (31623, 31641), False, 'from sklearn.metrics import roc_curve, auc\n'), ((32143, 32171), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (32153, 32171), True, 'import matplotlib.pyplot as plt\n'), ((32185, 32202), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""FPR"""'], {}), "('FPR')\n", (32195, 32202), True, 'import matplotlib.pyplot as plt\n'), ((32216, 32233), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""TPR"""'], {}), "('TPR')\n", (32226, 32233), True, 'import matplotlib.pyplot as plt\n'), ((32247, 32294), 'matplotlib.pyplot.title', 'plt.title', (["('ROC test curve for category ' + cat)"], {}), "('ROC test curve for category ' + cat)\n", (32256, 32294), True, 'import matplotlib.pyplot as plt\n'), ((32375, 32439), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr_tst', 'tpr_tst', 'colors[3]'], {'label': 'text', 'linewidth': '(6.0)'}), '(fpr_tst, tpr_tst, colors[3], label=text, linewidth=6.0)\n', (32383, 32439), True, 'import matplotlib.pyplot as plt\n'), ((32453, 32467), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (32461, 32467), True, 'import matplotlib.pyplot as plt\n'), ((32481, 32510), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (32491, 32510), True, 'import matplotlib.pyplot as plt\n'), ((32632, 32653), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (32643, 32653), True, 'import matplotlib.pyplot as plt\n'), ((32667, 32678), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (32676, 32678), True, 'import matplotlib.pyplot as plt\n'), ((33475, 33502), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_tst', 'preds_tst'], {}), '(y_tst, preds_tst)\n', (33484, 33502), False, 'from sklearn.metrics import roc_curve, auc\n'), ((33530, 33551), 'sklearn.metrics.auc', 'auc', (['fpr_tst', 'tpr_tst'], {}), '(fpr_tst, tpr_tst)\n', (33533, 33551), False, 'from sklearn.metrics import roc_curve, auc\n'), ((34039, 34067), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 12)'}), '(figsize=(15, 12))\n', (34049, 34067), True, 'import matplotlib.pyplot as plt\n'), ((34081, 34098), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""FPR"""'], {}), "('FPR')\n", (34091, 34098), True, 'import matplotlib.pyplot as plt\n'), ((34112, 34129), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""TPR"""'], {}), "('TPR')\n", (34122, 34129), True, 'import matplotlib.pyplot as plt\n'), ((34143, 34190), 'matplotlib.pyplot.title', 'plt.title', (["('ROC test curve for category ' + cat)"], {}), "('ROC test curve for category ' + cat)\n", (34152, 34190), True, 'import matplotlib.pyplot as plt\n'), ((34265, 34329), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr_tst', 'tpr_tst', 'colors[3]'], {'label': 'text', 'linewidth': '(6.0)'}), '(fpr_tst, tpr_tst, colors[3], label=text, linewidth=6.0)\n', (34273, 34329), True, 'import matplotlib.pyplot as plt\n'), ((34343, 34357), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (34351, 34357), True, 'import matplotlib.pyplot as plt\n'), ((34371, 34400), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (34381, 34400), True, 'import matplotlib.pyplot as plt\n'), ((34554, 34575), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (34565, 34575), True, 'import matplotlib.pyplot as plt\n'), ((34589, 34600), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (34598, 34600), True, 'import matplotlib.pyplot as plt\n'), ((37125, 37149), 'pickle.dump', 'pickle.dump', (['ths_dict', 'f'], {}), '(ths_dict, f)\n', (37136, 37149), False, 'import pickle\n'), ((40614, 40628), 'numpy.mean', 'np.mean', (['jrbos'], {}), '(jrbos)\n', (40621, 40628), True, 'import numpy as np\n'), ((42248, 42282), 'pickle.dump', 'pickle.dump', (['self.multilabel_th', 'f'], {}), '(self.multilabel_th, f)\n', (42259, 42282), False, 'import pickle\n'), ((42469, 42503), 'pickle.dump', 'pickle.dump', (['self.multilabel_th', 'f'], {}), '(self.multilabel_th, f)\n', (42480, 42503), False, 'import pickle\n'), ((44974, 44988), 'numpy.mean', 'np.mean', (['jrbos'], {}), '(jrbos)\n', (44981, 44988), True, 'import numpy as np\n'), ((46591, 46637), 'os.path.join', 'os.path.join', (['path2export', '"""multilabel_th.pkl"""'], {}), "(path2export, 'multilabel_th.pkl')\n", (46603, 46637), False, 'import os\n'), ((49774, 49784), 'numpy.sum', 'np.sum', (['w0'], {}), '(w0)\n', (49780, 49784), True, 'import numpy as np\n'), ((5564, 5576), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5573, 5576), False, 'import json\n'), ((6482, 6496), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6493, 6496), False, 'import pickle\n'), ((6828, 6842), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6839, 6842), False, 'import pickle\n'), ((7102, 7116), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7113, 7116), False, 'import pickle\n'), ((7198, 7276), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['results'])", '"""ths_dict.pkl"""'], {}), "(self._project_path + self._subfolders['results'], 'ths_dict.pkl')\n", (7210, 7276), False, 'import os\n'), ((7939, 7953), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7950, 7953), False, 'import pickle\n'), ((8204, 8218), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8215, 8218), False, 'import pickle\n'), ((8473, 8487), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8484, 8487), False, 'import pickle\n'), ((8710, 8724), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8721, 8724), False, 'import pickle\n'), ((9000, 9014), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9011, 9014), False, 'import pickle\n'), ((9098, 9188), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""categories.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'categories.pkl')\n", (9110, 9188), False, 'import os\n'), ((9716, 9811), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""models2evaluate.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'models2evaluate.pkl')\n", (9728, 9811), False, 'import os\n'), ((10352, 10445), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['training_data'])", '"""multilabel_th.pkl"""'], {}), "(self._project_path + self._subfolders['training_data'],\n 'multilabel_th.pkl')\n", (10364, 10445), False, 'import os\n'), ((21861, 21876), 'numpy.zeros', 'np.zeros', (['Ncats'], {}), '(Ncats)\n', (21869, 21876), True, 'import numpy as np\n'), ((22171, 22186), 'numpy.zeros', 'np.zeros', (['Ncats'], {}), '(Ncats)\n', (22179, 22186), True, 'import numpy as np\n'), ((22436, 22452), 'numpy.minimum', 'np.minimum', (['p', 'q'], {}), '(p, q)\n', (22446, 22452), True, 'import numpy as np\n'), ((22474, 22489), 'numpy.diag', 'np.diag', (['min_pq'], {}), '(min_pq)\n', (22481, 22489), True, 'import numpy as np\n'), ((24214, 24231), 'pandas.read_excel', 'pd.read_excel', (['fp'], {}), '(fp)\n', (24227, 24231), True, 'import pandas as pd\n'), ((24344, 24361), 'numpy.minimum', 'np.minimum', (['C', 'Cf'], {}), '(C, Cf)\n', (24354, 24361), True, 'import numpy as np\n'), ((26075, 26090), 'numpy.zeros', 'np.zeros', (['Ncats'], {}), '(Ncats)\n', (26083, 26090), True, 'import numpy as np\n'), ((26385, 26400), 'numpy.zeros', 'np.zeros', (['Ncats'], {}), '(Ncats)\n', (26393, 26400), True, 'import numpy as np\n'), ((26665, 26683), 'pyemd.emd', 'pyemd.emd', (['p', 'q', 'C'], {}), '(p, q, C)\n', (26674, 26683), False, 'import pyemd\n'), ((32108, 32129), 'pickle.dump', 'pickle.dump', (['mdict', 'f'], {}), '(mdict, f)\n', (32119, 32129), False, 'import pickle\n'), ((34002, 34023), 'pickle.dump', 'pickle.dump', (['mdict', 'f'], {}), '(mdict, f)\n', (34013, 34023), False, 'import pickle\n'), ((35390, 35404), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (35401, 35404), False, 'import pickle\n'), ((36717, 36731), 'numpy.argmax', 'np.argmax', (['mix'], {}), '(mix)\n', (36726, 36731), True, 'import numpy as np\n'), ((37613, 37648), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['tags'], {}), '(tags)\n', (37642, 37648), False, 'import itertools\n'), ((39032, 39055), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['l'], {}), '(l)\n', (39052, 39055), False, 'from collections import OrderedDict\n'), ((43382, 43405), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['l'], {}), '(l)\n', (43402, 43405), False, 'from collections import OrderedDict\n'), ((46721, 46735), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (46732, 46735), False, 'import pickle\n'), ((5858, 5870), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5867, 5870), False, 'import json\n'), ((7406, 7420), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7417, 7420), False, 'import pickle\n'), ((7470, 7547), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['export'])", '"""ths_dict.pkl"""'], {}), "(self._project_path + self._subfolders['export'], 'ths_dict.pkl')\n", (7482, 7547), False, 'import os\n'), ((9316, 9330), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9327, 9330), False, 'import pickle\n'), ((9380, 9459), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['export'])", '"""categories.pkl"""'], {}), "(self._project_path + self._subfolders['export'], 'categories.pkl')\n", (9392, 9459), False, 'import os\n'), ((9944, 9958), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9955, 9958), False, 'import pickle\n'), ((10008, 10096), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['export'])", '"""models2evaluate.pkl"""'], {}), "(self._project_path + self._subfolders['export'],\n 'models2evaluate.pkl')\n", (10020, 10096), False, 'import os\n'), ((10576, 10590), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10587, 10590), False, 'import pickle\n'), ((10640, 10726), 'os.path.join', 'os.path.join', (["(self._project_path + self._subfolders['export'])", '"""multilabel_th.pkl"""'], {}), "(self._project_path + self._subfolders['export'],\n 'multilabel_th.pkl')\n", (10652, 10726), False, 'import os\n'), ((12250, 12272), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (12269, 12272), False, 'import operator\n'), ((22043, 22052), 'numpy.sum', 'np.sum', (['p'], {}), '(p)\n', (22049, 22052), True, 'import numpy as np\n'), ((22353, 22362), 'numpy.sum', 'np.sum', (['q'], {}), '(q)\n', (22359, 22362), True, 'import numpy as np\n'), ((22632, 22646), 'numpy.sum', 'np.sum', (['min_pq'], {}), '(min_pq)\n', (22638, 22646), True, 'import numpy as np\n'), ((26257, 26266), 'numpy.sum', 'np.sum', (['p'], {}), '(p)\n', (26263, 26266), True, 'import numpy as np\n'), ((26567, 26576), 'numpy.sum', 'np.sum', (['q'], {}), '(q)\n', (26573, 26576), True, 'import numpy as np\n'), ((36345, 36359), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (36356, 36359), False, 'import pickle\n'), ((51366, 51379), 'numpy.sum', 'np.sum', (['pesos'], {}), '(pesos)\n', (51372, 51379), True, 'import numpy as np\n'), ((6116, 6128), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6125, 6128), False, 'import json\n'), ((7677, 7691), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7688, 7691), False, 'import pickle\n'), ((9591, 9605), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9602, 9605), False, 'import pickle\n'), ((10229, 10243), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10240, 10243), False, 'import pickle\n'), ((10857, 10871), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10868, 10871), False, 'import pickle\n'), ((12025, 12039), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12036, 12039), False, 'import pickle\n'), ((12860, 12874), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12871, 12874), False, 'import pickle\n'), ((13202, 13258), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr', 'colors[k]'], {'label': 'text', 'linewidth': '(6.0)'}), '(fpr, tpr, colors[k], label=text, linewidth=6.0)\n', (13210, 13258), True, 'import matplotlib.pyplot as plt\n'), ((13357, 13413), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr', 'colors[k]'], {'label': 'text', 'linewidth': '(2.0)'}), '(fpr, tpr, colors[k], label=text, linewidth=2.0)\n', (13365, 13413), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python3 # do not hesitate to debug import pdb # python computation modules and visualization import numpy as np import sympy as sy import scipy as sp import matplotlib.pyplot as plt from sympy import Q as syQ sy.init_printing(use_latex=True,forecolor="White") def Lyapunov_stability_test_linear(ev): ''' test if a linear homogeneous system with constant coefficients is stable in the sense of Lyapunov by checking the theorem conditions against the provided eigenvalues source https://www.math24.net/stability-theory-basic-concepts/ TODO taking into account eigenvalue multiplicity ''' # the criteria result will be saved here r = None # system is asymptotically stable if only if # all eigenvalues have negative real parts r = 'asymptotically stable' if ( not r and all(sy.ask(syQ.negative(sy.re(_))) for _ in ev) ) else None # system is stable if and only if # all eigenvalues have nonpositive real parts # TODO incorporate algebraic and geometric multiplicity criteria r = 'stable' if ( not r and all(sy.ask(syQ.nonpositive(sy.re(_))) for _ in ev) ) else None # system is unstable if # at least one eigenvalue has positive real part # TODO incorporate algebraic and geometric multiplicity criteria r = 'unstable' if ( not r and any(sy.ask(syQ.positive(sy.re(_))) for _ in ev) ) else None return r def Lyapunov_stability_test_nonlinear(ev): ''' test if the fixed point of a nonlinear structure stable system is stable, unstable, critical or impossible to determine using Lyapunov criteria of first order and thus other methods are needed TODO tests are only applicable for structurally stable systems, i.e. with purely imaginary eigenvalues are not taken into account source https://www.math24.net/stability-first-approximation/ ''' # the criteria result will be saved here r = None # system is asymptotically stable if only if # all eigenvalues have negative real parts r = 'asymptotically stable' if ( not r and all(sy.ask(syQ.negative(sy.re(_))) for _ in ev) ) else None # system is unstable if # at least one eigenvalue has positive real part r = 'unstable' if ( not r and any(sy.ask(syQ.positive(sy.re(_))) for _ in ev) ) else None # if all eigenvalues have non-positive real parts, # and there is at least one eigenvalue with zero real part # then fixed point can be stable or unstable and other methods should be # used, thus mark the point critical r = 'critical' if ( not r and all(sy.ask(Q.nonpositive(sy.re(_))) for _ in ev) and any(sy.re(_) == 0 for _ in ev) ) else None return r if r else 'not decided' def RouthHurwitz_Criterion(p): ''' return principal minors of Hurwitz matrix as sympy polynomials, which if all are positive it is sufficient condition for asymptotic stability NOTE: if all n-1 principal minors are positive, and nth minor is zero, the system is at the boundary of stability, with two cases: a_n = 0 -- one of the root is zero and system is on the boundary of aperiodic stability n-1 minor is zero -- there are two complex conjugate imaginary roots and the system is at boundary of oscillatory stability source https://www.math24.net/routh-hurwitz-criterion/ ''' # initial key and index pair needed to create Hurwitz matrix via sympy banded # each entry is of the type [ dictionary key, coefficient slice ] idxs = [ [ 1, 0 ] ] # generate next key by decrementing with 1 genKey = lambda _: _ - 1 # generate next index by incrementing with 1 if key was nonnegative # or with 2 if key is negative genSlice = lambda _, __: __ + 1 if _ >= 0 else __ + 2 # fill the rest pairs w.r.t. the polynomial degree - 1, as we already have # one entry for _ in range(p.degree() - 1): key = genKey(idxs[-1][0]) idxs.append( [ key, genSlice(key, idxs[-1][1] ) ] ) # create the matrix itself H = sy.banded({ k: p.all_coeffs()[v:] for k, v in idxs }) return [ H[:_, :_].det() if _ > 0 else p.LC() for _ in range(0, p.degree()+1) ] # define independent variable t = sy.symbols('t', real=True) # define dependent variables individually and pact them in an variable theta, omega = sy.symbols(r'\theta, \omega', real = True) Y = theta, omega # define free parameters of they system and pack them in a variable g, L = sy.symbols('g, L', positive = True) parms = g, L # create rhs as sympy expressions theta_dt = omega omega_dt = -(g/L)*sy.sin(theta) rhs = {} rhs['sympy'] = sy.Matrix([theta_dt, omega_dt]) # convert the sympy matrix function to numpy function with usual signature rhs['numpy'] = sy.lambdify((t, Y, *parms), rhs['sympy'], 'numpy') # create Jacobian matrix as sympy expression J = {} J['sympy'] = rhs['sympy'].jacobian(Y) # convert the sympy Jacobian expression to numpy function with usual signature J['numpy'] = sy.lambdify((t, Y, *parms), J['sympy']) # calculate rhs fixed points fixed_points = sy.solve(rhs['sympy'], Y) # substitute each fixed point in the Jacobian # and calculate the eigenvalues J_fixed = {} for i, fp in enumerate(fixed_points): J_subs = J['sympy'].subs( [(y, v) for y, v in zip(Y, fp)]) #J_eigenvals = J_subs.eigenvals(multiple=True) J_eigenvals = J_subs.eigenvals() # save the fixed point results in more details # most importantly the eigenvalues and their corresponding multiplicity J_fixed[i] = { 'fixed point': fp, 'subs': J_subs, 'eigenvalues': list(J_eigenvals.keys()), 'multiplicity': list(J_eigenvals.values()) } def plot_phase_portrait(ax, rhs, section, args=(), n_points=25): ''' plot section of phase space of a field defined via its rhs ''' # create section grid x_grid, y_grid = np.meshgrid( np.linspace( section[0][0], section[0][1], n_points ), np.linspace( section[1][0], section[1][1], n_points ) ) # calculate rhs on the grid xx, yy = rhs(None, ( x_grid, y_grid ), *args) # compute vector norms and make line width proportional to them # i.e. greater the vector length, the thicker the line # TODO not sure why rhs returns different shape vector_norms = np.sqrt(xx[0]**2 + yy[0]**2) lw = 0.25 + 3*vector_norms/vector_norms.max() # plot the phase portrait ax.streamplot( x_grid, y_grid, xx[0], yy[0], linewidth = lw, arrowsize = 1.2, density = 1 ) return ax def plot_main(): fig, ax = plt.subplots() ax = plot_phase_portrait( ax, rhs['numpy'], ( ( -np.pi, np.pi ), ( -2*np.pi, 2*np.pi) ), args = ( 5, 1 ), ) if __name__ == '__main__': plot_main()
[ "sympy.sin", "numpy.sqrt", "sympy.re", "sympy.lambdify", "sympy.Matrix", "sympy.init_printing", "sympy.symbols", "numpy.linspace", "sympy.solve", "matplotlib.pyplot.subplots" ]
[((227, 278), 'sympy.init_printing', 'sy.init_printing', ([], {'use_latex': '(True)', 'forecolor': '"""White"""'}), "(use_latex=True, forecolor='White')\n", (243, 278), True, 'import sympy as sy\n'), ((4294, 4320), 'sympy.symbols', 'sy.symbols', (['"""t"""'], {'real': '(True)'}), "('t', real=True)\n", (4304, 4320), True, 'import sympy as sy\n'), ((4408, 4449), 'sympy.symbols', 'sy.symbols', (['"""\\\\theta, \\\\omega"""'], {'real': '(True)'}), "('\\\\theta, \\\\omega', real=True)\n", (4418, 4449), True, 'import sympy as sy\n'), ((4545, 4578), 'sympy.symbols', 'sy.symbols', (['"""g, L"""'], {'positive': '(True)'}), "('g, L', positive=True)\n", (4555, 4578), True, 'import sympy as sy\n'), ((4702, 4733), 'sympy.Matrix', 'sy.Matrix', (['[theta_dt, omega_dt]'], {}), '([theta_dt, omega_dt])\n', (4711, 4733), True, 'import sympy as sy\n'), ((4825, 4875), 'sympy.lambdify', 'sy.lambdify', (['(t, Y, *parms)', "rhs['sympy']", '"""numpy"""'], {}), "((t, Y, *parms), rhs['sympy'], 'numpy')\n", (4836, 4875), True, 'import sympy as sy\n'), ((5060, 5099), 'sympy.lambdify', 'sy.lambdify', (['(t, Y, *parms)', "J['sympy']"], {}), "((t, Y, *parms), J['sympy'])\n", (5071, 5099), True, 'import sympy as sy\n'), ((5145, 5170), 'sympy.solve', 'sy.solve', (["rhs['sympy']", 'Y'], {}), "(rhs['sympy'], Y)\n", (5153, 5170), True, 'import sympy as sy\n'), ((4664, 4677), 'sympy.sin', 'sy.sin', (['theta'], {}), '(theta)\n', (4670, 4677), True, 'import sympy as sy\n'), ((6409, 6441), 'numpy.sqrt', 'np.sqrt', (['(xx[0] ** 2 + yy[0] ** 2)'], {}), '(xx[0] ** 2 + yy[0] ** 2)\n', (6416, 6441), True, 'import numpy as np\n'), ((6735, 6749), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6747, 6749), True, 'import matplotlib.pyplot as plt\n'), ((5992, 6043), 'numpy.linspace', 'np.linspace', (['section[0][0]', 'section[0][1]', 'n_points'], {}), '(section[0][0], section[0][1], n_points)\n', (6003, 6043), True, 'import numpy as np\n'), ((6059, 6110), 'numpy.linspace', 'np.linspace', (['section[1][0]', 'section[1][1]', 'n_points'], {}), '(section[1][0], section[1][1], n_points)\n', (6070, 6110), True, 'import numpy as np\n'), ((2713, 2721), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (2718, 2721), True, 'import sympy as sy\n'), ((865, 873), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (870, 873), True, 'import sympy as sy\n'), ((1130, 1138), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (1135, 1138), True, 'import sympy as sy\n'), ((1387, 1395), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (1392, 1395), True, 'import sympy as sy\n'), ((2137, 2145), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (2142, 2145), True, 'import sympy as sy\n'), ((2325, 2333), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (2330, 2333), True, 'import sympy as sy\n'), ((2669, 2677), 'sympy.re', 'sy.re', (['_'], {}), '(_)\n', (2674, 2677), True, 'import sympy as sy\n')]
#coding=utf-8 import numpy as np import tensorflow as tf import os import sys import time import shutil import re import signal import subprocess import numpy as np import math from Policy import * np.set_printoptions(threshold=np.inf) BASELINES = 1 class MultiBaseline: def __init__(self, baseline_number): self.baseline_number = baseline_number self.baselines = [Baseline() for _ in range(baseline_number)] self.reward_signal_access, self.reward_signal_wait, self.reward_signal_piece = [], [], [] self.reward_signal_wait_info1, self.reward_signal_wait_info2, self.reward_signal_wait_info3 = [], [], [] def __str__(self): stri = '' for i in range(self.baseline_number): stri = stri + 'baseline number ' + str(i) + ' has reward ' + str(self.baselines[i].reward) + '\n' stri = stri + str(self.baselines[i].sample) + '\n' return stri def insert_baseline(self, baseline): if baseline > self.baselines[0]: self.baselines[0].SetSampleWithAnotherBaseline(baseline) self.baselines.sort() def store_reward_signal(self, result): self.reward_signal_access.extend(result[0]) self.reward_signal_wait.extend(result[1]) self.reward_signal_piece.extend(result[2]) self.reward_signal_wait_info1.extend(result[3]) self.reward_signal_wait_info2.extend(result[4]) self.reward_signal_wait_info3.extend(result[5]) def samples_different_action(self, access, wait, piece, waitinfo1, waitinfo2, waitinfo3): # get a all True form result = Sample.default_different_action() # get different actions for j in range(self.baseline_number): diff = self.baselines[j].different_action(\ access, wait, piece, waitinfo1, waitinfo2, waitinfo3) for i in range(len(result)): result[i] = result[i] & np.array(diff[i]) self.store_reward_signal(result) def get_ratio(self, avg_reward): rewards = [] for i in range(self.baseline_number): reward_ = self.baselines[i].reward - avg_reward if reward_ > 0: rewards.append(reward_) else: rewards.append(0) rewards = np.array(rewards) if np.sum(rewards) == 0: return [1 / self.baseline_number] * self.baseline_number else: return rewards / np.sum(rewards) def calculate_reward(self, reward): # ratio = self.get_ratio(np.mean(reward)) access_rs, wait_rs, piece_rs = \ [0] * (len(reward) * ACCESSE_SPACE), [0] * (len(reward) * WAIT_SPACE), [0] * (len(reward) * PIECE_SPACE) waitinfo1_rs, waitinfo2_rs, waitinfo3_rs = \ [0] * (len(reward) * WAIT_SPACE), [0] * (len(reward) * WAIT_SPACE), [0] * (len(reward) * WAIT_SPACE) # for i in range(self.baseline_number): # calculate discount_reward for each slot access_dr, wait_dr, piece_dr = [], [], [] waitinfo1_dr, waitinfo2_dr, waitinfo3_dr = [], [], [] for j in range(len(reward)): for _ in range(ACCESSE_SPACE): access_dr.append(reward[j]) for _ in range(PIECE_SPACE): piece_dr.append(reward[j]) for _ in range(WAIT_SPACE): wait_dr.append(reward[j]) waitinfo1_dr.append(reward[j]) waitinfo2_dr.append(reward[j]) waitinfo3_dr.append(reward[j]) avg_reward = np.mean(reward) access_rs = np.array(access_dr) - avg_reward wait_rs = np.array(wait_dr) - avg_reward piece_rs = np.array(piece_dr) - avg_reward waitinfo1_rs = (np.array(waitinfo1_dr) - avg_reward) * 5 waitinfo2_rs = (np.array(waitinfo2_dr) - avg_reward) * 2 waitinfo3_rs = (np.array(waitinfo3_dr) - avg_reward) * 2.5 # access_dr = np.array(access_dr) - self.baselines[i].reward # wait_dr = np.array(wait_dr) - self.baselines[i].reward # piece_dr = np.array(piece_dr) - self.baselines[i].reward # waitinfo1_dr = np.array(waitinfo1_dr) - self.baselines[i].reward # waitinfo2_dr = np.array(waitinfo2_dr) - self.baselines[i].reward # waitinfo3_dr = np.array(waitinfo3_dr) - self.baselines[i].reward # access_rs = access_rs + ratio[i] * access_dr * ((access_dr > 0) | self.reward_signal_access) # wait_rs = wait_rs + ratio[i] * wait_dr * ((wait_dr > 0) | self.reward_signal_wait) # piece_rs = piece_rs + ratio[i] * piece_dr * ((piece_dr > 0) | self.reward_signal_piece) # waitinfo1_rs = waitinfo1_rs + ratio[i] * waitinfo1_dr * ((waitinfo1_dr > 0) | self.reward_signal_wait_info1) # waitinfo2_rs = waitinfo2_rs + ratio[i] * waitinfo2_dr * ((waitinfo2_dr > 0) | self.reward_signal_wait_info2) # waitinfo3_rs = waitinfo3_rs + ratio[i] * waitinfo3_dr * ((waitinfo3_dr > 0) | self.reward_signal_wait_info3) return access_rs, wait_rs, piece_rs, waitinfo1_rs, waitinfo2_rs, waitinfo3_rs def clear_signal(self): self.reward_signal_access, self.reward_signal_wait, self.reward_signal_piece = [], [], [] self.reward_signal_wait_info1, self.reward_signal_wait_info2, self.reward_signal_wait_info3 = [], [], [] class Baseline: def __init__(self, access = [], wait = [], piece = [], \ waitinfo1 = [], waitinfo2 = [], waitinfo3 = [], \ reward = 0): if access == []: self.set = False else: self.set = True # manual asign a opt setting for backoff self.sample = Sample(access, wait, piece, waitinfo1, waitinfo2, waitinfo3, 6, [0,4,8,1,0,0,8,4,2,1,8,1,4,2,1,4,2,4]) self.reward = reward def setSample(self, access, wait, piece, waitinfo1, waitinfo2, waitinfo3, reward): self.set = True self.sample.set_sample(access, wait, piece, waitinfo1, waitinfo2, waitinfo3) self.reward = reward def SetSampleWithAnotherBaseline(self, baseline): self.setSample(baseline.sample.access, baseline.sample.wait, baseline.sample.piece, \ baseline.sample.wait_info1, baseline.sample.wait_info2, baseline.sample.wait_info3, \ baseline.reward) def __lt__(self, r): return self.reward < r.reward def different_action(self, access, wait, piece, waitinfo1, waitinfo2, waitinfo3): if self.set == False: return Sample.default_different_action() return self.sample.different_action(access, wait, piece, \ waitinfo1, waitinfo2, waitinfo3) class PolicyGradient: # initialize def __init__(self, log_dir, kid_dir, learning_rate,rd,output_graph=False): self.log_dir = log_dir self.kid_dir = kid_dir self.lr = learning_rate self.reward_decay = rd self.best_seen = 0 self.round_best = 0 self.round_mean = 0 self.round_worst = 0 self.round_std = 0 self.round_best_sample = None self.baselines = MultiBaseline(BASELINES) # to store observations, actions and corresponding rewards self.access_p, self.wait_p, self.piece_p = [], [], [] self.wait_info1_p, self.wait_info2_p, self.wait_info3_p = [], [], [] self.ep_access_rs, self.ep_wait_rs, self.ep_piece_rs = [], [], [] self.ep_waitinfo1_rs, self.ep_waitinfo2_rs, self.ep_waitinfo3_rs = [], [], [] self.ep_access_act, self.ep_wait_act, self.ep_piece_act = [], [], [] self.ep_wait_info_act1, self.ep_wait_info_act2, self.ep_wait_info_act3 = [], [], [] self.samples_count = 0 self.policy = Policy() self._build_net() self.sess = tf.Session() if output_graph: tf.summary.FileWriter("logs/", self.sess.graph) self.sess.run(tf.global_variables_initializer()) self.update_policy() def clear_round_info(self): self.round_best = 0 self.round_mean = 0 self.round_worst = 0 self.round_std = 0 self.round_best_sample = None def _build_net(self): with tf.name_scope('inputs'): self.tf_access_vt = tf.placeholder(tf.float32, [None, ], name="access_value") self.tf_wait_vt = tf.placeholder(tf.float32, [None, ], name="wait_value") self.tf_piece_vt = tf.placeholder(tf.float32, [None, ], name="piece_value") self.tf_wait_info_vt1 = tf.placeholder(tf.float32, [None, ], name="wait_info_value1") self.tf_wait_info_vt2 = tf.placeholder(tf.float32, [None, ], name="wait_info_value2") self.tf_wait_info_vt3 = tf.placeholder(tf.float32, [None, ], name="wait_info_value3") self.tf_access_act = tf.placeholder(tf.int32, [None, ], name="access_act") self.tf_wait_act = tf.placeholder(tf.int32, [None, ], name="wait_act") self.tf_piece_act = tf.placeholder(tf.int32, [None, ], name="piece_act") self.tf_wait_info_act1 = tf.placeholder(tf.int32, [None, ], name="wait_info_act1") self.tf_wait_info_act2 = tf.placeholder(tf.int32, [None, ], name="wait_info_act2") self.tf_wait_info_act3 = tf.placeholder(tf.int32, [None, ], name="wait_info_act3") self.tf_samples_count = tf.placeholder(tf.float32, name='samples_count') self.learning_rate = tf.placeholder(tf.float32, name='learning_rate') self.access_action_v = tf.Variable(tf.random_normal(shape=[INPUT_SPACE, 2], mean=0, stddev=1), name='access_action_v') self.wait_action_v = tf.Variable(tf.random_normal(shape=[WAIT_SPACE, 2], mean=0, stddev=1), name='wait_action_v') self.piece_action_v = tf.Variable(tf.random_normal(shape=[PIECE_SPACE, 2], mean=0, stddev=1), name='piece_action_v') self.wait_info_action1_v = tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[0]], mean=0, stddev=1), name='wait_info_action1_v') self.wait_info_action2_v = tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[1]], mean=0, stddev=1), name='wait_info_action2_v') self.wait_info_action3_v = tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[2]], mean=0, stddev=1), name='wait_info_action3_v') self.access_action = tf.nn.softmax(self.access_action_v, axis = 1) self.wait_action = tf.nn.softmax(self.wait_action_v, axis = 1) self.piece_action = tf.nn.softmax(self.piece_action_v, axis = 1) self.wait_info_action1 = tf.nn.softmax(self.wait_info_action1_v, axis = 1) self.wait_info_action2 = tf.nn.softmax(self.wait_info_action2_v, axis = 1) self.wait_info_action3 = tf.nn.softmax(self.wait_info_action3_v, axis = 1) # self.access_action = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[ACCESSE_SPACE, 2], mean=0, stddev=1), name='access_action'), axis = 1) # self.wait_action = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[WAIT_SPACE, 2], mean=0, stddev=1), name='wait_action'), axis = 1) # self.piece_action = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[PIECE_SPACE, 2], mean=0, stddev=1), name='piece_action'), axis = 1) # self.wait_info_action1 = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[0]], mean=0, stddev=1), name='wait_info_action1'), axis = 1) # self.wait_info_action2 = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[1]], mean=0, stddev=1), name='wait_info_action2'), axis = 1) # self.wait_info_action3 = tf.nn.softmax(tf.Variable(tf.random_normal(shape=[WAIT_SPACE, wait_info_act_count[2]], mean=0, stddev=1), name='wait_info_action3'), axis = 1) with tf.name_scope('reward'): # add a very small number to the probability in case of logging a very small number and then ouputting NAN self.access_action = tf.add(self.access_action, 0.000001) self.wait_action = tf.add(self.wait_action, 0.000001) self.piece_action = tf.add(self.piece_action, 0.000001) self.wait_info_action1 = tf.add(self.wait_info_action1, 0.000001) self.wait_info_action2 = tf.add(self.wait_info_action2, 0.000001) self.wait_info_action3 = tf.add(self.wait_info_action3, 0.000001) access_act = tf.reshape(tf.one_hot(self.tf_access_act, 2), [-1, ACCESSE_SPACE * 2]) access_act_prob = tf.reshape((access_act * (tf.reshape(self.access_action, [ACCESSE_SPACE * 2]))), [-1 ,2]) access_act_prob = -tf.log(tf.reduce_sum(access_act_prob, axis = 1)) wait_act = tf.reshape(tf.one_hot(self.tf_wait_act, 2), [-1, WAIT_SPACE * 2]) wait_act_prob = tf.reshape((wait_act * (tf.reshape(self.wait_action, [WAIT_SPACE * 2]))), [-1 ,2]) wait_act_prob = -tf.log(tf.reduce_sum(wait_act_prob, axis = 1)) piece_act = tf.reshape(tf.one_hot(self.tf_piece_act, 2), [-1, PIECE_SPACE * 2]) piece_act_prob = tf.reshape((piece_act * (tf.reshape(self.piece_action, [PIECE_SPACE * 2]))), [-1 ,2]) piece_act_prob = -tf.log(tf.reduce_sum(piece_act_prob, axis = 1)) wait_info_act1 = tf.reshape((tf.one_hot(self.tf_wait_info_act1, wait_info_act_count[0])), [-1, WAIT_SPACE * wait_info_act_count[0]]) wait_info_act1_prob = tf.reshape((wait_info_act1 * (tf.reshape(self.wait_info_action1, [WAIT_SPACE * wait_info_act_count[0]]))), [-1, wait_info_act_count[0]]) wait_info_act1_prob = -tf.log(tf.reduce_sum(wait_info_act1_prob, axis = 1)) wait_info_act2 = tf.reshape((tf.one_hot(self.tf_wait_info_act2, wait_info_act_count[1])), [-1, WAIT_SPACE * wait_info_act_count[1]]) wait_info_act2_prob = tf.reshape((wait_info_act2 * (tf.reshape(self.wait_info_action2, [WAIT_SPACE * wait_info_act_count[1]]))), [-1, wait_info_act_count[1]]) wait_info_act2_prob = -tf.log(tf.reduce_sum(wait_info_act2_prob, axis = 1)) wait_info_act3 = tf.reshape((tf.one_hot(self.tf_wait_info_act3, wait_info_act_count[2])), [-1, WAIT_SPACE * wait_info_act_count[2]]) wait_info_act3_prob = tf.reshape((wait_info_act3 * (tf.reshape(self.wait_info_action3, [WAIT_SPACE * wait_info_act_count[2]]))), [-1, wait_info_act_count[2]]) wait_info_act3_prob = -tf.log(tf.reduce_sum(wait_info_act3_prob, axis = 1)) self.reward = tf.divide(tf.reduce_sum(access_act_prob * self.tf_access_vt) + \ tf.reduce_sum(piece_act_prob * self.tf_piece_vt) + \ tf.reduce_sum(wait_act_prob * self.tf_wait_vt) + \ tf.reduce_sum(wait_info_act1_prob * self.tf_wait_info_vt1) + \ tf.reduce_sum(wait_info_act2_prob * self.tf_wait_info_vt2) + \ tf.reduce_sum(wait_info_act3_prob * self.tf_wait_info_vt3), self.tf_samples_count) with tf.name_scope('train'): self.train_op = tf.train.GradientDescentOptimizer(learning_rate = self.learning_rate).minimize(self.reward) def update_policy(self): access_p, wait_p, piece_p, wait_info1_p, wait_info2_p, wait_info3_p = \ self.sess.run([self.access_action, self.wait_action, self.piece_action, \ self.wait_info_action1, self.wait_info_action2, self.wait_info_action3]) self.policy.set_prob(access_p, wait_p, piece_p, \ wait_info1_p, wait_info2_p, wait_info3_p) # store corresponding reward def record_reward(self, round_id, reward, previous_samples, idx): access = self.ep_access_act[previous_samples * ACCESSE_SPACE : (previous_samples + 1) * ACCESSE_SPACE] wait = self.ep_wait_act[previous_samples * WAIT_SPACE : (previous_samples + 1) * WAIT_SPACE] piece = self.ep_piece_act[previous_samples * PIECE_SPACE : (previous_samples + 1) * PIECE_SPACE] waitinfo1 = self.ep_wait_info_act1[previous_samples * WAIT_SPACE : (previous_samples + 1) * WAIT_SPACE] waitinfo2 = self.ep_wait_info_act2[previous_samples * WAIT_SPACE : (previous_samples + 1) * WAIT_SPACE] waitinfo3 = self.ep_wait_info_act3[previous_samples * WAIT_SPACE : (previous_samples + 1) * WAIT_SPACE] if reward > self.baselines.baselines[0].reward: baseline_ = Baseline(access, wait, piece, waitinfo1, waitinfo2, waitinfo3, reward) self.baselines.insert_baseline(baseline_) if reward > self.best_seen: self.best_seen = reward # save RL best seen result print('Update rl best seen sample - {}'.format(reward)) kid_path = os.path.join(os.getcwd(), self.kid_dir + '/kid_' + str(idx) + '.txt') log_path = os.path.join(os.getcwd(), self.log_dir + '/rl_best.txt') shutil.copy(kid_path, log_path) # save RL best seen result for every round old_path = os.path.join(os.getcwd(), self.log_dir + '/rl_best.txt') new_path = os.path.join(os.getcwd(), self.log_dir + '/rl_best_iter_' + str(round_id) + '.txt') shutil.copy(old_path, new_path) if reward > self.round_best: self.round_best = reward kid_path = os.path.join(os.getcwd(), self.kid_dir + '/kid_' + str(idx) + '.txt') log_path = os.path.join(os.getcwd(), self.log_dir + '/round_best_' + str(round_id) + '.txt') shutil.copy(kid_path, log_path) # store round_best sample for EA future use self.round_best_sample = Sample(access, wait, piece, \ waitinfo1, waitinfo2, waitinfo3, 6, [0,4,8,1,0,0,8,4,2,1,8,1,4,2,1,4,2,4]) if self.round_worst == 0: self.round_worst = reward if reward < self.round_worst: self.round_worst = reward self.round_mean = (self.round_mean * previous_samples + reward)/(previous_samples + 1) # store reward for each sample self.ep_rs.append(reward) def Evaluate(self, command, round_id, samples_per_distribution, load_per_sample): base_path = os.path.join(os.getcwd(), self.log_dir) policy_path = os.path.join(base_path, 'Distribution.txt') with open(policy_path, 'a+') as f: f.write('RL at iter {}'.format(round_id) + '\n') f.write(str(self.policy) + '\n') self.ep_rs = [] self.ep_access_act, self.ep_wait_act, self.ep_piece_act, \ self.ep_wait_info_act1, self.ep_wait_info_act2, self.ep_wait_info_act3, \ = self.policy.table_sample_batch(self.kid_dir, samples_per_distribution) policies_res = samples_eval(command, samples_per_distribution, load_per_sample) reward_ = 0 fail_to_exe = 0 for idx in range(samples_per_distribution): # if the execution has failed, rollback the ep_obs and ep_as, continue the training if policies_res[idx][0] == 0.0 and policies_res[idx][1] == 1.0: print("continue") self.rollback(idx, fail_to_exe) fail_to_exe += 1 continue print("RL sample:" + str(idx) + " throughput:" + str(policies_res[idx][0])) self.record_reward(round_id, policies_res[idx][0], idx - fail_to_exe, idx) def set_baseline(self, access, wait, piece, \ wait_info1, wait_info2, wait_info3, \ reward_buffer): samples = int(len(access) / ACCESSE_SPACE) for i in range(samples): r = reward_buffer[i] if r > self.baselines.baselines[0].reward: access_t = access[i * ACCESSE_SPACE : (i + 1) * ACCESSE_SPACE] wait_t = wait[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] piece_t = piece[i * PIECE_SPACE : (i + 1) * PIECE_SPACE] waitinfo1_t = wait_info1[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] waitinfo2_t = wait_info2[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] waitinfo3_t = wait_info3[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] baseline_ = Baseline(access_t, wait_t, piece_t, \ waitinfo1_t, waitinfo2_t, waitinfo3_t, \ r) self.baselines.insert_baseline(baseline_) print("access") print(self.baselines.baselines[0].sample) access, wait, piece, waitinfo1, waitinfo2, waitinfo3 = self.baselines.baselines[0].sample.get_actions() assign_access = tf.assign(self.access_action_v, access) assign_wait = tf.assign(self.wait_action_v, wait) assign_piece = tf.assign(self.piece_action_v, piece) assign_waitinfo1 = tf.assign(self.wait_info_action1_v, waitinfo1) assign_waitinfo2 = tf.assign(self.wait_info_action2_v, waitinfo2) assign_waitinfo3 = tf.assign(self.wait_info_action3_v, waitinfo3) self.sess.run([assign_access, assign_wait, assign_piece, assign_waitinfo1, assign_waitinfo2, assign_waitinfo3]) self.update_policy() def get_ic3_distribution(self, access_in, wait_in , piece_in, waitinfo1_in, waitinfo2_in, waitinfo3_in): access, wait, piece, waitinfo1, waitinfo2, waitinfo3 = \ self.baselines.baselines[0].sample.get_actions(access_in, wait_in , piece_in, waitinfo1_in, waitinfo2_in, waitinfo3_in) assign_access = tf.assign(self.access_action_v, access) assign_wait = tf.assign(self.wait_action_v, wait) assign_piece = tf.assign(self.piece_action_v, piece) assign_waitinfo1 = tf.assign(self.wait_info_action1_v, waitinfo1) assign_waitinfo2 = tf.assign(self.wait_info_action2_v, waitinfo2) assign_waitinfo3 = tf.assign(self.wait_info_action3_v, waitinfo3) self.sess.run([assign_access, assign_wait, assign_piece, assign_waitinfo1, assign_waitinfo2, assign_waitinfo3]) self.update_policy() # preprocess the reward def get_reward(self, access, wait, piece, \ wait_info1, wait_info2, wait_info3, \ reward_buffer): samples = int(len(access) / ACCESSE_SPACE) for i in range(samples): access_t = access[i * ACCESSE_SPACE : (i + 1) * ACCESSE_SPACE] wait_t = wait[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] piece_t = piece[i * PIECE_SPACE : (i + 1) * PIECE_SPACE] waitinfo1_t = wait_info1[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] waitinfo2_t = wait_info2[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] waitinfo3_t = wait_info3[i * WAIT_SPACE : (i + 1) * WAIT_SPACE] self.baselines.samples_different_action(access_t, wait_t, piece_t, \ waitinfo1_t, waitinfo2_t, waitinfo3_t) self.ep_access_rs, self.ep_wait_rs, self.ep_piece_rs, \ self.ep_waitinfo1_rs, self.ep_waitinfo2_rs, self.ep_waitinfo3_rs, \ = self.baselines.calculate_reward(reward_buffer) self.baselines.clear_signal() def learn(self, idx, lr, generations): if (len(self.ep_access_act) == 0): print("useless round") return base_path = os.path.join(os.getcwd(), self.log_dir) baseline_path = os.path.join(base_path, 'Baseline.txt') with open(baseline_path, 'a+') as f: f.write('RL at iter {}'.format(idx) + ', ') f.write(str(self.baselines) + '\n') self.get_reward(self.ep_access_act, self.ep_wait_act, self.ep_piece_act, \ self.ep_wait_info_act1, self.ep_wait_info_act2, self.ep_wait_info_act3, \ self.ep_rs) self.lr = 0.5 * lr * (1 + math.cos(math.pi * idx / generations)) self.samples_count = len(self.ep_rs) self.sess.run(self.train_op, feed_dict={ self.tf_access_act: self.ep_access_act, self.tf_wait_act: self.ep_wait_act, self.tf_piece_act: self.ep_piece_act, self.tf_wait_info_act1: self.ep_wait_info_act1, self.tf_wait_info_act2: self.ep_wait_info_act2, self.tf_wait_info_act3: self.ep_wait_info_act3, self.tf_access_vt: self.ep_access_rs, self.tf_wait_vt: self.ep_wait_rs, self.tf_piece_vt: self.ep_piece_rs, self.tf_wait_info_vt1: self.ep_waitinfo1_rs, self.tf_wait_info_vt2: self.ep_waitinfo2_rs, self.tf_wait_info_vt3: self.ep_waitinfo3_rs, self.tf_samples_count: self.samples_count, self.learning_rate: self.lr, }) self.update_policy() # tool functions: def get_prob(self): self.access_p, self.wait_p, self.piece_p, \ self.wait_info1_p, self.wait_info2_p, self.wait_info3_p, \ = self.sess.run([self.access_action, self.wait_action, self.piece_action, \ self.wait_info_action1, self.wait_info_action2, self.wait_info_action3]) self.print_prob() def print_prob(self): stri = "" stri += str(self.access_p) + " " stri += str(self.wait_p) + " " stri += str(self.piece_p) + " " stri += str(self.wait_info1_p) + " " stri += str(self.wait_info2_p) + " " stri += str(self.wait_info3_p) + " " print(stri + "\n") def rollback(self, index, fail_to_exe): self.ep_access_act = self.ep_access_act[:(index - fail_to_exe) * ACCESSE_SPACE] + self.ep_access_act[(index + 1 - fail_to_exe) * ACCESSE_SPACE :] self.ep_wait_act = self.ep_wait_act[:(index - fail_to_exe) * WAIT_SPACE] + self.ep_wait_act[(index + 1 - fail_to_exe) * WAIT_SPACE :] self.ep_piece_act = self.ep_piece_act[:(index - fail_to_exe) * PIECE_SPACE] + self.ep_piece_act[(index + 1 - fail_to_exe) * PIECE_SPACE :] self.ep_wait_info_act1 = self.ep_wait_info_act1[:(index - fail_to_exe) * WAIT_SPACE] + self.ep_wait_info_act1[(index + 1 - fail_to_exe) * WAIT_SPACE :] self.ep_wait_info_act2 = self.ep_wait_info_act2[:(index - fail_to_exe) * WAIT_SPACE] + self.ep_wait_info_act2[(index + 1 - fail_to_exe) * WAIT_SPACE :] self.ep_wait_info_act3 = self.ep_wait_info_act3[:(index - fail_to_exe) * WAIT_SPACE] + self.ep_wait_info_act3[(index + 1 - fail_to_exe) * WAIT_SPACE :]
[ "tensorflow.reduce_sum", "math.cos", "numpy.array", "tensorflow.nn.softmax", "numpy.mean", "tensorflow.random_normal", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.assign", "tensorflow.one_hot", "tensorflow.add", "tensorflow.train.GradientDescentOptimizer", "shutil.copy", "tensorflow.reshape", "tensorflow.summary.FileWriter", "numpy.set_printoptions", "os.path.join", "os.getcwd", "tensorflow.global_variables_initializer", "numpy.sum", "tensorflow.name_scope" ]
[((199, 236), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (218, 236), True, 'import numpy as np\n'), ((2315, 2332), 'numpy.array', 'np.array', (['rewards'], {}), '(rewards)\n', (2323, 2332), True, 'import numpy as np\n'), ((3569, 3584), 'numpy.mean', 'np.mean', (['reward'], {}), '(reward)\n', (3576, 3584), True, 'import numpy as np\n'), ((7904, 7916), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7914, 7916), True, 'import tensorflow as tf\n'), ((10475, 10518), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.access_action_v'], {'axis': '(1)'}), '(self.access_action_v, axis=1)\n', (10488, 10518), True, 'import tensorflow as tf\n'), ((10548, 10589), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.wait_action_v'], {'axis': '(1)'}), '(self.wait_action_v, axis=1)\n', (10561, 10589), True, 'import tensorflow as tf\n'), ((10620, 10662), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.piece_action_v'], {'axis': '(1)'}), '(self.piece_action_v, axis=1)\n', (10633, 10662), True, 'import tensorflow as tf\n'), ((10698, 10745), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.wait_info_action1_v'], {'axis': '(1)'}), '(self.wait_info_action1_v, axis=1)\n', (10711, 10745), True, 'import tensorflow as tf\n'), ((10781, 10828), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.wait_info_action2_v'], {'axis': '(1)'}), '(self.wait_info_action2_v, axis=1)\n', (10794, 10828), True, 'import tensorflow as tf\n'), ((10864, 10911), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['self.wait_info_action3_v'], {'axis': '(1)'}), '(self.wait_info_action3_v, axis=1)\n', (10877, 10911), True, 'import tensorflow as tf\n'), ((18424, 18467), 'os.path.join', 'os.path.join', (['base_path', '"""Distribution.txt"""'], {}), "(base_path, 'Distribution.txt')\n", (18436, 18467), False, 'import os\n'), ((20805, 20844), 'tensorflow.assign', 'tf.assign', (['self.access_action_v', 'access'], {}), '(self.access_action_v, access)\n', (20814, 20844), True, 'import tensorflow as tf\n'), ((20867, 20902), 'tensorflow.assign', 'tf.assign', (['self.wait_action_v', 'wait'], {}), '(self.wait_action_v, wait)\n', (20876, 20902), True, 'import tensorflow as tf\n'), ((20926, 20963), 'tensorflow.assign', 'tf.assign', (['self.piece_action_v', 'piece'], {}), '(self.piece_action_v, piece)\n', (20935, 20963), True, 'import tensorflow as tf\n'), ((20991, 21037), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action1_v', 'waitinfo1'], {}), '(self.wait_info_action1_v, waitinfo1)\n', (21000, 21037), True, 'import tensorflow as tf\n'), ((21065, 21111), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action2_v', 'waitinfo2'], {}), '(self.wait_info_action2_v, waitinfo2)\n', (21074, 21111), True, 'import tensorflow as tf\n'), ((21139, 21185), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action3_v', 'waitinfo3'], {}), '(self.wait_info_action3_v, waitinfo3)\n', (21148, 21185), True, 'import tensorflow as tf\n'), ((21664, 21703), 'tensorflow.assign', 'tf.assign', (['self.access_action_v', 'access'], {}), '(self.access_action_v, access)\n', (21673, 21703), True, 'import tensorflow as tf\n'), ((21726, 21761), 'tensorflow.assign', 'tf.assign', (['self.wait_action_v', 'wait'], {}), '(self.wait_action_v, wait)\n', (21735, 21761), True, 'import tensorflow as tf\n'), ((21785, 21822), 'tensorflow.assign', 'tf.assign', (['self.piece_action_v', 'piece'], {}), '(self.piece_action_v, piece)\n', (21794, 21822), True, 'import tensorflow as tf\n'), ((21850, 21896), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action1_v', 'waitinfo1'], {}), '(self.wait_info_action1_v, waitinfo1)\n', (21859, 21896), True, 'import tensorflow as tf\n'), ((21924, 21970), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action2_v', 'waitinfo2'], {}), '(self.wait_info_action2_v, waitinfo2)\n', (21933, 21970), True, 'import tensorflow as tf\n'), ((21998, 22044), 'tensorflow.assign', 'tf.assign', (['self.wait_info_action3_v', 'waitinfo3'], {}), '(self.wait_info_action3_v, waitinfo3)\n', (22007, 22044), True, 'import tensorflow as tf\n'), ((23530, 23569), 'os.path.join', 'os.path.join', (['base_path', '"""Baseline.txt"""'], {}), "(base_path, 'Baseline.txt')\n", (23542, 23569), False, 'import os\n'), ((2344, 2359), 'numpy.sum', 'np.sum', (['rewards'], {}), '(rewards)\n', (2350, 2359), True, 'import numpy as np\n'), ((3606, 3625), 'numpy.array', 'np.array', (['access_dr'], {}), '(access_dr)\n', (3614, 3625), True, 'import numpy as np\n'), ((3657, 3674), 'numpy.array', 'np.array', (['wait_dr'], {}), '(wait_dr)\n', (3665, 3674), True, 'import numpy as np\n'), ((3707, 3725), 'numpy.array', 'np.array', (['piece_dr'], {}), '(piece_dr)\n', (3715, 3725), True, 'import numpy as np\n'), ((7955, 8002), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs/"""', 'self.sess.graph'], {}), "('logs/', self.sess.graph)\n", (7976, 8002), True, 'import tensorflow as tf\n'), ((8026, 8059), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8057, 8059), True, 'import tensorflow as tf\n'), ((8313, 8336), 'tensorflow.name_scope', 'tf.name_scope', (['"""inputs"""'], {}), "('inputs')\n", (8326, 8336), True, 'import tensorflow as tf\n'), ((8370, 8425), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""access_value"""'}), "(tf.float32, [None], name='access_value')\n", (8384, 8425), True, 'import tensorflow as tf\n'), ((8458, 8511), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""wait_value"""'}), "(tf.float32, [None], name='wait_value')\n", (8472, 8511), True, 'import tensorflow as tf\n'), ((8545, 8599), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""piece_value"""'}), "(tf.float32, [None], name='piece_value')\n", (8559, 8599), True, 'import tensorflow as tf\n'), ((8638, 8697), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""wait_info_value1"""'}), "(tf.float32, [None], name='wait_info_value1')\n", (8652, 8697), True, 'import tensorflow as tf\n'), ((8736, 8795), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""wait_info_value2"""'}), "(tf.float32, [None], name='wait_info_value2')\n", (8750, 8795), True, 'import tensorflow as tf\n'), ((8834, 8893), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""wait_info_value3"""'}), "(tf.float32, [None], name='wait_info_value3')\n", (8848, 8893), True, 'import tensorflow as tf\n'), ((8930, 8981), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""access_act"""'}), "(tf.int32, [None], name='access_act')\n", (8944, 8981), True, 'import tensorflow as tf\n'), ((9015, 9064), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""wait_act"""'}), "(tf.int32, [None], name='wait_act')\n", (9029, 9064), True, 'import tensorflow as tf\n'), ((9099, 9149), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""piece_act"""'}), "(tf.int32, [None], name='piece_act')\n", (9113, 9149), True, 'import tensorflow as tf\n'), ((9189, 9244), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""wait_info_act1"""'}), "(tf.int32, [None], name='wait_info_act1')\n", (9203, 9244), True, 'import tensorflow as tf\n'), ((9284, 9339), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""wait_info_act2"""'}), "(tf.int32, [None], name='wait_info_act2')\n", (9298, 9339), True, 'import tensorflow as tf\n'), ((9379, 9434), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""wait_info_act3"""'}), "(tf.int32, [None], name='wait_info_act3')\n", (9393, 9434), True, 'import tensorflow as tf\n'), ((9474, 9522), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""samples_count"""'}), "(tf.float32, name='samples_count')\n", (9488, 9522), True, 'import tensorflow as tf\n'), ((9556, 9604), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""learning_rate"""'}), "(tf.float32, name='learning_rate')\n", (9570, 9604), True, 'import tensorflow as tf\n'), ((9649, 9707), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[INPUT_SPACE, 2]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[INPUT_SPACE, 2], mean=0, stddev=1)\n', (9665, 9707), True, 'import tensorflow as tf\n'), ((9774, 9831), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[WAIT_SPACE, 2]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[WAIT_SPACE, 2], mean=0, stddev=1)\n', (9790, 9831), True, 'import tensorflow as tf\n'), ((9897, 9955), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[PIECE_SPACE, 2]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[PIECE_SPACE, 2], mean=0, stddev=1)\n', (9913, 9955), True, 'import tensorflow as tf\n'), ((10027, 10105), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[WAIT_SPACE, wait_info_act_count[0]]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[WAIT_SPACE, wait_info_act_count[0]], mean=0, stddev=1)\n', (10043, 10105), True, 'import tensorflow as tf\n'), ((10182, 10260), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[WAIT_SPACE, wait_info_act_count[1]]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[WAIT_SPACE, wait_info_act_count[1]], mean=0, stddev=1)\n', (10198, 10260), True, 'import tensorflow as tf\n'), ((10337, 10415), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[WAIT_SPACE, wait_info_act_count[2]]', 'mean': '(0)', 'stddev': '(1)'}), '(shape=[WAIT_SPACE, wait_info_act_count[2]], mean=0, stddev=1)\n', (10353, 10415), True, 'import tensorflow as tf\n'), ((11916, 11939), 'tensorflow.name_scope', 'tf.name_scope', (['"""reward"""'], {}), "('reward')\n", (11929, 11939), True, 'import tensorflow as tf\n'), ((12093, 12126), 'tensorflow.add', 'tf.add', (['self.access_action', '(1e-06)'], {}), '(self.access_action, 1e-06)\n', (12099, 12126), True, 'import tensorflow as tf\n'), ((12161, 12192), 'tensorflow.add', 'tf.add', (['self.wait_action', '(1e-06)'], {}), '(self.wait_action, 1e-06)\n', (12167, 12192), True, 'import tensorflow as tf\n'), ((12228, 12260), 'tensorflow.add', 'tf.add', (['self.piece_action', '(1e-06)'], {}), '(self.piece_action, 1e-06)\n', (12234, 12260), True, 'import tensorflow as tf\n'), ((12301, 12338), 'tensorflow.add', 'tf.add', (['self.wait_info_action1', '(1e-06)'], {}), '(self.wait_info_action1, 1e-06)\n', (12307, 12338), True, 'import tensorflow as tf\n'), ((12379, 12416), 'tensorflow.add', 'tf.add', (['self.wait_info_action2', '(1e-06)'], {}), '(self.wait_info_action2, 1e-06)\n', (12385, 12416), True, 'import tensorflow as tf\n'), ((12457, 12494), 'tensorflow.add', 'tf.add', (['self.wait_info_action3', '(1e-06)'], {}), '(self.wait_info_action3, 1e-06)\n', (12463, 12494), True, 'import tensorflow as tf\n'), ((15172, 15194), 'tensorflow.name_scope', 'tf.name_scope', (['"""train"""'], {}), "('train')\n", (15185, 15194), True, 'import tensorflow as tf\n'), ((17062, 17093), 'shutil.copy', 'shutil.copy', (['kid_path', 'log_path'], {}), '(kid_path, log_path)\n', (17073, 17093), False, 'import shutil\n'), ((17348, 17379), 'shutil.copy', 'shutil.copy', (['old_path', 'new_path'], {}), '(old_path, new_path)\n', (17359, 17379), False, 'import shutil\n'), ((17664, 17695), 'shutil.copy', 'shutil.copy', (['kid_path', 'log_path'], {}), '(kid_path, log_path)\n', (17675, 17695), False, 'import shutil\n'), ((18375, 18386), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (18384, 18386), False, 'import os\n'), ((23479, 23490), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (23488, 23490), False, 'import os\n'), ((2478, 2493), 'numpy.sum', 'np.sum', (['rewards'], {}), '(rewards)\n', (2484, 2493), True, 'import numpy as np\n'), ((3763, 3785), 'numpy.array', 'np.array', (['waitinfo1_dr'], {}), '(waitinfo1_dr)\n', (3771, 3785), True, 'import numpy as np\n'), ((3828, 3850), 'numpy.array', 'np.array', (['waitinfo2_dr'], {}), '(waitinfo2_dr)\n', (3836, 3850), True, 'import numpy as np\n'), ((3893, 3915), 'numpy.array', 'np.array', (['waitinfo3_dr'], {}), '(waitinfo3_dr)\n', (3901, 3915), True, 'import numpy as np\n'), ((12535, 12568), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_access_act', '(2)'], {}), '(self.tf_access_act, 2)\n', (12545, 12568), True, 'import tensorflow as tf\n'), ((12830, 12861), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_wait_act', '(2)'], {}), '(self.tf_wait_act, 2)\n', (12840, 12861), True, 'import tensorflow as tf\n'), ((13108, 13140), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_piece_act', '(2)'], {}), '(self.tf_piece_act, 2)\n', (13118, 13140), True, 'import tensorflow as tf\n'), ((13400, 13458), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_wait_info_act1', 'wait_info_act_count[0]'], {}), '(self.tf_wait_info_act1, wait_info_act_count[0])\n', (13410, 13458), True, 'import tensorflow as tf\n'), ((13805, 13863), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_wait_info_act2', 'wait_info_act_count[1]'], {}), '(self.tf_wait_info_act2, wait_info_act_count[1])\n', (13815, 13863), True, 'import tensorflow as tf\n'), ((14210, 14268), 'tensorflow.one_hot', 'tf.one_hot', (['self.tf_wait_info_act3', 'wait_info_act_count[2]'], {}), '(self.tf_wait_info_act3, wait_info_act_count[2])\n', (14220, 14268), True, 'import tensorflow as tf\n'), ((16913, 16924), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (16922, 16924), False, 'import os\n'), ((17006, 17017), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17015, 17017), False, 'import os\n'), ((17185, 17196), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17194, 17196), False, 'import os\n'), ((17265, 17276), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17274, 17276), False, 'import os\n'), ((17490, 17501), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17499, 17501), False, 'import os\n'), ((17583, 17594), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17592, 17594), False, 'import os\n'), ((23972, 24009), 'math.cos', 'math.cos', (['(math.pi * idx / generations)'], {}), '(math.pi * idx / generations)\n', (23980, 24009), False, 'import math\n'), ((1953, 1970), 'numpy.array', 'np.array', (['diff[i]'], {}), '(diff[i])\n', (1961, 1970), True, 'import numpy as np\n'), ((12651, 12702), 'tensorflow.reshape', 'tf.reshape', (['self.access_action', '[ACCESSE_SPACE * 2]'], {}), '(self.access_action, [ACCESSE_SPACE * 2])\n', (12661, 12702), True, 'import tensorflow as tf\n'), ((12753, 12791), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['access_act_prob'], {'axis': '(1)'}), '(access_act_prob, axis=1)\n', (12766, 12791), True, 'import tensorflow as tf\n'), ((12937, 12983), 'tensorflow.reshape', 'tf.reshape', (['self.wait_action', '[WAIT_SPACE * 2]'], {}), '(self.wait_action, [WAIT_SPACE * 2])\n', (12947, 12983), True, 'import tensorflow as tf\n'), ((13032, 13068), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wait_act_prob'], {'axis': '(1)'}), '(wait_act_prob, axis=1)\n', (13045, 13068), True, 'import tensorflow as tf\n'), ((13219, 13267), 'tensorflow.reshape', 'tf.reshape', (['self.piece_action', '[PIECE_SPACE * 2]'], {}), '(self.piece_action, [PIECE_SPACE * 2])\n', (13229, 13267), True, 'import tensorflow as tf\n'), ((13317, 13354), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['piece_act_prob'], {'axis': '(1)'}), '(piece_act_prob, axis=1)\n', (13330, 13354), True, 'import tensorflow as tf\n'), ((13568, 13641), 'tensorflow.reshape', 'tf.reshape', (['self.wait_info_action1', '[WAIT_SPACE * wait_info_act_count[0]]'], {}), '(self.wait_info_action1, [WAIT_SPACE * wait_info_act_count[0]])\n', (13578, 13641), True, 'import tensorflow as tf\n'), ((13717, 13759), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wait_info_act1_prob'], {'axis': '(1)'}), '(wait_info_act1_prob, axis=1)\n', (13730, 13759), True, 'import tensorflow as tf\n'), ((13973, 14046), 'tensorflow.reshape', 'tf.reshape', (['self.wait_info_action2', '[WAIT_SPACE * wait_info_act_count[1]]'], {}), '(self.wait_info_action2, [WAIT_SPACE * wait_info_act_count[1]])\n', (13983, 14046), True, 'import tensorflow as tf\n'), ((14122, 14164), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wait_info_act2_prob'], {'axis': '(1)'}), '(wait_info_act2_prob, axis=1)\n', (14135, 14164), True, 'import tensorflow as tf\n'), ((14378, 14451), 'tensorflow.reshape', 'tf.reshape', (['self.wait_info_action3', '[WAIT_SPACE * wait_info_act_count[2]]'], {}), '(self.wait_info_action3, [WAIT_SPACE * wait_info_act_count[2]])\n', (14388, 14451), True, 'import tensorflow as tf\n'), ((14527, 14569), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wait_info_act3_prob'], {'axis': '(1)'}), '(wait_info_act3_prob, axis=1)\n', (14540, 14569), True, 'import tensorflow as tf\n'), ((15075, 15133), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wait_info_act3_prob * self.tf_wait_info_vt3)'], {}), '(wait_info_act3_prob * self.tf_wait_info_vt3)\n', (15088, 15133), True, 'import tensorflow as tf\n'), ((15224, 15291), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': 'self.learning_rate'}), '(learning_rate=self.learning_rate)\n', (15257, 15291), True, 'import tensorflow as tf\n'), ((14976, 15034), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wait_info_act2_prob * self.tf_wait_info_vt2)'], {}), '(wait_info_act2_prob * self.tf_wait_info_vt2)\n', (14989, 15034), True, 'import tensorflow as tf\n'), ((14877, 14935), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wait_info_act1_prob * self.tf_wait_info_vt1)'], {}), '(wait_info_act1_prob * self.tf_wait_info_vt1)\n', (14890, 14935), True, 'import tensorflow as tf\n'), ((14790, 14836), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(wait_act_prob * self.tf_wait_vt)'], {}), '(wait_act_prob * self.tf_wait_vt)\n', (14803, 14836), True, 'import tensorflow as tf\n'), ((14610, 14660), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(access_act_prob * self.tf_access_vt)'], {}), '(access_act_prob * self.tf_access_vt)\n', (14623, 14660), True, 'import tensorflow as tf\n'), ((14701, 14749), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(piece_act_prob * self.tf_piece_vt)'], {}), '(piece_act_prob * self.tf_piece_vt)\n', (14714, 14749), True, 'import tensorflow as tf\n')]
import numpy as np from scipy.special import factorial from itertools import permutations, product from pysat.solvers import Minisat22, Minicard from pysat.pb import PBEnc from clauses import build_clauses, build_max_min_clauses from clauses import build_permutation_clauses from clauses import build_cardinality_lits, build_exclusivity_lits def compare_dice(first, second): hits = 0 for x in first: for y in second: if y < x: hits += 1 return hits def compare_doubled_dice(first, second, comp="max"): d = len(first) hits = 0 if comp == "max": indices = range(1, 2 * d, 2) if comp == "min": indices = range(2 * d - 1, 0, -2) for i, x in zip(indices, first): for j, y in zip(indices, second): if y < x: hits += i * j return hits def recover_values(d, dice_names, constraints): natural_faces = [] for die in dice_names: faces = np.arange(d) for die2 in dice_names: if die != die2: faces += constraints[(die, die2)].sum(1) natural_faces.append(faces) return natural_faces def compress_values(*args): T = {} for i, die in enumerate(args): T.update({k: i for k in die}) n = len(T.keys()) T_list = [T[i] for i in range(n)] current_value = 0 current_die = T_list[0] compressed_dice = [[] for _ in args] compressed_dice[current_die].append(current_value) for i in range(1, n): previous_die = current_die current_die = T_list[i] if current_die != previous_die: current_value += 1 compressed_dice[current_die].append(current_value) return compressed_dice def sat_to_constraints(d, dice_names, sat_solution, compress=True): dice_pairs = list(permutations(dice_names, 2)) n = len(dice_pairs) signs_array = (sat_solution[: (n * d ** 2)] > 0).reshape((n, d, d)) constraints = {v: s for v, s in zip(dice_pairs, signs_array)} return constraints def sat_to_dice(d, dice_names, sat_solution, compress=False): constraints = sat_to_constraints(d, dice_names, sat_solution) natural_faces = recover_values(d, dice_names, constraints) if compress: dice_faces = compress_values(*natural_faces) dice_dict = {k: v for k, v in zip(dice_names, dice_faces)} else: dice_dict = {k: v for k, v in zip(dice_names, natural_faces)} return dice_dict def dice_to_constraints(dice, dtype=np.int): dice_names = list(dice.keys()) d = len(dice[dice_names[0]]) dice_pairs = list(permutations(dice_names, 2)) n = len(dice_pairs) constraints = dict() for x, y in dice_pairs: foo = np.array(dice[x]).reshape(len(dice[x]), 1) bar = np.array(dice[y]).reshape(1, len(dice[y])) constraint = foo > bar constraints[(x, y)] = constraint.astype(dtype) return constraints def dice_to_word(dice_solution): dice_names = list(dice_solution.keys()) m = len(dice_names) d = len(dice_solution[dice_names[0]]) foo = [[(x, dice_solution[x][i]) for i in range(d)] for x in dice_names] bar = sum(foo, []) ram = sorted(bar, key=lambda x: x[1]) word = "".join([t[0] for t in ram]) segments = [word[i : (i + m)] for i in range(0, m * d, m)] segmented_word = " ".join(segments) return word, segmented_word def word_to_dice(word): dice_names = set(word) dice_solution = dict() for i, w in enumerate(word): if w in dice_solution: dice_solution[w].append(i) else: dice_solution[w] = [i] return dice_solution def permute_letters(string, permutation, relative=True): letter_set = set(string) if relative: pairs = [(string.index(letter), letter) for letter in letter_set] sorted_pairs = sorted(pairs) letters = "".join(l for i, l in sorted_pairs) # letters = string[: len(letter_set)] else: letters = sorted(list(set(string))) subs = {s: letters[p] for s, p in zip(letters, permutation)} subs_string = "".join([subs[s] for s in string]) return subs_string # ---------------------------------------------------------------------------- def verify_solution(scores, dice_solution): for x, y in scores: check = compare_dice(dice_solution[x], dice_solution[y]) print((x, y), check, scores[(x, y)]) def verify_doubling_solution( scores, doubled_scores_max, doubled_scores_min, dice_solution ): verify_solution(scores, dice_solution) print() for x, y in doubled_scores_max: check = compare_doubled_dice(dice_solution[x], dice_solution[y], "max") print((x, y), check, doubled_scores_max[(x, y)]) print() for x, y in doubled_scores_min: check = compare_doubled_dice(dice_solution[x], dice_solution[y], "min") print((x, y), check, doubled_scores_min[(x, y)]) def verify_go_first(dice_solution, verbose=True): m = len(dice_solution) keys = np.array(sorted(list(dice_solution.keys()))) d = len(dice_solution[keys[0]]) check = d ** m // factorial(m, exact=True) counts = {x: 0 for x in permutations(keys)} for outcome in product(*[dice_solution[k] for k in keys]): perm = np.argsort(outcome) counts[tuple(keys[perm])] += 1 if verbose: for k in counts: print(k, check, counts[k]) print() return counts # ============================================================================ def build_sat( d, dice_names, scores, cardinality_clauses=False, symmetry_clauses=True, structure_clauses=True, pb=PBEnc.equals, ): clauses, cardinality_lits = build_clauses( d, dice_names, scores, card_clauses=cardinality_clauses, symmetry_clauses=symmetry_clauses, structure_clauses=structure_clauses, ) sat = Minicard() for clause in clauses: sat.add_clause(clause) if not cardinality_clauses: for x, lits in cardinality_lits.items(): if pb in (PBEnc.equals, PBEnc.atmost): sat.add_atmost(lits, scores[x]) if pb in (PBEnc.equals, PBEnc.atleast): conv_lits = [-l for l in lits] sat.add_atmost(conv_lits, d ** 2 - scores[x]) return sat def sat_search( d, dice_names, scores, cardinality_clauses=False, symmetry_clauses=True, structure_clauses=True, pb=PBEnc.equals, solution_type="dice_solution", ): sat = build_sat( d=d, dice_names=dice_names, scores=scores, cardinality_clauses=cardinality_clauses, symmetry_clauses=symmetry_clauses, structure_clauses=structure_clauses, pb=pb, ) is_solvable = sat.solve() if is_solvable: sat_solution = np.array(sat.get_model()) dice_solution = sat_to_dice(d, dice_names, sat_solution, compress=False) else: sat_solution = None dice_solution = None if solution_type == "sat_solution": return sat_solution elif solution_type == "dice_solution": return dice_solution # ---------------------------------------------------------------------------- def sat_exhaust( d, dice_names, scores, cardinality_clauses=False, symmetry_clauses=True, structure_clauses=True, pb=PBEnc.equals, solution_type="sat_solution", ): sat = build_sat( d=d, dice_names=dice_names, scores=scores, cardinality_clauses=cardinality_clauses, symmetry_clauses=symmetry_clauses, structure_clauses=structure_clauses, pb=pb, ) dice_pairs = list(permutations(dice_names, 2)) n = len(dice_pairs) solutions = sat.enum_models() if solution_type == "sat_solution": return [np.array(s) for s in solutions] elif solution_type == "dice_solution": dice_solutions = [sat_to_dice(d, dice_names, np.array(s)) for s in solutions] return dice_solutions # ---------------------------------------------------------------------------- def sat_search_max_min(d, dice_names, scores, max_scores, min_scores): clauses = build_max_min_clauses(d, dice_names, scores, max_scores, min_scores) sat = Minisat22() for clause in clauses: sat.add_clause(clause) is_solvable = sat.solve() if is_solvable: model = np.array(sat.get_model()) sat_solution = np.array(sat.get_model()) dice_solution = sat_to_dice(d, dice_names, sat_solution, compress=False) else: dice_solution = None return dice_solution # ---------------------------------------------------------------------------- def sat_search_go_first(d, dice_names, scores_2, scores_m, m=None): if m == None: m = len(dice_names) start_enum = 1 dice_pairs = list(permutations(dice_names, 2)) faces = {x: ["%s%i" % (x, i) for i in range(1, d + 1)] for x in dice_names} # ------------------------------------------------------------------------ var_lists_2 = {(x, y): list(product(faces[x], faces[y])) for (x, y) in dice_pairs} variables_2 = sum(var_lists_2.values(), []) var_dict_2 = dict((v, k) for k, v in enumerate(variables_2, start_enum)) start_enum += len(variables_2) # ------------------------------------------------------------------------ dice_perms = list(permutations(dice_names, m)) var_lists_m = {xs: list(product(*[faces[x] for x in xs])) for xs in dice_perms} variables_m = sum(var_lists_m.values(), []) var_dict_m = dict((v, k) for k, v in enumerate(variables_m, start_enum)) start_enum += len(variables_m) # ------------------------------------------------------------------------ clauses_2, cardinality_lits_2 = build_clauses(d, dice_names, scores_2) # ------------------------------------------------------------------------ clauses_m = build_permutation_clauses(d, var_dict_2, var_dict_m, dice_names, m) cardinality_lits_m = build_cardinality_lits(d, var_dict_m, var_lists_m) exclusivity_lits = build_exclusivity_lits(d, var_dict_m, dice_names, m) # ------------------------------------------------------------------------ clauses = clauses_2 + clauses_m sat = Minicard() for clause in clauses: sat.add_clause(clause) for x, lits in cardinality_lits_2.items(): sat.add_atmost(lits, scores_2[x]) conv_lits = [-l for l in lits] sat.add_atmost(conv_lits, d ** 2 - scores_2[x]) for x, lits in cardinality_lits_m.items(): sat.add_atmost(lits, scores_m[x]) conv_lits = [-l for l in lits] sat.add_atmost(conv_lits, d ** m - scores_m[x]) for x, lits in exclusivity_lits.items(): sat.add_atmost(lits, 1) conv_lits = [-l for l in lits] sat.add_atmost(conv_lits, len(lits) - 1) is_solvable = sat.solve() if is_solvable: sat_solution = np.array(sat.get_model()) dice_solution = sat_to_dice(d, dice_names, sat_solution, compress=False) else: dice_solution = None return dice_solution
[ "clauses.build_exclusivity_lits", "pysat.solvers.Minicard", "clauses.build_permutation_clauses", "scipy.special.factorial", "itertools.product", "clauses.build_cardinality_lits", "pysat.solvers.Minisat22", "numpy.argsort", "numpy.array", "clauses.build_max_min_clauses", "clauses.build_clauses", "itertools.permutations", "numpy.arange" ]
[((5231, 5273), 'itertools.product', 'product', (['*[dice_solution[k] for k in keys]'], {}), '(*[dice_solution[k] for k in keys])\n', (5238, 5273), False, 'from itertools import permutations, product\n'), ((5738, 5884), 'clauses.build_clauses', 'build_clauses', (['d', 'dice_names', 'scores'], {'card_clauses': 'cardinality_clauses', 'symmetry_clauses': 'symmetry_clauses', 'structure_clauses': 'structure_clauses'}), '(d, dice_names, scores, card_clauses=cardinality_clauses,\n symmetry_clauses=symmetry_clauses, structure_clauses=structure_clauses)\n', (5751, 5884), False, 'from clauses import build_clauses, build_max_min_clauses\n'), ((5947, 5957), 'pysat.solvers.Minicard', 'Minicard', ([], {}), '()\n', (5955, 5957), False, 'from pysat.solvers import Minisat22, Minicard\n'), ((8259, 8327), 'clauses.build_max_min_clauses', 'build_max_min_clauses', (['d', 'dice_names', 'scores', 'max_scores', 'min_scores'], {}), '(d, dice_names, scores, max_scores, min_scores)\n', (8280, 8327), False, 'from clauses import build_clauses, build_max_min_clauses\n'), ((8339, 8350), 'pysat.solvers.Minisat22', 'Minisat22', ([], {}), '()\n', (8348, 8350), False, 'from pysat.solvers import Minisat22, Minicard\n'), ((9867, 9905), 'clauses.build_clauses', 'build_clauses', (['d', 'dice_names', 'scores_2'], {}), '(d, dice_names, scores_2)\n', (9880, 9905), False, 'from clauses import build_clauses, build_max_min_clauses\n'), ((10003, 10070), 'clauses.build_permutation_clauses', 'build_permutation_clauses', (['d', 'var_dict_2', 'var_dict_m', 'dice_names', 'm'], {}), '(d, var_dict_2, var_dict_m, dice_names, m)\n', (10028, 10070), False, 'from clauses import build_permutation_clauses\n'), ((10096, 10146), 'clauses.build_cardinality_lits', 'build_cardinality_lits', (['d', 'var_dict_m', 'var_lists_m'], {}), '(d, var_dict_m, var_lists_m)\n', (10118, 10146), False, 'from clauses import build_cardinality_lits, build_exclusivity_lits\n'), ((10170, 10222), 'clauses.build_exclusivity_lits', 'build_exclusivity_lits', (['d', 'var_dict_m', 'dice_names', 'm'], {}), '(d, var_dict_m, dice_names, m)\n', (10192, 10222), False, 'from clauses import build_cardinality_lits, build_exclusivity_lits\n'), ((10351, 10361), 'pysat.solvers.Minicard', 'Minicard', ([], {}), '()\n', (10359, 10361), False, 'from pysat.solvers import Minisat22, Minicard\n'), ((974, 986), 'numpy.arange', 'np.arange', (['d'], {}), '(d)\n', (983, 986), True, 'import numpy as np\n'), ((1827, 1854), 'itertools.permutations', 'permutations', (['dice_names', '(2)'], {}), '(dice_names, 2)\n', (1839, 1854), False, 'from itertools import permutations, product\n'), ((2612, 2639), 'itertools.permutations', 'permutations', (['dice_names', '(2)'], {}), '(dice_names, 2)\n', (2624, 2639), False, 'from itertools import permutations, product\n'), ((5139, 5163), 'scipy.special.factorial', 'factorial', (['m'], {'exact': '(True)'}), '(m, exact=True)\n', (5148, 5163), False, 'from scipy.special import factorial\n'), ((5290, 5309), 'numpy.argsort', 'np.argsort', (['outcome'], {}), '(outcome)\n', (5300, 5309), True, 'import numpy as np\n'), ((7755, 7782), 'itertools.permutations', 'permutations', (['dice_names', '(2)'], {}), '(dice_names, 2)\n', (7767, 7782), False, 'from itertools import permutations, product\n'), ((8936, 8963), 'itertools.permutations', 'permutations', (['dice_names', '(2)'], {}), '(dice_names, 2)\n', (8948, 8963), False, 'from itertools import permutations, product\n'), ((9477, 9504), 'itertools.permutations', 'permutations', (['dice_names', 'm'], {}), '(dice_names, m)\n', (9489, 9504), False, 'from itertools import permutations, product\n'), ((5192, 5210), 'itertools.permutations', 'permutations', (['keys'], {}), '(keys)\n', (5204, 5210), False, 'from itertools import permutations, product\n'), ((7900, 7911), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (7908, 7911), True, 'import numpy as np\n'), ((9158, 9185), 'itertools.product', 'product', (['faces[x]', 'faces[y]'], {}), '(faces[x], faces[y])\n', (9165, 9185), False, 'from itertools import permutations, product\n'), ((9534, 9566), 'itertools.product', 'product', (['*[faces[x] for x in xs]'], {}), '(*[faces[x] for x in xs])\n', (9541, 9566), False, 'from itertools import permutations, product\n'), ((2732, 2749), 'numpy.array', 'np.array', (['dice[x]'], {}), '(dice[x])\n', (2740, 2749), True, 'import numpy as np\n'), ((2789, 2806), 'numpy.array', 'np.array', (['dice[y]'], {}), '(dice[y])\n', (2797, 2806), True, 'import numpy as np\n'), ((8028, 8039), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (8036, 8039), True, 'import numpy as np\n')]
#!/usr/bin/env python # # import modules used here -- sys is a very standard one from __future__ import print_function import argparse import csv import logging import zipfile from collections import OrderedDict from glob import glob import os import sys import nibabel as nb import json import pandas as pd import numpy as np # Gather our code in a main() function from shutil import copy def get_metadata_for_nifti(bids_root, path): #TODO support .nii sidecarJSON = path.replace(".nii.gz", ".json") pathComponents = os.path.split(sidecarJSON) filenameComponents = pathComponents[-1].split("_") sessionLevelComponentList = [] subjectLevelComponentList = [] topLevelComponentList = [] ses = None; sub = None; for filenameComponent in filenameComponents: if filenameComponent[:3] != "run": sessionLevelComponentList.append(filenameComponent) if filenameComponent[:3] == "ses": ses = filenameComponent else: subjectLevelComponentList.append(filenameComponent) if filenameComponent[:3] == "sub": sub = filenameComponent else: topLevelComponentList.append(filenameComponent) topLevelJSON = os.path.join(bids_root, "_".join(topLevelComponentList)) potentialJSONs = [topLevelJSON] subjectLevelJSON = os.path.join(bids_root, sub, "_".join(subjectLevelComponentList)) potentialJSONs.append(subjectLevelJSON) if ses: sessionLevelJSON = os.path.join(bids_root, sub, ses, "_".join(sessionLevelComponentList)) potentialJSONs.append(sessionLevelJSON) potentialJSONs.append(sidecarJSON) merged_param_dict = {} for json_file_path in potentialJSONs: if os.path.exists(json_file_path): param_dict = json.load(open(json_file_path, "r")) merged_param_dict.update(param_dict) return merged_param_dict def dict_append(d, key, value): if key in d: d[key].append(value) else: d[key] = [value, ] def run(args): guid_mapping = dict([line.split(" - ") for line in open(args.guid_mapping).read().split("\n") if line != '']) suffix_to_scan_type = {"dwi": "MR diffusion", "bold": "fMRI", #""MR structural(MPRAGE)", "T1w": "MR structural (T1)", "PD": "MR structural (PD)", #"MR structural(FSPGR)", "T2w": "MR structural (T2)", "T2map": "MR structural (T2)", "T2star": "MR: T2star", "FLAIR": "MR: FLAIR", "asl": "ASL", "FLASH": "MR structural (FLASH)", #PET; #microscopy; #MR structural(PD, T2); #MR structural(B0 map); #MR structural(B1 map); #single - shell DTI; #multi - shell DTI; "epi": "Field Map", "phase1": "Field Map", "phase2": "Field Map", "phasediff": "Field Map", "magnitude1": "Field Map", "magnitude2": "Field Map", "fieldmap": "Field Map" #X - Ray } units_dict = {"mm": "Millimeters", "sec": "Seconds", "msec": "Milliseconds"} participants_df = pd.read_csv(os.path.join(args.bids_directory, "participants.tsv"), header=0, sep="\t") participants_df['age'] = participants_df.age.astype(str).str.rstrip('Y').str.lstrip('0') image03_dict = OrderedDict() for file in glob(os.path.join(args.bids_directory, "sub-*", "*", "sub-*.nii.gz")) + \ glob(os.path.join(args.bids_directory, "sub-*", "ses-*", "*", "sub-*_ses-*.nii.gz")): metadata = get_metadata_for_nifti(args.bids_directory, file) bids_subject_id = os.path.split(file)[-1].split("_")[0][4:] dict_append(image03_dict, 'subjectkey', guid_mapping[bids_subject_id]) dict_append(image03_dict, 'src_subject_id', bids_subject_id) sub = file.split("sub-")[-1].split("_")[0] if "ses-" in file: ses = file.split("ses-")[-1].split("_")[0] scans_file = (os.path.join(args.bids_directory, "sub-" + sub, "ses-" + ses, "sub-" + sub + "_ses-" + ses + "_scans.tsv")) else: scans_file = (os.path.join(args.bids_directory, "sub-" + sub, "sub-" + sub + "_scans.tsv")) if os.path.exists(scans_file): scans_df = pd.read_csv(scans_file, header=0, sep="\t") else: print("%s file not found - information about scan date required by NDA could not be found." % scans_file) sys.exit(-1) for (_, row) in scans_df.iterrows(): if file.endswith(row["filename"].replace("/", os.sep)): date = row.acq_time break sdate = date.split("-") ndar_date = sdate[1] + "/" + sdate[2].split("T")[0] + "/" + sdate[0] dict_append(image03_dict, 'interview_date', ndar_date) interview_age = int(round(float(participants_df[participants_df.participant_id == "sub-" + sub].age.values[0]), 0)*12) dict_append(image03_dict, 'interview_age', interview_age) sex = list(participants_df[participants_df.participant_id == "sub-" + sub].sex)[0] dict_append(image03_dict, 'gender', sex) dict_append(image03_dict, 'image_file', file) suffix = file.split("_")[-1].split(".")[0] if suffix == "bold": description = suffix + " " + metadata["TaskName"] dict_append(image03_dict, 'experiment_id', metadata.get("ExperimentID", args.experiment_id)) else: description = suffix dict_append(image03_dict, 'experiment_id', '') dict_append(image03_dict, 'image_description', description) dict_append(image03_dict, 'scan_type', suffix_to_scan_type[suffix]) dict_append(image03_dict, 'scan_object', "Live") dict_append(image03_dict, 'image_file_format', "NIFTI") dict_append(image03_dict, 'image_modality', "MRI") dict_append(image03_dict, 'scanner_manufacturer_pd', metadata.get("Manufacturer", "")) dict_append(image03_dict, 'scanner_type_pd', metadata.get("ManufacturersModelName", "")) dict_append(image03_dict, 'scanner_software_versions_pd', metadata.get("SoftwareVersions", "")) dict_append(image03_dict, 'magnetic_field_strength', metadata.get("MagneticFieldStrength", "")) dict_append(image03_dict, 'mri_echo_time_pd', metadata.get("EchoTime", "")) dict_append(image03_dict, 'flip_angle', metadata.get("FlipAngle", "")) dict_append(image03_dict, 'receive_coil', metadata.get("ReceiveCoilName", "")) plane = metadata.get("ImageOrientationPatient","") get_orientation = lambda place: ['Axial','Coronal','Sagittal'][np.argmax(plane[:3])] dict_append(image03_dict, 'image_orientation',get_orientation(plane)) dict_append(image03_dict, 'transformation_performed', 'Yes') dict_append(image03_dict, 'transformation_type', 'BIDS2NDA') nii = nb.load(file) dict_append(image03_dict, 'image_num_dimensions', len(nii.shape)) dict_append(image03_dict, 'image_extent1', nii.shape[0]) dict_append(image03_dict, 'image_extent2', nii.shape[1]) dict_append(image03_dict, 'image_extent3', nii.shape[2]) if suffix == "bold": extent4_type = "time" elif suffix == "dwi": extent4_type = "diffusion weighting" else: extent4_type = "" dict_append(image03_dict, 'extent4_type', extent4_type) dict_append(image03_dict, 'acquisition_matrix', "%g x %g" %(nii.shape[0], nii.shape[1])) dict_append(image03_dict, 'image_resolution1', nii.header.get_zooms()[0]) dict_append(image03_dict, 'image_resolution2', nii.header.get_zooms()[1]) dict_append(image03_dict, 'image_resolution3', nii.header.get_zooms()[2]) dict_append(image03_dict, 'image_slice_thickness', nii.header.get_zooms()[2]) dict_append(image03_dict, 'photomet_interpret', metadata.get("global",{}).get("const",{}).get("PhotometricInterpretation","MONOCHROME2")) if len(nii.shape) > 3: image_extent4 = nii.shape[3] image_resolution4 = nii.header.get_zooms()[3] image_unit4 = units_dict[nii.header.get_xyzt_units()[1]] if image_unit4 == "Milliseconds": TR = nii.header.get_zooms()[3]/1000. else: TR = nii.header.get_zooms()[3] else: image_resolution4 = "" image_unit4 = "" image_extent4 = "" TR = metadata.get("RepetitionTime", "") slice_timing = metadata.get("SliceTiming", "") dict_append(image03_dict, 'image_extent4', image_extent4) dict_append(image03_dict, 'slice_timing', slice_timing) dict_append(image03_dict, 'image_unit4', image_unit4) dict_append(image03_dict, 'mri_repetition_time_pd', TR) dict_append(image03_dict, 'image_resolution4', image_resolution4) dict_append(image03_dict, 'image_unit1', units_dict[nii.header.get_xyzt_units()[0]]) dict_append(image03_dict, 'image_unit2', units_dict[nii.header.get_xyzt_units()[0]]) dict_append(image03_dict, 'image_unit3', units_dict[nii.header.get_xyzt_units()[0]]) dict_append(image03_dict, 'mri_field_of_view_pd', "%g x %g %s" % (nii.header.get_zooms()[0], nii.header.get_zooms()[1], units_dict[nii.header.get_xyzt_units()[0]])) dict_append(image03_dict, 'patient_position', 'head first-supine') if file.split(os.sep)[-1].split("_")[1].startswith("ses"): visit = file.split(os.sep)[-1].split("_")[1][4:] else: visit = "" dict_append(image03_dict, 'visit', visit) if len(metadata) > 0 or suffix in ['bold', 'dwi']: _, fname = os.path.split(file) zip_name = fname.split(".")[0] + ".metadata.zip" zip_path = os.path.join(args.output_directory, zip_name) zip_path_exists = os.path.exists(zip_path) if not zip_path_exists or (zip_path_exists and args.overwrite_zips): with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: zipf.writestr(fname.replace(".nii.gz", ".json"), json.dumps(metadata, indent=4, sort_keys=True)) if suffix == "bold": #TODO write a more robust function for finding those files events_file = file.split("_bold")[0] + "_events.tsv" arch_name = os.path.split(events_file)[1] if not os.path.exists(events_file): task_name = file.split("_task-")[1].split("_")[0] events_file = os.path.join(args.bids_directory, "task-" + task_name + "_events.tsv") if os.path.exists(events_file): zipf.write(events_file, arch_name) dict_append(image03_dict, 'data_file2', zip_path) dict_append(image03_dict, 'data_file2_type', "ZIP file with additional metadata from Brain Imaging " "Data Structure (http://bids.neuroimaging.io)") else: dict_append(image03_dict, 'data_file2', "") dict_append(image03_dict, 'data_file2_type', "") if suffix == "dwi": # TODO write a more robust function for finding those files bvec_file = file.split("_dwi")[0] + "_dwi.bvec" if not os.path.exists(bvec_file): bvec_file = os.path.join(args.bids_directory, "dwi.bvec") if os.path.exists(bvec_file): dict_append(image03_dict, 'bvecfile', bvec_file) else: dict_append(image03_dict, 'bvecfile', "") bval_file = file.split("_dwi")[0] + "_dwi.bval" if not os.path.exists(bval_file): bval_file = os.path.join(args.bids_directory, "dwi.bval") if os.path.exists(bval_file): dict_append(image03_dict, 'bvalfile', bval_file) else: dict_append(image03_dict, 'bvalfile', "") if os.path.exists(bval_file) or os.path.exists(bvec_file): dict_append(image03_dict, 'bvek_bval_files', 'Yes') else: dict_append(image03_dict, 'bvek_bval_files', 'No') else: dict_append(image03_dict, 'bvecfile', "") dict_append(image03_dict, 'bvalfile', "") dict_append(image03_dict, 'bvek_bval_files', "") # all values of image03_dict should be the same length. # Fail when this is not true instead of when the dataframe # is created. assert(len(set(map(len,image03_dict.values()))) ==1) image03_df = pd.DataFrame(image03_dict) with open(os.path.join(args.output_directory, "image03.txt"), "w") as out_fp: out_fp.write('"image"\t"3"\n') image03_df.to_csv(out_fp, sep="\t", index=False, quoting=csv.QUOTE_ALL) def main(): class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) parser = MyParser( description="BIDS to NDA converter.", fromfile_prefix_chars='@') # TODO Specify your real parameters here. parser.add_argument( "bids_directory", help="Location of the root of your BIDS compatible directory", metavar="BIDS_DIRECTORY") parser.add_argument('-e', '--experiment_id', default=None, help = ("Functional scans require an experiment_id. If ExperimentID is not" " found in the scan metadata this value is used")) parser.add_argument('-o', '--overwrite_zips', action='store_true', help = ("If a conversion has already been performed, the default is " "to avoid rewriting each zip file generated and instead just rewrite image03.txt")) parser.add_argument( "guid_mapping", help="Path to a text file with participant_id to GUID mapping. You will need to use the " "GUID Tool (https://ndar.nih.gov/contribute.html) to generate GUIDs for your participants.", metavar="GUID_MAPPING") parser.add_argument( "output_directory", help="Directory where NDA files will be stored", metavar="OUTPUT_DIRECTORY") args = parser.parse_args() run(args) print("Metadata extraction complete.") if __name__ == '__main__': main()
[ "os.path.exists", "collections.OrderedDict", "pandas.read_csv", "nibabel.load", "zipfile.ZipFile", "json.dumps", "os.path.join", "numpy.argmax", "os.path.split", "sys.stderr.write", "sys.exit", "pandas.DataFrame" ]
[((538, 564), 'os.path.split', 'os.path.split', (['sidecarJSON'], {}), '(sidecarJSON)\n', (551, 564), False, 'import os\n'), ((3938, 3951), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3949, 3951), False, 'from collections import OrderedDict\n'), ((13537, 13563), 'pandas.DataFrame', 'pd.DataFrame', (['image03_dict'], {}), '(image03_dict)\n', (13549, 13563), True, 'import pandas as pd\n'), ((1795, 1825), 'os.path.exists', 'os.path.exists', (['json_file_path'], {}), '(json_file_path)\n', (1809, 1825), False, 'import os\n'), ((3748, 3801), 'os.path.join', 'os.path.join', (['args.bids_directory', '"""participants.tsv"""'], {}), "(args.bids_directory, 'participants.tsv')\n", (3760, 3801), False, 'import os\n'), ((4825, 4851), 'os.path.exists', 'os.path.exists', (['scans_file'], {}), '(scans_file)\n', (4839, 4851), False, 'import os\n'), ((7524, 7537), 'nibabel.load', 'nb.load', (['file'], {}), '(file)\n', (7531, 7537), True, 'import nibabel as nb\n'), ((3973, 4036), 'os.path.join', 'os.path.join', (['args.bids_directory', '"""sub-*"""', '"""*"""', '"""sub-*.nii.gz"""'], {}), "(args.bids_directory, 'sub-*', '*', 'sub-*.nii.gz')\n", (3985, 4036), False, 'import os\n'), ((4059, 4137), 'os.path.join', 'os.path.join', (['args.bids_directory', '"""sub-*"""', '"""ses-*"""', '"""*"""', '"""sub-*_ses-*.nii.gz"""'], {}), "(args.bids_directory, 'sub-*', 'ses-*', '*', 'sub-*_ses-*.nii.gz')\n", (4071, 4137), False, 'import os\n'), ((4587, 4697), 'os.path.join', 'os.path.join', (['args.bids_directory', "('sub-' + sub)", "('ses-' + ses)", "('sub-' + sub + '_ses-' + ses + '_scans.tsv')"], {}), "(args.bids_directory, 'sub-' + sub, 'ses-' + ses, 'sub-' + sub +\n '_ses-' + ses + '_scans.tsv')\n", (4599, 4697), False, 'import os\n'), ((4735, 4811), 'os.path.join', 'os.path.join', (['args.bids_directory', "('sub-' + sub)", "('sub-' + sub + '_scans.tsv')"], {}), "(args.bids_directory, 'sub-' + sub, 'sub-' + sub + '_scans.tsv')\n", (4747, 4811), False, 'import os\n'), ((4876, 4919), 'pandas.read_csv', 'pd.read_csv', (['scans_file'], {'header': '(0)', 'sep': '"""\t"""'}), "(scans_file, header=0, sep='\\t')\n", (4887, 4919), True, 'import pandas as pd\n'), ((5064, 5076), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (5072, 5076), False, 'import sys\n'), ((10523, 10542), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (10536, 10542), False, 'import os\n'), ((10627, 10672), 'os.path.join', 'os.path.join', (['args.output_directory', 'zip_name'], {}), '(args.output_directory, zip_name)\n', (10639, 10672), False, 'import os\n'), ((10703, 10727), 'os.path.exists', 'os.path.exists', (['zip_path'], {}), '(zip_path)\n', (10717, 10727), False, 'import os\n'), ((12364, 12389), 'os.path.exists', 'os.path.exists', (['bvec_file'], {}), '(bvec_file)\n', (12378, 12389), False, 'import os\n'), ((12729, 12754), 'os.path.exists', 'os.path.exists', (['bval_file'], {}), '(bval_file)\n', (12743, 12754), False, 'import os\n'), ((13579, 13629), 'os.path.join', 'os.path.join', (['args.output_directory', '"""image03.txt"""'], {}), "(args.output_directory, 'image03.txt')\n", (13591, 13629), False, 'import os\n'), ((13870, 13911), 'sys.stderr.write', 'sys.stderr.write', (["('error: %s\\n' % message)"], {}), "('error: %s\\n' % message)\n", (13886, 13911), False, 'import sys\n'), ((13954, 13965), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (13962, 13965), False, 'import sys\n'), ((7271, 7291), 'numpy.argmax', 'np.argmax', (['plane[:3]'], {}), '(plane[:3])\n', (7280, 7291), True, 'import numpy as np\n'), ((12247, 12272), 'os.path.exists', 'os.path.exists', (['bvec_file'], {}), '(bvec_file)\n', (12261, 12272), False, 'import os\n'), ((12302, 12347), 'os.path.join', 'os.path.join', (['args.bids_directory', '"""dwi.bvec"""'], {}), "(args.bids_directory, 'dwi.bvec')\n", (12314, 12347), False, 'import os\n'), ((12612, 12637), 'os.path.exists', 'os.path.exists', (['bval_file'], {}), '(bval_file)\n', (12626, 12637), False, 'import os\n'), ((12667, 12712), 'os.path.join', 'os.path.join', (['args.bids_directory', '"""dwi.bval"""'], {}), "(args.bids_directory, 'dwi.bval')\n", (12679, 12712), False, 'import os\n'), ((12912, 12937), 'os.path.exists', 'os.path.exists', (['bval_file'], {}), '(bval_file)\n', (12926, 12937), False, 'import os\n'), ((12941, 12966), 'os.path.exists', 'os.path.exists', (['bvec_file'], {}), '(bvec_file)\n', (12955, 12966), False, 'import os\n'), ((10830, 10882), 'zipfile.ZipFile', 'zipfile.ZipFile', (['zip_path', '"""w"""', 'zipfile.ZIP_DEFLATED'], {}), "(zip_path, 'w', zipfile.ZIP_DEFLATED)\n", (10845, 10882), False, 'import zipfile\n'), ((10962, 11008), 'json.dumps', 'json.dumps', (['metadata'], {'indent': '(4)', 'sort_keys': '(True)'}), '(metadata, indent=4, sort_keys=True)\n', (10972, 11008), False, 'import json\n'), ((11556, 11583), 'os.path.exists', 'os.path.exists', (['events_file'], {}), '(events_file)\n', (11570, 11583), False, 'import os\n'), ((4237, 4256), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (4250, 4256), False, 'import os\n'), ((11247, 11273), 'os.path.split', 'os.path.split', (['events_file'], {}), '(events_file)\n', (11260, 11273), False, 'import os\n'), ((11308, 11335), 'os.path.exists', 'os.path.exists', (['events_file'], {}), '(events_file)\n', (11322, 11335), False, 'import os\n'), ((11457, 11527), 'os.path.join', 'os.path.join', (['args.bids_directory', "('task-' + task_name + '_events.tsv')"], {}), "(args.bids_directory, 'task-' + task_name + '_events.tsv')\n", (11469, 11527), False, 'import os\n')]